Repository Public
1// Rédaction « SP Mail Next » : éditeur riche, image en ligne (cid:) et pièce jointe reçues telles quelles, réponse qui garde la citation,2// plusieurs brouillons enregistrés sans doublon, fermeture hors ligne, envoi différé, annulation d'envoi (retenue côté serveur),3// destinataire sensible, pièce jointe oubliée, signatures par adresse, extraits, autocomplétion, modèles, alias, téléphone, accessibilité.4// Captures dans /tmp/spmail-next-shots/web-compose. Le fichier se suffit : lancé seul (--project=compose --no-deps), il fait lui-même5// l'enrôlement ; après les autres parcours, il reprend la clé d'accès exportée. Ses boîtes (web-c*-<run>) lui sont propres ; les envois6// réels sont peu nombreux et répartis entre elles (le serveur de recette limite chaque expéditeur).7import AxeBuilder from "@axe-core/playwright"8import { expect, test, type BrowserContext, type Locator, type Page } from "@playwright/test"9import fs from "node:fs"10import zlib from "node:zlib"11import { OUT, readState, writeState } from "./env"12import { addAuthenticator, exportCredential, importCredential, purgeLeftoverMailboxes, row, signIn, toastText, track } from "./helpers"1314test.describe.configure({ mode: "serial" })1516const SHOTS = "/tmp/spmail-next-shots/web-compose"17const st = readState()18const C1 = `web-c1-${st.run}@stg.spboucher.ai`19const C2 = `web-c2-${st.run}@stg.spboucher.ai`20const C3 = `web-c3-${st.run}@stg.spboucher.ai`21const C4 = `web-c4-${st.run}@stg.spboucher.ai`22const ALIAS = `web-c1-alias-${st.run}@stg.spboucher.ai`23const THEMES = [["light", "Clair"], ["dark", "Sombre"], ["midnight", "Minuit"]] as const2425let context: BrowserContext26let page: Page27let storage: Awaited<ReturnType<BrowserContext["storageState"]>>28const consoleErrors: string[] = []29/** Créations de brouillon vues sur le réseau (Email/set → create avec $draft), par objet. */30const draftCreates: { subject: string; at: number }[] = []31/** Fichiers remis à l'API d'envoi (POST /api/v1/files). */32let fileUploads = 03334/** `only` : limite l'analyse à une partie de la page (la rédaction plein écran recouvre le reste, qui n'est pas visible). */35async function axe(p: Page, name: string, only?: string) {36 let builder = new AxeBuilder({ page: p }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]).exclude(".html-frame iframe").exclude(".html-measure")37 if (only) builder = builder.include(only)38 const r = await builder.analyze()39 const bad = r.violations.filter((v) => v.impact === "serious" || v.impact === "critical")40 fs.appendFileSync(`${OUT}/axe.log`, `compose-${name}: ${r.violations.length} violation(s), ${bad.length} serious/critical, ${r.passes.length} passes\n${bad.map((v) => ` ${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(" | ")}`).join("\n")}\n`)41 expect(bad.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).slice(0, 4).join(" | ")}`), `axe ${name}`).toEqual([])42}43const shot = (p: Page, name: string) => p.screenshot({ path: `${SHOTS}/${name}.png` })4445/** Appel d'API authentifié depuis la page (cookie de session, en-tête anti-CSRF). */46async function api<T>(p: Page, method: string, url: string, body?: unknown): Promise<T> {47 return p.evaluate(48 async ({ method, url, body }) => {49 const r = await fetch(url, { method, headers: { "x-spmail": "1", ...(body === undefined ? {} : { "content-type": "application/json" }) }, body: body === undefined ? undefined : JSON.stringify(body) })50 if (!r.ok) throw new Error(`${method} ${url} → ${r.status} ${await r.text()}`)51 return r.json()52 },53 { method, url, body },54 ) as Promise<T>55}56interface Received {57 id: string58 subject: string59 from: { email: string; name: string | null }[]60 inReplyTo: string[] | null61 html: string | null62 text: string | null63 attachments: { name: string | null; type: string; disposition: string | null; cid: string | null; size: number }[]64}65/** Messages d'un dossier dont l'objet contient `subject`, lus par JMAP comme le ferait un autre client. */66async function messages(p: Page, address: string, role: "inbox" | "drafts" | "sent", subject: string): Promise<Received[]> {67 return p.evaluate(68 async ({ address, role, subject }) => {69 const me = await (await fetch("/api/me")).json()70 const mb = me.mailboxes.find((m: { address: string }) => m.address === address).id71 const session = await (await fetch(`/api/jmap/${mb}/session`)).json()72 const accountId = session.primaryAccounts["urn:ietf:params:jmap:mail"]73 const call = async (methodCalls: unknown[]) => (await (await fetch(`/api/jmap/${mb}/api`, { method: "POST", headers: { "content-type": "application/json", "x-spmail": "1" }, body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"], methodCalls }) })).json()).methodResponses74 const boxes = (await call([["Mailbox/get", { accountId, properties: ["role"] }, "m"]]))[0][1].list as { id: string; role: string }[]75 const folder = boxes.find((b) => b.role === role)?.id76 if (!folder) return []77 const res = await call([78 ["Email/query", { accountId, filter: { inMailbox: folder }, sort: [{ property: "receivedAt", isAscending: false }], limit: 60 }, "q"],79 ["Email/get", { accountId, "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["subject", "from", "inReplyTo", "htmlBody", "textBody", "bodyValues", "attachments"], bodyProperties: ["partId", "name", "type", "disposition", "cid", "size"], fetchHTMLBodyValues: true, fetchTextBodyValues: true }, "g"],80 ])81 type Part = { partId: string; name: string | null; type: string; disposition: string | null; cid: string | null; size: number }82 const list = res[1][1].list as { id: string; subject: string; from: { email: string; name: string | null }[]; inReplyTo: string[] | null; htmlBody: Part[]; textBody: Part[]; bodyValues: Record<string, { value: string }>; attachments: Part[] }[]83 return list84 .filter((e) => (e.subject ?? "").includes(subject))85 .map((e) => ({86 id: e.id, subject: e.subject, from: e.from, inReplyTo: e.inReplyTo,87 html: e.htmlBody.filter((x) => x.type === "text/html").map((x) => e.bodyValues[x.partId]?.value ?? "").join("") || null,88 text: e.textBody.filter((x) => x.type === "text/plain").map((x) => e.bodyValues[x.partId]?.value ?? "").join("") || null,89 attachments: e.attachments.map((a) => ({ name: a.name, type: a.type, disposition: a.disposition, cid: a.cid, size: a.size })),90 }))91 },92 { address, role, subject },93 )94}95async function received(p: Page, address: string, subject: string, timeout = 40_000): Promise<Received> {96 let found: Received[] = []97 await expect.poll(async () => (found = await messages(p, address, "inbox", subject)).length, { timeout, message: `message « ${subject} » attendu dans ${address}` }).toBeGreaterThan(0)98 return found[0]99}100const mailboxId = (p: Page, address: string) => p.evaluate(async (address) => ((await (await fetch("/api/me")).json()).mailboxes as { id: string; address: string }[]).find((m) => m.address === address)?.id ?? null, address)101async function openBox(p: Page, address: string) {102 await p.getByRole("link", { name: address }).or(p.getByRole("heading", { level: 2, name: address })).first().waitFor()103 if (await p.getByRole("link", { name: address }).count()) await p.getByRole("link", { name: address }).click()104 await expect(p.getByRole("heading", { level: 2, name: address })).toBeVisible()105 await expect(p.getByRole("heading", { level: 1, name: "Boîte de réception" })).toBeVisible()106}107async function palette(p: Page, query: string, expected: string | RegExp) {108 await p.keyboard.press("Control+k")109 const dlg = p.getByRole("dialog", { name: "Palette de commandes" })110 await expect(dlg).toBeVisible()111 await dlg.getByRole("combobox").fill(query)112 await expect(dlg.getByRole("option").first()).toHaveText(expected)113 await p.keyboard.press("Enter")114 await expect(dlg).toHaveCount(0)115}116async function setTheme(p: Page, label: string, theme: string) {117 await palette(p, `>theme ${label}`, `Thème : ${label}`)118 await expect(p.locator("html")).toHaveAttribute("data-theme", theme)119}120const prefs = (p: Page, patch: Record<string, unknown>) => api(p, "PUT", "/api/next/compose/prefs", { undo_seconds: 0, sensitive: [], warn_missing_attachment: true, warn_external: false, ...patch })121122const composer = (p: Page) => p.locator("section.composer")123const body = (dlg: Locator) => dlg.getByRole("textbox", { name: "Corps du message" })124const tool = (dlg: Locator, name: string) => dlg.getByRole("toolbar", { name: "Mise en forme" }).getByRole("button", { name, exact: true })125/** Ouvre une rédaction, choisit l'expéditeur, pose un destinataire et l'objet. */126async function compose(p: Page, opts: { from?: string; to?: string; subject?: string } = {}) {127 await p.getByRole("button", { name: "Nouveau message" }).first().click()128 const dlg = composer(p)129 await expect(dlg).toBeVisible()130 if (opts.from) {131 const from = dlg.getByLabel("De :")132 await from.selectOption({ label: (await from.locator("option").allTextContents()).find((o) => o.includes(opts.from!))! })133 }134 if (opts.to) {135 await dlg.getByRole("combobox", { name: "À :" }).fill(opts.to)136 await dlg.getByRole("combobox", { name: "À :" }).press("Enter")137 }138 if (opts.subject) await dlg.getByLabel("Objet :").fill(opts.subject)139 return dlg140}141/** Curseur au tout début (ou à la toute fin) du texte, quel que soit le système où tourne le navigateur. */142async function caret(p: Page, where: "start" | "end") {143 await p.keyboard.press(process.platform === "darwin" ? (where === "start" ? "Meta+ArrowUp" : "Meta+ArrowDown") : where === "start" ? "Control+Home" : "Control+End")144}145async function typeBody(p: Page, dlg: Locator, text: string) {146 await body(dlg).click()147 await caret(p, "start")148 await p.keyboard.type(text)149}150async function discard(p: Page) {151 await composer(p).getByRole("button", { name: "Supprimer le brouillon" }).click()152 await p.getByRole("alertdialog").getByRole("button", { name: "Supprimer le brouillon" }).click()153 await expect(composer(p)).toHaveCount(0)154}155const delivered = async (p: Page, address: string) => {156 const delivery = p.locator('[data-testid="delivery"]').last()157 await expect(delivery.locator(`[data-recipient="${address}"]`)).toHaveAttribute("data-delivered", "yes", { timeout: 45_000 })158 await delivery.getByRole("button", { name: "Masquer" }).click()159}160161// ---------------------------------------------------------------- images d'essai (PNG valides, sans dépendance)162function png(width: number, height: number, pixel: (x: number, y: number) => [number, number, number]): Buffer {163 const raw = Buffer.alloc((width * 3 + 1) * height)164 for (let y = 0; y < height; y++) {165 raw[y * (width * 3 + 1)] = 0166 for (let x = 0; x < width; x++) raw.set(pixel(x, y), y * (width * 3 + 1) + 1 + x * 3)167 }168 const chunk = (type: string, data: Buffer) => {169 const head = Buffer.alloc(8)170 head.writeUInt32BE(data.length, 0)171 head.write(type, 4, "ascii")172 const crc = Buffer.alloc(4)173 crc.writeUInt32BE(zlib.crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0)174 return Buffer.concat([head, data, crc])175 }176 const ihdr = Buffer.alloc(13)177 ihdr.writeUInt32BE(width, 0)178 ihdr.writeUInt32BE(height, 4)179 ihdr.set([8, 2, 0, 0, 0], 8)180 return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))])181}182const LOGO = png(96, 48, (x, y) => (x < 48 ? [44, 91, 77] : y < 24 ? [224, 236, 231] : [176, 122, 0]))183// large et bruitée : la réduction côté navigateur (canvas) la ramène à 1600 px et l'allège réellement184let seed = 0x9e3779b9185const noise = () => {186 seed ^= seed << 13187 seed ^= seed >>> 17188 seed ^= seed << 5189 return seed & 0xff190}191const WIDE = png(2400, 40, () => [noise(), noise(), noise()])192193async function insertImage(p: Page, dlg: Locator, file: { name: string; buffer: Buffer }) {194 const chooser = p.waitForEvent("filechooser")195 await tool(dlg, "Insérer une image").click()196 await (await chooser).setFiles({ name: file.name, mimeType: "image/png", buffer: file.buffer })197}198199test.beforeAll(async ({ browser }) => {200 fs.mkdirSync(SHOTS, { recursive: true })201 context = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: "fr-CA", timezoneId: "America/Toronto" })202 page = await context.newPage()203 page.on("console", (m) => {204 if (m.type() === "error") consoleErrors.push(m.text())205 })206 page.on("pageerror", (e) => consoleErrors.push(`pageerror: ${e.message}`))207 page.on("request", (r) => {208 const url = r.url()209 if (r.method() !== "POST") return210 if (/\/api\/v1\/files\?/.test(url)) fileUploads++211 if (!/\/api\/jmap\/[^/]+\/api$/.test(url)) return212 try {213 const calls = (JSON.parse(r.postData() ?? "{}") as { methodCalls?: [string, { create?: Record<string, { subject?: string; keywords?: Record<string, boolean> }> }, string][] }).methodCalls ?? []214 for (const [name, args] of calls) if (name === "Email/set") for (const e of Object.values(args.create ?? {})) if (e.keywords?.$draft) draftCreates.push({ subject: e.subject ?? "", at: Date.now() })215 } catch {216 /* corps non JSON (téléversement) */217 }218 })219 const authn = await addAuthenticator(context, page)220 if (readState().credential) {221 await importCredential(authn, 3000)222 await signIn(page)223 } else {224 // lancé seul : premier enrôlement de l'installation225 await page.goto(st.enrollUrl)226 await page.getByLabel("Nom affiché").fill("Propriétaire Essai")227 await page.getByLabel("Identifiant").fill("owner")228 await page.getByRole("button", { name: "Créer la clé d'accès" }).click()229 await expect(page.locator("#sidebar")).toBeAttached()230 await exportCredential(authn)231 }232 // Après les autres parcours, leurs boîtes d'essai existent encore : chacune tient une connexion de notification ouverte, et le233 // navigateur n'en accorde que six par hôte en HTTP/1.1 (le serveur d'essai local) — avec les quatre boîtes de ce parcours,234 // plus rien d'autre ne passerait. Celles des parcours déjà terminés sont donc purgées ici (le démontage global l'aurait fait).235 // Seules les deux boîtes des parcours « desktop » et « mobile » sont visées (terminés : ce projet en dépend) — jamais une boîte236 // d'un autre parcours.237 await purgeLeftoverMailboxes(page)238 const me = await api<{ mailboxes: { id: string; address: string }[] }>(page, "GET", "/api/me")239 for (const m of me.mailboxes) if (m.address === st.addrA || m.address === st.addrB) await api(page, "DELETE", `/api/admin/mailboxes/${m.id}?purge=delete-all-mail`).catch(() => {})240 track(C1, C2, C3, C4)241 for (const [address, name] of [[C1, "Compose Un"], [C2, "Compose Deux"], [C3, "Compose Trois"], [C4, "Compose Quatre"]]) await api(page, "POST", "/api/admin/mailboxes", { address, display_name: name })242 await api(page, "POST", "/api/v1/addresses", { address: ALIAS, kind: "alias", mailbox: C1, display_name: "Alias Compose" })243 await prefs(page, {})244 await page.goto("/")245 await openBox(page, C1)246 storage = await context.storageState()247 writeState({ storage: JSON.stringify(storage) })248})249test.afterAll(async () => {250 fs.writeFileSync(`${OUT}/compose-console-errors.log`, consoleErrors.join("\n"))251 for (const address of [C1, C2, C3, C4]) {252 const id = await mailboxId(page, address).catch(() => null)253 if (id) await api(page, "DELETE", `/api/admin/mailboxes/${id}?purge=delete-all-mail`).catch(() => {})254 }255 await context?.close()256})257258test("message riche : image en ligne (cid:), pièce jointe, mise en forme — reçu avec le bon HTML et sa version texte", async () => {259 const subject = `Riche ${st.run}`260 const dlg = await compose(page, { from: C1, to: C2, subject })261 // le focus est entré dans la fenêtre ; elle est étiquetée par son titre262 await expect(dlg).toHaveAttribute("aria-labelledby", /.+/)263 expect(await dlg.evaluate((el) => el.contains(document.activeElement))).toBe(true)264 await body(dlg).click()265 await page.keyboard.type("Bonjour ")266 await page.keyboard.press("ControlOrMeta+b")267 await expect(tool(dlg, "Gras")).toHaveAttribute("aria-pressed", "true")268 await page.keyboard.type("gras")269 await page.keyboard.press("ControlOrMeta+b")270 await expect(tool(dlg, "Gras")).toHaveAttribute("aria-pressed", "false")271 await page.keyboard.type(" et ")272 await tool(dlg, "Italique").click()273 await page.keyboard.type("italique")274 await tool(dlg, "Italique").click()275 await page.keyboard.type(" — été, naïve, 日本語.")276 await page.keyboard.press("Enter")277 await tool(dlg, "Liste à puces").click()278 await expect(tool(dlg, "Liste à puces")).toHaveAttribute("aria-pressed", "true")279 await page.keyboard.type("un")280 await page.keyboard.press("Enter")281 await page.keyboard.type("deux")282 await page.keyboard.press("Enter")283 // Entrée dans un élément vide : sortie de la liste284 await page.keyboard.press("Enter")285 await expect(tool(dlg, "Liste à puces")).toHaveAttribute("aria-pressed", "false")286 await page.keyboard.type("Voir ")287 // lien : adresse validée, protocole ajouté288 await page.keyboard.press("ControlOrMeta+k")289 const link = page.getByRole("dialog", { name: "Insérer un lien" })290 await link.getByLabel("Adresse du lien").fill("javascript:alert(1)")291 await link.getByRole("button", { name: "Insérer" }).click()292 await expect(link.getByRole("alert")).toContainText("n'est pas valide")293 await link.getByLabel("Adresse du lien").fill("example.org/guide")294 await link.getByLabel("Texte affiché").fill("le guide")295 await link.getByRole("button", { name: "Insérer" }).click()296 await expect(body(dlg).locator('a[href="https://example.org/guide"]')).toHaveText("le guide")297 await body(dlg).focus()298 await caret(page, "end")299 await page.keyboard.press("Enter")300 // image en ligne : affichée par une adresse locale, référencée par son identifiant301 await insertImage(page, dlg, { name: "logo.png", buffer: LOGO })302 const img = body(dlg).locator("img[data-cid]")303 await expect(img).toHaveCount(1)304 await expect(img).toHaveAttribute("src", /^blob:/)305 await expect.poll(() => img.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBe(96)306 await img.click()307 const tools = dlg.getByRole("group", { name: "Réglages de l'image" })308 await tools.getByLabel("Texte de remplacement").fill("Logo d'essai")309 await tools.getByRole("radio", { name: "Petite" }).click()310 await tools.getByRole("button", { name: "Fermer" }).click()311 await expect(img).toHaveAttribute("alt", "Logo d'essai")312 // pièce jointe ordinaire313 await page.locator('.composer input[type="file"]').setInputFiles({ name: "notes d'été.txt", mimeType: "text/plain", buffer: Buffer.from("contenu accentué : éàç\n") })314 await expect(page.locator(".composer-att")).toContainText("notes d'été.txt")315 await expect(page.locator(".composer-att progress")).toHaveCount(0)316 await expect(dlg.locator(".composer-atts-total")).toContainText("1 image dans le texte")317 // annuler / rétablir : notre historique, pas celui du navigateur318 await body(dlg).focus()319 await caret(page, "end")320 await page.keyboard.type("À retirer")321 await expect(body(dlg)).toContainText("À retirer")322 await page.keyboard.press("ControlOrMeta+z")323 await expect(body(dlg)).not.toContainText("À retirer")324 await page.keyboard.press("ControlOrMeta+Shift+z")325 await expect(body(dlg)).toContainText("À retirer")326 await page.keyboard.press("ControlOrMeta+z")327 await expect(body(dlg)).not.toContainText("À retirer")328 await axe(page, "desktop-rich")329 await shot(page, "desktop-light-rich")330 await dlg.getByRole("button", { name: "Envoyer", exact: true }).click()331 await expect(page.locator('[data-testid="delivery"]').last()).toContainText("Accepté pour livraison")332 await expect(dlg).toHaveCount(0)333 await delivered(page, C2)334 // ---- ce que le destinataire a réellement reçu335 const m = await received(page, C2, subject)336 expect(m.from[0].email).toBe(C1)337 expect(m.html).toMatch(/<strong>gras<\/strong>/)338 expect(m.html).toMatch(/<em>italique<\/em>/)339 expect(m.html).toMatch(/<ul>\s*<li>un<\/li>\s*<li>deux<\/li>\s*<\/ul>/)340 expect(m.html).toMatch(/<a href="https:\/\/example\.org\/guide"[^>]*>le guide<\/a>/)341 expect(m.html).toContain("été, naïve, 日本語")342 expect(m.html).not.toMatch(/blob:|data-cid||À retirer/)343 const src = /<img[^>]*src="cid:([^"]+)"[^>]*>/.exec(m.html ?? "")344 expect(src, "image référencée par cid:").not.toBeNull()345 expect(src![0]).toContain('alt="Logo d\'essai"')346 const inline = m.attachments.filter((a) => a.disposition === "inline")347 expect(inline).toHaveLength(1)348 expect(inline[0].type).toBe("image/png")349 expect(inline[0].cid).toBe(src![1])350 expect(m.attachments.filter((a) => a.disposition !== "inline").map((a) => a.name)).toEqual(["notes d'été.txt"])351 // version texte : lisible sans HTML352 expect(m.text).toContain("Bonjour gras et italique — été, naïve, 日本語.")353 expect(m.text).toMatch(/• un\s+• deux/)354 expect(m.text).toContain("le guide <https://example.org/guide>")355 // copie dans « Envoyés » de l'expéditeur356 await expect.poll(async () => (await messages(page, C1, "sent", subject)).length, { timeout: 20_000 }).toBe(1)357})358359test("répondre garde la citation, ses images et le fil ; l'image citée repart en ligne", async () => {360 await openBox(page, C2)361 await row(page, new RegExp(`Riche ${st.run}`)).click()362 await page.locator(".msg-foot").getByRole("button", { name: "Répondre", exact: true }).click()363 const dlg = composer(page)364 await expect(dlg.getByLabel("Objet :")).toHaveValue(`Re: Riche ${st.run}`)365 await expect(dlg.locator(".rcpt-chip")).toContainText("Compose Un")366 const quote = dlg.locator(".editor blockquote")367 await expect(quote).toContainText("Bonjour gras et italique")368 await expect(quote.locator("img[data-cid]")).toHaveCount(1)369 // l'image du message d'origine est affichée par la passerelle (aucune adresse distante)370 await expect(quote.locator("img[data-cid]")).toHaveAttribute("src", /^\/api\/jmap\//)371 await expect.poll(() => quote.locator("img[data-cid]").evaluate((el: HTMLImageElement) => el.naturalWidth)).toBe(96)372 // le curseur est dans le corps, au-dessus de la citation373 expect(await body(dlg).evaluate((el) => el === document.activeElement)).toBe(true)374 await caret(page, "start")375 await page.keyboard.type("Bien reçu, merci !")376 await shot(page, "desktop-light-reply")377 await page.keyboard.press("ControlOrMeta+Enter")378 await expect(page.locator('[data-testid="delivery"]').last()).toContainText("Accepté pour livraison")379 await delivered(page, C1)380 const m = await received(page, C1, `Re: Riche ${st.run}`)381 expect(m.inReplyTo?.length, "en-tête In-Reply-To").toBeGreaterThan(0)382 expect(m.html).toMatch(/Bien reçu, merci !/)383 expect(m.html).toMatch(/<blockquote[\s\S]*<strong>gras<\/strong>[\s\S]*<\/blockquote>/)384 const src = /<blockquote[\s\S]*<img[^>]*src="cid:([^"]+)"/.exec(m.html ?? "")385 expect(src, "image citée gardée").not.toBeNull()386 expect(m.attachments.filter((a) => a.disposition === "inline").map((a) => a.cid)).toEqual([src![1]])387 // la pièce jointe ordinaire d'origine n'est pas renvoyée dans une réponse388 expect(m.attachments.filter((a) => a.disposition !== "inline")).toHaveLength(0)389 expect(m.text).toContain("Bien reçu, merci !")390 expect(m.text).toMatch(/> Bonjour gras et italique/)391 await page.getByRole("button", { name: "Retour à la liste" }).click()392})393394test("plusieurs brouillons : enregistrés séparément, un seul identifiant sur 20 s de frappe, repris après rechargement", async () => {395 await openBox(page, C1)396 const subjectA = `Brouillon A ${st.run}`397 const subjectB = `Brouillon B ${st.run}`398 const dlg = await compose(page, { to: C3, subject: subjectA })399 await typeBody(page, dlg, "Texte du premier brouillon.")400 await expect(dlg.locator(".composer-save")).toHaveAttribute("data-save", "saved", { timeout: 15_000 })401 await expect(dlg.locator(".composer-save")).toHaveText("Enregistré")402 expect(draftCreates.filter((d) => d.subject === subjectA)).toHaveLength(1)403 // second message : le premier est réduit dans la barre du bas, sans être fermé404 await page.getByRole("button", { name: "Nouveau message" }).first().click()405 const dock = page.locator(".cmp-dock .composer-min")406 await expect(dock).toHaveCount(1)407 await expect(dock).toContainText(subjectA)408 await expect(dlg.getByLabel("Objet :")).toHaveValue("")409 await dlg.getByRole("combobox", { name: "À :" }).fill(C4)410 await dlg.getByRole("combobox", { name: "À :" }).press("Enter")411 await dlg.getByLabel("Objet :").fill(subjectB)412 // ---- 20 s de frappe continue : la copie locale suit, le serveur n'est sollicité qu'une fois, à la pause413 await body(dlg).click()414 const started = Date.now()415 let typed = 0416 while (Date.now() - started < 20_000) {417 await page.keyboard.type(`mot${typed++} `, { delay: 45 })418 }419 expect(draftCreates.filter((d) => d.subject === subjectB), "aucun enregistrement serveur pendant la frappe").toHaveLength(0)420 const local = await page.evaluate(() => JSON.parse(localStorage.getItem("spmail.draft") ?? "null") as { subject: string; html: string } | null)421 expect(local?.subject).toBe(subjectB)422 expect(local?.html).toContain("mot3 ")423 await expect(dlg.locator(".composer-save")).toHaveAttribute("data-save", "saved", { timeout: 15_000 })424 await page.waitForTimeout(5000)425 expect(draftCreates.filter((d) => d.subject === subjectB), "un seul brouillon créé sur le serveur").toHaveLength(1)426 expect(await messages(page, C1, "drafts", subjectB)).toHaveLength(1)427 // ---- bascule : chaque brouillon garde son contenu ; celui qu'on quitte est enregistré tout de suite s'il a changé428 await dock.locator(".composer-min-main").click()429 await expect(dlg.getByLabel("Objet :")).toHaveValue(subjectA)430 await expect(body(dlg)).toContainText("Texte du premier brouillon.")431 await expect(page.locator(".cmp-dock .composer-min")).toContainText(subjectB)432 await body(dlg).click()433 await caret(page, "end")434 await page.keyboard.type(" Suite ajoutée.")435 await shot(page, "desktop-light-two-drafts")436 await axe(page, "desktop-two-drafts")437 // Échap réduit (ne ferme pas, n'abandonne rien) et le focus revient à l'application438 await page.keyboard.press("Escape")439 await expect(dlg).toHaveCount(0)440 await expect(page.locator(".cmp-dock .composer-min")).toHaveCount(2)441 expect(await page.evaluate(() => document.activeElement !== document.body && document.activeElement !== null)).toBe(true)442 await expect(page.locator(`.cmp-dock .composer-min[data-save="saved"]`)).toHaveCount(2, { timeout: 15_000 })443 await expect.poll(async () => (await messages(page, C1, "drafts", subjectA)).map((m) => m.html ?? "").join("")).toContain("Suite ajoutée.")444 expect(await messages(page, C1, "drafts", subjectA), "l'ancienne version a été remplacée, pas doublée").toHaveLength(1)445 // ---- rechargement : les deux rédactions reviennent446 await page.reload()447 await expect(page.locator(".cmp-dock .composer-min")).toHaveCount(2)448 await page.locator(".cmp-dock .composer-min-main", { hasText: subjectB }).click()449 await expect(dlg.getByLabel("Objet :")).toHaveValue(subjectB)450 await expect(body(dlg)).toContainText("mot3 ")451 await discard(page)452 await page.locator(".cmp-dock .composer-min-main", { hasText: subjectA }).click()453 await expect(body(dlg)).toContainText("Texte du premier brouillon. Suite ajoutée.")454 await expect(dlg.locator(".rcpt-chip")).toHaveCount(1)455 await discard(page)456 await expect(page.locator(".cmp-dock")).toHaveCount(0)457 await expect.poll(async () => (await messages(page, C1, "drafts", `${st.run}`)).length).toBe(0)458})459460test("hors ligne : état annoncé, la fermeture garde le brouillon sur l'appareil, il part au retour du réseau", async () => {461 const subject = `Hors ligne compose ${st.run}`462 const dlg = await compose(page, { to: C3, subject })463 await context.setOffline(true)464 await typeBody(page, dlg, "Écrit sans réseau.")465 const save = dlg.locator(".composer-save")466 await expect(save).toHaveText("Hors ligne — conservé sur cet appareil")467 await shot(page, "desktop-light-offline")468 await dlg.getByRole("button", { name: "Enregistrer et fermer" }).click()469 await expect(dlg).toHaveCount(0)470 await expect(toastText(page, /reste sur cet appareil/)).toBeVisible()471 await expect(page.locator(".cmp-dock .composer-min")).toContainText(subject)472 expect(await page.evaluate(() => (JSON.parse(localStorage.getItem("spmail.draft") ?? "null") as { html: string } | null)?.html ?? "")).toContain("Écrit sans réseau.")473 await context.setOffline(false)474 await expect(page.locator('.cmp-dock .composer-min[data-save="saved"]')).toHaveCount(1, { timeout: 30_000 })475 expect(await messages(page, C1, "drafts", subject)).toHaveLength(1)476 await page.locator(".cmp-dock .composer-min-main").click()477 await expect(body(dlg)).toContainText("Écrit sans réseau.")478 await discard(page)479})480481test("envoyer plus tard : choix rapides, fuseau affiché, puis annulation — la rédaction se rouvre, rien ne part", async () => {482 const subject = `Différé ${st.run}`483 const dlg = await compose(page, { to: C3, subject })484 await typeBody(page, dlg, "À envoyer demain.")485 await dlg.getByRole("button", { name: "Autres options d'envoi" }).click()486 await shot(page, "desktop-light-send-menu")487 await page.getByRole("menuitem", { name: "Envoyer plus tard…" }).click()488 const later = page.getByRole("dialog", { name: "Envoyer plus tard" })489 await expect(later).toContainText("Fuseau horaire : America/Toronto (UTC−")490 await expect(later.locator(".cmp-when-preset")).toHaveCount(await later.locator(".cmp-when-preset").count())491 await later.getByLabel("Autre date et heure").fill("2020-01-01T10:00")492 await later.getByRole("button", { name: "Programmer l'envoi" }).click()493 await expect(later.getByRole("alert")).toContainText("à venir")494 await axe(page, "desktop-send-later")495 await shot(page, "desktop-light-send-later")496 await later.locator('.cmp-when-preset[data-preset="tomorrowMorning"]').click()497 await expect(dlg).toHaveCount(0)498 await expect(toastText(page, /Envoi programmé/)).toBeVisible()499 const scheduled = async () => (await api<{ data: { id: string; status: string }[] }>(page, "GET", "/api/v1/messages/scheduled")).data500 expect(await scheduled()).toHaveLength(1)501 await toastText(page, /Envoi programmé/).getByRole("button", { name: "Annuler" }).click()502 await expect(dlg).toBeVisible()503 await expect(dlg.getByLabel("Objet :")).toHaveValue(subject)504 await expect(body(dlg)).toContainText("À envoyer demain.")505 expect(await scheduled()).toHaveLength(0)506 await discard(page)507 expect(await messages(page, C3, "inbox", subject)).toHaveLength(0)508})509510test("réglages › Rédaction : délai d'annulation ; annuler dans le délai (rien n'arrive, tout revient), puis laisser partir (remis une fois)", async () => {511 // ---- le délai se règle dans les réglages512 await page.getByRole("link", { name: "Réglages" }).click()513 await page.locator(".page-nav").getByRole("link", { name: "Rédaction" }).click()514 await expect(page.getByRole("heading", { level: 3, name: "Annulation d'envoi" })).toBeVisible()515 const undo = page.getByRole("radiogroup", { name: "Annulation d'envoi" })516 await expect(undo.getByRole("radio", { name: "Désactivée" })).toHaveAttribute("aria-checked", "true")517 await undo.getByRole("radio", { name: "10 s" }).click()518 await expect(undo.getByRole("radio", { name: "10 s" })).toHaveAttribute("aria-checked", "true")519 await axe(page, "settings-composing")520 await shot(page, "desktop-light-settings-composing")521 expect((await api<{ undo_seconds: number }>(page, "GET", "/api/next/compose/prefs")).undo_seconds).toBe(10)522 await page.getByRole("link", { name: "Courrier" }).click()523 await openBox(page, C1)524 // ---- envoi retenu525 const subject = `Annulable ${st.run}`526 const dlg = await compose(page, { from: C3, to: C4, subject })527 await typeBody(page, dlg, "Message à rattraper.")528 await page.locator('.composer input[type="file"]').setInputFiles({ name: "contrat.txt", mimeType: "text/plain", buffer: Buffer.from("clause 1\n") })529 await expect(page.locator(".composer-att progress")).toHaveCount(0)530 await insertImage(page, dlg, { name: "large.png", buffer: WIDE })531 // la grande image a été réduite avant le téléversement532 await expect.poll(() => body(dlg).locator("img[data-cid]").evaluate((el: HTMLImageElement) => el.naturalWidth)).toBe(1600)533 await expect(dlg.locator(".composer-save")).toHaveAttribute("data-save", "saved", { timeout: 20_000 })534 const uploadsBefore = fileUploads535 await dlg.getByRole("button", { name: "Envoyer", exact: true }).click()536 const hold = toastText(page, /Envoi dans \d+ s/)537 await expect(hold).toBeVisible()538 await expect(dlg).toHaveCount(0)539 // pendant la retenue : jamais « envoyé », aucun suivi de remise540 expect(await hold.textContent()).not.toMatch(/envoyé/i)541 expect(await page.locator(".toast").allTextContents()).not.toContainEqual(expect.stringMatching(/message envoyé|a été envoyé/i))542 await expect(page.locator('[data-testid="delivery"]')).toHaveCount(0)543 await shot(page, "desktop-light-undo-toast")544 await axe(page, "desktop-undo-toast")545 expect(fileUploads - uploadsBefore, "chaque pièce est remise une fois à l'API").toBe(2)546 await hold.getByRole("button", { name: "Annuler" }).click()547 // ---- la rédaction se rouvre avec tout : destinataire, texte, image en ligne, pièce jointe548 await expect(dlg).toBeVisible()549 await expect(toastText(page, /Envoi annulé/).last()).toBeVisible()550 await expect(dlg.getByLabel("Objet :")).toHaveValue(subject)551 await expect(dlg.locator(".rcpt-chip")).toHaveCount(1)552 await expect(body(dlg)).toContainText("Message à rattraper.")553 await expect(dlg.locator(".composer-att")).toContainText("contrat.txt")554 await expect(body(dlg).locator("img[data-cid]")).toHaveCount(1)555 await expect.poll(() => body(dlg).locator("img[data-cid]").evaluate((el: HTMLImageElement) => el.naturalWidth)).toBe(1600)556 // le délai d'origine passe : le destinataire n'a rien reçu557 await page.waitForTimeout(13_000)558 expect(await messages(page, C4, "inbox", subject)).toHaveLength(0)559 await expect(page.locator('[data-testid="delivery"]')).toHaveCount(0)560 // ---- second envoi, sans annuler : il part à la fin du délai, une seule fois, sans retéléverser les pièces561 await typeBody(page, dlg, "Cette fois c'est bon. ")562 await dlg.getByRole("button", { name: "Envoyer", exact: true }).click()563 await expect(toastText(page, /Envoi dans \d+ s/)).toBeVisible()564 expect(fileUploads - uploadsBefore, "aucun nouveau téléversement après l'annulation").toBe(2)565 await expect(page.locator('[data-testid="delivery"]')).toHaveCount(1, { timeout: 20_000 })566 await expect(toastText(page, /Envoi dans/)).toHaveCount(0)567 await delivered(page, C4)568 const m = await received(page, C4, subject)569 expect(m.html).toContain("Cette fois c'est bon.")570 expect(m.attachments.filter((a) => a.disposition !== "inline").map((a) => a.name)).toEqual(["contrat.txt"])571 expect(m.attachments.filter((a) => a.disposition === "inline")).toHaveLength(1)572 await page.waitForTimeout(3000)573 expect(await messages(page, C4, "inbox", subject), "remis une seule fois").toHaveLength(1)574 expect(await messages(page, C3, "drafts", subject), "aucun brouillon résiduel").toHaveLength(0)575 await prefs(page, {})576})577578test("destinataire sensible : le serveur exige une confirmation (409), l'envoi n'a lieu qu'après accord explicite", async () => {579 const subject = `Sensible ${st.run}`580 const dlg = await compose(page, { from: C2, to: C4, subject })581 await typeBody(page, dlg, "Information réservée.")582 // la liste change « sur un autre appareil » après l'ouverture : seule la réponse du serveur peut le savoir583 await page.waitForTimeout(800)584 await prefs(page, { sensitive: [C4] })585 await dlg.getByRole("button", { name: "Envoyer", exact: true }).click()586 const confirm = page.getByRole("alertdialog", { name: "Confirmer l'envoi à un destinataire sensible" })587 await expect(confirm).toContainText(C4)588 await shot(page, "desktop-light-sensitive")589 await confirm.getByRole("button", { name: "Annuler" }).click()590 await expect(dlg).toBeVisible()591 await expect(page.locator('[data-testid="delivery"]')).toHaveCount(0)592 expect(await messages(page, C4, "inbox", subject)).toHaveLength(0)593 await dlg.getByRole("button", { name: "Envoyer", exact: true }).click()594 await page.getByRole("alertdialog", { name: "Confirmer l'envoi à un destinataire sensible" }).getByRole("button", { name: "Envoyer quand même" }).click()595 await expect(page.locator('[data-testid="delivery"]').last()).toContainText("Accepté pour livraison")596 await delivered(page, C4)597 expect((await received(page, C4, subject)).from[0].email).toBe(C2)598 // ---- liste connue du client : la confirmation vient avant même la requête, avec les autres contrôles599 const again = await compose(page, { to: C4, subject: "" })600 await typeBody(page, again, "Deuxième essai.")601 await again.getByRole("button", { name: "Envoyer", exact: true }).click()602 const checks = page.getByRole("alertdialog", { name: "Vérifier avant l'envoi" })603 await expect(checks.locator('[data-check="sensitive"]')).toContainText(C4)604 await expect(checks.locator('[data-check="noSubject"]')).toBeVisible()605 await checks.getByRole("button", { name: "Annuler" }).click()606 await discard(page)607 await prefs(page, {})608})609610test("pièce jointe annoncée mais absente : avertissement, sauf dans la citation et la signature ; destinataires en double signalés", async () => {611 const dlg = await compose(page, { to: C3, subject: `Oubli ${st.run}` })612 await typeBody(page, dlg, "Vous trouverez ci-joint le rapport.")613 await dlg.getByRole("button", { name: "Cc / Cci" }).click()614 await dlg.getByRole("combobox", { name: "Cc :" }).fill(C3.toUpperCase())615 await dlg.getByRole("combobox", { name: "Cc :" }).press("Enter")616 await expect(dlg.locator(".rcpt-chip.dup")).toHaveCount(2)617 await dlg.getByRole("button", { name: "Envoyer", exact: true }).click()618 const checks = page.getByRole("alertdialog", { name: "Vérifier avant l'envoi" })619 await expect(checks.locator('[data-check="missingAttachment"]')).toContainText("ci-joint")620 await expect(checks.locator('[data-check="duplicates"]')).toContainText(C3)621 await axe(page, "desktop-presend")622 await shot(page, "desktop-light-presend")623 await checks.getByRole("button", { name: "Annuler" }).click()624 await expect(dlg).toBeVisible()625 // un fichier joint : plus d'avertissement de pièce jointe626 await page.locator('.composer input[type="file"]').setInputFiles({ name: "rapport.txt", mimeType: "text/plain", buffer: Buffer.from("rapport\n") })627 await expect(page.locator(".composer-att progress")).toHaveCount(0)628 await dlg.getByRole("button", { name: "Envoyer", exact: true }).click()629 await expect(checks.locator('[data-check="duplicates"]')).toBeVisible()630 await expect(checks.locator('[data-check="missingAttachment"]')).toHaveCount(0)631 await checks.getByRole("button", { name: "Annuler" }).click()632 await discard(page)633 expect(await messages(page, C3, "inbox", `Oubli ${st.run}`)).toHaveLength(0)634})635636test("signatures : gestion dans les réglages, défaut par adresse, remplacement au changement d'expéditeur, jamais de doublon", async () => {637 await page.getByRole("link", { name: "Réglages" }).click()638 await page.locator(".page-nav").getByRole("link", { name: "Signatures", exact: true }).click()639 await expect(page.getByText("Aucune signature pour l'instant.")).toBeVisible()640 await page.getByRole("button", { name: "Nouvelle signature" }).click()641 const form = page.getByRole("form", { name: "Nouvelle signature" })642 await form.getByLabel("Nom").fill("Signature Un")643 await form.getByRole("textbox", { name: "Texte de la signature" }).click()644 await page.keyboard.type("Camille Un")645 await page.keyboard.press("Enter")646 await page.keyboard.press("ControlOrMeta+b")647 await page.keyboard.type(`Direction ${st.run}`)648 await form.getByRole("group", { name: "Par défaut pour les nouveaux messages de" }).getByLabel(C1, { exact: true }).check()649 await axe(page, "settings-signature-form")650 await shot(page, "desktop-light-settings-signature")651 await form.getByRole("button", { name: "Enregistrer" }).click()652 await expect(page.locator('[data-signature="Signature Un"]')).toContainText(`Direction ${st.run}`)653 await expect(page.locator('[data-signature="Signature Un"]')).toContainText(`Nouveaux messages : ${C1}`)654 // seconde signature, par défaut pour l'autre boîte (créée par l'API, comme le ferait une application)655 const addresses = (await api<{ data: { id: string; address: string }[] }>(page, "GET", "/api/v1/addresses")).data656 const idOf = (address: string) => addresses.find((a) => a.address === address)!.id657 await api(page, "POST", "/api/next/signatures", { name: "Signature Deux", html: `<div>Camille Deux</div><div>Ventes ${st.run}</div>`, default_for: [idOf(C2)] })658 await page.getByRole("link", { name: "Courrier" }).click()659 await openBox(page, C1)660 // ---- nouveau message depuis C1 : sa signature par défaut661 const dlg = await compose(page, {})662 const sig = dlg.locator(".editor .spm-signature")663 await expect(sig).toHaveCount(1)664 await expect(sig).toContainText(`Camille UnDirection ${st.run}`)665 await expect(sig.locator("strong")).toHaveText(`Direction ${st.run}`)666 await expect(dlg.getByLabel("Signature :")).toHaveValue(/.+/)667 await typeBody(page, dlg, "Texte tapé avant de changer d'expéditeur.")668 // ---- changement d'expéditeur : remplacée, jamais doublée, le texte reste669 const from = dlg.getByLabel("De :")670 const pick = async (address: string) => from.selectOption({ label: (await from.locator("option").allTextContents()).find((o) => o.includes(address))! })671 await pick(C2)672 await expect(sig).toHaveCount(1)673 await expect(sig).toContainText(`Camille DeuxVentes ${st.run}`)674 await expect(body(dlg)).not.toContainText("Camille Un")675 await expect(body(dlg)).toContainText("Texte tapé avant de changer d'expéditeur.")676 await pick(C1)677 await expect(sig).toHaveCount(1)678 await expect(sig).toContainText("Camille Un")679 await expect(body(dlg)).not.toContainText("Camille Deux")680 await shot(page, "desktop-light-signature")681 // ---- sélecteur : aucune signature, puis une autre682 await dlg.getByLabel("Signature :").selectOption({ label: "Aucune signature" })683 await expect(sig).toHaveCount(0)684 await dlg.getByLabel("Signature :").selectOption({ label: "Signature Deux" })685 await expect(sig).toContainText("Camille Deux")686 // ---- bloc réécrit à la main : un changement d'expéditeur n'y touche plus et n'en ajoute pas687 await body(dlg).focus()688 await sig.evaluate((el) => {689 const text = document.createTreeWalker(el, NodeFilter.SHOW_TEXT).nextNode()!690 getSelection()!.collapse(text, 7)691 })692 await page.keyboard.type(" Tremblay")693 await expect(sig).toContainText("Camille Tremblay Deux")694 await pick(C3)695 await expect(body(dlg).getByText("Camille Tremblay Deux")).toHaveCount(1)696 await expect(dlg.getByLabel("Signature :")).toHaveValue("none")697 await pick(C1)698 await expect(body(dlg).getByText("Camille Tremblay Deux")).toHaveCount(1)699 await expect(body(dlg)).not.toContainText("Camille Un")700 await discard(page)701})702703test("extraits : gestion dans les réglages, expansion de « ;raccourci » en riche et en texte brut, sélecteur", async () => {704 await page.getByRole("link", { name: "Réglages" }).click()705 await page.locator(".page-nav").getByRole("link", { name: "Extraits" }).click()706 await page.getByRole("button", { name: "Nouvel extrait" }).click()707 const form = page.getByRole("form", { name: "Nouvel extrait" })708 await form.getByLabel("Nom").fill("Remerciement")709 await form.getByLabel("Raccourci").fill(";merci")710 await form.getByLabel("Objet proposé").fill(`Suivi ${st.run}`)711 await form.getByRole("textbox", { name: "Texte de l'extrait" }).click()712 await page.keyboard.type("Merci de votre message, je reviens vers vous ")713 await page.keyboard.press("ControlOrMeta+i")714 await page.keyboard.type("rapidement")715 await page.keyboard.press("ControlOrMeta+i")716 await page.keyboard.type(".")717 await shot(page, "desktop-light-settings-snippet")718 await axe(page, "settings-snippet-form")719 await form.getByRole("button", { name: "Enregistrer" }).click()720 await expect(page.locator('[data-snippet="Remerciement"]')).toContainText(";merci")721 await page.getByRole("link", { name: "Courrier" }).click()722 await openBox(page, C1)723 const dlg = await compose(page, { to: C3 })724 await body(dlg).click()725 await caret(page, "start")726 await page.keyboard.type("Bonjour, ;merci ")727 await expect(body(dlg)).toContainText("Bonjour, Merci de votre message, je reviens vers vous rapidement.")728 await expect(body(dlg)).not.toContainText(";merci")729 await expect(body(dlg).locator("em")).toHaveText("rapidement")730 // l'objet proposé est posé parce que le message n'en avait pas731 await expect(dlg.getByLabel("Objet :")).toHaveValue(`Suivi ${st.run}`)732 // un raccourci inconnu reste tel quel733 await page.keyboard.type(" ;inconnu ")734 await expect(body(dlg)).toContainText(";inconnu")735 // sélecteur d'extraits, au clavier736 await dlg.getByRole("button", { name: "Insérer un extrait" }).click()737 const picker = page.getByRole("dialog", { name: "Extraits" })738 await picker.getByRole("combobox", { name: "Chercher un extrait" }).fill("remer")739 await expect(picker.getByRole("option")).toHaveCount(1)740 await shot(page, "desktop-light-snippet-picker")741 await axe(page, "desktop-snippet-picker")742 await page.keyboard.press("Enter")743 await expect(picker).toHaveCount(0)744 await expect(body(dlg).getByText("Merci de votre message")).toHaveCount(2)745 // texte brut : même expansion746 await dlg.getByRole("button", { name: "Texte brut" }).click()747 const area = dlg.locator("textarea.editor")748 await area.fill("")749 await area.pressSequentially("Re ;merci ")750 await expect(area).toHaveValue("Re Merci de votre message, je reviens vers vous rapidement.")751 await discard(page)752})753754test("destinataires : autocomplétion au clavier, groupe déployé, liste collée, pastilles au clavier, déplacement entre champs", async () => {755 const zoe = `zoe-${st.run}@example.org`756 const group = await api<{ id: string }>(page, "POST", "/api/next/contact-groups", { name: `Équipe ${st.run}` })757 await api(page, "POST", "/api/next/contacts", { name: "Zoé Compose", emails: [{ email: zoe }], favorite: true, groups: [group.id] })758 await api(page, "POST", "/api/next/contacts", { name: "Marc Compose", emails: [{ email: `marc-${st.run}@example.org` }], groups: [group.id] })759 const dlg = await compose(page, {})760 const to = dlg.getByRole("combobox", { name: "À :" })761 await to.pressSequentially("zoé com")762 const options = dlg.getByRole("listbox", { name: "Suggestions de destinataires" }).first().getByRole("option")763 await expect(options.first()).toContainText("Zoé Compose")764 await expect(to).toHaveAttribute("aria-expanded", "true")765 await shot(page, "desktop-light-autocomplete")766 await axe(page, "desktop-autocomplete")767 await page.keyboard.press("ArrowDown")768 await expect(to).toHaveAttribute("aria-activedescendant", /.+/)769 await page.keyboard.press("Enter")770 await expect(dlg.locator('[data-field="to"] .rcpt-chip')).toHaveText(["Zoé Compose"])771 await expect(to).toHaveValue("")772 // un groupe se déploie en ses membres (celui déjà présent n'est pas doublé)773 await to.pressSequentially("équipe")774 await expect(options.filter({ hasText: `Équipe ${st.run}` })).toContainText("Groupe · 2 membres")775 await page.keyboard.press("ArrowDown")776 await page.keyboard.press("Enter")777 await expect(dlg.locator('[data-field="to"] .rcpt-chip')).toHaveText(["Zoé Compose", "Marc Compose"])778 // liste collée ou saisie : virgules, points-virgules ; l'entrée invalide reste à corriger779 await to.fill(`a-${st.run}@example.org; "Roy, Léa" <lea-${st.run}@example.org>, pas-une-adresse,`)780 await expect(dlg.locator('[data-field="to"] .rcpt-chip')).toHaveCount(4)781 await expect(to).toHaveValue("pas-une-adresse")782 await expect(to).toHaveAttribute("aria-invalid", "true")783 await expect(dlg.locator('[data-field="to"]').getByRole("alert")).toContainText("Adresse non valide")784 await to.fill("")785 // au clavier : flèche gauche entre dans les pastilles, Suppr retire, Alt+↓ déplace vers Cc786 await to.press("ArrowLeft")787 await expect(dlg.locator('[data-field="to"] .cmp-token-main').last()).toBeFocused()788 await page.keyboard.press("Delete")789 await expect(dlg.locator('[data-field="to"] .rcpt-chip')).toHaveCount(3)790 await to.press("ArrowLeft")791 await page.keyboard.press("ArrowLeft")792 await expect(dlg.locator('[data-field="to"] .cmp-token-main').nth(1)).toBeFocused()793 await page.keyboard.press("Alt+ArrowDown")794 await expect(dlg.locator('[data-field="cc"] .rcpt-chip')).toHaveText(["Marc Compose"])795 await expect(dlg.locator('[data-field="to"] .rcpt-chip')).toHaveCount(2)796 // à la souris : une pastille glissée de À vers Cci change de champ797 await dlg.locator('[data-field="to"] .rcpt-chip').first().dragTo(dlg.locator('[data-field="bcc"] .rcpt-box'))798 await expect(dlg.locator('[data-field="bcc"] .rcpt-chip')).toHaveText(["Zoé Compose"])799 await expect(dlg.locator('[data-field="to"] .rcpt-chip')).toHaveCount(1)800 // hors ligne : l'historique d'envoi prend le relais (C2 a déjà reçu un message de cette boîte)801 await context.setOffline(true)802 await to.pressSequentially("web-c2")803 await expect(options.first()).toContainText(C2)804 await context.setOffline(false)805 await to.fill("")806 await discard(page)807})808809test("modèle de la bibliothèque : variables remplies, rendu par l'API, inséré comme contenu modifiable", async () => {810 await api(page, "POST", "/api/templates", {811 name: `Relance ${st.run}`, subject: "Relance pour {{prenom}}", html: `<table width="600"><tr><td><h1 style="color:#2c5b4d">Bonjour {{prenom}}</h1><p>Votre dossier <b>{{dossier}}</b> attend une réponse.</p></td></tr></table>`,812 variables: [{ name: "prenom", description: "Prénom du destinataire", example: "Alex", required: true }, { name: "dossier", description: "", example: "D-100", required: false }],813 })814 const dlg = await compose(page, { to: C3 })815 await typeBody(page, dlg, "")816 await dlg.getByRole("button", { name: "Insérer un modèle" }).click()817 const tpl = page.getByRole("dialog", { name: "Modèles" })818 await tpl.getByRole("button", { name: new RegExp(`Relance ${st.run}`) }).click()819 const fill = page.getByRole("dialog", { name: `Modèle : Relance ${st.run}` })820 await fill.getByLabel("{{prenom}} *").fill("Maude <script>")821 await fill.getByLabel("{{dossier}}").fill("D-42")822 await shot(page, "desktop-light-template")823 await axe(page, "desktop-template")824 await fill.getByRole("button", { name: "Insérer dans le message" }).click()825 await expect(fill).toHaveCount(0)826 await expect(body(dlg)).toContainText("Bonjour Maude <script>")827 await expect(body(dlg)).toContainText("Votre dossier D-42 attend une réponse.")828 await expect(body(dlg).locator("script")).toHaveCount(0)829 await expect(dlg.getByLabel("Objet :")).toHaveValue("Relance pour Maude <script>")830 await discard(page)831})832833test("expéditeur alias : même chemin d'envoi, l'en-tête From est l'alias", async () => {834 const subject = `Alias ${st.run}`835 const dlg = await compose(page, { from: ALIAS, to: C2, subject })836 await expect(dlg.getByLabel("De :")).toHaveAttribute("data-via", "api")837 await typeBody(page, dlg, "Envoyé depuis un alias.")838 // « envoyer et me rappeler » : même envoi, un rappel est créé côté serveur une fois le message parti839 await dlg.getByRole("button", { name: "Autres options d'envoi" }).click()840 await page.getByRole("menuitem", { name: "Envoyer et me rappeler sans réponse…" }).click()841 const remind = page.getByRole("dialog", { name: "Envoyer et me rappeler" })842 await expect(remind.getByLabel("Seulement si personne n'a répondu")).toBeChecked()843 await shot(page, "desktop-light-remind")844 await remind.locator('.cmp-when-preset[data-preset="in3d"]').click()845 await expect(page.locator('[data-testid="delivery"]').last()).toContainText("Accepté pour livraison")846 await expect(toastText(page, /Rappel prévu le/)).toBeVisible()847 await delivered(page, C2)848 const m = await received(page, C2, subject)849 expect(m.from[0].email).toBe(ALIAS)850 expect(m.from[0].name).toBe("Alias Compose")851 await expect852 .poll(async () => (await api<{ data: { subject: string; only_if_no_reply: boolean; status: string }[] }>(page, "GET", "/api/next/reminders?status=pending")).data.filter((r) => r.subject === subject).map((r) => r.only_if_no_reply), { timeout: 20_000 })853 .toEqual([true])854})855856test("brouillon avec image en ligne : relu depuis « Brouillons » ; repris sur un autre appareil, les deux versions sont gardées", async () => {857 const subject = `Image brouillon ${st.run}`858 const dlg = await compose(page, { to: C3, subject })859 await typeBody(page, dlg, "Brouillon illustré.")860 await insertImage(page, dlg, { name: "logo.png", buffer: LOGO })861 await expect(body(dlg).locator("img[data-cid]")).toHaveCount(1)862 await expect(dlg.locator(".composer-save")).toHaveAttribute("data-save", "saved", { timeout: 20_000 })863 await dlg.getByRole("button", { name: "Enregistrer et fermer" }).click()864 await expect(dlg).toHaveCount(0)865 const stored = await messages(page, C1, "drafts", subject)866 expect(stored).toHaveLength(1)867 expect(stored[0].html).toMatch(/<img[^>]*src="cid:/)868 expect(stored[0].attachments.filter((a) => a.disposition === "inline")).toHaveLength(1)869 // ---- relu du serveur (plus aucune copie locale) : l'image est là, servie par la passerelle870 expect(await page.evaluate(() => localStorage.getItem("spmail.draft"))).toBeNull()871 await page.getByRole("link", { name: /^Brouillons/ }).click()872 await row(page, new RegExp(subject)).click()873 await expect(dlg.getByLabel("Objet :")).toHaveValue(subject)874 const img = body(dlg).locator("img[data-cid]")875 await expect(img).toHaveAttribute("src", /^\/api\/jmap\//)876 await expect.poll(() => img.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBe(96)877 await expect(dlg.locator(".composer-save")).toHaveAttribute("data-save", "saved")878 // ouvrir un brouillon ne le réenregistre pas879 const before = draftCreates.filter((d) => d.subject === subject).length880 await page.waitForTimeout(3000)881 expect(draftCreates.filter((d) => d.subject === subject)).toHaveLength(before)882 // ---- « un autre appareil » remplace la version du serveur pendant que celle-ci est ouverte ici883 await page.evaluate(884 async ({ address, id, subject }) => {885 const me = await (await fetch("/api/me")).json()886 const mb = me.mailboxes.find((m: { address: string }) => m.address === address).id887 const session = await (await fetch(`/api/jmap/${mb}/session`)).json()888 const accountId = session.primaryAccounts["urn:ietf:params:jmap:mail"]889 const call = async (methodCalls: unknown[]) => (await (await fetch(`/api/jmap/${mb}/api`, { method: "POST", headers: { "content-type": "application/json", "x-spmail": "1" }, body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"], methodCalls }) })).json()).methodResponses890 const drafts = ((await call([["Mailbox/get", { accountId, properties: ["role"] }, "m"]]))[0][1].list as { id: string; role: string }[]).find((b) => b.role === "drafts")!.id891 await call([["Email/set", { accountId, destroy: [id], create: { o: { mailboxIds: { [drafts]: true }, keywords: { $seen: true }, subject, bodyValues: { t: { value: "Version de l'autre appareil." } }, textBody: [{ partId: "t", type: "text/plain" }] } } }, "s"]])892 },893 { address: C1, id: stored[0].id, subject },894 )895 await body(dlg).click()896 await caret(page, "start")897 await page.keyboard.type("Version d'ici. ")898 await dlg.getByRole("button", { name: "Réduire", exact: true }).click()899 await expect(toastText(page, /autre appareil/)).toBeVisible({ timeout: 15_000 })900 await expect.poll(async () => (await messages(page, C1, "drafts", subject)).length).toBe(2)901 const both = (await messages(page, C1, "drafts", subject)).map((m) => `${m.html ?? ""}${m.text ?? ""}`)902 expect(both.some((t) => t.includes("Version d'ici."))).toBe(true)903 expect(both.some((t) => t.includes("Version de l'autre appareil."))).toBe(true)904 await page.locator(".cmp-dock .composer-min-main").click()905 await discard(page)906 await page.getByRole("link", { name: /^Boîte de réception/ }).click()907})908909test("fenêtre : pleine largeur avec focus piégé, trois thèmes sans défaut d'accessibilité, dépôt de fichiers", async () => {910 const dlg = await compose(page, { to: C3, subject: `Thèmes ${st.run}` })911 await typeBody(page, dlg, "Un message pour les captures.")912 // ---- saisie par composition (accents morts, japonais…) : le navigateur garde la main, le texte arrive intact913 const cdp = await context.newCDPSession(page)914 await cdp.send("Input.imeSetComposition", { text: "に", selectionStart: 1, selectionEnd: 1 })915 await cdp.send("Input.imeSetComposition", { text: "にほ", selectionStart: 2, selectionEnd: 2 })916 await cdp.send("Input.insertText", { text: "日本" })917 await cdp.detach()918 await expect(body(dlg)).toContainText("Un message pour les captures.日本")919 // ---- collage riche hostile : réduit à la liste blanche avant d'entrer dans la page (ni image distante, ni script)920 const paste = (data: Record<string, string>, plain = false) =>921 body(dlg).evaluate(922 (el, { data, plain }) => {923 if (plain) el.dispatchEvent(new KeyboardEvent("keydown", { key: "v", code: "KeyV", metaKey: true, ctrlKey: true, shiftKey: true, bubbles: true }))924 const dt = new DataTransfer()925 for (const [type, value] of Object.entries(data)) dt.setData(type, value)926 el.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true }))927 },928 { data, plain },929 )930 await paste({ "text/html": `<span style="color:red" onclick="window.pwned=1"> Collé <b>riche</b><img src="https://evil.example/suivi.gif"><script>window.pwned=1</script><iframe src="https://evil.example"></iframe></span>`, "text/plain": " Collé riche" })931 await expect(body(dlg)).toContainText("日本 Collé riche")932 await expect(body(dlg).locator("strong", { hasText: "riche" })).toHaveCount(1)933 expect(await body(dlg).evaluate((el) => el.querySelectorAll("img, script, iframe, [onclick]").length)).toBe(0)934 // ---- coller sans mise en forme (⇧⌘V) : le texte seul935 await paste({ "text/html": "<h1>Titre <i>collé</i></h1>", "text/plain": " texte seul" }, true)936 await expect(body(dlg)).toContainText("Collé riche texte seul")937 expect(await body(dlg).evaluate((el) => el.querySelectorAll("i, em").length)).toBe(0)938 expect(await page.evaluate(() => (window as unknown as { pwned?: number }).pwned)).toBeUndefined()939 await page.keyboard.press("Enter")940 await tool(dlg, "Titre").click()941 await page.keyboard.type("Ordre du jour")942 await page.keyboard.press("Enter")943 await tool(dlg, "Liste numérotée").click()944 await page.keyboard.type("Budget")945 await page.keyboard.press("Enter")946 await page.keyboard.type("Calendrier")947 await page.keyboard.press("Enter")948 await page.keyboard.press("Enter")949 await tool(dlg, "Citation").click()950 await page.keyboard.type("Une citation courte.")951 await insertImage(page, dlg, { name: "logo.png", buffer: LOGO })952 await expect(body(dlg).locator("img[data-cid]")).toHaveCount(1)953 await page.locator('.composer input[type="file"]').setInputFiles([954 { name: "devis 2026.pdf", mimeType: "application/pdf", buffer: Buffer.from("%PDF-1.4\n") },955 { name: "budget.xlsx", mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", buffer: Buffer.alloc(2048) },956 { name: "photo.png", mimeType: "image/png", buffer: LOGO },957 ])958 await expect(dlg.locator(".composer-att")).toHaveCount(3)959 await expect(dlg.locator(".composer-att progress")).toHaveCount(0)960 await expect(dlg.locator(".composer-att img")).toHaveCount(1)961 // réordonner au clavier : Alt+→ déplace la pièce962 await dlg.locator(".cmp-att-main").first().focus()963 await page.keyboard.press("Alt+ArrowRight")964 await expect(dlg.locator(".cmp-att-name")).toHaveText(["budget.xlsx", "devis 2026.pdf", "photo.png"])965 for (const [theme, label] of THEMES) {966 await setTheme(page, label, theme)967 await axe(page, `desktop-${theme}`)968 await shot(page, `desktop-${theme}-composer`)969 }970 // ---- dépôt de fichiers : zones nettes971 await dlg.evaluate((el) => {972 const dt = new DataTransfer()973 dt.items.add(new File([new Uint8Array(8)], "glisse.png", { type: "image/png" }))974 el.dispatchEvent(new DragEvent("dragenter", { bubbles: true, dataTransfer: dt }))975 })976 await expect(dlg.locator(".cmp-drop-zone")).toHaveCount(2)977 await page.waitForTimeout(300)978 await shot(page, "desktop-midnight-drop")979 await dlg.evaluate((el) => {980 const dt = new DataTransfer()981 dt.items.add(new File([new Uint8Array(8)], "glisse.png", { type: "image/png" }))982 el.dispatchEvent(new DragEvent("dragleave", { bubbles: true, dataTransfer: dt }))983 })984 await expect(dlg.locator(".cmp-drop")).toHaveCount(0)985 // ---- pleine largeur : fenêtre modale, le focus n'en sort pas986 await setTheme(page, "Sombre", "dark")987 await dlg.getByRole("button", { name: "Agrandir la fenêtre" }).click()988 await expect(dlg).toHaveAttribute("aria-modal", "true")989 expect((await dlg.boundingBox())!.width).toBeGreaterThan(1300)990 await dlg.getByRole("button", { name: "Supprimer le brouillon" }).focus()991 await page.keyboard.press("Tab")992 expect(await dlg.evaluate((el) => el.contains(document.activeElement))).toBe(true)993 await page.keyboard.press("Shift+Tab")994 await page.keyboard.press("Shift+Tab")995 expect(await dlg.evaluate((el) => el.contains(document.activeElement))).toBe(true)996 await axe(page, "desktop-wide")997 await shot(page, "desktop-dark-wide")998 await dlg.getByRole("button", { name: "Réduire la taille de la fenêtre" }).click()999 await expect(dlg).not.toHaveAttribute("aria-modal", "true")1000 await setTheme(page, "Clair", "light")1001 await discard(page)1002})10031004test("téléphone : rédaction plein écran, focus piégé, barre de mise en forme, brouillons réduits au-dessus de la barre du bas", async ({ browser }) => {1005 const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: "fr-CA", timezoneId: "America/Toronto", storageState: storage, isMobile: true, hasTouch: true, deviceScaleFactor: 2 })1006 const p = await ctx.newPage()1007 const authn = await addAuthenticator(ctx, p)1008 await importCredential(authn, 4000)1009 await p.goto("/")1010 if (await p.getByRole("button", { name: "Se connecter avec une clé d'accès" }).count()) await p.getByRole("button", { name: "Se connecter avec une clé d'accès" }).click()1011 const nav = p.getByRole("navigation", { name: "Navigation principale" })1012 await expect(nav).toBeVisible()1013 await nav.getByRole("button", { name: "Écrire" }).tap()1014 const dlg = composer(p)1015 await expect(dlg).toBeVisible()1016 await expect(dlg).toHaveAttribute("aria-modal", "true")1017 // (la fenêtre arrive en glissant : on mesure une fois posée)1018 await expect.poll(async () => dlg.boundingBox().then((b) => [Math.round(b!.width), Math.round(b!.height), Math.round(b!.y)])).toEqual([390, 844, 0])1019 await dlg.getByRole("combobox", { name: "À :" }).fill(C3)1020 await dlg.getByLabel("Objet :").fill(`Téléphone ${st.run}`)1021 await body(dlg).click()1022 await p.keyboard.type("Écrit au pouce. ")1023 await tool(dlg, "Gras").tap()1024 await p.keyboard.type("Important")1025 await expect(body(dlg).locator("strong", { hasText: "Important" })).toHaveText("Important")1026 // le clic sous le texte n'a pas mis le curseur dans la signature (qui se termine en gras)1027 await expect(body(dlg).locator(".spm-signature")).not.toContainText("pouce")1028 await p.locator('.composer input[type="file"]').setInputFiles({ name: "billet.pdf", mimeType: "application/pdf", buffer: Buffer.from("%PDF-1.4\n") })1029 await expect(dlg.locator(".composer-att progress")).toHaveCount(0)1030 // rien ne déborde en largeur ; les cibles tactiles font au moins 40 px1031 expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)1032 expect((await tool(dlg, "Gras").boundingBox())!.height).toBeGreaterThanOrEqual(40)1033 for (const [theme] of THEMES) {1034 await p.evaluate((theme) => document.documentElement.setAttribute("data-theme", theme), theme)1035 // les couleurs changent en fondu (120 ms) : on mesure une fois le thème posé1036 await p.waitForTimeout(400)1037 await axe(p, `phone-${theme}`, "section.composer")1038 await shot(p, `phone-${theme}-composer`)1039 }1040 await p.evaluate(() => document.documentElement.setAttribute("data-theme", "light"))1041 // options d'envoi au pouce1042 await dlg.getByRole("button", { name: "Autres options d'envoi" }).tap()1043 await expect(p.getByRole("menuitem", { name: "Envoyer plus tard…" })).toBeVisible()1044 await shot(p, "phone-light-send-menu")1045 await p.keyboard.press("Escape")1046 // réduire : le brouillon passe au-dessus de la barre du bas, puis se rouvre1047 await dlg.getByRole("button", { name: "Réduire", exact: true }).tap()1048 await expect(dlg).toHaveCount(0)1049 const dock = p.locator(".cmp-dock .composer-min")1050 await expect(dock).toContainText(`Téléphone ${st.run}`)1051 const navBox = (await nav.boundingBox())!1052 // (la pastille arrive en glissant : on mesure une fois posée)1053 await expect.poll(async () => (await dock.boundingBox().then((b) => b!.y + b!.height)) <= navBox.y + 1).toBe(true)1054 await shot(p, "phone-light-dock")1055 await dock.locator(".composer-min-main").tap()1056 await expect(body(dlg)).toContainText("Écrit au pouce. Important")1057 await dlg.getByRole("button", { name: "Supprimer le brouillon" }).tap()1058 await p.getByRole("alertdialog").getByRole("button", { name: "Supprimer le brouillon" }).tap()1059 await expect(dlg).toHaveCount(0)1060 await ctx.close()1061})10621063test("aucune erreur de console ni requête hors de l'application pendant le parcours", async () => {1064 const relevant = consoleErrors.filter(1065 (e) =>1066 // attendus : 409 du destinataire sensible, réseau coupé par les essais hors ligne1067 !/Failed to load resource: the server responded with a status of (401|404|409|502)/.test(e) &&1068 !/ERR_INTERNET_DISCONNECTED/.test(e) &&1069 // émis par l'enregistreur de traces de Playwright dans le cadre de lecture sans scripts (voir desktop.spec.ts)1070 !/Blocked script execution in 'about:srcdoc'/.test(e),1071 )1072 expect(relevant).toEqual([])1073})1074