| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import EquipoKit |
| 4 | |
| 5 | @MainActor @Suite struct TaskDetailModelTests { |
| 6 | static func model(_ transport: any EquipoTransport) throws -> TaskDetailModel { |
| 7 | var account = DeviceAccount.new(origin: transport.origin, label: "fixture") |
| 8 | account.credential = DeviceCredential(id: "fixture", token: "fixture", audience: "equipo.person.v1", instanceId: "fixture", expiresAt: .distantFuture) |
| 9 | let session = EquipoSession(account: account, accounts: DeviceAccounts(store: MemorySecretStore()), transport: transport) |
| 10 | session.apply(try Fixture.decode("thin/snapshot")) |
| 11 | return TaskDetailModel(session: session, taskID: "tkqsrho7oq3n") |
| 12 | } |
| 13 | @Test func mergeUndoAndCancelRequireAConfirmedModelIntent() async throws { |
| 14 | for action in [TaskAction.merge, .undoMerge, .cancel] { |
| 15 | let server = TaskDetailServer(), model = try Self.model(server) |
| 16 | await model.load(); model.loaded?.mergeOffered = true |
| 17 | model.loaded?.undoOffered = true |
| 18 | model.loaded?.merged = ThinMerged(sha: "hub-sha", withoutChecks: true, at: Date()) |
| 19 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 20 | var receipt = try TaskDecisionTests.card(try #require(model.task), kind: "merge_receipt", options: ["undo"]) |
| 21 | receipt.revision = 72; snapshot.cards = [receipt]; model.session.apply(snapshot) |
| 22 | await model.perform(action) |
| 23 | #expect(await server.writes == 0) |
| 24 | #expect(model.confirmation?.action == action) |
| 25 | await model.confirm() |
| 26 | #expect(await server.writes == 1) |
| 27 | #expect(model.confirmation == nil) |
| 28 | if action == .undoMerge { |
| 29 | let request = try #require(await server.requests.last { $0.path.hasSuffix("/undo-merge") }) |
| 30 | let body = try JSONSerialization.jsonObject(with: try #require(request.body)) as! [String: Int] |
| 31 | #expect(body["revision"] == 72) |
| 32 | } |
| 33 | await model.confirm(); #expect(await server.writes == 1) |
| 34 | } |
| 35 | } |
| 36 | @Test func busyPerformRejectsAnImmediateSecondIntent() async throws { |
| 37 | let server = TaskDetailServer(), model = try Self.model(server) |
| 38 | await model.load(); model.busy = true |
| 39 | await model.perform(.urgent) |
| 40 | #expect(await server.writes == 0) |
| 41 | #expect(model.busy) |
| 42 | } |
| 43 | @Test func busyConfirmationKeepsItsIntentAndSendsNothing() async throws { |
| 44 | let server = TaskDetailServer(), model = try Self.model(server) |
| 45 | await model.load(); model.loaded?.mergeOffered = true |
| 46 | await model.perform(.merge) |
| 47 | let intent = try #require(model.confirmation) |
| 48 | model.busy = true |
| 49 | await model.confirm() |
| 50 | #expect(model.confirmation?.id == intent.id) |
| 51 | #expect(await server.writes == 0) |
| 52 | #expect(model.busy) |
| 53 | } |
| 54 | @Test func busyAnswerCannotSendOrReplaceFeedback() async throws { |
| 55 | let server = TaskDetailServer(), model = try Self.model(server) |
| 56 | await model.load() |
| 57 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 58 | let card = try TaskDecisionTests.card(try #require(model.task)) |
| 59 | snapshot.cards = [card]; model.session.apply(snapshot) |
| 60 | model.busy = true; model.failure = "prior feedback" |
| 61 | await model.answer(card, choice: "wait", note: "") |
| 62 | #expect(await server.writes == 0) |
| 63 | #expect(model.failure == "prior feedback") |
| 64 | #expect(model.busy) |
| 65 | } |
| 66 | @Test func modelSendsCurrentRevisionAndPreservesUrgentDeadline() async throws { |
| 67 | let server = TaskDetailServer(), model = try Self.model(server) |
| 68 | await model.load() |
| 69 | await model.perform(.explore) |
| 70 | let kind = try #require(await server.requests.last { $0.path.hasSuffix("/kind") }) |
| 71 | let kindBody = try JSONSerialization.jsonObject(with: try #require(kind.body)) as! NSDictionary |
| 72 | #expect(kindBody == ["kind": "explore", "revision": 9] as NSDictionary) |
| 73 | let deadline = Date(timeIntervalSince1970: 1_800_000_000) |
| 74 | model.loaded?.priority = ThinPriority(priority: "normal", by: deadline) |
| 75 | await model.perform(.urgent) |
| 76 | let urgent = try #require(await server.requests.last { $0.path.hasSuffix("/priority") }) |
| 77 | let urgentBody = try JSONSerialization.jsonObject(with: try #require(urgent.body)) as! NSDictionary |
| 78 | #expect(urgentBody == ["priority": "urgent", "revision": 9, "by": "2027-01-15T08:00:00Z"] as NSDictionary) |
| 79 | } |
| 80 | |
| 81 | @Test func directionNoteClearsAfterSuccessAndNeverGoesWithMerge() async throws { |
| 82 | let server = TaskDetailServer(), model = try Self.model(server) |
| 83 | await model.load() |
| 84 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 85 | let direction = try TaskDecisionTests.card(try #require(model.task), kind: "direction", options: ["build", "again", "drop"]) |
| 86 | snapshot.cards = [direction]; model.session.apply(snapshot) |
| 87 | await server.answerSuccessfully(direction) |
| 88 | model.directionNote = "Use the smaller control" |
| 89 | await model.answer(direction, choice: "again", note: model.directionNote) |
| 90 | #expect(model.failure == nil) |
| 91 | #expect(model.directionNote.isEmpty) |
| 92 | let sent = try #require(await server.requests.last { $0.path.contains("/answer") }) |
| 93 | let body = try JSONSerialization.jsonObject(with: try #require(sent.body)) as! [String: Any] |
| 94 | #expect(body["note"] as? String == "Use the smaller control") |
| 95 | let merge = try TaskDecisionTests.card(try #require(model.task)) |
| 96 | snapshot.cards = [merge]; model.session.apply(snapshot) |
| 97 | await model.answer(merge, choice: "wait", note: "A stale direction note") |
| 98 | let next = try #require(await server.requests.last { $0.path.contains("/answer") }) |
| 99 | let nextBody = try JSONSerialization.jsonObject(with: try #require(next.body)) as! [String: Any] |
| 100 | #expect(nextBody["note"] == nil) |
| 101 | } |
| 102 | @Test func cancelIsLastAndHiddenWhileMerging() async throws { |
| 103 | let model = try Self.model(TaskDetailServer()); await model.load() |
| 104 | #expect(model.menuActions.last == .cancel) |
| 105 | model.loaded?.stage = "merging" |
| 106 | #expect(!model.menuActions.contains(.cancel)) |
| 107 | await model.perform(.cancel) |
| 108 | #expect(model.confirmation == nil) |
| 109 | } |
| 110 | |
| 111 | @Test func taskActionsRefreshTheFullTaskAndRejectOtherCreators() async throws { |
| 112 | let server = TaskDetailServer(), model = try Self.model(server) |
| 113 | await model.load() |
| 114 | await model.perform(.cancel); await model.confirm() |
| 115 | #expect(await server.writes == 1) |
| 116 | #expect(await server.reads >= 2) |
| 117 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot"); snapshot.me.address = "another@example.com" |
| 118 | model.session.apply(snapshot) |
| 119 | await model.perform(.cancel); await model.confirm() |
| 120 | #expect(await server.writes == 1) |
| 121 | } |
| 122 | @Test func doubleTapCannotSendTwice() async throws { |
| 123 | let server = TaskDetailServer(), model = try Self.model(server) |
| 124 | await model.load(); await server.configure(held: true) |
| 125 | let first = Task { await model.perform(.urgent) } |
| 126 | for _ in 0..<100 { if await server.writes > 0 { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 127 | #expect(model.busy) |
| 128 | let second = Task { await model.perform(.urgent) } |
| 129 | try await Task.sleep(for: .milliseconds(20)) |
| 130 | #expect(await server.writes == 1) |
| 131 | await server.finish(); await first.value; await second.value |
| 132 | #expect(!model.busy) |
| 133 | } |
| 134 | @Test func conflictsRemainVisibleAndRefetchTheTaskRevision() async throws { |
| 135 | let server = TaskDetailServer(), model = try Self.model(server) |
| 136 | await model.load(); await server.configure(conflict: true) |
| 137 | await model.perform(.cancel); await model.confirm() |
| 138 | #expect(model.failure == EquipoStrings.text("api.revision_conflict")) |
| 139 | #expect(model.loaded?.revision == 10) |
| 140 | #expect(!model.busy) |
| 141 | } |
| 142 | @Test func confirmationCannotApplyAfterTheViewedTaskChanges() async throws { |
| 143 | let server = TaskDetailServer(), model = try Self.model(server) |
| 144 | await model.load() |
| 145 | await model.perform(.cancel, seenRevision: 8); await model.confirm() |
| 146 | #expect(await server.writes == 0) |
| 147 | #expect(model.failure == EquipoStrings.text("card.changed")) |
| 148 | } |
| 149 | @Test func mergeCardConfirmationBindsTheTaskRevisionToo() async throws { |
| 150 | let server = TaskDetailServer(), model = try Self.model(server); await model.load() |
| 151 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 152 | let card = try TaskDecisionTests.card(try #require(model.task)); snapshot.cards = [card] |
| 153 | model.session.apply(snapshot) |
| 154 | await model.answer(card, choice: "merge", note: "") |
| 155 | model.loaded?.revision += 1 |
| 156 | await model.confirm() |
| 157 | #expect(await server.writes == 0) |
| 158 | #expect(model.failure == EquipoStrings.text("card.changed")) |
| 159 | } |
| 160 | |
| 161 | @Test func cardAnswerBindsTheCurrentCardRevisionAndOptions() async throws { |
| 162 | let server = TaskDetailServer(), model = try Self.model(server) |
| 163 | await model.load() |
| 164 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 165 | let task = try #require(model.task) |
| 166 | let card = try TaskDecisionTests.card(task) |
| 167 | snapshot.cards = [card]; model.session.apply(snapshot) |
| 168 | model.busy = true |
| 169 | await model.answer(card, choice: "merge", note: "") |
| 170 | #expect(await server.writes == 0) |
| 171 | model.busy = false |
| 172 | var unrelated = card; unrelated.id = "another-card" |
| 173 | await model.answer(unrelated, choice: "merge", note: "") |
| 174 | #expect(await server.writes == 0) |
| 175 | await model.answer(card, choice: "unknown", note: "") |
| 176 | #expect(await server.writes == 0) |
| 177 | var stale = card; stale.revision -= 1 |
| 178 | await model.answer(stale, choice: "merge", note: "") |
| 179 | #expect(await server.writes == 0) |
| 180 | #expect(model.failure == EquipoStrings.text("card.changed")) |
| 181 | await model.answer(card, choice: "merge", note: "") |
| 182 | #expect(await server.writes == 0) |
| 183 | await model.confirm() |
| 184 | #expect(await server.writes == 1) |
| 185 | // This server returns malformed JSON: it must never look successful. |
| 186 | #expect(model.failure == EquipoStrings.text("card.failed")) |
| 187 | } |
| 188 | |
| 189 | @Test func unreadOrStaleTaskCannotOfferWrites() async throws { |
| 190 | let model = try Self.model(TaskDetailServer()) |
| 191 | #expect(model.rules.available.isEmpty) |
| 192 | #expect(model.decision.card == nil) |
| 193 | await model.load() |
| 194 | #expect(model.rules.available.contains(.cancel)) |
| 195 | model.readFailure = "fixture" |
| 196 | #expect(model.rules.available.isEmpty) |
| 197 | #expect(model.decision.card == nil) |
| 198 | model.readFailure = nil |
| 199 | await model.session.refresh() |
| 200 | model.loaded?.revision = 0 |
| 201 | #expect(model.rules.available.isEmpty) |
| 202 | #expect(model.decision.card == nil) |
| 203 | } |
| 204 | @Test func ownMoveUsesAllowedProjectsAndRejectsUnknownDestinations() async throws { |
| 205 | let server = TaskDetailServer(), model = try Self.model(server) |
| 206 | await model.load(); model.loaded?.repo = "oficina/equipo" |
| 207 | await model.beginMove() |
| 208 | #expect(model.moving) |
| 209 | #expect(model.destinations == ["oficina/calendar", "oficina/notes"]) |
| 210 | await model.perform(.move, repo: "evil/repo") |
| 211 | #expect(await server.writes == 0) |
| 212 | model.destinations.append("oficina/equipo") |
| 213 | await model.perform(.move, repo: "oficina/equipo") |
| 214 | #expect(await server.writes == 0) |
| 215 | await model.perform(.move, repo: "oficina/notes") |
| 216 | #expect(await server.writes == 1) |
| 217 | #expect(!model.moving) |
| 218 | model.loaded?.creator = "another@example.com" |
| 219 | await model.perform(.move, repo: "oficina/notes") |
| 220 | #expect(await server.writes == 1) |
| 221 | } |
| 222 | @Test func undoUsesTheReceiptThePersonConfirmed() async throws { |
| 223 | let server = TaskDetailServer(), model = try Self.model(server) |
| 224 | await model.load() |
| 225 | model.loaded?.undoOffered = true |
| 226 | model.loaded?.merged = ThinMerged(sha: "hub-sha", withoutChecks: true, at: Date()) |
| 227 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 228 | var receipt = try TaskDecisionTests.card(try #require(model.task), kind: "merge_receipt", options: ["undo"]) |
| 229 | receipt.revision = 72; snapshot.cards = [receipt]; model.session.apply(snapshot) |
| 230 | await model.perform(.undoMerge, receiptRevision: 71); await model.confirm() |
| 231 | #expect(await server.writes == 0) |
| 232 | #expect(model.failure == EquipoStrings.text("card.changed")) |
| 233 | } |
| 234 | |
| 235 | @Test func anotherCreatorsMoveUsesTheWebWithoutReadingViewerProjects() async throws { |
| 236 | let server = TaskDetailServer(), original = try Self.model(server) |
| 237 | var opened: [URL] = [] |
| 238 | let model = TaskDetailModel(session: original.session, taskID: original.taskID) { origin, path in |
| 239 | SettingsNavigation.open(origin: origin, path: path) { opened.append($0) } |
| 240 | } |
| 241 | await model.load(); model.loaded?.creator = "another@example.com" |
| 242 | await model.beginMove() |
| 243 | #expect(opened.map(\.absoluteString) == ["https://task-detail.invalid/tasks/tkqsrho7oq3n/move"]) |
| 244 | #expect(await server.projectReads == 0) |
| 245 | #expect(!model.moving) |
| 246 | } |
| 247 | |
| 248 | @Test func busyAndUnloadedMoveCannotReadProjects() async throws { |
| 249 | let server = TaskDetailServer(), model = try Self.model(server) |
| 250 | await model.beginMove() |
| 251 | #expect(await server.projectReads == 0) |
| 252 | await model.load() |
| 253 | model.loaded?.stage = "done" |
| 254 | await model.beginMove() |
| 255 | #expect(await server.projectReads == 0) |
| 256 | model.loaded?.stage = "in_progress"; model.busy = true |
| 257 | await model.beginMove() |
| 258 | #expect(await server.projectReads == 0) |
| 259 | } |
| 260 | |
| 261 | } |
| 262 | |
| 263 | actor TaskDetailServer: EquipoTransport { |
| 264 | nonisolated let origin = URL(string: "https://task-detail.invalid")! |
| 265 | var requests: [APIRequest] = [] |
| 266 | var projectReads = 0 |
| 267 | var writes = 0 |
| 268 | var reads = 0 |
| 269 | var answeredCard: ThinCard? |
| 270 | func answerSuccessfully(_ card: ThinCard) { answeredCard = card } |
| 271 | var held = false |
| 272 | var conflict = false |
| 273 | var revision = 9 |
| 274 | var readStatus = 200 |
| 275 | func refuseRead(_ status: Int) { readStatus = status } |
| 276 | var pending: [CheckedContinuation<Void, Never>] = [] |
| 277 | func configure(held: Bool = false, conflict: Bool = false) { self.held = held; self.conflict = conflict } |
| 278 | func finish() { held = false; for c in pending { c.resume() }; pending = [] } |
| 279 | func send(_ request: APIRequest) async throws -> APIResponse { |
| 280 | requests.append(request) |
| 281 | if request.method == "GET", request.path == "/tasks/tkqsrho7oq3n" { |
| 282 | reads += 1 |
| 283 | if readStatus != 200 { return APIResponse(status: readStatus, data: Data()) } |
| 284 | var json = try JSONSerialization.jsonObject(with: Fixture.data("thin/task")) as! [String: Any] |
| 285 | json["revision"] = revision |
| 286 | return APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: json)) |
| 287 | } |
| 288 | if ["/tasks", "/needs-you"].contains(request.path) { |
| 289 | var task = try JSONSerialization.jsonObject(with: Fixture.data("thin/task")) as! [String: Any] |
| 290 | task["revision"] = revision |
| 291 | return APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: ["items": [task]])) |
| 292 | } |
| 293 | if request.path == "/time-zone" { return APIResponse(status: 200, data: Data(#"{"time_zone":"Europe/Dublin"}"#.utf8)) } |
| 294 | if request.path == "/snapshot" { return APIResponse(status: 200, data: Fixture.data("thin/snapshot")) } |
| 295 | if request.path == "/projects" { projectReads += 1; return APIResponse(status: 200, data: Data("{\"items\":[],\"allowed\":[\"oficina/notes\",\"oficina/equipo\",\"oficina/calendar\"]}".utf8)) } |
| 296 | writes += 1 |
| 297 | if held { await withCheckedContinuation { pending.append($0) } } |
| 298 | if conflict { |
| 299 | revision = 10 |
| 300 | return APIResponse(status: 409, data: Data(#"{"code":"revision_conflict","copy_key":"api.revision_conflict","request_id":"fixture"}"#.utf8)) |
| 301 | } |
| 302 | if request.path.contains("/answer"), var card = answeredCard { |
| 303 | card.state = "answered" |
| 304 | let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| 305 | return APIResponse(status: 200, data: try encoder.encode(Answered(card: card))) |
| 306 | } |
| 307 | return APIResponse(status: 202, data: Data("{}".utf8)) |
| 308 | } |
| 309 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| 310 | } |
| 311 | |