Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : tests/e2e/next-prod/search.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 « search » : langage du serveur en pastilles, suggestions, validation en direct, portée (une boîte / toutes),44// pages à curseur, regroupement par fil, lecteur, actions groupées, recherches enregistrées, panneau de filtres, repli hors ligne, téléphone.45import { expect, test, type Page } from "@playwright/test"46import { list, row, toastText } from "../helpers"47import { THEMES, type Part, type Seed } from "./harness"4849const box = (p: Page) => p.getByRole("searchbox", { name: "Rechercher dans le courrier" })50const chips = (p: Page) => p.locator(".nx-sb-chip")51const count = (p: Page) => p.getByTestId("search-count")52const scope = (p: Page) => p.getByRole("group", { name: "Portée de la recherche" })53const suggestions = (p: Page) => p.getByRole("listbox", { name: "Suggestions de recherche" })54const smart = (p: Page) => p.locator('#sidebar [data-slot="smart"]')55const options = (p: Page) => list(p).getByRole("option")5657export const searchPart: Part = (h) => {58 const R = () => h().run59 const alice = () => `alice-${R()}`60 const lot = () => `lot-${R()}`61 const s = (x: string) => `${x} ${R()}`62 let labelName = ""63 let idsP1: string[] = []64 /** Lance une requête depuis le champ (pastilles existantes retirées d'abord). */65 const search = async (p: Page, q: string) => {66 if (await p.getByRole("button", { name: "Effacer la recherche" }).count()) await p.getByRole("button", { name: "Effacer la recherche" }).click()67 await box(p).fill(q)68 await box(p).press("Enter")69 }70 /** Boîte de réception de la boîte donnée, d'où que l'on vienne (recherche en cours comprise). */71 const home = async (p: Page, address: string) => {72 await p.goto(`/m/${await mbIndex(p, address)}/inbox`)73 await expect(p.getByRole("heading", { level: 1, name: "Boîte de réception" })).toBeVisible()74 await expect(p.getByRole("heading", { level: 2, name: address })).toBeVisible()75 await expect(p.locator(".nx-sb")).toBeVisible() // le module de recherche (chargé après la connexion) a pris le champ76 }77 const mbIndex = async (p: Page, address: string) => (await h().api<{ mailboxes: { address: string }[] }>(p, "GET", "/api/me")).mailboxes.findIndex((m) => m.address === address)7879 test("search : semis (deux boîtes, pièces jointes, favori, fil, libellé, 72 messages pour les pages)", async () => {80 test.setTimeout(240_000)81 const { page, P1, P2 } = h()82 const named1: Seed[] = [83 { subject: s("Devis toiture"), from: ["Alice Tremblay", `${alice()}@fournisseur.test`], preview: "Voici le devis demandé pour la toiture.", attachments: [{ name: "devis-toiture.txt", type: "text/plain", text: "Devis toiture : 12 400 $" }], minutesAgo: 30 },84 { subject: s("Compte rendu"), from: ["Alice Tremblay", `${alice()}@fournisseur.test`], preview: "Compte rendu de la rencontre de chantier.", keywords: ["$flagged", "$seen"], minutesAgo: 40 },85 { subject: s("Facture hiver"), from: ["Bob Gagnon", `bob-${R()}@compta.test`], preview: "Facture de déneigement de la saison.", minutesAgo: 50 },86 { subject: s("Fil chantier"), from: ["Dana Roy", `dana-${R()}@chantier.test`], preview: "Premier message du fil.", messageId: `fil-1-${R()}@chantier.test`, minutesAgo: 70 },87 { subject: `Re: ${s("Fil chantier")}`, from: ["Dana Roy", `dana-${R()}@chantier.test`], preview: "Suite du fil.", messageId: `fil-2-${R()}@chantier.test`, references: `fil-1-${R()}@chantier.test`, minutesAgo: 60 },88 ]89 idsP1 = await h().seed(page, P1, named1)90 await h().seed(page, P2, [91 { subject: s("Devis fenêtres"), from: ["Alice Tremblay", `${alice()}@fournisseur.test`], preview: "Le devis des fenêtres, avec le plan.", attachments: [{ name: "plan-fenetres.txt", type: "text/plain", text: "Plan des fenêtres" }], minutesAgo: 35 },92 { subject: s("Relance"), from: ["Carl Morin", `carl-${R()}@relance.test`], preview: "Avez-vous reçu ma proposition ?", minutesAgo: 45 },93 ])94 // deux lots entrelacés dans le temps (P1 aux minutes entières, P2 aux demies) : les pages mêlent les deux boîtes95 const batch = (from: number, offset: number): Seed[] => Array.from({ length: 36 }, (_, i) => ({ subject: s(`Lot pagination n° ${String(from + i).padStart(3, "0")}`), from: ["Lot Série", `${lot()}@serie.test`] as [string, string], preview: `Message ${from + i} du lot.`, minutesAgo: 100 + i + offset }))96 await h().seed(page, P1, batch(1, 0))97 await h().seed(page, P2, batch(101, 0.5))98 // un libellé créé par l'API, posé par JMAP comme le ferait un autre client99 labelName = `Chantier ${R()}`100 const label = await h().api<{ keyword: string }>(page, "POST", "/api/next/labels", { name: labelName })101 await h().jmap(page, P1, [["Email/set", { update: { [idsP1[2]]: { [`keywords/${label.keyword}`]: true } } }, "u"]])102 // un contact pour les suggestions103 await h().api(page, "POST", "/api/next/contacts", { name: "Alice Tremblay", emails: [{ email: `${alice()}@fournisseur.test` }] })104 // le serveur trouve bien tout (l'index plein texte du serveur de courrier est asynchrone)105 await expect.poll(async () => (await h().api<{ data: unknown[] }>(page, "GET", `/api/next/search?q=${encodeURIComponent(`from:${lot()}`)}&limit=100`)).data.length, { timeout: 60_000 }).toBe(72)106 await expect.poll(async () => (await h().api<{ data: unknown[] }>(page, "GET", `/api/next/search?q=${encodeURIComponent(`from:${alice()} has:attachment`)}`)).data.length, { timeout: 60_000 }).toBe(2)107 })108109 test("search : opérateurs en pastilles, portée boîte courante ⇄ toutes les boîtes, libellé", async () => {110 const { page, P1, P2 } = h()111 await home(page, P1)112 // la recherche d'origine (Email/query du navigateur) ne doit plus tourner quand le serveur cherche113 const legacyQueries: string[] = []114 const spy = (r: { url(): string; postData(): string | null }) => {115 if (/\/api\/jmap\/[^/]+\/api/.test(r.url()) && (r.postData() ?? "").includes("Email/query") && (r.postData() ?? "").includes(alice())) legacyQueries.push(r.postData() as string)116 }117 page.on("request", spy)118 await page.keyboard.press("/")119 await expect(box(page)).toBeFocused()120 // tapé au clavier : l'opérateur terminé devient pastille dès l'espace, avant même de lancer121 await box(page).pressSequentially(`from:${alice()} `)122 await expect(chips(page)).toHaveCount(1)123 await expect(chips(page).first()).toContainText(`De : ${alice()}`)124 await box(page).pressSequentially("has:attachment")125 await page.keyboard.press("Enter")126 await expect(page).toHaveURL(/\/m\/\d+\/search\?q=/)127 await expect(chips(page)).toHaveCount(2)128 await expect(chips(page).nth(1)).toHaveText(/Avec pièce jointe/)129 await expect(row(page, new RegExp(s("Devis toiture")))).toBeVisible()130 await expect(options(page)).toHaveCount(1)131 await expect(count(page)).toHaveText("1 résultat")132 await expect(page.getByRole("heading", { level: 1, name: "Recherche" })).toBeVisible()133 // ---- toutes les boîtes : le résultat de l'autre boîte arrive, chaque ligne dit sa boîte134 await scope(page).getByRole("button", { name: "Toutes les boîtes" }).click()135 await expect(page).toHaveURL(/\/u\/search\?q=/)136 await expect(options(page)).toHaveCount(2)137 await expect(row(page, new RegExp(s("Devis fenêtres")))).toBeVisible()138 await expect(row(page, new RegExp(s("Devis fenêtres"))).locator(".addr-chip")).toHaveAttribute("data-address", P2)139 await expect(row(page, new RegExp(s("Devis toiture"))).locator(".addr-chip")).toHaveAttribute("data-address", P1)140 await expect(chips(page)).toHaveCount(2)141 await h().shot(page, "search-results-all")142 // ---- retour à la boîte courante143 await scope(page).getByRole("button", { name: /^Boîte / }).click()144 await expect(page).toHaveURL(/\/m\/\d+\/search\?q=/)145 await expect(options(page)).toHaveCount(1)146 // ---- retirer une pastille relance la recherche147 await page.getByRole("button", { name: "Retirer le filtre Avec pièce jointe" }).click()148 await expect(chips(page)).toHaveCount(1)149 await expect(options(page)).toHaveCount(2)150 await expect(row(page, new RegExp(s("Compte rendu")))).toBeVisible()151 // ---- libellé par son nom (avec espace : guillemets), favori, négation, OR152 await search(page, `label:"${labelName}"`)153 await expect(chips(page).first()).toHaveText(new RegExp(`Libellé : ${labelName}`))154 await expect(options(page)).toHaveCount(1)155 await expect(row(page, new RegExp(s("Facture hiver")))).toBeVisible()156 // la pastille de libellé des lignes vient du module des libellés (fournisseur inscrit), comme dans la liste du courrier157 await expect(row(page, new RegExp(s("Facture hiver"))).locator(".label-dot")).toHaveCount(1)158 await search(page, `est:suivi de:${alice()}`)159 await expect(chips(page).first()).toHaveText(/Favori/)160 await expect(options(page)).toHaveCount(1)161 await expect(row(page, new RegExp(s("Compte rendu")))).toBeVisible()162 await search(page, `from:${alice()} -has:attachment`)163 await expect(chips(page).nth(1)).toHaveText(/Sauf Avec pièce jointe/)164 await expect(options(page)).toHaveCount(1)165 await search(page, `from:${alice()} OR from:bob-${R()}`)166 await expect(chips(page)).toHaveCount(3)167 await expect(chips(page).nth(1)).toHaveText(/OU/)168 await expect(options(page)).toHaveCount(3)169 // ---- mots libres : ceux de la fin restent du texte modifiable dans le champ, le critère reste en pastille170 await search(page, `from:${alice()} toiture`)171 await expect(chips(page)).toHaveCount(1)172 await expect(box(page)).toHaveValue("toiture")173 await expect(options(page)).toHaveCount(1)174 await expect(row(page, new RegExp(s("Devis toiture")))).toBeVisible()175 await search(page, `from:${alice()} OR from:bob-${R()}`)176 // ---- le parcours des suites d'origine (desktop.spec « recherche plein texte et filtres ») tient toujours, tel quel177 await page.getByRole("button", { name: "Effacer la recherche" }).click()178 await expect(page.getByRole("heading", { level: 1, name: "Boîte de réception" })).toBeVisible()179 await page.keyboard.press("/")180 await expect(page.getByRole("searchbox")).toBeFocused()181 await page.getByRole("searchbox").fill(`toiture has:attachment from:${alice()}`)182 await page.keyboard.press("Enter")183 await expect(row(page, new RegExp(s("Devis toiture")))).toBeVisible()184 await expect(options(page)).toHaveCount(1)185 await expect(page.locator(".chip")).toHaveCount(2)186 await page.getByRole("searchbox").fill("motintrouvablezzqx")187 await page.keyboard.press("Enter")188 await expect(page.getByRole("heading", { name: "Aucun résultat" })).toBeVisible()189 await page.getByRole("button", { name: "Effacer la recherche" }).click()190 await expect(row(page, new RegExp(s("Compte rendu")))).toBeVisible()191 await expect(page).toHaveURL(/\/m\/\d+\/inbox$/)192 page.off("request", spy)193 expect(legacyQueries).toEqual([])194 expect(consoleClean(h().consoleErrors)).toEqual([])195 })196197 test("search : suggestions au clavier (opérateurs, libellés, contacts, récentes), retour arrière, Échap", async () => {198 const { page, P1 } = h()199 await home(page, P1)200 await box(page).click()201 const sug = suggestions(page)202 await expect(sug).toBeVisible()203 // champ vide : recherches récentes puis critères204 await expect(sug.getByRole("option").first()).toContainText("motintrouvablezzqx")205 await expect(sug.getByRole("option", { name: `from:${alice()} OR from:bob-${R()}` })).toBeVisible()206 await expect(sug.locator('[data-suggestion="k.from"]')).toContainText("De")207 await expect(box(page)).toHaveAttribute("aria-controls", await sug.getAttribute("id") as string)208 // début d'une clé : l'opérateur est proposé ; Entrée pose la clé, la valeur reste à taper209 await box(page).pressSequentially("lib")210 await expect(sug.getByRole("option").first()).toContainText("Libellé")211 await page.keyboard.press("ArrowDown")212 await expect(box(page)).toHaveAttribute("aria-activedescendant", /.+/)213 await page.keyboard.press("Enter")214 await expect(box(page)).toHaveValue("label:")215 await expect(sug.getByRole("option", { name: new RegExp(labelName) })).toBeVisible()216 // d'autres libellés peuvent exister (parcours complet) : quelques lettres ne laissent que le nôtre217 await box(page).pressSequentially(labelName.slice(0, 5))218 await expect(sug.getByRole("option").first()).toContainText(labelName)219 await page.keyboard.press("ArrowDown")220 await page.keyboard.press("Enter")221 await expect(chips(page)).toHaveCount(1)222 await expect(chips(page).first()).toHaveText(new RegExp(`Libellé : ${labelName}`))223 await expect(box(page)).toHaveValue("")224 await expect(page).not.toHaveURL(/search/) // choisir une suggestion ne lance rien225 // valeurs d'état et de dossier226 await box(page).pressSequentially("is:")227 await expect(sug.getByRole("option", { name: /Non lu/ })).toBeVisible()228 await box(page).fill("in:cor")229 await expect(sug.getByRole("option", { name: /Corbeille/ })).toBeVisible()230 // contacts (carnet du serveur)231 await box(page).fill("from:Alice")232 await expect(sug.getByRole("option", { name: /Alice Tremblay/ })).toBeVisible()233 // la liste ouverte, dans les trois thèmes (le changement de thème passe par la palette : la liste est rouverte à chaque fois)234 for (const [theme, label] of THEMES) {235 await h().setTheme(page, label, theme)236 await box(page).click()237 await expect(sug.getByRole("option", { name: /Alice Tremblay/ })).toBeVisible()238 await h().axe(page, `search-suggestions-${theme}`)239 if (theme !== "dark") await h().shot(page, `search-suggestions-${theme}`)240 }241 await h().setTheme(page, "Clair", "light")242 await box(page).click()243 await expect(sug).toBeVisible()244 // Échap ferme les suggestions sans quitter le champ ; retour arrière sur champ vide retire la dernière pastille245 await page.keyboard.press("Escape")246 await expect(sug).toHaveCount(0)247 await expect(box(page)).toBeFocused()248 await box(page).fill("")249 await page.keyboard.press("Backspace")250 await expect(chips(page)).toHaveCount(0)251 // une recherche récente se relance d'un geste252 await box(page).click()253 await suggestions(page).getByRole("option", { name: `from:${alice()} OR from:bob-${R()}` }).click()254 await expect(page).toHaveURL(/\/search\?q=/)255 await expect(options(page)).toHaveCount(3)256 })257258 test("search : erreurs d'analyse en direct, sans bloquer ni la frappe ni l'envoi", async () => {259 const { page, P1 } = h()260 await home(page, P1)261 await box(page).click()262 await box(page).pressSequentially(`before:notadate is:bogus from:${alice()}`)263 const errs = page.getByTestId("search-errors")264 await expect(errs).toContainText("« before:notadate » — date non reconnue")265 await expect(errs).toContainText("« is:bogus » — valeur inconnue")266 // les pastilles fautives sont marquées, la frappe continue267 await expect(page.locator(".nx-sb-chip.err")).toHaveCount(2)268 await box(page).pressSequentially(" has:attachment")269 await expect(box(page)).toHaveValue("has:attachment")270 await page.keyboard.press("Enter")271 // envoyée telle quelle : le serveur ignore les termes fautifs, le reste s'applique272 await expect(page).toHaveURL(/q=before%3Anotadate/)273 await expect(options(page)).toHaveCount(1)274 await expect(row(page, new RegExp(s("Devis toiture")))).toBeVisible()275 await expect(page.locator(".nx-sb-chip.err")).toHaveCount(2)276 await expect(errs).toContainText("« is:bogus »")277 // libellé inconnu : signalé par la recherche elle-même278 await search(page, "label:introuvablezz")279 await expect(page.getByTestId("search-errors")).toContainText("aucun libellé ne porte ce nom")280 await expect(page.getByRole("heading", { name: "Aucun résultat" })).toBeVisible()281 await expect(page.getByRole("button", { name: "Rechercher partout" })).toBeVisible()282 })283284 test("search : pages à curseur (deuxième page au défilement, aucun doublon), regroupement par fil", async () => {285 const { page } = h()286 await page.getByRole("button", { name: "Effacer la recherche" }).click()287 await h().palette(page, ">rechercher partout", "Rechercher partout")288 await expect(page).toHaveURL(/\/u\/search/)289 await expect(page.getByRole("heading", { name: "Recherche", level: 2 })).toBeVisible()290 await expect(box(page)).toBeFocused()291 const pages: string[] = []292 page.on("request", (r) => {293 if (r.url().includes("/api/next/search?")) pages.push(new URL(r.url()).searchParams.get("cursor") ?? "")294 })295 await box(page).fill(`from:${lot()}`)296 await page.keyboard.press("Enter")297 await expect(count(page)).toHaveText("50 résultats et plus")298 // défilement jusqu'au bout : la deuxième page arrive, chaque rang n'a qu'un message et chaque message qu'un rang299 const seen = new Map<number, string>()300 for (let guard = 0; guard < 80; guard++) {301 for (const o of await options(page).evaluateAll((els) => els.map((e) => [Number(e.getAttribute("aria-posinset")), e.getAttribute("data-id") ?? ""] as [number, string]))) {302 if (seen.has(o[0])) expect(seen.get(o[0])).toBe(o[1])303 seen.set(o[0], o[1])304 }305 const done = await page.locator(".mlist").evaluate((el) => {306 const end = el.scrollTop + el.clientHeight >= el.scrollHeight - 2307 el.scrollTop += Math.floor(el.clientHeight * 0.8)308 return end309 })310 if (done && seen.size >= 72) break311 await page.waitForTimeout(120)312 }313 await expect(count(page)).toHaveText("72 résultats")314 expect(seen.size).toBe(72)315 expect(new Set(seen.values()).size).toBe(72)316 expect(pages.filter((c) => c).length).toBeGreaterThanOrEqual(1)317 // ---- curseur refusé par le serveur (400 invalid_cursor) : la recherche repart du début, sans erreur à l'écran318 await search(page, `from:${lot()} in:inbox`)319 await expect(count(page)).toHaveText("50 résultats et plus")320 let refusedOnce = false321 await page.route("**/api/next/search?*", async (route) => {322 if (!refusedOnce && new URL(route.request().url()).searchParams.has("cursor")) {323 refusedOnce = true324 return route.fulfill({ status: 400, json: { error: "invalid_cursor", message: "cursor does not match this query" } })325 }326 return route.continue()327 })328 const restarted = page.waitForRequest((r) => r.url().includes("/api/next/search?") && refusedOnce && !new URL(r.url()).searchParams.has("cursor"))329 await page.locator(".mlist").evaluate((el) => (el.scrollTop = el.scrollHeight))330 await restarted331 await expect(count(page)).toHaveText("50 résultats et plus")332 await expect(page.locator("#list-pane [role=alert], #list-pane .list-banner")).toHaveCount(0)333 await page.unroute("**/api/next/search?*")334 await page.locator(".mlist").evaluate((el) => (el.scrollTop = el.scrollHeight))335 await expect(count(page)).toHaveText("72 résultats")336 // ---- regroupement par fil : une ligne par conversation, ou une par message337 await search(page, `from:dana-${R()}`)338 const toggle = page.getByRole("button", { name: "Regrouper par conversation" })339 await expect(toggle).toHaveAttribute("aria-pressed", "true")340 await expect(options(page)).toHaveCount(1)341 const req = page.waitForRequest((r) => r.url().includes("/api/next/search?") && !new URL(r.url()).searchParams.has("threads"))342 await toggle.click()343 expect(new URL((await req).url()).searchParams.get("tz")).toBe("America/Toronto")344 await expect(toggle).toHaveAttribute("aria-pressed", "false")345 await expect(options(page)).toHaveCount(2)346 await toggle.click()347 await expect(options(page)).toHaveCount(1)348 })349350 test("search : ouvrir un résultat dans le lecteur, revenir sans perdre les résultats (une boîte et toutes)", async () => {351 const { page, P1, P2 } = h()352 await search(page, `from:${alice()} has:attachment`)353 await expect(options(page)).toHaveCount(2)354 // ---- toutes les boîtes : le fil s'ouvre dans sa boîte, la liste reste355 await row(page, new RegExp(s("Devis fenêtres"))).click()356 await expect(page).toHaveURL(new RegExp(`/u/search/t/${await mbIndex(page, P2)}/[^?]+\\?q=`))357 await expect(page.locator(".reader-subject")).toHaveText(new RegExp(s("Devis fenêtres")))358 await expect(page.locator("#main")).toContainText("plan-fenetres.txt")359 await expect(options(page)).toHaveCount(2)360 await expect(row(page, new RegExp(s("Devis fenêtres")))).toHaveClass(/open/)361 // au clavier : ligne suivante dans le lecteur, puis retour362 await list(page).focus()363 await page.keyboard.press("k")364 await expect(page.locator(".reader-subject")).toHaveText(new RegExp(s("Devis toiture")))365 await expect(page).toHaveURL(new RegExp(`/u/search/t/${await mbIndex(page, P1)}/`))366 await page.keyboard.press("u")367 await expect(page).toHaveURL(/\/u\/search\?q=/)368 await expect(page.locator(".reader-subject")).toHaveCount(0)369 await expect(options(page)).toHaveCount(2)370 await expect(chips(page)).toHaveCount(2)371 // ---- bouton « précédent » du navigateur : pareil372 await row(page, new RegExp(s("Devis toiture"))).click()373 await expect(page.locator(".reader-subject")).toHaveText(new RegExp(s("Devis toiture")))374 await page.goBack()375 await expect(page).toHaveURL(/\/u\/search\?q=/)376 await expect(options(page)).toHaveCount(2)377 // ---- une seule boîte378 await scope(page).getByRole("button", { name: /^Boîte / }).click()379 await expect(options(page)).toHaveCount(1)380 await options(page).first().click()381 await expect(page).toHaveURL(/\/m\/\d+\/search\/t\/[^?]+\?q=/)382 await expect(page.locator(".reader-subject")).toBeVisible()383 await page.keyboard.press("Escape")384 await expect(page).toHaveURL(/\/m\/\d+\/search\?q=/)385 await expect(options(page)).toHaveCount(1)386 })387388 test("search : sélection et actions groupées sur des résultats de deux boîtes (lu, favori, archive, corbeille, annulation)", async () => {389 const { page, P1, P2 } = h()390 await h().palette(page, ">rechercher partout", "Rechercher partout")391 await search(page, `from:${lot()}`)392 await expect(count(page)).toHaveText("50 résultats et plus")393 // les deux premières lignes viennent de deux boîtes différentes394 const boxesOf = async (n: number) => options(page).evaluateAll((els, n) => els.slice(0, n).map((e) => e.querySelector(".addr-chip")?.getAttribute("data-address")), n)395 expect(new Set(await boxesOf(2))).toEqual(new Set([P1, P2]))396 const firstIds = await options(page).evaluateAll((els) => els.slice(0, 4).map((e) => e.getAttribute("data-id") as string))397 const rowById = (id: string) => page.locator(`[role="option"][data-id="${id}"]`)398 await rowById(firstIds[0]).click({ modifiers: ["ControlOrMeta"] })399 await rowById(firstIds[1]).click({ modifiers: ["ControlOrMeta"] })400 const bar = page.getByRole("toolbar", { name: "Actions sur la liste" })401 await expect(bar).toContainText("2 sélectionnées")402 await expect(rowById(firstIds[0])).toHaveClass(/unread/)403 await bar.getByRole("button", { name: "Marquer comme lu" }).click()404 await expect(rowById(firstIds[0])).not.toHaveClass(/unread/)405 await expect(rowById(firstIds[1])).not.toHaveClass(/unread/)406 await bar.getByRole("button", { name: "Ajouter aux favoris" }).click()407 await expect(rowById(firstIds[0]).locator(".mrow-star.on")).toHaveCount(1)408 await expect(rowById(firstIds[1]).locator(".mrow-star.on")).toHaveCount(1)409 // le serveur de courrier a bien reçu l'état, dans chaque boîte410 const kw = async (key: string) => {411 const [mb, id] = key.split(":")412 const address = (await h().mailboxId(page, P1)) === mb ? P1 : P2413 const e = (await h().jmap(page, address, [["Email/get", { ids: [id], properties: ["keywords", "mailboxIds"] }, "g"]]))[0][1].list[0]414 const roles = (await h().jmap(page, address, [["Mailbox/get", { properties: ["role"] }, "m"]]))[0][1].list as { id: string; role: string | null }[]415 return { keywords: Object.keys(e.keywords), roles: Object.keys(e.mailboxIds).map((f) => roles.find((r) => r.id === f)?.role) }416 }417 await expect.poll(async () => (await kw(firstIds[0])).keywords).toEqual(expect.arrayContaining(["$flagged", "$seen"]))418 await expect.poll(async () => (await kw(firstIds[1])).keywords).toEqual(expect.arrayContaining(["$flagged", "$seen"]))419 // ---- archive : annoncée, annulable ; le message reste un résultat, rangé ailleurs420 await bar.getByRole("button", { name: "Archiver" }).click()421 await expect(toastText(page, "2 conversations archivées")).toBeVisible()422 await expect(rowById(firstIds[0]).locator(".nx-sr-folder")).toHaveText("Archives")423 await expect.poll(async () => (await kw(firstIds[0])).roles).toEqual(["archive"])424 await expect.poll(async () => (await kw(firstIds[1])).roles).toEqual(["archive"])425 // ---- corbeille : les lignes quittent les résultats ; « Annuler » les ramène426 await rowById(firstIds[2]).click({ modifiers: ["ControlOrMeta"] })427 await rowById(firstIds[3]).click({ modifiers: ["ControlOrMeta"] })428 await bar.getByRole("button", { name: "Supprimer" }).click()429 const trashed = toastText(page, "2 conversations placées dans la corbeille")430 await expect(trashed).toBeVisible()431 await expect(rowById(firstIds[2])).toHaveCount(0)432 await expect(rowById(firstIds[3])).toHaveCount(0)433 await expect.poll(async () => (await kw(firstIds[2])).roles).toEqual(["trash"])434 await expect.poll(async () => (await kw(firstIds[3])).roles).toEqual(["trash"])435 await trashed.getByRole("button", { name: "Annuler" }).click()436 await expect(toastText(page, "Action annulée")).toBeVisible()437 await expect(rowById(firstIds[2])).toHaveCount(1)438 await expect(rowById(firstIds[3])).toHaveCount(1)439 await expect.poll(async () => (await kw(firstIds[2])).roles).toEqual(["inbox"])440 // au clavier : x coche la ligne sous le curseur, Échap vide la sélection441 await list(page).focus()442 await page.keyboard.press("j")443 await page.keyboard.press("x")444 await expect(bar).toContainText("1 sélectionnée")445 await page.keyboard.press("Escape")446 await expect(bar).not.toContainText("sélectionnée")447 })448449 test("search : enregistrer la recherche → dossier intelligent (survit au rechargement), renommer, modifier, épingler, supprimer", async () => {450 const { page } = h()451 await search(page, `from:${alice()} has:attachment`)452 await expect(options(page)).toHaveCount(2)453 const name = `Devis Alice ${R()}`454 await page.getByRole("button", { name: "Enregistrer la recherche" }).click()455 const dlg = page.getByRole("dialog", { name: "Enregistrer la recherche" })456 await expect(dlg.getByLabel("Requête")).toHaveValue(`from:${alice()} has:attachment`)457 await expect(dlg.getByLabel("Portée de la recherche")).toHaveValue("all")458 await expect(dlg.getByRole("button", { name: "Enregistrer" })).toBeDisabled()459 await dlg.getByLabel("Nom").fill(name)460 await h().axe(page, "search-save-dialog")461 await h().shot(page, "search-save-dialog-light")462 await dlg.getByRole("button", { name: "Enregistrer" }).click()463 await expect(dlg).toHaveCount(0)464 await expect(toastText(page, `Recherche « ${name} » enregistrée`)).toBeVisible()465 const link = () => smart(page).getByRole("link", { name, exact: true })466 await expect(link()).toBeVisible()467 await expect(link()).toHaveAttribute("aria-current", "page")468 // une deuxième, limitée à une boîte, créée de toutes pièces par le « + » de la section469 const other = `Lot P1 ${R()}`470 await page.locator("#sidebar").getByRole("button", { name: "Créer un dossier intelligent" }).click()471 const dlg2 = page.getByRole("dialog", { name: "Enregistrer la recherche" })472 await dlg2.getByLabel("Nom").fill(other)473 await dlg2.getByLabel("Requête").fill(`from:${lot()} is:unread`)474 await dlg2.getByLabel("Portée de la recherche").selectOption({ label: h().P1 })475 await dlg2.getByRole("button", { name: "Enregistrer" }).click()476 await expect(dlg2).toHaveCount(0)477 await expect(smart(page).getByRole("link", { name: other, exact: true })).toBeVisible()478 const api = async () => (await h().api<{ data: { name: string; query: string; mailbox_ids: string[] | null; pinned: boolean }[] }>(page, "GET", "/api/next/searches")).data479 expect((await api()).map((x) => [x.name, x.query, x.mailbox_ids?.length ?? null, x.pinned])).toEqual([[name, `from:${alice()} has:attachment`, null, false], [other, `from:${lot()} is:unread`, 1, false]])480 // ---- rechargement : les entrées sont là (copie locale puis serveur) et lancent leur recherche dans leur portée481 await page.goto("/")482 await expect(link()).toBeVisible()483 await link().click()484 await expect(page).toHaveURL(/\/u\/search\?q=/)485 await expect(options(page)).toHaveCount(2)486 await expect(chips(page)).toHaveCount(2)487 await smart(page).getByRole("link", { name: other, exact: true }).click()488 await expect(page).toHaveURL(/\/m\/\d+\/search\?q=/)489 await expect(row(page, /Lot pagination/).first()).toBeVisible()490 await expect(options(page).first().locator(".addr-chip")).toHaveCount(0)491 // ---- menu : épingler (passe en tête, icône d'épingle), renommer492 const menu = async (n: string, item: string) => {493 await smart(page).getByRole("link", { name: n, exact: true }).hover()494 await smart(page).getByRole("button", { name: `Actions pour le dossier ${n}` }).click()495 await page.getByRole("menuitem", { name: item, exact: true }).click()496 }497 // la section porte aussi les entrées d'autres modules (veille, suivis) : seules les recherches comptent ici498 const names = () => smart(page).locator('a[href*="/search"] .nav-label').allTextContents()499 expect(await names()).toEqual([name, other])500 await menu(other, "Épingler")501 await expect.poll(names).toEqual([other, name])502 expect((await api()).find((x) => x.name === other)?.pinned).toBe(true)503 await menu(other, "Renommer")504 const edit = page.getByRole("dialog", { name: "Modifier la recherche enregistrée" })505 await expect(edit.getByLabel("Nom")).toBeFocused()506 const renamed = `Lot non lu ${R()}`507 await edit.getByLabel("Nom").fill(renamed)508 await edit.getByRole("button", { name: "Enregistrer" }).click()509 await expect(edit).toHaveCount(0)510 await expect(smart(page).getByRole("link", { name: renamed, exact: true })).toBeVisible()511 // ---- modifier la requête : erreurs en direct sous le champ, refus du serveur (400 invalid_query) affiché sur place512 await menu(renamed, "Modifier la requête")513 await expect(edit.getByLabel("Requête")).toBeFocused()514 await edit.getByLabel("Requête").fill("before:notadate")515 await expect(edit.getByTestId("saved-query-errors")).toContainText("« before:notadate » — date non reconnue")516 const refused = page.waitForResponse((r) => r.url().includes("/api/next/searches/") && r.request().method() === "PATCH")517 await edit.getByRole("button", { name: "Enregistrer" }).click()518 expect((await refused).status()).toBe(400)519 await expect(edit.getByTestId("saved-query-errors")).toContainText("Le serveur refuse cette requête")520 await expect(edit).toBeVisible()521 await edit.getByLabel("Requête").fill(`from:${lot()} is:starred`)522 await expect(edit.getByTestId("saved-query-errors")).toHaveCount(0)523 await edit.getByRole("button", { name: "Enregistrer" }).click()524 await expect(edit).toHaveCount(0)525 expect((await api()).find((x) => x.name === renamed)?.query).toBe(`from:${lot()} is:starred`)526 await menu(renamed, "Désépingler")527 await expect.poll(names).toEqual([name, renamed])528 // ---- supprimer (confirmation)529 await menu(renamed, "Supprimer")530 await page.getByRole("alertdialog").getByRole("button", { name: "Supprimer" }).click()531 await expect(smart(page).getByRole("link", { name: renamed, exact: true })).toHaveCount(0)532 await expect.poll(async () => (await api()).map((x) => x.name)).toEqual([name])533 // ---- palette : « Enregistrer la recherche » sur une recherche en cours534 await link().click()535 await expect(options(page)).toHaveCount(2)536 await h().palette(page, ">enregistrer la rech", "Enregistrer la recherche")537 await expect(page.getByRole("dialog", { name: "Enregistrer la recherche" })).toBeVisible()538 await page.keyboard.press("Escape")539 })540541 test("search : depuis « Toutes les boîtes », panneau de filtres qui édite les pastilles", async () => {542 const { page, P1, P2 } = h()543 await page.locator("#sidebar .nav-unified a").first().click()544 await expect(page).toHaveURL(/\/u\/inbox/)545 // le champ est dans l'en-tête de la vue unifiée ; « / » y mène sans quitter la vue546 await expect(box(page)).toBeVisible()547 await page.keyboard.press("/")548 await expect(box(page)).toBeFocused()549 await expect(page).toHaveURL(/\/u\/inbox/)550 await h().shot(page, "search-unified-header")551 await box(page).fill(`from:carl-${R()}`)552 await page.keyboard.press("Enter")553 await expect(page).toHaveURL(/\/u\/search\?q=/)554 await expect(options(page)).toHaveCount(1)555 await expect(row(page, new RegExp(s("Relance"))).locator(".addr-chip")).toHaveAttribute("data-address", P2)556 await expect(scope(page).getByRole("button", { name: "Toutes les boîtes" })).toHaveAttribute("aria-pressed", "true")557 // ---- panneau de filtres dans une boîte : chaque champ modifie les pastilles, sur-le-champ558 await page.getByRole("button", { name: "Effacer la recherche" }).click()559 await home(page, P1)560 await page.getByRole("button", { name: "Filtres de recherche" }).click()561 const panel = page.getByRole("form", { name: "Filtres de recherche" })562 await expect(panel.getByLabel("De", { exact: true })).toBeFocused()563 await panel.getByLabel("De", { exact: true }).fill(alice())564 await expect(chips(page)).toHaveCount(1)565 await expect(chips(page).first()).toHaveText(new RegExp(`De : ${alice()}`))566 await panel.getByLabel("Avec pièce jointe").check()567 await panel.getByLabel("Taille maximale (Mo)").fill("5")568 await panel.getByLabel("Dossier").selectOption({ label: "Boîte de réception" })569 await expect(chips(page)).toHaveCount(4)570 await expect(chips(page).allTextContents()).resolves.toEqual(expect.arrayContaining([expect.stringContaining("Avec pièce jointe"), expect.stringContaining("Moins de : 5m"), expect.stringContaining("Dossier : Boîte de réception")]))571 await expect(panel.getByLabel("Libellé")).toBeVisible()572 await h().axeThemes(page, "search-filter-panel")573 await h().shotThemes(page, "search-filter-panel")574 await expect(panel).toBeVisible()575 await page.getByRole("form", { name: "Filtres de recherche" }).getByRole("button", { name: "Rechercher" }).click()576 await expect(page.getByRole("form", { name: "Filtres de recherche" })).toHaveCount(0)577 await expect(page).toHaveURL(/q=from%3Aalice-.*has%3Aattachment.*smaller%3A5m.*in%3Ainbox/)578 await expect(options(page)).toHaveCount(1)579 await expect(row(page, new RegExp(s("Devis toiture")))).toBeVisible()580 // rouvert : le panneau relit les pastilles ; décocher retire la pastille ; une pastille écrite à la main y apparaît581 await page.getByRole("button", { name: "Filtres de recherche" }).click()582 await expect(panel.getByLabel("De", { exact: true })).toHaveValue(alice())583 await expect(panel.getByLabel("Avec pièce jointe")).toBeChecked()584 await expect(panel.getByLabel("Dossier")).toHaveValue("inbox")585 await panel.getByLabel("Avec pièce jointe").uncheck()586 await panel.getByLabel("Taille maximale (Mo)").fill("")587 await expect(chips(page)).toHaveCount(2)588 await panel.getByRole("button", { name: "Réinitialiser" }).click()589 await expect(chips(page)).toHaveCount(0)590 await page.keyboard.press("Escape")591 await expect(panel).toHaveCount(0)592 void P2593 })594595 test("search : résultats avec pastilles — axe dans les trois thèmes, captures", async () => {596 const { page } = h()597 await h().palette(page, ">rechercher partout", "Rechercher partout")598 await search(page, `from:${alice()} OR from:${lot()} -is:starred before:notadate`)599 await expect(count(page)).toHaveText("50 résultats et plus")600 await expect(page.locator(".nx-sb-chip.err")).toHaveCount(1)601 await box(page).blur()602 await h().axeThemes(page, "search-results")603 await h().shotThemes(page, "search-results")604 // dialogue d'enregistrement en minuit605 await h().setTheme(page, "Minuit", "midnight")606 await page.getByRole("button", { name: "Enregistrer la recherche" }).click()607 await expect(page.getByRole("dialog", { name: "Enregistrer la recherche" })).toBeVisible()608 await h().axe(page, "search-save-dialog-midnight")609 await h().shot(page, "search-save-dialog-midnight")610 await page.keyboard.press("Escape")611 await h().setTheme(page, "Sombre", "dark")612 await page.getByRole("button", { name: "Enregistrer la recherche" }).click()613 await h().axe(page, "search-save-dialog-dark")614 await page.keyboard.press("Escape")615 await h().setTheme(page, "Clair", "light")616 })617618 test("search : hors ligne — la boîte courante garde la recherche d'origine (copie locale), toutes les boîtes demandent le réseau", async () => {619 const { page, context, P1 } = h()620 await home(page, P1)621 await search(page, `from:${alice()}`)622 await expect(options(page)).toHaveCount(2)623 await expect(page.getByTestId("search-fallback")).toHaveCount(0)624 await context.setOffline(true)625 try {626 // la liste d'origine reprend la vue, avec la copie locale de la première page ; le champ dit pourquoi, discrètement627 await expect(page.getByTestId("search-fallback")).toContainText("Hors ligne : recherche simplifiée")628 await expect(page.locator("#list-pane")).not.toHaveAttribute("data-search", /.*/)629 await expect(options(page)).toHaveCount(2)630 await expect(row(page, new RegExp(s("Devis toiture")))).toBeVisible()631 await expect(page.getByRole("toolbar", { name: "Actions sur la liste" })).toContainText("copie locale")632 // le champ reste utilisable : frappe, pastilles, envoi (la liste d'origine répond ce qu'elle peut sans réseau)633 await box(page).click()634 await box(page).pressSequentially("has:attachment ")635 await expect(chips(page)).toHaveCount(2)636 await page.keyboard.press("Enter")637 await expect(page).toHaveURL(/has%3Aattachment/)638 await expect(page.getByTestId("search-fallback")).toBeVisible()639 await expect(page.locator("#list-pane")).toBeVisible()640 // toutes les boîtes : explication, et un chemin vers la boîte courante641 await h().palette(page, ">rechercher partout", "Rechercher partout")642 await expect(page).toHaveURL(/\/u\/search\?q=/)643 await expect(page.getByTestId("search-needs-network")).toContainText("La recherche dans toutes les boîtes demande le réseau")644 await page.getByTestId("search-needs-network").getByRole("button", { name: "Chercher dans cette boîte" }).click()645 await expect(page).toHaveURL(/\/m\/\d+\/search\?q=/)646 } finally {647 await context.setOffline(false)648 }649 // retour du réseau : la recherche du serveur reprend la vue650 await expect(page.getByTestId("search-fallback")).toHaveCount(0)651 await expect(page.locator("#list-pane")).toHaveAttribute("data-search", "mailbox")652 await expect(options(page)).toHaveCount(1)653 })654655 test("search : « par le sens » — absent sans fournisseur ; avec lui, résultats étiquetés et repli discret en cas d'échec", async () => {656 const { page } = h()657 // l'intelligence est coupée par défaut : aucun bouton dans le DOM658 await expect(page.getByTestId("semantic-toggle")).toHaveCount(0)659 const { ctx, p } = await h().fromStorage({ width: 1440, height: 900 })660 try {661 let fail = false662 const semanticSeen: unknown[] = []663 // seuls les réglages d'IA et la route sémantique sont simulés (le module d'IA inscrit alors son fournisseur)664 await p.route("**/api/next/ai/settings", async (route) => {665 if (route.request().method() !== "GET") return route.abort()666 const r = await route.fetch()667 const j = await r.json()668 return route.fulfill({ response: r, json: { ...j, provider: "local", features: { ...j.features, semantic: true }, available: { ...j.available, local: true, semantic: true } } })669 })670 const normal = await h().api<{ data: Record<string, unknown>[] }>(page, "GET", `/api/next/search?q=${encodeURIComponent(`from:${alice()}`)}`)671 await p.route("**/api/next/ai/search", async (route) => {672 semanticSeen.push(route.request().postDataJSON())673 if (fail) return route.fulfill({ status: 503, json: { error: "provider_unavailable", message: "embedding backend down" } })674 return route.fulfill({ json: { data: normal.data.slice(0, 2).map((m, i) => ({ ...m, score: 0.9 - i / 10, match: "semantic" })), semantic: { backend: "stub", model: "e5-essai", indexed: 10 } } })675 })676 await p.goto(`/u/search?q=${encodeURIComponent("devis de toiture")}`)677 const toggle = p.getByTestId("semantic-toggle")678 await expect(toggle).toBeVisible()679 await expect(toggle).toHaveAttribute("aria-pressed", "false")680 await toggle.click()681 await expect(toggle).toHaveAttribute("aria-pressed", "true")682 await expect(p.getByTestId("semantic-by")).toContainText("e5-essai")683 await expect(options(p)).toHaveCount(2)684 expect(semanticSeen[0]).toEqual({ q: "devis de toiture" })685 await h().axe(p, "search-semantic")686 await h().shot(p, "search-semantic-light")687 // échec classé du fournisseur : résultats de la recherche habituelle, une ligne d'explication688 fail = true689 await search(p, `from:${alice()}`)690 await expect(p.getByTestId("semantic-note")).toContainText("Recherche par le sens indisponible")691 await expect(p.getByTestId("semantic-by")).toHaveCount(0)692 await expect(options(p)).toHaveCount(3)693 await toggle.click()694 await expect(p.getByTestId("semantic-note")).toHaveCount(0)695 } finally {696 await ctx.close()697 }698 })699700 test("search : téléphone — champ, pastilles, résultats, filtres en dialogue, lecteur et retour", async () => {701 const { P1 } = h()702 const { ctx, p } = await h().fromStorage({ width: 390, height: 844 }, true)703 try {704 await p.goto(`/m/${await mbIndex(h().page, P1)}/inbox`)705 await expect(p.locator(".nx-sb")).toBeVisible()706 await p.locator(".bottom-nav").getByRole("button", { name: "Rechercher" }).tap()707 await expect(box(p)).toBeFocused()708 await expect(suggestions(p)).toBeVisible()709 await h().shot(p, "search-suggestions-phone")710 await box(p).fill(`from:${alice()} OR from:${lot()} -is:starred`)711 await p.keyboard.press("Enter")712 await expect(count(p)).toHaveText(/résultats/)713 await expect(chips(p)).toHaveCount(4)714 expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)715 await h().shot(p, "search-results-phone")716 await h().axe(p, "search-results-phone")717 // cibles tactiles : retrait de pastille et options ≥ 28 px dans un cadre de 44 px, portée ≥ 36 px718 expect((await scope(p).getByRole("button").first().boundingBox())!.height).toBeGreaterThanOrEqual(36)719 // filtres : dialogue pleine largeur720 await p.getByRole("button", { name: "Filtres de recherche" }).tap()721 const dlg = p.getByRole("dialog", { name: "Filtres de recherche" })722 await expect(dlg).toBeVisible()723 await dlg.getByLabel("Avec pièce jointe").check()724 await expect(chips(p)).toHaveCount(5)725 await h().shot(p, "search-filter-panel-phone")726 await h().axe(p, "search-filter-panel-phone")727 await dlg.getByRole("button", { name: "Rechercher" }).tap()728 await expect(dlg).toHaveCount(0)729 await expect(options(p)).toHaveCount(1)730 // lecteur puis retour : les résultats sont toujours là731 await options(p).first().tap()732 await expect(p.locator(".reader-subject")).toHaveText(new RegExp(s("Devis toiture")))733 await p.getByRole("button", { name: "Retour à la liste" }).tap()734 await expect(options(p)).toHaveCount(1)735 await expect(chips(p)).toHaveCount(5)736 // enregistrement : dialogue737 await p.getByRole("button", { name: "Enregistrer la recherche" }).tap()738 await expect(p.getByRole("dialog", { name: "Enregistrer la recherche" })).toBeVisible()739 await h().shot(p, "search-save-dialog-phone")740 await p.keyboard.press("Escape")741 } finally {742 await ctx.close()743 }744 })745746 test("search : ménage (recherches enregistrées, libellé, contact) et console propre", async () => {747 const { page } = h()748 for (const x of (await h().api<{ data: { id: string }[] }>(page, "GET", "/api/next/searches")).data) await h().api(page, "DELETE", `/api/next/searches/${x.id}`)749 for (const l of (await h().api<{ data: { id: string; name: string }[] }>(page, "GET", "/api/next/labels")).data) if (l.name === labelName) await h().api(page, "DELETE", `/api/next/labels/${l.id}`)750 expect(consoleClean(h().consoleErrors)).toEqual([])751 })752}753754/** Erreurs de console qui ne viennent pas de la recherche : requêtes coupées par l'essai hors ligne, refus simulés. */755function consoleClean(errors: string[]): string[] {756 return errors.filter((e) => !/ERR_INTERNET_DISCONNECTED|Failed to load resource|net::ERR_|status of 400|status of 503|EventSource/.test(e))757}758