Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/app/src/context/sync.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,43 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({

return runInflight(inflight, key, () => Promise.all([sessionReq, messagesReq]).then(() => {}))
},
async refresh(sessionID: string) {
const directory = sdk.directory
const client = sdk.client
const [, setStore] = globalSync.child(directory)
const key = keyFor(directory, sessionID)

touch(directory, setStore, sessionID)

const limit = meta.limit[key] ?? messagePageSize

const sessionReq = retry(() => client.session.get({ sessionID })).then((session) => {
if (!tracked(directory, sessionID)) return
const data = session.data
if (!data) return
setStore(
"session",
produce((draft) => {
const match = Binary.search(draft, sessionID, (s) => s.id)
if (match.found) {
draft[match.index] = data
return
}
draft.splice(match.index, 0, data)
}),
)
})

const messagesReq = loadMessages({
directory,
client,
setStore,
sessionID,
limit,
})

return runInflight(inflight, key, () => Promise.all([sessionReq, messagesReq]).then(() => {}))
},
async diff(sessionID: string) {
const directory = sdk.directory
const client = sdk.client
Expand Down
8 changes: 6 additions & 2 deletions packages/app/src/entry.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @refresh reload

import { iife } from "@opencode-ai/util/iife"
import { Router, type BaseRouterProps } from "@solidjs/router"
import { render } from "solid-js/web"
import { AppBaseProviders, AppInterface } from "@/app"
import { type Platform, PlatformProvider } from "@/context/platform"
Expand Down Expand Up @@ -102,7 +103,8 @@ const getCurrentUrl = () => {
if (location.hostname.includes("opencode.ai")) return "http://localhost:4096"
if (import.meta.env.DEV)
return `http://${import.meta.env.VITE_OPENCODE_SERVER_HOST ?? "localhost"}:${import.meta.env.VITE_OPENCODE_SERVER_PORT ?? "4096"}`
return location.origin
const base = (window as Window & { __OPENCODE_BASE_PATH?: string }).__OPENCODE_BASE_PATH ?? ""
return base ? `${location.origin}${base}` : location.origin
}

const getDefaultUrl = () => {
Expand All @@ -127,12 +129,14 @@ const platform: Platform = {
}

if (root instanceof HTMLElement) {
const base = (window as Window & { __OPENCODE_BASE_PATH?: string }).__OPENCODE_BASE_PATH ?? ""
const router = (props: BaseRouterProps) => <Router {...props} base={base || undefined} />
const server: ServerConnection.Http = { type: "http", http: { url: getCurrentUrl() } }
render(
() => (
<PlatformProvider value={platform}>
<AppBaseProviders>
<AppInterface defaultServer={ServerConnection.Key.make(getDefaultUrl())} servers={[server]} />
<AppInterface defaultServer={ServerConnection.Key.make(getDefaultUrl())} servers={[server]} router={router} />
</AppBaseProviders>
</PlatformProvider>
),
Expand Down
16 changes: 16 additions & 0 deletions packages/app/src/pages/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,22 @@ export default function Page() {
}),
)

createEffect(
on([() => sdk.directory, () => params.id] as const, ([, id]) => {
if (!id) return
const base = (window as Window & { __OPENCODE_BASE_PATH?: string }).__OPENCODE_BASE_PATH
if (!base) return

const timer = setInterval(() => {
if (document.visibilityState !== "visible") return
void sync.session.refresh(id)
void sync.session.todo(id)
}, 2000)

onCleanup(() => clearInterval(timer))
Comment thread
picbeats marked this conversation as resolved.
Outdated
}),
)

createEffect(
on(
() => visibleUserMessages().at(-1)?.id,
Expand Down
28 changes: 19 additions & 9 deletions packages/opencode/src/cli/cmd/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,33 +28,44 @@ function getNetworkIPs() {
return results
}

function normalizeBasePath(raw: string): string {
if (!raw || raw.trim() === "") throw new Error("--base-path must not be empty")
const normalized = raw.startsWith("/") ? raw : `/${raw}`
Comment thread
picbeats marked this conversation as resolved.
Outdated
return normalized === "/" ? "/" : normalized.replace(/\/+$/, "")
}

export const WebCommand = cmd({
command: "web",
builder: (yargs) => withNetworkOptions(yargs),
builder: (yargs) =>
withNetworkOptions(yargs).option("base-path", {
type: "string",
default: "/",
description: "Base path to serve the app under (e.g. /opencode)",
}),
describe: "start opencode server and open web interface",
handler: async (args) => {
if (!Flag.OPENCODE_SERVER_PASSWORD) {
UI.println(UI.Style.TEXT_WARNING_BOLD + "! " + "OPENCODE_SERVER_PASSWORD is not set; server is unsecured.")
}
const opts = await resolveNetworkOptions(args)
const server = Server.listen(opts)
const base = normalizeBasePath(args["base-path"] as string)
const server = Server.listen({ ...opts, basePath: base })
UI.empty()
UI.println(UI.logo(" "))
UI.empty()

const suffix = base === "/" ? "" : base
if (opts.hostname === "0.0.0.0") {
// Show localhost for local access
const localhostUrl = `http://localhost:${server.port}`
const localhostUrl = `http://localhost:${server.port}${suffix}`
UI.println(UI.Style.TEXT_INFO_BOLD + " Local access: ", UI.Style.TEXT_NORMAL, localhostUrl)

// Show network IPs for remote access
const networkIPs = getNetworkIPs()
if (networkIPs.length > 0) {
for (const ip of networkIPs) {
UI.println(
UI.Style.TEXT_INFO_BOLD + " Network access: ",
UI.Style.TEXT_NORMAL,
`http://${ip}:${server.port}`,
`http://${ip}:${server.port}${suffix}`,
)
}
}
Expand All @@ -63,14 +74,13 @@ export const WebCommand = cmd({
UI.println(
UI.Style.TEXT_INFO_BOLD + " mDNS: ",
UI.Style.TEXT_NORMAL,
`${opts.mdnsDomain}:${server.port}`,
`${opts.mdnsDomain}:${server.port}${suffix}`,
)
}

// Open localhost in browser
open(localhostUrl.toString()).catch(() => {})
} else {
const displayUrl = server.url.toString()
const displayUrl = `${server.url.toString().replace(/\/$/, "")}${suffix}`
UI.println(UI.Style.TEXT_INFO_BOLD + " Web interface: ", UI.Style.TEXT_NORMAL, displayUrl)
open(displayUrl).catch(() => {})
}
Expand Down
8 changes: 7 additions & 1 deletion packages/opencode/src/file/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,13 @@ export namespace File {
}
if (!query) {
if (kind === "file") return result.files.slice(0, limit)
return sortHiddenLast(result.dirs.toSorted()).slice(0, limit)
const dirs = sortHiddenLast(result.dirs.toSorted())
if (dirs.length) return dirs.slice(0, limit)
const root = await list("")
return root
.filter((item) => item.type === "directory")
.map((item) => (item.path.endsWith("/") ? item.path : `${item.path}/`))
.slice(0, limit)
Comment thread
picbeats marked this conversation as resolved.
Outdated
}

const items =
Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/src/flag/flag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ export namespace Flag {
export declare const OPENCODE_CLIENT: string
export const OPENCODE_SERVER_PASSWORD = process.env["OPENCODE_SERVER_PASSWORD"]
export const OPENCODE_SERVER_USERNAME = process.env["OPENCODE_SERVER_USERNAME"]
export const OPENCODE_WEB_APP_URL = process.env["OPENCODE_WEB_APP_URL"]
export const OPENCODE_WEB_APP_DIR = process.env["OPENCODE_WEB_APP_DIR"]
export const OPENCODE_ENABLE_QUESTION_TOOL = truthy("OPENCODE_ENABLE_QUESTION_TOOL")

// Experimental
Expand Down
101 changes: 89 additions & 12 deletions packages/opencode/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,52 @@ import { PermissionRoutes } from "./routes/permission"
import { GlobalRoutes } from "./routes/global"
import { MDNS } from "./mdns"
import { lazy } from "@/util/lazy"
import * as path from "node:path"

// @ts-ignore This global is needed to prevent ai-sdk from logging warnings to stdout https://github.com/vercel/ai/blob/2dc67e0ef538307f21368db32d5a12345d98831b/packages/ai/src/logger/log-warnings.ts#L85
globalThis.AI_SDK_LOG_WARNINGS = false

export namespace Server {
const log = Log.create({ service: "server" })

function rewrite(input: string, type: string, base: string, js: "assets" | "all" = "all") {
const root = `${base}/`
const fix = (text: string) =>
text.replaceAll(`${root}hub/assets/`, `${root}assets/`).replaceAll("/hub/assets/", `${root}assets/`)
if (type.includes("text/html")) {
return fix(
input
.replace(/<base\s+href=["'][^"']*["']\s*\/?>/gi, "")
.replace(/((?:src|href|content)=["'])\/(?!\/)/g, `$1${root}`)
.replace(/<head>/i, `<head><base href="${root}">`)
.replace(/\s*<link rel="manifest"[^>]*>\s*/g, "\n"),
)
}
if (type.includes("javascript")) {
const pattern =
js === "all"
? /([=:(,\[]\s*["'])\/(?=(?:global|project|provider|session|find|file|path|event|assets|oc-theme-preload|favicon|apple-touch-icon|social-share))/g
: /([=:(,\[]\s*["'])\/(?=(?:assets|oc-theme-preload|favicon|apple-touch-icon|social-share))/g
return fix(input.replace(pattern, `$1${root}`))
}
if (type.includes("text/css")) {
return fix(input.replace(/url\((["']?)\/(?!\/)/g, `url($1${root}`))
}
return fix(input)
}

function history(base: string) {
return `;(function(){var b=${JSON.stringify(base)};globalThis.__OPENCODE_BASE_PATH=b;var f=function(u){if(typeof u!=="string")return u;if(!u.startsWith("/")||u.startsWith("//"))return u;if(u===b||u.startsWith(b+"/"))return u;return b+u};var p=history.pushState.bind(history);history.pushState=function(s,t,u){return p(s,t,f(u))};var r=history.replaceState.bind(history);history.replaceState=function(s,t,u){return r(s,t,f(u))}})();\n`
}

export const Default = lazy(() => createApp({}))

export const createApp = (opts: { cors?: string[] }): Hono => {
const app = new Hono()
return app
export const createApp = (opts: { cors?: string[]; basePath?: string }): Hono => {
const base = opts.basePath && opts.basePath !== "/" ? opts.basePath : ""
Comment thread
picbeats marked this conversation as resolved.
Outdated
const ui = new URL(Flag.OPENCODE_WEB_APP_URL ?? "https://app.opencode.ai")
Comment thread
picbeats marked this conversation as resolved.
Outdated
const dir = Flag.OPENCODE_WEB_APP_DIR ? path.resolve(Flag.OPENCODE_WEB_APP_DIR) : undefined
const inner = new Hono()
inner
.onError((err, c) => {
log.error("failed", {
error: err,
Expand Down Expand Up @@ -219,7 +253,7 @@ export namespace Server {
.use(WorkspaceRouterMiddleware)
.get(
"/doc",
openAPIRouteHandler(app, {
openAPIRouteHandler(inner, {
documentation: {
info: {
title: "opencode",
Expand Down Expand Up @@ -554,21 +588,63 @@ export namespace Server {
},
)
.all("/*", async (c) => {
const path = c.req.path
const req = c.req.path
const upstream = base ? req.slice(base.length) || "/" : req
const target = new URL(upstream, ui)

Comment thread
picbeats marked this conversation as resolved.
const response = await proxy(`https://app.opencode.ai${path}`, {
...c.req,
headers: {
...c.req.raw.headers,
host: "app.opencode.ai",
},
})
const response = dir
? await (async () => {
const rel = upstream === "/" ? "/index.html" : upstream
const file = path.resolve(dir, "." + rel)
const inside = file === dir || file.startsWith(dir + path.sep)
if (!inside) return new Response("forbidden", { status: 403 })

const asset = Bun.file(file)
if (await asset.exists()) return new Response(asset)

Comment thread
picbeats marked this conversation as resolved.
const route = path.extname(rel) === ""
if (route) {
const index = Bun.file(path.join(dir, "index.html"))
if (await index.exists()) return new Response(index)
}

return new Response("not found", { status: 404 })
})()
: await proxy(target.toString(), {
...c.req,
headers: {
...c.req.raw.headers,
host: ui.host,
},
})
const type = response.headers.get("content-type") ?? ""
const text = type.includes("text/html") || type.includes("javascript") || type.includes("text/css")
if (base && text) {
const mode: "assets" | "all" = dir ? "assets" : "all"
let body = rewrite(await response.text(), type, base, mode)
if (upstream === "/oc-theme-preload.js") body = history(base) + body
const next = new Response(body, response)
next.headers.delete("content-length")
next.headers.delete("etag")
next.headers.delete("last-modified")
next.headers.set("cache-control", "no-store")
next.headers.set(
"Content-Security-Policy",
"default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; media-src 'self' data:; connect-src 'self' data:",
)
return next
}
response.headers.set(
"Content-Security-Policy",
"default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; media-src 'self' data:; connect-src 'self' data:",
)
return response
})

if (!base) return inner
const app = new Hono()
app.route(base, inner)
return app
}

export async function openapi() {
Expand All @@ -595,6 +671,7 @@ export namespace Server {
mdns?: boolean
mdnsDomain?: string
cors?: string[]
basePath?: string
}) {
url = new URL(`http://${opts.hostname}:${opts.port}`)
const app = createApp(opts)
Expand Down
Loading
Loading