Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Command Center (MCC)8 * File : apps/web/e2e/specs/07-operations.spec.ts9 * Module : web10 * Repository : https://git.spboucher.ai/maclustr-command-center11 * Project Website : https://clustr.spboucher.ai12 * Created : 2026-11-1813 * Last Modified : 2026-11-1814 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { expect, test, type BrowserContext, type Page } from "@playwright/test";43import { NODE, seedCluster, touchNodes } from "../lib/fixtures";44import { endpointLive, signedIn, sql, type Problems } from "../lib/harness";4546// Operations plane against live endpoints: maintenance calendar and notes, alerts, actions, audit. Each test skips47// itself while its endpoint still answers 501 (the explicit not-available state is then asserted by 05-screens).48test.describe.serial("operations against live endpoints", () => {49 let context: BrowserContext;50 let page: Page;51 let problems: Problems;52 let windowId = "";5354 test.beforeAll(async ({ browser }) => {55 ({ context, page, problems } = await signedIn(browser, "e2e-owner"));56 seedCluster();57 });58 test.beforeEach(() => {59 touchNodes();60 });61 test.afterAll(async () => {62 await context.close();63 });6465 const need = async (path: string) => {66 test.skip(!(await endpointLive(page, path)), `GET ${path} is not live yet (501/503)`);67 };68 /** Local date-time for <input type="datetime-local">, `days` from today at `hour`:00. */69 const local = (days: number, hour: number) => {70 const d = new Date();71 d.setDate(d.getDate() + days);72 const p = (n: number) => String(n).padStart(2, "0");73 return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(hour)}:00`;74 };75 const pickNode = async (alias: string) => {76 const nodes = page.getByRole("dialog").getByRole("combobox", { name: "Nœuds concernés" });77 await nodes.fill(alias);78 await page.getByRole("dialog").getByRole("option", { name: new RegExp(alias) }).click();79 };8081 test("maintenance: create a window from the calendar; time zone is explicit", async () => {82 await need("/maintenance/windows");83 await page.goto("/maintenance");84 await expect(page.getByTestId("screen-maintenance")).toBeVisible();85 await expect(page.getByTestId("mt-zone-label")).toContainText("America/Toronto");86 await page.getByTestId("mt-view-agenda").click();87 await page.getByTestId("mt-new-window").click();88 await page.getByTestId("mt-field-title").fill("E2E — remplacement SSD");89 await page.getByTestId("mt-field-start").fill(local(1, 10));90 await page.getByTestId("mt-field-end").fill(local(1, 12));91 await expect(page.getByTestId("mt-form-resolved")).toContainText("UTC");92 await pickNode(NODE.fresh.alias);93 await page.getByTestId("mt-window-save").click();94 const chip = page.locator('[data-testid^="mt-occurrence-"]').filter({ hasText: "E2E — remplacement SSD" }).first();95 await expect(chip).toBeVisible();96 windowId = ((await chip.getAttribute("data-testid")) ?? "").replace("mt-occurrence-", "");97 expect(windowId).toMatch(/^[0-9a-f-]{36}$/);98 expect(sql(`select timezone from maintenance_windows where id = '${windowId}'`)).toBe("America/Toronto");99 // stored instant = the local time typed, converted to UTC by the form100 const stored = sql(`select to_char(starts_at at time zone 'America/Toronto', 'YYYY-MM-DD"T"HH24:MI') from maintenance_windows where id = '${windowId}'`);101 expect(stored).toBe(local(1, 10));102 });103104 test("maintenance: validation and the overlap warning reported by the server", async () => {105 await need("/maintenance/windows");106 await page.goto("/maintenance");107 await page.getByTestId("mt-new-window").click();108 await page.getByTestId("mt-field-title").fill("E2E — chevauchement");109 await page.getByTestId("mt-field-start").fill(local(1, 11));110 await page.getByTestId("mt-field-end").fill(local(1, 10)); // end before start111 await page.getByTestId("mt-window-save").click();112 await expect(page.getByTestId("mt-window-form").getByRole("alert").first()).toBeVisible();113 await page.getByTestId("mt-field-end").fill(local(1, 13));114 await pickNode(NODE.fresh.alias);115 await page.getByTestId("mt-window-save").click();116 // same node, intersecting period: the API answers with a non-blocking warning, shown as is117 await expect(page.getByTestId("mt-server-warnings")).toBeVisible();118 await expect(page.getByTestId("mt-server-warnings").locator("li")).not.toHaveCount(0);119 await page.getByTestId("mt-warnings-ack").click();120 expect(Number(sql(`select count(*) from maintenance_windows where title like 'E2E — %'`))).toBe(2);121 });122123 test("maintenance: month and week views are keyboard navigable", async () => {124 await need("/maintenance/windows");125 await page.goto("/maintenance");126 await page.getByTestId("mt-view-month").click();127 const grid = page.getByTestId("mt-month-grid");128 await expect(grid).toBeVisible();129 const current = grid.locator('[tabindex="0"]').first();130 await current.focus();131 const before = await page.evaluate(() => document.activeElement?.getAttribute("data-day"));132 await page.keyboard.press("ArrowRight");133 const after = await page.evaluate(() => document.activeElement?.getAttribute("data-day"));134 expect(after).not.toBe(before);135 expect(after).toMatch(/^\d{4}-\d{2}-\d{2}$/);136 await page.keyboard.press("ArrowDown");137 expect(await page.evaluate(() => document.activeElement?.getAttribute("data-day"))).not.toBe(after);138 await page.getByTestId("mt-view-week").click();139 await expect(page.getByTestId("mt-week")).toBeVisible();140 await page.getByTestId("mt-next").click();141 await page.getByTestId("mt-today").click();142 await page.reload();143 await expect(page.getByTestId("mt-week")).toBeVisible(); // the view is a remembered preference144 await page.getByTestId("mt-view-agenda").click();145 });146147 test("maintenance window: notes — add (keyboard), auto-link, edit, pin, search, delete", async () => {148 await need("/maintenance/notes");149 test.skip(windowId === "", "no window was created");150 await page.goto(`/maintenance/${windowId}`);151 await expect(page.getByTestId("screen-maintenance-window")).toBeVisible();152 await expect(page.getByTestId("mt-window-status")).toHaveAttribute("data-status", "scheduled");153 await expect(page.getByTestId("mt-window-nodes")).toContainText(NODE.fresh.alias);154 const panel = page.getByTestId("notes-panel").first();155 // quick-add shortcut: "n" focuses the note field156 await page.locator("h1").click();157 await page.keyboard.press("n");158 await expect(panel.getByTestId("note-input")).toBeFocused();159 await page.keyboard.type("Pièce commandée.\nSuivi : https://example.org/suivi?id=42 <b>pas de HTML</b>");160 await page.keyboard.press("ControlOrMeta+Enter");161 const note = panel.getByTestId("note-item").filter({ hasText: "Pièce commandée." });162 await expect(note).toHaveCount(1);163 await expect(note).toContainText("E2E Owner");164 await expect(note.getByRole("link", { name: "https://example.org/suivi?id=42" })).toHaveAttribute("rel", /noopener/);165 await expect(note).toContainText("<b>pas de HTML</b>"); // shown as text166 await expect(note.locator("b")).toHaveCount(0);167 expect(sql(`select count(*) from maintenance_notes where window_id = '${windowId}' and deleted_at is null`)).toBe("1");168169 await panel.getByTestId("note-input").fill("Deuxième note, intervention confirmée.");170 await panel.getByTestId("note-save").click();171 await expect(panel.getByTestId("note-item")).toHaveCount(2);172173 // edit → edited marker174 await note.getByTestId("note-edit").click();175 await panel.getByTestId("note-edit-input").fill("Pièce reçue le jour même.");176 await panel.getByTestId("note-edit-save").click();177 const edited = panel.getByTestId("note-item").filter({ hasText: "Pièce reçue le jour même." });178 await expect(edited.getByTestId("note-edited")).toBeVisible();179180 // pin → first in the list181 await edited.getByTestId("note-pin").click();182 await expect(panel.getByTestId("note-item").first()).toContainText("Pièce reçue le jour même.");183 await expect(panel.getByTestId("note-item").first()).toHaveAttribute("data-pinned", "true");184185 // search186 await panel.getByTestId("note-search").fill("confirmée");187 await expect(panel.getByTestId("note-item")).toHaveCount(1);188 await panel.getByTestId("note-search").fill("");189 await expect(panel.getByTestId("note-item")).toHaveCount(2);190191 // delete with confirmation192 await panel.getByTestId("note-item").filter({ hasText: "Deuxième note" }).getByTestId("note-delete").click();193 await page.getByRole("dialog").getByRole("button", { name: "Supprimer" }).click();194 await expect(panel.getByTestId("note-item")).toHaveCount(1);195 });196197 test("node detail embeds the notes of the node", async () => {198 await need("/maintenance/notes");199 await need(`/nodes/${NODE.fresh.id}`);200 await page.goto(`/nodes/${NODE.fresh.id}?tab=maintenance`);201 const panel = page.getByTestId("node-notes").getByTestId("notes-panel");202 await panel.getByTestId("note-input").fill("Note de nœud e2e : ventilateur bruyant.");203 await panel.getByTestId("note-save").click();204 await expect(panel.getByTestId("note-item").filter({ hasText: "ventilateur bruyant" })).toHaveCount(1);205 expect(sql(`select count(*) from maintenance_notes where node_id = '${NODE.fresh.id}' and window_id is null`)).toBe("1");206 });207208 test("maintenance: ICS export and completing a window", async () => {209 await need("/maintenance/windows");210 test.skip(windowId === "", "no window was created");211 await page.goto("/maintenance");212 const href = await page.getByTestId("mt-ics-link").getAttribute("href");213 expect(href).toContain("/api/v1/maintenance/calendar.ics");214 const ics = await page.evaluate(async (u) => { const r = await fetch(u as string); return { status: r.status, type: r.headers.get("content-type"), text: await r.text() }; }, href);215 expect(ics.status).toBe(200);216 expect(ics.type).toContain("text/calendar");217 expect(ics.text).toContain("BEGIN:VCALENDAR");218 expect(ics.text).toContain("E2E — remplacement SSD");219 await page.goto(`/maintenance/${windowId}`);220 await page.getByTestId("mt-window-cancel").click();221 await page.getByRole("dialog").getByRole("button", { name: /annuler la fenêtre|confirmer|annuler cette/i }).last().click();222 await expect(page.getByTestId("mt-window-status")).toHaveAttribute("data-status", "cancelled");223 });224225 test("alerts: create a threshold rule in the editor and validate it on history", async () => {226 await need("/alert-rules");227 await page.goto("/alerts?tab=rules");228 await expect(page.getByTestId("rules-tab")).toBeVisible();229 await page.getByTestId("rule-new").first().click();230 const form = page.getByTestId("rule-form");231 await form.getByRole("textbox", { name: "Nom" }).first().fill("E2E — CPU élevé");232 const metric = form.getByRole("combobox", { name: "Métrique" });233 await metric.fill("cpu.usage");234 await page.getByRole("option", { name: /cpu\.usage|Utilisation CPU/ }).first().click();235 await page.getByTestId("rule-threshold").fill("50");236 await page.getByTestId("rule-for").fill("1 min");237 // "validate on history": the server replays the draft rule on stored samples238 await page.getByTestId("rule-validate").click();239 await expect(page.getByTestId("rule-preview")).toBeVisible();240 await expect(page.getByTestId("rule-preview-firings")).toContainText(/\d/);241 await page.getByTestId("rule-save").click();242 await expect(page.locator('[data-testid^="rule-row-"]').filter({ hasText: "E2E — CPU élevé" })).toBeVisible();243 expect(sql(`select kind || ' ' || metric || ' ' || op || ' ' || threshold || ' ' || for_seconds from alert_rules where name = 'E2E — CPU élevé'`)).toBe("threshold cpu.usage > 50 60");244 await page.goto("/alerts?tab=silences");245 await expect(page.getByTestId("silences-tab")).toBeVisible();246 });247248 test("alerts: a firing alert is listed, acknowledged with a comment, and its timeline shows it", async () => {249 await need("/alerts");250 const rule = sql(`select id from alert_rules where name = 'E2E — CPU élevé'`);251 test.skip(rule === "", "no alert rule exists in this database");252 const id = "0e2e0000-0000-7000-8000-0000000a1e47";253 sql(`insert into alerts(id, rule_id, node_id, label, fingerprint, state, severity, summary, last_value, started_at, fired_at, last_eval_at)254 values ('${id}', '${rule}', '${NODE.fresh.id}', '', 'e2e-fingerprint-1', 'firing', 'critical', 'E2E synthetic alert: disk almost full', 97.5, now() - interval '10 minutes', now() - interval '5 minutes', now())255 on conflict (id) do nothing`);256 await page.goto("/alerts");257 await expect(page.getByTestId("screen-alerts")).toBeVisible();258 const row = page.getByTestId(`alert-row-${id}`);259 await expect(row).toBeVisible();260 await row.click();261 await expect(page.getByTestId("screen-alert-detail")).toBeVisible();262 await expect(page.getByTestId("alert-state")).toHaveAttribute("data-state", "firing");263 await expect(page.locator("main")).toContainText("E2E synthetic alert: disk almost full");264 await page.getByTestId("alert-ack").click();265 await page.getByRole("dialog").getByRole("textbox").first().fill("Pris en charge par e2e.");266 await page.getByTestId("transition-confirm").click();267 await expect(page.getByTestId("alert-state")).toHaveAttribute("data-state", "acknowledged");268 await expect(page.getByTestId("timeline")).toContainText("Pris en charge par e2e.");269 await page.getByTestId("comment-input").fill("Commentaire e2e <i>texte brut</i>");270 await page.getByTestId("comment-submit").click();271 await expect(page.getByTestId("timeline")).toContainText("Commentaire e2e <i>texte brut</i>");272 // the bell in the top bar no longer counts it as firing273 expect(sql(`select state from alerts where id = '${id}'`)).toBe("acknowledged");274 });275276 test("actions: the generic flow from a node — catalogue form, server refusal explained, live view", async () => {277 await need("/action-types");278 await need(`/nodes/${NODE.fresh.id}`);279 await page.goto(`/nodes/${NODE.fresh.id}`);280 await page.locator('[data-action-type="inventory.refresh"]').click();281 const dialog = page.getByRole("dialog");282 await expect(dialog.getByTestId("action-target")).toHaveText(NODE.fresh.alias);283 await expect(dialog).toContainText("inventory.refresh");284 const posts: { key: string | undefined; status: number }[] = [];285 page.on("response", (r) => { if (r.request().method() === "POST" && r.url().endsWith("/api/v1/actions")) posts.push({ key: r.request().headers()["idempotency-key"], status: r.status() }); });286 await dialog.getByTestId("action-submit").click();287 // either the action is accepted (live view) or the server refuses it with an explained pre-check288 await expect(page.getByTestId("action-state").or(page.getByTestId("action-error"))).toBeVisible();289 expect(posts.length).toBeGreaterThan(0);290 expect(posts[0]?.key).toMatch(/^[0-9a-f-]{36}$/);291 if (await page.getByTestId("action-error").isVisible()) {292 // a retry of the same dialog submission reuses the same Idempotency-Key293 await dialog.getByTestId("action-submit").click();294 await expect.poll(() => posts.length).toBeGreaterThan(1);295 expect(posts[1]?.key).toBe(posts[0]?.key);296 await expect(page.getByTestId("action-error")).toHaveAttribute("data-code", /.+/);297 await page.keyboard.press("Escape");298 } else {299 await expect(page).toHaveURL(/\/actions\/[0-9a-f-]{36}$/);300 await expect(page.getByTestId("action-state")).toHaveAttribute("data-state", /queued|dispatched|running|succeeded|failed|timed_out|pending_approval/);301 await expect(page.getByRole("heading", { name: "Sortie", exact: true })).toBeVisible();302 }303 });304305 test("actions: a dangerous action collects justification and typed confirmation before anything is sent", async () => {306 await need("/action-types");307 await need(`/nodes/${NODE.fresh.id}`);308 const critical = await page.evaluate(async () => {309 const r = (await (await fetch("/api/v1/action-types")).json()) as { items: { type: string; available: boolean; requires_confirmation: boolean; requires_justification: boolean; target_kinds: string[] }[] };310 return r.items.find((x) => x.available && x.requires_confirmation && x.requires_justification && x.target_kinds.includes("node"))?.type ?? null;311 });312 test.skip(critical === null, "no available action type requires confirmation + justification");313 await page.goto(`/nodes/${NODE.fresh.id}`);314 await page.getByTestId("node-actions").click();315 await page.getByRole("menuitem", { name: /Redémarrer le nœud|Éteindre le nœud/ }).first().click();316 const dialog = page.getByRole("dialog");317 let sent = 0;318 page.on("request", (r) => { if (r.method() === "POST" && r.url().endsWith("/api/v1/actions")) sent++; });319 await dialog.getByTestId("action-submit").click();320 await expect(dialog.getByText("Ce champ est obligatoire.").first()).toBeVisible();321 expect(sent).toBe(0);322 // a wrong alias is not judged by the UI: it is sent and the SERVER refuses it323 await dialog.getByLabel("Justification").fill("Test e2e : la confirmation est vérifiée par le serveur.");324 await dialog.getByTestId("action-confirm").fill("not-the-alias");325 await dialog.getByTestId("action-submit").click();326 await expect(page.getByTestId("action-error")).toBeVisible();327 expect(sent).toBe(1);328 await page.keyboard.press("Escape");329 });330331 test("audit: UTC timestamps, chain verification, correlation drill-down", async () => {332 await need("/audit");333 await page.goto("/audit");334 await expect(page.getByTestId("screen-audit")).toBeVisible();335 await expect(page.getByTestId("audit-row").first()).toBeVisible();336 await expect(page.getByTestId("audit-row").first()).toContainText(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC/);337 await expect(page.getByRole("columnheader", { name: /UTC/ })).toBeVisible();338 await expect(page.getByTestId("audit-verify-result")).toHaveAttribute("data-ok", "true");339 await page.getByTestId("audit-verify").click();340 await expect(page.getByTestId("audit-verify-result")).toHaveAttribute("data-ok", "true");341 await page.getByTestId("audit-row").first().getByTestId("audit-correlation").click();342 await expect(page).toHaveURL(/correlation_id=[0-9a-f-]{36}/);343 await expect(page.getByTestId("audit-drilldown")).toBeVisible();344 });345346 test("audit: export requires a step-up and downloads a file", async () => {347 await need("/audit");348 await page.goto("/audit");349 sql(`update sessions set authenticated_at = now() - interval '10 minutes' where user_id = (select id from users where handle = 'e2e-owner')`);350 await page.getByTestId("audit-export").click();351 const download = page.waitForEvent("download");352 await page.getByTestId("audit-export-submit").click();353 await expect(page.getByTestId("stepup-verify")).toBeVisible();354 await page.getByTestId("stepup-verify").click();355 const file = await download;356 expect(file.suggestedFilename()).toMatch(/audit.*\.jsonl$/);357 const stream = await file.createReadStream();358 let text = "";359 for await (const chunk of stream) text += String(chunk);360 const lines = text.trim().split("\n");361 expect(lines.length).toBeGreaterThan(1);362 expect(JSON.parse(lines[0] ?? "{}")).toHaveProperty("seq");363 expect(JSON.parse(lines[lines.length - 1] ?? "{}")).toHaveProperty("manifest");364 });365366 test("activity: feed, actions and approvals tabs", async () => {367 await need("/activity");368 await page.goto("/activity");369 await expect(page.getByTestId("screen-activity")).toBeVisible();370 await expect(page.getByTestId("activity-feed")).toBeVisible();371 await page.goto("/activity?tab=actions");372 await expect(page.getByTestId("actions-filter-state")).toBeVisible();373 await page.goto("/activity?tab=approvals");374 await expect(page.getByTestId("screen-activity")).toBeVisible();375 });376377 test("jobs: templates, schedules and the list render", async () => {378 await need("/jobs");379 await page.goto("/jobs");380 await expect(page.getByTestId("screen-jobs")).toBeVisible();381 await page.goto("/jobs?tab=templates");382 await expect(page.getByTestId("screen-jobs")).toBeVisible();383 await page.goto("/jobs?tab=schedules");384 await expect(page.getByTestId("screen-jobs")).toBeVisible();385 });386387 test("no CSP violation and no console error", async () => {388 problems.assertClean();389 });390});391