Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Default user launchers to static frontend (#434)

Graham Neubiga4089e0e4a24
diff --git a/.gitignore b/.gitignore
index 3db9526adc..b262bd3976 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,6 +5,7 @@ src/i18n/declaration.ts
.envrc
node_modules/
build/
+logs/
/.tmp/live-e2e-state/
dist/
diff --git a/AGENTS.md b/AGENTS.md
index a95cd7f7e2..48b4d23fa5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -135,7 +135,7 @@
- `BackendSelector`'s cloud-org switch paths should never rethrow from the dropdown `onChange` handler: unexpected non-Axios failures need a generic error toast instead of an unhandled promise rejection, and the malformed `(cloud backend, null org)` self-heal path should fall back to the bundled backend if `/switch` fails.
- `NewConversationButton` should support keyboard dismissal (`Escape`) for its inline popover, while still keeping the popover open when its modal children (`FolderBrowserModal`, `ManageWorkspacesModal`) are active.
-- README expectation: keep the first section as a concrete, chronological from-scratch quickstart for running this frontend against a real `openhands-agent-server` (clone, install uv, optional `.env`, run `npm run dev`).
+- README expectation: keep the first section as a concrete, chronological from-scratch quickstart for running this frontend against a real `openhands-agent-server` (clone, install prerequisites, optional `.env`, run `npm run dev:docker` or `npm run dev:dangerously-dockerless`).
- Keep README user-focused and move contributor/developer-specific workflows (`dev:safe`, mock mode, detailed env vars/build-test notes) into `DEVELOPMENT.md`.
- `scripts/dev-safe.mjs` uses `uvx` for temporary agent-server installation β€” no permanent `uv tool install` needed. Environment variables (highest precedence first):
- `OH_AGENT_SERVER_LOCAL_PATH` β€” absolute path to a local `software-agent-sdk` checkout. Runs the local checkout via `uvx` with `--with-editable` for `openhands-sdk`/`openhands-tools`/`openhands-workspace` and `--reinstall` for `openhands-agent-server`, so SDK edits are picked up on restart. Highest precedence.
@@ -144,7 +144,7 @@
- `OH_SECRET_KEY` β€” secret key for settings encryption; uses a static default for local dev since it's needed for reading persisted encrypted values across restarts
- `SESSION_API_KEY` / `OH_SESSION_API_KEYS_0` / `VITE_SESSION_API_KEY` β€” session API key for agent-server authentication; auto-generated using `crypto.randomBytes(32)` if not set, passed to both agent-server (`OH_SESSION_API_KEYS_0`) and frontend (`VITE_SESSION_API_KEY`)
- Default: released PyPI version `1.22.0` for agent-server SDK libraries
-- `scripts/dev-docker.mjs` runs the agent-server inside a Docker container instead of via `uvx`. The default image uses versioned release tags:
+- `scripts/dev-docker.mjs` runs the agent-server inside a Docker container instead of via `uvx`, and serves a static frontend build by default for stable user/tunnel access. Use `npm run dev:docker:dynamic` or `node scripts/dev-docker.mjs --dynamic` for the Vite dev server. The default image uses versioned release tags:
- `DEFAULT_AGENT_SERVER_TAG` β€” uses format `{version}-python` (e.g., `1.22.0-python`) for reproducibility. Note: the SDK build script strips the "v" prefix from semver release tags.
- Should stay in sync with `DEFAULT_AGENT_SERVER_VERSION` in `dev-safe.mjs` for consistency between Docker and non-Docker dev modes
- `OH_AGENT_SERVER_GIT_REF` β€” override to use a git ref-based tag (e.g., `main` β†’ `main-python`, `abc1234` β†’ `abc1234-python`)
@@ -154,11 +154,11 @@
- `AUTOMATION_LOCAL_API_KEY` β€” 64-character hex for automation backend auth; auto-generated per session unless overridden
- `OH_SECRET_KEY` β€” kept as a static default because it's used for encrypting/decrypting persisted settings values and needs consistency across restarts
- `scripts/dev-safe.mjs` should fail fast if `uvx` cannot be spawned (for example missing PATH entries).
-- `npm run dev` now runs the full stack with automation by default (via `dev:automation`). Use `npm run dev:minimal` for agent-server + Vite only.
-- `scripts/dev-with-automation.mjs` runs the full stack: agent-server, automation backend (both via uvx), Vite dev server, and ingress proxy. Uses a standalone ingress proxy (`scripts/ingress.mjs`) to route traffic:
+- `npm run dev` now runs the Docker full stack with automation and a static frontend by default (via `dev:docker`). `npm run dev:dangerously-dockerless` does the same without Docker through the `dev-static.mjs` launcher. Use `npm run dev:docker:dynamic` or `npm run dev:dangerously-dockerless:dynamic` for Vite/HMR.
+- `scripts/dev-with-automation.mjs` runs the full stack: agent-server, automation backend (both via uvx), frontend server, and ingress proxy. It defaults to Vite when run directly, supports `--static` for an existing build, and supports `--dynamic` so wrappers that default static can opt back into Vite. Uses a standalone ingress proxy (`scripts/ingress.mjs`) to route traffic:
- `/api/automation/*` β†’ automation backend (:18001)
- `/api/*`, `/sockets`, etc. β†’ agent server (:18000)
- - `/*` (default) β†’ Vite dev server (:3001)
+ - `/*` (default) β†’ frontend server (:3001), either Vite or static depending on launcher mode
- Environment variables: `PORT` (ingress port, default: 8000), `OH_AUTOMATION_GIT_REF` (git ref, overrides default version), `OH_AUTOMATION_VERSION` (default: `1.0.0a2`), `AUTOMATION_LOCAL_API_KEY` (optional, use a fixed key; default: auto-generated random key per session)
- Access points: `http://localhost:8000/` (main UI), `http://localhost:8000/api/automation/docs` (API docs)
- Security: `AUTOMATION_LOCAL_API_KEY` is auto-generated using `crypto.randomBytes(32)` on each startup for better security isolation. Set the env var explicitly to use a consistent key across restarts. The cipher key (`OH_SECRET_KEY`) keeps a static default for local dev since it's used for encrypting/decrypting persisted settings values.
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index c3d139bfc9..e6b848b822 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -4,15 +4,30 @@ This document is for contributors working on `agent-canvas` itself.
## Recommended local workflow
-The default development command is:
+The README quickstart commands (`npm run dev`, `npm run dev:docker`, and
+`npm run dev:dangerously-dockerless`) serve a static frontend build by default.
+Use them for user-like local testing, remote access, and tunnels such as ngrok.
+
+When you are editing the Agent Canvas frontend and want Vite live reload, use a
+dynamic command explicitly:
```sh
-npm run dev
+npm run dev:docker:dynamic
```
-This is an alias for `npm run dev:safe`.
+For a dockerless frontend/backend dev loop:
+
+```sh
+npm run dev:dangerously-dockerless:dynamic
+```
-It uses `uvx` to run a temporary `agent-server` installation for this checkout on `127.0.0.1:18000` and points the frontend at it. It isolates conversation persistence by setting separate `OH_CONVERSATIONS_PATH`, `OH_BASH_EVENTS_DIR`, and `OH_VSCODE_PORT` values under `.openhands-dev/`, and places tmux sockets under `/tmp` (via `TMUX_TMPDIR`) to avoid filesystem-support issues with mounted volumes, so it does not collide with other local or cloud-backed OpenHands sessions.
+The dockerless dynamic stack uses `uvx` to run a temporary `agent-server`
+installation on `127.0.0.1:18000` and points the frontend at it. It isolates
+conversation persistence by setting separate `OH_CONVERSATIONS_PATH`,
+`OH_BASH_EVENTS_DIR`, and `OH_VSCODE_PORT` values under `.openhands-dev/`, and
+places tmux sockets under `/tmp` (via `TMUX_TMPDIR`) to avoid filesystem-support
+issues with mounted volumes, so it does not collide with other local or
+cloud-backed OpenHands sessions.
### Environment Variables
@@ -38,20 +53,18 @@ Access at `http://localhost:3001/`
By default, the latest released version from PyPI is used. You can override this (highest precedence first):
```sh
-# Run against a local software-agent-sdk checkout. Workspace packages
-# (openhands-sdk, openhands-tools, openhands-workspace) are installed editable
-# so source edits there are picked up on restart. Highest precedence.
-OH_AGENT_SERVER_LOCAL_PATH=/abs/path/to/software-agent-sdk npm run dev
+# Run against a local software-agent-sdk checkout.
+OH_AGENT_SERVER_LOCAL_PATH=/abs/path/to/software-agent-sdk npm run dev:docker
# Use a git branch or commit (takes precedence over version)
-OH_AGENT_SERVER_GIT_REF=main npm run dev
-OH_AGENT_SERVER_GIT_REF=abc1234 npm run dev
+OH_AGENT_SERVER_GIT_REF=main npm run dev:docker
+OH_AGENT_SERVER_GIT_REF=abc1234 npm run dev:docker
# Use a specific PyPI version
-OH_AGENT_SERVER_VERSION=1.18.0 npm run dev
+OH_AGENT_SERVER_VERSION=1.18.0 npm run dev:dangerously-dockerless
```
-`OH_AGENT_SERVER_LOCAL_PATH` must be an absolute path to a `software-agent-sdk` checkout containing the `openhands-agent-server`, `openhands-sdk`, `openhands-tools`, and `openhands-workspace` workspace packages. The agent-server itself is rebuilt from local source on each `npm run dev` start (`uvx --reinstall`); the other workspace packages are installed editable, so their source changes take effect without a rebuild.
+`OH_AGENT_SERVER_LOCAL_PATH` must be an absolute path to a `software-agent-sdk` checkout containing the `openhands-agent-server`, `openhands-sdk`, `openhands-tools`, and `openhands-workspace` workspace packages. In docker mode it is bind-mounted into the container and installed editable before the server starts. In dockerless mode the agent-server itself is rebuilt from local source on each start (`uvx --reinstall`); the other workspace packages are installed editable, so their source changes take effect without a rebuild.
### Other useful overrides
diff --git a/README.md b/README.md
index 000a7de26a..500158ffcf 100644
--- a/README.md
+++ b/README.md
@@ -44,7 +44,9 @@ npm install
npm run dev:docker
```
-Windows PowerShell exception: if `npm run dev:docker` starts the backend but `localhost:8000` shows Bad Gateway and the logs include a Vite error like `'C:\Program' is not recognized`, start the same stack directly with Node instead. Replace the path below with your projects folder, and do not include any prompt characters or a trailing `>` in the value.
+This serves a static production build of the frontend behind the local ingress proxy. That is the recommended mode for normal use, remote access, and tunnels such as ngrok because it avoids Vite hot-reload restarts and large dev-module request bursts. If you are developing the Agent Canvas frontend itself and want live reload, use `npm run dev:docker:dynamic` instead.
+
+Windows PowerShell exception: if `npm run dev:docker` starts the backend but `localhost:8000` shows Bad Gateway, start the same stack directly with Node instead. Replace the path below with your projects folder, and do not include any prompt characters or a trailing `>` in the value.
```powershell
$env:PROJECT_PATH = "/path/to/your/projects"
@@ -80,10 +82,10 @@ npm run dev:dangerously-dockerless
Access the UI at [http://localhost:8000](http://localhost:8000)
-If you're not actively developing on agent-canvas and just want to run it locally, use the static build instead (faster loads, no hot reload):
+This also serves a static production build for stability. If you are developing the Agent Canvas frontend itself and want live reload, use the dynamic dockerless command instead:
```sh
-npm run dev:static
+npm run dev:dangerously-dockerless:dynamic
```
# Architecture
diff --git a/__tests__/api/backend-registry/storage.test.ts b/__tests__/api/backend-registry/storage.test.ts
index b02577eb11..8fab5f0ebd 100644
--- a/__tests__/api/backend-registry/storage.test.ts
+++ b/__tests__/api/backend-registry/storage.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
ACTIVE_BACKEND_STORAGE_KEY,
BACKENDS_STORAGE_KEY,
@@ -11,6 +11,7 @@ import type { Backend } from "#/api/backend-registry/types";
afterEach(() => {
window.localStorage.clear();
+ vi.unstubAllEnvs();
});
describe("backend-registry storage", () => {
@@ -91,6 +92,57 @@ describe("backend-registry storage", () => {
]);
});
+ it("fills a missing API key on the default Local backend from env defaults", () => {
+ vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key");
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ {
+ id: "default-local",
+ name: "Local",
+ host: window.location.origin,
+ apiKey: "",
+ kind: "local",
+ },
+ ]),
+ );
+
+ const result = readStoredBackends();
+
+ expect(result[0]).toMatchObject({
+ id: "default-local",
+ apiKey: "fresh-session-key",
+ });
+ expect(
+ JSON.parse(window.localStorage.getItem(BACKENDS_STORAGE_KEY)!)[0],
+ ).toMatchObject({
+ id: "default-local",
+ apiKey: "fresh-session-key",
+ });
+ });
+
+ it("does not fill the default Local backend API key after its host is edited", () => {
+ vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key");
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ {
+ id: "default-local",
+ name: "Local",
+ host: "http://127.0.0.1:9999",
+ apiKey: "",
+ kind: "local",
+ },
+ ]),
+ );
+
+ expect(readStoredBackends()[0]).toMatchObject({
+ id: "default-local",
+ host: "http://127.0.0.1:9999",
+ apiKey: "",
+ });
+ });
+
it("round-trips active selection with orgId", () => {
writeStoredActiveBackend({ backendId: "xyz", orgId: "org-1" });
expect(readStoredActiveBackend()).toEqual({
diff --git a/__tests__/package-library.test.ts b/__tests__/package-library.test.ts
index 8db4b2748a..2fb164a0f4 100644
--- a/__tests__/package-library.test.ts
+++ b/__tests__/package-library.test.ts
@@ -11,6 +11,7 @@ const packageJson = JSON.parse(
module: string;
types: string;
exports: Record<string, unknown>;
+ scripts: Record<string, string>;
};
describe("package library metadata", () => {
@@ -47,4 +48,19 @@ describe("package library metadata", () => {
},
});
});
+
+ it("uses static frontend launchers for user-facing dev commands", () => {
+ expect(packageJson.scripts.dev).toBe("npm run dev:docker");
+ expect(packageJson.scripts["dev:dangerously-dockerless"]).toBe(
+ "node --env-file-if-exists=.env scripts/dev-static.mjs",
+ );
+ expect(packageJson.scripts["dev:static"]).toBeUndefined();
+ expect(packageJson.scripts["dev:docker"]).toContain(
+ "scripts/dev-docker.mjs",
+ );
+ expect(packageJson.scripts["dev:docker:dynamic"]).toContain("--dynamic");
+ expect(packageJson.scripts["dev:dangerously-dockerless:dynamic"]).toBe(
+ "node --env-file-if-exists=.env scripts/dev-with-automation.mjs",
+ );
+ });
});
diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.ts
index cb4c61f0ed..9247dbcc6f 100644
--- a/__tests__/scripts/dev-with-automation.test.ts
+++ b/__tests__/scripts/dev-with-automation.test.ts
@@ -404,6 +404,8 @@ describe("dev-with-automation CLI", () => {
expect(output).toContain("--port");
expect(output).toContain("--automation-ref");
expect(output).toContain("--automation-repo");
+ expect(output).toContain("--static");
+ expect(output).toContain("--dynamic");
expect(output).toContain("OH_AUTOMATION_GIT_REF");
expect(output).toContain("AUTOMATION_LOCAL_API_KEY");
expect(output).toContain("OPENHANDS_AUTOMATION_API_KEY");
diff --git a/package.json b/package.json
index be07b37577..24d3effbfa 100644
--- a/package.json
+++ b/package.json
@@ -66,12 +66,13 @@
},
"scripts": {
"dev": "npm run dev:docker",
- "dev:dangerously-dockerless": "npm run dev:automation",
+ "dev:dangerously-dockerless": "node --env-file-if-exists=.env scripts/dev-static.mjs",
+ "dev:dangerously-dockerless:dynamic": "node --env-file-if-exists=.env scripts/dev-with-automation.mjs",
"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:docker": "node --env-file-if-exists=.env scripts/dev-docker.mjs",
- "dev:static": "node --env-file-if-exists=.env scripts/dev-static.mjs",
+ "dev:docker:dynamic": "node --env-file-if-exists=.env scripts/dev-docker.mjs --dynamic",
"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-docker.mjs b/scripts/dev-docker.mjs
index db55242f12..f60b96b3e3 100644
--- a/scripts/dev-docker.mjs
+++ b/scripts/dev-docker.mjs
@@ -1,8 +1,10 @@
/**
* Dockerized Development Stack
*
- * Same as `dev-with-automation.mjs` (Vite + ingress + automation backend),
- * but runs the agent-server inside a Docker container instead of via `uvx`.
+ * Same as `dev-with-automation.mjs`, but runs the agent-server inside a Docker
+ * container instead of via `uvx`. The default frontend is a static production
+ * build for stability over tunnels and slow networks; pass `--dynamic` for the
+ * Vite dev server with live reload.
*
* The agent-server image listens on port 8000 inside the container; we map
* it to the host's `agentServerPort` (default 18000) so the ingress proxy
@@ -42,6 +44,7 @@
*
* Usage:
* PROJECT_PATH=/path/to/your/projects npm run dev:docker
+ * PROJECT_PATH=/path/to/your/projects npm run dev:docker -- --dynamic
* OH_AGENT_SERVER_GIT_REF=main PROJECT_PATH=... npm run dev:docker
*/
@@ -62,6 +65,7 @@ import {
spawnService,
} from "./dev-with-automation.mjs";
import { validateLocalAgentServerPath } from "./dev-safe.mjs";
+import { buildFrontend } from "./static-build.mjs";
// Path inside the container where OH_AGENT_SERVER_LOCAL_PATH is bind-mounted.
const CONTAINER_LOCAL_SDK_DIR = "/agent-server-src";
@@ -309,6 +313,8 @@ if (isMainModule) {
extraPrereqs: checkDockerPrereqs,
startAgentServer: startAgentServerDocker,
viteWorkingDir: CONTAINER_WORKSPACES_DIR,
+ defaultStaticMode: true,
+ buildStaticFrontend: buildFrontend,
}).catch((err) => {
logError(`Fatal error: ${err.message}`);
if (err.stack) {
diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjs
index 5ca70e7e9b..194fd62509 100644
--- a/scripts/dev-static.mjs
+++ b/scripts/dev-static.mjs
@@ -1,9 +1,9 @@
/**
* 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)
+ * Mirrors the dockerless automation stack but serves a production build of the
+ * frontend via `scripts/static-server.mjs` 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.
@@ -24,10 +24,10 @@
* β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
*
* 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
+ * npm run dev:dangerously-dockerless
+ * npm run dev:dangerously-dockerless -- --port 12000
+ * npm run dev:dangerously-dockerless -- --skip-build # reuse an existing build/
+ * npm run dev:dangerously-dockerless -- --automation-ref feat/my-branch
*
* Environment variables (all optional, same as dev:automation):
* - PORT: Ingress port (default: 8000)
@@ -37,17 +37,16 @@
*/
import { spawn, spawnSync } from "node:child_process";
-import { existsSync } from "node:fs";
import { join, resolve, dirname } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { setTimeout as delay } from "node:timers/promises";
import process from "node:process";
+import { buildFrontend } from "./static-build.mjs";
import {
buildAgentServerCommand,
buildSafeDevConfig,
buildAgentServerEnv,
- buildNpmScriptCommand,
formatMissingUvxGuidance,
isPortBusy,
releaseStaleConversationLeases,
@@ -139,12 +138,12 @@ 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).
+Runs the dockerless automation stack, but serves a production build of the
+frontend via scripts/static-server.mjs. Use this when a remote or flaky network
+makes Vite's per-module requests painful (e.g. ngrok or plane wifi).
USAGE:
- npm run dev:static [-- options]
+ npm run dev:dangerously-dockerless [-- options]
OPTIONS:
-p, --port <port> Ingress port (default: 8000)
@@ -201,66 +200,6 @@ function checkPrerequisites() {
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
// ═══════════════════════════════════════════════════════════════════════════
@@ -553,7 +492,7 @@ function printBanner(config) {
`${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}`,
+ `${c.dim}Edit sources, then re-run \`npm run dev:dangerously-dockerless\` to rebuild.${c.reset}`,
);
console.log(`${c.dim}Press Ctrl+C to stop${c.reset}`);
console.log("");
@@ -607,7 +546,7 @@ async function main() {
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.`,
+ `before running dev:dangerously-dockerless.`,
);
process.exit(1);
}
diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjs
index 7a1e454e68..add73a96e5 100644
--- a/scripts/dev-with-automation.mjs
+++ b/scripts/dev-with-automation.mjs
@@ -118,7 +118,9 @@ function parseArgs() {
automationRepo: null,
verbose: false,
static: false,
+ dynamic: false,
staticDir: null,
+ skipBuild: false,
};
for (let i = 0; i < args.length; i++) {
@@ -140,9 +142,15 @@ function parseArgs() {
case "--static":
config.static = true;
break;
+ case "--dynamic":
+ config.dynamic = true;
+ break;
case "--static-dir":
config.staticDir = args[++i];
break;
+ case "--skip-build":
+ config.skipBuild = true;
+ break;
case "-h":
case "--help":
showHelp();
@@ -167,6 +175,10 @@ OPTIONS:
-p, --port <port> Ingress port (default: 8000)
--automation-ref <ref> Git ref for automation (branch/tag/SHA)
--automation-repo <url> Git repo URL (default: ${DEFAULT_AUTOMATION_REPO})
+ --static Serve an existing production build instead of Vite
+ --static-dir <dir> Static build directory (default: build/)
+ --skip-build Reuse build/ when the launcher builds static assets
+ --dynamic Force Vite dev server when a wrapper defaults static
-v, --verbose Show detailed output
-h, --help Show this help
@@ -710,14 +722,19 @@ async function main(options = {}) {
extraPrereqs,
viteWorkingDir,
staticMode: staticModeOverride,
+ defaultStaticMode = false,
+ buildStaticFrontend,
staticDir: staticDirOverride,
} = options;
const args = parseArgs();
// Allow options to override CLI args (for bin/agent-canvas.mjs)
- const useStaticMode = staticModeOverride ?? args.static;
- const staticDir = staticDirOverride ?? args.staticDir ?? join(projectRoot, "build", "client");
+ const useStaticMode =
+ staticModeOverride ??
+ (args.dynamic ? false : args.static || defaultStaticMode);
+ const staticDir =
+ staticDirOverride ?? args.staticDir ?? join(projectRoot, "build");
const modeLabel = useStaticMode ? "(Static)" : "";
const titleWithMode = modeLabel ? `${bannerTitle} ${modeLabel}` : bannerTitle;
@@ -729,14 +746,10 @@ async function main(options = {}) {
// Setup phase
// (uvx is still required even in docker mode because the automation
// backend runs via uvx; only the agent-server is dockerized.)
- checkPrerequisites({ checkFrontendDependencies: !useStaticMode });
-
- // In static mode, verify build exists
- if (useStaticMode && !existsSync(staticDir)) {
- logError(`Static directory not found: ${staticDir}`);
- logError(`Run 'npm run build' first to create the static files.`);
- process.exit(1);
- }
+ checkPrerequisites({
+ checkFrontendDependencies:
+ !useStaticMode || typeof buildStaticFrontend === "function",
+ });
// Build config with dynamic port allocation
const config = await buildConfig(args);
@@ -746,6 +759,17 @@ async function main(options = {}) {
extraPrereqs(config);
}
+ if (useStaticMode && typeof buildStaticFrontend === "function") {
+ buildStaticFrontend(config, args);
+ }
+
+ // In static mode, verify build exists after any launcher-managed build.
+ if (useStaticMode && !existsSync(staticDir)) {
+ logError(`Static directory not found: ${staticDir}`);
+ logError(`Run 'npm run build' first to create the static files.`);
+ process.exit(1);
+ }
+
// Start services phase
logStep("2/2", "Starting services...");
diff --git a/scripts/static-build.mjs b/scripts/static-build.mjs
new file mode 100644
index 0000000000..3d094331e8
--- /dev/null
+++ b/scripts/static-build.mjs
@@ -0,0 +1,73 @@
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ c,
+ logError,
+ logService,
+ logStep,
+ logSuccess,
+} from "./dev-with-automation.mjs";
+import { buildNpmScriptCommand } from "./dev-safe.mjs";
+
+export 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("build", "Skipping frontend build (--skip-build)");
+ logService("build", `Reusing existing build/ at ${buildDir}`, c.dim);
+ return;
+ }
+
+ logStep("build", "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 same default workspace path that the dynamic launcher passes
+ // to Vite. Docker uses an in-container path; dockerless uses host state.
+ VITE_WORKING_DIR:
+ config.viteWorkingDir ?? 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,
+ // Bake the same session key the agent-server accepts. Without this,
+ // a fresh browser session seeds the Local backend with an empty key and
+ // all authenticated agent-server calls fail with 401.
+ VITE_SESSION_API_KEY: config.sessionApiKey,
+ // Intentionally do NOT set VITE_BACKEND_BASE_URL: leaving it unset makes
+ // the runtime fall back to window.location.origin, which keeps the build
+ // portable across localhost, LAN hosts, and tunnels such as ngrok.
+ },
+ });
+
+ 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");
+}
diff --git a/scripts/static-server.mjs b/scripts/static-server.mjs
index 66a1b86e52..56a59cb27b 100644
--- a/scripts/static-server.mjs
+++ b/scripts/static-server.mjs
@@ -1,7 +1,7 @@
/**
* Combined static file server + reverse proxy.
*
- * Replaces `sirv-cli` for `npm run dev:static`. The reason a plain static
+ * Replaces `sirv-cli` for the dockerless static launcher. 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
diff --git a/src/api/backend-registry/storage.ts b/src/api/backend-registry/storage.ts
index 9a1231cdeb..058e9517c3 100644
--- a/src/api/backend-registry/storage.ts
+++ b/src/api/backend-registry/storage.ts
@@ -21,6 +21,34 @@ function isValidBackend(value: unknown): value is Backend {
);
}
+function normalizeHostForComparison(host: string): string {
+ try {
+ return new URL(host).origin;
+ } catch {
+ return host.replace(/\/+$/, "");
+ }
+}
+
+function syncDefaultLocalBackendAuth(backend: Backend): Backend {
+ const defaultBackend = makeDefaultLocalBackend();
+
+ if (
+ backend.id !== defaultBackend.id ||
+ backend.kind !== "local" ||
+ backend.apiKey ||
+ !defaultBackend.apiKey ||
+ normalizeHostForComparison(backend.host) !==
+ normalizeHostForComparison(defaultBackend.host)
+ ) {
+ return backend;
+ }
+
+ return {
+ ...backend,
+ apiKey: defaultBackend.apiKey,
+ };
+}
+
export function writeStoredBackends(backends: Backend[]): void {
if (typeof window === "undefined") return;
try {
@@ -61,7 +89,12 @@ export function readStoredBackends(): Backend[] {
return seeded;
}
- return valid;
+ const synced = valid.map(syncDefaultLocalBackendAuth);
+ if (synced.some((backend, index) => backend !== valid[index])) {
+ writeStoredBackends(synced);
+ }
+
+ return synced;
} catch {
return [];
}
diff --git a/src/mocks/file-service-handlers.ts b/src/mocks/file-service-handlers.ts
index ed68e65bdb..f3ef3fdc4c 100644
--- a/src/mocks/file-service-handlers.ts
+++ b/src/mocks/file-service-handlers.ts
@@ -8,6 +8,25 @@ export const FILE_VARIANTS_2 = [
];
export const FILE_SERVICE_HANDLERS = [
+ http.all("*/api/bash/execute_bash_command", async () =>
+ HttpResponse.json({
+ command: "",
+ exit_code: 0,
+ output: "",
+ }),
+ ),
+
+ http.get("*/api/file/search_subdirs", async () =>
+ HttpResponse.json({ path: "/projects", subdirs: [] }),
+ ),
+
+ http.get("*/api/file/:path", async ({ params }) =>
+ HttpResponse.json({
+ path: `/${params.path?.toString() ?? "home"}`,
+ subdirs: [],
+ }),
+ ),
+
http.get(
"/api/conversations/:conversationId/list-files",
async ({ params }) => {
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-collapsed.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-collapsed.png
index 84a5531d6e..f2ddd1a544 100644
Binary files a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-collapsed.png and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-collapsed.png differ
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-expanded.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-expanded.png
index d4523d3ff8..11c927c967 100644
Binary files a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-expanded.png and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-expanded.png differ
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-collapsed.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-collapsed.png
index a8d386f68b..57afada303 100644
Binary files a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-collapsed.png and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-collapsed.png differ
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-expanded.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-expanded.png
index d6cc0f408f..1c15b4051d 100644
Binary files a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-expanded.png and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-expanded.png differ
diff --git a/tests/e2e/snapshots/collapsible-thinking.snapshot.spec.ts b/tests/e2e/snapshots/collapsible-thinking.snapshot.spec.ts
index c05a6377a3..ce76c03ef4 100644
--- a/tests/e2e/snapshots/collapsible-thinking.snapshot.spec.ts
+++ b/tests/e2e/snapshots/collapsible-thinking.snapshot.spec.ts
@@ -93,8 +93,12 @@ const USER_MESSAGE_EVENT = {
id: "user-msg-1",
timestamp: "2026-01-01T00:00:00.000Z",
source: "user",
- role: "user",
- payload: [{ type: "text", text: "Help me understand this project" }],
+ llm_message: {
+ role: "user",
+ content: [{ type: "text", text: "Help me understand this project" }],
+ },
+ activated_microagents: [],
+ extended_content: [],
};
/**
@@ -121,32 +125,79 @@ async function dismissConsentModal(page: Page) {
* Inject events into the event store via the exposed Zustand API.
*/
async function injectEvents(page: Page, events: unknown[]) {
- await page.evaluate((evts) => {
+ await page.waitForFunction(() => {
const store = (
window as unknown as {
__OH_EVENT_STORE__?: {
- getState: () => { addEvents: (e: unknown[]) => void };
+ getState: () => { addEvents?: (e: unknown[]) => void };
};
}
).__OH_EVENT_STORE__;
- if (store) {
- store.getState().addEvents(evts);
- }
- }, events);
+ return Boolean(store?.getState().addEvents);
+ });
+
+ await expect
+ .poll(
+ async () =>
+ page.evaluate((evts) => {
+ const store = (
+ window as unknown as {
+ __OH_EVENT_STORE__?: {
+ getState: () => {
+ addEvents: (e: unknown[]) => void;
+ events: unknown[];
+ };
+ };
+ }
+ ).__OH_EVENT_STORE__;
+
+ if (!store) {
+ return 0;
+ }
+
+ const state = store.getState();
+ state.addEvents(evts);
+ return store.getState().events.length;
+ }, events),
+ { timeout: 10000 },
+ )
+ .toBeGreaterThanOrEqual(events.length);
+
// Wait for React to re-render
await page.waitForTimeout(500);
}
/**
- * Navigate to a conversation page and wait for the chat interface to load.
+ * Navigate to a conversation page and seed it with events so the chat
+ * interface renders instead of the empty launch prompt.
* Uses mock conversation "1" which exists in the MSW handlers.
*/
-async function navigateToConversation(page: Page) {
+async function navigateToConversation(page: Page, events: unknown[]) {
// Skip onboarding
await page.addInitScript(() => {
window.localStorage.setItem("openhands-onboarded", "true");
});
+ await page.route("**/api/bash/execute_bash_command", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ command: "ls -la",
+ exit_code: 0,
+ output: "",
+ }),
+ });
+ });
+
+ await page.route("**/api/file/**", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ path: "/home", subdirs: [] }),
+ });
+ });
+
// Stub WebSocket to prevent connection errors
await page.addInitScript(() => {
const noop = () => {};
@@ -189,6 +240,11 @@ async function navigateToConversation(page: Page) {
waitUntil: "domcontentloaded",
});
await dismissConsentModal(page);
+ await expect(page.getByText("Let's start building!")).toBeVisible({
+ timeout: 20000,
+ });
+
+ await injectEvents(page, events);
const chatInterface = page.getByTestId("chat-interface");
await expect(chatInterface).toBeVisible({ timeout: 20000 });
@@ -203,10 +259,10 @@ test.describe("Collapsible Thinking Visual Snapshots", () => {
test.setTimeout(60000);
test("ThinkAction renders as collapsed section", async ({ page }) => {
- const chatInterface = await navigateToConversation(page);
-
- // Inject events
- await injectEvents(page, [USER_MESSAGE_EVENT, THINK_ACTION_EVENT]);
+ const chatInterface = await navigateToConversation(page, [
+ USER_MESSAGE_EVENT,
+ THINK_ACTION_EVENT,
+ ]);
// Verify the collapsible thinking section is rendered
const collapsibleThinking = page.getByTestId("collapsible-thinking");
@@ -217,19 +273,17 @@ test.describe("Collapsible Thinking Visual Snapshots", () => {
await expect(content).toHaveCount(0);
// Snapshot: collapsed state
- await expect(chatInterface).toHaveScreenshot(
- "think-action-collapsed.png",
- {
- maxDiffPixelRatio: 0.01,
- animations: "disabled",
- },
- );
+ await expect(chatInterface).toHaveScreenshot("think-action-collapsed.png", {
+ maxDiffPixelRatio: 0.01,
+ animations: "disabled",
+ });
});
test("ThinkAction expands on click", async ({ page }) => {
- const chatInterface = await navigateToConversation(page);
-
- await injectEvents(page, [USER_MESSAGE_EVENT, THINK_ACTION_EVENT]);
+ const chatInterface = await navigateToConversation(page, [
+ USER_MESSAGE_EVENT,
+ THINK_ACTION_EVENT,
+ ]);
const toggle = page.getByTestId("collapsible-thinking-toggle");
await expect(toggle).toBeVisible({ timeout: 5000 });
@@ -242,21 +296,16 @@ test.describe("Collapsible Thinking Visual Snapshots", () => {
await expect(content).toBeVisible({ timeout: 5000 });
// Snapshot: expanded state
- await expect(chatInterface).toHaveScreenshot(
- "think-action-expanded.png",
- {
- maxDiffPixelRatio: 0.01,
- animations: "disabled",
- },
- );
+ await expect(chatInterface).toHaveScreenshot("think-action-expanded.png", {
+ maxDiffPixelRatio: 0.01,
+ animations: "disabled",
+ });
});
test("Reasoning content renders as collapsed section with action", async ({
page,
}) => {
- const chatInterface = await navigateToConversation(page);
-
- await injectEvents(page, [
+ const chatInterface = await navigateToConversation(page, [
USER_MESSAGE_EVENT,
BASH_WITH_REASONING_EVENT,
]);
@@ -276,9 +325,7 @@ test.describe("Collapsible Thinking Visual Snapshots", () => {
});
test("Reasoning content expands on click", async ({ page }) => {
- const chatInterface = await navigateToConversation(page);
-
- await injectEvents(page, [
+ const chatInterface = await navigateToConversation(page, [
USER_MESSAGE_EVENT,
BASH_WITH_REASONING_EVENT,
]);
diff --git a/tests/e2e/snapshots/settings-page.snapshot.spec.ts b/tests/e2e/snapshots/settings-page.snapshot.spec.ts
index cb5f0c9f23..3a343c7287 100644
--- a/tests/e2e/snapshots/settings-page.snapshot.spec.ts
+++ b/tests/e2e/snapshots/settings-page.snapshot.spec.ts
@@ -94,6 +94,18 @@ async function setupMocks(page: Page, showConsentModal = false) {
});
});
+ await page.route("**/api/bash/execute_bash_command", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ command: "",
+ exit_code: 0,
+ output: "",
+ }),
+ });
+ });
+
// Mock file APIs to prevent proxy errors
await page.route("**/api/file/**", async (route) => {
await route.fulfill({