Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/SelfTest+System.swift3// Description: DEBUG-only self-test of the system-integration layer against the development backend: token registration (simulated token)4// with the fields the server stores, preferences round trip, a simulated remote notification routed to its conversation, the notification5// actions (« mark as read », « archive », reminder, quick reply — exactly one outbound message, to a staging address) checked on the server,6// widget snapshot content per privacy level and lock, the share-extension hand-off, `mailto:`, Spotlight bookkeeping, and what sign-out clears.7#if DEBUG8import SPMailCore9import SPMailSystem10import SwiftUI1112extension SelfTest {13 /// The payload the server builds for a message (sp-mail server/src/next/apns.ts `buildPayload`).14 private static func payload(kind: String = "new", category: String = "MAIL_NEW", mailbox: String, email: EmailSummary) -> [AnyHashable: Any] {15 ["aps": ["alert": ["title": "Essai A", "body": "Nouveau message"], "badge": 1, "sound": "default", "thread-id": "\(mailbox):\(email.threadId)", "category": category, "mutable-content": 1, "interruption-level": "active"] as [String: Any],16 "mb": mailbox, "email": email.id, "thread": email.threadId, "kind": kind]17 }1819 static func systemSteps(_ model: AppModel, a: MeResponse.Box, b: MeResponse.Box, run: String, report: (String, Bool, String) -> Void) async {20 func step(_ name: String, _ ok: Bool, _ detail: String = "") { report("system: " + name, ok, detail) }21 let system = model.system, push = system.push, next = system.next, notifications = system.notifications22 guard a.address.hasSuffix("@stg.spboucher.ai"), b.address.hasSuffix("@stg.spboucher.ai"), let store = model.store, let engineA = model.engines[a.id], let engineB = model.engines[b.id] else {23 step("staging-only guard", false); return24 }2526 // 1. token registration: a simulated token reaches the backend with the right fields; registering again does not create a second device27 push.environmentOverride = .sandbox28 let token = Data((0..<32).map { _ in UInt8.random(in: 0...255) })29 await push.didRegister(token: token)30 let devices = (try? await next.pushDevices()) ?? []31 let mine = devices.first { $0.id == push.deviceId }32 step("token registration reaches the backend with the right fields",33 mine != nil && mine?.current == true && mine?.bundleId == AppConfig.bundleId && mine?.environment == .sandbox && mine?.deviceName == AppConfig.clientInfo.deviceName34 && mine?.locale == PushRegistrar.locale && mine?.appVersion == PushRegistrar.appVersion && mine?.enabled == true && push.registration == .registered,35 "device \(mine?.id ?? "-") bundle \(mine?.bundleId ?? "-") env \(mine?.environment.rawValue ?? "-") name \(mine?.deviceName ?? "-") locale \(mine?.locale ?? "-") version \(mine?.appVersion ?? "-") state \(push.registration)")36 let firstId = push.deviceId37 await push.didRegister(token: token)38 let again = (try? await next.pushDevices()) ?? []39 step("re-registration keeps one device", push.deviceId == firstId && again.filter { $0.current }.count == 1, "\(again.count) devices")4041 // 2. preferences round trip, then back to the defaults42 let wanted = PushPrefs(enabled: true, preview: .full, quietHours: QuietHours(start: "22:30", end: "06:45", timeZone: "America/Toronto"), prioritySenders: ["chef@stg.spboucher.ai", "@exemple.org"], priorityOnly: false, mailboxes: [a.id: false], badge: .inbox)43 await push.save(wanted)44 let read = try? await next.pushPrefs()45 step("preferences round trip", read == wanted && push.prefs == wanted && BadgeMath.badge(inboxUnread: [a.id: 5, b.id: 2], prefs: read) == 2, "\(String(describing: read))")46 await push.save(PushPrefs(preview: .full))47 step("preferences back to defaults (preview full)", (try? await next.pushPrefs()) == PushPrefs(preview: .full))48 await push.refreshServerState()49 let status = push.serverStatus50 let queued = await push.sendTest(to: mine)51 step("push status and test notification", status != nil && (status?.configured == true ? queued == 1 : queued == 0), "configured \(status?.configured == true) queued \(queued ?? -1) error \(status?.lastError ?? "-")")5253 // a fresh unread message A → B to act on54 await model.loadSenders()55 guard let identity = model.senders.first(where: { $0.account == a.id && !$0.isAlias })?.identity else { step("sender identity", false); return }56 var outgoing = ReplyBuilder.blank(identity: identity)57 outgoing.to = [EmailAddress(name: "Essai B", email: b.address)]58 outgoing.subject = "Système \(run)"59 outgoing.text = "Message pour les notifications SYS-\(run)"60 let sent = await engineA.send(OutboxItem(account: a.id, message: outgoing))61 var mail: EmailSummary?62 let arrived = await wait(45) {63 try? await engineB.syncNowAndWait()64 guard let inbox = try? await engineB.mailboxId(role: .inbox) else { return false }65 mail = ((try? await store.threads(b.id, scope: .mailbox(inbox), threaded: false, limit: 50)) ?? []).first { $0.email.subject == "Système \(run)" }?.email66 return mail != nil67 }68 guard arrived, let mail, let inboxB = try? await engineB.mailboxId(role: .inbox) else { step("test message delivered", false, "send state \(sent.state)"); return }69 /// The message as the SERVER has it now (`Thread/get` + refetch), not the optimistic local copy.70 func onServer() async -> EmailSummary? {71 try? await engineB.syncNowAndWait()72 guard let t = try? await engineB.thread(mail.threadId), t.complete else { return nil }73 return t.emails.first { $0.id == mail.id }74 }7576 // 3. a simulated remote notification routes to the right conversation — from another mailbox's window77 await model.switchAccount(a.id)78 let info = payload(mailbox: b.id, email: mail)79 let route = NotificationRoute(userInfo: info)80 _ = notifications.present(NotificationCoordinator.Incoming(route: route, payload: NotificationPayload(userInfo: info), threadKey: "\(b.id):\(mail.threadId)", identifier: "remote-\(run)", isRemote: true))81 step("remote notification recorded: the app will not announce that message again", notifications.ledgerContains(mailboxId: b.id, emailId: mail.id) && route == .conversation(mailboxId: b.id, emailId: mail.id, threadId: mail.threadId))82 await notifications.respond(.resolve(actionIdentifier: NotificationActionID.systemDefault, userInfo: info), identifier: "remote-\(run)")83 let routed = await wait(20) { model.main.activeAccount == b.id && model.main.reader.focusedEmailId == mail.id && model.main.reader.bodies[mail.id] != nil }84 step("notification tap opens the exact conversation", routed && model.main.reader.conversation.contains { $0.id == mail.id } && system.router.lastDelivered == .conversation(mailboxId: b.id, emailId: mail.id, threadId: mail.threadId),85 "account \(model.main.activeAccount ?? "-") focused \(model.main.reader.focusedEmailId ?? "-")")86 // the conversation is on screen: a notification for it must not show a banner over it (when the app is frontmost)87 if AppActivity.isActive {88 let options = notifications.present(NotificationCoordinator.Incoming(route: route, payload: NotificationPayload(userInfo: info), threadKey: "\(b.id):\(mail.threadId)", identifier: "remote-\(run)", isRemote: true))89 step("no banner for the conversation being read", !options.contains(.banner) && !options.contains(.sound), "\(options.rawValue)")90 }9192 // 4. « mark as read » changes server state93 await engineB.markSeen(false, ids: [mail.id])94 let unreadFirst = await wait(15) { await onServer()?.isSeen == false }95 await notifications.respond(.resolve(actionIdentifier: NotificationActionID.markRead.rawValue, userInfo: info), identifier: "remote-\(run)")96 let readOnServer = await wait(20) { await onServer()?.isSeen == true }97 step("action « mark as read » changes server state", unreadFirst && readOnServer && notifications.lastCommand == .markRead(mailboxId: b.id, emailId: mail.id), "unread first \(unreadFirst) read \(readOnServer)")9899 // 5. reminder actions: « Terminé » settles the reminder, « Rappeler dans 1 heure » snoozes the message on the server100 let reminderInfo = payload(kind: "reminder", category: "MAIL_REMINDER", mailbox: b.id, email: mail)101 let reminder = try? await next.createReminder(mailboxId: b.id, emailId: mail.id, dueAt: Date().addingTimeInterval(3600))102 await notifications.respond(.resolve(actionIdentifier: NotificationActionID.done.rawValue, userInfo: reminderInfo), identifier: "reminder-\(run)")103 let afterDone = ((try? await next.reminders()) ?? []).first { $0.id == reminder?.id }104 step("reminder action « Terminé » marks the reminder done", reminder != nil && afterDone?.status == .done, "status \(afterDone?.status.rawValue ?? "-")")105 await notifications.respond(.resolve(actionIdentifier: NotificationActionID.snoozeHour.rawValue, userInfo: reminderInfo), identifier: "reminder-\(run)")106 let snooze = ((try? await next.snoozes(status: .active)) ?? []).first { $0.mailboxId == b.id && $0.emailId == mail.id }107 let snoozedFor = snooze?.until.map { $0.timeIntervalSinceNow } ?? 0108 step("reminder action « Rappeler dans 1 heure » snoozes on the server", snooze != nil && snoozedFor > 3300 && snoozedFor < 3700, "until in \(Int(snoozedFor)) s")109 if let snooze { _ = try? await next.cancelSnooze(id: snooze.id) }110 let backInInbox = await wait(25) { await onServer()?.mailboxIds.contains(inboxB) == true }111 step("snooze cancelled: the message is back in the Inbox", backInInbox)112113 // 6. quick reply: the normal send path, exactly one outbound message, to a staging address114 let outboxBefore = await engineB.outbox().count115 let replyText = "Réponse rapide REP-\(run)"116 let replyCommand = NotificationCommand.resolve(actionIdentifier: NotificationActionID.reply.rawValue, userInfo: info, replyText: replyText)117 await notifications.respond(replyCommand, identifier: "remote-\(run)")118 let replies = await engineB.outbox().filter { $0.message.text.hasPrefix(replyText) }119 let recipients = replies.first?.message.to.map(\.email) ?? []120 step("quick reply produces exactly one outbound message to a staging address",121 replies.count == 1 && replies.first?.state == .accepted && recipients == [a.address] && recipients.allSatisfy { $0.hasSuffix("@stg.spboucher.ai") } && replies.first?.message.subject == "Re: Système \(run)"122 && replies.first?.message.relatedEmailId == mail.id && !(replies.first?.message.inReplyTo.isEmpty ?? true),123 "\(replies.count) item(s), state \(String(describing: replies.first?.state)), to \(recipients), outbox \(outboxBefore) → \(await engineB.outbox().count)")124 var received = 0125 let replyArrived = await wait(45) {126 try? await engineA.syncNowAndWait()127 guard let inbox = try? await engineA.mailboxId(role: .inbox) else { return false }128 received = ((try? await store.threads(a.id, scope: .mailbox(inbox), threaded: false, limit: 80)) ?? []).filter { $0.email.subject == "Re: Système \(run)" }.count129 return received >= 1130 }131 try? await Task.sleep(for: .seconds(3))132 try? await engineA.syncNowAndWait()133 if let inbox = try? await engineA.mailboxId(role: .inbox) { received = ((try? await store.threads(a.id, scope: .mailbox(inbox), threaded: false, limit: 80)) ?? []).filter { $0.email.subject == "Re: Système \(run)" }.count }134 step("quick reply received once", replyArrived && received == 1, "\(received) received")135136 // 7. « archive » changes server state137 await notifications.respond(.resolve(actionIdentifier: NotificationActionID.archive.rawValue, userInfo: info), identifier: "remote-\(run)")138 let archived = await wait(20) { guard let e = await onServer() else { return false }; return !e.mailboxIds.contains(inboxB) && !e.mailboxIds.isEmpty }139 step("action « archive » changes server state", archived, "\((await onServer())?.mailboxIds ?? [])")140 await engineB.move(ids: [mail.id], to: inboxB)141 _ = await wait(15) { await onServer()?.mailboxIds.contains(inboxB) == true }142 await model.reloadMailboxes()143144 // 8. badge: the app's number follows the server rule and drops at once after a local read145 await engineB.markSeen(false, ids: [mail.id])146 _ = await wait(15) { await onServer()?.isSeen == false }147 await model.reloadMailboxes()148 let before = BadgeMath.badge(inboxUnread: model.inboxUnread, prefs: push.prefs)149 await engineB.markSeen(true, ids: [mail.id])150 await model.reloadMailboxes()151 let after = BadgeMath.badge(inboxUnread: model.inboxUnread, prefs: push.prefs)152 await push.save(PushPrefs(preview: .full, mailboxes: [b.id: false]))153 let muted = BadgeMath.badge(inboxUnread: model.inboxUnread, prefs: push.prefs)154 await push.save(PushPrefs(preview: .full, badge: .none))155 let none = BadgeMath.badge(inboxUnread: model.inboxUnread, prefs: push.prefs)156 step("badge recomputed after a local read, muted mailbox left out, mode « none »", before >= 1 && after == before - 1 && muted == (model.inboxUnread[a.id] ?? 0) && none == 0, "before \(before) after \(after) muted \(muted) none \(none)")157158 // 9. widget snapshot content per privacy level, and the lock159 var levels: [String] = []160 var levelsOK = true161 for level in [PushPreview.full, .sender, .none] {162 await push.save(PushPrefs(preview: level))163 await system.shared.writeSnapshot()164 guard let s = await system.shared.buildSnapshot(), let stored = system.shared.store.snapshot() else { levelsOK = false; continue }165 let c = s.conversations166 let hasAll = !c.isEmpty && s.unread.map(\.mailboxId).sorted() == [a.id, b.id].sorted()167 switch level {168 case .full: levelsOK = levelsOK && hasAll && c.allSatisfy { $0.sender != nil && $0.subject != nil } && c.contains { $0.subject == "Système \(run)" }169 case .sender: levelsOK = levelsOK && hasAll && c.allSatisfy { $0.sender != nil && $0.subject == nil && $0.preview == nil }170 default: levelsOK = levelsOK && hasAll && c.allSatisfy { $0.sender == nil && $0.subject == nil && $0.preview == nil }171 }172 levelsOK = levelsOK && stored.previewLevel == level.rawValue && stored.conversations.map(\.emailId) == c.map(\.emailId)173 levels.append("\(level.rawValue):\(c.count)/\(stored.previewLevel)")174 }175 step("widget snapshot content per privacy level", levelsOK, levels.joined(separator: " "))176 await push.save(PushPrefs(preview: .full))177 await system.shared.writeSnapshot()178 var state = system.shared.currentState()179 let shown = WidgetContent.resolve(state: state, snapshot: system.shared.store.snapshot())180 state.lock = LockSnapshot(enabled: true, afterMinutes: 5, locked: true)181 let lockedContent = WidgetContent.resolve(state: state, snapshot: system.shared.store.snapshot())182 model.settings.hideNotificationContent = true183 let hidden = await system.shared.buildSnapshot()184 model.settings.hideNotificationContent = false185 var isContent = false186 if case .content = shown { isContent = true }187 step("widget content: shown when unlocked, lock glyph when locked, nothing readable with the device switch",188 isContent && lockedContent == .locked && hidden?.previewLevel == "none" && hidden?.conversations.allSatisfy { $0.sender == nil && $0.subject == nil } == true && system.shared.store.state()?.signedIn == true && system.shared.store.token() == model.api.token,189 "container \(system.shared.store.hasContainer) token shared \(system.shared.store.token() != nil)")190191 // 10. share-extension hand-off: a queued draft (sealed, with a file when the container exists) becomes a draft of the app192 let queue = system.shared.store.shareQueue193 let file = FileManager.default.temporaryDirectory.appendingPathComponent("partage-\(run).txt")194 try? Data("pièce partagée \(run)".utf8).write(to: file)195 let sources = queue.acceptsFiles ? [ShareSource(url: file, name: "partage-\(run).txt", type: "text/plain")] : []196 let queuedDraft = try? queue.enqueue(ShareDraft(mailboxId: a.id, to: [b.address], subject: "Partage \(run)", note: "Note partagée \(run)"), sources: sources)197 let imported = await system.shared.importSharedDrafts()198 let composer = imported.first.flatMap { model.composers[$0] }199 step("share-extension hand-off creates the draft",200 queuedDraft != nil && imported.count == 1 && composer?.item.account == a.id && composer?.to.map(\.email) == [b.address] && composer?.subject == "Partage \(run)" && composer?.plainText.hasPrefix("Note partagée \(run)") == true201 && composer?.attachments.map(\.name) == sources.map(\.name) && queue.pending().isEmpty,202 "queued \(queuedDraft != nil) imported \(imported.count) files \(composer?.attachments.count ?? -1)/\(sources.count) container \(queue.acceptsFiles)")203 if let composer { await composer.discard(); model.composerClosed(composer.id) }204 for scene in model.scenes { scene.composeRequest = nil }205 try? FileManager.default.removeItem(at: file)206207 // 11. mailto: opens a prefilled composer208 let before11 = Set(model.composers.keys)209 let mailto = URL(string: "mailto:\(b.address)?subject=Bonjour%20\(run)&body=Premi%C3%A8re%20ligne%0ADeuxi%C3%A8me&cc=\(a.address)")!210 if let link = DeepLink(url: mailto) { system.router.deliver(link) }211 let opened = await wait(15) { model.composers.keys.contains { !before11.contains($0) } }212 let prefilled = model.composers.first { !before11.contains($0.key) }?.value213 step("mailto: opens a prefilled composer", opened && prefilled?.to.map(\.email) == [b.address] && prefilled?.cc.map(\.email) == [a.address] && prefilled?.subject == "Bonjour \(run)" && prefilled?.plainText.hasPrefix("Première ligne\nDeuxième") == true,214 "to \(prefilled?.to.map(\.email) ?? []) cc \(prefilled?.cc.map(\.email) ?? []) subject \(prefilled?.subject ?? "-")")215 if let prefilled { await prefilled.discard(); model.composerClosed(prefilled.id) }216 for scene in model.scenes { scene.composeRequest = nil }217218 // 12. Spotlight: opt-in, bounded by the privacy level, per-item removal when a message goes to the trash219 let wasEnabled = model.settings.spotlightEnabled220 Spotlight.index([mail], account: b.id, app: model)221 let notIndexedWhenOff = wasEnabled || !Spotlight.trackedIds(b.id).contains(mail.id)222 model.settings.spotlightEnabled = true223 await push.save(PushPrefs(preview: .none))224 Spotlight.index([mail], account: b.id, app: model)225 let notIndexedWhenPrivate = !Spotlight.trackedIds(b.id).contains(mail.id)226 await push.save(PushPrefs(preview: .full))227 Spotlight.index([mail], account: b.id, app: model)228 let indexed = Spotlight.trackedIds(b.id).contains(mail.id) && Spotlight.parse(identifier: Spotlight.identifier(account: b.id, emailId: mail.id))?.emailId == mail.id229 var deleteError = "-"230 do { try await engineB.delete(ids: [mail.id]) } catch { deleteError = "\(error)" }231 let removed = await wait(20) {232 await model.reloadMailboxes()233 await Spotlight.reconcileNow(account: b.id, app: model)234 return !Spotlight.trackedIds(b.id).contains(mail.id)235 }236 Spotlight.index([mail], account: b.id, app: model) // something left for sign-out to purge237 step("Spotlight: opt-in, privacy level respected, item removed when the message is trashed", notIndexedWhenOff && notIndexedWhenPrivate && indexed && removed, "off \(notIndexedWhenOff) private \(notIndexedWhenPrivate) indexed \(indexed) removed \(removed) delete \(deleteError) folders \(model.mailboxes(for: b.id).compactMap(\.role))")238 try? await engineB.delete(ids: [mail.id]) // from the Trash: gone239 await push.save(PushPrefs())240241 // 13. sign-out, first half: the server forgets this device while the session is still valid242 let deviceId = push.deviceId243 await system.sessionEnding()244 let left = try? await next.pushDevices()245 step("sign-out deletes the device on the server", deviceId != nil && left != nil && left?.contains { $0.id == deviceId } == false && push.deviceId == nil, "\(left?.count ?? -1) device(s) left")246 model.settings.spotlightEnabled = wasEnabled247 }248249 /// After `signOut()`: nothing of the account is left outside the app.250 static func systemSignedOutSteps(_ model: AppModel, mailboxes: [String], report: (String, Bool, String) -> Void) {251 let shared = model.system.shared.store252 let tracked = mailboxes.flatMap { Spotlight.trackedIds($0) }253 report("system: sign-out clears the shared token, the widget snapshot, the share queue and Spotlight",254 shared.token() == nil && shared.snapshot() == nil && shared.state()?.signedIn != true && shared.widgetContent() == .signedOut && shared.shareQueue.pending().isEmpty && tracked.isEmpty && model.system.push.deviceId == nil255 && !model.system.notifications.ledgerContains(mailboxId: mailboxes.first ?? "", emailId: "any"),256 "token \(shared.token() == nil) snapshot \(shared.snapshot() == nil) signedIn \(shared.state()?.signedIn == true) spotlight \(tracked.count)")257 }258}259#endif260