| 1 | |
| 2 | |
| 3 | |
| 4 | import assert from "node:assert/strict"; |
| 5 | import { spawn } from "node:child_process"; |
| 6 | import { once } from "node:events"; |
| 7 | import { randomBytes } from "node:crypto"; |
| 8 | import { cp, mkdtemp, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises"; |
| 9 | import { tmpdir } from "node:os"; |
| 10 | import { join } from "node:path"; |
| 11 | import { setTimeout as delay } from "node:timers/promises"; |
| 12 | |
| 13 | if (process.platform === "linux") assert.ok(process.env.DISPLAY, "Provide an isolated X display"); |
| 14 | const executable = process.env.CAGE_TEST_BROWSER_PATH || "/usr/bin/chromium"; |
| 15 | const directory = await realpath(await mkdtemp(join(tmpdir(), "cage-devtools-smoke-"))); |
| 16 | const token = randomBytes(32).toString("hex"); |
| 17 | let agent, control, stderr = ""; |
| 18 | async function waitFor(fn, label) { |
| 19 | const deadline = Date.now() + 20000; |
| 20 | while (Date.now() < deadline) { |
| 21 | if (agent && agent.exitCode !== null) throw new Error("Controller exited: " + stderr); |
| 22 | const result = await fn(); |
| 23 | if (result) return result; |
| 24 | await delay(100); |
| 25 | } |
| 26 | throw new Error("Timed out: " + label + ". " + stderr); |
| 27 | } |
| 28 | async function api(path, input) { |
| 29 | const response = await fetch(control + path, { |
| 30 | method: input === undefined ? "GET" : "POST", |
| 31 | headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, |
| 32 | ...(input === undefined ? {} : { body: JSON.stringify(input) }), |
| 33 | }); |
| 34 | const result = await response.json(); |
| 35 | assert.equal(response.status, 200, JSON.stringify(result)); |
| 36 | return result; |
| 37 | } |
| 38 | const cdp = (method, params = {}, sessionId) => api("/__devtools-test", { method, params, sessionId }); |
| 39 | try { |
| 40 | const sourceDirectory = new URL("../internal/cage/", import.meta.url); |
| 41 | for (const name of await readdir(sourceDirectory)) |
| 42 | if ((name.startsWith("browser-") && name.endsWith(".mjs")) || name === "native-input.mjs") |
| 43 | await cp(new URL(name, sourceDirectory), join(directory, name)); |
| 44 | await cp(new URL("split-extension", sourceDirectory), join(directory, "extension"), { recursive: true }); |
| 45 | const source = await readFile(new URL("browser-agent.mjs", sourceDirectory), "utf8"); |
| 46 | const listen = 'server.listen(18500, "127.0.0.1");'; |
| 47 | const input = 'const input = JSON.parse(text || "{}");'; |
| 48 | assert.ok(source.includes(listen) && source.includes(input), "Update the isolated controller adapter"); |
| 49 | |
| 50 | |
| 51 | const adapted = source |
| 52 | .replaceAll("/home/cage-browser", directory) |
| 53 | .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json")) |
| 54 | .replace("/usr/local/lib/cage-split", join(directory, "extension")) |
| 55 | .replace('spawn("/usr/bin/chromium", flags', `spawn(${JSON.stringify(executable)}, [...flags, "--auto-open-devtools-for-tabs"]`) |
| 56 | .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("PORT=" + server.address().port));') |
| 57 | .replace(input, `${input} |
| 58 | if (req.url === "/__devtools-test") { |
| 59 | res.end(JSON.stringify(await cdp(input.method, input.params || {}, input.sessionId))); |
| 60 | return; |
| 61 | }`); |
| 62 | await writeFile(join(directory, "browser-agent.mjs"), adapted); |
| 63 | await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory })); |
| 64 | await writeFile(join(directory, "homepage.json"), JSON.stringify({ url: "about:blank" })); |
| 65 | agent = spawn(process.execPath, [join(directory, "browser-agent.mjs")], { stdio: ["ignore", "pipe", "pipe"] }); |
| 66 | let output = ""; |
| 67 | agent.stdout.on("data", chunk => { |
| 68 | output += chunk; |
| 69 | const match = output.match(/PORT=(\d+)/); |
| 70 | if (match) control = `http://127.0.0.1:${match[1]}`; |
| 71 | }); |
| 72 | agent.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-4000); }); |
| 73 | await waitFor(() => control, "control listener"); |
| 74 | await waitFor(async () => (await fetch(control + "/health", { headers: { Authorization: `Bearer ${token}` } })).ok, "browser ready"); |
| 75 | const devtools = await waitFor(async () => (await cdp("Target.getTargets")).targetInfos.find(t => t.url.startsWith("devtools://")), "real DevTools page"); |
| 76 | const { sessionId } = await cdp("Target.attachToTarget", { targetId: devtools.targetId, flatten: true }); |
| 77 | await waitFor(async () => { |
| 78 | const result = await cdp("Runtime.evaluate", { expression: "document.readyState === 'complete' && document.title.includes('DevTools')", returnByValue: true }, sessionId); |
| 79 | return result.result.value; |
| 80 | }, "DevTools UI loaded"); |
| 81 | const state = await api("/tabs"); |
| 82 | assert.equal(state.tabs.length, 1, "DevTools must not appear as a Cage tab"); |
| 83 | assert.equal(state.tabs[0].url, "about:blank"); |
| 84 | assert.equal(state.active, state.tabs[0].id, "DevTools must not become the active Cage tab"); |
| 85 | await cdp("Target.closeTarget", { targetId: devtools.targetId }); |
| 86 | assert.equal((await api("/tabs")).active, state.active); |
| 87 | console.log("PASS: production fullscreen controller opens real DevTools, keeps its page out of Cage tabs, and preserves the active website when DevTools closes"); |
| 88 | } finally { |
| 89 | if (agent?.exitCode === null) { |
| 90 | const exited = once(agent, "exit"); |
| 91 | agent.kill("SIGTERM"); |
| 92 | const timer = setTimeout(() => agent.kill("SIGKILL"), 5000); |
| 93 | await exited; |
| 94 | clearTimeout(timer); |
| 95 | } |
| 96 | await rm(directory, { recursive: true, force: true }); |
| 97 | } |