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>
This commit is contained in:
Pierre MARTIN
2026-11-18 06:19:15 +01:00
co-authored by Claude Opus 5.5
parent c12e37e215
commit 08cc995eef
22 changed files with 3814 additions and 25 deletions
+208 -1
View File
@@ -16,10 +16,12 @@ 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", ".css": "text/css; charset=utf-8",
".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",
};
@@ -336,6 +338,8 @@ function check(scheme, cond, msg) {
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");
@@ -345,3 +349,206 @@ function check(scheme, cond, msg) {
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();
}