diff --git a/packages/app/index.html b/packages/app/index.html
index 1cec152cd0e..c9c930acf6d 100644
--- a/packages/app/index.html
+++ b/packages/app/index.html
@@ -10,13 +10,13 @@
OpenCode
-
+
-
+
-
+
diff --git a/packages/app/src/entry.tsx b/packages/app/src/entry.tsx
index 969f506c1f6..f9a06a0f135 100644
--- a/packages/app/src/entry.tsx
+++ b/packages/app/src/entry.tsx
@@ -53,7 +53,9 @@ const clearAuthToken = () => {
const web = createWebPlatform(import.meta.env.VITE_OPENCODE_VERSION ?? pkg.version)
if (import.meta.env.PROD && "serviceWorker" in navigator) {
- window.addEventListener("load", () => void navigator.serviceWorker.register("/sw.js"), { once: true })
+ window.addEventListener("load", () => void navigator.serviceWorker.register(`${import.meta.env.BASE_URL}sw.js`), {
+ once: true,
+ })
}
if (import.meta.env.VITE_SENTRY_DSN) {
diff --git a/packages/app/src/env.d.ts b/packages/app/src/env.d.ts
index afe80ccabab..64057f079c3 100644
--- a/packages/app/src/env.d.ts
+++ b/packages/app/src/env.d.ts
@@ -1,4 +1,6 @@
interface ImportMetaEnv {
+ /** Vite's `base`, the path the build is served under, such as `/opencode/`; `/` at the root. */
+ readonly BASE_URL: string
readonly VITE_OPENCODE_SERVER_MODE?: "none" | "origin"
readonly VITE_OPENCODE_SERVER_HOST: string
readonly VITE_OPENCODE_SERVER_PORT: string
diff --git a/packages/app/src/runtime/platform/base-path-router.tsx b/packages/app/src/runtime/platform/base-path-router.tsx
new file mode 100644
index 00000000000..0dfe8857be1
--- /dev/null
+++ b/packages/app/src/runtime/platform/base-path-router.tsx
@@ -0,0 +1,66 @@
+import {
+ type BaseRouterProps,
+ createBeforeLeave,
+ createRouter,
+ keepDepth,
+ notifyIfNotBlocked,
+ saveCurrentDepth,
+} from "@solidjs/router"
+import { basePath, stripBasePath, withBasePath } from "@/runtime/platform/base-path"
+
+/**
+ * A history router for builds served under a base path. Unlike the router's own `base`, it keeps every route path the
+ * app sees base-free, so code reading `useLocation().pathname` or navigating to it works the same under any base.
+ */
+export function BasePathRouter(props: BaseRouterProps) {
+ const read = () => {
+ const state = history.state
+
+ return {
+ value: stripBasePath(location.pathname + location.search + location.hash),
+ // The router marks its own entries with only a depth; that is not app state.
+ state: state && state._depth && Object.keys(state).length === 1 ? undefined : state,
+ }
+ }
+
+ const beforeLeave = createBeforeLeave()
+
+ return createRouter({
+ get: read,
+ set({ value, replace, scroll, state }) {
+ const url = withBasePath(value)
+
+ if (replace) history.replaceState(keepDepth(state), "", url)
+ else history.pushState(state, "", url)
+
+ const hash = decodeURIComponent(location.hash.slice(1))
+ const target = hash && document.getElementById(hash)
+
+ if (target) target.scrollIntoView()
+ else if (scroll) window.scrollTo(0, 0)
+
+ saveCurrentDepth()
+ },
+ init: (notify) => {
+ const handler = notifyIfNotBlocked(notify, (delta) => {
+ if (delta) return !beforeLeave.confirm(delta)
+
+ const source = read()
+
+ return !beforeLeave.confirm(source.value, { state: source.state })
+ })
+
+ window.addEventListener("popstate", handler)
+
+ return () => window.removeEventListener("popstate", handler)
+ },
+ utils: {
+ go: (delta) => history.go(delta),
+ renderPath: withBasePath,
+ parsePath: stripBasePath,
+ beforeLeave,
+ },
+ })(props)
+}
+
+export const baseRouter = basePath ? BasePathRouter : undefined
diff --git a/packages/app/src/runtime/platform/base-path.test.ts b/packages/app/src/runtime/platform/base-path.test.ts
new file mode 100644
index 00000000000..8bf1e00598b
--- /dev/null
+++ b/packages/app/src/runtime/platform/base-path.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from "bun:test"
+import { normalizeBasePath, stripBasePath, withBasePath } from "./base-path"
+
+describe("normalizeBasePath", () => {
+ test("is empty at the root", () => {
+ expect(normalizeBasePath(undefined)).toBe("")
+ expect(normalizeBasePath("/")).toBe("")
+ expect(normalizeBasePath("")).toBe("")
+ })
+
+ test("has a leading slash and no trailing slash", () => {
+ expect(normalizeBasePath("/opencode/")).toBe("/opencode")
+ expect(normalizeBasePath("opencode")).toBe("/opencode")
+ expect(normalizeBasePath("//a/b//")).toBe("/a/b")
+ })
+})
+
+describe("withBasePath", () => {
+ test("leaves paths alone at the root", () => {
+ expect(withBasePath("/new-session?x=1", "")).toBe("/new-session?x=1")
+ })
+
+ test("prefixes paths with the base", () => {
+ expect(withBasePath("/", "/opencode")).toBe("/opencode/")
+ expect(withBasePath("/server/a/session/b#m", "/opencode")).toBe("/opencode/server/a/session/b#m")
+ })
+})
+
+describe("stripBasePath", () => {
+ test("leaves paths alone at the root", () => {
+ expect(stripBasePath("/new-session", "")).toBe("/new-session")
+ })
+
+ test("removes the base", () => {
+ expect(stripBasePath("/opencode", "/opencode")).toBe("/")
+ expect(stripBasePath("/opencode/", "/opencode")).toBe("/")
+ expect(stripBasePath("/opencode?draftId=1", "/opencode")).toBe("/?draftId=1")
+ expect(stripBasePath("/opencode/new-session#top", "/opencode")).toBe("/new-session#top")
+ })
+
+ test("keeps paths outside the base", () => {
+ expect(stripBasePath("/opencode-other/x", "/opencode")).toBe("/opencode-other/x")
+ expect(stripBasePath("/elsewhere", "/opencode")).toBe("/elsewhere")
+ })
+
+ test("round-trips with withBasePath", () => {
+ for (const path of ["/", "/new-session", "/server/a/session/b?q=1#h"])
+ expect(stripBasePath(withBasePath(path, "/opencode"), "/opencode")).toBe(path)
+ })
+})
diff --git a/packages/app/src/runtime/platform/base-path.ts b/packages/app/src/runtime/platform/base-path.ts
new file mode 100644
index 00000000000..220a322f945
--- /dev/null
+++ b/packages/app/src/runtime/platform/base-path.ts
@@ -0,0 +1,28 @@
+/** The path a build is served under, such as `/opencode`, without a trailing slash; empty at the root. */
+export const basePath = normalizeBasePath(import.meta.env.BASE_URL)
+
+export function normalizeBasePath(base: string | undefined) {
+ const trimmed = (base ?? "").replace(/^\/+|\/+$/g, "")
+
+ return trimmed ? `/${trimmed}` : ""
+}
+
+/** The browser path for an app path, such as `/opencode/new-session` for `/new-session`. */
+export function withBasePath(path: string, base = basePath) {
+ if (!base) return path
+
+ return path === "/" ? `${base}/` : `${base}${path}`
+}
+
+/** The app path for a browser path, or the path itself when it lies outside the base. */
+export function stripBasePath(path: string, base = basePath) {
+ if (!base || !path.startsWith(base)) return path
+
+ const rest = path.slice(base.length)
+
+ if (rest.startsWith("/")) return rest
+
+ if (rest === "" || rest.startsWith("?") || rest.startsWith("#")) return `/${rest}`
+
+ return path
+}
diff --git a/packages/app/src/runtime/platform/pwa.ts b/packages/app/src/runtime/platform/pwa.ts
index 1fb7fc97766..611cd322aee 100644
--- a/packages/app/src/runtime/platform/pwa.ts
+++ b/packages/app/src/runtime/platform/pwa.ts
@@ -1,5 +1,6 @@
import { useLocation } from "@solidjs/router"
import { createEffect } from "solid-js"
+import { stripBasePath, withBasePath } from "./base-path"
const LAST_ROUTE_KEY = "opencode.pwa.last-route"
@@ -11,7 +12,7 @@ export function isStandalone() {
}
export function restorePwaRoute() {
- if (location.pathname !== "/" || location.search || location.hash) return
+ if (stripBasePath(location.pathname) !== "/" || location.search || location.hash) return
try {
const value = localStorage.getItem(LAST_ROUTE_KEY)
@@ -27,7 +28,7 @@ export function restorePwaRoute() {
!/^\/server\/[^/]+\/session\/[^/]+$/.test(url.pathname)
)
return
- history.replaceState(history.state, "", url.pathname + url.search + url.hash)
+ history.replaceState(history.state, "", withBasePath(url.pathname) + url.search + url.hash)
} catch {
// Storage may be unavailable; keep the launch URL in that case.
}
diff --git a/packages/app/src/runtime/platform/web.ts b/packages/app/src/runtime/platform/web.ts
index 28944b06574..b4c822cdab7 100644
--- a/packages/app/src/runtime/platform/web.ts
+++ b/packages/app/src/runtime/platform/web.ts
@@ -1,4 +1,5 @@
import { createBrowserDraftStore } from "@/runtime/persistence/drafts"
+import { basePath } from "./base-path"
import type { Platform } from "./platform"
export function createWebPlatform(version: string) {
@@ -57,5 +58,6 @@ function getCurrentServerUrl() {
return `http://${host}:${import.meta.env.VITE_OPENCODE_SERVER_PORT ?? "4096"}`
}
- return location.origin
+ // A build under a base path reaches the server through the same prefix.
+ return location.origin + basePath
}
diff --git a/packages/app/src/runtime/server/client.tsx b/packages/app/src/runtime/server/client.tsx
index 5f79979a1c9..c28e0417e20 100644
--- a/packages/app/src/runtime/server/client.tsx
+++ b/packages/app/src/runtime/server/client.tsx
@@ -229,7 +229,10 @@ export function createServerTransport(input: {
http: ServerConnection.HttpBase
fetch?: typeof globalThis.fetch
}): ServerTransport {
- const queue = createRequestQueue({ fetch: input.fetch ?? globalThis.fetch })
+ const queue = createRequestQueue({
+ fetch: input.fetch ?? globalThis.fetch,
+ prefix: () => serverPathPrefix(state.current.http.url),
+ })
// Keeps the endpoint as plain values: a plugin's endpoint can be a store proxy that already reads the next password,
// and the client built here keeps the one it started with.
@@ -290,3 +293,10 @@ function createDirSdkContext(directory: string, serverSDK: ServerSDKBase): Locat
event: serverSDK.event.location(directory),
}
}
+
+/** The path a server URL sits under, such as `/opencode` for `https://host/opencode/`; empty at the root. */
+function serverPathPrefix(url: string) {
+ if (!URL.canParse(url)) return ""
+
+ return new URL(url).pathname.replace(/\/+$/, "")
+}
diff --git a/packages/app/src/runtime/server/request-queue-machine.test.ts b/packages/app/src/runtime/server/request-queue-machine.test.ts
index c6757c22952..51e5002c41d 100644
--- a/packages/app/src/runtime/server/request-queue-machine.test.ts
+++ b/packages/app/src/runtime/server/request-queue-machine.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test"
import {
+ classifyRequest,
createRequestQueueState,
selectInflightCount,
selectQueuedCount,
@@ -125,3 +126,26 @@ describe("transitionRequestQueue", () => {
])
})
})
+
+describe("classifyRequest", () => {
+ test("classifies API paths under a server path prefix like those at the root", () => {
+ const paths = [
+ ["GET", "/api/event"],
+ ["GET", "/api/session"],
+ ["GET", "/api/session/ses_1/message"],
+ ["GET", "/api/vcs/diff"],
+ ["POST", "/api/worktree"],
+ ["GET", "/api/project"],
+ ] as const
+
+ for (const [method, path] of paths)
+ expect(classifyRequest(method, new URL(`http://server/opencode${path}`), "/opencode")).toEqual(
+ classifyRequest(method, new URL(`http://server${path}`)),
+ )
+ })
+
+ test("leaves paths outside the prefix alone", () => {
+ expect(classifyRequest("GET", new URL("http://server/api/event"), "/opencode").bypass).toBe(true)
+ expect(classifyRequest("GET", new URL("http://server/opencode-other/api/event"), "/opencode").bypass).toBe(false)
+ })
+})
diff --git a/packages/app/src/runtime/server/request-queue-machine.ts b/packages/app/src/runtime/server/request-queue-machine.ts
index 6a97096e8e6..6f70da99b0a 100644
--- a/packages/app/src/runtime/server/request-queue-machine.ts
+++ b/packages/app/src/runtime/server/request-queue-machine.ts
@@ -149,9 +149,11 @@ export function isRequestInflight(state: RequestQueueState, id: number) {
/**
* The event stream bypasses the queue. Writes go first. Session lists and the first transcript page unblock
* navigation, so they go ahead of location reads. Older pages and filtered indexes keep background priority.
+ * `prefix` is the server URL's path, such as `/opencode`, when the server sits under one.
*/
-export function classifyRequest(method: string, url: URL): RequestClassification {
- const pathname = url.pathname
+export function classifyRequest(method: string, url: URL, prefix = ""): RequestClassification {
+ // A server behind a path prefix serves its API under it; classify the path the server sees.
+ const pathname = prefix && url.pathname.startsWith(`${prefix}/`) ? url.pathname.slice(prefix.length) : url.pathname
// The event stream is long-lived; never count it against the request budget.
if (pathname === "/api/event") return bypass
diff --git a/packages/app/src/runtime/server/request-queue.test.ts b/packages/app/src/runtime/server/request-queue.test.ts
index 797d9d30990..1474ab14bb4 100644
--- a/packages/app/src/runtime/server/request-queue.test.ts
+++ b/packages/app/src/runtime/server/request-queue.test.ts
@@ -8,6 +8,7 @@ function setup(input?: {
stallMs?: number
headersTimeoutMs?: number
setupHeadersTimeoutMs?: number
+ prefix?: string
}) {
const pending: Array<{ url: string; signal: AbortSignal; resolve: () => void }> = []
const logs: Array<{ message: string; data: RequestStallSnapshot }> = []
@@ -19,6 +20,7 @@ function setup(input?: {
stallMs: input?.stallMs,
headersTimeoutMs: input?.headersTimeoutMs,
setupHeadersTimeoutMs: input?.setupHeadersTimeoutMs,
+ prefix: () => input?.prefix ?? "",
now: () => clock,
log: (message, data) => logs.push({ message, data }),
fetch: Object.assign(
@@ -159,6 +161,18 @@ describe("createRequestQueue", () => {
expect(input.queue.inflight()).toBe(1)
})
+ test("never counts the event stream of a server under a path prefix against the budget", async () => {
+ const input = setup({ limit: 1, prefix: "/opencode" })
+ void input.queue.fetch("http://server/opencode/api/session")
+ void input.queue.fetch("http://server/opencode/api/event")
+ await input.settle()
+ expect(input.pending.map((item) => new URL(item.url).pathname).toSorted()).toEqual([
+ "/opencode/api/event",
+ "/opencode/api/session",
+ ])
+ expect(input.queue.inflight()).toBe(1)
+ })
+
test("a queued request leaves without being sent as soon as its caller aborts, while every slot stays stuck", async () => {
const input = setup({ limit: 1, stallMs: 5 })
const controller = new AbortController()
diff --git a/packages/app/src/runtime/server/request-queue.ts b/packages/app/src/runtime/server/request-queue.ts
index 37d5c2aebb8..72666f62582 100644
--- a/packages/app/src/runtime/server/request-queue.ts
+++ b/packages/app/src/runtime/server/request-queue.ts
@@ -26,6 +26,8 @@ const setupRequestHeadersTimeoutMs = 10 * 60_000
export function createRequestQueue(input: {
fetch: typeof globalThis.fetch
+ /** The server URL's path, such as `/opencode`, when the server sits under a prefix. */
+ prefix?: () => string
limit?: number
slowLimit?: number
stallMs?: number
@@ -106,7 +108,7 @@ export function createRequestQueue(input: {
const fetch: typeof globalThis.fetch = Object.assign(
async (resource: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(resource, init)
- const kind = classifyRequest(request.method, new URL(request.url))
+ const kind = classifyRequest(request.method, new URL(request.url), input.prefix?.())
if (kind.bypass) return base(request)
diff --git a/packages/app/vite.config.ts b/packages/app/vite.config.ts
index 87b1ce7a66b..7eed5fd162d 100644
--- a/packages/app/vite.config.ts
+++ b/packages/app/vite.config.ts
@@ -1,6 +1,6 @@
import { sentryVitePlugin } from "@sentry/vite-plugin"
import { fileURLToPath } from "node:url"
-import { defineConfig } from "vite"
+import { defineConfig, type Plugin, type UserConfig } from "vite"
import desktopPlugin, { channel } from "./vite.js"
import { icons } from "./vite.icons"
import { serviceWorker } from "./vite.pwa"
@@ -22,8 +22,32 @@ const sentry =
})
: false
+// The app is built for the root by default; `vite build --base=/opencode/` serves it under that path. A base without
+// its trailing slash would reach `import.meta.env.BASE_URL` and `%BASE_URL%` as is and glue paths onto it.
+const basePath: Plugin = {
+ name: "opencode-app:base-path",
+ config(config) {
+ if (config.base?.startsWith("/") && !config.base.endsWith("/")) return { base: `${config.base}/` }
+ },
+}
+
+// The e2e build also emits the fixture pages the tests open beside the app.
+const testFixtureInput = [
+ "index.html",
+ "e2e/utils/settings-wsl.html",
+ "e2e/utils/app-direction.html",
+ "e2e/utils/windows-menu.html",
+]
+
+const build: UserConfig["build"] = { assetsDir: "_assets", target: "esnext", sourcemap: true }
+
+if (process.env.VITE_OPENCODE_TEST_FIXTURES === "1") build.rolldownOptions = { input: testFixtureInput }
+
export default defineConfig({
+ // SAFETY: the plugins are typed against the different Vite versions their packages depend on, but all of them only
+ // use hooks this Vite runs.
plugins: [
+ basePath,
desktopPlugin,
icons(channel),
serviceWorker(fileURLToPath(new URL("./dist", import.meta.url))),
@@ -34,21 +58,5 @@ export default defineConfig({
allowedHosts: true,
port: 3000,
},
- build: {
- ...(process.env.VITE_OPENCODE_TEST_FIXTURES === "1"
- ? {
- rolldownOptions: {
- input: [
- "index.html",
- "e2e/utils/settings-wsl.html",
- "e2e/utils/app-direction.html",
- "e2e/utils/windows-menu.html",
- ],
- },
- }
- : {}),
- assetsDir: "_assets",
- target: "esnext",
- sourcemap: true,
- },
+ build,
})
diff --git a/packages/app/vite.icons.test.ts b/packages/app/vite.icons.test.ts
index 73179adedd2..7bdbc4b404f 100644
--- a/packages/app/vite.icons.test.ts
+++ b/packages/app/vite.icons.test.ts
@@ -33,6 +33,40 @@ test.each(["dev", "beta", "prod", "local"])("bundles %s app icons", async (chann
})
})
+test("bundles app icons under a base path", async () => {
+ const result = await build({
+ root: import.meta.dirname,
+ configFile: false,
+ logLevel: "silent",
+ base: "/opencode/",
+ plugins: [
+ icons("prod"),
+ {
+ name: "icons-only-fixture",
+ transformIndexHtml: {
+ order: "pre",
+ handler: (html) => html.replace(/