SPB Git

Repository Public

SelfTest.swift 34.6 KB 449 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/SelfTest.swift3// Description: DEBUG-only end-to-end self-test of the running app against a development backend (`-spmSelfTest YES` with `-spmBaseURL` / `-spmDevToken`):4// launch → sync → compose → send → receive → open → isolated renderer checks → reply → flag/archive → template studio (replayed generation, preview,5// save, versions, send by template) → unified inbox → alias identity → encrypted cache → sign out. Writes a JSON report in the app container.6#if DEBUG7import SPMailCore8import SwiftUI9import WebKit1011@MainActor12enum SelfTest {13    static var reportURL: URL { AppConfig.cacheDirectory.deletingLastPathComponent().appendingPathComponent("SPMail-selftest.json") }14    static var progressURL: URL { AppConfig.cacheDirectory.deletingLastPathComponent().appendingPathComponent("SPMail-selftest-progress.txt") }1516    static func wait(_ seconds: Double, _ condition: () async -> Bool) async -> Bool {17        let end = Date().addingTimeInterval(seconds)18        while Date() < end {19            if await condition() { return true }20            try? await Task.sleep(for: .milliseconds(300))21        }22        return await condition()23    }2425    private static var started = false2627    static func run(_ model: AppModel) async {28        guard !started else { return } // one run per process, whatever the number of windows29        started = true30        var steps: [[String: Any]] = []31        var failed = false32        func step(_ name: String, _ ok: Bool, _ detail: String = "") {33            steps.append(["step": name, "ok": ok, "detail": detail])34            if !ok { failed = true }35            try? name.write(to: progressURL, atomically: true, encoding: .utf8)36        }37        func finish() {38            let report: [String: Any] = ["ok": !failed, "passed": steps.filter { $0["ok"] as? Bool == true }.count, "total": steps.count, "steps": steps,39                                         "bundle": AppConfig.bundleId, "server": AppConfig.baseURL.absoluteString, "date": Date().formatted(.iso8601)]40            if let d = try? JSONSerialization.data(withJSONObject: report, options: [.prettyPrinted, .sortedKeys]) { try? d.write(to: reportURL) }41            try? "done".write(to: progressURL, atomically: true, encoding: .utf8)42            exit(failed ? 1 : 0)43        }44        try? FileManager.default.removeItem(at: reportURL)45        let run = String(UUID().uuidString.prefix(6)).lowercased()46        let marker = "AUTOTEST-\(run)"4748        // 1. launch with the development token (no passkey prompt)49        step("launch", await wait(30) { model.phase == .ready || model.phase == .signedOut } && model.phase == .ready, "phase \(model.phase) notice \(model.notice ?? "-") error \(model.signInError ?? "-")")50        guard model.phase == .ready, model.accounts.count >= 2, let a = model.accounts.first, let b = model.accounts.dropFirst().first else {51            step("two test mailboxes", false, "accounts \(model.accounts.count)"); finish(); return52        }53        guard a.address.hasSuffix("@stg.spboucher.ai"), b.address.hasSuffix("@stg.spboucher.ai"), a.address.hasPrefix("apple-"), b.address.hasPrefix("apple-") else {54            step("staging-only guard", false, "refusing to send from \(a.address)"); finish(); return55        }56        let savedToken = model.api.token ?? ""5758        // 2. first sync59        await model.switchAccount(a.id)60        step("sync", await wait(30) { model.mailbox(.inbox) != nil && model.mailbox(.sent) != nil && model.mailbox(.drafts) != nil }, "\(model.mailboxes.count) folders")6162        // 3. compose with rich text + attachment, send, and report the server's answer63        await model.compose(.new)64        guard let composer = model.composeRequest.flatMap({ model.composers[$0] }) else { step("compose", false); finish(); return }65        composer.to = [EmailAddress(name: "Essai B", email: b.address)]66        composer.subject = "Auto-test \(run) — été 日本語"67        var text = AttributedString("Bonjour, ceci est \(marker) ")68        var bold = AttributedString("en gras")69        bold.inlinePresentationIntent = .stronglyEmphasized70        text.append(bold)71        composer.body = text72        composer.addAttachment(name: "note-\(run).txt", type: "text/plain", data: Data("pièce \(marker)".utf8))73        composer.edited()74        step("compose", composer.canSend && composer.currentMessage().html?.contains("<b>en gras</b>") == true, composer.currentMessage().html ?? "no html")75        let state = await composer.send()76        step("send accepted by server", state == .accepted, "state \(state) \(composer.item.lastError ?? "")")77        model.composerClosed(composer.id); model.composeRequest = nil78        await model.reloadOutbox()79        step("outbox shows accepted (not delivered yet by assumption)", model.outbox.first { $0.id == composer.id }?.state == .accepted, OutboxView.stateLabel(composer.item).text)80        let deliveredOK = await wait(25) {81            await model.engines[a.id]?.refreshDelivery()82            await model.reloadOutbox()83            return model.outbox.first { $0.id == composer.id }?.delivery[b.address]?.delivered == .yes84        }85        step("per-recipient delivery status from EmailSubmission/get", deliveredOK, "\(model.outbox.first { $0.id == composer.id }?.delivery ?? [:])")8687        // 4. receive on the other mailbox (live EventSource / delta sync), open and read88        await model.switchAccount(b.id)89        let arrived = await wait(40) {90            await model.reloadThreads()91            return model.rows.contains { $0.email.subject.contains(run) }92        }93        step("receive", arrived, "\(model.rows.count) rows")94        guard let row = model.rows.first(where: { $0.email.subject.contains(run) }) else { finish(); return }95        model.selectedIds = [row.id]96        await model.open(emailId: row.id)97        let bodyOK = await wait(15) { model.bodies[row.id] != nil }98        let body = model.bodies[row.id]99        step("open message", bodyOK && body?.text?.contains(marker) == true && body?.html?.contains("<b>en gras</b>") == true && body?.attachments.first?.name == "note-\(run).txt", body?.text ?? "no body")100        if let part = body?.attachments.first, let url = try? await model.file(for: part) {101            step("attachment download", (try? String(contentsOf: url, encoding: .utf8)) == "pièce \(marker)", url.lastPathComponent)102        } else { step("attachment download", false) }103        step("marked read on open", await wait(10) { (try? await model.store?.email(b.id, id: row.id))??.isSeen == true })104        step("reader: HTML sanitised once, off the main actor, and cached", await wait(10) { model.main.reader.sanitizedHTML(row.id) != nil }, "cached \(model.main.reader.sanitizedHTML(row.id) != nil)")105        await nextSteps(model, a: a, b: b, row: row) { step($0, $1, $2) }106        try? await Task.sleep(for: .seconds(4)) // the reader stays on screen long enough for a window capture107        try? "reader".write(to: progressURL, atomically: true, encoding: .utf8)108        try? await Task.sleep(for: .seconds(4))109110        // 5. the body renderer: page JavaScript does not run, nothing loads from the network, the app can still measure the document111        if let rules = await BodyRenderer.contentRules() {112            let handler = MailImageSchemeHandler { _ in nil }113            let web = BodyRenderer.makeWebView(rules: rules, handler: handler)114            web.frame = CGRect(x: 0, y: 0, width: 400, height: 300)115            let probe = AppConfig.baseURL.appendingPathComponent("api/health/live").absoluteString + "?selftest-probe=\(run)"116            let hostile = "<p id=\"p\">x</p><script>document.title='js-ran'</script><img src=\"\(probe)\" onerror=\"document.title='js-ran'\"><link rel=\"stylesheet\" href=\"\(probe)&css=1\">"117            web.loadHTMLString("<!doctype html><html><head><title>idle</title></head><body>\(hostile)</body></html>", baseURL: nil)118            try? await Task.sleep(for: .seconds(2))119            let title = web.title ?? ""120            let height = (try? await web.callAsyncJavaScript("return document.body.scrollHeight", contentWorld: .defaultClient)) as? NSNumber121            let loaded = (try? await web.callAsyncJavaScript("const i = document.images[0]; return i ? i.naturalWidth : -1", contentWorld: .defaultClient)) as? NSNumber122            step("renderer: page JavaScript disabled", title != "js-ran", "title=\(title)")123            step("renderer: remote load blocked (see backend log for probe \(run))", loaded?.intValue == 0, "naturalWidth=\(loaded?.intValue ?? -99)")124            step("renderer: app-side height measurement works", (height?.doubleValue ?? 0) > 0, "height=\(height?.doubleValue ?? 0)")125        } else { step("renderer: content rule list compiled", false) }126        let hostile = HTMLSanitizer.sanitize("<script>x</script><img src=\"https://tracker.example/p.gif\"><a href=\"javascript:x\">l</a><p onclick=\"x\">ok</p>")127        step("sanitiser in the app build", !hostile.html.contains("script") && !hostile.html.contains("tracker") && !hostile.html.contains("onclick") && hostile.remoteImageCount == 1, hostile.html)128129        // 6. reply builder from the UI path, then discard130        await model.compose(.reply(row.email))131        if let reply = model.composeRequest.flatMap({ model.composers[$0] }) {132            let m = reply.currentMessage()133            step("reply", m.to.first?.email == a.address && m.subject.hasPrefix("Re: ") && !m.inReplyTo.isEmpty && m.quotedText?.contains(marker) == true, "to \(m.to.map(\.email)) inReplyTo \(m.inReplyTo)")134            await reply.discard(); model.composerClosed(reply.id); model.composeRequest = nil135        } else { step("reply", false) }136137        // 7. flag, search, archive138        await model.perform(.flag(true), on: [row.id])139        step("flag", (try? await model.store?.email(b.id, id: row.id))??.isFlagged == true)140        model.searchText = marker141        let found = await wait(20) { await model.runSearch(); return model.searchResults?.contains { $0.id == row.id } == true }142        step("search", found, "offline=\(model.searchIsOffline)")143        model.searchText = ""; model.searchResults = nil144        await model.perform(.archive, on: [row.id])145        step("archive: toast offers one undo action", model.toast?.action != nil && model.toast?.actionTitle != nil, model.toast?.message ?? "no toast")146        let archived = await wait(10) { guard let ar = model.mailbox(.archive) else { await model.reloadMailboxes(); return false }; return (try? await model.store?.email(b.id, id: row.id))??.mailboxIds == [ar.id] }147        step("archive", archived)148        await model.perform(.delete, on: [row.id]) // tidy: to the Trash149        await model.perform(.delete, on: [row.id]) // and gone150151        // 7b. template studio, send by template, unified inbox, alias identity (generation replayed by Scripts/dev-replay-proxy.mjs: no AI call)152        await studioSteps(model, a: a, b: b, run: run) { step($0, $1, $2) }153        await composeSteps(model, a: a, b: b, run: run) { step($0, $1, $2) } // Next composer (Sources/Shared/SelfTest+Compose.swift)154155        // 7b'. SP Mail Next features (labels, pin, snooze, reminders, search, contacts, gallery, dashboard, intelligence, vacation)156        await featureSteps(model, a: a, b: b, run: run) { step($0, $1, $2) }157158        // 7b''. integration of the three Next branches (SelfTest+Integration.swift): one store per session, writing assistant, outbox159        // follow-up of server-tracked sends, template + sensitive recipient, removed mailbox160        await integrationSteps(model, a: a, b: b, run: run) { step($0, $1, $2) }161162        // 7c. app lock: « on leaving the app » locks at once, notifications conceal content, secondary windows are gated163        let hadLock = model.settings.lockEnabled, hadDelay = model.settings.lockAfterMinutes164        model.settings.lockEnabled = true; model.settings.lockAfterMinutes = 0165        model.lock.simulateLeave()166        let lockedOnLeave = model.phase == .locked, concealed = model.lock.concealsContent167        model.phase = .ready // the self-test cannot answer Touch ID / Face ID168        model.settings.lockAfterMinutes = 5169        model.lock.simulateLeave()170        let staysOpenWithDelay = model.phase == .ready171        model.settings.lockEnabled = hadLock; model.settings.lockAfterMinutes = hadDelay172        step("lock: leaving the app locks at once (0 min), not before the delay otherwise; content concealed while locked", lockedOnLeave && concealed && staysOpenWithDelay, "locked \(lockedOnLeave) concealed \(concealed) delay \(staysOpenWithDelay)")173        step("lock: composer, message, studio and settings windows are gated",174             LockGate<EmptyView>.presentation(for: .locked, requiresSession: true) == .lock && LockGate<EmptyView>.presentation(for: .locked, requiresSession: false) == .lock175             && LockGate<EmptyView>.presentation(for: .ready, requiresSession: true) == .content && LockGate<EmptyView>.presentation(for: .signedOut, requiresSession: true) == .signedOut)176177        // 8. at rest: the body marker is not readable in the cache files178        try? await model.store?.checkpoint()179        var leaked = false180        for f in (try? FileManager.default.contentsOfDirectory(at: AppConfig.cacheDirectory, includingPropertiesForKeys: nil)) ?? [] {181            if let d = try? Data(contentsOf: f), d.range(of: Data(marker.utf8)) != nil { leaked = true }182        }183        step("cache encrypted at rest", !leaked && FileManager.default.fileExists(atPath: AppConfig.cacheDirectory.appendingPathComponent("mail.sqlite").path))184        step("token not in preferences", !(UserDefaults.standard.persistentDomain(forName: AppConfig.bundleId) ?? [:]).values.contains { ($0 as? String) == savedToken })185186        // system integration (SelfTest+System.swift): push registration, notification routing and actions, widgets, share hand-off, mailto187        await systemSteps(model, a: a, b: b, run: run) { step($0, $1, $2) }188189        // 9. sign out: session revoked server-side, cache and keys gone190        await model.signOut()191        systemSignedOutSteps(model, mailboxes: [a.id, b.id]) { step($0, $1, $2) }192        let secrets = AppConfig.secrets()193        let tokenGone = (try? secrets.read(SecretKeys.bearerToken)) == nil, keyGone = (try? secrets.read(SecretKeys.cacheKey)) == nil194        let fileGone = !FileManager.default.fileExists(atPath: AppConfig.cacheDirectory.appendingPathComponent("mail.sqlite").path)195        var revoked = false196        do { _ = try await APIClient(baseURL: AppConfig.baseURL, token: savedToken).me() } catch let e as APIError { revoked = e.isUnauthorized } catch {}197        step("sign out", model.phase == .signedOut && tokenGone && keyGone && fileGone && revoked, "phase \(model.phase) token \(tokenGone) key \(keyGone) file \(fileGone) revoked \(revoked)")198        integrationSignedOutSteps(model) { step($0, $1, $2) }199        finish()200    }201202    /// SP Mail Next: design tokens and theme, window identifiers and restoration, command palette, per-scene state, layout observer.203    static func nextSteps(_ model: AppModel, a: MeResponse.Box, b: MeResponse.Box, row: ThreadSummary, report: (String, Bool, String) -> Void) async {204        func step(_ name: String, _ ok: Bool, _ detail: String = "") { report(name, ok, detail) }205206        // theme: the preference is stored, midnight layers over dark, tokens resolve per theme207        let before = model.settings.theme208        model.settings.theme = .midnight209        var env = EnvironmentValues()210        env.colorScheme = .dark; env.spMidnight = true211        var darkEnv = EnvironmentValues()212        darkEnv.colorScheme = .dark213        let stored = UserDefaults.standard.string(forKey: "theme")214        step("theme: switch to midnight (stored, dark scheme, true-black tokens)",215             stored == "midnight" && model.settings.theme.colorScheme == .dark && env.spVariant == .midnight && darkEnv.spVariant == .dark216             && SPColor.bg.value(.midnight).rgb == 0x000000 && SPColor.bg.value(.dark).rgb == 0x141513 && SPColor.bg.value(.light).rgb == 0xf6f5f1 && SPColor.accent.value(.light).rgb == 0x2c5b4d,217             "stored \(stored ?? "-") variant \(env.spVariant)")218        model.settings.theme = before219220        // a message window: Codable identifier (state restoration), its own scene, the main window untouched221        let ref = MessageRef(account: b.id, emailId: row.id, conversation: true)222        let decoded = (try? JSONEncoder().encode(ref)).flatMap { try? JSONDecoder().decode(MessageRef.self, from: $0) }223        let detached = MailScene(app: model, detached: true)224        let opened = decoded != nil ? await detached.openDetached(decoded!) : false225        step("windows: message window opens from its restorable identifier", decoded == ref && opened && detached.reader.conversation.contains { $0.id == row.id } && detached.activeAccount == b.id && detached.reader.bodies[row.id] != nil226             && model.main.reader.focusedEmailId == row.id, "decoded \(decoded == ref) opened \(opened)")227228        // a composer window: the draft is read back from the local outbox after the in-memory composer is gone (relaunch)229        await model.compose(.new)230        if let composer = model.composeRequest.flatMap({ model.composers[$0] }) {231            model.composeRequest = nil232            composer.subject = "Brouillon restauré"233            composer.edited()234            await composer.save()235            let id = composer.id236            model.composerClosed(id)237            let restored = await model.restoreComposer(id: id)238            step("windows: composer window restores its draft from the local outbox", restored != nil && restored?.id == id && restored?.subject == "Brouillon restauré", "restored \(restored != nil)")239            if let restored { await restored.discard(); model.composerClosed(id) }240        } else { step("windows: composer window restores its draft from the local outbox", false, "no composer") }241242        // command palette: fuzzy search and scoped prefixes243        let items = CommandPalette.items(for: model.main)244        let arch = CommandPalette.search("archiv", in: items, scene: model.main)245        let trash = CommandPalette.search("#corb", in: items, scene: model.main)246        let commandsOnly = CommandPalette.search(">", in: items, scene: model.main)247        let boxes = CommandPalette.search("@", in: items, scene: model.main)248        let mailSearch = CommandPalette.search("/facture", in: items, scene: model.main)249        step("command palette: fuzzy results and scopes (> # @ /)",250             arch.first?.id == "cmd.archive" && trash.first?.kind == .folder && trash.first?.title == L("Corbeille") && !commandsOnly.isEmpty && commandsOnly.allSatisfy { $0.kind == .command }251             && boxes.map(\.title) == [a.address] && mailSearch.count == 1 && mailSearch.first?.kind == .search && CommandPalette.score("xyzq", in: "Archiver") == nil,252             "arch \(arch.first?.id ?? "-") trash \(trash.first?.title ?? "-") boxes \(boxes.map(\.title))")253254        // a second window (iPad scene): its own mailbox, folder, selection and search — same session and engines255        let second = MailScene(app: model)256        second.adopt(account: a.id)257        _ = await wait(10) { second.selection != nil }258        second.selection = .flagged259        second.didSelectSidebar()260        second.search.text = "seconde fenêtre"261        second.list.selectedIds = ["x"]262        step("scenes: a second window has independent navigation state on the shared session",263             second.currentAccount == a.id && model.main.currentAccount == b.id && second.selection == .flagged && model.main.selection != .flagged && model.main.search.text.isEmpty264             && model.main.list.selectedIds == [row.id] && second.engine === model.engines[a.id] && model.scenes.contains { $0 === second } && model.scenes.contains { $0 === model.main },265             "second \(second.currentAccount ?? "-") main \(model.main.currentAccount ?? "-") scenes \(model.scenes.count)")266        model.releaseScene(second)267268        // body height: reported by the app's layout observer in its isolated world while page JavaScript stays disabled269        if let rules = await BodyRenderer.contentRules() {270            final class Probe: NSObject, WKScriptMessageHandler {271                var heights: [Double] = []272                func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { if let h = (message.body as? NSNumber)?.doubleValue { heights.append(h) } }273            }274            let probe = Probe()275            let web = BodyRenderer.makeWebView(rules: rules, handler: MailImageSchemeHandler { _ in nil }, heightObserver: probe)276            web.frame = CGRect(x: 0, y: 0, width: 400, height: 100)277            web.loadHTMLString(HTMLSanitizer.document(body: "<title>idle</title><script>document.title='js-ran'</script><div style=\"height:900px\">x</div>", dark: false), baseURL: nil)278            let reported = await wait(8) { (probe.heights.last ?? 0) >= 900 }279            step("renderer: height from the layout observer, page JavaScript still disabled", reported && web.title != "js-ran", "heights \(probe.heights) title \(web.title ?? "-")")280            web.configuration.userContentController.removeScriptMessageHandler(forName: BodyRenderer.heightMessage, contentWorld: .defaultClient)281        } else { step("renderer: height from the layout observer, page JavaScript still disabled", false, "no rules") }282    }283284    static func studioSteps(_ model: AppModel, a: MeResponse.Box, b: MeResponse.Box, run: String, report: (String, Bool, String) -> Void) async {285        func step(_ name: String, _ ok: Bool, _ detail: String = "") { report(name, ok, detail) }286        let studio = model.studio287        // open the studio (its own window on macOS, a full-screen cover on iOS) and load the library288        model.studioRequest += 1289        step("studio: open, library loaded", await wait(20) { studio.loaded }, "\(studio.templates.count) templates, AI configured \(studio.aiConfigured), error \(studio.loadError ?? "-")")290        let before = studio.templates.count291292        // create with the replayed stream, watching the progress the server reports293        studio.showGenerator = true294        let starter = StudioText.starters[0]295        studio.brief = starter.fr; studio.briefCategory = starter.category; studio.language = "fr"296        studio.brand.name = "Auto-test \(run)"; studio.brand.accent = "#4f46e5"297        var maxChars = 0, sawRunning = false, model_ = ""298        let watcher = Task { @MainActor in299            while !Task.isCancelled {300                if studio.generation.isRunning { sawRunning = true; maxChars = max(maxChars, studio.generation.chars); model_ = studio.generation.model.isEmpty ? model_ : studio.generation.model }301                try? await Task.sleep(for: .milliseconds(40))302            }303        }304        await studio.generate()305        watcher.cancel()306        guard let editor = studio.current else { step("studio: create with AI (replayed stream)", false, "phase \(studio.generation.phase)"); return }307        step("studio: create with AI (replayed stream)", sawRunning && maxChars >= 400 && !model_.isEmpty && studio.templates.count == before + 1 && !studio.showGenerator && studio.brief.isEmpty,308             "running \(sawRunning) chars \(maxChars) model \(model_) library \(before)→\(studio.templates.count)")309        let prefs = (try? await model.api.me())?.user.prefs310        step("studio: brand kit stored under templateBrand", TemplateBrand(json: prefs?["templateBrand"] ?? .null).name == "Auto-test \(run)")311312        // editor: live preview, forced light and dark313        await editor.load()314        editor.scheme = .light315        let light = editor.previewDocument ?? ""316        editor.scheme = .dark317        let dark = editor.previewDocument ?? ""318        step("studio: editor preview light / dark", light.contains("(max-width:0)") && dark.contains("(min-width:0)") && dark.contains("Content-Security-Policy") && !dark.contains("{{") && editor.rendered?.sanitizedHTML != nil,319             "light \(light.count) dark \(dark.count) error \(editor.previewError ?? "-")")320        try? "studio-editor".write(to: progressURL, atomically: true, encoding: .utf8)321        try? await Task.sleep(for: .seconds(5)) // the editor stays on screen for a window capture322323        // library thumbnail: rendered off screen in the isolated renderer and snapshotted324        let thumb = await ThumbnailStore.shared.image(for: editor.template, api: model.api)325        step("studio: thumbnail snapshot", (thumb?.contentRatio ?? 0) > 0.02 && ThumbnailStore.shared.cached(editor.template) != nil, "content ratio \(thumb?.contentRatio ?? -1)")326327        // edit a variable: the preview follows328        guard let variable = editor.liveVariables.first(where: { !$0.name.contains("url") }) ?? editor.liveVariables.first else { step("studio: edit a variable", false, "no variable"); return }329        editor.values[variable.name] = "VALEUR-\(run)"330        await editor.renderPreview()331        step("studio: edit a variable", editor.rendered?.html.contains("VALEUR-\(run)") == true || editor.rendered?.subject.contains("VALEUR-\(run)") == true, variable.name)332333        // save → version 2 → restore version 1 → version 3334        let originalSubject = editor.subject335        editor.subject = "Auto-test \(run) {{\(variable.name)}}"336        editor.html = editor.html.replacingOccurrences(of: "</body>", with: "<script>document.title='x'</script></body>")337        let dirty = editor.isDirty338        let saved = await editor.save()339        step("studio: save makes version 2 (server sanitiser reported)", dirty && saved && !editor.isDirty && editor.template.version == 2 && editor.sanitizerNotice && !editor.html.contains("<script"), "version \(editor.template.version) error \(editor.saveError ?? "-")")340        await editor.restore(version: 1)341        step("studio: restore version 1", editor.template.version == 3 && editor.subject == originalSubject && editor.versions.map(\.version) == [2, 1], "version \(editor.template.version) versions \(editor.versions.map(\.version))")342343        // renderer isolation for template previews: page JavaScript does not run, no direct remote request, https images go through the proxy loader344        if let rules = await BodyRenderer.contentRules() {345            final class Seen: @unchecked Sendable { private let lock = NSLock(); private var urls: [String] = []; func add(_ u: String) { lock.withLock { urls.append(u) } }; var all: [String] { lock.withLock { urls } } }346            let seen = Seen()347            let api = model.api348            let handler = MailImageSchemeHandler { url in349                seen.add(url.absoluteString)350                return await TemplateRendering.loader(api: api)(url)351            }352            let web = BodyRenderer.makeWebView(rules: rules, handler: handler, passthrough: false)353            web.frame = CGRect(x: 0, y: 0, width: 600, height: 400)354            let direct = AppConfig.baseURL.appendingPathComponent("api/health/live").absoluteString + "?template-probe=\(run)"355            // 127.0.0.1 over https: the backend proxy refuses private destinations, so the probe proves the route without any outside request356            let hostile = "<html><head><title>idle</title><style>body{background:url(\(direct)&css=1)}</style></head><body><p>x</p><script>document.title='js-ran'</script><img id=\"a\" src=\"https://127.0.0.1/template-probe-\(run).png\" onerror=\"document.title='js-ran'\"><img id=\"b\" src=\"\(direct)\"><link rel=\"stylesheet\" href=\"\(direct)&link=1\"></body></html>"357            web.loadHTMLString(TemplatePreview.document(html: hostile, scheme: .dark), baseURL: nil)358            _ = await wait(6) { !seen.all.isEmpty }359            try? await Task.sleep(for: .seconds(1))360            let title = web.title ?? ""361            let widths = (try? await web.callAsyncJavaScript("return [...document.images].map(i => i.naturalWidth).join(',')", contentWorld: .defaultClient)) as? String362            step("template renderer: page JavaScript disabled", title != "js-ran", "title=\(title)")363            step("template renderer: https image asked through the proxy scheme only", seen.all.count == 1 && seen.all[0].hasPrefix("spmail-img://proxy/?u=https%3A%2F%2F127.0.0.1"), "\(seen.all)")364            step("template renderer: no direct load (backend log: no GET /api/health/live, one GET /api/img)", widths == "0,0", "naturalWidths=\(widths ?? "?")")365        } else { step("template renderer: content rule list compiled", false, "") }366367        // send the template from B to A: required variables enforced, honest status368        if model.senders.isEmpty { await model.loadSenders() }369        let send = TemplateSendModel(editor: editor)370        send.senderId = model.senders.first { $0.email == b.address }?.id ?? ""371        send.to = [EmailAddress(name: "Essai A", email: a.address)]372        let required = editor.template.variables.filter(\.required).map(\.name)373        send.values = [:]374        let blocked = !required.isEmpty && !send.canSend375        for v in editor.template.variables { send.values[v.name] = v.name.contains("url") ? "https://example.org/\(run)" : (v.name == variable.name ? "VALEUR-\(run)" : v.example) }376        send.subject = "Modèle auto-test \(run)"377        await send.send()378        step("studio: send template (required variables enforced, accepted by the server)", (required.isEmpty || blocked) && send.phase == .done && ["sent", "delivered"].contains(send.outcome?.status ?? ""),379             "required \(required) blocked \(blocked) phase \(send.phase) status \(send.outcome?.status ?? "-")")380        let delivered = await wait(30) { send.outcome?.status == "delivered" }381        step("studio: per-recipient delivery from the outbound status", delivered && send.outcome?.recipients.first?.status == "delivered", "\(send.outcome?.recipients.map { "\($0.address)=\($0.status)" } ?? [])")382383        // unified inbox: the message shows across mailboxes with its receiving address, and opens through the engine of ITS mailbox384        #if os(iOS)385        model.showStudio = false // the mail interface comes back in front386        try? await Task.sleep(for: .seconds(1.5))387        #endif388        model.selection = .unified(.inbox) // the split view reacts as it does to a tap on the sidebar389        try? await Task.sleep(for: .seconds(1))390        let listed = await wait(40) {391            if !model.unifiedRows.contains(where: { $0.email.subject == "Modèle auto-test \(run)" }) { await model.reloadUnified() }392            return model.unifiedRows.contains { $0.email.subject == "Modèle auto-test \(run)" }393        }394        let row = model.unifiedRows.first { $0.email.subject == "Modèle auto-test \(run)" }395        let ordered = model.unifiedRows.map(\.email.receivedAt) == model.unifiedRows.map(\.email.receivedAt).sorted(by: >)396        step("unified inbox shows it", listed && row?.account == a.id && row?.receivingAddress == a.address.lowercased() && ordered && Set(model.unifiedRows.compactMap(\.account)).count >= 1,397             "\(model.unifiedRows.count) rows, offline \(model.unifiedIsOffline), accounts \(Set(model.unifiedRows.compactMap(\.account)).count)")398        if let row {399            await model.openUnified(row)400            let opened = await wait(15) { model.bodies[row.email.id]?.html != nil }401            let html = model.bodies[row.email.id]?.html ?? ""402            step("unified: open in the reader (template layout kept)", opened && model.readingAccount == a.id && model.currentAccount == b.id && html.contains("<style") && html.contains("VALEUR-\(run)") && model.conversation.first?.from.first?.email == b.address,403                 "reading \(model.readingAccount == a.id) html \(html.count) style \(html.contains("<style"))")404            let moveTargets = model.main.activeMailboxes.map(\.id)405            step("unified: « Déplacer vers » lists the folders of the message's mailbox", !moveTargets.isEmpty && moveTargets == model.mailboxes(for: a.id).map(\.id) && moveTargets != model.main.mailboxes.map(\.id),406                 "\(moveTargets.count) folders of A, window on B")407            try? "unified".write(to: progressURL, atomically: true, encoding: .utf8)408            try? await Task.sleep(for: .seconds(4))409            await model.performUnified(.flag(true), on: [row])410            let flagged = await wait(10) { (try? await model.store?.email(a.id, id: row.email.id))??.isFlagged == true }411            step("unified: flag acts on the right mailbox", flagged && model.unifiedRows.first { $0.id == row.id }?.email.isFlagged == true)412            await model.performUnified(.delete, on: [row]) // to the Trash of mailbox A413            let trashed = await wait(10) { guard let t = try? await model.engines[a.id]?.mailboxId(role: .trash) else { return false }; return (try? await model.store?.email(a.id, id: row.email.id))??.mailboxIds == [t] }414            step("unified: delete acts on the right mailbox", trashed && !model.unifiedRows.contains { $0.id == row.id })415            try? await model.engines[a.id]?.delete(ids: [row.email.id]) // and gone416        }417418        // sender identities: the alias is offered, switching swaps the signature block without touching the typed text419        model.selection = model.mailbox(.inbox).map { .mailbox($0.id) }420        model.didSelectSidebar()421        await model.switchAccount(a.id)422        await model.compose(.new)423        if let composer = model.composeRequest.flatMap({ model.composers[$0] }), let alias = composer.senders.first(where: { $0.isAlias && $0.account == a.id }), let primary = composer.sender {424            composer.body = AttributedString("Texte tapé \(run)" + String(composer.body.characters))425            composer.senderId = alias.id426            composer.senderChanged(from: primary.id)427            let once = composer.plainText428            composer.senderId = primary.id429            composer.senderChanged(from: alias.id)430            composer.senderId = alias.id431            composer.senderChanged(from: primary.id)432            let m = composer.currentMessage()433            step("composer: alias identity and signature swap", !alias.signature.isEmpty && once == "Texte tapé \(run)" + SignatureBlock.block(alias.signature) && composer.plainText == once && m.from.email == alias.email && m.from.name == alias.name,434                 "senders \(composer.senders.map(\.email)) text \(once.debugDescription)")435            await composer.discard(); model.composerClosed(composer.id); model.composeRequest = nil436        } else { step("composer: alias identity and signature swap", false, "senders \(model.senders.map(\.email))") }437        await model.switchAccount(b.id)438439        // tidy: the test template goes (archived on the dev backend), the brand kit is cleared440        await studio.delete(editor.template)441        _ = try? await model.api.patchPrefs(["templateBrand": nil])442        step("studio: delete with undo available", studio.undo?.id == editor.id && studio.current == nil && !studio.templates.contains { $0.id == editor.id })443        #if os(iOS)444        model.showStudio = false445        #endif446    }447}448#endif449
Files main
Menu

Theme