Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/SelfTest+Compose.swift3// Description: DEBUG-only self-test steps of the Next composer against the development backend and the real staging mail server: rich message4// with an inline image and an attachment verified at reception, reply with the quote kept byte for byte, drafts closed and reopened (also one5// the server wrote), offline compose then send, send later / reschedule / cancel, undo send inside and outside its window, sensitive6// recipients, default signatures, alias sender, snippets, autocomplete, draft conflict. Mail only travels between the two test mailboxes.7#if DEBUG8import SPMailCore9import SwiftUI1011extension SelfTest {12 static func composeSteps(_ 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("composer: " + 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.compose16 let toB = EmailAddress(name: "Essai B", email: b.address)17 let png = ComposeDemo.demoImage() ?? Data()1819 /// A new headless composer in mailbox `account` (no window: the model is what is tested).20 func composer(_ kind: ComposeKind = .new, in account: String) async -> ComposeModel? {21 guard let id = await model.makeComposer(kind, account: account) else { return nil }22 return model.composers[id]23 }24 /// Messages of a mailbox's Inbox whose subject is exactly `subject` (asked to the server).25 func inbox(_ engine: SyncEngine, _ subject: String) async -> [EmailSummary] {26 var f = SearchFilter()27 f.subject = subject28 f.inMailbox = try? await engine.mailboxId(role: .inbox)29 return ((try? await engine.search(f))?.results ?? []).filter { $0.subject == subject }30 }31 func arrives(_ engine: SyncEngine, _ subject: String, within seconds: Double = 45) async -> EmailSummary? {32 _ = await wait(seconds) { !(await inbox(engine, subject)).isEmpty }33 return await inbox(engine, subject).first34 }35 func stored(_ id: String) async -> OutboxItem? { (try? await store.outboxItem(id)) ?? nil }36 func setPrefs(undo: Int, sensitive: [String] = []) async {37 var p = center.prefs38 p.undoSeconds = undo; p.sensitive = sensitive; p.warnMissingAttachment = true39 await center.setPrefs(p)40 }41 func addInline(_ c: ComposeModel) async -> Bool {42 c.editor.selection = NSRange(location: c.editor.storage.length, length: 0)43 c.addInlineImage(data: png, name: "graphique.png")44 return await wait(8) { c.attachments.contains { $0.inline } && !RichText.cids(in: c.editor.storage).isEmpty }45 }4647 // --- 0. the editor itself, as typed in (no server involved)48 do {49 let ed = RichTextController()50 func html() -> String { RichHTML.html(from: ed.document) }51 var notes: [String] = []52 func expect(_ what: String, _ ok: Bool) { if !ok { notes.append("\(what): \(html())") } }53 ed.setDocument(RichText.attributed(fromPlain: "un\ndeux"))54 ed.selection = NSRange(location: 0, length: 7)55 ed.toggleList(ordered: false)56 expect("list", html() == "<ul><li>un</li><li>deux</li></ul>" && ed.block.kind == .bullet)57 ed.selection = NSRange(location: 7, length: 0)58 ed.simulateTyping("\ntrois")59 expect("Return continues the list", html() == "<ul><li>un</li><li>deux</li><li>trois</li></ul>")60 ed.indent(1)61 expect("indent", html() == "<ul><li>un</li><li>deux<ul><li>trois</li></ul></li></ul>")62 ed.simulateTyping("\n\n\n")63 expect("Return in an empty item goes one level out, then leaves the list", ed.block == .body && html() == "<ul><li>un</li><li>deux<ul><li>trois</li></ul></li></ul><div><br></div>")64 ed.setHeading(1)65 ed.simulateTyping("Titre\ncorps")66 expect("heading then body after Return", html().hasSuffix("<h1>Titre</h1><div>corps</div>"))67 ed.toggle(.bold)68 ed.simulateTyping(" gras")69 ed.toggle(.bold)70 ed.simulateTyping(" fin")71 expect("bold typed from the insertion point", html().hasSuffix("<div>corps<b> gras</b> fin</div>"))72 let s = ed.storage.string as NSString73 ed.selection = s.range(of: "fin")74 ed.setLink(RichImport.normalizedLink("example.org/a"), text: "le lien")75 expect("link inserted over the selection", html().hasSuffix("<a href=\"https://example.org/a\" rel=\"noopener noreferrer\">le lien</a></div>"))76 ed.selection = NSRange(location: ed.storage.length - 2, length: 0)77 let seen = ed.linkAtSelection == "https://example.org/a" && ed.linkText() == "le lien"78 ed.setLink("mailto:a@b.co", text: "écrire")79 expect("link edited from an insertion point inside it", seen && html().hasSuffix("<a href=\"mailto:a@b.co\" rel=\"noopener noreferrer\">écrire</a></div>"))80 ed.selection = NSRange(location: ed.storage.length - 2, length: 0)81 ed.setLink(nil)82 expect("link removed", html().hasSuffix("<div>corps<b> gras</b> écrire</div>") && RichImport.normalizedLink("javascript:alert(1)") == nil && RichImport.normalizedLink("a@b.co") == "mailto:a@b.co")83 // one user action = one undo step. In the app the undo manager groups by event; here each action is grouped by hand.84 ed.undo.removeAllActions()85 ed.undo.groupsByEvent = false86 func act(_ body: () -> Void) { ed.undo.beginUndoGrouping(); body(); ed.undo.endUndoGrouping() }87 ed.selection = (ed.storage.string as NSString).range(of: "corps gras écrire")88 act { ed.toggleQuote() }89 act { ed.clearFormatting() }90 expect("clear formatting", html().hasSuffix("<h1>Titre</h1><div>corps gras écrire</div>"))91 ed.undoEdit()92 expect("undo", html().hasSuffix("<blockquote style=\"margin:0 0 0 .8ex;border-left:2px solid #999;padding-left:1ex\"><div>corps<b> gras</b> écrire</div></blockquote>"))93 ed.redoEdit()94 expect("redo", html().hasSuffix("<h1>Titre</h1><div>corps gras écrire</div>"))95 ed.undo.removeAllActions()96 ed.undo.groupsByEvent = true97 ed.selection = NSRange(location: 3, length: 0)98 ed.simulateBackspace()99 expect("Backspace at the start of an item leaves the list", html().hasPrefix("<ul><li>un</li></ul><div>deux</div><ul><li>trois</li></ul>"))100 // what a copy writes (the composer's own HTML) pasted back, then pasted as plain text — without touching the system pasteboard101 let piece = RichText.semantic(ed.storage)102 ed.selection = NSRange(location: ed.storage.length, length: 0)103 ed.handle(.rich(RichHTML.parse(RichHTML.html(from: piece), mode: .paste).text))104 expect("pasting the composer's own HTML keeps the structure", html().components(separatedBy: "<h1>Titre</h1>").count == 3 && html().components(separatedBy: "<ul><li>trois</li></ul>").count == 3)105 ed.handle(.plain(RichHTML.plainText(from: piece)))106 expect("pasting plain text brings no formatting", html().components(separatedBy: "<h1>").count == 3 && html().components(separatedBy: "Titre").count == 4)107 step("editor: lists, Return / Backspace rules, headings, marks, links, clear, undo / redo, paste rich and plain", notes.isEmpty, notes.joined(separator: " | "))108 }109110 // --- preferences: the undo delay comes from the server111 await center.load(force: true)112 await setPrefs(undo: 0)113 let fresh = try? await center.freshPrefs()114 step("preferences read from the server", fresh?.undoSeconds == 0 && center.prefsKnown && !center.nextUnavailable, "undo \(fresh?.undoSeconds ?? -1) next \(center.nextUnavailable) error \(center.lastError ?? "-")")115 step("sendable addresses with their server ids (mailboxes and alias)", center.addressId(for: a.address) != nil && center.addresses.contains { $0.kind == "alias" && $0.isSendable }, "\(center.addresses.map(\.address))")116117 // --- 1. rich message with inline image + attachment, A → B, verified at reception118 let richSubject = "Riche \(run)"119 let richHTML = "<h2>Titre \(run)</h2><div>Bonjour <b>gras</b>, <i>italique</i>, <u>souligné</u>, <s>barré</s> et <code>code</code> — <a href=\"https://example.org/\(run)\">un lien</a>.</div><ul><li>un<ul><li>un-a</li></ul></li><li>deux</li></ul><ol><li>premier</li></ol><blockquote><div>cité 日本語 👩🏽💻</div></blockquote><div>Image :</div>"120 var sentHTML = ""121 if let c = await composer(in: a.id) {122 c.to = [toB]; c.subject = richSubject123 c.editor.setDocument(RichHTML.parse(richHTML, mode: .paste).text)124 let inline = await addInline(c)125 c.addAttachment(name: "note-\(run).txt", type: "text/plain", data: Data("pièce jointe \(run)".utf8))126 let m = c.currentMessage()127 sentHTML = m.html ?? ""128 let cid = m.attachments.first { $0.inline }?.cid ?? "?"129 step("rich text → clean HTML + text alternative, inline image as cid", inline && sentHTML.hasPrefix(String(richHTML.replacingOccurrences(of: "<a href=\"https://example.org/\(run)\">", with: "<a href=\"https://example.org/\(run)\" rel=\"noopener noreferrer\">").replacingOccurrences(of: "<blockquote>", with: "<blockquote style=\"margin:0 0 0 .8ex;border-left:2px solid #999;padding-left:1ex\">").dropLast(6)))130 && sentHTML.hasSuffix("<div>Image :<img src=\"cid:\(cid)\" alt=\"graphique.png\"></div>") && m.text.contains("• un\n • un-a\n• deux\n1. premier\n> cité") && m.attachments.count == 2131 && HTMLSanitizer.sanitizeForQuoting(sentHTML, availableCIDs: [cid]).html == sentHTML, sentHTML)132 let result = await c.deliver(.now)133 var accepted = false134 if case .accepted(let o) = result { accepted = ["sent", "delivered", "queued"].contains(o.outbound.status) }135 let leftLocally = await stored(c.id)136 step("send through /api/v1 (no hold with a 0 s delay): taken by the server", accepted && leftLocally == nil, "\(result) status \(c.status)")137 model.composerClosed(c.id)138 } else { step("rich text → clean HTML + text alternative, inline image as cid", false, "no composer") }139 var received: EmailSummary?140 if let mail = await arrives(eb, richSubject), let body = try? await eb.body(for: mail.id) {141 received = mail142 let html = body.html ?? ""143 let image = body.attachments.first { $0.cid != nil && $0.type.hasPrefix("image/") }144 let cidOK = image?.cid.map { html.contains("cid:\(HTMLSanitizer.normalizedCID($0))") } ?? false145 step("received: HTML structure, cid part, attachment, text alternative",146 html.contains("<h2>Titre \(run)</h2>") && html.contains("<b>gras</b>") && html.contains("<u>souligné</u>") && html.contains("<ul><li>un<ul><li>un-a</li></ul></li><li>deux</li></ul>") && html.contains("<ol><li>premier</li></ol>")147 && html.contains("<blockquote") && html.contains("href=\"https://example.org/\(run)\"") && html.contains("日本語 👩🏽💻") && cidOK && image?.disposition == "inline"148 && body.attachments.contains { $0.name == "note-\(run).txt" } && (body.text ?? "").contains("• un") && (body.text ?? "").contains("[image: graphique.png]"),149 "parts \(body.attachments.map { "\($0.name ?? "-")/\($0.type)/\($0.disposition ?? "-")/\($0.cid ?? "-")" }) html \(html.prefix(400))")150 } else { step("received: HTML structure, cid part, attachment, text alternative", false, "not received") }151152 // --- 2. reply: the quoted original is never touched (draft closed and reopened, then sent — outbox path, no rewriting anywhere)153 if let mail = received, let c = await composer(.reply(mail), in: b.id) {154 let quote = c.currentMessage().quotedHTML ?? ""155 c.insertText("Réponse \(run) ")156 c.editor.selection = NSRange(location: 0, length: 7)157 c.editor.toggle(.bold)158 await c.save()159 let before = c.currentMessage()160 let id = c.id161 model.composerClosed(id)162 let again = await model.restoreComposer(id: id)163 let after = again?.currentMessage()164 let inlineKept = after?.attachments.contains { $0.inline && $0.blobId != nil } == true && quote.contains("cid:")165 step("reply: quote kept byte for byte through save and reopen, its inline image re-attached", !quote.isEmpty && quote.hasPrefix(OutgoingMessage.quoteBlockOpen) && after?.quotedHTML == quote && after?.fullHTML == before.fullHTML166 && after?.html == "<div><b>Réponse</b> \(run) </div>" && inlineKept && again?.hasQuote == true, "quote \(quote.count) bytes, html \(after?.html ?? "-") inline \(inlineKept)")167 if let again {168 let state = await again.send()169 model.composerClosed(id)170 if state == .accepted, let back = await arrives(ea, "Re: \(richSubject)"), let body = try? await ea.body(for: back.id) {171 step("reply received: the quote arrives byte for byte", (body.html ?? "").hasSuffix(quote) && (body.html ?? "").hasPrefix("<div><b>Réponse</b>") && back.inReplyTo == mail.messageId, "suffix \((body.html ?? "").hasSuffix(quote)) inReplyTo \(back.inReplyTo)")172 } else { step("reply received: the quote arrives byte for byte", false, "state \(state)") }173 }174 } else { step("reply: quote kept byte for byte through save and reopen, its inline image re-attached", false, "nothing to reply to") }175176 // --- 3. draft closed and reopened: from the device, then from the server copy alone177 if let c = await composer(in: a.id) {178 c.to = [toB]; c.subject = "Brouillon \(run)"179 c.editor.setDocument(RichHTML.parse(richHTML, mode: .paste).text)180 _ = await addInline(c)181 c.addAttachment(name: "annexe-\(run).txt", type: "text/plain", data: Data("annexe".utf8))182 c.edited()183 let wasSaving = c.status == .saving184 await c.save()185 let html = c.currentMessage().html ?? "", id = c.id, serverId = c.item.serverEmailId186 step("draft: states « Enregistrement… » then « Enregistré » (on the server)", wasSaving && c.status == .savedOnServer && serverId != nil, "status \(c.status)")187 model.composerClosed(id)188 let local = await model.restoreComposer(id: id)189 let lm = local?.currentMessage()190 step("draft reopened from the device: same HTML, inline image and attachment", lm?.html == html && lm?.attachments.count == 2 && !RichText.cids(in: local?.editor.storage ?? NSAttributedString()).isEmpty && local?.files.count == 1, "html equal \(lm?.html == html)")191 // a draft another device edits: its server copy is replaced under this one → both kept, said in the composer192 if let local, let serverId {193 await ea.destroy(ids: [serverId])194 local.insertText("suite ")195 await local.save()196 step("draft conflict from another device is said in the composer", local.conflictNotice && local.item.serverEmailId != nil && local.item.serverEmailId != serverId, "notice \(local.conflictNotice)")197 }198 // the server copy alone (as on a second device): the local item goes, the draft is adopted from Drafts199 let finalHTML = local?.currentMessage().html ?? "", finalServer = local?.item.serverEmailId200 model.composerClosed(id)201 try? await store.deleteOutbox(id)202 if let finalServer, (try? await ea.ensureCached(ids: [finalServer])) != nil, let email = (try? await store.email(a.id, id: finalServer)) ?? nil, let remote = await composer(.serverDraft(email), in: a.id) {203 let rm = remote.currentMessage()204 let loaded = remote.editor.storage.string.contains(RichText.attachmentCharacter)205 step("draft reopened from the server copy: editable rich text, same HTML, parts by blob", rm.html == finalHTML && rm.quotedHTML == nil && rm.attachments.count == 2 && rm.attachments.allSatisfy { $0.blobId != nil } && rm.attachments.contains { $0.inline && $0.cid != nil } && loaded,206 "html equal \(rm.html == finalHTML) atts \(rm.attachments.map { "\($0.name)/\($0.inline)/\($0.blobId != nil)" })")207 await remote.discard(); model.composerClosed(remote.id)208 } else { step("draft reopened from the server copy: editable rich text, same HTML, parts by blob", false, "server draft not found") }209 } else { step("draft: states « Enregistrement… » then « Enregistré » (on the server)", false, "no composer") }210211 // --- 4. drafts the server wrote (as the webmail does): one the composer can edit, one it must keep whole212 func serverDraft(_ subject: String, html: String) async -> EmailSummary? {213 let body: JSONValue = ["from": .string(a.address), "to": [["email": .string(b.address)]], "subject": .string(subject), "html": .string(html), "draft": true]214 guard (try? await model.api.json("POST", "/api/v1/messages/send", body: body, headers: ["Idempotency-Key": "selftest-\(run)-\(subject.hashValue)"])) != nil else { return nil }215 var f = SearchFilter()216 f.subject = subject217 f.inMailbox = try? await ea.mailboxId(role: .drafts)218 var found: EmailSummary?219 _ = await wait(15) { found = (try? await ea.search(f))?.results.first { $0.subject == subject }; return found != nil }220 if let found { try? await ea.ensureCached(ids: [found.id]) }221 return found222 }223 if let e = await serverDraft("Webmail \(run)", html: "<p>Bonjour,</p><p>Voici <strong>trois</strong> <em>points</em> :</p><ul><li>un</li><li>deux</li></ul><p>Merci</p>"), let c = await composer(.serverDraft(e), in: a.id) {224 let stored = (try? await ea.body(for: e.id))?.html ?? ""225 let m = c.currentMessage()226 let blocks = RichText.paragraphRanges(in: c.editor.storage.string as NSString).map { RichText.block(ofParagraph: $0, in: c.editor.storage).rawValue }227 step("draft written by the server (webmail-like) reopens as editable rich text, nothing lost", c.editor.storage.string == "Bonjour,\nVoici trois points :\nun\ndeux\nMerci" && blocks == ["p", "p", "ul1", "ul1", "p"]228 && c.editor.storage.attribute(RichKey.bold, at: 15, effectiveRange: nil) != nil && !c.hasQuote && m.text.contains("• un") && !stored.isEmpty, "text \(c.editor.storage.string.debugDescription) blocks \(blocks) stored \(stored)")229 await c.discard(); model.composerClosed(c.id)230 } else { step("draft written by the server (webmail-like) reopens as editable rich text, nothing lost", false, "no server draft") }231 if let e = await serverDraft("Tableau \(run)", html: "<p>Avant</p><table border=\"1\"><tr><td>a</td><td>b</td></tr></table>"), let c = await composer(.serverDraft(e), in: a.id) {232 let stored = (try? await ea.body(for: e.id))?.html ?? ""233 c.insertText("Ajout \(run)")234 let m = c.currentMessage()235 step("draft the composer cannot represent (a table) is kept whole under the editable part", c.hasQuote && !c.quoteIsOriginal && m.quotedHTML == stored && stored.contains("<table") && m.fullHTML == "<div>Ajout \(run)</div>" + stored, "stored \(stored) full \(m.fullHTML ?? "-")")236 await c.discard(); model.composerClosed(c.id)237 } else { step("draft the composer cannot represent (a table) is kept whole under the editable part", false, "no server draft") }238239 // --- 5. offline: written and sent without the server, queued in the outbox, delivered once when it is back240 let realURL = model.api.baseURL241 let offlineSubject = "Hors ligne \(run)"242 if let c = await composer(in: a.id) {243 model.api.baseURL = URL(string: "http://127.0.0.1:9")! // nothing listens there: every request fails as « unreachable »244 model.isOnline = false245 c.to = [toB]; c.subject = offlineSubject246 c.insertText("Écrit hors ligne \(run)")247 c.editor.selection = NSRange(location: 0, length: 5)248 c.editor.toggle(.italic)249 await c.save()250 let savedItem = await stored(c.id)251 let kept = c.status == .savedLocally && savedItem?.message.html == "<div><i>Écrit</i> hors ligne \(run)</div>"252 var refusedSchedule = false253 if case .failed = await c.deliver(.later(Date().addingTimeInterval(3600))) { let st = await stored(c.id); refusedSchedule = c.status != .sending && st?.state == .draft }254 let result = await c.deliver(.now)255 var queued = false256 if case .queuedOffline = result { let st = await stored(c.id); queued = st?.state == .queuedOffline }257 step("offline: « conservé sur cet appareil », no schedule without the server, send queues in the outbox", kept && refusedSchedule && queued, "kept \(kept) schedule refused \(refusedSchedule) result \(result) status \(c.status)")258 model.composerClosed(c.id)259 model.api.baseURL = realURL260 model.isOnline = true261 if let item = await stored(c.id) { await model.retry(item) }262 let mail = await arrives(eb, offlineSubject)263 try? await Task.sleep(for: .seconds(3))264 await ea.flushOutbox()265 let count = await inbox(eb, offlineSubject).count266 let finalItem = await stored(c.id)267 step("offline: delivered exactly once after reconnection", mail != nil && count == 1 && finalItem?.state == .accepted, "count \(count) state \(String(describing: finalItem?.state))")268 } else { step("offline: « conservé sur cet appareil », no schedule without the server, send queues in the outbox", false, "no composer") }269 model.api.baseURL = realURL270 model.isOnline = true271272 // --- 6. send later, change the time (the message comes back to the composer with its attachment), cancel273 let laterSubject = "Plus tard \(run)"274 if let c = await composer(in: a.id) {275 c.to = [toB]; c.subject = laterSubject276 c.insertText("Programmé \(run)")277 c.addAttachment(name: "plus-tard.txt", type: "text/plain", data: Data("plus tard".utf8))278 let first = await c.deliver(.later(Date().addingTimeInterval(3600)))279 model.composerClosed(c.id)280 if case .scheduled(let o) = first {281 let listed = ((try? await model.api.scheduledSends()) ?? []).contains { $0.id == o.id }282 let reopenedId = await center.undo(o.id, open: false)283 let reopened = reopenedId.flatMap { model.composers[$0] }284 let rm = reopened?.currentMessage()285 let gone = !((try? await model.api.scheduledSends()) ?? []).contains { $0.id == o.id }286 step("send later: listed in « Programmés »; « Modifier » brings it back with its attachment", listed && gone && rm?.subject == laterSubject && rm?.text == "Programmé \(run)" && rm?.attachments.first?.name == "plus-tard.txt" && rm?.attachments.first?.blobId != nil,287 "listed \(listed) gone \(gone) atts \(rm?.attachments.map { "\($0.name)/\($0.blobId != nil)" } ?? [])")288 if let reopened {289 let second = await reopened.deliver(.later(Date().addingTimeInterval(7200)))290 model.composerClosed(reopened.id)291 if case .scheduled(let o2) = second {292 let at = ((try? await model.api.scheduledSends()) ?? []).first { $0.id == o2.id }?.sendAt293 let cancelled = (try? await model.api.cancelScheduled(id: o2.id))?.status == "cancelled"294 let drafts = (try? await ea.mailboxId(role: .drafts)) ?? nil295 var f = SearchFilter(); f.subject = laterSubject; f.inMailbox = drafts296 try? await ea.syncNowAndWait()297 let leftovers = ((try? await ea.search(f))?.results ?? []).count298 step("send later: rescheduled (+2 h), then cancelled — nothing queued, no draft left behind", o2.id != o.id && (at.map { abs($0.timeIntervalSinceNow - 7200) < 120 } ?? false) && cancelled && leftovers == 0, "at \(String(describing: at)) cancelled \(cancelled) drafts left \(leftovers)")299 } else { step("send later: rescheduled (+2 h), then cancelled — nothing queued, no draft left behind", false, "\(second)") }300 }301 } else { step("send later: listed in « Programmés »; « Modifier » brings it back with its attachment", false, "\(first) \(c.status)") }302 }303304 // --- 7. undo send inside the window: the server holds, the recipient never receives, the composer reopens with everything305 let undoSubject = "Annulé \(run)"306 await setPrefs(undo: 20)307 if let c = await composer(in: a.id) {308 c.to = [toB]; c.subject = undoSubject309 c.editor.setDocument(RichHTML.parse(richHTML, mode: .paste).text)310 _ = await addInline(c)311 c.addAttachment(name: "retenu.txt", type: "text/plain", data: Data("retenu \(run)".utf8))312 let html = c.currentMessage().html ?? ""313 let result = await c.deliver(.now)314 model.composerClosed(c.id)315 if case .held(let o) = result {316 let remaining = o.undoRemaining()317 let held = try? await center.next.heldMessage(id: o.id)318 let serverParts = held?.attachments ?? []319 let localCopy = await stored(c.id)320 step("undo send: held by the server (« Envoi dans N s »), never shown as sent", o.outbound.status == "scheduled" && remaining > 10 && remaining <= 20.5 && center.holds.contains { $0.id == o.id } && localCopy == nil321 && serverParts.count == 2 && serverParts.contains { $0.inline && $0.cid != nil } && serverParts.allSatisfy { $0.blobId != nil }, "remaining \(remaining) server parts \(serverParts.map { "\($0.name)/\($0.inline)/\($0.blobId != nil)" }) html kept by server unchanged: \(held?.html == html) status \(o.outbound.status) hold listed \(center.holds.contains { $0.id == o.id }) local copy \(localCopy.map { "\($0.state)" } ?? "none")")322 // what another device would rebuild from the server's content alone323 var fromServer = held.map { OutgoingMessage(held: $0, from: EmailAddress(email: a.address), identityId: nil) }324 let serverDoc = fromServer != nil ? RichBody.load(&fromServer!) : NSAttributedString()325 let reopenedId = await center.undo(o.id, open: false)326 let reopened = reopenedId.flatMap { model.composers[$0] }327 let rm = reopened?.currentMessage()328 let status = (try? await model.api.outbound(id: o.id))?.status329 step("undo send: composer reopens with the same content, inline image and attachment (server draft kept)", rm?.html == html && rm?.subject == undoSubject && rm?.to.first?.email == b.address && rm?.attachments.count == 2 && rm?.attachments.allSatisfy { $0.blobId != nil } == true330 && reopened?.item.serverEmailId == held?.emailId && held?.emailId != nil && status == "cancelled" && center.holds.isEmpty && serverDoc.string.contains("Titre \(run)") && fromServer?.attachments.count == 2,331 "status \(status ?? "-") html equal \(rm?.html == html) atts \(rm?.attachments.map { "\($0.name)/\($0.blobId != nil)" } ?? []) server-only text \(serverDoc.string.prefix(40).debugDescription)")332 try? await Task.sleep(for: .seconds(max(1, o.undoRemaining() + 6)))333 try? await eb.syncNowAndWait()334 let leaked = await inbox(eb, undoSubject).count335 step("undo send: the recipient never receives the message", leaked == 0, "received \(leaked)")336 if let reopened { await reopened.discard(); model.composerClosed(reopened.id) }337 } else { step("undo send: held by the server (« Envoi dans N s »), never shown as sent", false, "\(result) \(c.status)") }338 }339340 // --- 8. undo outside the window: too late, delivered exactly once341 let lateSubject = "Trop tard \(run)"342 await setPrefs(undo: 5)343 if let c = await composer(in: a.id) {344 c.to = [toB]; c.subject = lateSubject345 c.insertText("Parti \(run)")346 let result = await c.deliver(.now)347 model.composerClosed(c.id)348 if case .held(let o) = result {349 try? await Task.sleep(for: .seconds(o.undoRemaining() + 4))350 let reopened = await center.undo(o.id, open: false)351 let mail = await arrives(eb, lateSubject)352 try? await Task.sleep(for: .seconds(4))353 let count = await inbox(eb, lateSubject).count354 let status = (try? await model.api.outbound(id: o.id))?.status ?? "-"355 step("undo after the window: refused (« trop tard »), delivered exactly once", reopened == nil && mail != nil && count == 1 && ["sent", "delivered"].contains(status) && model.toast?.kind == .error, "reopened \(reopened ?? "-") count \(count) status \(status) toast \(model.toast?.message ?? "-")")356 } else { step("undo after the window: refused (« trop tard »), delivered exactly once", false, "\(result)") }357 }358359 // --- 9. sensitive recipients: nothing leaves without an explicit confirmation360 let sensitiveSubject = "Sensible \(run)"361 await setPrefs(undo: 0, sensitive: [b.address.uppercased()])362 if let c = await composer(in: a.id) {363 c.to = [toB]; c.subject = sensitiveSubject364 c.insertText("Confidentiel \(run)")365 let first = await c.deliver(.now)366 var asked: [String] = []367 if case .needsConfirmation(let r) = first { asked = r }368 let scheduledNow = (try? await model.api.scheduledSends()) ?? [], draftItem = await stored(c.id)369 let nothingQueued = !scheduledNow.contains { $0.recipients.contains { $0.address == b.address } } && draftItem?.state == .draft && c.status != .sending370 try? await Task.sleep(for: .seconds(4))371 let notSent = await inbox(eb, sensitiveSubject).isEmpty372 let second = await c.deliver(.now, confirmSensitive: true)373 var accepted = false374 if case .accepted = second { accepted = true }375 model.composerClosed(c.id)376 let mail = await arrives(eb, sensitiveSubject)377 step("sensitive recipient: the server asks, nothing is queued; sent only after the confirmation", asked == [b.address.lowercased()] && center.prefs.sensitiveRecipients(among: [b.address]) == [b.address] && nothingQueued && notSent && accepted && mail != nil,378 "asked \(asked) queued-nothing \(nothingQueued) not sent \(notSent) then \(second)")379 }380 await setPrefs(undo: 0)381382 // --- 10. signatures: default per address and for replies, swapped with the sender, never when edited383 let aliasSender = model.senders.first { $0.isAlias && $0.account == a.id }384 if let addressA = center.addressId(for: a.address) {385 await center.saveSignature(id: nil, SignatureContent(name: "Travail \(run)", html: "<div><b>Signature</b> \(run)</div><div><a href=\"https://spboucher.ai\">spboucher.ai</a></div>", text: "Signature \(run)\nspboucher.ai", defaultFor: [addressA], defaultForReplies: []))386 await center.saveSignature(id: nil, SignatureContent(name: "Réponse \(run)", html: "", text: "Courte \(run)", defaultFor: [], defaultForReplies: [addressA]))387 let created = center.signatures.filter { $0.name.hasSuffix(run) && !$0.isReadOnly && !NextStore.isLocal($0.id) }388 var ok = created.count == 2, detail = "created \(created.map(\.name)) error \(center.lastError ?? "-")"389 if let c = await composer(in: a.id), let primary = c.sender {390 await c.prepare()391 let fresh = c.plainText392 c.insertText("Texte \(run)")393 let html = c.currentMessage().html ?? ""394 ok = ok && fresh == "\n\n-- \nSignature \(run)\nspboucher.ai" && html.hasSuffix("<div class=\"spm-signature\"><div>-- </div><div><b>Signature</b> \(run)</div><div><a href=\"https://spboucher.ai\" rel=\"noopener noreferrer\">spboucher.ai</a></div></div>") && c.currentSignatureId == created.first(where: { $0.name.hasPrefix("Travail") })?.id395 if let alias = aliasSender {396 c.senderId = alias.id; c.senderChanged(from: primary.id)397 let onAlias = c.plainText398 c.senderId = primary.id; c.senderChanged(from: alias.id)399 let back = c.plainText400 ok = ok && onAlias == "Texte \(run)\n\n-- \n\(alias.signature)" && back == "Texte \(run)\n\n-- \nSignature \(run)\nspboucher.ai" && !alias.signature.isEmpty401 // an edited signature stays as the person left it402 c.editor.selection = NSRange(location: c.editor.storage.length, length: 0)403 c.insertText(" (modifiée)")404 c.senderId = alias.id; c.senderChanged(from: primary.id)405 ok = ok && c.plainText == back + " (modifiée)"406 detail += " alias \(onAlias.debugDescription) edited \(c.plainText.debugDescription)"407 }408 detail += " fresh \(fresh.debugDescription)"409 await c.discard(); model.composerClosed(c.id)410 } else { ok = false }411 if received != nil, let mail = await inbox(ea, "Re: \(richSubject)").first, let r = await composer(.reply(mail), in: a.id) {412 await r.prepare()413 ok = ok && r.plainText == "\n\n-- \nCourte \(run)" && r.hasQuote414 detail += " reply \(r.plainText.debugDescription)"415 await r.discard(); model.composerClosed(r.id)416 }417 step("signatures: default per address and for replies, swapped with the sender, an edited one left alone", ok, detail)418 for s in created { await center.deleteSignature(id: s.id) }419 } else { step("signatures: default per address and for replies, swapped with the sender, an edited one left alone", false, "no address id") }420421 // --- 11. alias sender through /api/v1: only addresses the server lists; From is the alias at reception422 let aliasSubject = "Alias \(run)"423 if let alias = aliasSender, let c = await composer(in: a.id) {424 c.senderId = alias.id425 if let primary = model.senders.first(where: { $0.account == a.id && !$0.isAlias }) { c.senderChanged(from: primary.id) }426 c.to = [toB]; c.subject = aliasSubject427 c.insertText("Depuis l’alias \(run)")428 let offered = c.availableSenders.allSatisfy { s in center.addresses.contains { $0.address.lowercased() == s.email.lowercased() && $0.isSendable } }429 let result = await c.deliver(.now)430 model.composerClosed(c.id)431 let mail = await arrives(eb, aliasSubject)432 step("alias sender: offered from the server's sendable addresses only; received From the alias", offered && mail?.from.first?.email.lowercased() == alias.email.lowercased(), "\(result) from \(mail?.from.first?.email ?? "-") offered \(offered)")433 } else { step("alias sender: offered from the server's sendable addresses only; received From the alias", false, "no alias") }434435 // --- 12. snippets: created on the server, expanded by `;shortcut` while typing, picked by hand436 await center.saveSnippet(id: nil, SnippetContent(name: "Merci \(run)", shortcut: "st\(run)", subject: "Objet d’extrait", html: "<div>Merci <b>beaucoup</b></div><ul><li>point</li></ul>", text: "Merci beaucoup\n• point"))437 if let snippet = center.snippets.first(where: { $0.shortcut == "st\(run)" && !NextStore.isLocal($0.id) }), let c = await composer(in: a.id) {438 c.editor.setDocument(RichText.attributed(fromPlain: "Bonjour"))439 c.editor.selection = NSRange(location: c.editor.storage.length, length: 0)440 c.editor.simulateTyping(" ;st\(run) ") // what the text view does when the person types441 let expanded = c.currentMessage().html ?? ""442 c.editor.undoEdit()443 let undone = c.plainText444 step("snippets: `;shortcut` expands while typing (undoable), subject proposed", expanded == "<div>Bonjour Merci <b>beaucoup</b></div><ul><li>point </li></ul>" && c.subject == "Objet d’extrait" && undone == "Bonjour ;st\(run) ", "html \(expanded) undone \(undone.debugDescription) subject \(c.subject)")445 await c.discard(); model.composerClosed(c.id)446 await center.deleteSnippet(id: snippet.id)447 } else { step("snippets: `;shortcut` expands while typing (undoable), subject proposed", false, "snippet not created: \(center.lastError ?? "-") \(center.snippets.map { $0.shortcut ?? "-" })") }448449 // --- 13. recipients: server autocomplete, then the device alone when offline450 let online = await center.suggest("apple-b", taken: [])451 model.api.baseURL = URL(string: "http://127.0.0.1:9")!; model.isOnline = false452 let offline = await center.suggest("apple-b", taken: [])453 model.api.baseURL = realURL; model.isOnline = true454 let taken = await center.suggest("apple-b", taken: [b.address.lowercased()])455 step("recipients: autocomplete from the server, from the device when offline, never a recipient already there", online.contains { $0.email.lowercased() == b.address.lowercased() } && offline.contains { $0.email.lowercased() == b.address.lowercased() }456 && !taken.contains { $0.email.lowercased() == b.address.lowercased() }, "online \(online.map(\.email)) offline \(offline.map(\.email))")457458 // --- 14. the composer on screen (window on macOS, sheet on iOS): opened through the interface, filled through the public entry points459 await model.switchAccount(a.id)460 if let c = await model.openComposer(to: [toB], subject: "À l’écran \(run)", body: "Écrit par un autre module.") {461 c.insertText(" Suite.", replacingSelection: false)462 let shown = await wait(8) { c.editor.textView != nil && c.editor.contentHeight > 0 }463 c.editor.selection = NSRange(location: 0, length: 5)464 c.editor.toggle(.bold); c.editor.toggleList(ordered: false)465 try? "composer".write(to: progressURL, atomically: true, encoding: .utf8)466 try? await Task.sleep(for: .seconds(4))467 step("on screen: editor mounted in the composer, entry points for other features (openComposer, insertText, currentPlainText, setSubject)",468 shown && c.currentPlainText.hasPrefix("• Écrit par un autre module. Suite.") && c.subject == "À l’écran \(run)" && c.editor.activeMarks.contains(.bold) && c.editor.block.kind == .bullet, "shown \(shown) text \(c.currentPlainText.debugDescription)")469 await c.discard(); model.composerClosed(c.id); model.composeRequest = nil470 } else { step("on screen: editor mounted in the composer, entry points for other features (openComposer, insertText, currentPlainText, setSubject)", false, "no composer") }471 await model.switchAccount(b.id)472 }473}474#endif475