Files
ia-fit/tests/browser/parcours.cjs
T
2026-11-18 15:15:45 +01:00

768 lines
46 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Parcours de l'app dans un vrai navigateur (Chromium sans écran, Playwright),
// en thème sombre puis clair, avec des captures 412×915 dans build/shots/.
// Lancé par `make test-browser` dans l'image Docker de Playwright :
// node parcours.cjs <dossier de l'app> <dossier des captures>
// Le script sert lui-même l'app (serveur statique minimal) et mesure le poids
// transféré au premier chargement (brut et compressé gzip).
//
// La date est figée au mercredi 18 novembre 2026, 9 h, puis le temps s'écoule
// normalement : le planning de la semaine est donc toujours le même.
const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const zlib = require("node:zlib");
const { chromium } = require("/tools/node_modules/playwright");
const appDir = path.resolve(process.argv[2] ?? "app");
const outDir = path.resolve(process.argv[3] ?? "build/shots");
/** Le vrai serveur (server/main.js, lancé par make test-browser), pour la synchro. */
const serverBase = process.argv[4] ?? "";
const START = new Date("2026-11-18T09:00:00");
const TYPES = {
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
".json": "application/json", ".webmanifest": "application/manifest+json", ".svg": "image/svg+xml",
".woff2": "font/woff2", ".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8",
};
/** Octets servis au chargement : chemin → {brut, gzip}. */
const served = new Map();
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
const file = path.join(appDir, decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname));
if (!file.startsWith(appDir) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
res.writeHead(404).end();
return;
}
const body = fs.readFileSync(file);
if (!served.has(url.pathname)) served.set(url.pathname, { raw: body.length, gzip: zlib.gzipSync(body, { level: 9 }).length });
res.writeHead(200, { "Content-Type": TYPES[path.extname(file)] ?? "application/octet-stream", "Cache-Control": "no-cache" });
res.end(body);
});
let failures = 0;
/** Page en cours, pour une capture si le parcours s'interrompt. */
let lastPage = null;
/** @param {string} scheme @param {boolean} cond @param {string} msg */
function check(scheme, cond, msg) {
if (cond) console.log(`ok [${scheme}] ${msg}`);
else {
failures++;
console.log(`ÉCHEC [${scheme}] ${msg}`);
}
}
(async () => {
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const base = `http://127.0.0.1:${server.address().port}/`;
fs.mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch();
for (const scheme of ["dark", "light"]) {
const ctx = await browser.newContext({
viewport: { width: 412, height: 915 }, colorScheme: scheme, deviceScaleFactor: 1, locale: "fr-FR",
acceptDownloads: true, permissions: ["clipboard-read", "clipboard-write"],
});
await ctx.clock.install({ time: START });
await ctx.clock.resume();
const page = await ctx.newPage();
lastPage = page;
const errors = [];
page.on("pageerror", (e) => errors.push(String(e)));
page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });
const ok = (cond, msg) => check(scheme, cond, msg);
const shot = (name, full = false) => page.screenshot({ path: `${outDir}/${scheme}-${name}.png`, fullPage: full });
const settle = () => page.waitForTimeout(250);
const go = async (hash) => { await page.goto(base + hash); await page.waitForSelector("h1"); await settle(); };
const button = (name, opts = {}) => page.getByRole("button", { name, ...opts });
const inDialog = (name) => page.locator("dialog[open]").getByRole("button", { name });
// ---- premier lancement ---------------------------------------------------------
served.clear();
await go("#/");
await page.waitForLoadState("networkidle");
if (scheme === "dark") {
const raw = [...served.values()].reduce((n, x) => n + x.raw, 0);
const gz = [...served.values()].reduce((n, x) => n + x.gzip, 0);
const report = `Premier chargement (onboarding) : ${served.size} fichiers, ${(raw / 1024).toFixed(1)} Ko bruts, ${(gz / 1024).toFixed(1)} Ko en gzip -9.\n` +
[...served].sort((a, b) => b[1].raw - a[1].raw).map(([p, x]) => ` ${p} ${x.raw} o (gzip ${x.gzip} o)`).join("\n") + "\n";
fs.writeFileSync(`${outDir}/poids.txt`, report);
console.log(report.split("\n")[0]);
}
ok(await button("Créer mon programme").isVisible(), "onboarding : action principale visible");
await shot("01-onboarding", true);
await button("Créer mon programme").click();
await settle();
ok(await page.getByText("Copié. Colle-le dans ton IA.").isVisible(), "texte d'accueil copié");
// ---- programme d'exemple : proposition, aperçu, adoption -----------------------
await button("Programme d'exemple").click();
await settle();
ok(await page.getByText("Un programme t'attend").isVisible(), "la proposition passe avant tout");
ok(await page.getByText("Nouveau programme ·").isVisible(), "aperçu : nouveau programme");
await shot("02-proposition");
await button("Adopter").click();
await settle();
ok(await page.getByText("Pas de planning").isVisible(), "accueil sans planning : rotation annoncée");
ok(await page.locator(".hud").isVisible(), "HUD de niveau affiché");
// ---- semaine : jours, jour imposé, semaine suivante, .ics ------------------------
await go("#/semaine");
for (const d of ["lundi", "mercredi", "vendredi", "samedi"]) await page.getByRole("button", { name: d, exact: true }).click();
await settle();
ok(await page.locator(".week__row").count() === 7, "semaine : sept jours");
ok(await page.locator(".week__row", { hasText: "Séance" }).count() === 3, "trois séances de force placées");
ok(await page.locator(".week__row", { hasText: "Cardio" }).count() === 1, "le cardio remplit le samedi");
await page.locator(".week__day").nth(6).click();
await button("Repos", { exact: true }).click();
await settle();
ok(await page.locator(".week__row").nth(6).getByText("Repos imposé").isVisible(), "dimanche : repos imposé");
await shot("03-semaine", true);
const ics = page.waitForEvent("download");
await button("Télécharger le .ics").click();
const icsText = fs.readFileSync(await (await ics).path(), "utf8");
ok(/BEGIN:VCALENDAR/.test(icsText) && /DTSTART:20261120T180000/.test(icsText), "export .ics : vendredi 18 h");
await button("Semaine suivante").click();
await settle();
ok(await page.getByText("réglage propre à cette semaine").count() === 0, "semaine suivante : suit le réglage par défaut");
await page.getByRole("button", { name: "mardi", exact: true }).click();
await settle();
ok(await page.getByText("réglage propre à cette semaine").isVisible(), "semaine suivante : réglage propre");
// Onglet et jour déplié dans l'adresse (ADR 0009, lot 3c).
const hashOf = () => page.url().split("#")[1] ?? "";
ok(hashOf() === "/semaine?semaine=2026-W48", "onglet dans l'adresse : " + hashOf());
await page.reload();
await page.waitForSelector("h1");
await settle();
ok(await button("Semaine suivante").getAttribute("aria-pressed") === "true", "semaine suivante retrouvée après rechargement");
await page.locator(".week__day").nth(2).click();
await settle();
ok(hashOf() === "/semaine?semaine=2026-W48&jour=3", "jour déplié dans l'adresse : " + hashOf());
await page.goBack();
await page.waitForSelector("h1");
await settle();
ok(hashOf() === "/semaine?semaine=2026-W48" && await page.locator(".week .choice-list").count() === 0
&& await button("Semaine suivante").getAttribute("aria-pressed") === "true", "retour : le jour se referme, l'onglet reste");
await button("Cette semaine").click();
ok(hashOf() === "/semaine", "semaine en cours : adresse sans paramètre");
// ---- accueil planifié : carte du jour, retard ---------------------------------------
await go("#/");
ok(await page.getByText("En retard cette semaine").isVisible(), "lundi en retard");
ok(await page.getByRole("link", { name: "Commencer" }).isVisible(), "aujourd'hui : séance à commencer");
await shot("04-accueil");
await shot("04b-accueil-long", true);
await button("Autre activité").click();
ok(await page.getByLabel("Le", { exact: true }).isVisible(), "autre activité : date au choix");
await button("Autre activité").click();
// ---- séance A (le retard de lundi), faite aujourd'hui ---------------------------
await page.locator(".block--today").getByRole("link", { name: "Faire" }).click();
await page.waitForSelector(".screen--session");
await settle();
await page.locator("summary", { hasText: "Squat barre" }).click();
const squat = page.locator("details[open]", { hasText: "Squat barre" }).last();
const load = squat.getByLabel("Charge");
await load.fill("60");
await load.press("Tab");
for (let i = 1; i <= 3; i++) {
await squat.getByRole("button", { name: new RegExp(`^Série ${i} : à faire`) }).click();
await squat.locator(".effort[data-effort=ok]").click();
await page.locator(".timer").getByRole("button", { name: "Terminer" }).click();
}
ok(await page.locator(".combo").innerText().then((t) => /COMBO ×3/i.test(t)), "combo ×3 après trois séries");
await squat.getByRole("button", { name: /^Série 4 : à faire/ }).click();
await squat.getByRole("button", { name: "Une répétition de moins" }).click();
await shot("05-serie");
await squat.locator(".effort[data-effort=hard]").click();
await settle();
ok(await page.locator(".timer").isVisible(), "le repos démarre au ressenti");
ok(await squat.getByRole("button", { name: "Série 4 : 7 répétitions, dur" }).count() === 1, "série 4 : 7 répétitions, dur");
await shot("06-repos");
await page.locator(".timer").getByRole("button", { name: "Terminer" }).click();
// Gainage : chrono de 2 s, qui coche la série.
await page.locator("summary", { hasText: "Gainage" }).click();
const plank = page.locator("details[open]", { hasText: "Gainage" }).last();
const secs = plank.getByLabel("Durée");
await secs.fill("2");
await secs.press("Tab");
await plank.getByRole("button", { name: /Lancer la série/ }).click();
await page.waitForTimeout(3000);
ok(await plank.locator(".set-btn--done").count() === 1, "le chrono coche la série au temps");
await plank.locator(".effort[data-effort=ok]").click();
await page.locator(".timer").getByRole("button", { name: "Terminer" }).click();
await button("Terminer la séance").click();
await page.waitForSelector("dialog[open]");
await inDialog("Enregistrer quand même").click();
await page.waitForSelector(".screen--finish");
await page.waitForTimeout(1200);
ok(await page.getByText("Bien joué.").isVisible(), "écran de fin de séance");
ok(await page.locator(".reward__gain").innerText().then((t) => /\+\d+ XP/.test(t.replace(/\s/g, " "))), "XP gagnée affichée");
ok(await page.locator(".reward__big .big-number").innerText().then((t) => t.replace(/\s/g, "") === "1860"), "1 860 kg soulevés (31 répétitions × 60 kg)");
await shot("07-fin-de-seance", true);
await page.getByRole("link", { name: "Continuer" }).click();
await settle();
ok(await page.getByText("En retard cette semaine").count() === 0, "le retard de lundi est rattrapé");
// ---- progression de la charge (double progression) ---------------------------------
// Une séance A complète au haut de la fourchette : le conseil apparaît.
await page.evaluate(async () => {
const { store } = await import("./main.js");
const s = store.getState();
const a = s.program.sessions.find((x) => x.key === "A");
store.dispatch("SessionLogged", {
date: "2026-11-18", kind: "strength", ref: "A", name: a.name, warmup: null,
exercises: [{ id: "squat", name: "Squat barre", target: "4 × 8", tracking: "load", loadKg: 60, seconds: null, plannedSets: 4,
sets: Array.from({ length: 4 }, () => ({ reps: 8, effort: "easy" })) }],
});
});
await go("#/seance/A");
await page.locator("summary", { hasText: "Squat barre" }).click();
ok(await page.getByText("Prêt à monter").isVisible(), "conseil de progression : prêt à monter");
ok(await page.locator(".exercise--warmup").getByText("50 kg × 5 reps").count() === 0 && await page.locator(".exercise--warmup").getByText("30 kg × 8 reps").isVisible(), "séries d'approche chiffrées depuis 60 kg");
await shot("08-conseil");
await button("Adopter 62,5 kg").click();
ok(await page.locator("details[open]", { hasText: "Squat barre" }).last().getByLabel("Charge").inputValue().then((v) => v === "62,5"), "charge adoptée : 62,5 kg");
await page.locator("#session-date").fill("2026-11-17");
ok(hashOf() === "/seance/A/2026-11-17", "date de la séance dans l'adresse : " + hashOf());
await page.evaluate(() => localStorage.removeItem("ia-fit.draft"));
// ---- activités -------------------------------------------------------------------
await go("#/activites");
await page.getByLabel("Nom").fill("Foot en salle");
await button("Bas du corps").click();
await button("Intense").click();
await button("Enregistrer l'activité").click();
await settle();
ok(await page.locator(".row", { hasText: "Foot en salle" }).isVisible(), "activité ajoutée");
await shot("09-activites", true);
await button("Modifier Foot en salle").click();
ok(hashOf() === "/activites?modifier=foot-en-salle", "activité modifiée dans l'adresse : " + hashOf());
await page.reload();
await page.waitForSelector("h1");
await settle();
ok(await page.getByLabel("Nom").inputValue() === "Foot en salle" && await page.getByText("Modifier · Foot en salle").isVisible(), "modification retrouvée après rechargement");
await button("Annuler la modification").click();
ok(hashOf() === "/activites", "modification annulée : adresse sans paramètre");
// ---- poids -----------------------------------------------------------------------
await go("#/poids");
await page.locator(".import > summary").click();
await page.getByLabel(/Une pesée par ligne/).fill(["2026-08-01 86,2", "15/08/2026 ; 85,4", "2026-09-01 84,9", "2026-09-20 84,1", "2026-10-10 83,6", "2026-10-30 83,0", "pas une pesée", "2026-11-12 82,4"].join("\n"));
await button("Lire").click();
ok(await page.getByText("7 pesées lisibles.").isVisible(), "import : 7 pesées lisibles, 1 ignorée");
await button("Importer 7 pesées").click();
await page.getByLabel("Poids (kg)").fill("82,1");
await button("Enregistrer", { exact: true }).click();
await settle();
ok(await page.locator(".stat__value").first().innerText().then((t) => t.startsWith("82,1")), "pesée du jour : 82,1 kg");
ok(await page.locator(".chart svg path.chart__line").count() === 1, "courbe tracée");
await button("Tout").click();
ok(hashOf() === "/poids?periode=tout", "période dans l'adresse : " + hashOf());
await page.reload();
await page.waitForSelector("h1");
await settle();
ok(await button("Tout").getAttribute("aria-pressed") === "true", "période retrouvée après rechargement");
await shot("10-poids", true);
// ---- profil et mode ----------------------------------------------------------------
await go("#/profil");
await page.getByLabel("Objectif").fill("Prendre de la force sans me blesser");
await page.getByLabel("Matériel").fill("Barre\nBanc\nHaltères");
await button("Enregistrer le profil").click();
ok(await page.getByText("Profil enregistré.").isVisible(), "profil enregistré");
await button("Maintien").click();
ok(await button("Maintien").getAttribute("aria-pressed") === "true", "mode maintien");
await shot("11-profil", true);
await button("Progression", { exact: true }).click();
// ---- analyses, progression -------------------------------------------------------
await go("#/analyses");
ok(await page.locator(".chart svg").count() === 1, "assiduité : barres");
await shot("12-analyses", true);
await page.getByRole("link", { name: /Squat barre/ }).click();
await settle();
ok(await page.locator(".chart__line").count() >= 1, "squat : courbe de charge");
await shot("13-analyse-squat", true);
await go("#/progression");
ok(await page.getByText("Premier pas").isVisible(), "succès « Premier pas »");
await shot("14-progression", true);
// ---- bibliothèque : filtres dans l'adresse, fiche, retour (ADR 0009) -------------
await go("#/");
await page.getByRole("link", { name: /Bibliothèque/ }).click();
await settle();
ok(await page.locator("h1").textContent() === "Bibliothèque", "tuile vers la bibliothèque");
await button("Bas du corps").click();
await button("Fessiers").click();
await page.locator("#lib-q").fill("pont");
await page.waitForTimeout(400);
ok(page.url().endsWith("#/bibliotheque?q=pont&zone=lower&muscle=glutes"), "filtres dans l'adresse : " + page.url().split("#")[1]);
await shot("19-bibliotheque", true);
await page.reload();
await page.waitForSelector("h1");
await settle();
ok(await page.locator("#lib-q").inputValue() === "pont" && await button("Fessiers").getAttribute("aria-pressed") === "true", "filtres retrouvés après rechargement");
const firstHit = page.locator(".lib-results .row").first();
const hitName = (await firstHit.locator(".row__title").textContent()) ?? "";
await firstHit.click();
await settle();
ok(await page.locator("h1").textContent() === hitName, "fiche : " + hitName);
ok(await page.getByRole("heading", { name: "Exercices proches" }).isVisible(), "fiche : exercices proches");
await shot("20-fiche", true);
await page.goBack();
await settle();
ok(page.url().endsWith("?q=pont&zone=lower&muscle=glutes"), "retour : la liste filtrée");
await go("#/bibliotheque/squat");
ok(await page.getByText(/Fait \d+ fois/).isVisible(), "fiche du squat : historique et lien vers les analyses");
await button(/Demander à mon IA/).click();
await settle();
ok(/## Ma demande/.test(await page.evaluate(() => navigator.clipboard.readText())), "texte pour l'IA copié");
// ---- remplacer un exercice en séance (lot 3b) -----------------------------------
await go("#/seance/A");
const firstCard = page.locator("details.exercise:not(.exercise--warmup)").first();
if (!(await firstCard.getAttribute("open") !== null)) await firstCard.locator("summary").click();
const planned = ((await firstCard.locator(".exercise__name strong").textContent()) ?? "").trim();
await firstCard.getByRole("button", { name: "Machine prise ? Remplacer cet exercice" }).click();
await settle();
ok(await page.locator("h1").textContent() === "Remplacer" && page.url().includes("remplacer=A.1"), "bibliothèque en mode choix");
await shot("21-remplacer", true);
const pickRow = page.locator(".rows button.row").first();
const picked = ((await pickRow.locator(".row__title").textContent()) ?? "").trim();
await pickRow.click();
await settle();
const card = page.locator("details.exercise:not(.exercise--warmup)").first();
ok(page.url().endsWith("#/seance/A") && ((await card.locator(".exercise__name strong").textContent()) ?? "").includes(picked), `remplacé : ${planned} → ${picked}`);
ok(await card.getByText(`À la place de « ${planned} »`).isVisible(), "la carte rappelle l'exercice prévu");
await shot("22-remplace", true);
await card.getByRole("button", { name: `Revenir à « ${planned} »` }).click();
await settle();
ok(((await page.locator("details.exercise:not(.exercise--warmup)").first().locator(".exercise__name strong").textContent()) ?? "").includes(planned), "retour à l'exercice prévu");
// ---- données : export, texte pour l'IA, import ----------------------------------
await go("#/donnees");
const dl = page.waitForEvent("download");
await button("Exporter une sauvegarde").click();
const snapshot = fs.readFileSync(await (await dl).path(), "utf8");
ok(JSON.parse(snapshot).format === "ia-fit-snapshot", "sauvegarde exportée");
await button("Copier le texte pour mon IA").click();
const brief = await page.evaluate(() => navigator.clipboard.readText());
ok(brief.startsWith("# IA-Fit : fais évoluer mon programme"), "texte pour l'IA copié");
// Un long texte : posé d'un coup plutôt que tapé.
await page.locator("#imp-text").evaluate((el, text) => { el.value = text; }, snapshot);
await button("Lire le texte").click();
ok(await page.getByText("Sauvegarde IA-Fit", { exact: true }).isVisible(), "import : instantané reconnu");
await shot("15-donnees", true);
await button("Fusionner avec mes données").click();
ok(await page.getByText("Rien de nouveau").isVisible(), "fusion : rien de nouveau");
// ---- proposition par lien : aperçu, refus, lien rouvert ---------------------------
const link = await page.evaluate(async () => {
const { store } = await import("./main.js");
const program = structuredClone(store.getState().program);
program.sessions[0].exercises[0].sets = 5;
program.sessions[0].exercises[0].reps = "5";
program.sessions[1].exercises.pop();
program.sessions[2].exercises.push({ ref: "plank", sets: 2, reps: "45 s", rest: 60 });
return "#import-json=" + encodeURIComponent(JSON.stringify({ program, reason: "Plus lourd sur le squat, moins de volume en B." }));
});
await go(link);
ok(await page.getByText("Par rapport à ton programme").isVisible(), "lien : aperçu des changements");
ok(await page.locator(".diff__lines li[data-change=removed]").count() === 1, "aperçu : un exercice retiré");
ok(await page.locator(".diff__lines li[data-change=added]").count() === 1, "aperçu : un exercice ajouté");
await shot("16-proposition-lien", true);
await button("Refuser").click();
await settle();
await go(link);
ok(await page.getByText("Déjà refusée").isVisible(), "lien rouvert : déjà refusée");
await shot("17-deja-refusee");
await button("La réexaminer").click();
await settle();
await button("Adopter").click();
await settle();
ok(await page.evaluate(async () => (await import("./main.js")).store.getState().program.sessions[0].exercises[0].sets) === 5, "proposition réexaminée puis adoptée");
// ---- historique : correction et retrait ------------------------------------------
await go("#/historique");
await page.locator(".history__item").first().click();
await settle();
await shot("18-correction");
await button("Enregistrer les modifications").click();
await settle();
ok(await page.locator(".history__item").count() >= 1, "historique listé");
// ---- semaine : Retirer, Non fait, Annuler ----------------------------------------
await go("#/semaine");
const monday = page.locator(".week__row").first();
ok(await monday.getByText("✓ Fait").isVisible(), "lundi fait (décalé)");
// Deux séances A ce mercredi : chacune remplit le créneau de lundi tour à tour.
for (let i = 0; i < 3 && await monday.getByRole("button", { name: "Retirer" }).count(); i++) {
await monday.getByRole("button", { name: "Retirer" }).click();
await inDialog("Retirer").click();
await settle();
}
await monday.getByRole("button", { name: "Non fait" }).click();
await settle();
ok(await monday.getByText("✕ Non fait").isVisible(), "lundi marqué non fait");
await monday.getByRole("button", { name: "Annuler" }).click();
await settle();
ok(await monday.getByRole("button", { name: "Faite" }).isVisible(), "lundi : de nouveau à faire");
// ---- WOD (lot 4b) : séance à format, chrono, score ------------------------------
const wodLink = await page.evaluate(async () => {
const { store } = await import("./main.js");
const program = structuredClone(store.getState().program);
program.sessions.push({ key: "J1", oneOff: true, name: "Mini Fran", format: { type: "fortime", capMinutes: 2 }, warmup: [],
exercises: [{ ref: "barbell-thruster", sets: 1, reps: "21-15-9", rest: 0, note: "RX 43 kg / 29 kg" }, { ref: "kipping-pull-up", sets: 1, reps: "21-15-9", rest: 0 }] });
return "#import-json=" + encodeURIComponent(JSON.stringify({ program, reason: "Un WOD pour essayer." }));
});
await go(wodLink);
await button("Adopter").click();
await settle();
await go("#/");
ok(await page.getByRole("heading", { name: /WOD proposé/ }).isVisible(), "WOD ponctuel : proposé sur l'accueil");
await page.getByRole("link", { name: /Mini Fran/ }).click();
await settle();
ok(page.url().endsWith("#/seance/J1") && await page.locator(".wod-format__label").textContent() === "For Time · cap 2 min", "WOD : format affiché");
ok(await page.locator(".wod-move").count() === 2, "WOD : deux mouvements");
await button("Terminer la séance").click();
ok(/temps/.test(await page.locator(".status").textContent() ?? ""), "WOD : score exigé avant d'enregistrer");
await button("Démarrer").click();
ok(await page.locator(".wod-clock__phase").textContent() === "Prêt ?", "WOD : compte à rebours");
await page.clock.fastForward(5000 + 42000);
await page.waitForTimeout(300);
ok(await page.locator(".wod-clock__phase").textContent() === "Chrono · cap 2 min" && /^0:4\d$/.test(await page.locator(".wod-clock__time").textContent() ?? ""), "WOD : chrono lancé, il monte");
await shot("23-wod", true);
await button("Fini !").click();
const wodTime = await page.locator("#wod-time").inputValue();
ok(/^0:4\d$/.test(wodTime), "WOD : temps relevé au « Fini » : " + wodTime);
await button("Scaled").click();
await button("Terminer la séance").click();
await settle();
ok(page.url().endsWith("#/bravo"), "WOD : séance enregistrée");
await go("#/historique");
ok(await page.getByText(`WOD · ${wodTime} · Scaled`).first().isVisible(), "WOD : score dans l'historique");
await go("#/");
ok(await page.getByRole("heading", { name: /WOD proposé/ }).count() === 0, "WOD ponctuel fait : plus proposé");
await go("#/analyses");
ok(await page.getByText(`Record ${wodTime} · Scaled`).isVisible(), "analyses : record du WOD");
// ---- WOD de référence (lot 4d) : catalogue, fiche, « Faire aujourd'hui » ----------
await go("#/");
await page.getByRole("link", { name: /^WOD/ }).click();
await settle();
ok(await page.locator("h1").textContent() === "Références" && await page.getByRole("link", { name: /Fran · For Time/ }).isVisible(), "catalogue des WOD de référence");
await page.getByRole("link", { name: /Cindy · AMRAP 20 min/ }).click();
await settle();
ok(page.url().endsWith("#/wod/cindy") && await page.getByText("Scaled : ").isVisible(), "fiche de Cindy, avec sa variante scaled");
await shot("24-wod-reference", true);
await button("Faire aujourd'hui").click();
await settle();
ok(/#\/seance\/J\d+$/.test(page.url()) && await page.locator(".wod-format__label").textContent() === "AMRAP 20 min", "Faire aujourd'hui : la séance WOD s'ouvre");
await go("#/wod/cindy");
ok(await button("Reprendre ce WOD").isVisible(), "pas de doublon : le WOD en attente est repris");
await page.evaluate(() => localStorage.removeItem("ia-fit.draft"));
// ---- réinitialisation --------------------------------------------------------------
await go("#/donnees");
await button("Tout effacer").click();
await inDialog("Continuer").click();
await inDialog("Tout effacer").click();
await settle();
ok(await button("Créer mon programme").isVisible(), "réinitialisation : retour à l'onboarding");
ok(errors.length === 0, "aucune erreur dans la console" + (errors.length ? " : " + errors.join(" | ") : ""));
await ctx.close();
}
if (serverBase) {
await syncJourney(browser, serverBase);
await updateJourney(browser, serverBase);
}
else check("synchro", false, "adresse du serveur absente : parcours de la synchro non joué (make test-browser la fournit)");
await browser.close();
server.close();
console.log(failures ? `\n${failures} échec(s).` : "\nParcours : OK");
process.exit(failures ? 1 : 0);
})().catch(async (e) => {
console.error(e);
if (lastPage) await lastPage.screenshot({ path: `${outDir}/erreur.png`, fullPage: true }).catch(() => {});
process.exit(1);
});
// ---- synchro : relais, QR code, appariement, IA branchée (serveur réel) -------------
// Trois navigateurs sans rien en commun (contextes séparés) : A active la
// synchro, B s'apparie par le lien du QR code, C (non relié) passe par la page
// d'autorisation. Le serveur est celui de production (server/main.js), avec un
// dossier de données temporaire.
/** Lit le QR code d'une capture PNG (jsQR, pngjs : outils du parcours seulement). */
function decodeQr(png) {
const { PNG } = require("/tools/node_modules/pngjs");
const jsqr = require("/tools/node_modules/jsqr");
const jsQR = jsqr.default ?? jsqr;
const img = PNG.sync.read(png);
const found = jsQR(new Uint8ClampedArray(img.data.buffer, img.data.byteOffset, img.data.length), img.width, img.height);
return found ? found.data : null;
}
/**
* Attend qu'une condition devienne vraie (au plus `ms`) : l'état d'un écran
* peut suivre une requête réseau ou un délai de synchro.
*/
async function until(fn, ms = 8000, step = 200) {
const end = Date.now() + ms;
for (;;) {
try {
if (await fn()) return true;
} catch {
// élément pas encore là : on réessaie
}
if (Date.now() > end) return false;
await new Promise((r) => setTimeout(r, step));
}
}
async function syncJourney(browser, base) {
const scheme = "synchro";
const ok = (cond, msg) => check(scheme, cond, msg);
const crypto = require("node:crypto");
const errors = [];
/** Requêtes refusées exprès (clé inconnue, journal absent) : le navigateur les note en console. */
const expected = /\/oauth\/authorize|\/api\/journals\//;
const open = async (name) => {
const ctx = await browser.newContext({
viewport: { width: 412, height: 915 }, colorScheme: "dark", deviceScaleFactor: 1, locale: "fr-FR",
permissions: ["clipboard-read", "clipboard-write"],
});
const page = await ctx.newPage();
lastPage = page;
page.on("pageerror", (e) => errors.push(`${name} : ${e}`));
page.on("console", (m) => {
if (m.type() === "error" && !(m.text().startsWith("Failed to load resource") && expected.test(m.location().url ?? "")))
errors.push(`${name} : ${m.text()}`);
});
return { ctx, page };
};
const goto = async (page, hash) => { await page.goto(base + hash); await page.waitForSelector("h1"); await page.waitForTimeout(250); };
const inPage = (page, fn) => page.evaluate(fn);
// ---- A : un programme, puis la synchro activée -----------------------------------
const A = await open("A");
const a = A.page;
await goto(a, "#/");
ok(await a.locator(".sync-flag").isHidden(), "sans clé : pas d'indicateur de synchro");
await a.getByRole("button", { name: "Programme d'exemple" }).click();
await a.getByRole("button", { name: "Adopter" }).click();
await a.waitForSelector(".hud");
await a.getByRole("link", { name: /^Synchro/ }).click();
await a.waitForSelector("text=Comment ça marche");
ok(await a.getByText("Le serveur ne garde que des blocs chiffrés").isVisible(), "synchro : explication avant activation");
await a.screenshot({ path: `${outDir}/${scheme}-20-sans-cle.png`, fullPage: true });
await a.getByRole("button", { name: "Activer la synchro" }).click();
ok(await until(() => a.locator(".sync-state").getAttribute("data-state").then((s) => s === "ok")), "synchro activée : premier dépôt fait");
ok(await a.locator(".sync-flag", { hasText: "Synchro à jour" }).isVisible(), "indicateur de l'en-tête : à jour");
ok(await a.locator(".sync-key").innerText().then((t) => t.startsWith("••••")), "clé masquée par défaut");
await a.getByRole("button", { name: "Afficher" }).click();
const key = (await a.locator(".sync-key").innerText()).trim();
ok(/^[0-9A-Z]{4}(-[0-9A-Z]{4}){5}-[0-9A-Z]{2}$/.test(key), "clé affichée en groupes");
// ---- le QR code se lit, et porte le lien d'appariement ----------------------------
// Le message bref (« Synchro activée. ») recouvrirait le code sur la capture :
// on attend qu'il soit parti.
await a.waitForSelector("svg.qr");
await a.locator(".toast--on").waitFor({ state: "detached", timeout: 6000 });
const decoded = decodeQr(await a.locator("svg.qr").screenshot({ path: `${outDir}/${scheme}-qr.png` }));
ok(decoded === `${base}#pair=${key}`, `QR code décodé : ${decoded === null ? "illisible" : decoded.replace(key, "<clé>")}`);
await a.getByRole("button", { name: "Copier la clé" }).click();
ok(await a.evaluate(() => navigator.clipboard.readText()) === key, "clé copiée");
ok(await a.locator(".copy-line__text", { hasText: "/mcp" }).innerText() === base + "mcp", "adresse du connecteur MCP affichée");
await a.getByRole("button", { name: "Masquer" }).click();
await a.locator(".toast--on").waitFor({ state: "detached", timeout: 5000 }).catch(() => {});
await a.screenshot({ path: `${outDir}/${scheme}-21-avec-cle.png`, fullPage: true });
// ---- B : appariement par le lien du QR code ---------------------------------------
const B = await open("B");
const b = B.page;
await goto(b, "#pair=" + key);
ok(await b.getByRole("heading", { name: "Relier cet appareil ?" }).isVisible(), "lien d'appariement : confirmation demandée");
ok(!b.url().includes("pair=") && b.url().endsWith("#/relier"), "la clé a quitté l'adresse");
await b.screenshot({ path: `${outDir}/${scheme}-22-relier.png` });
await b.locator(".action-bar").getByRole("button", { name: "Relier" }).click();
await b.waitForSelector(".hud");
ok(b.url().endsWith("#/") && !b.url().includes("pair="), "après l'appariement : l'accueil, sans la clé dans l'adresse");
ok(await inPage(b, async () => (await import("./main.js")).store.getState().program?.name ?? null) !== null, "B a reçu le programme de A");
// ---- un événement créé sur B apparaît sur A -----------------------------------------
await goto(b, "#/poids");
const before = await inPage(b, async () => (await import("./main.js")).sync.getStatus().lastAt);
await b.getByLabel("Poids (kg)").fill("80,5");
await b.getByRole("button", { name: "Enregistrer", exact: true }).click();
const synced = await until(() => b.evaluate(async (prev) => {
const s = (await import("./main.js")).sync.getStatus();
return s.lastAt !== prev && !s.running && !s.error;
}, before), 10000);
ok(synced, "B : synchro d'elle-même, quelques secondes après la saisie" + (synced ? "" : " : " + JSON.stringify(await inPage(b, async () => (await import("./main.js")).sync.getStatus())) + " avant " + before));
const weightOnA = () => inPage(a, async () => (await import("./main.js")).store.getState().weights.some((w) => w.kg === 80.5));
ok(await until(async () => {
// Retour sur l'onglet : déclencheur de la synchro (visibilitychange).
await a.evaluate(() => document.dispatchEvent(new Event("visibilitychange")));
await a.waitForTimeout(300);
return weightOnA();
}, 12000, 500), "la pesée saisie sur B apparaît sur A");
// ---- page d'autorisation d'une IA (A, relié) ----------------------------------------
const redirectUri = "https://ia.example/callback";
const reg = await (await fetch(base + "oauth/register", {
method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ client_name: "IA d'essai", redirect_uris: [redirectUri] }),
})).json();
const verifier = crypto.randomBytes(32).toString("base64url");
const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
const authorizeUrl = (state) => base + "oauth/authorize?" + new URLSearchParams({
response_type: "code", client_id: reg.client_id, redirect_uri: redirectUri, state, code_challenge: challenge, code_challenge_method: "S256",
});
// L'adresse de retour de l'IA n'existe pas : le navigateur s'y arrête.
await A.ctx.route("https://ia.example/**", (route) => route.fulfill({ status: 200, contentType: "text/plain", body: "IA" }));
await a.goto(authorizeUrl("etat-1"));
await a.waitForSelector("h1");
ok(a.url().includes("#/connecter-ia?"), "GET /oauth/authorize mène à la page de l'app");
ok(await a.getByRole("heading", { name: "IA d'essai" }).isVisible() && await a.getByText("veut lire ton programme et proposer des changements").isVisible(), "connecter-ia : nom de l'IA et ce qu'elle veut");
ok(await a.getByText("Retour vers ia.example").isVisible(), "connecter-ia : hôte de l'adresse de retour");
ok(await a.getByText(/Clé de cet appareil/).isVisible(), "connecter-ia : la clé de l'appareil est reprise");
await a.screenshot({ path: `${outDir}/${scheme}-23-connecter-ia.png`, fullPage: true });
await Promise.all([a.waitForURL(/^https:\/\/ia\.example\/callback/), a.locator(".action-bar").getByRole("button", { name: "Autoriser" }).click()]);
const back = new URL(a.url());
ok(back.searchParams.get("state") === "etat-1" && !!back.searchParams.get("code"), "Autoriser : retour vers l'IA avec un code et l'état");
const tokens = await (await fetch(base + "oauth/token", {
method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "authorization_code", code: back.searchParams.get("code") ?? "", code_verifier: verifier, client_id: reg.client_id, redirect_uri: redirectUri }),
})).json();
ok(typeof tokens.access_token === "string", "le code s'échange contre un jeton");
// ---- l'IA propose, A le voit à la synchro suivante ---------------------------------
await goto(a, "#/");
const profile = await inPage(a, async () => (await import("./main.js")).store.getState().profile);
const rpc = await (await fetch(base + "mcp", {
method: "POST", headers: { authorization: "Bearer " + tokens.access_token, "content-type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "propose_profile", arguments: { profile: { ...profile, goal: "Courir un 10 km" }, reason: "Essai du parcours." } } }),
})).json();
ok(!rpc.error && !rpc.result?.isError, "MCP : proposition enregistrée par l'IA" + (rpc.error ? " : " + JSON.stringify(rpc.error) : ""));
// Retour du réseau : déclencheur de la synchro (online).
await a.evaluate(() => window.dispatchEvent(new Event("online")));
ok(await until(() => a.getByText("Un programme t'attend").isVisible()), "la proposition de l'IA s'affiche à l'accueil");
ok(await a.locator(".toast--on", { hasText: "Nouvelle proposition" }).count() === 1, "message : nouvelle proposition");
await a.screenshot({ path: `${outDir}/${scheme}-24-proposition-ia.png` });
// ---- C, non relié : clé invalide, journal inconnu, refus ---------------------------
const C = await open("C");
const c = C.page;
await C.ctx.route("https://ia.example/**", (route) => route.fulfill({ status: 200, contentType: "text/plain", body: "IA" }));
await c.goto(authorizeUrl("etat-2"));
await c.waitForSelector("h1");
ok(await c.getByText("Cet appareil n'est pas relié").isVisible(), "connecter-ia sans clé : coller une clé ou activer la synchro");
await c.getByLabel("Ma clé de synchro").fill("pas une clé");
await c.locator(".action-bar").getByRole("button", { name: "Autoriser" }).click();
ok(await c.getByText("Clé de synchro invalide").isVisible(), "clé mal formée : refusée sur place");
await c.getByLabel("Ma clé de synchro").fill("0000-0000-0000-0000-0000-0000-00");
await c.locator(".action-bar").getByRole("button", { name: "Autoriser" }).click();
ok(await until(() => c.getByText("active d'abord la synchro et synchronise une fois").isVisible()), "journal inconnu : message traduit");
await Promise.all([c.waitForURL(/^https:\/\/ia\.example\/callback/), c.getByRole("button", { name: "Refuser" }).click()]);
const refused = new URL(c.url());
ok(refused.searchParams.get("error") === "access_denied" && refused.searchParams.get("state") === "etat-2", "Refuser : error=access_denied et l'état");
// ---- B : désactiver, puis « J'ai déjà une clé » (faute de frappe, puis la bonne) ----
await goto(b, "#/synchro");
await b.getByRole("button", { name: "Désactiver sur cet appareil" }).click();
await b.locator("dialog[open]").getByRole("button", { name: "Désactiver" }).click();
ok(await until(() => b.getByRole("button", { name: "Activer la synchro" }).isVisible()), "désactivée sur B");
ok(await b.locator(".sync-flag").isHidden(), "plus d'indicateur sur B");
ok(await inPage(b, async () => (await import("./main.js")).store.getEvents().length) > 0, "les données de B restent");
await b.getByLabel("Ma clé de synchro").fill("ZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZ-Z0");
await b.getByRole("button", { name: "Relier avec cette clé" }).click();
ok(await until(() => b.locator("dialog[open]", { hasText: "Aucun journal ne correspond" }).isVisible()), "clé sans journal : faute de frappe probable");
await b.locator("dialog[open]").getByRole("button", { name: "Corriger la clé" }).click();
await b.getByLabel("Ma clé de synchro").fill(key.toLowerCase());
await b.getByRole("button", { name: "Relier avec cette clé" }).click();
ok(await until(() => b.locator(".sync-state").getAttribute("data-state").then((s) => s === "ok")), "B relié de nouveau avec la clé recopiée");
ok(await until(() => inPage(b, async () => (await import("./main.js")).store.getState().proposals.length === 1)), "B reçoit la proposition de l'IA");
await b.screenshot({ path: `${outDir}/${scheme}-25-b-relie.png`, fullPage: true });
ok(errors.length === 0, "aucune erreur dans la console" + (errors.length ? " : " + errors.join(" | ") : ""));
for (const x of [A, B, C]) await x.ctx.close();
}
// ---- nouvelle version : bandeau « Mettre à jour », séance en cours gardée -----------
// Le serveur sert une copie du site assemblé (/site, service worker actif). On y
// publie une « deuxième version » en changeant la version de sw.js, comme le
// ferait make site après un commit.
async function updateJourney(browser, base) {
const scheme = "mise-a-jour";
const ok = (cond, msg) => check(scheme, cond, msg);
const errors = [];
const ctx = await browser.newContext({ viewport: { width: 412, height: 915 }, colorScheme: "dark", deviceScaleFactor: 1, locale: "fr-FR" });
const page = await ctx.newPage();
lastPage = page;
page.on("pageerror", (e) => errors.push(String(e)));
page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });
await page.goto(base + "#/");
await page.waitForSelector("h1");
const controlled = await until(() => page.evaluate(() => !!navigator.serviceWorker.controller), 10000);
if (!controlled) {
// Première visite : le service worker installé ne tient la page qu'au chargement suivant.
await page.reload();
await page.waitForSelector("h1");
}
const v1 = await page.evaluate(async () => (await caches.keys()).join(","));
ok(await until(() => page.evaluate(() => !!navigator.serviceWorker.controller), 10000), `version 1 en place, servie par le service worker (${v1})`);
ok(await page.locator(".update").count() === 0, "pas de bandeau sans nouvelle version");
// Une séance commencée : une série validée, dans le brouillon.
await page.getByRole("button", { name: "Programme d'exemple" }).click();
await page.getByRole("button", { name: "Adopter" }).click();
await page.waitForSelector(".hud");
await page.goto(base + "#/seance/A");
await page.waitForSelector(".screen--session");
await page.locator("summary", { hasText: "Squat barre" }).click();
const squat = page.locator("details[open]", { hasText: "Squat barre" }).last();
await squat.getByRole("button", { name: /^Série 1 : à faire/ }).click();
await squat.locator(".effort[data-effort=ok]").click();
await page.locator(".timer").getByRole("button", { name: "Terminer" }).click();
ok(await squat.locator(".set-btn--done").count() === 1, "séance : une série validée");
// Deuxième version publiée.
const swFile = "/site/sw.js";
const sw = fs.readFileSync(swFile, "utf8");
const v2 = sw.replace(/^const VERSION = "([^"]+)";/m, 'const VERSION = "$1-v2";');
ok(v2 !== sw, "sw.js : version réécrite");
fs.writeFileSync(swFile, v2);
await page.evaluate(async () => { await (await navigator.serviceWorker.getRegistration())?.update(); });
ok(await until(() => page.locator(".update").isVisible(), 15000), "bandeau : nouvelle version disponible");
ok(await page.locator(".update").getByText("Nouvelle version disponible").isVisible(), "texte du bandeau");
await page.evaluate(() => window.scrollTo(0, 0));
await page.screenshot({ path: `${outDir}/${scheme}-30-bandeau.png` });
// En pleine séance : confirmation d'abord ; « Plus tard » ne change rien.
await page.getByRole("button", { name: "Mettre à jour" }).click();
ok(await page.locator("dialog[open]", { hasText: "Mettre à jour maintenant ?" }).isVisible(), "en séance : confirmation demandée");
await page.locator("dialog[open]").getByRole("button", { name: "Plus tard" }).click();
ok(await page.locator(".update").isVisible(), "« Plus tard » : le bandeau reste");
const reloaded = page.waitForEvent("load");
await page.getByRole("button", { name: "Mettre à jour" }).click();
await page.locator("dialog[open]").getByRole("button", { name: "Mettre à jour" }).click();
await reloaded;
await page.waitForSelector(".screen--session");
ok(await until(() => page.evaluate(async () => (await caches.keys()).some((k) => k.endsWith("-v2")))), "version 2 active (son cache)");
ok(await page.evaluate(async () => !(await navigator.serviceWorker.getRegistration())?.waiting), "plus de version en attente");
ok(await page.locator(".update").count() === 0, "après la mise à jour : plus de bandeau");
const done = await page.locator("details", { hasText: "Squat barre" }).last().locator(".set-btn--done").count();
const draft = await page.evaluate(() => localStorage.getItem("ia-fit.draft") !== null);
ok(done === 1, `la séance reprend : la série validée est toujours là (${done} série, brouillon ${draft ? "présent" : "absent"})`);
ok(errors.length === 0, "aucune erreur dans la console" + (errors.length ? " : " + errors.join(" | ") : ""));
await ctx.close();
}