Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

ci: publish historical Midscene reports

quanrud3c88219c5af
diff --git a/.github/workflows/deploy-midscene-report.yml b/.github/workflows/deploy-midscene-report.yml
new file mode 100644
index 0000000..e2448ec
--- /dev/null
+++ b/.github/workflows/deploy-midscene-report.yml
@@ -0,0 +1,104 @@
+name: Deploy Midscene report to Pages
+
+on:
+ workflow_call:
+ inputs:
+ artifact-name:
+ description: Actions artifact containing one self-contained HTML report
+ required: true
+ type: string
+ report-label:
+ description: Distribution label shown in report history
+ required: true
+ type: string
+
+jobs:
+ deploy:
+ name: Publish HTML report history
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ concurrency:
+ group: pages-report-deploy
+ cancel-in-progress: false
+ permissions:
+ actions: read
+ contents: read
+ pages: write
+ id-token: write
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Download the successful run's HTML report artifact
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
+ with:
+ name: ${{ inputs.artifact-name }}
+ path: ${{ runner.temp }}/midscene-report
+
+ - name: Configure GitHub Pages
+ id: pages
+ uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
+
+ - name: Restore history and prepare the Pages site
+ env:
+ REPORT_RETENTION: ${{ vars.REPORT_RETENTION || '10' }}
+ PAGES_BASE_URL: ${{ steps.pages.outputs.base_url }}
+ REPORT_LABEL: ${{ inputs.report-label }}
+ run: |
+ node scripts/build-pages-report.mjs \
+ --report-dir "$RUNNER_TEMP/midscene-report" \
+ --site-dir "$RUNNER_TEMP/pages-site" \
+ --run-id "$GITHUB_RUN_ID" \
+ --workflow-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" \
+ --generated-at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
+ --retention "$REPORT_RETENTION" \
+ --pages-url "$PAGES_BASE_URL" \
+ --label "$REPORT_LABEL"
+
+ - name: Upload the restricted Pages payload
+ uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
+ with:
+ path: ${{ runner.temp }}/pages-site
+
+ - name: Deploy report history to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
+
+ - name: Verify the published HTML endpoints
+ env:
+ HISTORY_URL: ${{ steps.pages.outputs.base_url }}/
+ REPORT_URL: ${{ steps.pages.outputs.base_url }}/reports/${{ github.run_id }}/index.html
+ run: |
+ verify_html() {
+ local url="$1"
+ local headers
+ headers=$(mktemp)
+ for attempt in $(seq 1 12); do
+ if curl --fail --silent --show-error --location --head \
+ --connect-timeout 10 --max-time 20 \
+ --dump-header "$headers" --output /dev/null "$url" \
+ && grep -Eiq '^content-type:[[:space:]]*text/html([[:space:]]*;|[[:space:]]*$)' "$headers"; then
+ echo "Verified HTTP 200 text/html: $url"
+ return 0
+ fi
+ echo "Waiting for Pages propagation (${attempt}/12): $url"
+ sleep 5
+ done
+ echo "Pages endpoint did not return HTTP 200 text/html: $url" >&2
+ return 1
+ }
+
+ verify_html "$HISTORY_URL"
+ verify_html "$REPORT_URL"
+
+ - name: Add report links to the run summary
+ env:
+ HISTORY_URL: ${{ steps.pages.outputs.base_url }}/
+ REPORT_URL: ${{ steps.pages.outputs.base_url }}/reports/${{ github.run_id }}/index.html
+ run: |
+ echo "- [Open this run's report]($REPORT_URL)" >> "$GITHUB_STEP_SUMMARY"
+ echo "- [Browse report history]($HISTORY_URL)" >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/midscene-omarchy-4.0.3.yml b/.github/workflows/midscene-omarchy-4.0.3.yml
index 3c0b4c1..bd8a4a9 100644
--- a/.github/workflows/midscene-omarchy-4.0.3.yml
+++ b/.github/workflows/midscene-omarchy-4.0.3.yml
@@ -6,6 +6,9 @@ on:
branches: [main]
paths:
- ".github/workflows/midscene-omarchy-4.0.3.yml"
+ - ".github/workflows/deploy-midscene-report.yml"
+ - "scripts/build-pages-report.mjs"
+ - "tests/test_pages_report_history.mjs"
- "tests/midscene/package.json"
- "tests/midscene/package-lock.json"
- "tests/midscene/gtk_fixture.py"
@@ -23,6 +26,9 @@ on:
branches: [main]
paths:
- ".github/workflows/midscene-omarchy-4.0.3.yml"
+ - ".github/workflows/deploy-midscene-report.yml"
+ - "scripts/build-pages-report.mjs"
+ - "tests/test_pages_report_history.mjs"
- "tests/midscene/package.json"
- "tests/midscene/package-lock.json"
- "tests/midscene/gtk_fixture.py"
@@ -131,3 +137,20 @@ jobs:
path: tests/midscene/midscene_run/
if-no-files-found: warn
retention-days: 7
+
+ pages-report:
+ name: GitHub Pages report
+ needs: omarchy-vm
+ if: >-
+ needs.omarchy-vm.result == 'success' &&
+ github.event_name != 'pull_request' &&
+ github.ref_name == vars.PAGES_REPORT_BRANCH
+ permissions:
+ actions: read
+ contents: read
+ pages: write
+ id-token: write
+ uses: ./.github/workflows/deploy-midscene-report.yml
+ with:
+ artifact-name: omarchy-midscene-e2e-report
+ report-label: Omarchy 4.0.3
diff --git a/.github/workflows/midscene-ubuntu-22.04.yml b/.github/workflows/midscene-ubuntu-22.04.yml
index 3c5b5ef..b0cd019 100644
--- a/.github/workflows/midscene-ubuntu-22.04.yml
+++ b/.github/workflows/midscene-ubuntu-22.04.yml
@@ -6,6 +6,9 @@ on:
branches: [main]
paths:
- ".github/workflows/midscene-ubuntu-22.04.yml"
+ - ".github/workflows/deploy-midscene-report.yml"
+ - "scripts/build-pages-report.mjs"
+ - "tests/test_pages_report_history.mjs"
- "tests/midscene/package.json"
- "tests/midscene/package-lock.json"
- "tests/midscene/gtk_fixture.py"
@@ -15,6 +18,9 @@ on:
branches: [main]
paths:
- ".github/workflows/midscene-ubuntu-22.04.yml"
+ - ".github/workflows/deploy-midscene-report.yml"
+ - "scripts/build-pages-report.mjs"
+ - "tests/test_pages_report_history.mjs"
- "tests/midscene/package.json"
- "tests/midscene/package-lock.json"
- "tests/midscene/gtk_fixture.py"
@@ -140,3 +146,20 @@ jobs:
path: tests/midscene/midscene_run/
if-no-files-found: warn
retention-days: 7
+
+ pages-report:
+ name: GitHub Pages report
+ needs: ubuntu-gtk
+ if: >-
+ needs.ubuntu-gtk.result == 'success' &&
+ github.event_name != 'pull_request' &&
+ github.ref_name == vars.PAGES_REPORT_BRANCH
+ permissions:
+ actions: read
+ contents: read
+ pages: write
+ id-token: write
+ uses: ./.github/workflows/deploy-midscene-report.yml
+ with:
+ artifact-name: midscene-ubuntu-22.04-e2e-report
+ report-label: Ubuntu 22.04
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index a2b9203..d4f8244 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -10,6 +10,23 @@ concurrency:
cancel-in-progress: true
jobs:
+ pages-report-history:
+ name: Pages report history
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
+ with:
+ node-version: "22"
+ - name: Statically check and test Pages history builder
+ run: |
+ node --check scripts/build-pages-report.mjs
+ node --check tests/test_pages_report_history.mjs
+ node --test tests/test_pages_report_history.mjs
+
core-compatibility:
name: Core / Python ${{ matrix.python }}
runs-on: ubuntu-latest
diff --git a/scripts/build-pages-report.mjs b/scripts/build-pages-report.mjs
new file mode 100644
index 0000000..ffb082b
--- /dev/null
+++ b/scripts/build-pages-report.mjs
@@ -0,0 +1,355 @@
+#!/usr/bin/env node
+
+import { copyFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import process from 'node:process';
+
+const MANIFEST_VERSION = 1;
+
+function parseArguments(argv) {
+ const options = {};
+ for (let index = 0; index < argv.length; index += 2) {
+ const key = argv[index];
+ const value = argv[index + 1];
+ if (!key?.startsWith('--') || value === undefined) {
+ throw new Error(`Invalid argument near ${key ?? '<end>'}`);
+ }
+ options[key.slice(2)] = value;
+ }
+ return options;
+}
+
+function required(options, name) {
+ const value = options[name];
+ if (!value) {
+ throw new Error(`Missing --${name}`);
+ }
+ return value;
+}
+
+function validateRunId(value) {
+ if (!/^\d+$/.test(value)) {
+ throw new Error('Run ID must contain digits only');
+ }
+ return value;
+}
+
+function validateRetention(value) {
+ const retention = Number(value);
+ if (!Number.isInteger(retention) || retention < 1 || retention > 50) {
+ throw new Error('Report retention must be an integer from 1 to 50');
+ }
+ return retention;
+}
+
+function normalizeBaseUrl(value) {
+ const url = new URL(value);
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new Error('Pages URL must use HTTP or HTTPS');
+ }
+ if (!url.pathname.endsWith('/')) {
+ url.pathname += '/';
+ }
+ return url;
+}
+
+async function findHtmlFiles(directory) {
+ const results = [];
+ async function visit(current) {
+ for (const entry of await readdir(current, { withFileTypes: true })) {
+ const item = path.join(current, entry.name);
+ if (entry.isDirectory()) {
+ await visit(item);
+ } else if (entry.isFile() && entry.name.endsWith('.html')) {
+ results.push(item);
+ }
+ }
+ }
+ await visit(directory);
+ return results;
+}
+
+function collectModelUsage(reportHtml) {
+ const calls = new Map();
+ const dumps = reportHtml.matchAll(
+ /<script\s+type=["']midscene_web_dump["'][^>]*>\s*(\{[\s\S]*?)<\/script>/g,
+ );
+
+ function visit(value) {
+ if (Array.isArray(value)) {
+ value.forEach(visit);
+ return;
+ }
+ if (!value || typeof value !== 'object') {
+ return;
+ }
+ const usage = value.usage;
+ if (usage && typeof usage === 'object') {
+ const callId = usage._midscene_call_id;
+ if (typeof callId === 'string' && !calls.has(callId)) {
+ calls.set(callId, {
+ durationMs: Number.isFinite(usage.time_cost) ? usage.time_cost : null,
+ tokens: Number.isFinite(usage.total_tokens) ? usage.total_tokens : null,
+ });
+ }
+ }
+ Object.values(value).forEach(visit);
+ }
+
+ function normalizeJsonControlCharacters(source) {
+ let normalized = '';
+ let insideString = false;
+ let escaped = false;
+ for (const character of source) {
+ if (!insideString) {
+ normalized += character;
+ if (character === '"') insideString = true;
+ continue;
+ }
+ if (escaped) {
+ normalized += character;
+ escaped = false;
+ } else if (character === '\\') {
+ normalized += character;
+ escaped = true;
+ } else if (character === '"') {
+ normalized += character;
+ insideString = false;
+ } else if (character.charCodeAt(0) <= 0x1f) {
+ normalized += `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`;
+ } else {
+ normalized += character;
+ }
+ }
+ return normalized;
+ }
+
+ for (const match of dumps) {
+ try {
+ visit(JSON.parse(normalizeJsonControlCharacters(match[1])));
+ } catch (error) {
+ throw new Error(`Cannot parse embedded Midscene report data: ${error.message}`);
+ }
+ }
+
+ const durations = [...calls.values()]
+ .map((call) => call.durationMs)
+ .filter((duration) => duration !== null);
+ const tokens = [...calls.values()]
+ .map((call) => call.tokens)
+ .filter((tokenCount) => tokenCount !== null);
+ return {
+ modelCallCount: calls.size,
+ averageDurationMs: durations.length
+ ? Math.round(durations.reduce((sum, duration) => sum + duration, 0) / durations.length)
+ : null,
+ tokenUsage: tokens.length
+ ? tokens.reduce((sum, tokenCount) => sum + tokenCount, 0)
+ : null,
+ };
+}
+
+function validateHistoryManifest(manifest) {
+ if (
+ !manifest ||
+ manifest.version !== MANIFEST_VERSION ||
+ !Array.isArray(manifest.reports)
+ ) {
+ throw new Error('Existing Pages manifest has an unsupported shape');
+ }
+ for (const report of manifest.reports) {
+ if (
+ typeof report.runId !== 'string' ||
+ !/^\d+$/.test(report.runId) ||
+ report.reportPath !== `reports/${report.runId}/index.html` ||
+ typeof report.workflowUrl !== 'string'
+ ) {
+ throw new Error('Existing Pages manifest contains an invalid report entry');
+ }
+ }
+ return manifest;
+}
+
+async function fetchHistory(baseUrl) {
+ const manifestUrl = new URL('reports/manifest.json', baseUrl);
+ const response = await fetch(manifestUrl, { redirect: 'follow' });
+ if (response.status === 404) {
+ return [];
+ }
+ if (!response.ok) {
+ throw new Error(`Cannot download existing manifest: HTTP ${response.status}`);
+ }
+ let manifest;
+ try {
+ manifest = await response.json();
+ } catch (error) {
+ throw new Error(`Cannot parse existing manifest: ${error.message}`);
+ }
+ return validateHistoryManifest(manifest).reports;
+}
+
+async function restoreReport(baseUrl, siteDirectory, report) {
+ const response = await fetch(new URL(report.reportPath, baseUrl), {
+ redirect: 'follow',
+ });
+ if (!response.ok) {
+ throw new Error(
+ `Cannot restore report for run ${report.runId}: HTTP ${response.status}`,
+ );
+ }
+ const contentType = response.headers.get('content-type') ?? '';
+ if (!contentType.toLowerCase().includes('text/html')) {
+ throw new Error(
+ `Cannot restore report for run ${report.runId}: expected text/html, got ${contentType || 'no Content-Type'}`,
+ );
+ }
+ const destination = path.join(siteDirectory, report.reportPath);
+ await mkdir(path.dirname(destination), { recursive: true });
+ await writeFile(destination, Buffer.from(await response.arrayBuffer()));
+}
+
+function escapeHtml(value) {
+ return String(value)
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#039;');
+}
+
+function formatDuration(durationMs) {
+ if (durationMs === null) return 'Unavailable';
+ return `${(durationMs / 1000).toFixed(2)} s`;
+}
+
+function buildIndex(reports) {
+ const rows = reports
+ .map(
+ (report) => `
+ <tr>
+ <td><a href="${escapeHtml(report.workflowUrl)}">${escapeHtml(report.runId)}</a></td>
+ <td>${escapeHtml(report.label ?? 'Midscene E2E')}</td>
+ <td>${escapeHtml(report.generatedAt)}</td>
+ <td>${escapeHtml(report.successRate.toFixed(1))}%</td>
+ <td>${escapeHtml(formatDuration(report.averageDurationMs))}</td>
+ <td>${escapeHtml(report.modelCallCount)}</td>
+ <td>${report.tokenUsage === null ? 'Unavailable' : escapeHtml(report.tokenUsage.toLocaleString('en-US'))}</td>
+ <td><a href="${escapeHtml(report.workflowUrl)}">Actions run</a></td>
+ <td><a href="${escapeHtml(report.reportPath)}">HTML report</a></td>
+ </tr>`,
+ )
+ .join('');
+
+ return `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Doubao Say test report history</title>
+ <style>
+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
+ body { margin: 0 auto; max-width: 1180px; padding: 2rem 1rem; }
+ h1 { margin-bottom: .4rem; }
+ p { color: #777; margin-top: 0; }
+ .table-wrap { overflow-x: auto; }
+ table { border-collapse: collapse; width: 100%; }
+ th, td { border-bottom: 1px solid #8885; padding: .75rem; text-align: left; white-space: nowrap; }
+ th { font-size: .82rem; text-transform: uppercase; }
+ a { color: #2878d0; }
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Doubao Say test report history</h1>
+ <p>Successful Midscene CI reports, newest first.</p>
+ <div class="table-wrap">
+ <table>
+ <thead><tr><th>Run ID</th><th>Distribution</th><th>Generated (UTC)</th><th>Success rate</th><th>Avg. model call</th><th>Model calls</th><th>Tokens</th><th>Workflow</th><th>Report</th></tr></thead>
+ <tbody>${rows}
+ </tbody>
+ </table>
+ </div>
+ </main>
+ </body>
+</html>
+`;
+}
+
+export async function buildPagesReport(options) {
+ const reportDirectory = path.resolve(required(options, 'report-dir'));
+ const siteDirectory = path.resolve(required(options, 'site-dir'));
+ const runId = validateRunId(required(options, 'run-id'));
+ const workflowUrl = required(options, 'workflow-url');
+ const generatedAt = new Date(required(options, 'generated-at')).toISOString();
+ const retention = validateRetention(required(options, 'retention'));
+ const baseUrl = normalizeBaseUrl(required(options, 'pages-url'));
+ const label = options.label || 'Midscene E2E';
+
+ const existingItems = await readdir(siteDirectory).catch((error) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (existingItems?.length) {
+ throw new Error('Site output directory must be empty');
+ }
+
+ const htmlFiles = await findHtmlFiles(reportDirectory);
+ if (htmlFiles.length !== 1) {
+ throw new Error(`Expected exactly one report HTML file, found ${htmlFiles.length}`);
+ }
+ const reportHtml = await readFile(htmlFiles[0], 'utf8');
+ const usage = collectModelUsage(reportHtml);
+ const current = {
+ runId,
+ generatedAt,
+ label,
+ successRate: 100,
+ testCount: 1,
+ ...usage,
+ workflowUrl,
+ reportPath: `reports/${runId}/index.html`,
+ };
+
+ const history = (await fetchHistory(baseUrl))
+ .filter((report) => report.runId !== runId)
+ .slice(0, retention - 1);
+
+ await mkdir(siteDirectory, { recursive: true });
+ for (const report of history) {
+ await restoreReport(baseUrl, siteDirectory, report);
+ }
+
+ const currentDestination = path.join(siteDirectory, current.reportPath);
+ await mkdir(path.dirname(currentDestination), { recursive: true });
+ await copyFile(htmlFiles[0], currentDestination);
+
+ const reports = [current, ...history];
+ const manifest = {
+ version: MANIFEST_VERSION,
+ generatedAt,
+ retention,
+ reports,
+ };
+ await mkdir(path.join(siteDirectory, 'reports'), { recursive: true });
+ await writeFile(
+ path.join(siteDirectory, 'reports', 'manifest.json'),
+ `${JSON.stringify(manifest, null, 2)}\n`,
+ );
+ await writeFile(path.join(siteDirectory, 'index.html'), buildIndex(reports));
+ return manifest;
+}
+
+async function main() {
+ const options = parseArguments(process.argv.slice(2));
+ const manifest = await buildPagesReport(options);
+ process.stdout.write(
+ `Prepared ${manifest.reports.length} report(s); newest run is ${manifest.reports[0].runId}.\n`,
+ );
+}
+
+if (import.meta.url === new URL(process.argv[1], 'file:').href) {
+ main().catch((error) => {
+ process.stderr.write(`${error.stack ?? error.message}\n`);
+ process.exitCode = 1;
+ });
+}
diff --git a/tests/test_pages_report_history.mjs b/tests/test_pages_report_history.mjs
new file mode 100644
index 0000000..68b887c
--- /dev/null
+++ b/tests/test_pages_report_history.mjs
@@ -0,0 +1,170 @@
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+
+import { buildPagesReport } from '../scripts/build-pages-report.mjs';
+
+const fixtureHtml = `<!doctype html><html><body>report
+<script type="midscene_web_dump">{"usage":{"_midscene_call_id":"call-1","time_cost":2500,"total_tokens":120}}</script>
+<script type="midscene_web_dump">{"message":"raw
+control character","usage":{"_midscene_call_id":"call-2","time_cost":3500,"total_tokens":180}}</script>
+</body></html>`;
+
+async function fixtureDirectory(root) {
+ const reportDirectory = path.join(root, 'artifact', 'report');
+ await mkdir(reportDirectory, { recursive: true });
+ await writeFile(path.join(reportDirectory, 'midscene.html'), fixtureHtml);
+ return path.dirname(reportDirectory);
+}
+
+async function startServer(handler) {
+ const server = http.createServer(handler);
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ return {
+ url: `http://127.0.0.1:${address.port}/`,
+ close: () => new Promise((resolve) => server.close(resolve)),
+ };
+}
+
+function options(reportDirectory, siteDirectory, pagesUrl, runId = '200') {
+ return {
+ 'report-dir': reportDirectory,
+ 'site-dir': siteDirectory,
+ 'run-id': runId,
+ 'workflow-url': `https://github.com/quanru/doubao-say/actions/runs/${runId}`,
+ 'generated-at': '2026-09-15T12:00:00Z',
+ retention: '10',
+ 'pages-url': pagesUrl,
+ label: 'Ubuntu 22.04',
+ };
+}
+
+test('simulates a first deployment when Pages returns 404', async (context) => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'pages-first-'));
+ const reportDirectory = await fixtureDirectory(root);
+ const siteDirectory = path.join(root, 'site');
+ const server = await startServer((_request, response) => {
+ response.writeHead(404).end();
+ });
+ context.after(server.close);
+
+ const manifest = await buildPagesReport(
+ options(reportDirectory, siteDirectory, server.url),
+ );
+
+ assert.equal(manifest.reports.length, 1);
+ assert.equal(manifest.reports[0].runId, '200');
+ assert.equal(manifest.reports[0].reportPath, 'reports/200/index.html');
+ assert.equal(manifest.reports[0].successRate, 100);
+ assert.equal(manifest.reports[0].averageDurationMs, 3000);
+ assert.equal(manifest.reports[0].modelCallCount, 2);
+ assert.equal(manifest.reports[0].tokenUsage, 300);
+ const indexHtml = await readFile(path.join(siteDirectory, 'index.html'), 'utf8');
+ assert.match(indexHtml, /Run ID/);
+ assert.match(indexHtml, /Distribution/);
+ assert.match(indexHtml, /Ubuntu 22\.04/);
+ assert.equal(
+ await readFile(path.join(siteDirectory, 'reports', '200', 'index.html'), 'utf8'),
+ fixtureHtml,
+ );
+});
+
+test('restores retained history before adding the new run', async (context) => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'pages-history-'));
+ const reportDirectory = await fixtureDirectory(root);
+ const siteDirectory = path.join(root, 'site');
+ const oldReport = '<!doctype html><html><body>old report</body></html>';
+ const oldEntry = {
+ runId: '100',
+ generatedAt: '2026-09-14T12:00:00.000Z',
+ label: 'Omarchy 4.0.3',
+ successRate: 100,
+ testCount: 1,
+ averageDurationMs: 4000,
+ modelCallCount: 1,
+ tokenUsage: null,
+ workflowUrl: 'https://github.com/quanru/doubao-say/actions/runs/100',
+ reportPath: 'reports/100/index.html',
+ };
+ const server = await startServer((request, response) => {
+ if (request.url === '/reports/manifest.json') {
+ response.setHeader('content-type', 'application/json');
+ response.end(JSON.stringify({ version: 1, reports: [oldEntry] }));
+ } else if (request.url === '/reports/100/index.html') {
+ response.setHeader('content-type', 'text/html; charset=utf-8');
+ response.end(oldReport);
+ } else {
+ response.writeHead(404).end();
+ }
+ });
+ context.after(server.close);
+
+ const manifest = await buildPagesReport(
+ options(reportDirectory, siteDirectory, server.url),
+ );
+
+ assert.deepEqual(
+ manifest.reports.map((report) => report.runId),
+ ['200', '100'],
+ );
+ assert.equal(
+ await readFile(path.join(siteDirectory, 'reports', '100', 'index.html'), 'utf8'),
+ oldReport,
+ );
+ const writtenManifest = JSON.parse(
+ await readFile(path.join(siteDirectory, 'reports', 'manifest.json'), 'utf8'),
+ );
+ assert.equal(writtenManifest.reports[0].reportPath, 'reports/200/index.html');
+ assert.equal(
+ writtenManifest.reports[0].workflowUrl,
+ 'https://github.com/quanru/doubao-say/actions/runs/200',
+ );
+});
+
+test('stops when a manifest exists but an old report cannot be restored', async (context) => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'pages-failure-'));
+ const reportDirectory = await fixtureDirectory(root);
+ const siteDirectory = path.join(root, 'site');
+ const server = await startServer((request, response) => {
+ if (request.url === '/reports/manifest.json') {
+ response.setHeader('content-type', 'application/json');
+ response.end(
+ JSON.stringify({
+ version: 1,
+ reports: [
+ {
+ runId: '100',
+ workflowUrl: 'https://github.com/quanru/doubao-say/actions/runs/100',
+ reportPath: 'reports/100/index.html',
+ },
+ ],
+ }),
+ );
+ } else {
+ response.writeHead(503).end();
+ }
+ });
+ context.after(server.close);
+
+ await assert.rejects(
+ buildPagesReport(options(reportDirectory, siteDirectory, server.url)),
+ /Cannot restore report for run 100: HTTP 503/,
+ );
+});
+
+test('rejects retention outside the supported range', async (context) => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'pages-retention-'));
+ const reportDirectory = await fixtureDirectory(root);
+ const server = await startServer((_request, response) => {
+ response.writeHead(404).end();
+ });
+ context.after(server.close);
+ const invalid = options(reportDirectory, path.join(root, 'site'), server.url);
+ invalid.retention = '51';
+
+ await assert.rejects(buildPagesReport(invalid), /integer from 1 to 50/);
+});