oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import Testing
3@testable import EquipoKit
4import EquipoActivity
5
6// Native slice 2: the device's push registration, the gateway it names, tap
7// routing and the Live Activity's content state. The payloads under
8// Fixtures/push are the server's goldens (internal/equipo/push/testdata on
9// push/server 2ea81007), copied byte for byte.
10
11private let deviceToken = Data((0..<32).map { UInt8($0) + 0xA0 })
12private let startToken = Data((0..<32).map { UInt8($0) })
13private let deviceHex = "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
14private let startHex = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
15
16private let here = "https://oficina.example.test"
17private func client(_ t: ScriptedTransport, _ bearer: String = "equipo.person.v1.TOKENFIXTURE") -> EquipoClient {
18 EquipoClient(transport: t, token: bearer)
19}
20private func registered(_ t: ScriptedTransport) {
21 t.on("POST /push-registrations", .success(APIResponse(status: 200, data: Data(#"{"environment":"production","platform":"ios","live_activities":true,"updated_at":"2026-11-20T10:00:00Z"}"#.utf8))))
22}
23private func json(_ request: APIRequest) throws -> [String: String] {
24 try JSONSerialization.jsonObject(with: try #require(request.body)) as! [String: String]
25}
26
27@MainActor @Suite struct PushRegistrationTests {
28 @Test func lateAttachCannotReplaceTheNextSignIn() async throws {
29 let t = ScriptedTransport(); registered(t)
30 let r = PushRegistrar(environment: .production, platform: .ios)
31 let lifetimes = SignInLifetimes()
32 let old = lifetimes.current
33 await r.deviceTokenChanged(deviceToken)
34 let next = lifetimes.begin()
35 await r.attach(client(t, "new-sign-in"), lifetime: next)
36 let generation = r.generation
37 await r.attach(client(t, "old-sign-in"), lifetime: old)
38 #expect(r.generation == generation)
39 #expect(t.sent("POST /push-registrations").map(\.bearer) == ["new-sign-in"])
40 }
41
42 @Test func theBodyIsTheServersShapeInLowercaseHex() throws {
43 let body = PushRegistrationBody(token: PushToken.hex(deviceToken), environment: .production, platform: .ios, startToken: PushToken.hex(startToken))
44 let sent = try JSONSerialization.jsonObject(with: try EquipoJSON.encoder.encode(body)) as! [String: String]
45 #expect(sent == ["token": deviceHex, "environment": "production", "platform": "ios", "start_token": startHex])
46 let mac = PushRegistrationBody(token: deviceHex, environment: .production, platform: .macos, startToken: startHex)
47 #expect(mac.startToken == nil, "the server refuses a push-to-start token from a Mac")
48 }
49
50 @Test func registersOnceTheTokenArrivesWithTheDeviceBearer() async throws {
51 let t = ScriptedTransport(); registered(t)
52 let r = PushRegistrar(environment: .production, platform: .ios)
53 await r.attach(client(t))
54 #expect(t.requests.isEmpty, "nothing to register before APNs gives a token")
55 await r.deviceTokenChanged(deviceToken)
56 let sent = t.sent("POST /push-registrations")
57 #expect(sent.count == 1)
58 #expect(sent.first?.bearer == "equipo.person.v1.TOKENFIXTURE")
59 #expect(try json(sent[0]) == ["token": deviceHex, "environment": "production", "platform": "ios"])
60 await r.sync(); await r.deviceTokenChanged(deviceToken)
61 #expect(t.sent("POST /push-registrations").count == 1, "the server has it: not sent again")
62 }
63
64 @Test func aMacNeverSendsAStartToken() async throws {
65 let t = ScriptedTransport(); registered(t)
66 let r = PushRegistrar(environment: .production, platform: .macos)
67 await r.attach(client(t))
68 await r.deviceTokenChanged(deviceToken)
69 await r.startTokenChanged(startToken)
70 let sent = t.sent("POST /push-registrations")
71 #expect(sent.count == 1, "a start token is iPhone-only: nothing more to register")
72 #expect(try json(sent[0]) == ["token": deviceHex, "environment": "production", "platform": "macos"])
73 }
74
75 @Test func aChangedTokenRegistersAgain() async throws {
76 let t = ScriptedTransport(); registered(t)
77 let r = PushRegistrar(environment: .production, platform: .ios)
78 await r.attach(client(t))
79 await r.deviceTokenChanged(deviceToken)
80 await r.startTokenChanged(startToken)
81 func latest() throws -> [String: String] { try json(try #require(t.sent("POST /push-registrations").last)) }
82 #expect(t.sent("POST /push-registrations").count == 2)
83 #expect(try latest()["start_token"] == startHex)
84 await r.deviceTokenChanged(startToken)
85 #expect(t.sent("POST /push-registrations").count == 3, "a new APNs token is registered")
86 #expect(try latest()["token"] == startHex)
87 await r.startTokenChanged(deviceToken)
88 #expect(t.sent("POST /push-registrations").count == 4, "a new push-to-start token is registered")
89 #expect(try latest()["start_token"] == deviceHex)
90 }
91
92 @Test func anotherTeamsSessionRegistersAgainAndNoneStops() async throws {
93 let t = ScriptedTransport(); registered(t)
94 let r = PushRegistrar(environment: .production, platform: .ios)
95 await r.attach(client(t))
96 await r.deviceTokenChanged(deviceToken)
97 await r.attach(client(t, "equipo.person.v1.OTHER"))
98 #expect(t.sent("POST /push-registrations").map(\.bearer) == ["equipo.person.v1.TOKENFIXTURE", "equipo.person.v1.OTHER"])
99 await r.attach(nil)
100 await r.startTokenChanged(startToken)
101 #expect(t.sent("POST /push-registrations").count == 2, "signed out: nothing is sent")
102 }
103
104 @Test func aRegistrationThatDidNotLandIsSentOnTheNextSync() async throws {
105 let t = ScriptedTransport()
106 t.on("POST /push-registrations", .failure(.offline))
107 registered(t)
108 let r = PushRegistrar(environment: .production, platform: .ios)
109 await r.attach(client(t))
110 await r.deviceTokenChanged(deviceToken)
111 #expect(t.sent("POST /push-registrations").count == 1)
112 await r.sync()
113 #expect(t.sent("POST /push-registrations").count == 2, "sent again when the app is in front again")
114 await r.sync()
115 #expect(t.sent("POST /push-registrations").count == 2)
116 }
117
118 @Test func aBuildThatCannotReceivePushesDoesNotRegister() async throws {
119 let t = ScriptedTransport(); registered(t)
120 let r = PushRegistrar(environment: nil, platform: .macos)
121 await r.attach(client(t))
122 await r.deviceTokenChanged(deviceToken)
123 #expect(t.requests.isEmpty)
124 }
125
126 @Test func activityTokensFollowTheRegistrationAndStopWhenTheTaskEnded() async throws {
127 let t = ScriptedTransport()
128 t.on("POST /push-registrations/activities",
129 .success(APIResponse(status: 204, data: Data())),
130 .success(APIResponse(status: 409, data: Data(#"{"code":"task_ended","copy_key":"api.task_ended","request_id":"r"}"#.utf8))),
131 .success(APIResponse(status: 204, data: Data())))
132 let r = PushRegistrar(environment: .production, platform: .ios)
133 await r.attach(client(t))
134 await r.activityTokenChanged(startToken, task: "tk1", origin: here)
135 #expect(t.sent("POST /push-registrations/activities").isEmpty, "the device registers first")
136 registered(t)
137 await r.deviceTokenChanged(deviceToken)
138 let first = t.sent("POST /push-registrations/activities")
139 #expect(first.count == 1)
140 #expect(try json(first[0]) == ["task_id": "tk1", "token": startHex])
141 #expect(first[0].bearer == "equipo.person.v1.TOKENFIXTURE")
142 await r.activityTokenChanged(deviceToken, task: "tk2", origin: here)
143 #expect(t.sent("POST /push-registrations/activities").count == 2)
144 await r.sync()
145 #expect(t.sent("POST /push-registrations/activities").count == 2, "an ended task's token is not sent again")
146 await r.activityTokenChanged(startToken, task: "tk3", origin: here)
147 #expect(try json(t.sent("POST /push-registrations/activities")[2])["task_id"] == "tk3")
148 }
149
150 @Test func aTaskTheServerSaysEndedEndsItsActivityHere() async throws {
151 let t = ScriptedTransport(); registered(t)
152 t.on("POST /push-registrations/activities",
153 .success(APIResponse(status: 409, data: Data(#"{"code":"task_ended","copy_key":"api.task_ended","request_id":"r"}"#.utf8))))
154 let r = PushRegistrar(environment: .production, platform: .ios)
155 var closed: [String] = []
156 r.onActivityClosed = { closed.append($0) }
157 await r.attach(client(t))
158 await r.deviceTokenChanged(deviceToken)
159 await r.activityTokenChanged(startToken, task: "tk1", origin: here)
160 #expect(closed == ["tk1"], "the Lock Screen does not keep a task the server says is over")
161 }
162
163 @Test func anotherTeamNeverSendsTheLastTeamsActivities() async throws {
164 let a = ScriptedTransport(); registered(a)
165 a.on("POST /push-registrations/activities", .success(APIResponse(status: 204, data: Data())))
166 let b = ScriptedTransport(origin: URL(string: "https://other.example.test")!); registered(b)
167 b.on("POST /push-registrations/activities", .success(APIResponse(status: 204, data: Data())))
168 let r = PushRegistrar(environment: .production, platform: .ios)
169 var changes = 0
170 r.onSessionChanged = { changes += 1 }
171 await r.attach(client(a))
172 await r.deviceTokenChanged(deviceToken)
173 await r.activityTokenChanged(startToken, task: "tkA", origin: here)
174 await r.attach(client(b, "equipo.person.v1.OTHER"))
175 #expect(changes == 2, "observers deliver their tokens again for each new session")
176 // Team A's activity is still on the device and its observer delivers again.
177 await r.activityTokenChanged(startToken, task: "tkA", origin: here)
178 #expect(b.sent("POST /push-registrations/activities").isEmpty, "team A's activity tokens never go to team B's server")
179 }
180
181 @Test func afterARelaunchAnotherTeamsActivityIsStillNeverSent() async throws {
182 let b = ScriptedTransport(origin: URL(string: "https://other.example.test")!); registered(b)
183 b.on("POST /push-registrations/activities", .success(APIResponse(status: 204, data: Data())))
184 // A fresh process: nothing remembered, team B signed in, and team A's
185 // activity survived (its end failed). It is seen for the first time.
186 let r = PushRegistrar(environment: .production, platform: .ios)
187 await r.attach(client(b))
188 await r.deviceTokenChanged(deviceToken)
189 await r.activityTokenChanged(startToken, task: "tkA", origin: here)
190 #expect(b.sent("POST /push-registrations/activities").isEmpty, "an activity names its team, so it is never adopted")
191 await r.activityTokenChanged(deviceToken, task: "tkB", origin: "https://OTHER.example.test")
192 let own = try #require(b.sent("POST /push-registrations/activities").first, "team B's own activity is sent")
193 #expect(try json(own)["task_id"] == "tkB")
194 }
195
196 @Test func anActivitySeenBeforeTheSessionIsRestoredIsSentOnceItIs() async throws {
197 let t = ScriptedTransport(); registered(t)
198 t.on("POST /push-registrations/activities", .success(APIResponse(status: 204, data: Data())))
199 let r = PushRegistrar(environment: .production, platform: .ios)
200 // Cold launch: observation starts before the saved session attaches.
201 await r.activityTokenChanged(startToken, task: "tk1", origin: here)
202 await r.attach(client(t))
203 await r.deviceTokenChanged(deviceToken)
204 let sent = try #require(t.sent("POST /push-registrations/activities").first,
205 "a push-started activity still gets the server's updates and its end")
206 #expect(try json(sent)["task_id"] == "tk1")
207 }
208
209 @Test func anActivityThatNamesNoTeamIsNeverSent() async throws {
210 let t = ScriptedTransport(); registered(t)
211 t.on("POST /push-registrations/activities", .success(APIResponse(status: 204, data: Data())))
212 let r = PushRegistrar(environment: .production, platform: .ios)
213 await r.attach(client(t))
214 await r.deviceTokenChanged(deviceToken)
215 await r.activityTokenChanged(startToken, task: "tk1", origin: nil)
216 #expect(t.sent("POST /push-registrations/activities").isEmpty)
217 }
218
219 @Test func aPassSuspendedAcrossASessionChangeSendsNothingMore() async throws {
220 let inner = ScriptedTransport(); registered(inner)
221 inner.on("POST /push-registrations/activities", .success(APIResponse(status: 204, data: Data())))
222 let gate = GatedTransport(inner: inner, route: "POST /push-registrations/activities")
223 let r = PushRegistrar(environment: .production, platform: .ios)
224 await r.attach(EquipoClient(transport: gate, token: "equipo.person.v1.TOKENFIXTURE"))
225 // Two activities wait for the device's registration.
226 await r.activityTokenChanged(startToken, task: "tk1", origin: here)
227 await r.activityTokenChanged(deviceToken, task: "tk2", origin: here)
228 gate.hold = true
229 // The pass registers the device, then is held on the first activity request.
230 let pass = Task { await r.deviceTokenChanged(deviceToken) }
231 await gate.waitUntilHeld()
232 await r.attach(nil)
233 gate.release()
234 await pass.value
235 let sent = inner.sent("POST /push-registrations/activities")
236 #expect(sent.count == 1, "signed out mid-pass: the second activity is never sent (\(sent.count) requests)")
237 }
238}
239
240/// A transport that holds one route's first request until released.
241final class GatedTransport: EquipoTransport, @unchecked Sendable {
242 let inner: ScriptedTransport
243 let route: String
244 var origin: URL { inner.origin }
245 private let lock = NSLock()
246 private var waiting: CheckedContinuation<Void, Never>?
247 private var heldOnce = false
248 private var heldSignal: CheckedContinuation<Void, Never>?
249 private var isHeld = false
250 var hold = false
251 init(inner: ScriptedTransport, route: String) { self.inner = inner; self.route = route }
252 func send(_ request: APIRequest) async throws -> APIResponse {
253 if hold, request.method + " " + request.path == route, !lock.withLock({ heldOnce }) {
254 await withCheckedContinuation { c in
255 lock.withLock { heldOnce = true; isHeld = true; waiting = c; let s = heldSignal; heldSignal = nil; s?.resume() }
256 }
257 }
258 return try await inner.send(request)
259 }
260 func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { try await inner.lines(request) }
261 func waitUntilHeld() async {
262 if lock.withLock({ isHeld }) { return }
263 await withCheckedContinuation { c in
264 let now: Bool = lock.withLock { if isHeld { return true }; heldSignal = c; return false }
265 if now { c.resume() }
266 }
267 }
268 func release() { lock.withLock { let c = waiting; waiting = nil; return c }?.resume() }
269}
270
271@Suite struct PushEnvironmentTests {
272 private func profile(aps: String?) -> Data {
273 let entitlements = aps.map { "<key>aps-environment</key><string>\($0)</string>" } ?? ""
274 let plist = """
275 <?xml version="1.0" encoding="UTF-8"?>
276 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
277 <plist version="1.0"><dict><key>Name</key><string>Equipo</string>
278 <key>Entitlements</key><dict>\(entitlements)<key>get-task-allow</key><true/></dict></dict></plist>
279 """
280 // A CMS envelope around it: bytes before and after.
281 return Data([0x30, 0x82, 0x0F, 0xFF]) + Data(plist.utf8) + Data([0xA0, 0x82, 0x00])
282 }
283
284 @Test func theGatewayComesFromTheBuild() {
285 #expect(PushEnvironment.resolve(platform: .ios, simulator: false, embeddedProfile: nil, signedEntitlement: nil) == .production,
286 "TestFlight and the App Store strip the profile")
287 #expect(PushEnvironment.resolve(platform: .ios, simulator: false, embeddedProfile: profile(aps: "development"), signedEntitlement: nil) == .development,
288 "an Xcode build on a device")
289 #expect(PushEnvironment.resolve(platform: .ios, simulator: false, embeddedProfile: profile(aps: "production"), signedEntitlement: nil) == .production)
290 #expect(PushEnvironment.resolve(platform: .ios, simulator: false, embeddedProfile: profile(aps: nil), signedEntitlement: nil) == nil,
291 "a profile without push cannot receive any")
292 #expect(PushEnvironment.resolve(platform: .ios, simulator: true, embeddedProfile: nil, signedEntitlement: nil) == .development)
293 #expect(PushEnvironment.resolve(platform: .macos, simulator: false, embeddedProfile: nil, signedEntitlement: "production") == .production,
294 "Developer ID")
295 #expect(PushEnvironment.resolve(platform: .macos, simulator: false, embeddedProfile: nil, signedEntitlement: nil) == nil,
296 "an ad hoc build has no push entitlement")
297 }
298
299 @Test func thisTestRunnerCannotReceivePushes() {
300 #expect(PushEnvironment.current == nil, "swift test is not signed with the entitlement")
301 }
302}
303
304@Suite struct PushRouteTests {
305 private func userInfo(_ golden: String) throws -> [AnyHashable: Any] {
306 try JSONSerialization.jsonObject(with: Fixture.data("push/" + golden)) as! [AnyHashable: Any]
307 }
308
309 @Test func aTapOpensTheRightPlace() throws {
310 #expect(PushRoute(userInfo: try userInfo("card")) == .card("c1"))
311 #expect(PushRoute(userInfo: try userInfo("card"))?.destination == Destination(pane: .conversation, cardID: "c1"),
312 "a card alert opens the conversation at the card")
313 #expect(PushRoute(userInfo: try userInfo("reply"))?.destination == Destination(pane: .conversation), "a reply opens the conversation")
314 #expect(PushRoute(userInfo: try userInfo("task-done"))?.destination == Destination(pane: .tasks, taskID: "tk1"), "a task alert opens the task")
315 #expect(PushRoute(userInfo: try userInfo("task-failed")) == .task("tk1"))
316 #expect(PushRoute(userInfo: try userInfo("badge")) == nil, "a badge opens nothing")
317 #expect(PushRoute(userInfo: ["equipo": ["kind": "card", "task_id": "tk1"]]) == .task("tk1"))
318 #expect(PushRoute(userInfo: ["equipo": ["kind": "something_new"]]) == nil)
319 #expect(PushRoute(userInfo: ["equipo": ["kind": "task"]]) == nil)
320 }
321
322 @Test func aLiveActivityOpensItsTask() {
323 let link = EquipoLink.task("tk1")
324 #expect(link.absoluteString == "works.oficina.equipo://task/tk1")
325 #expect(PushRoute(url: link) == .task("tk1"))
326 #expect(PushRoute(url: URL(string: "https://oficina.example.test/task/tk1")!) == nil)
327 #expect(PushRoute(url: URL(string: "someone-else://task/tk1")!) == nil, "only this app's own links")
328 #expect(PushRoute(url: URL(string: "works.oficina.equipo://card/c1")!) == nil)
329 #expect(PushRoute(url: URL(string: "works.oficina.equipo://task/")!) == nil)
330 }
331}
332
333@Suite struct LiveActivityStateTests {
334 private func aps(_ golden: String) throws -> [String: Any] {
335 let payload = try JSONSerialization.jsonObject(with: Fixture.data("push/" + golden)) as! [String: Any]
336 return payload["aps"] as! [String: Any]
337 }
338 /// ActivityKit decodes the content state with a plain JSONDecoder.
339 private func state(_ golden: String) throws -> EquipoTaskAttributes.ContentState {
340 let raw = try JSONSerialization.data(withJSONObject: try aps(golden)["content-state"]!)
341 return try JSONDecoder().decode(EquipoTaskAttributes.ContentState.self, from: raw)
342 }
343
344 @Test func theServersGoldensDecode() throws {
345 let start = try aps("activity-start")
346 #expect(start["attributes-type"] as? String == String(describing: EquipoTaskAttributes.self),
347 "push-to-start names this type")
348 let attributes = try JSONDecoder().decode(EquipoTaskAttributes.self, from: JSONSerialization.data(withJSONObject: start["attributes"]!))
349 #expect(attributes == EquipoTaskAttributes(taskID: "tk1", origin: "https://oficina.example.test"))
350 #expect(try state("activity-start") == .init(taskID: "tk1", title: "Fix login", stage: "in_progress", specialist: "engineering",
351 activity: "Reading README.md", needsYou: "", tone: "positive"))
352 #expect(try state("activity-update").outcome == nil)
353 let needs = try state("activity-needs")
354 #expect(needs.needsYou == "merge"); #expect(needs.tone == "warning"); #expect(needs.stage == "ready_to_merge")
355 #expect(try state("activity-end").outcome == "done")
356 #expect(try state("activity-replaced").outcome == "replaced")
357 }
358
359 @Test func theStateEncodesAsTheWireDoes() throws {
360 let start = try state("activity-start")
361 let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(start)) as! [String: String]
362 #expect(encoded.keys.sorted() == ["activity", "needs_you", "specialist", "stage", "task_id", "title", "tone"], "no outcome until it ended")
363 #expect(try JSONDecoder().decode(EquipoTaskAttributes.ContentState.self, from: JSONEncoder().encode(try state("activity-end"))).outcome == "done")
364 }
365
366 @Test func theActivityIsDrawnFromRoster() throws {
367 let running = TaskActivityPresentation(try state("activity-update"))
368 #expect(running.line == "Reading README.md")
369 #expect(running.tone == .positive)
370 #expect(running.specialist == .engineering)
371 #expect(running.track.map(\.state) == [.done, .current, .todo, .todo, .todo])
372 #expect(running.outcome == nil)
373 #expect(running.url == EquipoLink.task("tk1"))
374
375 let needs = TaskActivityPresentation(try state("activity-needs"))
376 #expect(needs.needsYou)
377 #expect(needs.tone == .warning, "amber while it needs you")
378 #expect(needs.line == "Needs you")
379 #expect(needs.track.first { $0.state == .current }?.stage == .readyToMerge)
380 #expect(needs.track.first { $0.state == .current }?.tone == .warning)
381 var waitingAnyway = try state("activity-needs"); waitingAnyway.tone = "positive"
382 #expect(TaskActivityPresentation(waitingAnyway).tone == .warning, "a needs-you activity is never green")
383
384 let done = TaskActivityPresentation(try state("activity-end"))
385 #expect(done.outcome == "Done"); #expect(done.line == "Done"); #expect(!done.needsYou)
386 #expect(done.track.map(\.state) == [.done, .done, .done, .done, .current])
387
388 var cancelled = try state("activity-update"); cancelled.stage = "cancelled"; cancelled.outcome = "cancelled"
389 #expect(TaskActivityPresentation(cancelled).track.isEmpty, "a cancelled task has no track")
390 #expect(TaskActivityPresentation(cancelled).line == "Cancelled")
391 var failed = try state("activity-update"); failed.outcome = "failed"; failed.tone = "negative"
392 #expect(TaskActivityPresentation(failed).line == "Stopped")
393 #expect(TaskActivityPresentation(failed).tone == .negative)
394 #expect(TaskActivityPresentation(try state("activity-replaced")).outcome == nil, "a replaced activity is dismissed at once")
395 }
396
397 @Test func anActivityTheAppKnowsEndedIsEnded() throws {
398 let tasks: ThinList<ThinTask> = try Fixture.decode("thin/tasks")
399 let items = tasks.items ?? []
400 let ended = LiveActivityPolicy.finished(running: ["tkqsrho7oq3n", "tkyiki7muqby", "gone"], tasks: items)
401 #expect(ended == ["tkyiki7muqby": "done"], "only the finished task; one the app cannot see is left to the server")
402 #expect(LiveActivityPolicy.finished(running: ["tkqsrho7oq3n"], tasks: items).isEmpty, "only activities that run")
403 }
404}
405
406/// A fake system: what the app model asked of it.
407@MainActor final class FakeNotifications: NotificationSystem {
408 var asked = 0
409 var badges: [Int] = []
410 var unregistered = 0
411 func askAndRegister() { asked += 1 }
412 func setBadge(_ count: Int) { badges.append(count) }
413 func unregister() { unregistered += 1 }
414}
415
416@MainActor @Suite struct RemoteRegistrationTests {
417 @Test func signingOutWhileAskingNeverRegistersAfterwards() async {
418 var calls: [String] = []
419 var release: CheckedContinuation<Void, Never>?
420 var asked = 0
421 let gate = RemoteRegistration(
422 authorize: {
423 asked += 1
424 if asked == 1 { await withCheckedContinuation { release = $0 } }
425 },
426 register: { calls.append("register") },
427 unregister: { calls.append("unregister") })
428 let asking = gate.request()
429 while release == nil { await Task.yield() }
430 gate.stop()
431 release?.resume()
432 await asking.value
433 #expect(calls == ["unregister"], "a pending permission prompt cannot undo a sign-out")
434 await gate.request().value
435 #expect(calls == ["unregister", "register"], "pairing again registers again")
436 }
437
438 @Test func signingOutBeforeTheAskStartsNeverRegisters() async {
439 var calls: [String] = []
440 let gate = RemoteRegistration(
441 authorize: { calls.append("authorize") },
442 register: { calls.append("register") },
443 unregister: { calls.append("unregister") })
444 let queued = gate.request()
445 gate.stop()
446 await queued.value
447 #expect(calls == ["unregister"], "an ask queued before sign-out is stale too")
448 }
449}
450
451@MainActor @Suite struct NotificationPermissionTests {
452 @Test func permissionIsAskedAfterPairingNotBefore() throws {
453 let fake = FakeNotifications()
454 let model = EquipoAppModel(store: MemorySecretStore(), notifications: fake, push: PushRegistrar(environment: nil))
455 #expect(fake.asked == 0, "no team yet: nothing is asked at launch")
456 var account = DeviceAccount.new(origin: URL(string: "https://oficina.example.test")!, label: "Test")
457 account.credential = try Fixture.decode("device-credential")
458 model.adopt(account, transport: ScriptedTransport())
459 #expect(fake.asked == 1, "asked once the device is paired")
460 }
461
462 @Test func theBadgeIsTheNeedsYouCountAndClearsOnSignOut() async throws {
463 let fake = FakeNotifications()
464 let model = EquipoAppModel(store: MemorySecretStore(), notifications: fake, push: PushRegistrar(environment: nil))
465 model.needsYouChanged(3)
466 #expect(fake.badges.isEmpty, "no team, no badge")
467 var account = DeviceAccount.new(origin: URL(string: "https://oficina.example.test")!, label: "Test")
468 account.credential = try Fixture.decode("device-credential")
469 model.adopt(account, transport: ScriptedTransport())
470 model.needsYouChanged(nil)
471 #expect(fake.badges.isEmpty, "an unknown count is not zero")
472 model.needsYouChanged(2)
473 #expect(fake.badges == [2])
474 model.sessionEnded()
475 #expect(fake.badges == [2, 0])
476 }
477
478 @Test func signingOutStopsDeliveryEvenWhenTheServerCannotBeReached() async throws {
479 let fake = FakeNotifications()
480 let model = EquipoAppModel(store: MemorySecretStore(), notifications: fake, push: PushRegistrar(environment: nil))
481 var account = DeviceAccount.new(origin: URL(string: "https://oficina.example.test")!, label: "Test")
482 account.credential = try Fixture.decode("device-credential")
483 let t = ScriptedTransport()
484 t.on("GET /auth/devices", .failure(.offline))
485 model.adopt(account, transport: t)
486 await model.signOut()
487 #expect(fake.unregistered == 1, "offline sign-out still stops this device receiving the team's notifications")
488 model.adopt(account, transport: ScriptedTransport())
489 model.sessionEnded()
490 #expect(fake.unregistered == 2, "a session the server ended stops them too")
491 }
492
493 @Test func aTapGoesWhereItSays() {
494 let model = EquipoAppModel(store: MemorySecretStore(), notifications: FakeNotifications(), push: PushRegistrar(environment: nil))
495 model.open(.card("c1"))
496 #expect(model.destination == Destination(pane: .conversation, cardID: "c1"))
497 model.open(.task("tk1"))
498 #expect(model.destination == Destination(pane: .tasks, taskID: "tk1"))
499 }
500}
501