Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
21 changes: 21 additions & 0 deletions packages/app/src/pages/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,27 @@ 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 run = () => {
if (document.visibilityState !== "visible") return
const active = sync.data.session_status[id]?.type !== "idle"
if (!active) return
void sync.session.refresh(id)
void sync.session.todo(id)
}

run()
const timer = setInterval(run, 4000)

onCleanup(() => clearInterval(timer))
}),
)

createEffect(
on(
() => visibleUserMessages().at(-1)?.id,
Expand Down
29 changes: 20 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,45 @@ function getNetworkIPs() {
return results
}

function normalizeBasePath(raw: string): string {
const input = raw?.trim()
if (!input) throw new Error("--base-path must not be empty")
const normalized = input.startsWith("/") ? input : `/${input}`
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 +75,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
20 changes: 19 additions & 1 deletion packages/opencode/src/file/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,12 @@ export namespace File {
}
})

const fallback = {
dir: "",
at: 0,
dirs: [] as string[],
}

export function init() {
state()
}
Expand Down Expand Up @@ -638,7 +644,19 @@ 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)
if (fallback.dir === Instance.directory && Date.now() - fallback.at < 2000) {
return fallback.dirs.slice(0, limit)
}
const root = await list("")
const cached = root
.filter((item) => item.type === "directory")
.map((item) => (item.path.endsWith("/") ? item.path : `${item.path}/`))
fallback.dir = Instance.directory
fallback.at = Date.now()
fallback.dirs = cached
return cached.slice(0, limit)
}

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
Loading