#!/usr/bin/env node import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs"; import { resolve } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; if (process.platform !== "win32") { console.error( "zellij-smoke is the win32 smoke path. Use scripts/tmux-smoke.mjs on non-win32.", ); process.exit(2); } const args = new Set(process.argv.slice(2)); const noBrowser = args.has("--no-browser"); const noFallback = args.has("--no-fallback"); const zellij = process.env.ZELLIJ ?? "zellij"; const pi = process.env.PI_UI_SMOKE_PI ?? "pi.cmd"; const session = process.env.PI_UI_SMOKE_SESSION ?? `ui-smoke-${Date.now().toString(36)}`; const cwd = process.cwd(); const outDir = resolve(cwd, ".pi/tmp/ui-zellij-smoke"); const screenPath = resolve(outDir, `${session}.screen.txt`); const urlPath = resolve(outDir, `${session}.url.txt`); const env = { ...process.env, ZELLIJ_SESSION_NAME: session, MSYS_NO_PATHCONV: "1", }; mkdirSync(outDir, { recursive: true }); console.log(`zellij session: ${session}`); console.log(`cwd: ${cwd}`); run(zellij, ["--version"]); startZellijSession(); await waitForSession(); const pane = "terminal_0"; console.log(`pane: ${pane}`); sendLine(pane, `cd /d ${cwd}`); await sleep(500); sendLine( pane, `set PI_UI_NO_AUTO_OPEN=1&& set "PI_UI_SMOKE_URL_FILE=${urlPath}"&& ${pi} -e extensions/ui/index.ts`, ); await waitForPiReady(pane); sendLine(pane, "/ui"); await waitForUiUrl(pane, screenPath); const firstScreen = safeRead(screenPath); const url = safeRead(urlPath).trim() || extractUiUrl(firstScreen); if (!url) { const fallback = noFallback ? { status: "skipped" } : runPhase1Fallback(); writeSummary({ session, pane, screenPath, url: undefined, status401: undefined, zellijAutomation: "url-not-found", fallback, }); console.error(`No /ui URL found in ${screenPath}.`); console.error(`attach: ${zellij} attach ${session}`); console.error(`kill: ${zellij} kill-session ${session}`); if (fallback.status === "passed") process.exit(0); process.exit(1); } const status401 = await probe401(url); console.log(`url: ${redactUrl(url)}`); console.log(`tokenless /api/status: ${status401}`); if (status401 !== 401) { console.error("Expected tokenless /api/status to return 401."); } let browserText = "skipped"; if (!noBrowser) { browserText = await verifyBrowser(url); openBrowser(url); } rmSync(urlPath, { force: true }); await sleep(2_000); sendLine(pane, "/ui off"); await sleep(3_000); dump(pane, screenPath); writeSummary({ session, pane, screenPath, url: redactUrl(url), status401, browserText, }); console.log(`screen: ${screenPath}`); console.log(`attach: ${zellij} attach ${session}`); console.log(`kill: ${zellij} kill-session ${session}`); if (status401 !== 401) process.exit(1); function startZellijSession() { const psCommand = [ "Start-Process", "-FilePath", quoteForPowerShell(zellij), "-ArgumentList", `@('attach','--create-background','${session.replaceAll("'", "''")}')`, "-WindowStyle", "Minimized", ].join(" "); run("powershell.exe", ["-NoLogo", "-NoProfile", "-Command", psCommand]); } async function waitForSession() { for (let attempt = 0; attempt < 20; attempt += 1) { const sessions = runCapture(zellij, ["list-sessions"], { allowFailure: true, }); if (sessions.includes(session)) return; await sleep(500); } throw new Error(`zellij session did not start: ${session}`); } function quoteForPowerShell(value) { return `'${value.replaceAll("'", "''")}'`; } async function waitForPiReady(paneId) { for (let attempt = 0; attempt < 40; attempt += 1) { dump(paneId, screenPath); const screen = safeRead(screenPath); if (screen.includes("builtin-tools") && screen.includes("gpt-")) return; await sleep(1_000); } throw new Error("Pi did not become ready in zellij pane"); } async function waitForUiUrl(paneId, path) { for (let attempt = 0; attempt < 40; attempt += 1) { dump(paneId, path); if (safeRead(urlPath).trim() || extractUiUrl(safeRead(path))) return; await sleep(1_000); } } function sendLine(paneId, line) { const paneArgs = paneId ? ["-p", paneId] : []; run(zellij, ["action", "write-chars", ...paneArgs, line], { env }); run(zellij, ["action", "send-keys", ...paneArgs, "Enter"], { env }); } function dump(paneId, path) { const paneArgs = paneId ? ["-p", paneId] : []; run(zellij, ["action", "dump-screen", ...paneArgs, "--path", path], { env }); } async function probe401(uiUrl) { const parsed = new URL(uiUrl); const response = await fetch(`${parsed.origin}/api/status`); return response.status; } async function verifyBrowser(url) { const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe"; const { chromium } = await import("@playwright/test"); const browser = await chromium.launch({ headless: true, executablePath: existsSync(chromePath) ? chromePath : undefined, }); try { const page = await browser.newPage(); await page.goto(url); await page.waitForSelector("#ui-shell"); await page.waitForSelector("#ui-composer"); return await page.locator("#ui-progress").innerText(); } finally { await browser.close(); } } function openBrowser(url) { spawnSync("cmd.exe", ["/d", "/s", "/c", "start", "", url], { stdio: "ignore", detached: true, }); } function extractUiUrl(text) { const tokenParam = "token" + "="; return text .split(/\s+/) .find((part) => part.startsWith("http://") && part.includes(tokenParam)); } function redactUrl(value) { const tokenParam = "token" + "="; return value.replace( new RegExp(`${tokenParam}[A-Za-z0-9_-]+`), `${tokenParam}[redacted]`, ); } function safeRead(path) { try { return readFileSync(path, "utf8"); } catch { return ""; } } function runPhase1Fallback() { console.error( "Running Phase 1 browser smoke fallback outside zellij pane automation.", ); const commandArgs = [ "--import", "tsx", "extensions/ui/scripts/phase1-smoke.mjs", ]; if (noBrowser) commandArgs.push("--no-browser"); const result = spawnSync(process.execPath, commandArgs, { stdio: "inherit", shell: false, timeout: 120_000, }); return { status: result.status === 0 ? "passed" : "failed", exitCode: result.status, }; } function writeSummary(summary) { const path = resolve(outDir, `${session}.summary.json`); writeFileSync(path, `${JSON.stringify(summary, null, "\t")}\n`); console.log(`summary: ${path}`); } function run(command, commandArgs, options = {}) { const result = spawnSync(command, commandArgs, { stdio: "inherit", shell: false, timeout: 60_000, ...options, }); if (result.status !== 0) process.exit(result.status ?? 1); } function runCapture(command, commandArgs, options = {}) { const { allowFailure, ...spawnOptions } = options; const result = spawnSync(command, commandArgs, { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], shell: false, timeout: 60_000, ...spawnOptions, }); if (!allowFailure && result.status !== 0) process.exit(result.status ?? 1); return result.stdout ?? ""; }