Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Add npm run dev:static for offline / high-latency development (#168)

Robert Brennan9c3b936d1625
diff --git a/package.json b/package.json
index d8ae6fef63..e02ec5fe18 100644
--- a/package.json
+++ b/package.json
@@ -55,6 +55,7 @@
"dev:safe": "node --env-file-if-exists=.env scripts/dev-safe.mjs",
"dev:extra-backend": "node --env-file-if-exists=.env scripts/dev-extra-backend.mjs",
"dev:automation": "node --env-file-if-exists=.env scripts/dev-with-automation.mjs",
+ "dev:static": "node --env-file-if-exists=.env scripts/dev-static.mjs",
"dev:minimal": "node --env-file-if-exists=.env scripts/dev-safe.mjs",
"dev:frontend": "npm run make-i18n && cross-env VITE_MOCK_API=false react-router dev",
"dev:mock": "npm run make-i18n && cross-env VITE_MOCK_API=true react-router dev",
diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjs
index bb91ad0f4e..2a43ac2b33 100644
--- a/scripts/dev-safe.mjs
+++ b/scripts/dev-safe.mjs
@@ -1,5 +1,12 @@
import { spawn } from "node:child_process";
-import { existsSync, mkdirSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ statSync,
+ unlinkSync,
+} from "node:fs";
+import net from "node:net";
import { homedir } from "node:os";
import path from "node:path";
import process from "node:process";
@@ -430,6 +437,81 @@ async function main() {
});
}
+// ─────────────────────────────────────────────────────────────────────────────
+// Conversation lease cleanup
+// ─────────────────────────────────────────────────────────────────────────────
+
+/**
+ * Returns true if `host:port` accepts a TCP connection within `timeoutMs`.
+ * Used to detect a live agent-server we shouldn't disturb.
+ */
+export function isPortBusy(port, host = "127.0.0.1", timeoutMs = 500) {
+ return new Promise((resolve) => {
+ const socket = new net.Socket();
+ let settled = false;
+ const finish = (busy) => {
+ if (settled) return;
+ settled = true;
+ socket.destroy();
+ resolve(busy);
+ };
+ socket.setTimeout(timeoutMs);
+ socket.once("connect", () => finish(true));
+ socket.once("timeout", () => finish(false));
+ socket.once("error", () => finish(false));
+ socket.connect(port, host);
+ });
+}
+
+/**
+ * Remove stale `owner_lease.json` files under `conversationsDir` so a
+ * freshly spawned agent-server can claim ownership and re-load every
+ * existing conversation.
+ *
+ * Why this is needed: each conversation directory carries an
+ * `owner_lease.json` that locks it to a single agent-server's
+ * `owner_instance_id` for a 45 s TTL refreshed by heartbeat. On
+ * graceful shutdown the agent-server unlinks its leases; on a hard
+ * kill (or a fast restart, well under 45 s) the leases linger. A new
+ * agent-server with a fresh `owner_instance_id` will then raise
+ * `ConversationLeaseHeldError` for each conversation at startup load
+ * and skip it entirely β€” `/api/conversations/search` returns `[]`
+ * even though the meta files are right there on disk.
+ *
+ * The caller MUST verify (e.g. with `isPortBusy`) that no agent-server
+ * is currently bound to the backend port before calling this β€” there
+ * is no other reliable way to tell a stale lease from an actively
+ * renewed one.
+ *
+ * Returns the number of lease files unlinked.
+ */
+export function releaseStaleConversationLeases(conversationsDir) {
+ if (!existsSync(conversationsDir)) return 0;
+
+ let removed = 0;
+ for (const name of readdirSync(conversationsDir)) {
+ const convDir = path.join(conversationsDir, name);
+ let isDir = false;
+ try {
+ isDir = statSync(convDir).isDirectory();
+ } catch {
+ continue;
+ }
+ if (!isDir) continue;
+
+ const leasePath = path.join(convDir, "owner_lease.json");
+ if (!existsSync(leasePath)) continue;
+ try {
+ unlinkSync(leasePath);
+ removed += 1;
+ } catch {
+ // Best-effort: the new agent-server will simply skip this
+ // conversation as before. Don't fail the whole start.
+ }
+ }
+ return removed;
+}
+
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjs
new file mode 100644
index 0000000000..c00cd33ac8
--- /dev/null
+++ b/scripts/dev-static.mjs
@@ -0,0 +1,666 @@
+#!/usr/bin/env node
+/**
+ * Static-frontend Development Stack
+ *
+ * Mirrors `npm run dev` (scripts/dev-with-automation.mjs) but serves a
+ * production build of the frontend via `sirv-cli` instead of the Vite dev
+ * server. Designed for slow / flaky network situations (e.g. plane wifi)
+ * where Vite's ~1000 individual module requests per page load are the
+ * bottleneck. The static build collapses the frontend into ~50 hashed
+ * chunks that all 304 cleanly on reload.
+ *
+ * Architecture (identical to dev-with-automation, only the frontend differs):
+ * β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ * β”‚ http://localhost:8000 (Ingress Proxy) β”‚
+ * β”‚ /api/automation/* β†’ Automation Backend β”‚
+ * β”‚ /api/*, /sockets β†’ Agent Server β”‚
+ * β”‚ /* β†’ Static Frontend β”‚
+ * β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ * β”‚ β”‚ β”‚
+ * β–Ό β–Ό β–Ό
+ * β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ * β”‚ sirv-cli β”‚ β”‚ Agent Server β”‚ β”‚ Automation β”‚
+ * β”‚ build/ β”‚ β”‚ (uvx) :18000 β”‚ β”‚ Backend (uvx) β”‚
+ * β”‚ :3001 β”‚ β”‚ β”‚ β”‚ :18001 β”‚
+ * β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ *
+ * Usage:
+ * npm run dev:static
+ * npm run dev:static -- --port 12000
+ * npm run dev:static -- --skip-build # reuse an existing build/
+ * npm run dev:static -- --automation-ref feat/my-branch
+ *
+ * Environment variables (all optional, same as dev:automation):
+ * - PORT: Ingress port (default: 8000)
+ * - OH_AUTOMATION_GIT_REF: Git ref for automation (default: main)
+ * - OH_AGENT_SERVER_GIT_REF: Git ref for agent-server
+ * - OH_SECRET_KEY: Session secret key
+ */
+
+import { spawn, spawnSync, execSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { join, resolve, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { setTimeout as delay } from "node:timers/promises";
+import process from "node:process";
+
+import {
+ buildAgentServerCommand,
+ buildSafeDevConfig,
+ buildAgentServerEnv,
+ buildNpmScriptCommand,
+ formatMissingUvxGuidance,
+ isPortBusy,
+ releaseStaleConversationLeases,
+} from "./dev-safe.mjs";
+import {
+ buildAutomationCommand,
+ buildConfig,
+} from "./dev-with-automation.mjs";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const projectRoot = resolve(__dirname, "..");
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Terminal Styling
+// ═══════════════════════════════════════════════════════════════════════════
+
+const c = {
+ reset: "\x1b[0m",
+ bold: "\x1b[1m",
+ dim: "\x1b[2m",
+ red: "\x1b[31m",
+ green: "\x1b[32m",
+ yellow: "\x1b[33m",
+ blue: "\x1b[34m",
+ magenta: "\x1b[35m",
+ cyan: "\x1b[36m",
+};
+
+function logService(name, message, color = c.reset) {
+ const ts = new Date().toISOString().split("T")[1].split(".")[0];
+ console.log(`${c.dim}${ts}${c.reset} ${color}[${name}]${c.reset} ${message}`);
+}
+
+function logStep(step, message) {
+ console.log(`${c.cyan}[${step}]${c.reset} ${message}`);
+}
+
+function logSuccess(message) {
+ console.log(`${c.green}βœ“${c.reset} ${message}`);
+}
+
+function logError(message) {
+ console.error(`${c.red}βœ—${c.reset} ${message}`);
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// CLI parsing
+// ═══════════════════════════════════════════════════════════════════════════
+
+export function parseArgs(argv = process.argv.slice(2)) {
+ const config = {
+ port: null,
+ automationGitRef: null,
+ automationRepo: null,
+ skipBuild: false,
+ verbose: false,
+ };
+
+ for (let i = 0; i < argv.length; i++) {
+ switch (argv[i]) {
+ case "-p":
+ case "--port":
+ config.port = parseInt(argv[++i], 10);
+ break;
+ case "--automation-ref":
+ config.automationGitRef = argv[++i];
+ break;
+ case "--automation-repo":
+ config.automationRepo = argv[++i];
+ break;
+ case "--skip-build":
+ config.skipBuild = true;
+ break;
+ case "-v":
+ case "--verbose":
+ config.verbose = true;
+ break;
+ case "-h":
+ case "--help":
+ showHelp();
+ process.exit(0);
+ }
+ }
+
+ return config;
+}
+
+function showHelp() {
+ console.log(`
+Agent Canvas Static-frontend Development Stack
+
+Same backend stack as \`npm run dev\`, but serves a production build of the
+frontend via sirv-cli. Use this when a flaky network makes Vite's per-module
+requests painful (e.g. on a plane).
+
+USAGE:
+ npm run dev:static [-- options]
+
+OPTIONS:
+ -p, --port <port> Ingress port (default: 8000)
+ --automation-ref <ref> Git ref for automation backend (default: main)
+ --automation-repo <url> Git repo URL for automation
+ --skip-build Reuse existing build/ directory (faster restart)
+ -v, --verbose Show detailed output
+ -h, --help Show this help
+
+ENVIRONMENT VARIABLES:
+ PORT Alternative to --port
+ OH_AUTOMATION_GIT_REF Alternative to --automation-ref
+ OH_AGENT_SERVER_GIT_REF Git ref for agent-server SDK
+ OH_SECRET_KEY Secret key for sessions
+
+ACCESS POINTS:
+ Main UI: http://localhost:PORT/
+ API Docs: http://localhost:PORT/api/automation/docs
+
+NOTES:
+ β€’ The build is produced once at startup. Edit the source and rerun this
+ command (or rebuild with \`npm run build:app\`) to pick up changes.
+ β€’ The static server sends ETag headers, so reloads return 304s instead of
+ refetching content β€” much friendlier on slow links.
+`);
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Prerequisites & Setup
+// ═══════════════════════════════════════════════════════════════════════════
+
+function commandExists(cmd) {
+ try {
+ execSync(`command -v ${cmd}`, { stdio: "pipe" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function checkPrerequisites() {
+ logStep("1/3", "Checking prerequisites...");
+
+ if (!commandExists("uvx")) {
+ console.error(formatMissingUvxGuidance(projectRoot));
+ process.exit(1);
+ }
+ logSuccess("uvx found");
+
+ if (!commandExists("npm")) {
+ logError("npm is required but not found");
+ process.exit(1);
+ }
+ logSuccess("npm found");
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Build
+// ═══════════════════════════════════════════════════════════════════════════
+
+function buildFrontend(config, args) {
+ const buildDir = join(config.canvasPath, "build");
+
+ if (args.skipBuild) {
+ if (!existsSync(buildDir)) {
+ logError(
+ "--skip-build was passed but build/ does not exist. Run without --skip-build first.",
+ );
+ process.exit(1);
+ }
+ logStep("2/3", "Skipping build (--skip-build)");
+ logService("build", `Reusing existing build/ at ${buildDir}`, c.dim);
+ return;
+ }
+
+ logStep("2/3", "Building frontend (npm run build:app)...");
+ logService(
+ "build",
+ "This typically takes 30–60s; cached as build/ for --skip-build reuse",
+ c.dim,
+ );
+
+ const cmd = buildNpmScriptCommand("build:app");
+ const result = spawnSync(cmd.command, cmd.args, {
+ cwd: config.canvasPath,
+ stdio: "inherit",
+ env: {
+ ...process.env,
+ // Bake the agent-server's workspace path into the build so conversations
+ // start with the same default working directory as `npm run dev`.
+ VITE_WORKING_DIR: join(config.stateDir, "workspaces"),
+ // Bake the automation backend API key so the static frontend can talk
+ // to /api/automation through the ingress.
+ VITE_AUTOMATION_API_KEY: config.localApiKey,
+ // Intentionally do NOT set VITE_BACKEND_BASE_URL: leaving it unset makes
+ // the runtime fall back to window.location.origin (i.e. the ingress
+ // port the user is actually browsing), which keeps the build portable.
+ },
+ });
+
+ if (result.status !== 0) {
+ logError(`Build failed with exit code ${result.status ?? "null"}`);
+ process.exit(result.status ?? 1);
+ }
+
+ if (!existsSync(join(buildDir, "index.html"))) {
+ logError(
+ `Build completed but ${join(buildDir, "index.html")} is missing. ` +
+ `Did react-router build write somewhere unexpected?`,
+ );
+ process.exit(1);
+ }
+
+ logSuccess("Build complete");
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Process Management
+// ═══════════════════════════════════════════════════════════════════════════
+
+const processes = new Map();
+let shuttingDown = false;
+
+function spawnService(name, command, args, options = {}) {
+ const proc = spawn(command, args, {
+ stdio: ["ignore", "pipe", "pipe"],
+ env: { ...process.env, ...options.env },
+ cwd: options.cwd,
+ shell: process.platform === "win32",
+ });
+
+ const color = options.color || c.reset;
+
+ proc.stdout.on("data", (data) => {
+ data
+ .toString()
+ .split("\n")
+ .filter(Boolean)
+ .forEach((line) => logService(name, line.trim(), color));
+ });
+
+ proc.stderr.on("data", (data) => {
+ data
+ .toString()
+ .split("\n")
+ .filter(Boolean)
+ .forEach((line) => logService(name, line.trim(), c.yellow));
+ });
+
+ proc.on("error", (error) => {
+ logError(`${name} failed to start: ${error.message}`);
+ });
+
+ proc.on("exit", (code) => {
+ if (code !== 0 && code !== null && !shuttingDown) {
+ logService(name, `Exited with code ${code}`, c.red);
+ }
+ processes.delete(name);
+ });
+
+ processes.set(name, proc);
+ return proc;
+}
+
+async function waitForService(name, url, timeoutMs = 30000) {
+ const start = Date.now();
+
+ while (Date.now() - start < timeoutMs) {
+ try {
+ const res = await fetch(url);
+ if (res.ok) {
+ logService(name, `Ready at ${url}`, c.green);
+ return true;
+ }
+ } catch {
+ // Keep trying
+ }
+ await delay(500);
+ }
+
+ logService(name, `Timeout waiting for ${url}`, c.red);
+ return false;
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Service Starters (agent-server + automation are byte-for-byte the same as
+// dev-with-automation; the only difference is the frontend service.)
+// ═══════════════════════════════════════════════════════════════════════════
+
+function startAgentServer(config) {
+ logService(
+ "agent-server",
+ `Starting on port ${config.agentServerPort}...`,
+ c.blue,
+ );
+
+ const agentServerCmd = buildAgentServerCommand(process.env);
+ logService("agent-server", `Using ${agentServerCmd.source}`, c.dim);
+
+ const safeConfig = buildSafeDevConfig(config.canvasPath, {
+ ...process.env,
+ OH_CANVAS_SAFE_STATE_DIR: config.stateDir,
+ OH_CANVAS_SAFE_BACKEND_PORT: config.agentServerPort.toString(),
+ OH_CANVAS_SAFE_VSCODE_PORT: config.vscodePort.toString(),
+ });
+
+ const agentServerEnv = buildAgentServerEnv(safeConfig);
+
+ spawnService(
+ "agent-server",
+ agentServerCmd.command,
+ [
+ ...agentServerCmd.args,
+ "--host",
+ "0.0.0.0",
+ "--port",
+ String(config.agentServerPort),
+ ],
+ {
+ cwd: safeConfig.workspacesPath,
+ env: agentServerEnv,
+ color: c.blue,
+ },
+ );
+}
+
+function startAutomationBackend(config) {
+ logService(
+ "automation",
+ `Starting on port ${config.autoBackendPort}...`,
+ c.green,
+ );
+
+ const automationCmd = buildAutomationCommand(process.env);
+ logService("automation", `Using ${automationCmd.source}`, c.dim);
+
+ spawnService(
+ "automation",
+ automationCmd.command,
+ [
+ ...automationCmd.args,
+ "--host",
+ "0.0.0.0",
+ "--port",
+ config.autoBackendPort.toString(),
+ ],
+ {
+ cwd: config.stateDir,
+ env: {
+ AUTOMATION_AGENT_SERVER_URL: `http://localhost:${config.agentServerPort}`,
+ AUTOMATION_DB_URL: `sqlite+aiosqlite:///${join(config.stateDir, "automations.db")}`,
+ AUTOMATION_BASE_URL: `http://localhost:${config.ingressPort}`,
+ AUTOMATION_WORKSPACE_BASE: join(config.stateDir, "workspaces"),
+ AUTOMATION_LOCAL_API_KEY: config.localApiKey,
+ AUTOMATION_CORS_ORIGINS: `http://localhost:${config.ingressPort},http://127.0.0.1:${config.ingressPort},http://localhost:3001,http://127.0.0.1:3001`,
+ FILE_STORE: "local",
+ LOCAL_STORAGE_PATH: join(config.stateDir, "storage"),
+ OPENHANDS_SUPPRESS_BANNER: "1",
+ },
+ color: c.green,
+ },
+ );
+}
+
+function startStaticServer(config) {
+ // Reuse `vitePort` as the upstream port name so the ingress route table
+ // below stays identical to dev-with-automation.mjs.
+ logService("static", `Starting on port ${config.vitePort}...`, c.magenta);
+
+ // Mirror the proxy targets that vite.config.ts exposes in dev mode so that
+ // hitting :3001 directly behaves like Vite's dev server (e.g. /server_info
+ // is forwarded to the agent-server instead of falling back to the SPA
+ // shell). Without this, /server_info on :3001 returns index.html.
+ const staticServerScript = join(projectRoot, "scripts", "static-server.mjs");
+ spawnService(
+ "static",
+ "node",
+ [
+ staticServerScript,
+ "--dir",
+ join(config.canvasPath, "build"),
+ "--host",
+ "0.0.0.0",
+ "--port",
+ String(config.vitePort),
+ "--route",
+ `/api/automation=http://localhost:${config.autoBackendPort}`,
+ "--route",
+ `/api=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/sockets=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/server_info=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/health=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/ready=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/alive=http://localhost:${config.agentServerPort}`,
+ ],
+ {
+ cwd: config.canvasPath,
+ color: c.magenta,
+ },
+ );
+}
+
+function startIngress(config) {
+ logService("ingress", `Starting on port ${config.ingressPort}...`, c.yellow);
+
+ const ingressScript = join(projectRoot, "scripts", "ingress.mjs");
+
+ spawnService(
+ "ingress",
+ "node",
+ [
+ ingressScript,
+ "--port",
+ config.ingressPort.toString(),
+ "--route",
+ `/api/automation=http://localhost:${config.autoBackendPort}`,
+ "--route",
+ `/api=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/sockets=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/server_info=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/health=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/ready=http://localhost:${config.agentServerPort}`,
+ "--route",
+ `/alive=http://localhost:${config.agentServerPort}`,
+ "--default",
+ `http://localhost:${config.vitePort}`,
+ ],
+ {
+ cwd: projectRoot,
+ color: c.yellow,
+ },
+ );
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Shutdown / Banner
+// ═══════════════════════════════════════════════════════════════════════════
+
+function shutdown() {
+ if (shuttingDown) return;
+ shuttingDown = true;
+
+ console.log("");
+ console.log(`${c.yellow}Shutting down...${c.reset}`);
+
+ for (const [name, proc] of processes) {
+ logService(name, "Stopping...", c.dim);
+ proc.kill("SIGTERM");
+ }
+
+ setTimeout(() => {
+ for (const [, proc] of processes) {
+ if (!proc.killed) {
+ proc.kill("SIGKILL");
+ }
+ }
+ process.exit(0);
+ }, 3000);
+}
+
+process.on("SIGINT", shutdown);
+process.on("SIGTERM", shutdown);
+
+function printBanner(config) {
+ console.log("");
+ console.log(
+ `${c.green}${c.bold}╔══════════════════════════════════════════════════════════════╗${c.reset}`,
+ );
+ console.log(
+ `${c.green}${c.bold}β•‘${c.reset} ${c.bold}Agent Canvas Static-frontend Stack${c.reset} ${c.green}${c.bold}β•‘${c.reset}`,
+ );
+ console.log(
+ `${c.green}${c.bold}╠══════════════════════════════════════════════════════════════╣${c.reset}`,
+ );
+ console.log(
+ `${c.green}${c.bold}β•‘${c.reset} ${c.green}${c.bold}β•‘${c.reset}`,
+ );
+ console.log(
+ `${c.green}${c.bold}β•‘${c.reset} Main UI: ${c.cyan}http://localhost:${config.ingressPort}/${c.reset}`.padEnd(
+ 75,
+ ) + `${c.green}${c.bold}β•‘${c.reset}`,
+ );
+ console.log(
+ `${c.green}${c.bold}β•‘${c.reset} API Docs: ${c.cyan}http://localhost:${config.ingressPort}/api/automation/docs${c.reset}`.padEnd(
+ 75,
+ ) + `${c.green}${c.bold}β•‘${c.reset}`,
+ );
+ console.log(
+ `${c.green}${c.bold}β•‘${c.reset} ${c.green}${c.bold}β•‘${c.reset}`,
+ );
+ console.log(
+ `${c.green}${c.bold}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${c.reset}`,
+ );
+ console.log("");
+ console.log(`${c.dim}State directory: ${config.stateDir}${c.reset}`);
+ console.log(
+ `${c.dim}Frontend served from: ${join(config.canvasPath, "build")}${c.reset}`,
+ );
+ console.log(
+ `${c.dim}Edit sources, then re-run \`npm run dev:static\` to rebuild.${c.reset}`,
+ );
+ console.log(`${c.dim}Press Ctrl+C to stop${c.reset}`);
+ console.log("");
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Main
+// ═══════════════════════════════════════════════════════════════════════════
+
+async function main() {
+ const args = parseArgs();
+ const config = buildConfig(args);
+
+ console.log("");
+ console.log(
+ `${c.cyan}${c.bold}Agent Canvas Static-frontend Development Stack${c.reset}`,
+ );
+ console.log("");
+
+ // Setup phase (1/3)
+ checkPrerequisites();
+
+ // Ensure isolated state dirs (same as dev-with-automation).
+ const { mkdirSync } = await import("node:fs");
+ for (const dir of [
+ config.stateDir,
+ join(config.stateDir, "tmux"),
+ join(config.stateDir, "conversations"),
+ join(config.stateDir, "workspaces"),
+ join(config.stateDir, "bash_events"),
+ join(config.stateDir, "storage"),
+ ]) {
+ mkdirSync(dir, { recursive: true });
+ }
+
+ // Build phase (2/3): block until the SPA is ready to serve.
+ buildFrontend(config, args);
+
+ // Service phase (3/3)
+ logStep("3/3", "Starting services...");
+
+ // The agent-server skip-loads any conversation whose `owner_lease.json`
+ // is held by a different `owner_instance_id` and not yet expired (45 s
+ // TTL). If a previous agent-server (e.g. from `npm run dev`) was killed
+ // ungracefully β€” or we restart faster than the lease TTL β€” every
+ // conversation gets hidden until those stale leases age out, which
+ // looks like "the new agent-server doesn't inherit my conversations".
+ // Bail out if a live agent-server is already bound to our port (we'd
+ // collide anyway), otherwise unlink the stale leases so the new server
+ // can claim ownership immediately.
+ if (await isPortBusy(config.agentServerPort)) {
+ logError(
+ `Port ${config.agentServerPort} is already in use β€” another ` +
+ `agent-server is running. Stop it (e.g. quit \`npm run dev\`) ` +
+ `before running dev:static.`,
+ );
+ process.exit(1);
+ }
+ const conversationsPath = join(config.stateDir, "conversations");
+ const cleared = releaseStaleConversationLeases(conversationsPath);
+ if (cleared > 0) {
+ logService(
+ "agent-server",
+ `Released ${cleared} stale conversation lease(s) so the new ` +
+ `agent-server can resume ownership.`,
+ c.dim,
+ );
+ }
+
+ startAgentServer(config);
+ await waitForService(
+ "agent-server",
+ `http://localhost:${config.agentServerPort}/server_info`,
+ );
+
+ startAutomationBackend(config);
+
+ startStaticServer(config);
+
+ await delay(2000);
+
+ startIngress(config);
+
+ await delay(1000);
+
+ printBanner(config);
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Exports for testing
+// ═══════════════════════════════════════════════════════════════════════════
+
+export { buildFrontend, startStaticServer };
+
+// ═══════════════════════════════════════════════════════════════════════════
+// Main entry point (only when run directly, not when imported)
+// ═══════════════════════════════════════════════════════════════════════════
+
+const isMainModule = import.meta.url === `file://${process.argv[1]}`;
+
+if (isMainModule) {
+ main().catch((err) => {
+ logError(`Fatal error: ${err.message}`);
+ if (err.stack) {
+ console.error(c.dim + err.stack + c.reset);
+ }
+ process.exit(1);
+ });
+}
diff --git a/scripts/static-server.mjs b/scripts/static-server.mjs
new file mode 100644
index 0000000000..1fe8d29a79
--- /dev/null
+++ b/scripts/static-server.mjs
@@ -0,0 +1,421 @@
+#!/usr/bin/env node
+/**
+ * Combined static file server + reverse proxy.
+ *
+ * Replaces `sirv-cli` for `npm run dev:static`. The reason a plain static
+ * server is not enough: Vite's dev server (used by `npm run dev`) configures
+ * a proxy for `/api`, `/sockets`, `/server_info`, `/alive`, `/health`,
+ * `/ready` (see vite.config.ts) so requests to those paths are forwarded to
+ * the agent-server even when the browser is hitting Vite directly on :3001.
+ * sirv-cli has no proxy support, so under `--single` it falls back to
+ * index.html for any of those paths β€” making `/server_info` look like HTML
+ * to the SPA when the user hits the static port directly (e.g. via a tunnel
+ * that exposes :3001).
+ *
+ * This script provides Vite-equivalent behaviour: serve static files from
+ * --dir, fall back to index.html for HTML navigations, and reverse-proxy
+ * configured prefixes to upstream backends. The proxy + WebSocket logic is
+ * deliberately kept identical in spirit to scripts/ingress.mjs so the two
+ * servers route the same way.
+ *
+ * Usage (mirrors scripts/ingress.mjs's --route flag style):
+ * node scripts/static-server.mjs \
+ * --port 3001 --host 0.0.0.0 --dir build \
+ * --route "/api/automation=http://localhost:18001" \
+ * --route "/api=http://localhost:18000" \
+ * --route "/server_info=http://localhost:18000" \
+ * --route "/sockets=http://localhost:18000"
+ */
+
+import { createServer, request as httpRequest } from "node:http";
+import { createReadStream } from "node:fs";
+import { stat } from "node:fs/promises";
+import { extname, normalize, resolve } from "node:path";
+import process from "node:process";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// MIME types
+// ─────────────────────────────────────────────────────────────────────────────
+
+const MIME = {
+ ".html": "text/html; charset=utf-8",
+ ".js": "application/javascript; charset=utf-8",
+ ".mjs": "application/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".json": "application/json; charset=utf-8",
+ ".svg": "image/svg+xml",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".ico": "image/x-icon",
+ ".webp": "image/webp",
+ ".woff": "font/woff",
+ ".woff2": "font/woff2",
+ ".ttf": "font/ttf",
+ ".wav": "audio/wav",
+ ".mp3": "audio/mpeg",
+ ".webmanifest": "application/manifest+json",
+ ".txt": "text/plain; charset=utf-8",
+ ".xml": "application/xml",
+ ".map": "application/json",
+};
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Args
+// ─────────────────────────────────────────────────────────────────────────────
+
+export function parseArgs(argv = process.argv.slice(2)) {
+ const config = {
+ port: 3001,
+ host: "0.0.0.0",
+ dir: "build",
+ routes: {},
+ };
+
+ for (let i = 0; i < argv.length; i++) {
+ const flag = argv[i];
+ switch (flag) {
+ case "-p":
+ case "--port":
+ config.port = Number.parseInt(argv[++i], 10);
+ break;
+ case "-H":
+ case "--host":
+ config.host = argv[++i];
+ break;
+ case "-d":
+ case "--dir":
+ config.dir = argv[++i];
+ break;
+ case "-r":
+ case "--route": {
+ const value = argv[++i];
+ const eq = value.indexOf("=");
+ if (eq < 0) {
+ throw new Error(`Invalid --route (expected /prefix=url): ${value}`);
+ }
+ const prefix = value.slice(0, eq);
+ const url = value.slice(eq + 1);
+ if (!prefix.startsWith("/")) {
+ throw new Error(`--route prefix must start with '/': ${prefix}`);
+ }
+ config.routes[prefix] = url;
+ break;
+ }
+ case "-h":
+ case "--help":
+ showHelp();
+ process.exit(0);
+ default:
+ throw new Error(`Unknown flag: ${flag}`);
+ }
+ }
+
+ return config;
+}
+
+function showHelp() {
+ console.log(`
+Combined static file server + reverse proxy.
+
+USAGE:
+ node scripts/static-server.mjs [options]
+
+OPTIONS:
+ -p, --port <port> Port to bind (default: 3001)
+ -H, --host <host> Hostname to bind (default: 0.0.0.0)
+ -d, --dir <dir> Directory to serve (default: build)
+ -r, --route <prefix=url> Proxy <prefix> (and subpaths) to <url>;
+ may be repeated. WebSockets supported.
+ -h, --help Show this help
+
+ROUTING:
+ β€’ Routes are matched by longest prefix first (most-specific wins).
+ β€’ Anything that does not match a route is served from --dir.
+ β€’ Unknown paths fall back to index.html (SPA mode), unless they look
+ like an asset request (have a known file extension), in which case
+ a 404 is returned.
+`);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Router (kept structurally identical to scripts/ingress.mjs)
+// ─────────────────────────────────────────────────────────────────────────────
+
+export function createRouter(routes) {
+ const sortedRoutes = Object.entries(routes).sort(
+ ([a], [b]) => b.length - a.length,
+ );
+
+ return function route(url) {
+ for (const [prefix, backend] of sortedRoutes) {
+ if (
+ url === prefix ||
+ url.startsWith(prefix + "/") ||
+ url.startsWith(prefix + "?")
+ ) {
+ return backend;
+ }
+ }
+ return null;
+ };
+}
+
+function parseBackendUrl(backendUrl) {
+ const url = new URL(backendUrl);
+ return {
+ hostname: url.hostname,
+ port:
+ Number.parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80),
+ protocol: url.protocol,
+ };
+}
+
+function proxyRequest(req, res, backendUrl) {
+ const backend = parseBackendUrl(backendUrl);
+
+ const proxyReq = httpRequest(
+ {
+ hostname: backend.hostname,
+ port: backend.port,
+ path: req.url,
+ method: req.method,
+ headers: {
+ ...req.headers,
+ host: `${backend.hostname}:${backend.port}`,
+ },
+ },
+ (proxyRes) => {
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
+ proxyRes.pipe(res, { end: true });
+ },
+ );
+
+ proxyReq.on("error", (err) => {
+ console.error(`Proxy error for ${req.url} -> ${backendUrl}:`, err.message);
+ if (!res.headersSent) {
+ res.writeHead(502);
+ res.end(`Bad Gateway: ${err.message}`);
+ }
+ });
+
+ req.pipe(proxyReq, { end: true });
+}
+
+function proxyWebSocket(req, socket, head, backendUrl) {
+ const backend = parseBackendUrl(backendUrl);
+
+ const proxyReq = httpRequest({
+ hostname: backend.hostname,
+ port: backend.port,
+ path: req.url,
+ method: req.method,
+ headers: {
+ ...req.headers,
+ host: `${backend.hostname}:${backend.port}`,
+ },
+ });
+
+ proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
+ socket.write(
+ `HTTP/${proxyRes.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`,
+ );
+ for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
+ socket.write(
+ `${proxyRes.rawHeaders[i]}: ${proxyRes.rawHeaders[i + 1]}\r\n`,
+ );
+ }
+ socket.write("\r\n");
+ if (proxyHead.length > 0) {
+ socket.write(proxyHead);
+ }
+ proxySocket.pipe(socket, { end: true });
+ socket.pipe(proxySocket, { end: true });
+ });
+
+ proxyReq.on("error", (err) => {
+ console.error(
+ `WebSocket proxy error for ${req.url} -> ${backendUrl}:`,
+ err.message,
+ );
+ socket.destroy();
+ });
+
+ proxyReq.end();
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Static file serving
+// ─────────────────────────────────────────────────────────────────────────────
+
+async function tryStat(path) {
+ try {
+ const result = await stat(path);
+ return result.isFile() ? result : null;
+ } catch {
+ return null;
+ }
+}
+
+function makeEtag(stats) {
+ // Match sirv's weak-ETag format: W/"<size>-<mtime ms>"
+ return `W/"${stats.size}-${Math.floor(stats.mtimeMs)}"`;
+}
+
+function pickContentType(filePath) {
+ return MIME[extname(filePath).toLowerCase()] || "application/octet-stream";
+}
+
+function pickCacheControl(urlPath) {
+ // Vite/react-router builds emit content-hashed assets under /assets/.
+ // Those are safe to cache forever; everything else (index.html, public/
+ // copies, locales) should revalidate so a rebuild is picked up.
+ if (urlPath.startsWith("/assets/")) {
+ return "public, max-age=31536000, immutable";
+ }
+ return "no-cache";
+}
+
+function looksLikeAssetRequest(urlPath) {
+ // If the last path segment has a known file extension, treat 404s as 404
+ // instead of falling back to the SPA shell. Avoids serving index.html for
+ // missing /favicon.ico, missing source maps, etc.
+ const last = urlPath.split("/").pop() ?? "";
+ const ext = extname(last).toLowerCase();
+ return Boolean(ext) && ext in MIME;
+}
+
+async function serveFile(req, res, filePath, urlPath) {
+ const stats = await tryStat(filePath);
+ if (!stats) return false;
+
+ const etag = makeEtag(stats);
+ if (req.headers["if-none-match"] === etag) {
+ res.writeHead(304, { ETag: etag });
+ res.end();
+ return true;
+ }
+
+ res.writeHead(200, {
+ "Content-Type": pickContentType(filePath),
+ "Content-Length": stats.size,
+ "Cache-Control": pickCacheControl(urlPath),
+ ETag: etag,
+ });
+
+ if (req.method === "HEAD") {
+ res.end();
+ return true;
+ }
+
+ createReadStream(filePath).pipe(res);
+ return true;
+}
+
+async function handleStatic(req, res, dirAbs) {
+ const rawPath = req.url.split("?")[0];
+ let urlPath;
+ try {
+ urlPath = decodeURIComponent(rawPath);
+ } catch {
+ res.writeHead(400);
+ res.end("Bad Request");
+ return;
+ }
+
+ const safe = normalize(urlPath);
+ let filePath = resolve(dirAbs, "." + safe);
+ if (filePath !== dirAbs && !filePath.startsWith(dirAbs + "/")) {
+ res.writeHead(403);
+ res.end("Forbidden");
+ return;
+ }
+
+ // Directory request -> /index.html
+ if (urlPath.endsWith("/")) {
+ filePath = resolve(filePath, "index.html");
+ }
+
+ if (await serveFile(req, res, filePath, urlPath)) return;
+
+ // SPA fallback: only for non-asset requests, and not for non-GET/HEAD.
+ if (
+ (req.method === "GET" || req.method === "HEAD") &&
+ !looksLikeAssetRequest(urlPath)
+ ) {
+ const indexPath = resolve(dirAbs, "index.html");
+ if (await serveFile(req, res, indexPath, "/")) return;
+ }
+
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
+ res.end("Not Found");
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Server
+// ─────────────────────────────────────────────────────────────────────────────
+
+export function startStaticServer(config) {
+ const route = createRouter(config.routes);
+ const dirAbs = resolve(config.dir);
+
+ const server = createServer((req, res) => {
+ const backend = route(req.url);
+ if (backend) {
+ proxyRequest(req, res, backend);
+ return;
+ }
+ handleStatic(req, res, dirAbs).catch((err) => {
+ console.error(`Static handler error for ${req.url}:`, err);
+ if (!res.headersSent) {
+ res.writeHead(500);
+ res.end("Internal Server Error");
+ }
+ });
+ });
+
+ server.on("upgrade", (req, socket, head) => {
+ const backend = route(req.url);
+ if (backend) {
+ proxyWebSocket(req, socket, head, backend);
+ return;
+ }
+ socket.destroy();
+ });
+
+ return new Promise((resolveListen) => {
+ server.listen(config.port, config.host, () => {
+ console.log("");
+ console.log(
+ `Static-server + proxy listening on http://${config.host}:${config.port}/`,
+ );
+ console.log(` Static dir: ${dirAbs}`);
+ const sortedRoutes = Object.entries(config.routes).sort(
+ ([a], [b]) => b.length - a.length,
+ );
+ for (const [prefix, backend] of sortedRoutes) {
+ console.log(` ${prefix} -> ${backend}`);
+ }
+ console.log(" * (default) -> static files + SPA fallback");
+ console.log("");
+ resolveListen(server);
+ });
+ });
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Main
+// ─────────────────────────────────────────────────────────────────────────────
+
+const isMainModule = import.meta.url === `file://${process.argv[1]}`;
+
+if (isMainModule) {
+ try {
+ const config = parseArgs();
+ await startStaticServer(config);
+ } catch (err) {
+ console.error(err instanceof Error ? err.message : err);
+ process.exit(1);
+ }
+}