Skip to content

Commit a2ccd6e

Browse files
authored
test(ui): add service-worker update primary QA proof (#118805)
* test(ui): prove service-worker production updates * test(qa): register control ui service-worker proof * fix(ui): type production build environment * fix(ui): avoid service-worker test shadowing * test(ui): gate service-worker proof capture * test(ui): isolate production e2e build output * test(ui): assert claimed service worker version
1 parent 06b5f0b commit a2ccd6e

3 files changed

Lines changed: 358 additions & 8 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
title: Control UI production service-worker update
2+
3+
scenario:
4+
id: control-ui-service-worker-update
5+
surface: control-ui
6+
coverage:
7+
primary:
8+
- control-ui.service-worker-updates
9+
objective: >-
10+
Prove a production Control UI worker updates in place on one browser origin
11+
and serves the newly built application assets.
12+
successCriteria:
13+
- Chromium loads a production Control UI build and becomes controlled by its activated worker.
14+
- A second production build is published at the same origin.
15+
- The installed registration discovers and activates the updated worker.
16+
- The updated worker claims the page and the production update message reloads it.
17+
- A build-specific asset fetched while controlled matches the second build, not stale output.
18+
docsRefs:
19+
- docs/web/control-ui.md
20+
codeRefs:
21+
- ui/src/main.ts
22+
- ui/public/sw.js
23+
- ui/src/e2e/service-worker-update.e2e.test.ts
24+
- ui/src/test-helpers/control-ui-e2e.ts
25+
execution:
26+
kind: playwright
27+
path: ui/src/e2e/service-worker-update.e2e.test.ts
28+
testNamePattern: activates the next production worker and serves its refreshed build asset
29+
summary: >-
30+
Real Chromium proof across two production Control UI builds, native worker
31+
update and activation, page takeover, reload, and refreshed hashed assets.
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
import { createHash } from "node:crypto";
2+
import { mkdir, mkdtemp, readFile, readdir, rm } from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { chromium, type Browser, type Page } from "playwright";
6+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
7+
import {
8+
buildProductionControlUiE2e,
9+
canRunPlaywrightChromium,
10+
resolvePlaywrightChromiumExecutablePath,
11+
startProductionControlUiE2eServer,
12+
type ControlUiE2eServer,
13+
} from "../test-helpers/control-ui-e2e.ts";
14+
15+
const chromiumExecutablePath = resolvePlaywrightChromiumExecutablePath(chromium.executablePath());
16+
const artifactDir = path.resolve(".artifacts/control-ui-e2e/service-worker-update");
17+
const captureUiProof = process.env.OPENCLAW_CAPTURE_UI_PROOF === "1";
18+
const workerUpdateVersionsStorageKey = "openclaw.control-ui-e2e.worker-update-versions";
19+
20+
const buildA = "service-worker-build-a";
21+
const buildB = "service-worker-build-b";
22+
23+
type BuildAsset = {
24+
path: string;
25+
sha256: string;
26+
};
27+
28+
let browser: Browser;
29+
let outDir: string;
30+
let server: ControlUiE2eServer;
31+
32+
async function findBuildAsset(buildId: string): Promise<BuildAsset> {
33+
const assetsDir = path.join(outDir, "assets");
34+
for (const fileName of await readdir(assetsDir)) {
35+
if (!fileName.endsWith(".js")) {
36+
continue;
37+
}
38+
const source = await readFile(path.join(assetsDir, fileName));
39+
if (source.includes(Buffer.from(buildId))) {
40+
return {
41+
path: `assets/${fileName}`,
42+
sha256: createHash("sha256").update(source).digest("hex"),
43+
};
44+
}
45+
}
46+
throw new Error(`Production Control UI output did not contain build id ${buildId}`);
47+
}
48+
49+
async function ensureControlledPage(page: Page, pageErrors: string[], expectedBuildId: string) {
50+
const registration = await page.evaluate(async (workerBuildId) => {
51+
const ready = navigator.serviceWorker.ready.then((value) => ({
52+
activeState: value.active?.state ?? null,
53+
controlled: navigator.serviceWorker.controller !== null,
54+
error: null,
55+
}));
56+
const timeout = new Promise<{
57+
activeState: null;
58+
controlled: boolean;
59+
error: string;
60+
}>((resolve) => {
61+
window.setTimeout(() => {
62+
void (async () => {
63+
const registrations = await navigator.serviceWorker.getRegistrations();
64+
const response = await fetch(`/sw.js?v=${workerBuildId}`);
65+
resolve({
66+
activeState: null,
67+
controlled: navigator.serviceWorker.controller !== null,
68+
error: JSON.stringify({
69+
isSecureContext,
70+
location: window.location.href,
71+
registrations: registrations.map((value) => ({
72+
active: value.active?.state ?? null,
73+
activeScriptUrl: value.active?.scriptURL ?? null,
74+
installing: value.installing?.state ?? null,
75+
scope: value.scope,
76+
waiting: value.waiting?.state ?? null,
77+
})),
78+
serviceWorker: {
79+
contentType: response.headers.get("content-type"),
80+
status: response.status,
81+
},
82+
}),
83+
});
84+
})();
85+
}, 10_000);
86+
});
87+
return Promise.race([ready, timeout]);
88+
}, expectedBuildId);
89+
if (registration.error) {
90+
throw new Error(
91+
`Service worker did not become ready: ${registration.error}; page errors: ${JSON.stringify(pageErrors)}`,
92+
);
93+
}
94+
await page.waitForFunction(async () => {
95+
const value = await navigator.serviceWorker.ready;
96+
return value.active?.state === "activated";
97+
});
98+
if (!registration.controlled) {
99+
await page.reload();
100+
}
101+
await page.waitForFunction(() => navigator.serviceWorker?.controller?.state === "activated");
102+
}
103+
104+
async function readWorkerUpdateVersions(page: Page): Promise<string[]> {
105+
return page.evaluate((storageKey) => {
106+
const stored = JSON.parse(sessionStorage.getItem(storageKey) ?? "[]") as unknown;
107+
return Array.isArray(stored)
108+
? stored.filter((value): value is string => typeof value === "string")
109+
: [];
110+
}, workerUpdateVersionsStorageKey);
111+
}
112+
113+
async function fetchControlledAsset(
114+
page: Page,
115+
assetPath: string,
116+
): Promise<{ controllerState: string | null; sha256: string }> {
117+
return page.evaluate(async (relativePath) => {
118+
const controller = navigator.serviceWorker.controller;
119+
if (controller && controller.state !== "activated") {
120+
await new Promise<void>((resolve) => {
121+
controller.addEventListener(
122+
"statechange",
123+
() => {
124+
if (controller.state === "activated") {
125+
resolve();
126+
}
127+
},
128+
{ once: true },
129+
);
130+
});
131+
}
132+
const response = await fetch(new URL(relativePath, window.location.href));
133+
if (!response.ok) {
134+
throw new Error(`Build asset request failed with HTTP ${response.status}`);
135+
}
136+
const digest = await crypto.subtle.digest("SHA-256", await response.arrayBuffer());
137+
return {
138+
controllerState: controller?.state ?? null,
139+
sha256: [...new Uint8Array(digest)]
140+
.map((byte) => byte.toString(16).padStart(2, "0"))
141+
.join(""),
142+
};
143+
}, assetPath);
144+
}
145+
146+
describe("Control UI service-worker production update E2E", () => {
147+
beforeAll(async () => {
148+
if (!canRunPlaywrightChromium(chromiumExecutablePath)) {
149+
throw new Error(`Playwright Chromium is unavailable at ${chromiumExecutablePath}`);
150+
}
151+
outDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-service-worker-update-"));
152+
server = await startProductionControlUiE2eServer(outDir, buildA);
153+
browser = await chromium.launch({ executablePath: chromiumExecutablePath });
154+
}, 120_000);
155+
156+
afterAll(async () => {
157+
await browser?.close();
158+
await server?.close();
159+
if (outDir) {
160+
await rm(outDir, { force: true, recursive: true });
161+
}
162+
});
163+
164+
it("activates the next production worker and serves its refreshed build asset", async () => {
165+
if (captureUiProof) {
166+
await mkdir(artifactDir, { recursive: true });
167+
}
168+
const context = await browser.newContext({
169+
locale: "en-US",
170+
serviceWorkers: "allow",
171+
viewport: { height: 720, width: 1280 },
172+
...(captureUiProof
173+
? { recordVideo: { dir: artifactDir, size: { height: 720, width: 1280 } } }
174+
: {}),
175+
});
176+
// An update keeps the incumbent script URL while installing changed bytes.
177+
// The worker emits its embedded version only after clients.claim() resolves.
178+
await context.addInitScript((storageKey) => {
179+
navigator.serviceWorker.addEventListener("message", (event) => {
180+
if (event.data?.type !== "sw-updated" || typeof event.data.version !== "string") {
181+
return;
182+
}
183+
const stored = JSON.parse(sessionStorage.getItem(storageKey) ?? "[]") as unknown;
184+
const versions = Array.isArray(stored)
185+
? stored.filter((value): value is string => typeof value === "string")
186+
: [];
187+
versions.push(event.data.version);
188+
sessionStorage.setItem(storageKey, JSON.stringify(versions));
189+
});
190+
}, workerUpdateVersionsStorageKey);
191+
const page = await context.newPage();
192+
const pageErrors: string[] = [];
193+
page.on("pageerror", (error) => pageErrors.push(`${error.name}:${error.message}`));
194+
195+
try {
196+
expect((await page.goto(`${server.baseUrl}chat`))?.status()).toBe(200);
197+
await ensureControlledPage(page, pageErrors, buildA);
198+
await expect.poll(() => readWorkerUpdateVersions(page)).toContain(buildA);
199+
200+
const assetA = await findBuildAsset(buildA);
201+
const initialAsset = await fetchControlledAsset(page, assetA.path);
202+
expect(initialAsset).toEqual({
203+
controllerState: "activated",
204+
sha256: assetA.sha256,
205+
});
206+
await expect
207+
.poll(() => page.evaluate(() => caches.keys()))
208+
.toContain(`openclaw-control-${buildA}`);
209+
210+
await buildProductionControlUiE2e(outDir, buildB);
211+
const assetB = await findBuildAsset(buildB);
212+
expect(assetB.path).not.toBe(assetA.path);
213+
expect(assetB.sha256).not.toBe(assetA.sha256);
214+
215+
const reloaded = page.waitForEvent("domcontentloaded");
216+
await page.evaluate(() => {
217+
void navigator.serviceWorker.ready.then((registration) => registration.update());
218+
});
219+
await reloaded;
220+
await ensureControlledPage(page, pageErrors, buildB);
221+
await expect.poll(() => readWorkerUpdateVersions(page)).toContain(buildB);
222+
223+
await expect
224+
.poll(() => page.evaluate(() => caches.keys()))
225+
.toContain(`openclaw-control-${buildB}`);
226+
const refreshedAsset = await fetchControlledAsset(page, assetB.path);
227+
expect(refreshedAsset).toEqual({
228+
controllerState: "activated",
229+
sha256: assetB.sha256,
230+
});
231+
expect(refreshedAsset.sha256).not.toBe(initialAsset.sha256);
232+
233+
if (captureUiProof) {
234+
await page.screenshot({
235+
animations: "disabled",
236+
path: path.join(artifactDir, "updated-worker-controlled-page.png"),
237+
});
238+
}
239+
} finally {
240+
await context.close();
241+
}
242+
}, 120_000);
243+
});

‎ui/src/test-helpers/control-ui-e2e.ts‎

Lines changed: 84 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -447,15 +447,13 @@ function controlUiE2ePreviewConfigPlugin(): Plugin {
447447
};
448448
}
449449

450-
export async function startBundledControlUiE2eServer(outDir: string): Promise<ControlUiE2eServer> {
451-
const [{ build, preview }, { default: controlUiViteConfig }] = await Promise.all([
452-
import("vite"),
453-
import("../../vite.config.ts"),
454-
]);
455-
const port = await resolveAvailableLoopbackPort();
450+
function createBundledControlUiE2eConfig(
451+
controlUiViteConfig: (options: { outDir?: string }) => InlineConfig,
452+
outDir: string,
453+
): InlineConfig {
456454
const config = controlUiViteConfig({ outDir });
457455
const uiRoot = path.join(resolveRepoRoot(), "ui");
458-
const sharedConfig: InlineConfig = {
456+
return {
459457
...config,
460458
base: "/",
461459
configFile: false,
@@ -468,7 +466,60 @@ export async function startBundledControlUiE2eServer(outDir: string): Promise<Co
468466
logLevel: "error" as const,
469467
root: uiRoot,
470468
};
471-
await build(sharedConfig);
469+
}
470+
471+
export async function buildProductionControlUiE2e(outDir: string, buildId: string): Promise<void> {
472+
// Keep the production config outside Vitest, but write directly to the
473+
// caller-owned output so concurrent E2E builds cannot replace its worker.
474+
const repoRoot = resolveRepoRoot();
475+
const uiRoot = path.join(repoRoot, "ui");
476+
const env: NodeJS.ProcessEnv = {
477+
...process.env,
478+
NODE_ENV: "production",
479+
OPENCLAW_CONTROL_UI_BUILD_ID: buildId,
480+
};
481+
for (const key of Object.keys(env)) {
482+
if (key.startsWith("VITEST")) {
483+
delete env[key];
484+
}
485+
}
486+
const result = spawnSync(
487+
process.execPath,
488+
["--import", "tsx", fileURLToPath(import.meta.url), "--production-build", outDir],
489+
{
490+
cwd: uiRoot,
491+
encoding: "utf8",
492+
env,
493+
maxBuffer: 10 * 1024 * 1024,
494+
},
495+
);
496+
if (result.status !== 0) {
497+
throw new Error(
498+
`Production Control UI build failed (exit ${result.status ?? "unknown"}):\n${result.stderr || result.stdout}`,
499+
);
500+
}
501+
}
502+
503+
async function runProductionControlUiBuild(outDir: string): Promise<void> {
504+
const [{ build }, { default: controlUiViteConfig }] = await Promise.all([
505+
import("vite"),
506+
import("../../vite.config.ts"),
507+
]);
508+
await build({
509+
...controlUiViteConfig({ outDir }),
510+
configFile: false,
511+
logLevel: "error",
512+
root: path.join(resolveRepoRoot(), "ui"),
513+
});
514+
}
515+
516+
async function startBuiltControlUiE2eServer(outDir: string): Promise<ControlUiE2eServer> {
517+
const [{ preview }, { default: controlUiViteConfig }] = await Promise.all([
518+
import("vite"),
519+
import("../../vite.config.ts"),
520+
]);
521+
const port = await resolveAvailableLoopbackPort();
522+
const sharedConfig = createBundledControlUiE2eConfig(controlUiViteConfig, outDir);
472523
const server = await preview({
473524
...sharedConfig,
474525
plugins: [...(sharedConfig.plugins ?? []), controlUiE2ePreviewConfigPlugin()],
@@ -489,6 +540,23 @@ export async function startBundledControlUiE2eServer(outDir: string): Promise<Co
489540
}
490541
}
491542

543+
export async function startBundledControlUiE2eServer(outDir: string): Promise<ControlUiE2eServer> {
544+
const [{ build }, { default: controlUiViteConfig }] = await Promise.all([
545+
import("vite"),
546+
import("../../vite.config.ts"),
547+
]);
548+
await build(createBundledControlUiE2eConfig(controlUiViteConfig, outDir));
549+
return startBuiltControlUiE2eServer(outDir);
550+
}
551+
552+
export async function startProductionControlUiE2eServer(
553+
outDir: string,
554+
buildId: string,
555+
): Promise<ControlUiE2eServer> {
556+
await buildProductionControlUiE2e(outDir, buildId);
557+
return startBuiltControlUiE2eServer(outDir);
558+
}
559+
492560
async function resolveAvailableLoopbackPort(): Promise<number> {
493561
return new Promise((resolve, reject) => {
494562
const probe = createNetServer();
@@ -2053,4 +2121,12 @@ function createMockGatewayControls(page: Page, defaultSessionKey: string): MockG
20532121
},
20542122
};
20552123
}
2124+
2125+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
2126+
const [command, outDir] = process.argv.slice(2);
2127+
if (command !== "--production-build" || !outDir) {
2128+
throw new Error("Usage: control-ui-e2e.ts --production-build <out-dir>");
2129+
}
2130+
await runProductionControlUiBuild(outDir);
2131+
}
20562132
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

0 commit comments

Comments
 (0)