Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : tests/e2e/next-prod/ai.part.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// SP Mail Next — essais de la zone « ai » : intelligence coupée par défaut (aucune surface dans le DOM), aperçus de boîte sans modèle,44// consentement pour le fournisseur externe, fournisseur local scripté (résumé, rappel, suggestions, tri), sortie hostile inerte,45// panne discrète, retrait de toutes les surfaces à la désactivation, téléphone, axe et captures. Jamais de vrai fournisseur.46import { expect, test, type Page } from "@playwright/test"47import type { Part } from "./harness"4849/** Tout ce qui est une surface d'IA : panneaux, boutons, mention du fournisseur, pastilles de tri. Les pastilles d'aperçu n'en sont pas. */50const AI = '[data-nx-ai], [class*="nx-ai"], [class*="mrow-glyph-ai"]'51const HOSTILE_TEXT = '<img src=x onerror="window.__pwned=1"> [cliquez ici](javascript:alert(1)) **gras** <script>window.__pwned=1</script>'5253export const aiPart: Part = (h) => {54 let ids: string[] = []55 const subject = (k: string) => `${k} ${h().run}`56 const row = (p: Page, text: string) => p.locator("#list-pane").getByRole("option").filter({ hasText: text }).first()57 const openThread = async (p: Page, text: string) => {58 // liste virtualisée et longue dans le parcours complet : la ligne n'est cliquée que si elle est affichée ; sinon la conversation59 // est ouverte par son adresse, sans rechargement (même chemin que les boutons Précédent / Suivant du navigateur)60 if (await row(p, text).isVisible().catch(() => false)) await row(p, text).click()61 else {62 const r = await h().jmap(p, h().P1, [["Email/query", { filter: { subject: text }, limit: 1 }, "q"], ["Email/get", { "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["threadId"] }, "g"]])63 const threadId = r[1][1].list[0].threadId as string64 await p.evaluate((href) => {65 history.pushState(null, "", href)66 dispatchEvent(new PopStateEvent("popstate"))67 }, `/m/0/inbox/t/${threadId}`)68 }69 await expect(p.locator(".reader-subject")).toContainText(text)70 }71 const folderTotal = async (p: Page, address: string, role: string): Promise<number> => {72 const r = await h().jmap(p, address, [["Mailbox/get", { properties: ["role", "totalEmails"] }, "m"]])73 return (r[0][1].list as { role: string; totalEmails: number }[]).find((b) => b.role === role)?.totalEmails ?? 074 }75 const pwned = (p: Page) => p.evaluate(() => (window as unknown as { __pwned?: unknown }).__pwned)76 const completions = async (re: RegExp) => (await h().ai.seen()).filter((r) => r.path.endsWith("/chat/completions") && re.test(String(r.body?.messages?.[0]?.content ?? "")))77 const settings = (p: Page) => h().api<{ provider: string; consent_external_at: string | null; features: Record<string, boolean>; available: Record<string, boolean> }>(p, "GET", "/api/next/ai/settings")78 const toMail = async (p: Page) => {79 await p.goto("/")80 await h().openBox(p, h().P1)81 }82 const discardDraft = async (p: Page) => {83 await p.locator("section.composer").getByRole("button", { name: "Supprimer le brouillon" }).click()84 await p.getByRole("alertdialog").getByRole("button", { name: "Supprimer le brouillon" }).click()85 await expect(p.locator("section.composer")).toHaveCount(0)86 }8788 let sentAtStart = 089 test("ai : coupée par défaut — aucune surface d'IA dans le DOM ; les aperçus sans modèle fonctionnent", async () => {90 const { page, P1, P2 } = h()91 await h().ai.reset()92 ids = await h().seed(page, P1, [93 { subject: subject("Budget du trimestre"), from: ["Camille Roy", P2], preview: "Bonjour, peux-tu me confirmer le budget du trimestre avant vendredi ? Merci, Camille", minutesAgo: 3 * 1440 },94 { subject: subject("Infolettre de novembre"), from: ["Le Bulletin", P2], preview: "Les nouvelles du mois : trois articles à lire.", minutesAgo: 90, headers: { "List-Id": "<bulletin.stg.spboucher.ai>", "List-Unsubscribe": "<https://stg.spboucher.ai/unsubscribe>" } },95 { subject: subject("Contrat de service"), from: ["Dominique Tremblay", P2], preview: "Voici le contrat de service révisé. Dis-moi si la clause 4 te convient.", minutesAgo: 2 * 1440 },96 { subject: subject("Compte rendu de réunion"), from: ["Alex Gagnon", P2], preview: "Compte rendu : trois décisions prises, deux actions à suivre.", minutesAgo: 4 * 1440 },97 { subject: subject("Relance devis"), from: ["Prod Un", P1], to: [["Prod Deux", P2]], preview: "As-tu eu le temps de regarder le devis ?", minutesAgo: 5 * 1440, folder: "sent" },98 ])99 await toMail(page)100 expect((await settings(page)).provider).toBe("off")101102 // aperçus sans modèle : trois pastilles avec leurs comptes103 const strip = page.locator("[data-nx-insights]")104 await expect(strip.getByRole("button", { name: /Infolettres\s*1/ })).toBeVisible()105 await expect(strip.getByRole("button", { name: /À répondre\s*3/ })).toBeVisible()106 await expect(strip.getByRole("button", { name: /Sans réponse\s*1/ })).toBeVisible()107 await expect(strip.locator('[data-insight="important"]')).toHaveCount(0)108 await h().axeThemes(page, "ai-inbox-insights")109110 // une pastille ouvre la liste calme des conversations concernées111 await strip.getByRole("button", { name: /Sans réponse/ }).click()112 const sentPanel = strip.getByRole("region", { name: "Sans réponse" })113 await expect(sentPanel.getByRole("link")).toHaveCount(1)114 await expect(sentPanel.getByRole("link")).toContainText(subject("Relance devis"))115 await expect(sentPanel.getByRole("link")).toContainText("Prod Deux")116 await strip.getByRole("button", { name: /Infolettres/ }).click()117 await expect(strip.getByRole("region", { name: "Infolettres" }).getByRole("link")).toContainText(subject("Infolettre de novembre"))118 await strip.getByRole("button", { name: /À répondre/ }).click()119 const panel = strip.getByRole("region", { name: "À répondre" })120 await expect(panel.getByRole("link")).toHaveCount(3)121 await expect(panel.getByRole("link").first()).toContainText("Dominique Tremblay")122 await expect(strip.getByRole("button", { name: /À répondre/ })).toHaveAttribute("aria-pressed", "true")123 await h().shotThemes(page, "ai-inbox-insights")124 await panel.getByRole("link").filter({ hasText: "Camille Roy" }).click()125 await expect(page.locator(".reader-subject")).toContainText(subject("Budget du trimestre"))126 await expect(page).toHaveURL(/\/inbox\//)127128 // lecteur ouvert : rien d'IA, nulle part129 await expect(page.locator(AI)).toHaveCount(0)130 await expect(page.getByRole("button", { name: "Résumer" })).toHaveCount(0)131 // IA coupée : la rédaction n'a plus d'assistant (ni bouton, ni emplacement)132 await page.getByRole("button", { name: "Nouveau message" }).first().click()133 await expect(page.locator("section.composer")).toBeVisible()134 await expect(page.locator("section.composer [data-cmp-tools]")).toHaveCount(0)135 await expect(page.locator('[data-nx-ai="write"]')).toHaveCount(0)136 await page.locator("section.composer").getByRole("button", { name: "Enregistrer et fermer" }).click()137 await expect(page.locator("section.composer")).toHaveCount(0)138 await expect(page.getByRole("button", { name: "Suggestions de réponse" })).toHaveCount(0)139 // le serveur refuse de toute façon, et le fournisseur n'a rien reçu140 const refused = await h().api(page, "POST", "/api/next/ai/summarize", { mailbox_id: await h().mailboxId(page, P1), thread_id: "x" }).then(() => "ok", (e: Error) => e.message)141 expect(refused).toContain("409")142 expect(refused).toContain("ai_disabled")143 expect(await h().ai.seen()).toEqual([])144 // la palette ne propose pas « Résumer la conversation »145 await page.keyboard.press("Control+k")146 const dlg = page.getByRole("dialog", { name: "Palette de commandes" })147 await dlg.getByRole("combobox").fill(">résumer la conversation")148 await expect(dlg.getByRole("option", { name: "Résumer la conversation" })).toHaveCount(0)149 await page.keyboard.press("Escape")150 await expect(dlg).toHaveCount(0)151 })152153 test("ai : Réglages › Intelligence — états honnêtes, Anthropic exige un consentement explicite", async () => {154 const { page } = h()155 await h().palette(page, ">réglages intelligence", "Réglages : Intelligence")156 await expect(page).toHaveURL(/\/settings\/intelligence$/)157 const off = page.getByRole("radio", { name: /^Désactivée/ })158 const local = page.getByRole("radio", { name: /^MacLustr \(local\)/ })159 const anthropic = page.getByRole("radio", { name: /^Anthropic \(fournisseur externe\)/ })160 await expect(off).toBeChecked()161 await expect(local).toBeEnabled()162 // pas de clé Anthropic dans les essais : choix désactivé, avec la raison163 await expect(anthropic).toBeDisabled()164 await expect(page.locator('[data-unavailable="anthropic"]')).toContainText("aucune clé Anthropic")165 await expect(page.locator("[data-ai-state]")).toHaveAttribute("data-ai-state", "off")166 for (const f of ["summary", "reply", "write", "triage", "semantic"]) await expect(page.locator(`[data-ai-feature="${f}"]`)).toBeDisabled()167 // moteur d'indexation coupé dans les essais : l'état indisponible est dit tel quel, sans bouton de reconstruction168 await expect(page.locator('[data-nx-index="unavailable"]')).toContainText("n'est pas disponible sur ce serveur")169 await expect(page.locator('[data-nx-index="unavailable"]')).toContainText("Raison donnée par le serveur")170 await expect(page.getByRole("button", { name: "Reconstruire" })).toHaveCount(0)171 await expect(page.locator('[data-nx-usage="ready"]')).toContainText("Aucune demande pour l'instant.")172 await expect(page.getByRole("heading", { name: "Confidentialité, en un paragraphe" })).toBeVisible()173 await h().axeThemes(page, "ai-settings-off")174175 // Anthropic « disponible » (seule la lecture des réglages est simulée) ; l'écriture est interceptée pour vérifier ce qui part176 const puts: Record<string, unknown>[] = []177 await page.route("**/api/next/ai/settings", async (route) => {178 const req = route.request()179 if (req.method() === "GET") {180 const r = await route.fetch()181 const j = await r.json()182 return route.fulfill({ response: r, json: { ...j, available: { ...j.available, anthropic: true } } })183 }184 const body = req.postDataJSON() as Record<string, unknown>185 puts.push(body)186 return route.fulfill({ json: { provider: body.provider, consent_external_at: new Date().toISOString(), language: "auto", features: { summary: true, reply: true, write: true, triage: true, semantic: false }, available: { local: true, anthropic: true, semantic: false } } })187 })188 await page.reload()189 await expect(anthropic).toBeEnabled()190 const consent = page.getByRole("alertdialog", { name: "Envoyer du contenu à Anthropic ?" })191 for (const [theme, label] of [["light", "Clair"], ["dark", "Sombre"], ["midnight", "Minuit"]] as const) {192 await h().setTheme(page, label, theme)193 await anthropic.click()194 await expect(consent).toBeVisible()195 await h().axe(page, `ai-consent-${theme}`)196 if (theme !== "dark") await h().shot(page, `ai-consent-${theme}`)197 await consent.getByRole("button", { name: "Annuler" }).click()198 await expect(consent).toHaveCount(0)199 }200 await h().setTheme(page, "Clair", "light")201 // annuler : rien n'est parti, le choix précédent reste202 expect(puts).toEqual([])203 await expect(off).toBeChecked()204 await expect(anthropic).not.toBeChecked()205 // le dialogue nomme le fournisseur, dit ce qui part et où, et rappelle que le local garde tout206 await anthropic.click()207 await expect(consent).toContainText("sera envoyé à Anthropic")208 await expect(consent).toContainText("HORS de l'infrastructure du propriétaire")209 await expect(consent).toContainText("Le fournisseur local MacLustr, lui, garde tout sur les machines du propriétaire.")210 await expect(consent.getByRole("button", { name: "Annuler" })).toBeFocused()211 await page.keyboard.press("Escape")212 await expect(consent).toHaveCount(0)213 expect(puts).toEqual([])214 // confirmation explicite : alors seulement `consent_external: true` part, avec le fournisseur215 await anthropic.click()216 await consent.getByRole("button", { name: "J'accepte, activer Anthropic" }).click()217 await expect(consent).toHaveCount(0)218 expect(puts).toEqual([{ provider: "anthropic", consent_external: true }])219 await expect(anthropic).toBeChecked()220 await expect(page.getByText(/Consentement donné le/)).toBeVisible()221 // fin de la simulation : le serveur n'a jamais quitté « off »222 await page.unroute("**/api/next/ai/settings")223 await page.reload()224 await expect(off).toBeChecked()225 expect((await settings(page)).provider).toBe("off")226 expect(await h().ai.seen()).toEqual([])227 await h().shotThemes(page, "ai-settings-off")228 })229230 test("ai : fournisseur local — tri des lignes, résumé à la demande en texte, étiquette du fournisseur, rappel depuis une action", async () => {231 // référence : ce que « Envoyés » contient avant toute action d'IA (une autre zone a pu faire un vrai envoi plus tôt dans le parcours)232 sentAtStart = await folderTotal(h().page, h().P1, "sent")233 const { page, P1 } = h()234 await page.getByRole("radio", { name: /^MacLustr \(local\)/ }).click()235 await expect(page.locator("[data-ai-state]")).toHaveAttribute("data-ai-state", "local")236 const s = await settings(page)237 expect(s.provider).toBe("local")238 expect(s.features).toEqual({ summary: true, reply: true, write: true, triage: true, semantic: false })239 for (const f of ["summary", "reply", "write", "triage"]) await expect(page.locator(`[data-ai-feature="${f}"]`)).toBeChecked()240 await expect(page.locator('[data-ai-feature="semantic"]')).toBeDisabled()241 await h().axeThemes(page, "ai-settings-local")242 await h().shotThemes(page, "ai-settings")243244 await toMail(page)245 // tri : pastilles sur les lignes de la boîte de réception, pastille « Important » étiquetée du fournisseur246 await expect(page.locator('#list-pane [class*="mrow-glyph-ai-"]').first()).toBeVisible({ timeout: 20_000 })247 const strip = page.locator("[data-nx-insights]")248 await expect(strip.locator('[data-insight="important"]')).toContainText(/Important\s*1/)249 await expect(strip.locator('[data-nx-ai="by"]')).toHaveAttribute("data-provider", "local")250 await expect(strip.locator('[data-nx-ai="by"]')).toContainText("stub-model")251 expect(await page.locator("#list-pane .mrow-glyph-ai-important").count()).toBe(1)252 const triage = await completions(/Task: classify each/)253 expect(triage.length).toBe(1)254 expect(Object.keys(triage[0].body)).not.toContain("tools")255 await strip.locator('[data-insight="important"]').click()256 await expect(strip.getByRole("region", { name: "Important" }).getByRole("link")).toHaveCount(1)257 await h().axeThemes(page, "ai-inbox-triage")258 await h().shotThemes(page, "ai-inbox-triage")259 await strip.locator('[data-insight="important"]').click()260261 // résumé : jamais demandé tout seul262 await openThread(page, subject("Budget du trimestre"))263 const ask = page.getByRole("button", { name: "Résumer" })264 await expect(ask).toBeVisible()265 await page.waitForTimeout(800)266 expect(await completions(/Task: summarise/)).toEqual([])267 await ask.click()268 const panel = page.getByRole("region", { name: "Résumé de la conversation" })269 await expect(panel).toContainText("Résumé du fil par le modèle d'essai.")270 await expect(panel).toContainText("Décision A")271 await expect(panel).toContainText("Répondre à Camille")272 await expect(panel).toContainText("Remise du rapport")273 await expect(panel).toContainText("A envoyé le compte rendu")274 const by = panel.locator('[data-nx-ai="by"]')275 await expect(by).toHaveAttribute("data-provider", "local")276 await expect(by).toHaveAttribute("data-model", "stub-model")277 await expect(by).toHaveText(/MacLustr \(local\)\s*·\s*stub-model/)278 const sent = await completions(/Task: summarise/)279 expect(sent.length).toBe(1)280 expect(Object.keys(sent[0].body).sort()).toEqual(["max_tokens", "messages", "model", "stream", "temperature"])281 await h().axeThemes(page, "ai-reader-summary")282 await h().shotThemes(page, "ai-reader-summary")283284 // action → rappel sur le dernier message du fil, la note est le texte de l'action285 await panel.getByRole("button", { name: "Rappel" }).click()286 await page.getByRole("menuitem", { name: "Demain, 9 h" }).click()287 await expect(panel.locator(".nx-ai-reminded")).toContainText("Rappel :")288 const reminders = (await h().api<{ data: { email_id: string; note: string | null; status: string; due_at: string }[] }>(page, "GET", "/api/next/reminders")).data289 const mine = reminders.filter((r) => r.email_id === ids[0])290 expect(mine.length).toBe(1)291 expect(mine[0].note).toBe("Répondre à Camille")292 expect(mine[0].status).toBe("pending")293 expect(new Date(mine[0].due_at).getTime()).toBeGreaterThan(Date.now())294295 // régénérer : le serveur sert son cache de 24 h et le dit ; replier / déplier296 await panel.getByRole("button", { name: "Régénérer le résumé" }).click()297 await expect(by).toHaveAttribute("data-cached", "1")298 await expect(by).toContainText("depuis le cache")299 expect((await completions(/Task: summarise/)).length).toBe(1)300 await panel.getByRole("button", { name: "Replier" }).click()301 await expect(panel.getByText("Décision A")).toBeHidden()302 await panel.getByRole("button", { name: "Déplier" }).click()303 await expect(panel.getByText("Décision A")).toBeVisible()304 // palette : la commande existe maintenant305 await h().palette(page, ">résumer la conversation", "Résumer la conversation")306 await expect(panel).toContainText("Résumé du fil par le modèle d'essai.")307 expect(await folderTotal(page, P1, "sent")).toBe(sentAtStart)308 })309310 test("ai : suggestions de réponse — la rédaction s'ouvre avec le texte, rien n'est envoyé", async () => {311 const { page, P1, P2 } = h()312 const sentBefore = await folderTotal(page, P1, "sent")313 const inboxP2 = await folderTotal(page, P2, "inbox")314 await page.getByRole("button", { name: "Suggestions de réponse" }).click()315 const panel = page.getByRole("region", { name: "Suggestions de réponse" })316 await expect(panel.locator(".nx-ai-suggestion")).toHaveCount(3)317 await expect(panel).toContainText("Suggestion 1 du modèle d'essai")318 await expect(panel.locator('[data-nx-ai="by"]')).toHaveText(/MacLustr \(local\)\s*·\s*stub-model/)319 let asked = await completions(/draft three alternative replies/)320 expect(asked.length).toBe(1)321 expect(String(asked[0].body.messages[0].content)).toContain("Tone: professional")322 await h().axeThemes(page, "ai-reader-replies")323 await h().shotThemes(page, "ai-reader-replies")324 // ton et langue : nouvelle demande explicite325 await panel.getByRole("button", { name: "Concis" }).click()326 await expect(panel.getByRole("button", { name: "Concis" })).toHaveAttribute("aria-pressed", "true")327 await expect(panel.locator(".nx-ai-suggestion")).toHaveCount(3)328 await panel.getByLabel("Langue").selectOption("en")329 await expect(panel.locator(".nx-ai-suggestion")).toHaveCount(3)330 asked = await completions(/draft three alternative replies/)331 expect(asked.length).toBe(3)332 expect(String(asked[1].body.messages[0].content)).toContain("Tone: concise")333 expect(String(asked[2].body.messages[0].content)).toContain("Language: English")334335 await panel.getByRole("button", { name: "Utiliser la suggestion 2 dans la rédaction" }).click()336 const composer = page.locator("section.composer")337 await expect(composer).toBeVisible()338 const body = composer.getByRole("textbox", { name: "Corps du message" })339 await expect(body).toContainText("Suggestion 2 du modèle d'essai")340 // au-dessus du message cité, destinataire et objet de la réponse en place341 const text = (await body.innerText()).trim()342 expect(text.startsWith("Suggestion 2 du modèle d'essai")).toBe(true)343 expect(text).toContain("peux-tu me confirmer le budget")344 await expect(composer.locator(".rcpt-chip")).toHaveCount(1)345 await expect(composer.locator(".rcpt-chip")).toContainText("Camille Roy")346 await expect(composer.getByLabel("Objet :")).toHaveValue(`Re: ${subject("Budget du trimestre")}`)347 // ---- assistant d'écriture, monté dans la barre de la rédaction348 const tool = composer.locator('[data-cmp-tools] [data-nx-ai="write"]')349 await expect(tool).toHaveCount(1)350 const dlg = page.getByRole("dialog", { name: "Assistant d'écriture" })351 const lastWrite = async () => {352 // dernière demande d'écriture reçue par le fournisseur : son message porte le brouillon entre repères « DRAFT »353 const all = (await h().ai.seen()).filter((r) => r.path.endsWith("/chat/completions") && /<<<DRAFT /.test(String(r.body?.messages?.at(-1)?.content ?? "")))354 return String(all[all.length - 1]?.body?.messages?.at(-1)?.content ?? "")355 }356 // sans sélection : le texte rédigé seulement — jamais le message cité ni la signature357 await tool.getByRole("button", { name: "Assistant" }).click()358 await expect(dlg).toBeVisible()359 await dlg.getByRole("button", { name: "Améliorer" }).click()360 await expect(dlg.locator(".nx-ai-preview .nx-ai-text")).toHaveText("Texte réécrit par le modèle d'essai.")361 await expect(dlg.locator('[data-nx-ai="by"]')).toHaveText(/MacLustr \(local\)\s*·\s*stub-model/)362 const sentText = await lastWrite()363 expect(sentText).toContain("Suggestion 2 du modèle d'essai")364 expect(sentText).not.toContain("peux-tu me confirmer le budget")365 // « Annuler » : rien n'a changé dans le brouillon366 await dlg.getByRole("button", { name: "Annuler" }).click()367 await expect(dlg.getByRole("button", { name: "Améliorer" })).toBeVisible()368 await expect(body).toContainText("Suggestion 2 du modèle d'essai")369 // « Remplacer » : le texte rédigé est remplacé, la citation reste intacte370 await dlg.getByRole("button", { name: "Améliorer" }).click()371 await dlg.getByRole("button", { name: "Remplacer" }).click()372 await expect(dlg).toHaveCount(0)373 await expect(body).toContainText("Texte réécrit par le modèle d'essai.")374 await expect(body).not.toContainText("Suggestion 2 du modèle d'essai")375 await expect(body).toContainText("peux-tu me confirmer le budget")376 expect((await body.innerText()).trim().startsWith("Texte réécrit par le modèle d'essai.")).toBe(true)377 // avec une sélection : elle seule part au modèle, elle seule est remplacée378 await body.evaluate((root) => {379 const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)380 let n = w.nextNode() as Text | null381 while (n && !n.data.includes("Texte réécrit")) n = w.nextNode() as Text | null382 const at = n!.data.indexOf("Texte")383 const r = document.createRange()384 r.setStart(n!, at)385 r.setEnd(n!, at + 5)386 const sel = getSelection()!387 sel.removeAllRanges()388 sel.addRange(r)389 })390 await tool.getByRole("button", { name: "Assistant" }).click()391 await dlg.getByRole("button", { name: "Raccourcir" }).click()392 await expect(dlg.locator(".nx-ai-preview .nx-ai-text")).toBeVisible()393 expect(await lastWrite()).toMatch(/(^|[^\p{L}])Texte([^\p{L}]|$)/u)394 expect(await lastWrite()).not.toContain("réécrit par le modèle")395 await dlg.getByRole("button", { name: "Remplacer" }).click()396 await expect(body).toContainText("Texte réécrit par le modèle d'essai. réécrit par le modèle d'essai.")397 await expect(body).toContainText("peux-tu me confirmer le budget")398 // objets proposés : celui choisi entre dans le champ « Objet »399 await tool.getByRole("button", { name: "Assistant" }).click()400 await dlg.getByRole("button", { name: "Proposer un objet" }).click()401 await expect(dlg.locator(".nx-ai-subject")).toHaveCount(4)402 await dlg.getByRole("button", { name: "Sujet deux" }).click()403 await expect(composer.getByLabel("Objet :")).toHaveValue("Sujet deux")404 await h().shot(page, "ai-composer-write-light")405 // l'enregistrement automatique du brouillon passe ; aucun envoi406 await page.waitForTimeout(3000)407 expect(await folderTotal(page, P1, "sent")).toBe(sentBefore)408 expect(await folderTotal(page, P2, "inbox")).toBe(inboxP2)409 await discardDraft(page)410 expect(await folderTotal(page, P1, "sent")).toBe(sentBefore)411412 // la route d'écriture répond avec le fournisseur (le menu lui-même attend son hôte dans la rédaction)413 const w = await h().api<{ text: string; provider: string; model: string }>(page, "POST", "/api/next/ai/write", { action: "improve", text: "bonjour je veux le budget" })414 expect(w).toEqual({ text: "Texte réécrit par le modèle d'essai.", provider: "local", model: "stub-model" })415 const subj = await h().api<{ subjects: string[] }>(page, "POST", "/api/next/ai/write", { action: "subject", text: "bonjour je veux le budget" })416 expect(subj.subjects).toEqual(["Sujet un", "Sujet deux", "Sujet trois", "Sujet quatre"])417 })418419 test("ai : sortie hostile affichée inerte (texte littéral, aucun élément créé), dans le résumé comme dans la rédaction", async () => {420 const { page, P1 } = h()421 await h().ai.mode("hostile")422 await openThread(page, subject("Contrat de service"))423 await page.getByRole("button", { name: "Résumer" }).click()424 const panel = page.getByRole("region", { name: "Résumé de la conversation" })425 await expect(panel.locator(".nx-ai-text")).toHaveText(HOSTILE_TEXT)426 await expect(panel.getByText("[cliquez ici](javascript:alert(1))").first()).toBeVisible()427 await expect(panel.getByText('<img src=x onerror="window.__pwned=1">').first()).toBeVisible()428 await expect(panel.locator("img, script, a, iframe, strong, b, [onerror]")).toHaveCount(0)429 expect(await pwned(page)).toBeUndefined()430 await h().shot(page, "ai-reader-hostile-light")431432 const sentBefore = await folderTotal(page, P1, "sent")433 await page.getByRole("button", { name: "Suggestions de réponse" }).click()434 const replies = page.getByRole("region", { name: "Suggestions de réponse" })435 await expect(replies.locator(".nx-ai-suggestion")).toHaveCount(3)436 await expect(replies.locator(".nx-ai-suggestion .nx-ai-text").first()).toHaveText(HOSTILE_TEXT)437 await expect(replies.locator("img, script, a, iframe, [onerror]")).toHaveCount(0)438 await replies.getByRole("button", { name: "Utiliser la suggestion 1 dans la rédaction" }).click()439 const composer = page.locator("section.composer")440 const body = composer.getByRole("textbox", { name: "Corps du message" })441 await expect(body).toContainText('<img src=x onerror="window.__pwned=1">')442 await expect(body).toContainText("<script>window.__pwned=1</script>")443 // dans l'éditeur : du texte ; ni image, ni script, ni lien issus de la suggestion (le message cité n'en contient pas)444 expect(await body.locator("img, script, [onerror]").count()).toBe(0)445 expect(await body.locator('a[href^="javascript"]').count()).toBe(0)446 await page.waitForTimeout(2500) // enregistrement automatique : le brouillon repasse par l'assainisseur, toujours rien447 expect(await pwned(page)).toBeUndefined()448 expect(await page.evaluate(() => JSON.parse(localStorage.getItem("spmail.draft") ?? "{}").html as string)).toContain("<img src=x onerror=")449 // assistant d'écriture : sortie hostile montrée en texte dans l'aperçu, et entrée en texte dans le brouillon450 await composer.locator('[data-nx-ai="write"]').getByRole("button", { name: "Assistant" }).click()451 const wdlg = page.getByRole("dialog", { name: "Assistant d'écriture" })452 await wdlg.getByRole("button", { name: "Améliorer" }).click()453 await expect(wdlg.locator(".nx-ai-preview .nx-ai-text")).toHaveText(HOSTILE_TEXT)454 await expect(wdlg.locator("img, script, iframe, [onerror]")).toHaveCount(0)455 await wdlg.getByRole("button", { name: "Remplacer" }).click()456 await expect(body).toContainText("<script>window.__pwned=1</script>")457 expect(await body.locator("img, script, [onerror]").count()).toBe(0)458 expect(await body.locator('a[href^="javascript"]').count()).toBe(0)459 expect(await pwned(page)).toBeUndefined()460 expect(await folderTotal(page, P1, "sent")).toBe(sentBefore)461 await discardDraft(page)462 await h().ai.mode("normal")463 })464465 test("ai : fournisseur en panne — une ligne discrète avec « Réessayer », puis reprise", async () => {466 const { page } = h()467 await h().ai.mode("down")468 await openThread(page, subject("Compte rendu de réunion"))469 await page.getByRole("button", { name: "Résumer" }).click()470 const panel = page.getByRole("region", { name: "Résumé de la conversation" })471 const problem = panel.locator('[data-nx-ai="problem"]')472 await expect(problem).toHaveAttribute("data-issue", "unavailable", { timeout: 20_000 })473 await expect(problem).toContainText("Le fournisseur d'intelligence ne répond pas pour le moment.")474 await expect(problem.getByRole("button", { name: "Réessayer" })).toBeVisible()475 // discret : ni alerte, ni bandeau rouge, ni notification d'erreur476 await expect(page.locator(".reader [role=alert], .reader .banner.danger, .toast.error")).toHaveCount(0)477 await h().shot(page, "ai-reader-down-light")478 await h().axe(page, "ai-reader-down")479 await h().ai.mode("normal")480 await problem.getByRole("button", { name: "Réessayer" }).click()481 await expect(panel).toContainText("Résumé du fil par le modèle d'essai.")482 await expect(problem).toHaveCount(0)483 })484485 test("ai : téléphone — pastilles, résumé, suggestions, réglages et consentement", async () => {486 const { ctx, p } = await h().fromStorage({ width: 390, height: 844 }, true)487 try {488 await p.goto("/")489 const strip = p.locator("[data-nx-insights]")490 await expect(strip.getByRole("button", { name: /À répondre/ })).toBeVisible({ timeout: 20_000 })491 for (const chip of await strip.locator(".nx-insight-chip").all()) expect((await chip.boundingBox())!.height).toBeGreaterThanOrEqual(44)492 await strip.getByRole("button", { name: /À répondre/ }).tap()493 await expect(strip.getByRole("region", { name: "À répondre" }).getByRole("link").first()).toBeVisible()494 expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)495 await h().shot(p, "ai-inbox-insights-phone")496 await strip.getByRole("region", { name: "À répondre" }).getByRole("link").filter({ hasText: "Camille Roy" }).tap()497 await expect(p.locator(".reader-subject")).toContainText(subject("Budget du trimestre"))498 const ask = p.getByRole("button", { name: "Résumer" })499 expect((await ask.boundingBox())!.height).toBeGreaterThanOrEqual(44)500 await ask.tap()501 const panel = p.getByRole("region", { name: "Résumé de la conversation" })502 await expect(panel).toContainText("Résumé du fil par le modèle d'essai.")503 await expect(panel.locator('[data-nx-ai="by"]')).toContainText("stub-model")504 expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)505 await h().shot(p, "ai-reader-summary-phone")506 await h().axe(p, "ai-reader-summary-phone")507 await p.getByRole("button", { name: "Suggestions de réponse" }).scrollIntoViewIfNeeded()508 await p.getByRole("button", { name: "Suggestions de réponse" }).tap()509 const replies = p.getByRole("region", { name: "Suggestions de réponse" })510 await expect(replies.locator(".nx-ai-suggestion")).toHaveCount(3)511 await replies.locator(".nx-ai-suggestion").first().scrollIntoViewIfNeeded()512 await h().shot(p, "ai-reader-replies-phone")513 await h().axe(p, "ai-reader-replies-phone")514515 await p.route("**/api/next/ai/settings", async (route) => {516 if (route.request().method() !== "GET") return route.abort()517 const r = await route.fetch()518 const j = await r.json()519 return route.fulfill({ response: r, json: { ...j, available: { ...j.available, anthropic: true } } })520 })521 await p.goto("/settings/intelligence")522 await expect(p.getByRole("radio", { name: /^MacLustr \(local\)/ })).toBeChecked()523 expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)524 await h().shot(p, "ai-settings-phone")525 await h().axe(p, "ai-settings-phone")526 await p.getByRole("radio", { name: /^Anthropic \(fournisseur externe\)/ }).tap()527 const consent = p.getByRole("alertdialog", { name: "Envoyer du contenu à Anthropic ?" })528 await expect(consent).toBeVisible()529 await h().shot(p, "ai-consent-phone")530 await h().axe(p, "ai-consent-phone")531 await consent.getByRole("button", { name: "Annuler" }).tap()532 await expect(p.getByRole("radio", { name: /^MacLustr \(local\)/ })).toBeChecked()533 } finally {534 await ctx.close()535 }536 })537538 test("ai : une fonction coupée, puis le fournisseur coupé — chaque surface quitte le DOM, les aperçus restent", async () => {539 const { page, P1 } = h()540 await toMail(page)541 await openThread(page, subject("Budget du trimestre"))542 await expect(page.getByRole("button", { name: "Résumer" }).or(page.getByRole("region", { name: "Résumé de la conversation" })).first()).toBeVisible()543 await expect(page.getByRole("button", { name: "Suggestions de réponse" })).toBeVisible()544 await expect(page.locator('#list-pane [class*="mrow-glyph-ai-"]').first()).toBeVisible({ timeout: 20_000 })545 // réglage changé ailleurs (autre appareil) : au retour sur l'onglet, la surface concernée disparaît sans rechargement546 await h().api(page, "PUT", "/api/next/ai/settings", { features: { reply: false } })547 await page.evaluate(() => window.dispatchEvent(new Event("focus")))548 await expect(page.locator('[data-nx-ai="reply"]')).toHaveCount(0)549 await expect(page.locator('[data-nx-ai="summary"]')).toHaveCount(1)550 await h().api(page, "PUT", "/api/next/ai/settings", { provider: "off" })551 await page.evaluate(() => window.dispatchEvent(new Event("focus")))552 await expect(page.locator(AI)).toHaveCount(0)553 await expect(page.getByRole("button", { name: "Résumer" })).toHaveCount(0)554 // les aperçus sans modèle, eux, sont toujours là — sans pastille « Important » ni mention de fournisseur555 const strip = page.locator("[data-nx-insights]")556 await expect(strip.getByRole("button", { name: /Infolettres\s*1/ })).toBeVisible()557 await expect(strip.locator('[data-insight="important"]')).toHaveCount(0)558559 // par les réglages aussi : activer puis désactiver, sans rechargement de page560 await h().palette(page, ">réglages intelligence", "Réglages : Intelligence")561 await expect(page.getByRole("radio", { name: /^Désactivée/ })).toBeChecked()562 await page.getByRole("radio", { name: /^MacLustr \(local\)/ }).click()563 await expect(page.locator("[data-ai-state]")).toHaveAttribute("data-ai-state", "local")564 // le choix « reply: false » fait plus haut a été conservé par le serveur565 await expect(page.locator('[data-ai-feature="reply"]')).not.toBeChecked()566 await page.locator('[data-ai-feature="reply"]').click()567 await expect(page.locator('[data-ai-feature="reply"]')).toBeChecked()568 await expect(page.locator('[data-nx-usage="ready"] table')).toContainText("Résumé de conversation")569 await expect(page.locator('[data-nx-usage="ready"] table')).toContainText("stub-model")570 await h().shot(page, "ai-settings-usage-light")571 await page.locator(".page-head a.btn").click()572 await openThread(page, subject("Budget du trimestre"))573 await expect(page.getByRole("button", { name: "Résumer" }).or(page.getByRole("region", { name: "Résumé de la conversation" })).first()).toBeVisible()574 await h().palette(page, ">réglages intelligence", "Réglages : Intelligence")575 await page.getByRole("radio", { name: /^Désactivée/ }).click()576 await expect(page.locator("[data-ai-state]")).toHaveAttribute("data-ai-state", "off")577 await page.locator(".page-head a.btn").click()578 await openThread(page, subject("Budget du trimestre"))579 await expect(page.locator(".reader-subject")).toContainText(subject("Budget du trimestre"))580 await expect(page.locator("[data-nx-insights]")).toBeVisible()581 await expect(page.locator(AI)).toHaveCount(0)582 expect((await settings(page)).provider).toBe("off")583 expect(await folderTotal(page, P1, "sent")).toBe(sentAtStart)584 // aucune erreur de script pendant tout le parcours de la zone585 expect(h().consoleErrors.filter((e) => e.startsWith("pageerror"))).toEqual([])586 })587}588