Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/SelfTest+Integration.swift3// Description: DEBUG-only self-test steps of what joins the three SP Mail Next branches (features, composer, system): one NextStore per4// session shared by the composer, the writing assistant on the scripted local provider (Scripts/dev-ai-stub.mjs — no model call), the5// outbox follow-up of server-tracked sends (held, delivered — honest wording), a template sent to a sensitive recipient through the6// confirmation flow, and a mailbox that disappears (unsent items kept, exported, deleted). Mail only travels between the two test mailboxes.7#if DEBUG8import SPMailCore9import SwiftUI1011extension SelfTest {12 static func integrationSteps(_ model: AppModel, a: MeResponse.Box, b: MeResponse.Box, run: String, report: (String, Bool, String) -> Void) async {13 func step(_ name: String, _ ok: Bool, _ detail: String = "") { report("integration: " + name, ok, detail) }14 guard let ea = model.engines[a.id], let eb = model.engines[b.id], let store = model.store else { step("engines", false); return }15 let center = model.compose, next = model.next, fm = FileManager.default16 let toB = EmailAddress(name: "Essai B", email: b.address)17 func composer(in account: String) async -> ComposeModel? {18 guard let id = await model.makeComposer(.new, account: account) else { return nil }19 return model.composers[id]20 }21 func setPrefs(undo: Int, sensitive: [String] = []) async {22 var p = center.prefs23 p.undoSeconds = undo; p.sensitive = sensitive24 await center.setPrefs(p)25 }26 func inbox(_ engine: SyncEngine, _ subject: String) async -> [EmailSummary] {27 var f = SearchFilter()28 f.subject = subject29 f.inMailbox = try? await engine.mailboxId(role: .inbox)30 return ((try? await engine.search(f))?.results ?? []).filter { $0.subject == subject }31 }3233 // --- a. one NextStore / NextAPI per session: the composer reads and writes the store of NextServices; no second directory34 try? fm.createDirectory(at: ComposeCenter.legacyCacheDirectory, withIntermediateDirectories: true)35 try? Data("leftover".utf8).write(to: ComposeCenter.legacyCacheDirectory.appendingPathComponent("cache.sealed"))36 ComposeCenter.removeLegacyCache()37 await center.load(force: true)38 let shared = center.sharedStore != nil && center.sharedStore === next.store39 let name = "Signature \(run)"40 await center.saveSignature(id: nil, SignatureContent(name: name, text: "Intégration \(run)"))41 let inSharedStore = await next.store?.signatures().contains { $0.name == name } == true42 let prefsInSharedStore = await next.store?.composePrefs() != nil43 let folders = ((try? fm.contentsOfDirectory(atPath: AppConfig.cacheDirectory.path)) ?? []).filter { $0.hasPrefix("next") }44 if let created = center.signatures.first(where: { $0.name == name }) { await center.deleteSignature(id: created.id) }45 step("one NextStore per session: composer signatures and preferences live in the shared store, legacy « next-compose » folder removed",46 shared && inSharedStore && prefsInSharedStore && folders == ["next"] && center.next.api === model.api, "shared \(shared) signature \(inSharedStore) prefs \(prefsInSharedStore) folders \(folders)")4748 // --- b. writing assistant: hidden while the feature is off; preview, accept as one undoable edit, never the signature49 let hiddenWhenOff = await { () -> Bool in50 guard let c = await composer(in: a.id) else { return false }51 defer { Task { await c.discard(); model.composerClosed(c.id) } }52 c.insertText("Texte")53 await c.assist(.improve)54 return !c.assistantAvailable && !c.assistant.isPresented && c.assistant.proposal == nil55 }()56 if next.ai.localAvailable {57 try? await next.setAI(AISettingsUpdate(provider: .local, features: ["write": true]))58 if let c = await composer(in: a.id) {59 await c.prepare()60 c.chooseSignature(SignatureChoice(id: "selftest", text: "Signature d’essai \(run)"))61 c.to = [toB]62 c.editor.selection = NSRange(location: 0, length: 0)63 c.insertText("bonjour je veux un rendez vous vendredi")64 let original = c.authoredPlainText65 let outboxBefore = ((try? await store.outbox()) ?? []).filter { $0.state != .draft }.count66 await c.assist(.improve)67 let previewOnly = c.assistant.proposal == "Texte scripté." && c.authoredPlainText == original && c.assistant.isPresented && c.assistant.provider.contains("MacLustr") && c.assistant.source == original && !c.assistant.onSelection68 // (headless, the undo manager groups everything since the last event: the test marks the boundary a click would make)69 c.editor.undo.removeAllActions()70 let accepted = c.acceptAssist()71 let replaced = c.authoredPlainText == "Texte scripté." && c.plainText.contains("Signature d’essai \(run)") && !c.assistant.isPresented72 c.editor.undoEdit()73 let afterUndo = c.authoredPlainText74 let undone = afterUndo == original && !c.editor.canUndo75 // on a selection: only the selection is sent and replaced76 c.editor.selection = (c.editor.storage.string as NSString).range(of: "rendez vous")77 await c.assist(.shorten)78 let selectionSent = c.assistant.onSelection && c.assistant.source == "rendez vous"79 c.acceptAssist()80 let selectionReplaced = c.authoredPlainText == "bonjour je veux un Texte scripté. vendredi"81 // tone and translation carry their parameter; subjects are proposed and one is chosen82 await c.assist(.tone, tone: .friendly)83 let tone = c.assistant.proposal != nil && c.assistant.error == nil84 await c.assist(.translate, language: .en)85 let translated = c.assistant.proposal != nil && c.assistant.error == nil86 // the text changed since the request: the proposal is not applied over something else87 c.editor.selection = NSRange(location: 0, length: 0)88 c.insertText("Ajout. ")89 let refused = !c.acceptAssist() && c.assistant.error != nil && c.authoredPlainText.hasPrefix("Ajout. ")90 await c.assist(.subject)91 let subjects = c.assistant.subjects92 if let first = subjects.first { c.acceptSubject(first) }93 let outboxAfter = ((try? await store.outbox()) ?? []).filter { $0.state != .draft }.count94 let nothingSent = c.status != .sending && c.status != .accepted && outboxAfter == outboxBefore95 step("writing assistant: preview then accept (one undoable edit), selection or authored text only, signature untouched, nothing sent",96 hiddenWhenOff && c.assistantAvailable && previewOnly && accepted && replaced && undone && selectionSent && selectionReplaced && tone && translated && refused && subjects.count == 4 && c.subject == subjects.first && nothingSent,97 "off-hidden \(hiddenWhenOff) preview \(previewOnly) replaced \(replaced) undone \(undone) selection \(selectionSent)/\(selectionReplaced) tone \(tone) translate \(translated) refused \(refused) subjects \(subjects.count) unsent \(nothingSent) after undo \(afterUndo.debugDescription) error \(c.assistant.error ?? "-")")98 try? await next.setAI(AISettingsUpdate(provider: .off))99 step("writing assistant: hidden again when intelligence is switched off", !c.assistantAvailable)100 await c.discard(); model.composerClosed(c.id)101 } else { step("writing assistant: preview then accept (one undoable edit), selection or authored text only, signature untouched, nothing sent", false, "no composer") }102 } else {103 step("writing assistant: hidden while intelligence is off (no local provider on this server: assistant not exercised)", hiddenWhenOff)104 }105106 // --- c. outbox follow-up: what the composer sent through /api/v1 stays visible with the server's delivery status107 await model.outbound.reload(force: true)108 let tracked = model.outbound.items109 let withDelivery = tracked.filter { ["sent", "delivered"].contains($0.status) && !$0.recipients.isEmpty }110 let titled = withDelivery.contains { model.outbound.title(for: $0)?.isEmpty == false }111 let delivered = OutboundLabels.label("delivered").text112 let honest = tracked.allSatisfy { o in (OutboxView.outboundLabel(o).text == delivered) == (o.status == "delivered") && o.recipients.allSatisfy { (OutboxView.recipientLabel($0).text == delivered) == ($0.status == "delivered") } }113 step("outbox: sends made through /api/v1 are listed with the server's per-recipient status; « remis » only when the server says delivered",114 !withDelivery.isEmpty && titled && honest && !tracked.contains { $0.status == "cancelled" } && model.outbound.notice == nil,115 "tracked \(tracked.count) with delivery \(withDelivery.count) titled \(titled) honest \(honest) statuses \(Set(tracked.map(\.status)).sorted())")116 await setPrefs(undo: 20)117 if let c = await composer(in: a.id) {118 let subject = "Retenu suivi \(run)"119 c.to = [toB]; c.subject = subject120 c.insertText("Retenu puis repris \(run)")121 let result = await c.deliver(.now)122 model.composerClosed(c.id)123 if case .held(let o) = result {124 await model.outbound.reload(force: true)125 let row = model.outbound.items.first { $0.id == o.id }126 let label = row.map { OutboxView.outboundLabel($0).text } ?? "-"127 let heldRow = row.map { OutboundTracker.isHeld($0) } == true && label != delivered && label != OutboundLabels.label("sent").text && model.outbound.title(for: o.outbound) == subject128 let check = OutboundTracker.nextCheck(model.outbound.items) ?? -1129 let localGone = ((try? await store.outboxItem(c.id)) ?? nil) == nil130 let reopened = await center.undo(o.id, open: false)131 await model.outbound.reload(force: true)132 let goneAfterUndo = !model.outbound.items.contains { $0.id == o.id }133 step("outbox: a held message reads « Envoi dans N s » with Undo, is re-checked when the hold ends, and leaves the list once taken back",134 heldRow && localGone && check > 0 && check <= 23 && reopened != nil && goneAfterUndo, "label \(label) next check \(check) reopened \(reopened ?? "-") gone \(goneAfterUndo)")135 if let reopened, let draft = model.composers[reopened] { await draft.discard(); model.composerClosed(reopened) }136 } else { step("outbox: a held message reads « Envoi dans N s » with Undo, is re-checked when the hold ends, and leaves the list once taken back", false, "\(result)") }137 }138 await setPrefs(undo: 0)139140 // --- g. a template sent from the composer to a sensitive recipient goes through the confirmation, like any send141 let templateSubject = "Modèle sensible \(run)"142 if let template = try? await model.api.createTemplate(TemplateContent(name: "Essai \(run)", category: "other", subject: templateSubject, html: "<p>Bonjour, modèle \(run).</p>", text: "Bonjour, modèle \(run).")) {143 await setPrefs(undo: 0, sensitive: [b.address])144 if let c = await composer(in: a.id) {145 c.to = [toB]146 let delivery = TemplateDelivery(templateId: template.id, values: [:])147 let first = await c.deliverTemplate(delivery)148 var asked: [String] = []149 if case .needsConfirmation(let r) = first { asked = r }150 let waiting = c.pendingTemplate == delivery && c.status != .sending && !c.isLocked151 try? await Task.sleep(for: .seconds(3))152 let notSent = await inbox(eb, templateSubject).isEmpty153 let second = await c.deliverTemplate(delivery, confirmSensitive: true)154 var accepted = false155 if case .accepted = second { accepted = true }156 model.composerClosed(c.id)157 _ = await wait(45) { !(await inbox(eb, templateSubject)).isEmpty }158 let count = await inbox(eb, templateSubject).count159 step("template to a sensitive recipient: the server asks (confirmation flow, not an error), nothing leaves before; sent once after the confirmation",160 asked == [b.address.lowercased()] && waiting && notSent && accepted && c.pendingTemplate == nil && count == 1, "asked \(asked) waiting \(waiting) not sent \(notSent) then \(second) received \(count)")161 }162 await setPrefs(undo: 0)163 try? await model.api.archiveTemplate(id: template.id)164 } else { step("template to a sensitive recipient: the server asks (confirmation flow, not an error), nothing leaves before; sent once after the confirmation", false, "no template") }165166 // --- h. a mailbox disappears from the account: its unsent items are kept, shown as « boîte retirée », exported, deleted167 let attachment = OutgoingAttachment(name: "retirée-\(run).txt", type: "text/plain", size: 7)168 let keptMessage = OutgoingMessage(from: EmailAddress(name: "Essai B", email: b.address), to: [EmailAddress(email: a.address)], subject: "Boîte retirée \(run)", text: "Brouillon à conserver \(run)", attachments: [attachment])169 let kept = try? await eb.saveDraft(OutboxItem(account: b.id, message: keptMessage), attachments: [attachment.id: Data("retirée".utf8)])170 let doomed = try? await eb.saveDraft(OutboxItem(account: b.id, message: OutgoingMessage(from: EmailAddress(email: b.address), to: [EmailAddress(email: a.address)], subject: "À supprimer \(run)", text: "x")))171 if let kept, let doomed {172 await model.debugSimulateMailboxRemoval(b.id)173 let keptItem = (try? await store.outboxItem(kept.id)) ?? nil, keptBytes = (try? await store.attachmentData(attachment.id)) ?? nil174 let survived = keptItem != nil && keptBytes == Data("retirée".utf8)175 let listed = model.outbox.first { $0.id == kept.id }176 let orphan = listed.map { model.isOrphan($0) } == true && model.engines[b.id] == nil && model.outboxAttention >= 2177 let label = listed.map { OutboxView.orphanLabel($0).text } ?? "-"178 var eml = ""179 if let listed, let url = try? await model.exportEML(of: listed) { eml = (try? String(contentsOf: url, encoding: .utf8)) ?? "" }180 let exported = eml.contains("Subject: =?UTF-8?B?") && eml.contains("X-Unsent: 1") && eml.contains("To: \(a.address)") && eml.contains(Data("retirée".utf8).base64EncodedString()) && eml.contains("multipart/mixed")181 if let d = model.outbox.first(where: { $0.id == doomed.id }) { await model.deleteOrphan(d) }182 let deleted = ((try? await store.outboxItem(doomed.id)) ?? nil) == nil && !model.outbox.contains { $0.id == doomed.id }183 step("mailbox removed: unsent drafts are kept on the device (« boîte retirée »), exported as .eml with their attachment, deleted only on request",184 survived && orphan && label.contains("retirée") && exported && deleted, "survived \(survived) orphan \(orphan) label \(label) eml \(eml.count) bytes exported \(exported) deleted \(deleted)")185 // the server still lists the mailbox: it comes back, and the draft is an ordinary draft again186 await model.refreshAccounts()187 let back = await wait(45) { model.engines[b.id] != nil && model.mailboxes(for: b.id).contains { $0.role == "inbox" } }188 let ordinary = model.outbox.first { $0.id == kept.id }.map { !model.isOrphan($0) } == true189 step("mailbox back: its engine is attached again and the kept draft is editable", back && ordinary, "back \(back) ordinary \(ordinary)")190 await model.engines[b.id]?.discardDraft(id: kept.id)191 try? await model.engines[b.id]?.syncNowAndWait()192 await model.reloadMailboxes()193 await model.reloadOutbox()194 } else { step("mailbox removed: unsent drafts are kept on the device (« boîte retirée »), exported as .eml with their attachment, deleted only on request", false, "drafts not saved") }195 _ = ea196 }197198 /// After sign-out: nothing of the session's Next data stays — the shared store's folder, the composer's mirrors, the tracked sends.199 static func integrationSignedOutSteps(_ model: AppModel, report: (String, Bool, String) -> Void) {200 // (the store removes its sealed files; an empty folder may remain)201 let fm = FileManager.default202 let folders = ((try? fm.contentsOfDirectory(atPath: AppConfig.cacheDirectory.path)) ?? []).filter { $0.hasPrefix("next") && !((try? fm.contentsOfDirectory(atPath: AppConfig.cacheDirectory.appendingPathComponent($0).path)) ?? []).isEmpty }203 let center = model.compose204 let empty = center.signatures.isEmpty && center.snippets.isEmpty && center.holds.isEmpty && !center.prefsKnown && model.next.store == nil && model.outbound.items.isEmpty205 report("integration: sign-out wipes the shared Next store, the composer's mirrors and the tracked sends", folders.isEmpty && empty, "folders \(folders) empty \(empty)")206 }207}208#endif209