Files
ia-fit/tests/browser/parcours.cjs
T
Pierre MARTINandClaude Opus 5.5 08cc995eef Lot 2, interface : synchro, appariement par QR code, page d'autorisation d'une IA
- Écran Synchro (#/synchro) : activer, « J'ai déjà une clé » (pull d'abord,
  faute de frappe signalée), état, clé masquée, QR code, désactiver, brancher
  son IA (adresse du connecteur et mode d'emploi).
- Appariement #pair=<clé> : la clé quitte l'adresse aussitôt, confirmation,
  fusion des données locales.
- Page #/connecter-ia?… : autoriser (POST /oauth/authorize) ou refuser,
  erreurs traduites ; le routeur accepte « ? » dans le fragment.
- Synchro automatique sans scrutation (ouverture, 3 s après une saisie,
  online, visibilitychange), indicateur dans l'en-tête.
- QR code : qrcode-generator 2.0.4 (MIT) vendorisé, dessiné en SVG par le DOM.
- Magasin : dates strictement croissantes pour les événements de l'appareil
  (cause du flottement de test-browser : deux PlanSettingsChanged de la même
  milliseconde départagés par leur identifiant aléatoire).
- test-browser : parcours de la synchro contre server/main.js (données
  temporaires), QR décodé par jsQR dans la capture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 06:19:15 +01:00

555 lines
33 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");
await button("Cette semaine").click();
// ---- 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.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);
// ---- 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();
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);
// ---- 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");
// ---- 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);
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();
}