| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import EquipoKit |
| 4 | |
| 5 | @MainActor @Suite struct StoppedWorkTests { |
| 6 | private func stopped(reason: String = "push_failed", terminated: Bool = true) throws -> ThinTask { |
| 7 | var task: ThinTask = try Fixture.decode("thin/task") |
| 8 | task.stage = "in_progress"; task.needsYou = "retry" |
| 9 | task.steps = [try EquipoJSON.decoder.decode(ThinStep.self, from: Data(""" |
| 10 | {"id":"stopped","specialist":"engineering","state":"failed","reason":"\(reason)","terminated":\(terminated),"summary":"","headline":"Push the branch","verdict":"","review_label":"","checks":"","gate":"","finished_at":"2026-11-25T10:42:00Z"} |
| 11 | """.utf8))] |
| 12 | return task |
| 13 | } |
| 14 | |
| 15 | @Test func stoppedLeadUsesTheWebWordsAndLocalTime() throws { |
| 16 | let task = try stopped() |
| 17 | let now = ISO8601DateFormatter().date(from: "2026-11-25T12:00:00Z")! |
| 18 | let pause = try #require(TaskPause(task, mine: true, now: now, zone: TimeZone(identifier: "Europe/Madrid")!, locale: Locale(identifier: "en_GB"))) |
| 19 | #expect(pause.strong == "Stopped at 11:42:") |
| 20 | #expect(pause.rest == " the push to Amadan failed") |
| 21 | } |
| 22 | |
| 23 | @Test func clockPads24HourMidnightAndRespects12HourLocale() { |
| 24 | let at = ISO8601DateFormatter().date(from: "2026-11-26T00:20:00Z")! |
| 25 | for language in ["en_IE", "en_GB"] { |
| 26 | let words = TimeWords(now: at, zone: .gmt, locale: Locale(identifier: language)) |
| 27 | #expect(words.clockOrDay(at) == "00:20") |
| 28 | #expect(words.when(at) == "today at 00:20") |
| 29 | } |
| 30 | let words = TimeWords(now: at, zone: .gmt, locale: Locale(identifier: "en_US")) |
| 31 | #expect(words.clockOrDay(at).replacingOccurrences(of: "\u{202F}", with: " ") == "12:20 AM") |
| 32 | } |
| 33 | |
| 34 | @Test func retryIsOnlyForCreatorAndTerminatedStep() throws { |
| 35 | #expect(TaskPause(try stopped(), mine: true)?.canRetry == true) |
| 36 | #expect(TaskPause(try stopped(), mine: false)?.canRetry == false) |
| 37 | #expect(TaskPause(try stopped(terminated: false), mine: true)?.canRetry == false) |
| 38 | } |
| 39 | |
| 40 | @Test func everyReasonUsesReviewedWords() throws { |
| 41 | let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("internal/equipo/copy.go") |
| 42 | let source = try String(contentsOf: url, encoding: .utf8) |
| 43 | let regex = try NSRegularExpression(pattern: #""work\.reason\.([^"]+)":\s*("(?:[^"\\]|\\.)*")"#) |
| 44 | let ns = source as NSString |
| 45 | let matches = regex.matches(in: source, range: NSRange(location: 0, length: ns.length)) |
| 46 | #expect(matches.count >= 70) |
| 47 | for match in matches { |
| 48 | let reason = ns.substring(with: match.range(at: 1)) |
| 49 | let words = try JSONDecoder().decode(String.self, from: Data(ns.substring(with: match.range(at: 2)).utf8)) |
| 50 | #expect(StoppedReason.words(reason) == words, "\(reason)") |
| 51 | } |
| 52 | #expect(StoppedReason.words("future_reason") == "something went wrong") |
| 53 | } |
| 54 | |
| 55 | @Test func needsReasonsHaveALead() throws { |
| 56 | var task = try stopped() |
| 57 | for reason in ["fix_rounds", "branch_moved", "review_blocked", "merge_conflict", "direction", "machine_removed"] { |
| 58 | task.needsYou = reason |
| 59 | let pause = try #require(TaskPause(task, mine: true)) |
| 60 | #expect(pause.tone == .warning) |
| 61 | #expect(!(pause.strong + pause.rest).isEmpty) |
| 62 | #expect(pause.canRetry == true) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | @Test func retryConflictUsesReviewedMessage() async throws { |
| 67 | let transport = ScriptedTransport() |
| 68 | transport.on("POST /tasks/tk1/retry", .success(APIResponse(status: 409, data: Data(#"{"code":"not_retryable","copy_key":"api.not_retryable","request_id":"r"}"#.utf8)))) |
| 69 | let result = await StoppedWorkActions.retry(client: EquipoClient(transport: transport, token: "fixture"), task: "tk1") |
| 70 | #expect(result == "This work cannot be retried now. Check its latest status.") |
| 71 | } |
| 72 | @Test func retrySuccessAndLogReadUseDeviceAPI() async throws { |
| 73 | let transport = ScriptedTransport() |
| 74 | transport.on("POST /tasks/tk1/retry", .success(APIResponse(status: 202, data: Data(#"{"attempt":2}"#.utf8)))) |
| 75 | transport.on("GET /steps/s1/log", .success(APIResponse(status: 200, data: Data(#"{"step_id":"s1","attempt":1,"tail":"remote: [redacted]\nexit status 128"}"#.utf8)))) |
| 76 | let client = EquipoClient(transport: transport, token: "fixture") |
| 77 | #expect(await StoppedWorkActions.retry(client: client, task: "tk1") == nil) |
| 78 | #expect(try await client.stepLog("s1").boundedTail == "remote: [redacted]\nexit status 128") |
| 79 | #expect(transport.requests.allSatisfy { $0.bearer == "fixture" }) |
| 80 | } |
| 81 | |
| 82 | @Test func logIsBoundedByLinesAndBytes() { |
| 83 | let lines = (0..<300).map { "line \($0)" }.joined(separator: "\n") |
| 84 | #expect(StepLog(stepId: "s", attempt: 1, tail: lines).boundedTail.split(separator: "\n").count == 200) |
| 85 | #expect(StepLog(stepId: "s", attempt: 1, tail: String(repeating: "x", count: 40000)).boundedTail.utf8.count <= 32768) |
| 86 | let unicode = StepLog(stepId: "s", attempt: 1, tail: String(repeating: "€", count: 20000)).boundedTail |
| 87 | #expect(unicode.utf8.count <= 32768 && !unicode.contains("�")) |
| 88 | } |
| 89 | |
| 90 | @Test func resumeUsesMatchingRunnerAndPauseRevision() async throws { |
| 91 | var task = try stopped() |
| 92 | task.steps![0].runnerId = "runner1" |
| 93 | task.steps![0].hold = ThinHold(reason: "spend_unknown", connection: "local", provider: "tensorx", stepRevision: 4) |
| 94 | let right = ResumeConnection(id: "cn_right", runnerId: "runner1", localId: "local", provider: "tensorx", spend: .init(unknown: true, pauseRevision: 7)) |
| 95 | let wrong = ResumeConnection(id: "cn_wrong", runnerId: "runner2", localId: "local", provider: "tensorx", spend: .init(unknown: true, pauseRevision: 8)) |
| 96 | let connection = try #require(StoppedWorkActions.connection(for: task.steps![0], in: [wrong, right])) |
| 97 | #expect(connection.id == "cn_right") |
| 98 | let transport = ScriptedTransport() |
| 99 | transport.on("POST /connections/cn_right/resume", .success(APIResponse(status: 202, data: Data()))) |
| 100 | try await EquipoClient(transport: transport, token: "fixture").resumeConnection(connection) |
| 101 | let body = try #require(transport.requests.first?.body) |
| 102 | #expect(try JSONDecoder().decode([String: Int].self, from: body) == ["pause_revision": 7]) |
| 103 | } |
| 104 | |
| 105 | @Test func triageWithoutReasonDecodesAndSuppressesRetry() throws { |
| 106 | let triage = try EquipoJSON.decoder.decode(ThinTriage.self, from: Data(#"{"kind":"rebasing"}"#.utf8)) |
| 107 | var task = try stopped() |
| 108 | task.triage = triage |
| 109 | #expect(TaskPause(task, mine: true) == nil) |
| 110 | } |
| 111 | |
| 112 | @Test func directionWithoutAStepStillLeads() throws { |
| 113 | var task = try stopped() |
| 114 | task.needsYou = "direction"; task.steps = [] |
| 115 | #expect(TaskPause(task, mine: true)?.rest == "Equipo is waiting for your choice.") |
| 116 | } |
| 117 | |
| 118 | } |
| 119 | |
| 120 | @MainActor @Suite struct StoppedWorkReviewTests { |
| 121 | func task(_ reason: String = "push_failed", needs: String = "retry", terminated: Bool = true) throws -> ThinTask { |
| 122 | var task: ThinTask = try Fixture.decode("thin/task") |
| 123 | task.stage = "in_progress"; task.needsYou = needs; task.triage = nil |
| 124 | var step = task.steps!.first! |
| 125 | step.state = "failed"; step.reason = reason; step.terminated = terminated |
| 126 | step.runnerLabel = "Mac mini"; step.runnerId = "runner"; step.hold = nil; step.paused = nil |
| 127 | task.steps = [step] |
| 128 | return task |
| 129 | } |
| 130 | @Test func needsRetryHasBothGuardsForEveryReason() throws { |
| 131 | for needs in ["review_blocked", "fix_rounds", "branch_moved", "merge_conflict", "direction"] { |
| 132 | #expect(TaskPause(try task(needs: needs), mine: true)?.canRetry == true) |
| 133 | #expect(TaskPause(try task(needs: needs), mine: false)?.canRetry == false) |
| 134 | #expect(TaskPause(try task(needs: needs, terminated: false), mine: true)?.canRetry == false) |
| 135 | } |
| 136 | } |
| 137 | @Test func settingsAndResumeBelongToCreator() throws { |
| 138 | let outdated = try task("runner_outdated") |
| 139 | #expect(TaskPause(outdated, mine: true)?.settingsPath == "/conversation/settings/machines") |
| 140 | #expect(TaskPause(outdated, mine: false)?.settingsPath == nil) |
| 141 | for reason in ["budget", "spend_unknown"] { |
| 142 | for needs in [nil, "budget"] as [String?] { |
| 143 | var t = try task(); t.steps![0].state = "queued" |
| 144 | t.steps![0].hold = ThinHold(reason: reason, provider: "codex", needsPerson: needs, stepRevision: 2) |
| 145 | let mine = TaskPause(t, mine: true), other = TaskPause(t, mine: false) |
| 146 | if reason == "budget" { #expect(mine?.settingsPath != nil) } else { #expect(mine?.resumeStep != nil) } |
| 147 | #expect(other?.settingsPath == nil && other?.resumeStep == nil) |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | @Test func noFurtherChangesDependsOnPriorPushedWork() throws { |
| 152 | var t = try task("no_changes") |
| 153 | var earlier = t.steps![0]; earlier.id = "earlier"; earlier.state = "done"; earlier.specialist = "engineering"; earlier.pushed = true; earlier.candidateSha = "abc" |
| 154 | t.steps!.insert(earlier, at: 0) |
| 155 | #expect(TaskPause(t, mine: true)?.rest.contains(StoppedReason.words("no_further_changes")) == true) |
| 156 | t.steps![0].pushed = false |
| 157 | #expect(TaskPause(t, mine: true)?.rest.contains(StoppedReason.words("no_changes")) == true) |
| 158 | } |
| 159 | @Test func recoveryUsesTheWebGuards() throws { |
| 160 | let waiting = try task("machine_removed", needs: "machine_removed", terminated: false) |
| 161 | #expect(TaskPause(waiting, mine: true)?.canRecover == true) |
| 162 | #expect(TaskPause(waiting, mine: true)?.canRetry == false) |
| 163 | #expect(TaskPause(waiting, mine: false)?.canRecover == false) |
| 164 | #expect(TaskPause(try task("machine_removed", terminated: false), mine: true)?.tone != .negative) |
| 165 | #expect(TaskPause(try task("machine_removed"), mine: true)?.canRecover == false) |
| 166 | #expect(TaskPause(try task(), mine: true)?.canRecover == false) |
| 167 | } |
| 168 | @Test func transitionalWorkSuppressesActions() throws { |
| 169 | for key in ["moving", "stopping", "copyHold", "copyCanSkip"] { |
| 170 | var t = try task() |
| 171 | switch key { case "moving": t.moving = true; case "stopping": t.stopping = true; case "copyHold": t.copyHold = true; default: t.copyCanSkip = true } |
| 172 | #expect(TaskPause(t, mine: true) == nil, "\(key)") |
| 173 | } |
| 174 | for kind in ["retrying", "rebasing", "rechecking", "waiting"] { |
| 175 | var t = try task(); t.triage = ThinTriage(kind: kind, reason: kind == "waiting" ? "merge_unborn_default" : nil) |
| 176 | #expect(TaskPause(t, mine: true) == nil, "\(kind)") |
| 177 | } |
| 178 | } |
| 179 | @Test func resumeMatchesEveryIdentityAndUnknownSpend() throws { |
| 180 | var step = try task().steps![0] |
| 181 | step.hold = ThinHold(reason: "spend_unknown", connection: "local", provider: "codex", stepRevision: 2) |
| 182 | for wrong in [ |
| 183 | ResumeConnection(id: "wrong", runnerId: "runner", localId: "local", provider: "codex", spend: .init(unknown: false, pauseRevision: 1)), |
| 184 | ResumeConnection(id: "wrong", runnerId: "runner", localId: "other", provider: "codex", spend: .init(unknown: true, pauseRevision: 1)), |
| 185 | ResumeConnection(id: "wrong", runnerId: "runner", localId: "local", provider: "claude", spend: .init(unknown: true, pauseRevision: 1)) |
| 186 | ] { #expect(StoppedWorkActions.connection(for: step, in: [wrong]) == nil) } |
| 187 | } |
| 188 | @Test func deadlineAndHeldBoldSplitMatchWeb() throws { |
| 189 | let now = Date(timeIntervalSince1970: 1795608000) |
| 190 | var t = try task(); t.steps![0].state = "queued" |
| 191 | t.priority = ThinPriority(by: now.addingTimeInterval(3600)) |
| 192 | t.steps![0].hold = ThinHold(reason: "headroom", provider: "codex", resetsAt: now.addingTimeInterval(7200), needsPerson: "deadline", stepRevision: 2) |
| 193 | let words = TimeWords(now: now, zone: .gmt, locale: Locale(identifier: "en_GB")) |
| 194 | let lead = HeldLead.words(t.steps![0].hold!, name: "Codex", due: t.priority?.by, words: words) |
| 195 | #expect(lead == String(format: EquipoStrings.text("chat.held.run.after_by"), "Codex", String(format: EquipoStrings.text("time.when_in"), words.when(now.addingTimeInterval(7200)), words.inWords(7200)), "Wednesday 25 Nov")) |
| 196 | let pause = try #require(TaskPause(t, mine: true, now: now, zone: .gmt, locale: Locale(identifier: "en_GB"))) |
| 197 | #expect(pause.strong + pause.rest == lead) |
| 198 | if let colon = lead.firstIndex(of: ":") { #expect(pause.strong == String(lead[...colon])) } |
| 199 | } |
| 200 | @Test func failuresAndRecoverUseReviewedWords() async throws { |
| 201 | let transport = ScriptedTransport() |
| 202 | transport.on("POST /tasks/t/retry", .failure(EquipoAPIError.offline)) |
| 203 | let client = EquipoClient(transport: transport, token: "fixture") |
| 204 | #expect(await StoppedWorkActions.retry(client: client, task: "t") == EquipoStrings.text("card.failed")) |
| 205 | transport.on("POST /tasks/t/recover", .success(APIResponse(status: 202, data: Data(#"{"attempt":2}"#.utf8)))) |
| 206 | #expect(await StoppedWorkActions.recover(client: client, task: "t") == nil) |
| 207 | #expect(transport.requests.last?.path == "/tasks/t/recover") |
| 208 | #expect(StoppedWorkActions.logFailure(EquipoAPIError.offline) == EquipoStrings.text("card.offline")) |
| 209 | #expect(StoppedWorkActions.logFailure(EquipoAPIError.undecodable) == EquipoStrings.text("read.failed")) |
| 210 | #expect(StoppedWorkActions.logFailure(EquipoAPIError.status(500)) == EquipoStrings.text("read.failed_title")) |
| 211 | } |
| 212 | @Test func macSettingsUsesFixedPathAndOpener() { |
| 213 | var opened: URL? |
| 214 | let origin = URL(string: "https://team.example")! |
| 215 | SettingsNavigation.open(origin: origin, path: "/conversation/settings/connections") { opened = $0 } |
| 216 | #expect(opened?.absoluteString == "https://team.example/conversation/settings/connections") |
| 217 | opened = nil |
| 218 | SettingsNavigation.open(origin: origin, path: "https://evil.example") { opened = $0 } |
| 219 | #expect(opened == nil) |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | extension StoppedWorkReviewTests { |
| 224 | @Test func staleResumeReloadsRevisionBeforeAnotherTap() async throws { |
| 225 | var step = try task().steps![0] |
| 226 | step.hold = ThinHold(reason: "spend_unknown", connection: "local", provider: "codex", stepRevision: 2) |
| 227 | let transport = ScriptedTransport() |
| 228 | func connection(_ revision: Int) -> APIResponse { |
| 229 | APIResponse(status: 200, data: Data(""" |
| 230 | {"items":[{"id":"cn","runner_id":"runner","local_id":"local","provider":"codex","spend":{"unknown":true,"pause_revision":\(revision)}}]} |
| 231 | """.utf8)) |
| 232 | } |
| 233 | transport.on("GET /connections", .success(connection(7)), .success(connection(8))) |
| 234 | transport.on("POST /connections/cn/resume", .success(APIResponse(status: 409, data: Data())), .success(APIResponse(status: 202, data: Data()))) |
| 235 | let client = EquipoClient(transport: transport, token: "fixture") |
| 236 | let resume = ResumeAction() |
| 237 | await resume.load(client: client, step: step) |
| 238 | #expect(await resume.perform(client: client, step: step) == EquipoStrings.text("card.failed")) |
| 239 | #expect(resume.connection?.spend?.pauseRevision == 8) |
| 240 | #expect(await resume.perform(client: client, step: step) == nil) |
| 241 | let sent = transport.sent("POST /connections/cn/resume") |
| 242 | #expect(try JSONDecoder().decode([String: Int].self, from: sent.last!.body!) == ["pause_revision": 8]) |
| 243 | } |
| 244 | @Test func runNowFailureNeverLooksSuccessful() async { |
| 245 | let transport = ScriptedTransport() |
| 246 | transport.on("POST /tasks/t/run-now", .failure(EquipoAPIError.offline), .success(APIResponse(status: 409, data: Data()))) |
| 247 | let client = EquipoClient(transport: transport, token: "fixture") |
| 248 | let run = TaskPause.RunNow(label: "Codex", step: "s", revision: 2) |
| 249 | #expect(await StoppedWorkActions.runNow(client: client, task: "t", run: run) == EquipoStrings.text("card.failed")) |
| 250 | #expect(await StoppedWorkActions.runNow(client: client, task: "t", run: run) == EquipoStrings.text("card.failed")) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | extension StoppedWorkReviewTests { |
| 255 | @Test func runNowConflictsUseTheirReviewedWords() async throws { |
| 256 | for (code, expected) in [ |
| 257 | ("offer_changed", "The option to run this work has changed. Check the current option, then try again."), |
| 258 | ("already_running", "A request to run this work is already in progress."), |
| 259 | ("hold_bar", EquipoStrings.text("api.hold_bar")), |
| 260 | ("not_retryable", EquipoStrings.text("card.failed")), |
| 261 | ("unknown", EquipoStrings.text("card.failed")) |
| 262 | ] { |
| 263 | let transport = ScriptedTransport() |
| 264 | let body = try JSONSerialization.data(withJSONObject: ["code": code, "copy_key": "api." + code, "request_id": "r"]) |
| 265 | transport.on("POST /tasks/t/run-now", .success(APIResponse(status: 409, data: body))) |
| 266 | let result = await StoppedWorkActions.runNow(client: EquipoClient(transport: transport, token: "fixture"), task: "t", run: .init(label: "Codex", step: "s", revision: 2)) |
| 267 | #expect(result == expected, "\(code)") |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | @Test func recoverRequiresCreatorReasonAndUnterminatedStepOnBothPaths() throws { |
| 272 | for needs in ["retry", "machine_removed"] { |
| 273 | for mine in [false, true] { |
| 274 | for reason in ["machine_removed", "push_failed"] { |
| 275 | for terminated in [false, true] { |
| 276 | let pause = try #require(TaskPause(try task(reason, needs: needs, terminated: terminated), mine: mine)) |
| 277 | #expect(pause.canRecover == (mine && reason == "machine_removed" && !terminated)) |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | @Test func connectAndMachineSettingsRequireCreator() throws { |
| 285 | for offline in [false, true] { |
| 286 | var t = try task() |
| 287 | t.steps![0].state = "queued" |
| 288 | if offline { |
| 289 | t.steps![0].paused = try EquipoJSON.decoder.decode(ThinPaused.self, from: Data(#"{"offline":true}"#.utf8)) |
| 290 | } else { |
| 291 | t.steps![0].hold = ThinHold(reason: "no_connection", stepRevision: 2) |
| 292 | } |
| 293 | #expect(TaskPause(t, mine: true)?.settingsPath == (offline ? "/conversation/settings/machines" : "/conversation/settings/connections/add")) |
| 294 | #expect(TaskPause(t, mine: false)?.settingsPath == nil) |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | @Test func failedRecoverNeverLooksSuccessful() async { |
| 299 | let transport = ScriptedTransport() |
| 300 | transport.on("POST /tasks/t/recover", .failure(EquipoAPIError.offline), .success(APIResponse(status: 409, data: Data())), .success(APIResponse(status: 500, data: Data()))) |
| 301 | let client = EquipoClient(transport: transport, token: "fixture") |
| 302 | for _ in 0..<3 { |
| 303 | #expect(await StoppedWorkActions.recover(client: client, task: "t") == EquipoStrings.text("card.failed")) |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | @Test func settingsRejectsUnlistedOwnOriginPath() { |
| 308 | var opened: URL? |
| 309 | SettingsNavigation.open(origin: URL(string: "https://team.example")!, path: "/evil") { opened = $0 } |
| 310 | #expect(opened == nil) |
| 311 | } |
| 312 | } |
| 313 | |