repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

test(tune): cover live dashboard in browsers

a5adf07849196f8dc9b72c567f494ac041f68c15

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

+187 / −0 text lines

Diff layout

extensions/tune/__e2e__/dashboard.spec.ts

Added
new file mode 100644

+78 / −0 text lines

1import { appendFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2import { tmpdir } from "node:os";
3import { join } from "node:path";
4import { expect, test } from "@playwright/test";
5import { startTuneDashboard, type TuneDashboard } from "../dashboard.ts";
6
7let dashboard: TuneDashboard | undefined;
8let dir = "";
9
10test.afterEach(async () => {
11 dashboard?.close();
12 dashboard = undefined;
13 if (dir) await rm(dir, { recursive: true, force: true });
14 dir = "";
15});
17test("loads runs, switches theme, and receives live updates", async ({
18 page,
19}) => {
20 const pageErrors: string[] = [];
21 page.on("pageerror", (error) => pageErrors.push(error.message));
22 dir = await mkdtemp(join(tmpdir(), "tune-e2e-"));
23 const jsonlPath = join(dir, "session.jsonl");
24 const template = await readFile(
25 join(import.meta.dirname, "..", "assets", "template.html"),
26 "utf8",
27 );
28 const html = template.replace("__TUNE_TITLE__", "Latency");
29 await writeFile(
30 jsonlPath,
31 [
32 JSON.stringify({
33 type: "config",
34 name: "Latency",
35 metricName: "latency",
36 metricUnit: "ms",
37 bestDirection: "lower",
38 }),
39 JSON.stringify({
40 run: 1,
41 metric: 100,
42 status: "keep",
43 description: "baseline",
44 }),
45 ].join("\n") + "\n",
46 );
48 dashboard = await startTuneDashboard(html, jsonlPath);
49 const eventsReady = page.waitForResponse(
50 (response) =>
51 response.url().endsWith("/events") && response.status() === 200,
52 );
53 await page.goto(dashboard.url);
54 await eventsReady;
55 await expect(page.locator("#title")).toHaveText("Latency");
56 await expect(page.locator("#summary")).toContainText("latency (ms)");
57 await expect(page.locator("#runs")).toHaveText("1");
58 await expect(page.locator("#rows")).toContainText("baseline");
60 await page.locator("#theme-mode").selectOption("dark");
61 await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
63 await appendFile(
64 jsonlPath,
65 JSON.stringify({
66 run: 2,
67 metric: 80,
68 status: "keep",
69 description: "faster",
70 }) + "\n",
71 );
72 dashboard.broadcast();
74 await expect(page.locator("#runs")).toHaveText("2");
75 await expect(page.locator("#rows")).toContainText("faster");
76 await expect(page.locator("#baseline-best")).toHaveText("100ms → 80ms");
77 expect(pageErrors).toEqual([]);
78});

extensions/tune/dashboard.ts

Added
new file mode 100644

+98 / −0 text lines

1import { readFile } from "node:fs";
2import { createServer, type Server, type ServerResponse } from "node:http";
3
4export type TuneDashboard = {
5 url: string;
6 update(html: string, jsonlPath: string): void;
7 broadcast(): void;
8 close(): void;
9};
11export async function startTuneDashboard(
12 html: string,
13 jsonlPath: string,
14): Promise<TuneDashboard> {
15 let currentHtml = html;
16 let currentJsonlPath = jsonlPath;
17 let closed = false;
18 const clients = new Set<ServerResponse>();
19 const server = createServer((req, res) => {
20 const url = new URL(req.url ?? "/", "http://127.0.0.1");
21 if (url.pathname === "/events") {
22 res.writeHead(200, {
23 "Content-Type": "text/event-stream",
24 "Cache-Control": "no-cache",
25 Connection: "keep-alive",
26 });
27 res.write("retry: 1000\n\n");
28 clients.add(res);
29 res.on("close", () => clients.delete(res));
30 return;
31 }
32 if (url.pathname === "/") {
33 res.writeHead(200, {
34 "Content-Type": "text/html; charset=utf-8",
35 "Cache-Control": "no-store",
36 });
37 res.end(currentHtml);
38 return;
39 }
40 if (url.pathname === "/session.jsonl") {
41 readFile(currentJsonlPath, (error, data) => {
42 if (error) {
43 res.writeHead(404);
44 res.end();
45 return;
46 }
47 res.writeHead(200, {
48 "Content-Type": "application/x-ndjson; charset=utf-8",
49 "Cache-Control": "no-store",
50 });
51 res.end(data);
52 });
53 return;
54 }
55 res.writeHead(404);
56 res.end();
57 });
58 const port = await listen(server);
59 return {
60 url: `http://127.0.0.1:${port}`,
61 update(nextHtml, nextJsonlPath) {
62 currentHtml = nextHtml;
63 currentJsonlPath = nextJsonlPath;
64 },
65 broadcast() {
66 for (const client of clients) {
67 try {
68 client.write("event: jsonl-updated\n");
69 client.write(`data: ${Date.now()}\n\n`);
70 } catch {
71 clients.delete(client);
72 }
73 }
74 },
75 close() {
76 if (closed) return;
77 closed = true;
78 for (const client of clients) client.end();
79 clients.clear();
80 server.close();
81 },
82 };
83}
85function listen(server: Server): Promise<number> {
86 return new Promise((resolve, reject) => {
87 server.once("error", reject);
88 server.listen(0, "127.0.0.1", () => {
89 server.off("error", reject);
90 const address = server.address();
91 if (!address || typeof address === "string") {
92 reject(new Error("Failed to bind tune dashboard server"));
93 return;
94 }
95 resolve(address.port);
96 });
97 });
98}

extensions/tune/package.json

Modified

+1 / −0 text lines

1616 ],
1717 "devDependencies": {
1818 "@marcfargas/pi-test-harness": "^0.6.1",
19 "@playwright/test": "^1.61.0",
1920 "vitest": "^4.1.9"
2021 },
2122 "scripts": {

extensions/tune/playwright.config.ts

Added
new file mode 100644

+9 / −0 text lines

1import { defineConfig } from "@playwright/test";
2import base from "../../test/playwright.base.ts";
3
4export default defineConfig(base, {
5 testDir: "./__e2e__",
6 testMatch: "*.spec.ts",
7 timeout: 30_000,
8 expect: { timeout: 5_000 },
9});

package-lock.json

Modified

+1 / −0 text lines

494494 "license": "MIT",
495495 "devDependencies": {
496496 "@marcfargas/pi-test-harness": "^0.6.1",
497 "@playwright/test": "^1.61.0",
497498 "vitest": "^4.1.9"
498499 },
499500 "peerDependencies": {