SPB Git

Repository Public

NextAPITests.swift 80.2 KB 773 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailCore/Tests/SPMailCoreTests/NextAPITests.swift3// Description: Request / response tests of every NextAPI call against a stubbed URLProtocol: exact method, path, query and body; decoding of full,4// minimal and unknown-field answers; each typed error. Shapes are those of sp-mail `server/src/next/*.ts` (read on 2026-11-20).5import Foundation6import Testing7@testable import SPMailCore89private let t0 = Date(timeIntervalSince1970: 1_796_130_000) // 2026-12-01T13:00:00Z10private let iso0 = "2026-12-01T13:00:00Z"1112@Suite struct NextTransportTests {13    @Test func everyRequestCarriesTheSessionHeadersOfTheExistingClient() async throws {14        let (_, r) = try await exchange(.json(#"{"version":"0.4.0","features":["push","labels"]}"#)) { try await $0.capabilities() }15        #expect(r.line == "GET /api/next/capabilities")16        #expect(r.header("Authorization") == "Bearer test-token" && r.header("X-SPMail-Client") == "native" && r.header("User-Agent") == "SPMailCoreTests" && r.header("Accept") == "application/json")17        #expect(r.header("Origin") == nil && r.header("Cookie") == nil && r.body.isEmpty)18    }1920    @Test func capabilitiesDecodeAndAnOlderServerMeansNone() async throws {21        let (c, _) = try await exchange(.json(#"{"version":"0.4.0","features":["push","labels","saved_searches","undo_send","from_the_future"],"extra":1}"#)) { try await $0.capabilities() }22        #expect(c.version == "0.4.0" && c.has(.push) && c.has(.savedSearches) && c.has(.undoSend) && !c.has(.ai) && c.features.contains("from_the_future"))23        // Fastify's own 404 for a route that does not exist24        let (none, _) = try await exchange(.json(#"{"message":"Route GET:/api/next/capabilities not found","error":"Not Found","statusCode":404}"#, status: 404)) { try await $0.capabilitiesOrNone() }25        #expect(none == .none && !none.has(.push))26        let (minimal, _) = try await exchange(.json("{}")) { try await $0.capabilities() }27        #expect(minimal.version == "" && minimal.features.isEmpty)28    }2930    @Test func typedErrors() async throws {31        #expect(await failure(.error(409, "ai_disabled", message: "off")) { try await $0.aiSettings() } as? NextError == .aiDisabled)32        #expect(await failure(.error(412, "consent_required")) { try await $0.setAISettings(AISettingsUpdate(provider: .anthropic)) } as? NextError == .consentRequired)33        #expect(await failure(.error(404, "not_found")) { try await $0.deleteLabel(id: uuidA) } as? NextError == .notFound)34        #expect(await failure(.error(429, "rate_limited")) { try await $0.labels() } as? NextError == .rateLimited(retryAfter: nil))35        #expect(await failure(.error(429, "rate_limited", headers: ["Retry-After": "17"])) { try await $0.labels() } as? NextError == .rateLimited(retryAfter: 17))36        // /api/v1 envelope, with the matching recipients in details37        let v1 = StubReply.json(#"{"error":{"code":"confirmation_required","message":"Some recipients are marked as sensitive","details":{"recipients":["boss@example.com","x@secret.example"]}}}"#, status: 409)38        let e = await failure(v1) { try await $0.send(SendRequest(from: "a@stg.spboucher.ai", to: [EmailAddress(email: "boss@example.com")]), idempotencyKey: "k") }39        #expect(e as? NextError == .confirmationRequired(recipients: ["boss@example.com", "x@secret.example"]))40        // a 409 that is not one of the typed ones stays an APIError with its code41        let conflict = await failure(.error(409, "name_taken", message: "A label with this name already exists")) { try await $0.createLabel(name: "x") } as? APIError42        #expect(conflict?.status == 409 && conflict?.code == "name_taken" && conflict?.message == "A label with this name already exists")43        // the same code on another status is not misread44        #expect((await failure(.error(400, "confirmation_required")) { try await $0.labels() } as? APIError)?.status == 400)45        #expect((await failure(.error(503, "ai_not_configured")) { try await $0.write(AIWriteRequest(action: .improve, text: "x")) } as? APIError)?.code == "ai_not_configured")46    }4748    @Test func unauthorizedAndOfflineKeepTheHistoricalErrorType() async throws {49        let unauth = await failure(.error(401, "unauthenticated")) { try await $0.labels() }50        #expect((unauth as? APIError)?.isUnauthorized == true && NextError.isUnauthorized(unauth!) && !NextError.isPermanentRefusal(unauth!) && !NextError.isTransient(unauth!))51        let off = await failure(.offline) { try await $0.labels() }52        #expect((off as? APIError)?.isOffline == true && NextError.isOffline(off!) && NextError.isTransient(off!) && !NextError.isPermanentRefusal(off!))53        let server = await failure(.error(502, "mail_server_error")) { try await $0.labels() }54        #expect(NextError.isTransient(server!) && !NextError.isPermanentRefusal(server!))55        #expect(NextError.isPermanentRefusal(NextError.notFound) && NextError.isPermanentRefusal(APIError(status: 400, code: "invalid_request")) && !NextError.isPermanentRefusal(NextError.rateLimited(retryAfter: 3)))56        #expect(NextError.isTransient(NextError.rateLimited(retryAfter: nil)) && !NextError.isTransient(NextError.aiDisabled))57    }5859    @Test func aBodyThatIsNotWhatTheContractPromisesIsABadResponseNotACrash() async throws {60        #expect(await failure(.json("<html>proxy error</html>")) { try await $0.labels() } as? NextError == .badResponse("GET /api/next/labels: not JSON"))61        #expect(await failure(.json("{}")) { try await $0.createLabel(name: "x") } as? NextError == .badResponse("label"))62        #expect(await failure(.json(#"{"ok":true}"#)) { try await $0.registerPush(PushRegistration(apnsToken: Data([1]), sandbox: true, bundleId: "b")) } as? NextError == .badResponse("push/register: no device_id"))63        // an empty list answer is an empty list64        let (l, _) = try await exchange(.json("{}")) { try await $0.labels() }65        #expect(l.isEmpty)66    }6768    @Test func aCancelledTaskThrowsCancellation() async throws {69        let server = FakeServer(.ok)70        let api = server.api71        let task = Task { () -> Bool in72            withUnsafeCurrentTask { $0?.cancel() }73            do { _ = try await api.labels(); return false } catch is CancellationError { return true } catch { return false }74        }75        #expect(await task.value)76        #expect(server.requests.isEmpty)77    }78}7980@Suite struct NextPushAPITests {81    @Test func registerSendsTheExtendedFields() async throws {82        let reg = PushRegistration(apnsToken: Data([0xde, 0xad, 0xbe, 0xef]), sandbox: false, bundleId: "ai.spboucher.spmail", deviceName: "  iPhone de SP  ", locale: "fr_CA", appVersion: "2.0.0 (1)")83        let (id, r) = try await exchange(.json(#"{"ok":true,"device_id":"\#(uuidA)"}"#)) { try await $0.registerPush(reg) }84        #expect(id == uuidA && r.line == "POST /api/push/register" && r.header("Content-Type") == "application/json")85        #expect(r.json == ["apns_token": "deadbeef", "environment": "production", "bundle_id": "ai.spboucher.spmail", "device_name": "iPhone de SP", "locale": "fr_CA", "app_version": "2.0.0 (1)"])86        let (_, minimal) = try await exchange(.json(#"{"ok":true,"device_id":"x"}"#)) { try await $0.registerPush(PushRegistration(apnsToken: Data([1, 2]), sandbox: true, bundleId: "b", deviceName: " ")) }87        #expect(minimal.json == ["apns_token": "0102", "environment": "sandbox", "bundle_id": "b"])88    }8990    @Test func devicesListPatchDelete() async throws {91        let full = #"{"data":[{"id":"\#(uuidA)","session_id":"\#(uuidB)","device_name":"iPhone","bundle_id":"ai.spboucher.spmail","environment":"production","enabled":true,"current":true,"prefs":{"mailboxes":{"\#(uuidC)":false},"sound":false},"locale":"fr_CA","app_version":"2.0.0","created_at":"\#(iso0)","last_registered_at":"2026-12-01T13:00:00.123Z","last_push_at":null,"last_error":null,"new_field":{"x":1}},{"id":"d2","environment":"visionos"},{"no_id":true}]}"#92        let (devices, r) = try await exchange(.json(full)) { try await $0.pushDevices() }93        #expect(r.line == "GET /api/next/push/devices" && devices.count == 2)94        let d = devices[0]95        #expect(d.id == uuidA && d.sessionId == uuidB && d.current && d.enabled && d.environment == .production && d.mailboxes == [uuidC: false] && d.sound == false && d.appVersion == "2.0.0")96        #expect(d.createdAt == t0 && d.lastRegisteredAt != nil && d.lastPushAt == nil && d.lastError == nil)97        #expect(devices[1].environment == .unknown && devices[1].enabled && !devices[1].current && devices[1].deviceName == "" && devices[1].mailboxes.isEmpty && devices[1].sound == nil)9899        let (_, p) = try await exchange(.ok) { try await $0.updatePushDevice(id: uuidA, PushDevicePatch(enabled: false, mailboxes: [uuidC: true], sound: true)) }100        #expect(p.line == "PATCH /api/next/push/devices/\(uuidA)" && p.json == ["enabled": false, "prefs": ["mailboxes": [uuidC: true], "sound": true]])101        let (_, p2) = try await exchange(.ok) { try await $0.updatePushDevice(id: uuidA, PushDevicePatch(enabled: true)) }102        #expect(p2.json == ["enabled": true])103        let (_, del) = try await exchange(.ok) { try await $0.deletePushDevice(id: uuidA) }104        #expect(del.line == "DELETE /api/next/push/devices/\(uuidA)" && del.body.isEmpty)105    }106107    @Test func prefsRoundTrip() async throws {108        let body = #"{"enabled":true,"preview":"full","quiet_hours":{"start":"22:00","end":"07:00","tz":"America/Toronto"},"priority_senders":["boss@example.com","@uqo.ca"],"priority_only":true,"mailboxes":{"\#(uuidA)":false},"badge":"none","later":1}"#109        let (prefs, r) = try await exchange(.json(body)) { try await $0.pushPrefs() }110        #expect(r.line == "GET /api/next/push/prefs")111        #expect(prefs == PushPrefs(enabled: true, preview: .full, quietHours: QuietHours(start: "22:00", end: "07:00", timeZone: "America/Toronto"), prioritySenders: ["boss@example.com", "@uqo.ca"], priorityOnly: true, mailboxes: [uuidA: false], badge: PushBadge.none))112        #expect(prefs.isMuted(mailbox: uuidA) && !prefs.isMuted(mailbox: uuidB))113        let (defaults, _) = try await exchange(.json("{}")) { try await $0.pushPrefs() }114        #expect(defaults == PushPrefs() && defaults.preview == .sender && defaults.quietHours == nil && defaults.badge == .inbox)115116        var draft = prefs117        draft.prioritySenders = [" Boss@Example.com ", ""]118        draft.quietHours = nil119        let edited = draft120        let (saved, put) = try await exchange(.json(body)) { try await $0.setPushPrefs(edited) }121        #expect(put.line == "PUT /api/next/push/prefs" && saved.preview == .full)122        #expect(put.json == ["enabled": true, "preview": "full", "quiet_hours": nil, "priority_senders": ["boss@example.com"], "priority_only": true, "mailboxes": [uuidA: false], "badge": "none"])123        // a value this build does not know is not written back124        let (future, _) = try await exchange(.json(#"{"preview":"summary","badge":"all"}"#)) { try await $0.pushPrefs() }125        #expect(future.preview == .unknown && future.badge == .unknown && future.json["preview"].isNull && future.json["badge"].isNull && future.json["enabled"] == true)126    }127128    @Test func statusAndTest() async throws {129        let (s, r) = try await exchange(.json(#"{"configured":false,"environment_hosts":{"production":"api.push.apple.com","sandbox":"api.sandbox.push.apple.com"},"queue":{"pending":2,"failed_24h":1,"sent_24h":40},"last_error":"APNs key file missing"}"#)) { try await $0.pushStatus() }130        #expect(r.line == "GET /api/next/push/status" && !s.configured && s.pending == 2 && s.failed24h == 1 && s.sent24h == 40 && s.lastError == "APNs key file missing" && s.environmentHosts["sandbox"] == "api.sandbox.push.apple.com")131        let (empty, _) = try await exchange(.json("{}")) { try await $0.pushStatus() }132        #expect(!empty.configured && empty.pending == 0 && empty.environmentHosts.isEmpty && empty.lastError == nil)133        let (n, t) = try await exchange(.json(#"{"queued":2}"#)) { try await $0.testPush() }134        #expect(n == 2 && t.line == "POST /api/next/push/test" && t.json == [:])135        let (_, one) = try await exchange(.json(#"{"queued":1}"#)) { try await $0.testPush(deviceId: uuidA) }136        #expect(one.json == ["device_id": .string(uuidA)])137    }138}139140@Suite struct NextSnoozeAPITests {141    static let snooze = #"{"id":"\#(uuidA)","mailbox_id":"\#(uuidB)","email_id":"M1","thread_id":"T1","subject":"Devis","from":{"name":"Jeanne","email":"jeanne@example.com"},"until":"\#(iso0)","status":"active","created_at":"\#(iso0)","woken_at":null}"#142    static let reminder = #"{"id":"\#(uuidA)","mailbox_id":"\#(uuidB)","email_id":"M1","thread_id":"T1","subject":"Devis","counterpart":{"name":null,"email":"jeanne@example.com"},"due_at":"\#(iso0)","only_if_no_reply":true,"note":"relancer","status":"pending","fired_at":null,"created_at":"\#(iso0)"}"#143144    @Test func snoozeCreateListUpdateCancel() async throws {145        let (made, r) = try await exchange(.json(#"{"data":[\#(Self.snooze)]}"#)) { try await $0.snooze(mailboxId: uuidB, emailIds: ["M1", "M2"], until: t0) }146        #expect(r.line == "POST /api/next/snoozes" && r.json == ["mailbox_id": .string(uuidB), "email_ids": ["M1", "M2"], "until": .string(iso0)])147        #expect(made.count == 1 && made[0].id == uuidA && made[0].mailboxId == uuidB && made[0].emailId == "M1" && made[0].threadId == "T1" && made[0].from == EmailAddress(name: "Jeanne", email: "jeanne@example.com"))148        #expect(made[0].until == t0 && made[0].status == .active && made[0].isActive && made[0].createdAt == t0)149150        let (list, l) = try await exchange(.json(#"{"data":[\#(Self.snooze),{"id":"s2","mailbox_id":"m","email_id":"e","status":"hibernating"},{"id":"broken"}]}"#)) { try await $0.snoozes() }151        #expect(l.line == "GET /api/next/snoozes?status=active" && list.count == 2 && list[1].status == .unknown && list[1].from == nil && list[1].until == nil && list[1].subject == "")152        let (_, all) = try await exchange(.json(#"{"data":[]}"#)) { try await $0.snoozes(status: nil) }153        #expect(all.line == "GET /api/next/snoozes")154        let (_, done) = try await exchange(.json(#"{"data":[]}"#)) { try await $0.snoozes(status: .done) }155        #expect(done.line == "GET /api/next/snoozes?status=done")156157        let (moved, u) = try await exchange(.json(Self.snooze)) { try await $0.updateSnooze(id: uuidA, until: t0) }158        #expect(u.line == "PATCH /api/next/snoozes/\(uuidA)" && u.json == ["until": .string(iso0)] && moved.id == uuidA)159        let (status, d) = try await exchange(.json(#"{"ok":true,"status":"cancelled"}"#)) { try await $0.cancelSnooze(id: uuidA) }160        #expect(d.line == "DELETE /api/next/snoozes/\(uuidA)" && status == .cancelled)161        let closed = await failure(.error(409, "not_active", message: "This snooze is no longer active")) { try await $0.updateSnooze(id: uuidA, until: t0) } as? APIError162        #expect(closed?.code == "not_active")163    }164165    @Test func remindersCreateListUpdateCancel() async throws {166        let (made, r) = try await exchange(.json(Self.reminder)) { try await $0.createReminder(mailboxId: uuidB, emailId: "M1", dueAt: t0, onlyIfNoReply: true, note: "relancer") }167        #expect(r.line == "POST /api/next/reminders" && r.json == ["mailbox_id": .string(uuidB), "email_id": "M1", "due_at": .string(iso0), "only_if_no_reply": true, "note": "relancer"])168        #expect(made.counterpart == EmailAddress(email: "jeanne@example.com") && made.dueAt == t0 && made.onlyIfNoReply && made.note == "relancer" && made.status == .pending && made.isOpen && made.firedAt == nil)169        let (_, bare) = try await exchange(.json(Self.reminder)) { try await $0.createReminder(mailboxId: uuidB, emailId: "M1", dueAt: t0) }170        #expect(bare.json == ["mailbox_id": .string(uuidB), "email_id": "M1", "due_at": .string(iso0)])171172        let (list, l) = try await exchange(.json(#"{"data":[\#(Self.reminder),{"id":"r2","mailbox_id":"m","email_id":"e","status":"escalated","extra":[1]}]}"#)) { try await $0.reminders(status: .due) }173        #expect(l.line == "GET /api/next/reminders?status=due" && list.count == 2 && list[1].status == .unknown && !list[1].isOpen && !list[1].onlyIfNoReply)174        let (_, all) = try await exchange(.json(#"{"data":[]}"#)) { try await $0.reminders() }175        #expect(all.line == "GET /api/next/reminders")176177        let (_, u) = try await exchange(.json(Self.reminder)) { try await $0.updateReminder(id: uuidA, dueAt: t0, note: "", done: true) }178        #expect(u.line == "PATCH /api/next/reminders/\(uuidA)" && u.json == ["due_at": .string(iso0), "note": nil, "status": "done"])179        let (_, u2) = try await exchange(.json(Self.reminder)) { try await $0.updateReminder(id: uuidA, note: "plus tard") }180        #expect(u2.json == ["note": "plus tard"])181        let (status, d) = try await exchange(.json(#"{"ok":true,"status":"cancelled"}"#)) { try await $0.cancelReminder(id: uuidA) }182        #expect(d.line == "DELETE /api/next/reminders/\(uuidA)" && status == .cancelled)183    }184}185186@Suite struct NextOrganizeAPITests {187    @Test func labels() async throws {188        let (list, r) = try await exchange(.json(##"{"data":[{"id":"\##(uuidA)","name":"Clients","color":"#1d5fa8","keyword":"lbl_0a1b2c3d","position":2,"created_at":"x"},{"id":"l2"},{"name":"no id"}]}"##)) { try await $0.labels() }189        #expect(r.line == "GET /api/next/labels" && list.count == 2)190        #expect(list[0] == MailLabel(id: uuidA, name: "Clients", color: "#1d5fa8", keyword: "lbl_0a1b2c3d", position: 2))191        #expect(list[1].name == "" && list[1].color == LabelPalette.fallback && list[1].keyword == "" && list[1].position == 0)192193        let one = ##"{"id":"\##(uuidA)","name":"Clients","color":"#1d5fa8","keyword":"lbl_0a1b2c3d","position":0}"##194        let (made, c) = try await exchange(.json(one, status: 201)) { try await $0.createLabel(name: "  Clients  ", color: "#1D5FA8", position: 3) }195        #expect(c.line == "POST /api/next/labels" && c.json == ["name": "Clients", "color": "#1d5fa8", "position": 3] && made.keyword == "lbl_0a1b2c3d")196        let (_, c2) = try await exchange(.json(one, status: 201)) { try await $0.createLabel(name: String(repeating: "x", count: 60)) }197        #expect(c2.json == ["name": .string(String(repeating: "x", count: 40))])198        let (_, u) = try await exchange(.json(one)) { try await $0.updateLabel(id: uuidA, color: "#b3261e") }199        #expect(u.line == "PATCH /api/next/labels/\(uuidA)" && u.json == ["color": "#b3261e"])200        let (_, d) = try await exchange(.ok) { try await $0.deleteLabel(id: uuidA) }201        #expect(d.line == "DELETE /api/next/labels/\(uuidA)")202    }203204    @Test func savedSearches() async throws {205        let full = ##"{"id":"\##(uuidA)","name":"Factures","query":"has:attachment from:@hydro.qc.ca","mailbox_ids":["\##(uuidB)"],"icon":"doc","color":"#7a5c00","pinned":true,"position":1,"notify":true,"updated_at":"\##(iso0)"}"##206        let (list, r) = try await exchange(.json(#"{"data":[\#(full),{"id":"s2","mailbox_ids":null}]}"#)) { try await $0.savedSearches() }207        #expect(r.line == "GET /api/next/searches" && list.count == 2)208        #expect(list[0].name == "Factures" && list[0].query == "has:attachment from:@hydro.qc.ca" && list[0].scope == .only([uuidB]) && list[0].icon == "doc" && list[0].color == "#7a5c00" && list[0].pinned && list[0].notify && list[0].position == 1 && list[0].updatedAt == t0)209        #expect(list[1].scope == .all && !list[1].pinned && list[1].icon == nil && list[1].query == "")210211        let (_, c) = try await exchange(.json(full, status: 201)) { try await $0.createSavedSearch(SavedSearchContent(name: "Factures", query: "has:attachment", scope: .only([uuidB]), color: "#7A5C00", pinned: true)) }212        #expect(c.line == "POST /api/next/searches" && c.json == ["name": "Factures", "query": "has:attachment", "mailbox_ids": [.string(uuidB)], "color": "#7a5c00", "pinned": true])213        let (_, u) = try await exchange(.json(full)) { try await $0.updateSavedSearch(id: uuidA, SavedSearchContent(scope: .all, icon: "", color: "", position: 4, notify: false)) }214        #expect(u.line == "PATCH /api/next/searches/\(uuidA)" && u.json == ["mailbox_ids": nil, "icon": nil, "color": nil, "position": 4, "notify": false])215        let (_, d) = try await exchange(.ok) { try await $0.deleteSavedSearch(id: uuidA) }216        #expect(d.line == "DELETE /api/next/searches/\(uuidA)")217        #expect((await failure(.error(400, "invalid_query", message: "is:blue: Unknown state")) { try await $0.createSavedSearch(SavedSearchContent(name: "x", query: "is:blue")) } as? APIError)?.code == "invalid_query")218    }219220    @Test func snippets() async throws {221        let full = #"{"id":"\#(uuidA)","name":"Merci","shortcut":"merci","subject":null,"html":"<p>Merci !</p>","text":"Merci !","position":0,"updated_at":"\#(iso0)"}"#222        let (list, r) = try await exchange(.json(#"{"data":[\#(full),{"id":"n2"}]}"#)) { try await $0.snippets() }223        #expect(r.line == "GET /api/next/snippets" && list.count == 2 && list[0].shortcut == "merci" && list[0].subject == nil && list[0].html == "<p>Merci !</p>" && list[0].text == "Merci !" && list[0].updatedAt == t0)224        #expect(list[1].shortcut == nil && list[1].html == "" && list[1].name == "")225        let (_, c) = try await exchange(.json(full, status: 201)) { try await $0.createSnippet(SnippetContent(name: "Merci", shortcut: "MERCI", html: "<p>Merci !</p>", text: "Merci !")) }226        #expect(c.line == "POST /api/next/snippets" && c.json == ["name": "Merci", "shortcut": "merci", "html": "<p>Merci !</p>", "text": "Merci !"])227        let (_, u) = try await exchange(.json(full)) { try await $0.updateSnippet(id: uuidA, SnippetContent(shortcut: "", subject: "", position: 2)) }228        #expect(u.line == "PATCH /api/next/snippets/\(uuidA)" && u.json == ["shortcut": nil, "subject": nil, "position": 2])229        let (_, d) = try await exchange(.ok) { try await $0.deleteSnippet(id: uuidA) }230        #expect(d.line == "DELETE /api/next/snippets/\(uuidA)")231        #expect((await failure(.error(409, "shortcut_taken")) { try await $0.createSnippet(SnippetContent(name: "x", shortcut: "merci", text: "y")) } as? APIError)?.code == "shortcut_taken")232    }233234    @Test func signaturesIncludingTheReadOnlyPerAddressEntries() async throws {235        let own = #"{"id":"\#(uuidA)","source":"user","read_only":false,"name":"Travail","html":"<p>SP</p>","text":"SP","default_for":["\#(uuidB)"],"default_for_replies":[],"position":0,"updated_at":"\#(iso0)"}"#236        let legacy = #"{"id":"address:\#(uuidC)","source":"address","read_only":true,"address_id":"\#(uuidC)","name":"alias@stg.spboucher.ai","html":"","text":"Alias","default_for":["\#(uuidC)"],"default_for_replies":["\#(uuidC)"],"position":null,"updated_at":null}"#237        let (list, r) = try await exchange(.json(#"{"data":[\#(own),\#(legacy)]}"#)) { try await $0.signatures() }238        #expect(r.line == "GET /api/next/signatures" && list.count == 2)239        #expect(!list[0].isReadOnly && list[0].defaultFor == [uuidB] && list[0].position == 0 && list[1].isReadOnly && list[1].addressId == uuidC && list[1].id == "address:\(uuidC)" && list[1].position == nil)240        #expect(Signature.defaultSignature(forAddress: uuidB, isReply: false, in: list)?.id == uuidA)241        #expect(Signature.defaultSignature(forAddress: uuidB, isReply: true, in: list)?.id == uuidA)242        #expect(Signature.defaultSignature(forAddress: uuidC, isReply: true, in: list)?.id == "address:\(uuidC)")243        #expect(Signature.defaultSignature(forAddress: "other", isReply: false, in: list) == nil)244245        let (_, c) = try await exchange(.json(own, status: 201)) { try await $0.createSignature(SignatureContent(name: "Travail", html: "<p>SP</p>", text: "SP", defaultFor: [uuidB])) }246        #expect(c.line == "POST /api/next/signatures" && c.json == ["name": "Travail", "html": "<p>SP</p>", "text": "SP", "default_for": [.string(uuidB)]])247        let (_, u) = try await exchange(.json(own)) { try await $0.updateSignature(id: uuidA, SignatureContent(defaultForReplies: [])) }248        #expect(u.line == "PATCH /api/next/signatures/\(uuidA)" && u.json == ["default_for_replies": []])249        // the per-address id is one path segment250        let ro = FakeServer(.error(409, "read_only"))251        let e = await { do { _ = try await ro.api.updateSignature(id: "address:\(uuidC)", SignatureContent(name: "x")); return nil as APIError? } catch { return error as? APIError } }()252        #expect(e?.code == "read_only" && ro.last.path == "/api/next/signatures/address%3A\(uuidC)")253        let (_, d) = try await exchange(.ok) { try await $0.deleteSignature(id: uuidA) }254        #expect(d.line == "DELETE /api/next/signatures/\(uuidA)")255    }256}257258@Suite struct NextContactsAPITests {259    static let contact = ##"{"id":"\##(uuidA)","kind":"saved","name":"Jeanne Tremblay","emails":[{"email":"jeanne@example.com","label":"travail"},{"email":"jt@perso.example","label":null}],"organization":"UQO","title":null,"phones":[{"number":"+1 819 555 0100","label":"mobile"}],"notes":"note","favorite":true,"vip":true,"groups":["\##(uuidB)"],"avatar_color":"#0284c7","stats":{"sent":4,"received":9,"last_at":"\##(iso0)"},"created_at":"\##(iso0)","updated_at":"\##(iso0)"}"##260261    @Test func listWithEveryFilterAndPaging() async throws {262        let (page, r) = try await exchange(.json(#"{"data":[\#(Self.contact),{"id":"c2","kind":"harvested","emails":["x@example.com"]},{"kind":"saved"}],"next_cursor":"abc"}"#)) {263            try await $0.contacts(ContactQuery(q: "jean né", group: uuidB, favoritesOnly: true, kind: .saved, limit: 20, cursor: "c+/="))264        }265        #expect(r.line == "GET /api/next/contacts?q=jean%20n%C3%A9&group=\(uuidB)&favorite=1&kind=saved&limit=20&cursor=c%2B%2F%3D")266        #expect(page.contacts.count == 2 && page.nextCursor == "abc" && page.hasMore)267        let c = page.contacts[0]268        #expect(c.kind == .saved && c.isSaved && c.name == "Jeanne Tremblay" && c.emails == [ContactEmail(email: "jeanne@example.com", label: "travail"), ContactEmail(email: "jt@perso.example")])269        #expect(c.organization == "UQO" && c.title == nil && c.phones == [ContactPhone(number: "+1 819 555 0100", label: "mobile")] && c.favorite && c.vip && c.groups == [uuidB] && c.avatarColor == "#0284c7")270        #expect(c.stats == Contact.Stats(sent: 4, received: 9, lastAt: t0) && c.displayName == "Jeanne Tremblay" && c.address == EmailAddress(name: "Jeanne Tremblay", email: "jeanne@example.com"))271        let s = page.contacts[1]272        #expect(s.kind == .unknown && s.name == "" && s.displayName == "x@example.com" && !s.favorite && s.stats.sent == 0 && s.stats.lastAt == nil)273        let (empty, bare) = try await exchange(.json(#"{"data":[],"next_cursor":null}"#)) { try await $0.contacts() }274        #expect(bare.line == "GET /api/next/contacts" && empty.contacts.isEmpty && !empty.hasMore)275    }276277    @Test func suggest() async throws {278        let (list, r) = try await exchange(.json(#"{"data":[{"name":"Jeanne","email":"jeanne@example.com","contact_id":"\#(uuidA)","kind":"saved","favorite":true,"score":12.5},{"email":"x@example.com"},{"name":"no email"}]}"#)) { try await $0.suggestContacts("jea", limit: 5) }279        #expect(r.line == "GET /api/next/contacts/suggest?q=jea&limit=5" && list.count == 2)280        #expect(list[0] == ContactSuggestion(name: "Jeanne", email: "jeanne@example.com", contactId: uuidA, favorite: true, score: 12.5, kind: .saved) && list[0].address.formatted == "Jeanne <jeanne@example.com>")281        #expect(list[1].name == "" && list[1].contactId == nil && list[1].score == 0 && list[1].id == "x@example.com")282    }283284    @Test func crudAndHistory() async throws {285        let (one, g) = try await exchange(.json(Self.contact)) { try await $0.contact(id: uuidA) }286        #expect(g.line == "GET /api/next/contacts/\(uuidA)" && one.id == uuidA)287        let content = ContactContent(name: "Jeanne", emails: [ContactEmail(email: " Jeanne@Example.com ", label: "travail")], organization: "", phones: [ContactPhone(number: "555")], favorite: true, groups: [uuidB])288        let (_, c) = try await exchange(.json(Self.contact, status: 201)) { try await $0.createContact(content) }289        #expect(c.line == "POST /api/next/contacts")290        #expect(c.json == ["name": "Jeanne", "emails": [["email": "jeanne@example.com", "label": "travail"]], "organization": nil, "phones": [["number": "555"]], "favorite": true, "groups": [.string(uuidB)]])291        // saving a suggestion; `suggested` is never sent (the server only accepts `saved`)292        let (_, u) = try await exchange(.json(Self.contact)) { try await $0.updateContact(id: uuidA, ContactContent(kind: .saved, vip: false)) }293        #expect(u.line == "PATCH /api/next/contacts/\(uuidA)" && u.json == ["kind": "saved", "vip": false])294        #expect(ContactContent(kind: .suggested).json == [:])295        let (_, d) = try await exchange(.ok) { try await $0.deleteContact(id: uuidA) }296        #expect(d.line == "DELETE /api/next/contacts/\(uuidA)")297        #expect((await failure(.error(409, "email_in_use")) { try await $0.createContact(content) } as? APIError)?.code == "email_in_use")298299        let msg = #"{"mailbox_id":"\#(uuidB)","email_id":"M1","thread_id":"T1","from":[{"email":"jeanne@example.com","name":"Jeanne"}],"to":[{"email":"me@stg.spboucher.ai","name":null}],"subject":"Devis","preview":"Bonjour","received_at":"\#(iso0)","keywords":["$seen"],"mailbox_ids":["a"],"has_attachment":false,"size":1200,"folder_roles":["inbox"]}"#300        let rem = #"{"id":"r1","mailbox_id":"\#(uuidB)","email_id":"M1","thread_id":"T1","subject":"Devis","due_at":"\#(iso0)","only_if_no_reply":false,"note":null,"status":"pending"}"#301        let (h, hr) = try await exchange(.json(#"{"data":[\#(msg)],"reminders":[\#(rem)]}"#)) { try await $0.contactHistory(id: uuidA, limit: 5) }302        #expect(hr.line == "GET /api/next/contacts/\(uuidA)/history?limit=5" && h.messages.count == 1 && h.messages[0].subject == "Devis" && h.reminders.count == 1 && h.reminders[0].status == .pending)303        let (none, _) = try await exchange(.json(#"{"data":[],"reminders":[]}"#)) { try await $0.contactHistory(id: uuidA) }304        #expect(none.messages.isEmpty && none.reminders.isEmpty)305    }306307    @Test func groups() async throws {308        let (list, r) = try await exchange(.json(##"{"data":[{"id":"\##(uuidB)","name":"Famille","color":"#a8327a","members":3},{"id":"g2"}]}"##)) { try await $0.contactGroups() }309        #expect(r.line == "GET /api/next/contact-groups" && list.count == 2 && list[0].name == "Famille" && list[0].color == "#a8327a" && list[0].memberCount == 3 && list[1].memberCount == nil)310        let one = ##"{"id":"\##(uuidB)","name":"Famille","color":"#a8327a","members":0}"##311        let (_, c) = try await exchange(.json(one, status: 201)) { try await $0.createContactGroup(name: "Famille", color: "#A8327A") }312        #expect(c.line == "POST /api/next/contact-groups" && c.json == ["name": "Famille", "color": "#a8327a"])313        let (_, u) = try await exchange(.json(one)) { try await $0.updateContactGroup(id: uuidB, name: "Proches") }314        #expect(u.line == "PATCH /api/next/contact-groups/\(uuidB)" && u.json == ["name": "Proches"])315        let (_, d) = try await exchange(.ok) { try await $0.deleteContactGroup(id: uuidB) }316        #expect(d.line == "DELETE /api/next/contact-groups/\(uuidB)")317    }318319    @Test func vCardImportExportDuplicatesMerge() async throws {320        let card = Data("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Jeanne Tremblay\r\nEMAIL:jeanne@example.com\r\nEND:VCARD\r\n".utf8)321        let (res, r) = try await exchange(.json(#"{"total":3,"imported":1,"updated":1,"skipped":1}"#)) { try await $0.importContacts(vCard: card) }322        #expect(r.line == "POST /api/next/contacts/import" && r.header("Content-Type") == "text/vcard; charset=utf-8" && r.body == card)323        #expect(res.total == 3 && res.imported == 1 && res.updated == 1 && res.skipped == 1 && res.errors.isEmpty)324        // the 2 MB limit is refused before any request325        let big = FakeServer(.ok)326        let tooBig = await { do { _ = try await big.api.importContacts(vCard: Data(count: 2 * 1024 * 1024 + 1)); return nil as APIError? } catch { return error as? APIError } }()327        #expect(tooBig?.status == 413 && big.requests.isEmpty)328329        let server = FakeServer(StubReply(headers: ["Content-Type": "text/vcard; charset=utf-8"], body: card))330        let exported = try await server.api.exportContacts(kind: .all, group: uuidB)331        #expect(exported == card && server.last.line == "GET /api/next/contacts/export.vcf?kind=all&group=\(uuidB)" && server.last.header("Accept") == "text/vcard")332        let (_, plain) = try await exchange(StubReply(body: card)) { try await $0.exportContacts() }333        #expect(plain.line == "GET /api/next/contacts/export.vcf")334335        let other = Self.contact.replacingOccurrences(of: uuidA, with: uuidC)336        let (dups, dr) = try await exchange(.json(#"{"data":[{"reason":"email","key":"jeanne@example.com","contacts":[\#(Self.contact),\#(other)]},{"reason":"name","key":"x","contacts":[\#(Self.contact)]}]}"#)) { try await $0.contactDuplicates() }337        #expect(dr.line == "GET /api/next/contacts/duplicates" && dups.count == 1 && dups[0].reason == "email" && dups[0].key == "jeanne@example.com" && dups[0].contacts.map(\.id) == [uuidA, uuidC])338        let (kept, m) = try await exchange(.json(Self.contact)) { try await $0.mergeContacts(keep: uuidA, merge: [uuidC]) }339        #expect(m.line == "POST /api/next/contacts/merge" && m.json == ["keep": .string(uuidA), "merge": [.string(uuidC)]] && kept.id == uuidA)340    }341}342343@Suite struct NextSearchAPITests {344    static let hit = #"{"mailbox_id":"\#(uuidB)","email_id":"M1","thread_id":"T1","from":[{"email":"jeanne@example.com","name":"Jeanne"}],"to":[{"email":"me@stg.spboucher.ai","name":null}],"subject":"Devis","preview":"Bonjour","received_at":"\#(iso0)","keywords":["$flagged","$pinned","lbl_0a1b2c3d","lbl_bad"],"mailbox_ids":["a","b"],"has_attachment":true,"size":1200,"folder_roles":["inbox"]}"#345    static let parsed = #"{"terms":[{"op":"from","value":"jeanne","negated":false,"raw":"from:jeanne","start":0,"end":11,"group":0},{"op":"is","value":"unread","negated":true,"raw":"-is:unread","start":12,"end":22,"group":1},{"op":"before","value":"2026-12-01","negated":false,"raw":"before:2026-12-01","start":23,"end":40,"group":2,"date":"2026-12-02T05:00:00Z"},{"op":"larger","value":"5m","negated":false,"raw":"larger:5m","start":41,"end":50,"group":2,"bytes":5242880},{"op":"near","value":"x","negated":false,"raw":"near:x","start":51,"end":57,"group":3}],"filters":{"operator":"AND","conditions":[]},"errors":[{"token":"is:blue","start":58,"end":65,"code":"invalid_value","message":"Unknown state"}]}"#346347    @Test func searchSendsTheQueryAndDecodesResultsAndParse() async throws {348        let (page, r) = try await exchange(.json(#"{"data":[\#(Self.hit),{"mailbox_id":"m","email_id":"e","keywords":{"$seen":true,"$draft":false}},{"email_id":"orphan"}],"next_cursor":"n1","parsed":\#(Self.parsed)}"#)) {349            try await $0.search(SearchQuery("from:jeanne -is:unread \"à venir\"", scope: .only([uuidA, uuidB]), limit: 25, cursor: "c1", threads: true, tz: "America/Toronto"))350        }351        #expect(r.line == "GET /api/next/search?q=from%3Ajeanne%20-is%3Aunread%20%22%C3%A0%20venir%22&mailboxes=\(uuidA)%2C\(uuidB)&limit=25&cursor=c1&threads=1&tz=America%2FToronto")352        #expect(page.results.count == 2 && page.nextCursor == "n1" && page.hasMore)353        let h = page.results[0]354        #expect(h.id == "\(uuidB):M1" && h.threadId == "T1" && h.from == [EmailAddress(name: "Jeanne", email: "jeanne@example.com")] && h.to.first?.email == "me@stg.spboucher.ai" && h.receivedAt == t0)355        #expect(h.isUnread && h.isFlagged && h.isPinned && !h.isSnoozed && h.labelKeywords == ["lbl_0a1b2c3d"] && h.folderIds == ["a", "b"] && h.hasAttachment && h.size == 1200 && h.folderRoles == ["inbox"] && h.score == nil)356        #expect(h.summary.id == "M1" && h.summary.threadId == "T1" && h.summary.isFlagged && h.summary.hasAttachment && h.summary.preview == "Bonjour")357        let m = page.results[1]358        #expect(!m.isUnread && m.keywords == ["$seen"] && m.threadId == "e" && m.from.isEmpty && m.receivedAt == nil)359360        let p = page.parsed361        #expect(p.terms.count == 5 && !p.isValid && p.errors.first?.code == "invalid_value" && p.errors.first?.start == 58 && p.filters["operator"] == "AND")362        #expect(p.terms[1].negated && p.terms[1].knownOp == .is && p.terms[2].date == Date(timeIntervalSince1970: 1_796_187_600) && p.terms[3].bytes == 5_242_880 && p.terms[4].knownOp == nil)363        #expect(p.chips.map(\.token) == ["from:jeanne", "-is:unread", "before:2026-12-01", "larger:5m", "near:x"])364        #expect(p.chips[2].group == p.chips[3].group)365366        let (all, bare) = try await exchange(.json(#"{"data":[],"next_cursor":null,"parsed":{"terms":[],"filters":null,"errors":[]}}"#)) { try await $0.search(SearchQuery("budget", tz: nil)) }367        #expect(bare.line == "GET /api/next/search?q=budget&mailboxes=all" && all.results.isEmpty && all.parsed.isValid && all.parsed.filters.isNull && !all.hasMore)368    }369370    @Test func parseQueryPostsTheText() async throws {371        let (p, r) = try await exchange(.json(Self.parsed)) { try await $0.parseQuery("from:jeanne -is:unread", tz: "Europe/Paris") }372        #expect(r.line == "POST /api/next/search/parse" && r.json == ["q": "from:jeanne -is:unread", "tz": "Europe/Paris"] && p.terms.count == 5 && p.errors.count == 1)373        let (empty, bare) = try await exchange(.json("{}")) { try await $0.parseQuery("", tz: nil) }374        #expect(empty.terms.isEmpty && empty.isValid && bare.json == ["q": ""])375    }376377    /// `before:` / `after:` / `today` are evaluated in the user's zone: every search, parse and gallery request carries the device's IANA378    /// identifier unless the caller chose another one (or none).379    @Test func searchRequestsCarryTheDeviceTimeZoneByDefault() async throws {380        let device = TimeZone.current.identifier381        let encoded = device.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(CharacterSet(charactersIn: "-._~"))) ?? device382        #expect(SearchQuery("after:today").tz == device && AttachmentQuery().tz == device)383        let (_, s) = try await exchange(.json(#"{"data":[],"next_cursor":null,"parsed":{"terms":[],"filters":null,"errors":[]}}"#)) { try await $0.search(SearchQuery("after:today")) }384        #expect(s.line == "GET /api/next/search?q=after%3Atoday&mailboxes=all&tz=\(encoded)")385        let (_, p) = try await exchange(.json("{}")) { try await $0.parseQuery("before:yesterday") }386        #expect(p.json == ["q": "before:yesterday", "tz": .string(device)])387        let (_, a) = try await exchange(.json(#"{"data":[],"next_cursor":null}"#)) { try await $0.attachments() }388        #expect(a.line == "GET /api/next/attachments?mailboxes=all&tz=\(encoded)")389        // an explicit zone wins; an empty one is not sent390        let (_, t) = try await exchange(.json(#"{"data":[],"next_cursor":null}"#)) { try await $0.attachments(AttachmentQuery(tz: "Asia/Tokyo")) }391        #expect(t.line == "GET /api/next/attachments?mailboxes=all&tz=Asia%2FTokyo")392        let (_, none) = try await exchange(.json(#"{"data":[],"next_cursor":null}"#)) { try await $0.attachments(AttachmentQuery(tz: "")) }393        #expect(none.line == "GET /api/next/attachments?mailboxes=all")394    }395396    static let attachment = #"{"mailbox_id":"\#(uuidB)","email_id":"M1","thread_id":"T1","blob_id":"Bx1","part_id":"2","name":"devis été.pdf","type":"application/pdf","size":48213,"kind":"pdf","from":[{"email":"jeanne@example.com","name":"Jeanne"}],"subject":"Devis","received_at":"\#(iso0)","download_url":"/api/jmap/\#(uuidB)/download/acct/Bx1/devis%20%C3%A9t%C3%A9.pdf?accept=application%2Fpdf","inline_ok":true}"#397398    @Test func attachmentsGallery() async throws {399        let q = AttachmentQuery(scope: .only([uuidB]), kind: .pdf, minSize: 1000, maxSize: 5_000_000, q: "devis", from: "jeanne", after: t0, before: t0, limit: 30, cursor: "c", tz: "America/Toronto")400        let (page, r) = try await exchange(.json(#"{"data":[\#(Self.attachment),{"mailbox_id":"m","email_id":"e","blob_id":"b","kind":"hologram"},{"mailbox_id":"m"}],"next_cursor":"n"}"#)) { try await $0.attachments(q) }401        #expect(r.line == "GET /api/next/attachments?mailboxes=\(uuidB)&kind=pdf&min_size=1000&max_size=5000000&q=devis&from=jeanne&after=2026-12-01T13%3A00%3A00Z&before=2026-12-01T13%3A00%3A00Z&limit=30&cursor=c&tz=America%2FToronto")402        #expect(page.items.count == 2 && page.nextCursor == "n")403        let a = page.items[0]404        #expect(a.id == "\(uuidB):M1:2" && a.blobId == "Bx1" && a.name == "devis été.pdf" && a.type == "application/pdf" && a.size == 48213 && a.kind == .pdf && a.from?.email == "jeanne@example.com" && a.receivedAt == t0 && a.inlineOK && !a.isDangerous)405        #expect(page.items[1].kind == .unknown && page.items[1].downloadURL == nil && page.items[1].type == "application/octet-stream" && page.items[1].id == "m:e:b")406        let (_, bare) = try await exchange(.json(#"{"data":[],"next_cursor":null}"#)) { try await $0.attachments(AttachmentQuery(tz: nil)) }407        #expect(bare.line == "GET /api/next/attachments?mailboxes=all")408    }409410    @Test func zipIsStreamedToAFileAndLeavesNothingBehindOnFailure() async throws {411        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-zip-\(UUID().uuidString)")412        defer { try? FileManager.default.removeItem(at: dir) }413        let dest = dir.appendingPathComponent("pieces.zip")414        var bytes = Data([0x50, 0x4b, 0x03, 0x04])415        bytes.append(Data((0..<200_000).map { UInt8(truncatingIfNeeded: $0 &* 31) }))416        let item = AttachmentItem(json: (try JSONValue.parse(Data(Self.attachment.utf8))))!417        let server = FakeServer(StubReply(headers: ["Content-Type": "application/zip"], body: bytes))418        final class Seen: @unchecked Sendable { let lock = NSLock(); var v: [Int64] = []; func add(_ n: Int64) { lock.withLock { v.append(n) } } }419        let seen = Seen()420        let n = try await server.api.downloadAttachmentsZip([AttachmentZipItem(item), AttachmentZipItem(mailboxId: uuidA, emailId: "M2", blobId: "By", name: "b.png")], to: dest) { seen.add($0) }421        let written = try Data(contentsOf: dest)422        #expect(n == Int64(bytes.count) && written == bytes)423        #expect(server.last.line == "POST /api/next/attachments/zip" && server.last.header("Accept") == "application/zip")424        #expect(server.last.json == ["items": [["mailbox_id": .string(uuidB), "email_id": "M1", "blob_id": "Bx1", "name": "devis été.pdf"], ["mailbox_id": .string(uuidA), "email_id": "M2", "blob_id": "By", "name": "b.png"]]])425        #expect(seen.v.last == Int64(bytes.count) && seen.v == seen.v.sorted() && seen.v.count >= 3)426        let listing = try FileManager.default.contentsOfDirectory(atPath: dir.path)427        #expect(listing == ["pieces.zip"])428429        // a refusal carries its typed meaning and writes nothing; an existing file is untouched430        let refused = FakeServer(.error(404, "not_found", message: "An item is not an attachment of that message"), .error(413, "too_large"), .offline)431        await #expect(throws: NextError.notFound) { try await refused.api.downloadAttachmentsZip([AttachmentZipItem(item)], to: dest) }432        let tooLarge = await { do { _ = try await refused.api.downloadAttachmentsZip([AttachmentZipItem(item)], to: dest); return nil as APIError? } catch { return error as? APIError } }()433        #expect(tooLarge?.status == 413 && tooLarge?.code == "too_large")434        let off = await { do { _ = try await refused.api.downloadAttachmentsZip([AttachmentZipItem(item)], to: dest); return nil as APIError? } catch { return error as? APIError } }()435        #expect(off?.isOffline == true)436        let after = try Data(contentsOf: dest), listingAfter = try FileManager.default.contentsOfDirectory(atPath: dir.path)437        #expect(after == bytes && listingAfter == ["pieces.zip"])438        // limits are checked before any request439        let none = FakeServer()440        await #expect(throws: APIError.self) { try await none.api.downloadAttachmentsZip([], to: dest) }441        await #expect(throws: APIError.self) { try await none.api.downloadAttachmentsZip(Array(repeating: AttachmentZipItem(item), count: 51), to: dest) }442        #expect(none.requests.isEmpty)443    }444445    @Test func singleAttachmentDownloadFollowsOnlyTheSPMailOrigin() async throws {446        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-att-\(UUID().uuidString)")447        defer { try? FileManager.default.removeItem(at: dir) }448        let item = AttachmentItem(json: (try JSONValue.parse(Data(Self.attachment.utf8))))!449        let server = FakeServer(StubReply(headers: ["Content-Type": "application/pdf"], body: Data("%PDF-1.7".utf8)))450        let n = try await server.api.downloadAttachment(item, to: dir.appendingPathComponent("d.pdf"))451        #expect(n == 8 && server.last.line == "GET /api/jmap/\(uuidB)/download/acct/Bx1/devis%20%C3%A9t%C3%A9.pdf?accept=application%2Fpdf" && server.last.header("Authorization") == "Bearer test-token")452        var foreign = item453        foreign.downloadURL = "https://evil.example/steal"454        await #expect(throws: APIError.self) { try await server.api.downloadAttachment(foreign, to: dir.appendingPathComponent("x")) }455        foreign.downloadURL = nil456        await #expect(throws: NextError.self) { try await server.api.downloadAttachment(foreign, to: dir.appendingPathComponent("x")) }457        #expect(server.requests.count == 1)458    }459}460461@Suite struct NextSendAPITests {462    static let outbound = #"{"id":"msg_out_AbCdEfGhIjKl","status":"scheduled","from":"apple-a@stg.spboucher.ai","message_id":null,"recipients":[{"address":"apple-b@stg.spboucher.ai","status":"pending","smtp_reply":null}],"external":false,"send_at":"\#(iso0)","attempts":0,"last_error":null,"submitted_at":null,"final_at":null,"created_at":"\#(iso0)","updated_at":"\#(iso0)","undo_until":"\#(iso0)","thread_id":"thr_abc"}"#463464    @Test func composePrefs() async throws {465        let (p, r) = try await exchange(.json(#"{"undo_seconds":20,"sensitive":["boss@example.com","@secret.example"],"warn_missing_attachment":false,"warn_external":true}"#)) { try await $0.composePrefs() }466        #expect(r.line == "GET /api/next/compose/prefs" && p == ComposePrefs(undoSeconds: 20, sensitive: ["boss@example.com", "@secret.example"], warnMissingAttachment: false, warnExternal: true))467        #expect(p.sensitiveRecipients(among: ["Boss@Example.com", "ok@example.com", "x@SECRET.example"]) == ["Boss@Example.com", "x@SECRET.example"])468        let (d, _) = try await exchange(.json("{}")) { try await $0.composePrefs() }469        #expect(d == ComposePrefs() && d.undoSeconds == 10 && d.warnMissingAttachment && !d.warnExternal)470        let (_, put) = try await exchange(.json("{}")) { try await $0.setComposePrefs(ComposePrefs(undoSeconds: 500, sensitive: [" Boss@Example.com "], warnMissingAttachment: true, warnExternal: false)) }471        #expect(put.line == "PUT /api/next/compose/prefs" && put.json == ["undo_seconds": 120, "sensitive": ["boss@example.com"], "warn_missing_attachment": true, "warn_external": false])472    }473474    @Test func sendWithNextOptionsGoesThroughTheExistingV1Path() async throws {475        let msg = SendRequest(from: "apple-a@stg.spboucher.ai", to: [EmailAddress(name: "B", email: "apple-b@stg.spboucher.ai")], cc: [EmailAddress(email: "c@stg.spboucher.ai")], subject: "Essai", text: "Bonjour", html: "<p>Bonjour</p>",476                              attachments: [SendAttachment(fileId: "file_abcdefghij", filename: "a.pdf"), SendAttachment(fileId: "file_klmnopqrst", inline: true, cid: "logo")], replyToMessageId: "msg_x")477        let (out, r) = try await exchange(.json(Self.outbound, status: 202)) { try await $0.send(msg, options: SendOptions(undoSeconds: 300, remindAt: t0, remindIfNoReply: true, confirmSensitive: true), idempotencyKey: "key-1") }478        #expect(r.line == "POST /api/v1/messages/send" && r.header("Idempotency-Key") == "key-1")479        #expect(r.json == ["from": "apple-a@stg.spboucher.ai", "to": [["email": "apple-b@stg.spboucher.ai", "name": "B"]], "cc": [["email": "c@stg.spboucher.ai"]], "subject": "Essai", "text": "Bonjour", "html": "<p>Bonjour</p>",480                           "attachments": [["file_id": "file_abcdefghij", "filename": "a.pdf"], ["file_id": "file_klmnopqrst", "inline": true, "cid": "logo"]], "reply_to_message_id": "msg_x",481                           "undo_seconds": 120, "remind_at": .string(iso0), "remind_if_no_reply": true, "confirm_sensitive": true])482        #expect(out.id == "msg_out_AbCdEfGhIjKl" && out.outbound.isScheduled && out.undoUntil == t0 && out.canUndo && out.threadId == "thr_abc" && out.outbound.recipients.first?.address == "apple-b@stg.spboucher.ai")483        #expect(out.undoRemaining(now: t0.addingTimeInterval(-4)) == 4 && out.undoRemaining(now: t0.addingTimeInterval(9)) == 0)484485        // with no option the body is exactly a 0.3.0 send486        let plain = SendRequest(from: "a@stg.spboucher.ai", to: [EmailAddress(email: "b@stg.spboucher.ai")], subject: "S", text: "T")487        let (sent, bare) = try await exchange(.json(#"{"id":"msg_out_x","status":"sent","from":"a@stg.spboucher.ai","recipients":[]}"#)) { try await $0.send(plain, idempotencyKey: "k2") }488        #expect(bare.json == ["from": "a@stg.spboucher.ai", "to": [["email": "b@stg.spboucher.ai"]], "subject": "S", "text": "T"] && !sent.canUndo && sent.undoUntil == nil)489        // remind_if_no_reply is only sent with remind_at490        #expect(SendOptions(remindIfNoReply: true).apply(to: [:]) == [:])491        #expect(SendOptions(undoSeconds: -5).apply(to: [:]) == ["undo_seconds": 0])492    }493494    @Test func sendRequestFromTheComposerMessage() {495        var m = OutgoingMessage(from: EmailAddress(name: "A", email: "a@stg.spboucher.ai"), to: [EmailAddress(email: "b@stg.spboucher.ai")], subject: "Re: x", text: "Oui", inReplyTo: ["<1@x>"], references: ["<0@x>", "<1@x>"])496        m.quotedText = "> avant"497        let direct = SendRequest(m)498        #expect(direct.from == "a@stg.spboucher.ai" && direct.text == "Oui\n\n> avant" && direct.inReplyTo == "<1@x>" && direct.references == ["<0@x>", "<1@x>"] && direct.recipients == ["b@stg.spboucher.ai"])499        // with the id of the message answered, threading is left to the server500        let viaId = SendRequest(m, replyToMessageId: "msg_x")501        #expect(viaId.json["reply_to_message_id"] == "msg_x" && viaId.json["in_reply_to"].isNull && viaId.json["references"].isNull)502    }503504    @Test func templateSendKeepsItsBodyAndGainsTheOptions() async throws {505        let send = TemplateSend(from: "a@stg.spboucher.ai", to: [EmailAddress(email: "b@stg.spboucher.ai")], templateId: uuidA, variables: ["prenom": "SP"])506        let (out, r) = try await exchange(.json(Self.outbound, status: 202)) { try await $0.sendTemplate(send, options: SendOptions(undoSeconds: 10), idempotencyKey: "k") }507        #expect(r.line == "POST /api/v1/messages/send" && r.json == ["from": "a@stg.spboucher.ai", "to": [["email": "b@stg.spboucher.ai"]], "template_id": .string(uuidA), "variables": ["prenom": "SP"], "undo_seconds": 10] && out.canUndo)508    }509510    @Test func uploadFileSendsRawBytes() async throws {511        let (id, r) = try await exchange(.json(#"{"id":"file_abcdefghij","name":"a b.pdf","size":3}"#, status: 201)) { try await $0.uploadFile(Data([1, 2, 3]), name: "a b.pdf", type: "application/pdf", address: "apple-a@stg.spboucher.ai") }512        #expect(id == "file_abcdefghij" && r.line == "POST /api/v1/files?filename=a%20b.pdf&address=apple-a%40stg.spboucher.ai" && r.header("Content-Type") == "application/pdf" && r.body == Data([1, 2, 3]))513    }514515    static let held = #"{"id":"msg_out_AbCdEfGhIjKl","status":"scheduled","mailbox_id":"\#(uuidB)","email_id":"M9","thread_id":"T9","from":{"email":"apple-a@stg.spboucher.ai","name":"Apple A"},"to":[{"email":"apple-b@stg.spboucher.ai","name":null}],"cc":[],"bcc":[{"email":"c@stg.spboucher.ai","name":"C"}],"reply_to":[],"subject":"Essai","html":"<p>Bonjour</p>","text":"Bonjour","attachments":[{"blob_id":"Bz","name":null,"type":"image/png","size":10,"cid":"logo","inline":true}],"in_reply_to":["<1@x>"],"references":["<0@x>","<1@x>"],"send_at":"\#(iso0)","undo_until":"\#(iso0)"}"#516517    @Test func heldMessageAndUndoKeepingTheDraft() async throws {518        let (h, r) = try await exchange(.json(Self.held)) { try await $0.heldMessage(id: "msg_out_AbCdEfGhIjKl") }519        #expect(r.line == "GET /api/next/compose/undo/msg_out_AbCdEfGhIjKl")520        #expect(h.id == "msg_out_AbCdEfGhIjKl" && h.from == "apple-a@stg.spboucher.ai" && h.to.map(\.email) == ["apple-b@stg.spboucher.ai"] && h.bcc == [EmailAddress(name: "C", email: "c@stg.spboucher.ai")] && h.subject == "Essai" && h.text == "Bonjour" && h.html == "<p>Bonjour</p>")521        #expect(h.mailboxId == uuidB && h.emailId == "M9" && h.threadId == "T9" && h.undoUntil == t0 && h.inReplyTo == ["<1@x>"] && h.references.count == 2 && h.remaining(now: t0.addingTimeInterval(-3)) == 3)522        #expect(h.attachments == [HeldMessage.HeldAttachment(blobId: "Bz", name: "", type: "image/png", size: 10, cid: "logo", inline: true)])523        let (minimal, _) = try await exchange(.json(#"{"text":null}"#)) { try await $0.heldMessage(id: "msg_out_zzzzzzzzzz") }524        #expect(minimal.id == "msg_out_zzzzzzzzzz" && minimal.from == "" && minimal.to.isEmpty && minimal.text == "" && minimal.html == nil && minimal.remaining(now: t0) == 0)525526        // undo = ONE call to the keep-draft route (never the scheduled-cancel call, which destroys the draft and its attachments)527        let server = FakeServer(.json(Self.held))528        let undone = try await server.api.undoSend(id: "msg_out_AbCdEfGhIjKl")529        #expect(undone.subject == "Essai" && undone.emailId == "M9" && server.lines == ["POST /api/next/compose/undo/msg_out_AbCdEfGhIjKl"])530        // already gone: the server's refusal surfaces, nothing else is tried531        let late = FakeServer(.error(409, "not_cancellable", message: "This message can no longer be cancelled"))532        let e = await { do { _ = try await late.api.undoSend(id: "msg_out_AbCdEfGhIjKl"); return nil as APIError? } catch { return error as? APIError } }()533        #expect(e?.code == "not_cancellable" && late.requests.count == 1)534        // unknown id, or another user's message535        let unknown = FakeServer(.error(404, "not_found"))536        let e2 = await { do { _ = try await unknown.api.undoSend(id: "msg_out_AbCdEfGhIjKl"); return nil as NextError? } catch { return error as? NextError } }()537        #expect(e2 == .notFound && unknown.lines == ["POST /api/next/compose/undo/msg_out_AbCdEfGhIjKl"])538    }539}540541@Suite struct NextDashboardAndAIAPITests {542    @Test func dashboardDecodesFullAndEmpty() async throws {543        let body = #"""544        {"inbox":[{"mailbox_id":"\#(uuidA)","address":"a@stg.spboucher.ai","unread":3,"total":40},{"mailbox_id":"\#(uuidB)","address":"b@stg.spboucher.ai","unread":2,"total":7}],545         "attention":{"reminders_due":1,"flagged":4,"snoozed_today":2,"unanswered":5},546         "scheduled":[\#(NextSendAPITests.outbound)],"pending_replies":[\#(NextSearchAPITests.hit)],"recent_attachments":[\#(NextSearchAPITests.attachment)],"top_contacts":[\#(NextContactsAPITests.contact)],547         "storage":[{"mailbox_id":"\#(uuidA)","used_bytes":1048576,"quota_bytes":10485760},{"mailbox_id":"\#(uuidB)","used_bytes":null,"quota_bytes":null}],548         "delivery_issues":[{"id":"msg_out_f","status":"bounced","from":"a@stg.spboucher.ai","recipients":[{"address":"x@example.com","status":"bounced","smtp_reply":"550 no"}],"last_error":"550"}],549         "sync":{"watcher_lag_ms":1200,"mail_server":"reachable","push":"disabled"},"generated_at":"\#(iso0)","widgets_v2":{}}550        """#551        let (d, r) = try await exchange(.json(body)) { try await $0.dashboard() }552        #expect(r.line == "GET /api/next/dashboard")553        #expect(d.inbox.count == 2 && d.totalUnread == 5 && d.inbox[0].address == "a@stg.spboucher.ai" && d.attention == Dashboard.Attention(remindersDue: 1, flagged: 4, snoozedToday: 2, unanswered: 5))554        #expect(d.scheduled.first?.isScheduled == true && d.pendingReplies.first?.emailId == "M1" && d.recentAttachments.first?.kind == .pdf && d.topContacts.first?.name == "Jeanne Tremblay")555        #expect(d.storage[0].fraction == 0.1 && d.storage[1].usedBytes == 0 && d.storage[1].fraction == nil && d.deliveryIssues.first?.status == "bounced")556        #expect(d.sync == Dashboard.Sync(watcherLagMs: 1200, mailServer: "reachable", push: "disabled") && d.sync.isHealthy && d.generatedAt == t0)557        let (e, fresh) = try await exchange(.json("{}")) { try await $0.dashboard(fresh: true) }558        #expect(fresh.line == "GET /api/next/dashboard?fresh=1" && e.inbox.isEmpty && e.totalUnread == 0 && e.attention.flagged == 0 && e.sync.mailServer == "unknown" && !e.sync.isHealthy && e.generatedAt == nil)559    }560561    @Test func inboxInsights() async throws {562        let body = #"{"mailbox_id":"\#(uuidB)","ai":false,"newsletters":[\#(NextSearchAPITests.hit)],"needs_reply":[],"unanswered_sent":[\#(NextSearchAPITests.hit)],"generated_at":"\#(iso0)"}"#563        let (i, r) = try await exchange(.json(body)) { try await $0.inboxInsights(mailboxId: uuidB, replyAfterHours: 12, sentAfterDays: 2.5, limit: 50) }564        #expect(r.line == "GET /api/next/inbox/insights?mailbox_id=\(uuidB)&reply_after_hours=12&sent_after_days=2.5&limit=50")565        #expect(i.mailboxId == uuidB && !i.ai && i.newsletters.count == 1 && i.needsReply.isEmpty && i.unansweredSent.count == 1 && !i.isEmpty && i.generatedAt == t0)566        let (e, bare) = try await exchange(.json("{}")) { try await $0.inboxInsights(mailboxId: uuidB) }567        #expect(bare.line == "GET /api/next/inbox/insights?mailbox_id=\(uuidB)" && e.isEmpty)568    }569570    @Test func aiSettings() async throws {571        let body = #"{"provider":"local","consent_external_at":null,"features":{"summary":true,"reply":false,"vision":true},"language":"fr","available":{"local":true,"anthropic":false,"semantic":true},"updated_at":"x"}"#572        let (s, r) = try await exchange(.json(body)) { try await $0.aiSettings() }573        #expect(r.line == "GET /api/next/ai/settings" && s.provider == .local && s.language == .fr && s.localAvailable && !s.anthropicAvailable && s.semanticAvailable && !s.hasExternalConsent && !s.isExternal)574        #expect(s.isEnabled(.summary) && !s.isEnabled(.reply) && !s.isEnabled(.triage) && s.features["vision"] == true)575        let (off, _) = try await exchange(.json("{}")) { try await $0.aiSettings() }576        #expect(off.provider == .off && off.language == .auto && !off.isEnabled(.summary) && off.features.isEmpty)577        let (future, _) = try await exchange(.json(#"{"provider":"mistral","features":{"summary":true}}"#)) { try await $0.aiSettings() }578        #expect(future.provider == .unknown && !future.isEnabled(.summary))579580        let (saved, put) = try await exchange(.json(#"{"provider":"anthropic","consent_external_at":"\#(iso0)","features":{"summary":true},"language":"auto","available":{"local":true,"anthropic":true}}"#)) {581            try await $0.setAISettings(AISettingsUpdate(provider: .anthropic, features: ["summary": true], language: .auto, consentExternal: true))582        }583        #expect(put.line == "PUT /api/next/ai/settings" && put.json == ["provider": "anthropic", "features": ["summary": true], "language": "auto", "consent_external": true])584        #expect(saved.isExternal && saved.consentExternalAt == t0 && saved.hasExternalConsent)585        let (_, one) = try await exchange(.json("{}")) { try await $0.setAISettings(AISettingsUpdate(feature: .triage, enabled: false)) }586        #expect(one.json == ["features": ["triage": false]])587        #expect((await failure(.error(409, "provider_unavailable")) { try await $0.setAISettings(AISettingsUpdate(provider: .local)) } as? APIError)?.code == "provider_unavailable")588    }589590    @Test func summarizeRepliesWriteTriage() async throws {591        let sum = #"{"summary":"Jeanne demande un devis.","decisions":["Envoyer vendredi"],"action_items":[{"text":"Préparer le devis","owner":"SP","due":"2026-12-04"},{"text":"Relancer"}],"deadlines":[{"text":"Remise","date":"2026-12-05"}],"timeline":[{"at":"\#(iso0)","who":"Jeanne","what":"Demande"}],"provider":"local","model":"qwen3","language":"fr","cached":true,"confidence":0.9}"#592        let (s, r) = try await exchange(.json(sum)) { try await $0.summarize(mailboxId: uuidB, threadId: "T1", language: "fr") }593        #expect(r.line == "POST /api/next/ai/summarize" && r.json == ["mailbox_id": .string(uuidB), "thread_id": "T1", "language": "fr"])594        #expect(s.summary == "Jeanne demande un devis." && s.decisions == ["Envoyer vendredi"] && s.actionItems.count == 2 && s.actionItems[0].owner == "SP" && s.actionItems[1].due == nil && s.deadlines[0].date == "2026-12-05")595        #expect(s.timeline[0].date == t0 && s.timeline[0].who == "Jeanne" && s.provider == "local" && s.model == "qwen3" && s.cached && s.language == "fr")596        let (min, bare) = try await exchange(.json(#"{"summary":"x"}"#)) { try await $0.summarize(mailboxId: uuidB, threadId: "T1") }597        #expect(bare.json == ["mailbox_id": .string(uuidB), "thread_id": "T1"] && min.decisions.isEmpty && min.provider == "" && !min.cached)598        #expect(await failure(.error(409, "ai_disabled")) { try await $0.summarize(mailboxId: uuidB, threadId: "T1") } as? NextError == .aiDisabled)599        #expect(await failure(.error(412, "consent_required")) { try await $0.summarize(mailboxId: uuidB, threadId: "T1") } as? NextError == .consentRequired)600601        let (rep, rr) = try await exchange(.json(#"{"suggestions":[{"subject":"Re: Devis","text":"Bonjour, oui."},{"text":"Merci."},{"text":""}],"provider":"anthropic","model":"claude","language":"fr"}"#)) {602            try await $0.suggestReplies(mailboxId: uuidB, emailId: "M1", tone: .concise, language: "fr")603        }604        #expect(rr.line == "POST /api/next/ai/replies" && rr.json == ["mailbox_id": .string(uuidB), "email_id": "M1", "tone": "concise", "language": "fr"])605        #expect(rep.suggestions.count == 2 && rep.suggestions[0].subject == "Re: Devis" && rep.suggestions[1].subject == nil && rep.provider == "anthropic" && rep.model == "claude")606        let (_, dflt) = try await exchange(.json("{}")) { try await $0.suggestReplies(mailboxId: uuidB, emailId: "M1") }607        #expect(dflt.json == ["mailbox_id": .string(uuidB), "email_id": "M1", "tone": "professional"])608609        let (w, wr) = try await exchange(.json(#"{"text":"Mieux.","provider":"local","model":"m"}"#)) { try await $0.write(AIWriteRequest(action: .translate, text: "Better.", tone: "formal", targetLanguage: "fr", context: "ctx")) }610        #expect(wr.line == "POST /api/next/ai/write" && wr.json == ["action": "translate", "text": "Better.", "tone": "formal", "target_language": "fr", "context": "ctx"] && w.text == "Mieux." && w.subjects.isEmpty)611        let (subj, sr) = try await exchange(.json(#"{"subjects":["A","B"],"provider":"local","model":"m"}"#)) { try await $0.write(AIWriteRequest(action: .subject, text: "corps")) }612        #expect(sr.json == ["action": "subject", "text": "corps"] && subj.text == nil && subj.subjects == ["A", "B"])613614        let (tri, tr) = try await exchange(.json(#"{"data":[{"email_id":"M1","category":"work","needs_action":true,"important":false,"reason":"question directe"},{"email_id":"M2","category":"quantum"},{"category":"work"}],"provider":"local","model":"m"}"#)) {615            try await $0.triage(mailboxId: uuidB, emailIds: ["M1", "M2"])616        }617        #expect(tr.line == "POST /api/next/ai/triage" && tr.json == ["mailbox_id": .string(uuidB), "email_ids": ["M1", "M2"]])618        #expect(tri.count == 2 && tri[0].category == .work && tri[0].needsAction && !tri[0].important && tri[0].reason == "question directe" && tri[1].category == .unknown && !tri[1].needsAction)619    }620621    @Test func semanticSearchIndexAndUsage() async throws {622        let scored = NextSearchAPITests.hit.dropLast() + #","score":0.83}"#623        let (page, r) = try await exchange(.json(#"{"data":[\#(scored)],"next_cursor":null,"parsed":{"terms":[],"filters":null,"errors":[]},"provider":"local","model":"e5"}"#)) { try await $0.semanticSearch("devis de toiture", scope: .only([uuidB]), limit: 10) }624        #expect(r.line == "POST /api/next/ai/search" && r.json == ["q": "devis de toiture", "mailboxes": [.string(uuidB)], "limit": 10] && page.results.first?.score == 0.83 && page.model == "e5")625        let (_, all) = try await exchange(.json(#"{"data":[]}"#)) { try await $0.semanticSearch("x") }626        #expect(all.json == ["q": "x"])627628        let status = #"{"enabled":true,"available":true,"model":"e5-small","dim":384,"mailboxes":[{"mailbox_id":"\#(uuidB)","indexed":90,"queued":10,"total":200}],"indexed":90,"queued":10,"total":200,"last_indexed_at":"\#(iso0)"}"#629        let (s, sr) = try await exchange(.json(status)) { try await $0.semanticIndexStatus() }630        #expect(sr.line == "GET /api/next/ai/index/status" && s.enabled && s.available && s.indexed == 90 && s.pending == 10 && s.total == 200 && s.coverage == 0.45 && s.model == "e5-small" && s.running && s.lastIndexedAt == t0)631        #expect(s.mailboxes == [SemanticIndexStatus.Box(mailboxId: uuidB, indexed: 90, queued: 10, total: 200)] && s.raw["dim"] == 384)632        let (e, _) = try await exchange(.json("{}")) { try await $0.semanticIndexStatus() }633        #expect(!e.enabled && e.indexed == 0 && e.total == nil && e.coverage == nil && !e.running && e.mailboxes.isEmpty)634635        let (n, rb) = try await exchange(.json(#"{"queued":120}"#)) { try await $0.rebuildSemanticIndex(scope: .only([uuidB]), limit: 500, reset: true) }636        #expect(rb.line == "POST /api/next/ai/index/rebuild" && rb.json == ["mailboxes": [.string(uuidB)], "limit": 500, "reset": true] && n == 120)637        let (_, rb2) = try await exchange(.json("{}")) { try await $0.rebuildSemanticIndex() }638        #expect(rb2.json == [:])639640        let (u, ur) = try await exchange(.json(#"{"data":[{"day":"2026-12-01","feature":"summary","provider":"local","model":"m","status":"ok","requests":3,"input_tokens":1200,"output_tokens":300}],"limits":{"per_minute":20,"per_day":500,"used_24h":3}}"#)) { try await $0.aiUsage(days: 7) }641        #expect(ur.line == "GET /api/next/ai/usage?days=7" && u.rows.count == 1 && u.rows[0].requests == 3 && u.rows[0].inputTokens == 1200 && u.perMinute == 20 && u.perDay == 500 && u.used24h == 3)642    }643}644645@Suite struct NextRulesAPITests {646    static let rule = #"""647    {"id":"\#(uuidA)","name":"Factures","enabled":true,"position":2,"mailbox_ids":["\#(uuidB)"],"match":"any",648     "conditions":[{"field":"from","op":"matches_domain","value":"hydro.qc.ca"},{"field":"subject","op":"contains","value":"facture"},{"field":"has_attachment","op":"is","value":true},{"field":"is_newsletter","op":"is","value":false},649                   {"field":"ai_category","op":"is","value":"transaction"},{"field":"size","op":"gt","value":100000},{"field":"header","op":"regex","value":"^X-"},{"field":"size","op":"contains","value":"big"}],650     "actions":[{"type":"label","label_id":"\#(uuidC)"},{"type":"star"},{"type":"mark_read"},{"type":"pin"},{"type":"snooze","until_rule":"tomorrow"},{"type":"remind","after_hours":48},{"type":"event","name":"invoice.received"},651                {"type":"notify_app","app":"sp-wallet"},{"type":"draft_reply","snippet_id":"\#(uuidB)"},{"type":"draft_reply","ai_tone":"concise"},{"type":"extract","schema":{"fields":[{"name":"total","type":"number"}]}},652                {"type":"teleport","to":"mars"},{"type":"label"}],653     "stop":true,"created_at":"\#(iso0)","updated_at":"\#(iso0)"}654    """#655656    @Test func ruleDecodesKnownPartsAndKeepsUnknownOnesVerbatim() throws {657        let json = try JSONValue.parse(Data(Self.rule.utf8))658        let r = try #require(MailRule(json: json))659        #expect(r.id == uuidA && r.name == "Factures" && r.enabled && r.position == 2 && r.scope == .only([uuidB]) && r.match == .any && r.stop && r.updatedAt == t0)660        #expect(r.conditions[0] == .text(field: .from, op: .matchesDomain, value: "hydro.qc.ca") && r.conditions[1] == .text(field: .subject, op: .contains, value: "facture"))661        #expect(r.conditions[2] == .hasAttachment(true) && r.conditions[3] == .isNewsletter(false) && r.conditions[4] == .aiCategory("transaction") && r.conditions[5] == .sizeGreaterThan(100_000))662        #expect(r.conditions[6] == .unknown(["field": "header", "op": "regex", "value": "^X-"]) && r.conditions[7].isUnknown)663        #expect(r.actions[0] == .label(labelId: uuidC) && r.actions[1] == .star && r.actions[2] == .markRead && r.actions[3] == .pin && r.actions[4] == .snooze(untilRule: "tomorrow") && r.actions[5] == .remind(afterHours: 48))664        #expect(r.actions[6] == .event(name: "invoice.received") && r.actions[7] == .notifyApp(app: "sp-wallet") && r.actions[8] == .draftReply(snippetId: uuidB, aiTone: nil) && r.actions[9] == .draftReply(snippetId: nil, aiTone: "concise"))665        #expect(r.actions[10] == .extract(schema: ["fields": [["name": "total", "type": "number"]]]) && r.actions[11] == .unknown(["type": "teleport", "to": "mars"]) && r.actions[12].isUnknown)666        #expect(r.actions.map(\.type) == ["label", "star", "mark_read", "pin", "snooze", "remind", "event", "notify_app", "draft_reply", "draft_reply", "extract", "teleport", "label"])667        #expect(r.hasUnknownParts && r.needsAI)668        // what is written back equals what was read: nothing a newer client configured is lost669        #expect(r.json["conditions"] == json["conditions"] && r.json["actions"] == json["actions"] && r.json["mailbox_ids"] == json["mailbox_ids"] && r.json["match"] == "any" && r.json["id"].isNull)670        let minimal = try #require(MailRule(json: ["id": "r"]))671        #expect(minimal.enabled && minimal.match == .all && minimal.scope == .all && minimal.conditions.isEmpty && minimal.actions.isEmpty && !minimal.stop && !minimal.hasUnknownParts && !minimal.needsAI)672        let future = try #require(MailRule(json: ["id": "r", "match": "weighted"]))673        #expect(future.match == .unknown && future.hasUnknownParts && future.json["match"].isNull)674        #expect(MailRule(json: ["name": "no id"]) == nil)675    }676677    @Test func crudRunsAndTest() async throws {678        let (list, r) = try await exchange(.json(#"{"data":[\#(Self.rule)]}"#)) { try await $0.rules() }679        #expect(r.line == "GET /api/next/rules" && list.count == 1 && list[0].actions.count == 13)680        let new = MailRule(name: "VIP", conditions: [.text(field: .from, op: .equals, value: "boss@example.com")], actions: [.star, .label(labelId: uuidC)])681        let (_, c) = try await exchange(.json(Self.rule, status: 201)) { try await $0.createRule(new) }682        #expect(c.line == "POST /api/next/rules")683        #expect(c.json == ["name": "VIP", "enabled": true, "position": 0, "mailbox_ids": nil, "match": "all", "conditions": [["field": "from", "op": "equals", "value": "boss@example.com"]],684                           "actions": [["type": "star"], ["type": "label", "label_id": .string(uuidC)]], "stop": false])685        var renamed = list[0]686        renamed.name = "Factures 2"687        let edited = renamed688        let (_, u) = try await exchange(.json(Self.rule)) { try await $0.updateRule(edited) }689        #expect(u.line == "PATCH /api/next/rules/\(uuidA)" && u.json["name"] == "Factures 2" && u.json["actions"].arrayValue?.count == 13 && u.json["actions"][11] == ["type": "teleport", "to": "mars"])690        let (_, s) = try await exchange(.json(Self.rule)) { try await $0.setRule(id: uuidA, enabled: false, position: 5) }691        #expect(s.line == "PATCH /api/next/rules/\(uuidA)" && s.json == ["enabled": false, "position": 5])692        let (_, d) = try await exchange(.ok) { try await $0.deleteRule(id: uuidA) }693        #expect(d.line == "DELETE /api/next/rules/\(uuidA)")694695        let runs = #"{"data":[{"id":"42","mailbox_id":"\#(uuidB)","email_id":"M1","status":"partial","actions":[{"type":"label","status":"done"},{"type":"extract","status":"done","result":{"total":12.5}}],"error":null,"at":"\#(iso0)","finished_at":"\#(iso0)"},{"id":43,"status":"exploded"},{"status":"ok"}]}"#696        let (rr, rq) = try await exchange(.json(runs)) { try await $0.ruleRuns(id: uuidA, limit: 20) }697        #expect(rq.line == "GET /api/next/rules/\(uuidA)/runs?limit=20" && rr.count == 2 && rr[0].id == "42" && rr[0].status == .partial && rr[0].actions.count == 2 && rr[0].actions[1]["result"]["total"] == 12.5 && rr[0].at == t0)698        #expect(rr[1].id == "43" && rr[1].status == .unknown && rr[1].mailboxId == "")699        let (_, rq2) = try await exchange(.json(#"{"data":[]}"#)) { try await $0.ruleRuns(id: uuidA) }700        #expect(rq2.line == "GET /api/next/rules/\(uuidA)/runs")701702        let test = #"{"matched":true,"dry_run":true,"conditions":[{"field":"from","op":"equals","value":"boss@example.com","result":true}],"actions":[{"type":"star","would":"star the message"},{"type":"label","would":"add the label Clients"}],"facts":{"has_attachment":false,"is_newsletter":false,"size":1200,"list":"","ai_category":null}}"#703        let (t, tq) = try await exchange(.json(test)) { try await $0.testRule(new, mailboxId: uuidB, emailId: "M1") }704        #expect(tq.line == "POST /api/next/rules/test" && tq.json["rule"] == new.json && tq.json["mailbox_id"] == .string(uuidB) && tq.json["email_id"] == "M1")705        #expect(t.matched && t.conditions == [RuleTestResult.ConditionResult(condition: .text(field: .from, op: .equals, value: "boss@example.com"), result: true)] && t.actions.map(\.type) == ["star", "label"] && t.actions[1].would == "add the label Clients" && t.facts["size"] == 1200)706        let (no, _) = try await exchange(.json(#"{"matched":false}"#)) { try await $0.testRule(new, mailboxId: uuidB, emailId: "M1") }707        #expect(!no.matched && no.actions.isEmpty && no.conditions.isEmpty)708    }709}710711@Suite struct NextOpsAPITests {712    @Test func health() async throws {713        let body = #"{"status":"warn","checks":{"mail_server":{"status":"ok","detail":"reachable","checked_at":"\#(iso0)"},"disk":{"status":"warn","detail":"12 % free","checked_at":"\#(iso0)","data":{"free_pct":12}},"quantum":{"status":"entangled","detail":"?"},"broken":"x"},"generated_at":"\#(iso0)"}"#714        let (h, r) = try await exchange(.json(body)) { try await $0.adminHealth() }715        #expect(r.line == "GET /api/admin/health" && h.overall == .warn && h.status == .warn && h.generatedAt == t0 && h.checks.map(\.name) == ["disk", "mail_server", "quantum"])716        #expect(h.check("disk")?.status == .warn && h.check("disk")?.data["free_pct"] == 12 && h.check("mail_server")?.checkedAt == t0 && h.check("quantum")?.status == .unknown)717        // tolerated variants: an array of named checks, a flat map; the verdict is then computed here718        let (arr, fresh) = try await exchange(.json(#"{"checks":[{"name":"queue","status":"ok","detail":""},{"name":"dns","status":"fail","detail":"SPF"}]}"#)) { try await $0.adminHealth(fresh: true) }719        #expect(fresh.line == "GET /api/admin/health?fresh=1" && arr.status == nil && arr.overall == .fail && arr.checks.count == 2)720        let (flat, _) = try await exchange(.json(#"{"push":{"status":"ok","detail":"configured"}}"#)) { try await $0.adminHealth() }721        #expect(flat.checks.map(\.name) == ["push"] && flat.overall == .ok)722        let (none, _) = try await exchange(.json("{}")) { try await $0.adminHealth() }723        #expect(none.checks.isEmpty && none.overall == .unknown)724        let forbidden = await failure(.error(403, "forbidden")) { try await $0.adminHealth() } as? APIError725        #expect(forbidden?.status == 403)726    }727728    @Test func alerts() async throws {729        let alert = #"{"id":"\#(uuidA)","key":"disk.low","severity":"warn","title":"Disque presque plein","detail":"12 % libre","state":"open","first_seen":"\#(iso0)","last_seen":"\#(iso0)","count":3,"notified_at":null,"acked_by":null,"acked_at":null,"resolved_at":null,"acked_by_handle":null}"#730        let (list, r) = try await exchange(.json(#"{"data":[\#(alert),{"id":"a2","severity":"apocalyptic","state":"snoozed"}]}"#)) { try await $0.adminAlerts() }731        #expect(r.line == "GET /api/admin/alerts?state=open" && list.count == 2)732        #expect(list[0].key == "disk.low" && list[0].severity == .warn && list[0].state == .open && list[0].count == 3 && list[0].firstSeen == t0 && list[0].ackedAt == nil && list[1].severity == .unknown && list[1].state == .unknown && list[1].count == 1)733        let (_, all) = try await exchange(.json(#"{"data":[]}"#)) { try await $0.adminAlerts(openOnly: false) }734        #expect(all.line == "GET /api/admin/alerts?state=all")735        let acked = alert.replacingOccurrences(of: #""state":"open""#, with: #""state":"acked""#).replacingOccurrences(of: #""acked_at":null"#, with: #""acked_at":"\#(iso0)""#)736        let (a, ack) = try await exchange(.json(acked)) { try await $0.acknowledgeAlert(id: uuidA) }737        #expect(ack.line == "POST /api/admin/alerts/\(uuidA)/ack" && ack.json == [:] && a.state == .acked && a.ackedAt == t0)738        #expect((await failure(.error(409, "not_open")) { try await $0.acknowledgeAlert(id: uuidA) } as? APIError)?.code == "not_open")739    }740741    @Test func devicesTrendsAndSecurityEvents() async throws {742        let body = #"{"sessions":[{"id":"\#(uuidA)","user_id":"\#(uuidB)","handle":"sp","kind":"native","device_name":"Mac","platform":"macOS 27","ip":"10.0.0.1","user_agent":"SPMail","created_at":"\#(iso0)","last_seen_at":"\#(iso0)","expires_at":"\#(iso0)","current":true}],"push_devices":[{"id":"\#(uuidC)","session_id":"\#(uuidA)","user_id":"\#(uuidB)","environment":"sandbox","bundle_id":"ai.spboucher.spmail","device_name":"Mac","enabled":false,"app_version":"2.0.0","last_push_at":null,"last_error":"BadDeviceToken","handle":"sp","token_tail":"a1b2c3"}]}"#743        let (d, r) = try await exchange(.json(body)) { try await $0.adminDevices() }744        #expect(r.line == "GET /api/admin/devices" && d.sessions.count == 1 && d.sessions[0].user == "sp" && d.sessions[0].kind == "native" && d.sessions[0].current && d.sessions[0].lastSeenAt == t0)745        #expect(d.pushDevices.count == 1 && d.pushDevices[0].environment == .sandbox && !d.pushDevices[0].enabled && d.pushDevices[0].tokenTail == "a1b2c3" && d.pushDevices[0].lastError == "BadDeviceToken" && d.pushDevices[0].user == "sp")746        let (e, _) = try await exchange(.json("{}")) { try await $0.adminDevices() }747        #expect(e.sessions.isEmpty && e.pushDevices.isEmpty)748        let (_, rs) = try await exchange(.ok) { try await $0.adminRevokeSession(id: uuidA) }749        #expect(rs.line == "DELETE /api/admin/devices/sessions/\(uuidA)")750        let (_, rp) = try await exchange(.ok) { try await $0.adminRemovePushDevice(id: uuidC) }751        #expect(rp.line == "DELETE /api/admin/devices/push/\(uuidC)")752        // not re-authenticated: a 403, which must not look like a lost session753        let reauth = await failure(.error(403, "reauth_required")) { try await $0.adminRevokeSession(id: uuidA) }754        #expect((reauth as? APIError)?.code == "reauth_required" && !NextError.isUnauthorized(reauth!))755756        let storage = #"{"metric":"storage","days":7,"data":[{"day":"2026-11-30","used_bytes":1000,"mailboxes":[{"mailbox_id":"m","address":"a","used_bytes":"1000"}]},{"day":"2026-12-01","used_bytes":"2500","mailboxes":[]}]}"#757        let (t, tr) = try await exchange(.json(storage)) { try await $0.adminTrends(.storage, days: 7) }758        #expect(tr.line == "GET /api/admin/trends?metric=storage&days=7" && t.metric == "storage" && t.days == 7 && t.points.count == 2 && t.series("used_bytes").map(\.value) == [1000, 2500] && t.points[1].date == Date(timeIntervalSince1970: 1_796_083_200))759        let (dl, dr) = try await exchange(.json(#"{"metric":"deliveries","days":30,"data":[{"day":"2026-12-01","received":5,"sent":3,"delivered":3,"bounced":0,"failed":0}]}"#)) { try await $0.adminTrends(.deliveries) }760        #expect(dr.line == "GET /api/admin/trends?metric=deliveries&days=30" && dl.points[0].values == ["received": 5, "sent": 3, "delivered": 3, "bounced": 0, "failed": 0])761        let (api, _) = try await exchange(.json(#"{"data":[]}"#)) { try await $0.adminTrends(.api) }762        #expect(api.metric == "api" && api.points.isEmpty)763764        let events = #"{"data":[{"id":"901","at":"\#(iso0)","action":"login.failed","target":null,"meta":{"reason":"unknown_credential"},"ip":"203.0.113.9","actor":null},{"id":900,"at":"\#(iso0)","action":"session.revoke","target":"\#(uuidA)","meta":{},"ip":"10.0.0.1","actor":"sp"}],"next_before":900,"failed_24h":{"login_failed":4,"reauth_failed":1}}"#765        let (page, er) = try await exchange(.json(events)) { try await $0.adminSecurityEvents(limit: 2, before: 950, action: "login", hours: 24) }766        #expect(er.line == "GET /api/admin/security-events?limit=2&before=950&action=login&hours=24" && page.events.count == 2 && page.nextBefore == 900 && page.loginFailed24h == 4 && page.reauthFailed24h == 1)767        #expect(page.events[0].id == "901" && page.events[0].kind == "login.failed" && page.events[0].ip == "203.0.113.9" && page.events[0].user == nil && page.events[0].meta["reason"] == "unknown_credential" && page.events[0].at == t0)768        #expect(page.events[1].id == "900" && page.events[1].user == "sp" && page.events[1].target == uuidA)769        let (none, bare) = try await exchange(.json(#"{"data":[],"next_before":null}"#)) { try await $0.adminSecurityEvents() }770        #expect(bare.line == "GET /api/admin/security-events" && none.events.isEmpty && none.nextBefore == nil && none.loginFailed24h == 0)771    }772}773
Files main
Menu

Theme