SPB Git

Repository Public

offline.spec.ts 29.0 KB 456 lines typescript

1// Hors ligne et installabilité, de bout en bout : la coque se charge réseau coupé après une première visite ; aucune réponse de2// /api n'entre jamais dans Cache Storage ; les actions prises hors ligne (lu, favori, épinglage = mot-clé, archive) survivent à3// un rechargement hors ligne et atteignent le serveur exactement une fois à la reconnexion ; un changement fait entre-temps sur4// le serveur gagne ; une action refusée est signalée ; la déconnexion et la perte de session vident caches et file et5// désenregistrent le worker ; la mise à jour d'un build au suivant passe par « Une mise à jour est prête » sans mêler les versions.6import { expect, test, type Page } from "@playwright/test"7import crypto from "node:crypto"8import fs from "node:fs"9import path from "node:path"10import { OUT } from "../admin/env"11import { api, createMailbox, st } from "../admin/fixtures"12import { startBackend } from "../admin/global-setup"13import { secondSession, sql } from "../admin/ops-helpers"14import { list, row, toastText } from "../helpers"1516const MAIL = "urn:ietf:params:jmap:mail"17const tag = crypto.randomBytes(2).toString("hex")1819interface Box {20  id: string21  address: string22  acct: string23  folders: Record<string, string>24}25/** JMAP direct (session du lanceur, hors du navigateur) : sert à semer les messages et à lire l'état du serveur. */26async function jmap(box: Pick<Box, "id">, calls: unknown[]): Promise<any[]> {27  const r = await api("POST", `/api/jmap/${box.id}/api`, { using: ["urn:ietf:params:jmap:core", MAIL], methodCalls: calls })28  if (!r.ok) throw new Error(`jmap ${r.status} ${JSON.stringify(r.body)}`)29  return r.body.methodResponses30}31async function prepareBox(): Promise<Box> {32  const mb = await createMailbox("off", "Hors ligne")33  const acct = (await api("GET", `/api/jmap/${mb.id}/session`)).body.primaryAccounts[MAIL]34  const box: Box = { ...mb, acct, folders: {} }35  const read = async () => {36    const [[, r]] = await jmap(box, [["Mailbox/get", { accountId: acct, ids: null }, "m"]])37    for (const f of r.list as { id: string; role: string | null }[]) if (f.role) box.folders[f.role] = f.id38  }39  await read()40  // l'archivage hors ligne exige que le dossier existe déjà (une création de dossier ne se met pas en file)41  for (const [role, name] of [["archive", "Archive"], ["trash", "Deleted Items"]] as const) {42    if (box.folders[role]) continue43    await jmap(box, [["Mailbox/set", { accountId: acct, create: { n: { name, role, parentId: null, isSubscribed: true } } }, "c"]])44  }45  await read()46  expect(box.folders.inbox && box.folders.archive && box.folders.trash, JSON.stringify(box.folders)).toBeTruthy()47  return box48}49/** Sème des messages non lus dans la boîte de réception (Email/set : aucun envoi SMTP). Rend sujet → identifiant. */50async function seed(box: Box, names: string[]): Promise<Record<string, string>> {51  const create: Record<string, unknown> = {}52  names.forEach((n, i) => {53    create[`m${i}`] = {54      mailboxIds: { [box.folders.inbox]: true }, keywords: {}, from: [{ name: "Essai", email: st.addrB }], to: [{ email: box.address }], subject: `${n} ${tag}`,55      receivedAt: new Date(Date.now() - i * 60_000).toISOString().replace(/\.\d{3}Z$/, "Z"), textBody: [{ partId: "t", type: "text/plain" }], bodyValues: { t: { value: `Corps de ${n}.` } },56    }57  })58  const [[, r]] = await jmap(box, [["Email/set", { accountId: box.acct, create }, "s"]])59  expect(Object.keys(r.created ?? {}).length, JSON.stringify(r.notCreated)).toBe(names.length)60  return Object.fromEntries(names.map((n, i) => [n, r.created[`m${i}`].id as string]))61}62async function serverState(box: Box, ids: string[]): Promise<Record<string, { keywords: Record<string, boolean>; mailboxIds: Record<string, boolean> } | null>> {63  const [[, r]] = await jmap(box, [["Email/get", { accountId: box.acct, ids, properties: ["keywords", "mailboxIds"] }, "g"]])64  return Object.fromEntries(ids.map((id) => [id, (r.list as any[]).find((e) => e.id === id) ?? null]))65}6667// ---------------------------------------------------------------- lecture de l'état du navigateur68const shell = (page: Page) =>69  page.evaluate(async () => {70    const regs = await navigator.serviceWorker.getRegistrations()71    const keys = await caches.keys()72    const urls: string[] = []73    for (const k of keys) for (const req of await (await caches.open(k)).keys()) urls.push(new URL(req.url).pathname)74    return { registrations: regs.length, controlled: !!navigator.serviceWorker.controller, caches: keys, urls, build: document.documentElement.dataset.build ?? "" }75  })76const waitForShell = async (page: Page) => {77  await page.evaluate(() => navigator.serviceWorker.ready.then(() => true))78  await expect.poll(async () => (await shell(page)).controlled, { timeout: 30_000 }).toBe(true)79  await expect.poll(async () => (await shell(page)).caches.length).toBe(1)80}81/** File durable telle qu'elle est écrite dans IndexedDB (null : base ou clé absente). */82const storedQueue = (page: Page) =>83  page.evaluate(84    () =>85      new Promise<{ user: string; ops: { id: string; patch: Record<string, unknown> }[] } | null>((resolve) => {86        const open = indexedDB.open("spmail-cache")87        open.onerror = () => resolve(null)88        open.onupgradeneeded = () => open.transaction?.abort()89        open.onsuccess = () => {90          const db = open.result91          if (!db.objectStoreNames.contains("kv")) {92            db.close()93            return resolve(null)94          }95          const get = db.transaction("kv").objectStore("kv").get("offline-queue")96          get.onsuccess = () => {97            db.close()98            resolve((get.result as never) ?? null)99          }100          get.onerror = () => resolve(null)101        }102      }),103  )104const loadedAssets = (page: Page) => page.evaluate(() => [...new Set([...document.querySelectorAll<HTMLScriptElement>("script[src]")].map((s) => new URL(s.src).pathname).concat(performance.getEntriesByType("resource").map((e) => new URL(e.name).pathname)).filter((p) => p.startsWith("/assets/")))])105const sync = (page: Page) => page.locator("#sidebar .sync-indicator")106/**107 * Réseau coupé : « Hors ligne » tant que le navigateur le sait ; après un rechargement hors ligne, Chromium sous émulation rend108 * `navigator.onLine` vrai — l'application constate alors elle-même que le serveur ne répond pas (« Serveur injoignable »).109 */110const CUT = /^(offline|server)$/111const pendingText = (n: number) => new RegExp(`(Hors ligne|Serveur injoignable) · ${n} en attente`)112const subj = (n: string) => new RegExp(`${n} ${tag}`)113const select = (page: Page, n: string) => row(page, subj(n)).locator(".mrow-check").click()114115test.describe.configure({ mode: "serial" })116117test("manifeste et service worker : en-têtes, portée, installabilité", async ({ request }) => {118  const sw = await request.get("/sw.js")119  expect(sw.status()).toBe(200)120  expect(sw.headers()["content-type"]).toContain("javascript")121  expect(sw.headers()["cache-control"]).toBe("no-cache")122  expect(sw.headers()["service-worker-allowed"]).toBe("/")123  expect(sw.headers()["content-security-policy"]).toContain("worker-src 'self'")124  expect(sw.headers()["content-security-policy"]).toContain("manifest-src 'self'")125  const body = await sw.text()126  // pas de Web Push, aucune demande de permission — la liste des fichiers précachés, elle, nomme le morceau de l'écran « Notifications »127  expect(body).not.toMatch(/pushManager|showNotification|new Notification|Notification\.(requestPermission|permission)|addEventListener\(["']push["']/)128  expect(body.replace(/assets\/[A-Za-z0-9_.-]+/g, "")).not.toMatch(/Notification/)129  const mf = await request.get("/manifest.webmanifest")130  expect(mf.headers()["content-type"]).toContain("application/manifest+json")131  expect(mf.headers()["cache-control"]).toBe("no-cache")132  const m = await mf.json()133  expect(m).toMatchObject({ name: "SP Mail", display: "standalone", start_url: "/", scope: "/", theme_color: "#f6f5f1", background_color: "#f6f5f1" })134  expect(m.shortcuts.map((s: { name: string }) => s.name)).toEqual(["Nouveau message", "Boîte de réception"])135  for (const icon of m.icons as { src: string; sizes: string; type: string }[]) {136    const r = await request.get(icon.src)137    expect(r.status(), icon.src).toBe(200)138    expect(r.headers()["content-type"]).toContain(icon.type)139  }140  expect(m.icons.some((i: { sizes: string; purpose: string }) => i.sizes === "512x512" && i.purpose === "maskable")).toBe(true)141  // un actif haché absent n'est jamais remplacé par la page de l'application côté worker ; côté serveur, l'API inconnue reste du JSON142  expect((await request.get("/api/inconnu")).headers()["content-type"]).toContain("json")143})144145test("hors ligne : coque, cache sans /api, actions en file, rechargement, rejeu exactement une fois, conflit, refus", async ({ browser }) => {146  const box = await prepareBox()147  const ids = await seed(box, ["Lire", "Favori", "Epingler", "Archiver", "Conflit", "Disparu", "Annule", "Temoin"])148  const { context, page } = await secondSession(browser)149  const index = ((await api("GET", "/api/me")).body.mailboxes as { id: string }[]).findIndex((m) => m.id === box.id)150  const setCalls: string[] = []151  page.on("request", (r) => {152    if (r.method() === "POST" && r.url().endsWith(`/api/jmap/${box.id}/api`) && (r.postData() ?? "").includes('"Email/set"')) setCalls.push(r.postData() ?? "")153  })154  await page.goto(`/m/${index}/inbox`)155  for (const n of Object.keys(ids)) await expect(row(page, subj(n))).toBeVisible()156  await waitForShell(page)157158  // ---- Cache Storage : uniquement les fichiers publics du build ; rien de /api, aucun contenu de courrier159  const before = await shell(page)160  expect(before.caches[0]).toMatch(/^spmail-shell-[0-9a-f]{16}$/)161  expect(before.urls).toContain("/index.html")162  expect(before.urls.filter((u) => u.startsWith("/api") || u.includes("jmap")), "aucune réponse d'API dans Cache Storage").toEqual([])163  expect(before.urls.every((u) => u === "/index.html" || u === "/favicon.svg" || u === "/manifest.webmanifest" || u.startsWith("/assets/") || u.startsWith("/icons/")), before.urls.join(" ")).toBe(true)164165  // ---- réseau coupé : la coque se recharge, la liste vient de la copie locale166  await context.setOffline(true)167  await page.reload()168  await expect(page.locator("#sidebar")).toBeAttached()169  await expect(sync(page)).toHaveAttribute("data-sync", CUT)170  for (const n of Object.keys(ids)) await expect(row(page, subj(n))).toBeVisible()171  await expect(page.locator(".list-count")).toContainText("copie locale")172  await page.screenshot({ path: "/tmp/spmail-next-shots/web-ops/offline-shell.png" })173174  // ---- actions hors ligne175  await row(page, subj("Favori")).locator(".mrow-star").click()176  await expect(row(page, subj("Favori")).locator(".mrow-star")).toHaveClass(/\bon\b/)177  await row(page, subj("Disparu")).locator(".mrow-star").click()178  // favori puis retrait : les deux actions s'annulent dans la file179  await row(page, subj("Annule")).locator(".mrow-star").click()180  await expect(row(page, subj("Annule")).locator(".mrow-star")).toHaveClass(/\bon\b/)181  await row(page, subj("Annule")).locator(".mrow-star").click()182  await expect(row(page, subj("Annule")).locator(".mrow-star")).not.toHaveClass(/\bon\b/)183  await select(page, "Lire")184  await page.getByRole("button", { name: "Marquer comme lu" }).first().click()185  await expect(row(page, subj("Lire"))).not.toHaveClass(/unread/)186  await page.keyboard.press("Escape")187  await select(page, "Epingler")188  await page.keyboard.press("p")189  await page.keyboard.press("Escape")190  await select(page, "Archiver")191  await page.keyboard.press("e")192  await expect(row(page, subj("Archiver"))).toHaveCount(0)193  await select(page, "Conflit")194  await page.keyboard.press("e")195  await expect(row(page, subj("Conflit"))).toHaveCount(0)196  // rien n'a échoué ni été annulé : pas de notification d'erreur197  await expect(page.locator(".toast.error")).toHaveCount(0)198  // l'indicateur discret compte la vraie file : 6 actions (l'aller-retour « Annule » n'en laisse aucune)199  await expect(sync(page)).toContainText(pendingText(6))200  await expect(sync(page)).toHaveAttribute("title", /L'envoi et la suppression définitive exigent une connexion/)201  await page.screenshot({ path: "/tmp/spmail-next-shots/web-ops/offline-pending.png" })202  const me = (await api("GET", "/api/me")).body.user.id as string203  await expect.poll(async () => (await storedQueue(page))?.ops.length ?? 0).toBe(6)204  const q = (await storedQueue(page))!205  expect(q.user).toBe(me)206  expect(q.ops.map((o) => o.id).sort()).toEqual([ids.Lire, ids.Favori, ids.Epingler, ids.Archiver, ids.Conflit, ids.Disparu].sort())207  // le serveur n'a encore rien reçu208  const untouched = await serverState(box, Object.values(ids))209  expect(untouched[ids.Favori]!.keywords.$flagged).toBeUndefined()210  expect(untouched[ids.Archiver]!.mailboxIds).toEqual({ [box.folders.inbox]: true })211  expect(setCalls.length).toBe(0)212213  // ---- rechargement, toujours hors ligne : les actions sont encore là (file relue d'IndexedDB, affichage recouvert)214  await page.reload()215  await expect(page.locator("#sidebar")).toBeAttached()216  await expect(row(page, subj("Temoin"))).toBeVisible()217  await expect(row(page, subj("Favori")).locator(".mrow-star")).toHaveClass(/\bon\b/)218  await expect(row(page, subj("Lire"))).not.toHaveClass(/unread/)219  await expect(row(page, subj("Temoin"))).toHaveClass(/unread/)220  await expect(row(page, subj("Archiver"))).toHaveCount(0)221  await expect(row(page, subj("Conflit"))).toHaveCount(0)222  await expect(sync(page)).toContainText(pendingText(6))223  // suppression définitive : jamais mise en file, dite clairement224  expect((await shell(page)).urls.filter((u) => u.startsWith("/api"))).toEqual([])225226  // ---- pendant ce temps, sur le serveur : « Conflit » part à la corbeille, « Disparu » est supprimé définitivement227  await jmap(box, [["Email/set", { accountId: box.acct, update: { [ids.Conflit]: { mailboxIds: { [box.folders.trash]: true } } }, destroy: [ids.Disparu] }, "x"]])228229  // ---- reconnexion : rejeu dans l'ordre, une seule fois230  await context.setOffline(false)231  await expect(sync(page)).toHaveAttribute("data-sync", "idle", { timeout: 60_000 })232  await expect.poll(async () => (await storedQueue(page))?.ops.length ?? 0, { timeout: 30_000 }).toBe(0)233  const after = await serverState(box, Object.values(ids))234  expect(after[ids.Favori]!.keywords.$flagged).toBe(true)235  expect(after[ids.Lire]!.keywords.$seen).toBe(true)236  expect(after[ids.Epingler]!.keywords, JSON.stringify(after[ids.Epingler])).toMatchObject({ $pinned: true })237  expect(after[ids.Archiver]!.mailboxIds).toEqual({ [box.folders.archive]: true })238  expect(after[ids.Annule]!.keywords.$flagged).toBeUndefined()239  expect(Object.keys(after[ids.Temoin]!.keywords).filter((k) => ["$seen", "$flagged", "$pinned"].includes(k)), "le témoin n'a pas été touché").toEqual([])240  // conflit : le choix du serveur (corbeille) reste ; refus : le message supprimé n'est pas recréé241  expect(after[ids.Conflit]!.mailboxIds).toEqual({ [box.folders.trash]: true })242  expect(after[ids.Disparu]).toBeNull()243  await expect(toastText(page, /n'a pas pu être appliquée/)).toHaveCount(1)244  await expect(toastText(page, /remplacée par un changement plus récent/)).toHaveCount(1)245  // exactement une requête Email/set, portant les quatre actions valides et elles seules246  await page.waitForTimeout(4000)247  const replayed = setCalls.filter((b) => [ids.Favori, ids.Lire, ids.Epingler, ids.Archiver].some((id) => b.includes(id)))248  expect(replayed.length, "exactement une fois").toBe(1)249  for (const id of [ids.Favori, ids.Lire, ids.Epingler, ids.Archiver]) expect(replayed[0]).toContain(id)250  for (const id of [ids.Conflit, ids.Disparu, ids.Annule, ids.Temoin]) expect(setCalls.join("\n")).not.toContain(id)251  // l'interface converge vers l'état du serveur252  await expect(row(page, subj("Disparu"))).toHaveCount(0)253  await expect(row(page, subj("Conflit"))).toHaveCount(0)254  await expect(row(page, subj("Favori")).locator(".mrow-star")).toHaveClass(/\bon\b/)255  await expect(page.locator(".list-count")).not.toContainText("copie locale")256  await page.getByRole("link", { name: /Corbeille/ }).click()257  await expect(row(page, subj("Conflit"))).toBeVisible()258  await page.getByRole("link", { name: /Archives/ }).click()259  await expect(row(page, subj("Archiver"))).toBeVisible()260  await expect(list(page)).toBeVisible()261  await page.screenshot({ path: "/tmp/spmail-next-shots/web-ops/offline-converged.png" })262263  // ---- déconnexion avec une action encore en file : caches vidés, file effacée, worker désenregistré264  // (réseau présent, mais la passerelle JMAP de cette boîte ne répond plus : panne de transport → l'action attend)265  await page.getByRole("link", { name: /Boîte de réception/ }).click()266  await page.route(`**/api/jmap/${box.id}/api`, (route) => route.abort("connectionfailed"))267  await row(page, subj("Temoin")).locator(".mrow-star").click()268  await expect(row(page, subj("Temoin")).locator(".mrow-star")).toHaveClass(/\bon\b/)269  await expect.poll(async () => (await storedQueue(page))?.ops.length ?? 0).toBe(1)270  await expect(sync(page)).toHaveAttribute("data-pending", "1")271  await page.getByRole("button", { name: "Se déconnecter" }).click()272  await expect(page.getByRole("button", { name: "Se connecter avec une clé d'accès" })).toBeVisible()273  await expect.poll(async () => (await shell(page)).registrations).toBe(0)274  const out = await shell(page)275  expect(out.caches).toEqual([])276  expect(await storedQueue(page)).toBeNull()277  expect(await page.evaluate(async () => (await indexedDB.databases()).map((d) => d.name))).not.toContain("spmail-cache")278  // l'action abandonnée à la déconnexion n'atteint jamais le serveur, même réseau rétabli279  await page.unroute(`**/api/jmap/${box.id}/api`)280  await page.waitForTimeout(3000)281  expect((await serverState(box, [ids.Temoin]))[ids.Temoin]!.keywords.$flagged).toBeUndefined()282  await context.close()283})284285test("hors ligne, écrans Next : libellé et épingle en file (comptés), veille refusée avec sa raison, envoi expliqué dans la rédaction, aucune page blanche", async ({ browser }) => {286  const box = await prepareBox()287  const ids = await seed(box, ["Etiqueter", "Veiller", "Voisin"])288  const label = (await api("POST", "/api/next/labels", { name: `Hors ligne ${tag}` })).body as { id: string; keyword: string; name: string }289  expect(label.keyword, JSON.stringify(label)).toMatch(/^lbl_/)290  const { context, page } = await secondSession(browser)291  const failedChunks: string[] = []292  page.on("console", (m) => {293    if (m.type() === "error" && /dynamically imported module|Loading chunk|ChunkLoadError|module script/i.test(m.text())) failedChunks.push(m.text())294  })295  page.on("pageerror", (e) => failedChunks.push(`pageerror: ${e.message}`))296  const index = ((await api("GET", "/api/me")).body.mailboxes as { id: string }[]).findIndex((m) => m.id === box.id)297  await page.goto(`/m/${index}/inbox`)298  for (const n of Object.keys(ids)) await expect(row(page, subj(n))).toBeVisible()299  // les modules Next sont inscrits (le libellé créé par l'API est dans la barre latérale) avant de couper le réseau300  await expect(page.locator("#sidebar").getByRole("link", { name: new RegExp(label.name) })).toBeVisible()301  await waitForShell(page)302303  // ---- le précache contient tous les morceaux du build, y compris ceux chargés à la demande (écrans Next, rédaction)304  const built = fs.readdirSync(path.join(OUT, "web-a", "assets")).map((f) => `/assets/${f}`)305  const cached = (await shell(page)).urls306  expect(built.filter((f) => !cached.includes(f)), "morceaux absents du précache").toEqual([])307  expect(built.filter((f) => /^\/assets\/(Dashboard|ContactsScreen|GalleryScreen|SnoozedPage|Host|LabelDialogs|SearchResults)-/.test(f)).length, built.join(" ")).toBeGreaterThanOrEqual(6)308309  await context.setOffline(true)310  await expect(sync(page)).toHaveAttribute("data-sync", "offline")311312  // ---- libellé : cochable hors ligne, gardé dans la file durable, compté par l'indicateur313  await row(page, subj("Etiqueter")).click({ button: "right" })314  await page.getByRole("menu").getByRole("menuitem", { name: /^Libellés/ }).click()315  const picker = page.getByRole("dialog", { name: "Libellés" })316  await expect(picker.locator("[data-nx-offline-note]")).toContainText("partiront à la reconnexion")317  await picker.getByRole("checkbox", { name: new RegExp(label.name) }).check()318  await page.keyboard.press("Escape")319  await expect(row(page, subj("Etiqueter")).locator(".label-dot")).toHaveCount(1)320  await expect(page.locator(".toast.error")).toHaveCount(0)321  // ---- épingle : même file322  await select(page, "Voisin")323  await page.keyboard.press("p")324  await page.keyboard.press("Escape")325  await expect(sync(page)).toContainText(pendingText(2))326  await expect.poll(async () => (await storedQueue(page))?.ops.length ?? 0).toBe(2)327  const q = (await storedQueue(page))!328  expect(q.ops.find((o) => o.id === ids.Etiqueter)?.patch).toEqual({ [`keywords/${label.keyword}`]: true })329  expect(q.ops.find((o) => o.id === ids.Voisin)?.patch).toEqual({ "keywords/$pinned": true })330  expect((await serverState(box, [ids.Etiqueter]))[ids.Etiqueter]!.keywords[label.keyword]).toBeUndefined()331332  // ---- veille : planifiée par le serveur → refusée hors ligne, avec l'explication ; rien n'entre dans la file333  await select(page, "Veiller")334  await page.keyboard.press("b")335  await expect(toastText(page, "la mise en veille et les rappels sont planifiés par le serveur et demandent une connexion")).toBeVisible()336  await expect(page.getByRole("dialog", { name: "Mettre en veille" })).toHaveCount(0)337  await page.keyboard.press("Escape")338  expect((await storedQueue(page))?.ops.length).toBe(2)339340  // ---- rédaction : elle dit elle-même que l'envoi exige une connexion ; le bouton est désactivé, avec sa raison341  await page.keyboard.press("c")342  const composer = page.locator("section.composer")343  await expect(composer).toBeVisible()344  await expect(composer.locator('[data-cmp-blocked="offline"]')).toContainText("Hors ligne : l'envoi demande une connexion. Votre brouillon est conservé sur cet appareil")345  const send = composer.locator(".cmp-send-main")346  await expect(send).toBeDisabled()347  await expect(send).toHaveAttribute("title", "Hors ligne : l'envoi demande une connexion")348  await composer.getByRole("combobox", { name: "À :" }).fill(st.addrB)349  await composer.getByRole("combobox", { name: "À :" }).press("Enter")350  await composer.getByLabel("Objet :").fill(`Hors ligne ${tag}`)351  await page.keyboard.press("Control+Enter")352  await expect(composer).toBeVisible() // rien n'est parti, rien n'a été fermé353  await page.screenshot({ path: "/tmp/spmail-next-shots/web-final/composer-offline.png" })354355  // ---- rechargement hors ligne : la coque démarre sur chaque route des nouveaux écrans, jamais de page blanche356  for (const [route, heading] of [["/dashboard", "Centre de commande"], ["/contacts", "Contacts"], ["/attachments", "Pièces jointes"], ["/snoozed", "En veille"], ["/settings/intelligence", "Réglages"], ["/settings/rules", "Réglages"]] as const) {357    await page.goto(route)358    // (les réglages ont leur propre page, sans la barre latérale du courrier)359    if (!route.startsWith("/settings")) await expect(page.locator("#sidebar"), route).toBeAttached()360    await expect(page.getByRole("heading", { level: 1, name: heading }).first(), route).toBeVisible()361    expect((await page.locator("#main, main").first().innerText()).trim().length, `${route} : contenu`).toBeGreaterThan(20)362  }363  // après le rechargement hors ligne (le navigateur peut se croire en ligne : « serveur injoignable ») la rédaction le dit toujours364  await page.goto(`/m/${index}/inbox`)365  await expect(row(page, subj("Etiqueter"))).toBeVisible()366  await expect(row(page, subj("Etiqueter")).locator(".label-dot")).toHaveCount(1)367  await expect(sync(page)).toContainText(pendingText(2))368  const again = page.locator("section.composer")369  if (!(await again.count())) await page.locator('[data-cmp-dock]').first().click()370  await expect(again.locator('[data-cmp-blocked="offline"]')).toBeVisible()371  await expect(again.locator(".cmp-send-main")).toBeDisabled()372  expect(failedChunks, "aucun morceau introuvable hors ligne").toEqual([])373374  // ---- reconnexion : libellé et épingle atteignent le serveur ; l'envoi redevient possible375  await context.setOffline(false)376  await expect.poll(async () => (await storedQueue(page))?.ops.length ?? 0, { timeout: 60_000 }).toBe(0)377  const after = await serverState(box, [ids.Etiqueter, ids.Voisin, ids.Veiller])378  expect(after[ids.Etiqueter]!.keywords[label.keyword]).toBe(true)379  expect(after[ids.Voisin]!.keywords.$pinned).toBe(true)380  expect(after[ids.Veiller]!.keywords.$snoozed).toBeUndefined()381  await expect(again.locator('[data-cmp-blocked="offline"]')).toHaveCount(0, { timeout: 30_000 })382  await expect(again.locator(".cmp-send-main")).toBeEnabled()383  await again.getByRole("button", { name: "Supprimer le brouillon" }).click()384  await page.getByRole("alertdialog").getByRole("button", { name: "Supprimer le brouillon" }).click()385  await context.close()386  // la boîte de cet essai est purgée tout de suite : chaque boîte tient une connexion de notification, et le navigateur n'en accorde387  // que six par hôte en HTTP/1.1 (serveur d'essai local) — une sixième boîte empêcherait le précache des essais suivants388  expect((await api("DELETE", `/api/admin/mailboxes/${box.id}?purge=delete-all-mail`)).status).toBe(200)389})390391test("perte de session avec des actions en file : rien n'est rejoué, caches et file effacés, worker désenregistré", async ({ browser }) => {392  const box = await prepareBox()393  const ids = await seed(box, ["Perdu"])394  const { context, page } = await secondSession(browser)395  const index = ((await api("GET", "/api/me")).body.mailboxes as { id: string }[]).findIndex((m) => m.id === box.id)396  await page.goto(`/m/${index}/inbox`)397  await expect(row(page, subj("Perdu"))).toBeVisible()398  await waitForShell(page)399  const session = sql("select id from sessions where revoked_at is null order by created_at desc limit 1")400  await context.setOffline(true)401  await row(page, subj("Perdu")).locator(".mrow-star").click()402  await expect.poll(async () => (await storedQueue(page))?.ops.length ?? 0).toBe(1)403  // la session est révoquée ailleurs pendant que l'appareil est hors ligne404  sql(`update sessions set revoked_at = now() where id = '${session}'`)405  await context.setOffline(false)406  await expect(page.getByRole("button", { name: "Se connecter avec une clé d'accès" })).toBeVisible({ timeout: 60_000 })407  await expect(page.getByText("Votre session a expiré")).toBeVisible()408  await expect.poll(async () => (await shell(page)).registrations).toBe(0)409  expect((await shell(page)).caches).toEqual([])410  await expect.poll(() => storedQueue(page)).toBeNull()411  // l'action n'a jamais atteint le serveur412  expect((await serverState(box, [ids.Perdu]))[ids.Perdu]!.keywords.$flagged).toBeUndefined()413  await context.close()414})415416test("mise à jour : le build suivant attend, « Une mise à jour est prête », rechargement, aucune version mêlée", async ({ browser }) => {417  const files = (t: string) => fs.readdirSync(path.join(OUT, `web-${t}`, "assets")).map((f) => `/assets/${f}`)418  const A = files("a")419  const B = files("b")420  expect(A.filter((f) => !B.includes(f)).length, "les deux builds diffèrent par au moins un fichier haché").toBeGreaterThan(0)421  const { context, page } = await secondSession(browser)422  await waitForShell(page)423  const first = await shell(page)424  expect(first.build).toBe("a")425  const cacheA = first.caches[0]426  expect((await loadedAssets(page)).every((f) => A.includes(f))).toBe(true)427428  // ---- le serveur passe au build « b »429  await startBackend(st.addrExt, path.join(OUT, "web-b"))430  await page.evaluate(() => navigator.serviceWorker.getRegistration().then((r) => r?.update()))431  const toast = toastText(page, "Une mise à jour est prête")432  await expect(toast).toBeVisible({ timeout: 30_000 })433  await page.screenshot({ path: "/tmp/spmail-next-shots/web-ops/update-toast.png" })434  // tant que la personne n'a pas accepté : la page et un rechargement restent ENTIÈREMENT sur « a » (le serveur n'a plus ses fichiers)435  expect((await shell(page)).build).toBe("a")436  await page.reload()437  await expect(page.locator("#sidebar")).toBeAttached()438  expect((await shell(page)).build).toBe("a")439  const mixed = (await loadedAssets(page)).filter((f) => !A.includes(f))440  expect(mixed, "aucun fichier du build « b » dans une page « a »").toEqual([])441  expect((await shell(page)).caches).toContain(cacheA)442  await expect(toast).toBeVisible({ timeout: 30_000 })443444  // ---- acceptée : la nouvelle version prend la main, la page se recharge, l'ancien cache disparaît445  await Promise.all([page.waitForEvent("load"), toast.getByRole("button", { name: "Recharger" }).click()])446  await expect(page.locator("#sidebar")).toBeAttached()447  await expect.poll(async () => (await shell(page)).build, { timeout: 30_000 }).toBe("b")448  await expect.poll(async () => (await shell(page)).caches.length).toBe(1)449  const last = await shell(page)450  expect(last.caches[0]).not.toBe(cacheA)451  expect((await loadedAssets(page)).filter((f) => !B.includes(f)), "aucun fichier du build « a » dans une page « b »").toEqual([])452  expect(last.urls.filter((u) => u.startsWith("/assets/")).every((u) => B.includes(u))).toBe(true)453  await expect(toastText(page, "Une mise à jour est prête")).toHaveCount(0)454  await context.close()455})456
Files main
Menu

Theme