|
| 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 | +}); |
0 commit comments