mirror of
https://gitee.com/zhangsken/opencode.git
synced 2026-11-18 17:52:03 +08:00
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 733e7852ef | |||
| a5b3802ca3 | |||
| f28d1b44e3 | |||
| b81be469c8 | |||
| fca4a8fa3b | |||
| 8520617ca8 | |||
| ab3566ab82 | |||
| b642c1d9ea |
@@ -54,7 +54,7 @@ Review endpoints in document order. For each endpoint, select one disposition an
|
||||
### [x] `GET /api/health` and `GET /api/server`
|
||||
|
||||
- **Decision:** Merge and rename
|
||||
- **Replacement:** `GET /api/status` with operation ID `server.status`.
|
||||
- **Replacement:** `GET /api/info` with operation ID `server.info`.
|
||||
- **Notes:** Returns `version`, `pid`, and connection `urls`; readiness is conveyed by HTTP status.
|
||||
|
||||
### [x] `GET /api/project/current`
|
||||
@@ -74,7 +74,7 @@ Review endpoints in document order. For each endpoint, select one disposition an
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [x] 001–002 | `GET` | `/api/status` | `server.status` | Keep | Replaces the former health and server endpoints. |
|
||||
| [x] 001–002 | `GET` | `/api/info` | `server.info` | Keep | Replaces the former health and server endpoints. |
|
||||
| [x] 003 | `GET` | `/api/location` | `location.get` | Keep | Workspace selectors and response fields removed until workspace support ships. |
|
||||
| [x] 004 | `GET` | `/api/project` | `project.list` | Keep | Removed unused `time.initialized`; the database column remains for migration data. |
|
||||
| [x] 005 | `PATCH` | `/api/project/{projectID}` | `project.update` | Keep | Request and response accepted as-is. |
|
||||
|
||||
@@ -62,7 +62,8 @@ async function mockServers(page: Page, requests: string[]) {
|
||||
const current = url.origin === serverA ? sessionA : sessionB
|
||||
const directory = url.searchParams.get("directory")
|
||||
if (directory && directory !== current.directory) return json(route, { name: "InvalidDirectory" }, 500)
|
||||
if (url.pathname === "/api/status") return json(route, { version: "test", pid: 1, urls: [url.origin] })
|
||||
if (url.pathname === "/api/info")
|
||||
return json(route, { version: "test", pid: 1, urls: [url.origin], paths: { tmp: "/tmp/opencode" } })
|
||||
if (url.pathname === "/api/session") return json(route, { data: [currentSession(current)], cursor: {} })
|
||||
if (url.pathname === "/api/session/active") return json(route, { data: {} })
|
||||
if (url.pathname === `/api/session/${current.id}`) return json(route, { data: currentSession(current) })
|
||||
|
||||
@@ -16,8 +16,13 @@ test("server dialog keeps focus above fullscreen settings", async ({ page }) =>
|
||||
body: 'data: {"id":"evt_connected","type":"server.connected","data":{}}\n\n',
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/api/status") {
|
||||
return json(route, { version: "2.0.0", pid: 1, urls: [url.origin] })
|
||||
if (url.pathname === "/api/info") {
|
||||
return json(route, {
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: [url.origin],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
}
|
||||
return json(route, {})
|
||||
})
|
||||
|
||||
@@ -138,7 +138,14 @@ test("MCP authentication starts before a slow resource catalog finishes", async
|
||||
test("multiple desktop connections show the session's server name", async ({ page }) => {
|
||||
await mockStressTimeline(page)
|
||||
await page.route("http://secondary.test/**", (route) =>
|
||||
route.fulfill({ json: { version: "2.0.0", pid: 1, urls: ["http://secondary.test"] } }),
|
||||
route.fulfill({
|
||||
json: {
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: ["http://secondary.test"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
},
|
||||
}),
|
||||
)
|
||||
await page.addInitScript(
|
||||
({ directory, server }) => {
|
||||
|
||||
@@ -109,11 +109,11 @@ test("passes through non-event fetches", async ({ page }) => {
|
||||
const timeline = await setupTimeline(page)
|
||||
|
||||
const health = await page.evaluate(async () => {
|
||||
const response = await fetch("/api/status")
|
||||
const response = await fetch("/api/info")
|
||||
return response.json()
|
||||
})
|
||||
|
||||
expect(health).toEqual({ version: "2.0.0", pid: 1, urls: [] })
|
||||
expect(health).toEqual({ version: "2.0.0", pid: 1, urls: [], paths: { tmp: "/tmp/opencode" } })
|
||||
await expect.poll(async () => (await timeline.transport.connections()).length).toBe(1)
|
||||
})
|
||||
|
||||
|
||||
@@ -81,10 +81,10 @@ const fixture = test.extend<{ site: Site }, { builds: Record<string, Record<stri
|
||||
response.setHeader("cache-control", "no-store")
|
||||
if (path === "/observer.html")
|
||||
return void response.writeHead(200, { "content-type": "text/html" }).end("<title>Worker observer</title>")
|
||||
if (path === "/api/status")
|
||||
if (path === "/api/info")
|
||||
return void response
|
||||
.writeHead(200, { "content-type": "application/json" })
|
||||
.end(`{"version":"test","pid":1,"urls":["${url.origin}"]}`)
|
||||
.end(`{"version":"test","pid":1,"urls":["${url.origin}"],"paths":{"tmp":"/tmp/opencode"}}`)
|
||||
if (path === "/sw.js" && state.legacy && state.version === "old") {
|
||||
// Model the shipped worker's shared precache name and cache-first navigation behavior.
|
||||
const urls = Object.keys(builds.old).filter(
|
||||
@@ -334,8 +334,13 @@ fixture("upgrades the legacy shared precache only after old tabs close", async (
|
||||
|
||||
fixture("does not substitute cached HTML for API or missing asset navigations", async ({ page, site }) => {
|
||||
await install(page, site.url)
|
||||
const api = await page.goto(`${site.url}/api/status`)
|
||||
expect(await api?.json()).toEqual({ version: "test", pid: 1, urls: ["http://localhost"] })
|
||||
const api = await page.goto(`${site.url}/api/info`)
|
||||
expect(await api?.json()).toEqual({
|
||||
version: "test",
|
||||
pid: 1,
|
||||
urls: ["http://localhost"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
expect(api?.fromServiceWorker()).toBe(false)
|
||||
const asset = await page.goto(`${site.url}/_assets/missing.js`)
|
||||
expect(asset?.status()).toBe(404)
|
||||
|
||||
@@ -33,7 +33,7 @@ export class MockBadRequest extends Schema.TaggedError<MockBadRequest>()("MockBa
|
||||
}) {}
|
||||
|
||||
const Group = HttpApiGroup.make("mock")
|
||||
.add(HttpApiEndpoint.get("status", "/api/status", { success: Json }))
|
||||
.add(HttpApiEndpoint.get("info", "/api/info", { success: Json }))
|
||||
.add(
|
||||
HttpApiEndpoint.get("event", "/api/event", {
|
||||
success: Schema.String.pipe(HttpApiSchema.asText({ contentType: "text/event-stream" })),
|
||||
|
||||
@@ -219,7 +219,13 @@ function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, st
|
||||
}),
|
||||
)
|
||||
.handleAll({
|
||||
status: () => Effect.succeed({ version: "2.0.0", pid: 1, urls: config.server ? [config.server] : [] }),
|
||||
info: () =>
|
||||
Effect.succeed({
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: config.server ? [config.server] : [],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
}),
|
||||
config: () => Effect.succeed(configEntries),
|
||||
reference: () =>
|
||||
Effect.succeed({
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Icon } from "@opencode/ui/icon"
|
||||
import { getFilename } from "@opencode/util/path"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { sameDirectory } from "@/workspaces/paths"
|
||||
import { WorkspaceSubmenu } from "@/workspaces/submenu"
|
||||
|
||||
export function PromptWorkspaceSelector(props: {
|
||||
value: string
|
||||
@@ -27,20 +28,11 @@ export function PromptWorkspaceSelector(props: {
|
||||
const placement = createMemo(() =>
|
||||
summary() ? (language.direction() === "rtl" ? "right-start" : "left-start") : "bottom",
|
||||
)
|
||||
const [search, setSearch] = createStore({ workspaces: "", branches: "" })
|
||||
let searchInput: HTMLInputElement | undefined
|
||||
const [search, setSearch] = createStore({ branches: "" })
|
||||
let branchSearchInput: HTMLInputElement | undefined
|
||||
let focusSearch = false
|
||||
const branchTruncation = createTruncatedText()
|
||||
const focusWorktreeSearch = () =>
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => searchInput?.focus({ preventScroll: true })))
|
||||
let pending: { type: "select"; value: string } | { type: "create"; branch: string } | { type: "viewAll" } | undefined
|
||||
const selected = () => (sameDirectory(props.value, props.projectRoot) ? "main" : props.value)
|
||||
const workspaces = createMemo(() => {
|
||||
const query = search.workspaces.trim().toLowerCase()
|
||||
if (!query) return props.workspaces
|
||||
return props.workspaces.filter((workspace) => getFilename(workspace).toLowerCase().includes(query))
|
||||
})
|
||||
const icon = () => {
|
||||
if (selected() === "main") return "monitor"
|
||||
if (selected() === "create") return "plus"
|
||||
@@ -51,7 +43,7 @@ export function PromptWorkspaceSelector(props: {
|
||||
}
|
||||
const onOpenChange = (open: boolean) => {
|
||||
if (open) {
|
||||
setSearch({ workspaces: "", branches: "" })
|
||||
setSearch({ branches: "" })
|
||||
props.onSearch("")
|
||||
return
|
||||
}
|
||||
@@ -167,87 +159,12 @@ export function PromptWorkspaceSelector(props: {
|
||||
</Menu.Group>
|
||||
<Show when={props.workspaces.length > 0}>
|
||||
<Menu.Separator class="h-[0.5px]" />
|
||||
<Menu.Sub
|
||||
gutter={0}
|
||||
overlap
|
||||
overflowPadding={24}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
focusSearch = false
|
||||
return
|
||||
}
|
||||
if (!focusSearch || props.workspaces.length < 10) return
|
||||
focusSearch = false
|
||||
focusWorktreeSearch()
|
||||
}}
|
||||
>
|
||||
<Menu.SubTrigger
|
||||
onClick={focusWorktreeSearch}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === "ArrowRight" ||
|
||||
event.key === "ArrowLeft" ||
|
||||
event.key === "Enter" ||
|
||||
event.key === " "
|
||||
)
|
||||
focusSearch = true
|
||||
}}
|
||||
>
|
||||
<Icon name="outline-worktree" />
|
||||
<span class="min-w-0 flex-1 truncate">
|
||||
{language.t("session.new.workspace.existing").replace(/(…|\.{3})$/, "")}
|
||||
</span>
|
||||
</Menu.SubTrigger>
|
||||
<Menu.Portal>
|
||||
<Menu.SubContent class="max-h-[66.667dvh] w-[200px] overflow-y-auto !pb-0 [&>[data-component=menu-v2-item]:last-child]:mb-0.5 [@media(max-height:600px)]:max-h-[calc(100dvh-48px)]">
|
||||
<Show when={props.workspaces.length >= 10}>
|
||||
<div class="flex h-7 items-center gap-2 rounded-sm ps-3 pe-2 text-v2-icon-icon-muted">
|
||||
<Icon name="magnifying-glass" size="small" class="shrink-0" />
|
||||
<input
|
||||
ref={(element) => {
|
||||
searchInput = element
|
||||
}}
|
||||
value={search.workspaces}
|
||||
placeholder={language.t("session.new.workspace.search.placeholder")}
|
||||
aria-label={language.t("session.new.workspace.search.placeholder")}
|
||||
class="h-7 min-w-0 flex-1 border-0 bg-transparent text-[13px] font-[440] leading-5 tracking-[-0.04px] text-v2-text-text-base outline-none placeholder:text-v2-text-text-faint"
|
||||
onInput={(event) => setSearch("workspaces", event.currentTarget.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === "Escape" ||
|
||||
event.key === "ArrowDown" ||
|
||||
event.key === "ArrowUp" ||
|
||||
event.key === "Enter"
|
||||
)
|
||||
return
|
||||
event.stopPropagation()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Show>
|
||||
<For each={workspaces()}>
|
||||
{(workspace) => (
|
||||
<Menu.Item onSelect={() => select(workspace)}>
|
||||
<Icon name="outline-worktree" />
|
||||
<span class="min-w-0 flex-1 truncate">{getFilename(workspace)}</span>
|
||||
<Show when={selected() === workspace}>
|
||||
<Icon name="check" size="small" class="shrink-0" />
|
||||
</Show>
|
||||
</Menu.Item>
|
||||
)}
|
||||
</For>
|
||||
<Show when={search.workspaces.trim() && workspaces().length === 0}>
|
||||
<div class="px-3 py-4 text-center text-[13px] font-[440] leading-5 text-v2-text-text-muted">
|
||||
{language.t("session.new.workspace.search.empty")}
|
||||
</div>
|
||||
</Show>
|
||||
<Menu.Separator class="h-[0.5px]" />
|
||||
<Menu.Item onSelect={() => (pending = { type: "viewAll" })}>
|
||||
<span class="min-w-0 flex-1 truncate">{language.t("common.viewAll")}</span>
|
||||
</Menu.Item>
|
||||
</Menu.SubContent>
|
||||
</Menu.Portal>
|
||||
</Menu.Sub>
|
||||
<WorkspaceSubmenu
|
||||
directories={props.workspaces}
|
||||
selected={selected()}
|
||||
onSelect={select}
|
||||
onViewAll={() => (pending = { type: "viewAll" })}
|
||||
/>
|
||||
</Show>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
|
||||
@@ -90,7 +90,12 @@ test("rotates HTTP and PTY clients together", async () => {
|
||||
const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const request = input instanceof Request ? input : new Request(input, init)
|
||||
requests.push({ url: request.url, authorization: request.headers.get("authorization") })
|
||||
return Response.json({ version: "2.0.0-test", pid: 1, urls: [request.url] })
|
||||
return Response.json({
|
||||
version: "2.0.0-test",
|
||||
pid: 1,
|
||||
urls: [request.url],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
}) as typeof globalThis.fetch
|
||||
const transport = createServerTransport({
|
||||
http: { url: "http://127.0.0.1:4100", password: "first" },
|
||||
@@ -98,23 +103,23 @@ test("rotates HTTP and PTY clients together", async () => {
|
||||
})
|
||||
const initialPty = transport.pty
|
||||
|
||||
await transport.api.server.status()
|
||||
await transport.api.server.info()
|
||||
const replacement = transport.update({
|
||||
url: "http://127.0.0.1:4200",
|
||||
password: "second",
|
||||
})
|
||||
await transport.api.server.status()
|
||||
await transport.api.server.info()
|
||||
|
||||
expect(replacement).toBe(transport.api)
|
||||
expect(transport.pty).not.toBe(initialPty)
|
||||
expect(transport.url).toBe("http://127.0.0.1:4200")
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
url: "http://127.0.0.1:4100/api/status",
|
||||
url: "http://127.0.0.1:4100/api/info",
|
||||
authorization: `Basic ${btoa("opencode:first")}`,
|
||||
},
|
||||
{
|
||||
url: "http://127.0.0.1:4200/api/status",
|
||||
url: "http://127.0.0.1:4200/api/info",
|
||||
authorization: `Basic ${btoa("opencode:second")}`,
|
||||
},
|
||||
])
|
||||
|
||||
@@ -17,7 +17,12 @@ describe("checkServerHealth", () => {
|
||||
const headers: Array<string | null> = []
|
||||
const fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
headers.push(new Headers(init?.headers).get("authorization"))
|
||||
return Response.json({ version: "2.0.0", pid: 1, urls: [server.url] })
|
||||
return Response.json({
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: [server.url],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
}) as typeof globalThis.fetch
|
||||
|
||||
expect(await checkServerHealth({ ...server, password }, fetch)).toEqual({ healthy: true, version: "2.0.0" })
|
||||
@@ -28,16 +33,19 @@ describe("checkServerHealth", () => {
|
||||
let request: URL | undefined
|
||||
const fetch = (async (input: RequestInfo | URL) => {
|
||||
request = input instanceof URL ? input : new URL(input instanceof Request ? input.url : input)
|
||||
return new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
return new Response(
|
||||
JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url], paths: { tmp: "/tmp/opencode" } }),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
)
|
||||
}) as unknown as typeof globalThis.fetch
|
||||
|
||||
const result = await checkServerHealth(server, fetch)
|
||||
|
||||
expect(result).toEqual({ healthy: true, version: "1.2.3" })
|
||||
expect(request?.pathname).toBe("/api/status")
|
||||
expect(request?.pathname).toBe("/api/info")
|
||||
})
|
||||
|
||||
test("allows slow servers thirty seconds by default", async () => {
|
||||
@@ -52,7 +60,7 @@ describe("checkServerHealth", () => {
|
||||
})
|
||||
|
||||
const fetch = (async () =>
|
||||
new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url], paths: { tmp: "/tmp/opencode" } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})) as unknown as typeof globalThis.fetch
|
||||
@@ -111,10 +119,13 @@ describe("checkServerHealth", () => {
|
||||
let signal: AbortSignal | undefined
|
||||
const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
signal = abortFromInput(input, init)
|
||||
return new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
return new Response(
|
||||
JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url], paths: { tmp: "/tmp/opencode" } }),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
)
|
||||
}) as unknown as typeof globalThis.fetch
|
||||
|
||||
const abort = new AbortController()
|
||||
@@ -130,10 +141,13 @@ describe("checkServerHealth", () => {
|
||||
const fetch = (async () => {
|
||||
count += 1
|
||||
if (count < 3) throw new TypeError("network")
|
||||
return new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
return new Response(
|
||||
JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url], paths: { tmp: "/tmp/opencode" } }),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
)
|
||||
}) as unknown as typeof globalThis.fetch
|
||||
|
||||
const result = await checkServerHealth(server, fetch, {
|
||||
|
||||
@@ -95,7 +95,7 @@ export async function checkServerHealth(
|
||||
fetch,
|
||||
headers,
|
||||
})
|
||||
.server.status({ signal })
|
||||
.server.info({ signal })
|
||||
.then((status) => ({ data: { healthy: true as const, version: status.version } }))
|
||||
.catch((error) => ({ error }))
|
||||
if ("data" in current) return current.data
|
||||
|
||||
@@ -195,7 +195,7 @@ describe("createRequestQueue", () => {
|
||||
input.tick(50)
|
||||
input.queue.fetch("http://server/api/worktree?location[directory]=%2Fc").catch(() => undefined)
|
||||
input.tick(100)
|
||||
input.queue.fetch("http://server/api/status").catch(() => undefined)
|
||||
input.queue.fetch("http://server/api/info").catch(() => undefined)
|
||||
expect(input.logs).toEqual([])
|
||||
input.tick(2_000)
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
@@ -210,7 +210,7 @@ describe("createRequestQueue", () => {
|
||||
],
|
||||
queued: [
|
||||
{ method: "GET", url: "http://server/api/worktree?location[directory]=%2Fc", ms: 2_100 },
|
||||
{ method: "GET", url: "http://server/api/status", ms: 2_000 },
|
||||
{ method: "GET", url: "http://server/api/info", ms: 2_000 },
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { isScrollKeyTarget, scrollKey, scrollKeyOwner } from "@opencode/ui/scroll-view"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { useNavigate } from "@solidjs/router"
|
||||
import { createEffect, createMemo, on, onMount, type Accessor } from "solid-js"
|
||||
import { createEffect, createMemo, on, onMount, type Accessor, type JSX } from "solid-js"
|
||||
import { Composer } from "@/composer/composer"
|
||||
import { useComposerState } from "@/composer/persistence"
|
||||
import { createComposerControls } from "@/composer/selection"
|
||||
@@ -213,15 +213,16 @@ export function createActiveSessionRegion(input: {
|
||||
|
||||
export type ActiveSessionRegionModel = ReturnType<typeof createActiveSessionRegion>
|
||||
|
||||
export function ActiveSessionComposerRegion(props: { model: SessionComposerController }) {
|
||||
export function ActiveSessionComposerRegion(props: { model: SessionComposerController; footer?: JSX.Element }) {
|
||||
return (
|
||||
<SessionComposerRegion
|
||||
controller={props.model.region}
|
||||
composer={
|
||||
<div class="relative">
|
||||
<SessionQueuePanel queue={props.model.queue} />
|
||||
<div class="relative z-10">
|
||||
<div class="relative z-10 rounded-xl border border-v2-border-border-base bg-v2-background-bg-deep">
|
||||
<Composer model={props.model.composer} borderUnderlay />
|
||||
{props.footer}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { getFilename } from "@opencode/util/path"
|
||||
import { Show } from "solid-js"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import type { Project } from "@/runtime/server/types"
|
||||
import { containsDirectory, workspaceDirectories } from "@/workspaces/paths"
|
||||
import { SessionWorkspaceMenu } from "../timeline/session-workspace-menu"
|
||||
|
||||
export function SessionWorkspaceFooter(props: {
|
||||
directory: string
|
||||
local: boolean
|
||||
branch?: string
|
||||
move?: { project: Project; sessionID: string; eligible: boolean }
|
||||
}) {
|
||||
const language = useLanguage()
|
||||
const label = () => (
|
||||
<>
|
||||
<Icon
|
||||
name={props.local ? "monitor" : "outline-worktree"}
|
||||
size="small"
|
||||
class={props.local ? "shrink-0 text-v2-icon-icon-muted" : "shrink-0 text-v2-icon-icon-accent"}
|
||||
/>
|
||||
<span dir="auto" class="min-w-0 truncate">
|
||||
{props.local
|
||||
? language.t("session.new.workspace.triggerLocal")
|
||||
: getFilename(
|
||||
(props.move &&
|
||||
workspaceDirectories(props.move.project).find((directory) => containsDirectory(directory, props.directory))) ??
|
||||
props.directory,
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<div data-component="session-workspace-footer" class="w-full shrink-0 rounded-b-xl bg-v2-background-bg-deep">
|
||||
<div
|
||||
class="flex h-9 w-full min-w-0 items-center gap-2 px-2.5 text-[12px] font-[440] leading-text-compact tracking-[-0.04px] text-v2-text-text-faint"
|
||||
>
|
||||
<div class="min-w-0 max-w-[203px]" title={props.directory}>
|
||||
<Show when={props.move} fallback={<div class="flex h-6 min-w-0 items-center gap-1 px-1.5">{label()}</div>}>
|
||||
{(move) => (
|
||||
<SessionWorkspaceMenu
|
||||
project={move().project}
|
||||
sessionID={move().sessionID}
|
||||
eligible={move().eligible}
|
||||
directory={props.directory}
|
||||
placement="top-start"
|
||||
class="flex h-6 min-w-0 max-w-full items-center gap-1 rounded-sm px-1.5 hover:bg-v2-overlay-simple-overlay-hover focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:outline-none data-[expanded]:bg-v2-overlay-simple-overlay-pressed disabled:opacity-50"
|
||||
>
|
||||
{label()}
|
||||
<Icon name="chevron-down" size="small" class="size-3 shrink-0 text-v2-icon-icon-muted" />
|
||||
</SessionWorkspaceMenu>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={props.branch}>
|
||||
{(branch) => (
|
||||
<div
|
||||
class="flex h-5 min-w-0 max-w-[220px] items-center gap-1 rounded-full bg-v2-background-bg-layer-02 px-2"
|
||||
title={branch()}
|
||||
>
|
||||
<Icon name="branch" size="small" class="shrink-0 text-v2-icon-icon-muted" />
|
||||
<span dir="auto" class="min-w-0 truncate">
|
||||
{branch()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import { createSessionTimelineInteraction } from "./timeline/interaction"
|
||||
import { createTimelineSearchController } from "./timeline/search-controller"
|
||||
import { TimelineSearchBar } from "./timeline/search-bar"
|
||||
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
|
||||
import { SessionWorkspaceFooter } from "./composer/workspace-footer"
|
||||
import { SessionIdentityHeader } from "./session-identity-header"
|
||||
import { SessionReviewToggle } from "./header/session-header-actions"
|
||||
import { createAnimatedPresence } from "@/runtime/animated-presence"
|
||||
@@ -182,6 +183,12 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
visible: conversationVisible,
|
||||
})
|
||||
useUsageExceededDialogs()
|
||||
const workspaceMove = createMemo(() => {
|
||||
const project = detailsProject()
|
||||
const sessionID = session.identity.sessionID()
|
||||
if (!project || !sessionID) return
|
||||
return { project, sessionID, eligible: composer.workspaceMoveEligible() }
|
||||
})
|
||||
|
||||
const sessionErrorFallback = (error: unknown, reset: () => void) => {
|
||||
createEffect(on(session.identity.sessionKey, reset, { defer: true }))
|
||||
@@ -325,7 +332,19 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
</div>
|
||||
|
||||
<Show when={composer.active()} keyed>
|
||||
{(model) => <ActiveSessionComposerRegion model={model} />}
|
||||
{(model) => (
|
||||
<ActiveSessionComposerRegion
|
||||
model={model}
|
||||
footer={
|
||||
<SessionWorkspaceFooter
|
||||
move={workspaceMove()}
|
||||
directory={session.workspace.directory()}
|
||||
local={!session.workspace.current()}
|
||||
branch={session.shared.data.location.vcs.info({ directory: session.workspace.directory() })?.branch.current}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type SessionComposerRegionViewController,
|
||||
} from "@/session/composer/session-composer-region"
|
||||
import { SessionPanelFrame, SessionRouteFrame } from "@/session/session-frame"
|
||||
import { SessionWorkspaceFooter } from "@/session/composer/workspace-footer"
|
||||
import type { FormInfo, PermissionRequest, SessionStatus } from "@opencode/client/promise"
|
||||
import type { SessionDocument } from "@opencode/session-ui/document"
|
||||
import { CurrentSessionProviders, STORY_MODEL } from "@opencode/session-ui/storybook"
|
||||
@@ -266,7 +267,12 @@ function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void
|
||||
</div>
|
||||
<SessionComposerRegion
|
||||
controller={region}
|
||||
composer={<Composer model={prompt.controller} borderUnderlay />}
|
||||
composer={
|
||||
<div class="rounded-xl border border-v2-border-border-base bg-v2-background-bg-deep">
|
||||
<Composer model={prompt.controller} borderUnderlay />
|
||||
<SessionWorkspaceFooter directory="/workspace/opencode" local branch="modular-session-ui" />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
<Show when={state.reviewOpened}>
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Menu } from "@opencode/ui/menu"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { getFilename } from "@opencode/util/path"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createSignal, For, onCleanup, Show, type ComponentProps, type JSX } from "solid-js"
|
||||
import { createSignal, onCleanup, Show, type ComponentProps, type JSX } from "solid-js"
|
||||
import type { Project } from "@/runtime/server/types"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useServerSDK } from "@/runtime/server/client"
|
||||
@@ -11,6 +10,7 @@ import { pathKey } from "@/workspaces/path-key"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
import { containsDirectory, sameDirectory, workspaceDirectories } from "@/workspaces/paths"
|
||||
import { createWorktree } from "@/workspaces/create"
|
||||
import { WorkspaceSubmenu } from "@/workspaces/submenu"
|
||||
|
||||
export function SessionWorkspaceMenu(props: {
|
||||
eligible?: boolean
|
||||
@@ -112,24 +112,11 @@ export function SessionWorkspaceMenu(props: {
|
||||
{language.t("workspace.new")}
|
||||
</Menu.Item>
|
||||
<Show when={workspaces().length > 0}>
|
||||
<Menu.Sub gutter={0} overlap overflowPadding={24}>
|
||||
<Menu.SubTrigger>
|
||||
<Icon name="outline-worktree" />
|
||||
{language.t("session.new.workspace.existing").replace(/(…|\.{3})$/, "")}
|
||||
</Menu.SubTrigger>
|
||||
<Menu.Portal>
|
||||
<Menu.SubContent class="max-h-[66.667dvh] w-[200px] overflow-y-auto !pb-0 [&>[data-component=menu-v2-item]:last-child]:mb-0.5 [@media(max-height:600px)]:max-h-[calc(100dvh-48px)]">
|
||||
<For each={workspaces()}>
|
||||
{(workspace) => (
|
||||
<Menu.Item disabled={!!store.selected || blocked()} onSelect={() => void move(workspace)}>
|
||||
<Icon name="outline-worktree" />
|
||||
<span class="min-w-0 flex-1 truncate">{getFilename(workspace)}</span>
|
||||
</Menu.Item>
|
||||
)}
|
||||
</For>
|
||||
</Menu.SubContent>
|
||||
</Menu.Portal>
|
||||
</Menu.Sub>
|
||||
<WorkspaceSubmenu
|
||||
directories={workspaces()}
|
||||
disabled={!!store.selected || blocked()}
|
||||
onSelect={(directory) => void move(directory)}
|
||||
/>
|
||||
</Show>
|
||||
</Menu.Group>
|
||||
</Menu.Content>
|
||||
|
||||
@@ -218,22 +218,30 @@
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 64px) {
|
||||
@container (44px < width <= 64px) {
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]):not([data-editing="true"]):is(:hover, [data-active="true"])
|
||||
[data-slot="tab-link"] {
|
||||
-webkit-mask-image: none;
|
||||
mask-image: none;
|
||||
}
|
||||
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]):not([data-editing="true"]):is(:hover, [data-active="true"])
|
||||
[data-titlebar-tab-title] {
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 44px) {
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]) [data-titlebar-tab-link] {
|
||||
justify-content: center;
|
||||
gap: 0;
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
@media (hover: none) {
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]):not([data-editing="true"]) [data-slot="tab-link"],
|
||||
[data-titlebar-tab][data-title-overflow="true"]:not([data-orientation="vertical"]):not([data-editing="true"]):dir(
|
||||
rtl
|
||||
)
|
||||
[data-slot="tab-link"] {
|
||||
-webkit-mask-image: none;
|
||||
mask-image: none;
|
||||
}
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]):not([data-editing="true"]) [data-slot="tab-link"],
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]):not([data-editing="true"]):dir(rtl) [data-slot="tab-link"] {
|
||||
-webkit-mask-image: none;
|
||||
mask-image: none;
|
||||
}
|
||||
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]) [data-titlebar-tab-title] {
|
||||
@@ -244,6 +252,13 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]):not(:hover):not(:has(:focus-visible))
|
||||
[data-slot="tab-close"] {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-titlebar-tab]:not([data-orientation="vertical"]) [data-slot="tab-close"] {
|
||||
right: auto;
|
||||
left: 50%;
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { Menu } from "@opencode/ui/menu"
|
||||
import { getFilename } from "@opencode/util/path"
|
||||
import { createMemo, For, Show } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
|
||||
export function WorkspaceSubmenu(props: {
|
||||
directories: string[]
|
||||
selected?: string
|
||||
disabled?: boolean
|
||||
onSelect: (directory: string) => void
|
||||
onViewAll?: () => void
|
||||
}) {
|
||||
const language = useLanguage()
|
||||
const [store, setStore] = createStore({ search: "", focusSearch: false })
|
||||
let input: HTMLInputElement | undefined
|
||||
let list: HTMLDivElement | undefined
|
||||
const searchable = () => props.directories.length >= 10
|
||||
const directories = createMemo(() => {
|
||||
const query = store.search.trim().toLowerCase()
|
||||
return props.directories.filter((directory) => getFilename(directory).toLowerCase().includes(query))
|
||||
})
|
||||
const focusSearch = () => {
|
||||
if (!searchable()) return
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => input?.focus({ preventScroll: true })))
|
||||
}
|
||||
|
||||
return (
|
||||
<Menu.Sub
|
||||
gutter={0}
|
||||
overlap
|
||||
overflowPadding={24}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setStore({ search: "", focusSearch: false })
|
||||
return
|
||||
}
|
||||
if (store.focusSearch) focusSearch()
|
||||
setStore("focusSearch", false)
|
||||
}}
|
||||
>
|
||||
<Menu.SubTrigger
|
||||
onClick={focusSearch}
|
||||
onKeyDown={(event) => {
|
||||
if (["ArrowRight", "ArrowLeft", "Enter", " "].includes(event.key)) setStore("focusSearch", true)
|
||||
}}
|
||||
>
|
||||
<Icon name="outline-worktree" />
|
||||
<span class="min-w-0 flex-1 truncate">
|
||||
{language.t("session.new.workspace.existing").replace(/(…|\.{3})$/, "")}
|
||||
</span>
|
||||
</Menu.SubTrigger>
|
||||
<Menu.Portal>
|
||||
<Menu.SubContent
|
||||
data-slot="workspace-submenu"
|
||||
class="max-h-[min(320px,calc(100dvh-48px))] w-[200px] overflow-hidden"
|
||||
>
|
||||
<Show when={searchable()}>
|
||||
<div class="flex h-7 shrink-0 items-center gap-2 rounded-sm ps-3 pe-2 text-v2-icon-icon-muted">
|
||||
<Icon name="magnifying-glass" size="small" class="shrink-0" />
|
||||
<input
|
||||
ref={input}
|
||||
value={store.search}
|
||||
placeholder={language.t("session.new.workspace.search.placeholder")}
|
||||
aria-label={language.t("session.new.workspace.search.placeholder")}
|
||||
class="h-7 min-w-0 flex-1 border-0 bg-transparent text-[13px] font-[440] leading-text-compact tracking-[-0.04px] text-v2-text-text-base outline-none placeholder:text-v2-text-text-faint"
|
||||
onInput={(event) => setStore("search", event.currentTarget.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const items = list?.querySelectorAll<HTMLElement>('[role="menuitem"]:not([data-disabled])')
|
||||
items?.[event.key === "ArrowDown" ? 0 : items.length - 1]?.focus()
|
||||
return
|
||||
}
|
||||
if (["Escape", "Enter"].includes(event.key)) return
|
||||
event.stopPropagation()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Show>
|
||||
<div ref={list} data-slot="workspace-submenu-list" class="min-h-0 overflow-y-auto overscroll-contain">
|
||||
<For each={directories()}>
|
||||
{(directory) => (
|
||||
<Menu.Item disabled={props.disabled} onSelect={() => props.onSelect(directory)}>
|
||||
<Icon name="outline-worktree" />
|
||||
<span class="min-w-0 flex-1 truncate">{getFilename(directory)}</span>
|
||||
<Show when={props.selected === directory}>
|
||||
<Icon name="check" size="small" class="shrink-0" />
|
||||
</Show>
|
||||
</Menu.Item>
|
||||
)}
|
||||
</For>
|
||||
<Show when={store.search.trim() && directories().length === 0}>
|
||||
<div class="px-3 py-4 text-center text-[13px] font-[440] leading-5 text-v2-text-text-muted">
|
||||
{language.t("session.new.workspace.search.empty")}
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={props.onViewAll}>
|
||||
<Menu.Separator class="h-[0.5px] shrink-0" />
|
||||
<Menu.Item onSelect={() => props.onViewAll?.()}>
|
||||
<span class="min-w-0 flex-1 truncate">{language.t("common.viewAll")}</span>
|
||||
</Menu.Item>
|
||||
</Show>
|
||||
</Menu.SubContent>
|
||||
</Menu.Portal>
|
||||
</Menu.Sub>
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { NodeFileSystem } from "@effect/platform-node"
|
||||
import { Service } from "@opencode/client/effect/service"
|
||||
import { ServerStatus } from "@opencode/protocol/groups/server"
|
||||
import { ServerInfo } from "@opencode/protocol/groups/server"
|
||||
import { Effect, Schema } from "effect"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
@@ -42,12 +42,12 @@ try {
|
||||
const credential = btoa(`opencode:${info.password}`)
|
||||
const headers = { authorization: "Basic " + credential }
|
||||
const token = encodeURIComponent(credential)
|
||||
const status = await waitForReady(info.url, headers)
|
||||
if (status.pid !== info.pid) throw new Error("Status process does not match registration")
|
||||
const tokenStatus = await fetch(new URL(`/api/status?auth_token=${token}`, info.url), {
|
||||
const serverInfo = await waitForReady(info.url, headers)
|
||||
if (serverInfo.pid !== info.pid) throw new Error("Server info does not match registration")
|
||||
const tokenInfo = await fetch(new URL(`/api/info?auth_token=${token}`, info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
if (tokenStatus.status !== 200) throw new Error("Compiled service rejected query authentication")
|
||||
if (tokenInfo.status !== 200) throw new Error("Compiled service rejected query authentication")
|
||||
const tokenOpenApi = await fetch(new URL(`/openapi.json?auth_token=${token}`, info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
@@ -57,10 +57,10 @@ try {
|
||||
await fs.writeFile(plugin, pluginSource())
|
||||
await waitForPlugin(info.url, headers)
|
||||
|
||||
const unauthorizedStatus = await fetch(new URL("/api/status", info.url), {
|
||||
const unauthorizedInfo = await fetch(new URL("/api/info", info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
if (unauthorizedStatus.status !== 401) throw new Error("Compiled service exposed status without authentication")
|
||||
if (unauthorizedInfo.status !== 401) throw new Error("Compiled service exposed info without authentication")
|
||||
const unauthorizedOpenApi = await fetch(new URL("/openapi.json", info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
@@ -128,11 +128,11 @@ async function waitForRegistration() {
|
||||
async function waitForReady(url: string, headers: HeadersInit) {
|
||||
const deadline = Date.now() + 20_000
|
||||
while (Date.now() < deadline) {
|
||||
const response = await fetch(new URL("/api/status", url), {
|
||||
const response = await fetch(new URL("/api/info", url), {
|
||||
headers,
|
||||
signal: AbortSignal.timeout(1_000),
|
||||
}).catch(() => undefined)
|
||||
if (response?.ok) return Schema.decodeUnknownPromise(ServerStatus)(await response.json())
|
||||
if (response?.ok) return Schema.decodeUnknownPromise(ServerInfo)(await response.json())
|
||||
await Bun.sleep(25)
|
||||
}
|
||||
throw new Error("Compiled service did not become ready")
|
||||
|
||||
@@ -15,7 +15,7 @@ export default Runtime.handler(
|
||||
const urls = Option.isSome(input.url)
|
||||
? [input.url.value]
|
||||
: (yield* Effect.tryPromise(() =>
|
||||
OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.status(),
|
||||
OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.info(),
|
||||
)).urls
|
||||
const info = { urls, username: "opencode", password }
|
||||
process.stdout.write(
|
||||
|
||||
@@ -29,7 +29,7 @@ export const resolve = Effect.fn("cli.server-connection.resolve")(function* (arg
|
||||
} satisfies Endpoint
|
||||
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
|
||||
const health = yield* Effect.tryPromise({
|
||||
try: () => client.server.status({ signal: AbortSignal.timeout(5_000) }),
|
||||
try: () => client.server.info({ signal: AbortSignal.timeout(5_000) }),
|
||||
catch: (cause) => connectError(endpoint, cause),
|
||||
})
|
||||
if (health.version !== OPENCODE_VERSION)
|
||||
|
||||
@@ -272,7 +272,7 @@ function authServer(fetch: (request: Request, url: URL) => Response | Promise<Re
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
requests?.push(url.pathname)
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/info") return status()
|
||||
if (url.pathname === "/api/model/default") return Response.json(located(null))
|
||||
return fetch(request, url)
|
||||
},
|
||||
@@ -280,7 +280,7 @@ function authServer(fetch: (request: Request, url: URL) => Response | Promise<Re
|
||||
}
|
||||
|
||||
function status() {
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [], paths: { tmp: "/tmp/opencode" } })
|
||||
}
|
||||
|
||||
function located<T>(data: T) {
|
||||
|
||||
@@ -39,9 +39,14 @@ describe("debug config command", () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/status") {
|
||||
if (url.pathname === "/api/info") {
|
||||
healthProbes += 1
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
return Response.json({
|
||||
version: OPENCODE_VERSION,
|
||||
pid: process.pid,
|
||||
urls: [],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
}
|
||||
requested = url
|
||||
authorization.push(request.headers.get("authorization"))
|
||||
|
||||
@@ -12,7 +12,7 @@ await Effect.runPromise(
|
||||
command: [process.execPath, path.join(import.meta.dir, "../../src/index.ts"), "serve"],
|
||||
})
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/status", endpoint.url), { headers: Service.headers(endpoint) }),
|
||||
fetch(new URL("/api/info", endpoint.url), { headers: Service.headers(endpoint) }),
|
||||
)
|
||||
console.log(`STANDALONE_READY ${endpoint.pid} ${endpoint.url} ${response.status}`)
|
||||
return yield* Effect.never
|
||||
|
||||
@@ -42,7 +42,8 @@ const sanitizedTransfer = {
|
||||
],
|
||||
}
|
||||
|
||||
const status = () => Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
const status = () =>
|
||||
Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [], paths: { tmp: "/tmp/opencode" } })
|
||||
|
||||
function run(args: string[], stdin?: string) {
|
||||
const child = Bun.spawn([process.execPath, "run", "src/index.ts", ...args], {
|
||||
@@ -60,7 +61,7 @@ test("export is raw by default and supports explicit sanitization", async () =>
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/info") return status()
|
||||
if (url.pathname === `/api/session/${info.id}`) return Response.json({ data: info })
|
||||
if (url.pathname === `/api/experimental/session/${info.id}/export`) {
|
||||
sanitization.push(url.searchParams.get("sanitize") ?? "")
|
||||
@@ -98,7 +99,7 @@ test("export requires a session outside an interactive terminal", async () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/info") return status()
|
||||
if (url.pathname === "/api/location") {
|
||||
return Response.json({
|
||||
directory: "/project",
|
||||
@@ -127,7 +128,7 @@ test("export reports a missing session without a stack trace", async () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/info") return status()
|
||||
if (url.pathname === `/api/experimental/session/${sessionID}/export`) {
|
||||
return Response.json(
|
||||
{ _tag: "SessionNotFoundError", sessionID, message: `Session not found: ${sessionID}` },
|
||||
@@ -158,7 +159,7 @@ test("import validates a file and sends it to the resolved location", async () =
|
||||
port: 0,
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/info") return status()
|
||||
if (url.pathname === "/api/location") {
|
||||
return Response.json({
|
||||
directory: root,
|
||||
@@ -201,7 +202,7 @@ test("import reports an existing session without a stack trace", async () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/info") return status()
|
||||
if (url.pathname === "/api/location") {
|
||||
return Response.json({
|
||||
directory: root,
|
||||
|
||||
@@ -31,14 +31,24 @@ describe("mini command", () => {
|
||||
const initial = Bun.serve({
|
||||
port: 0,
|
||||
fetch() {
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
return Response.json({
|
||||
version: OPENCODE_VERSION,
|
||||
pid: process.pid,
|
||||
urls: [],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
},
|
||||
})
|
||||
const replacement = Bun.serve({
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
authorization.push(request.headers.get("authorization"))
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
return Response.json({
|
||||
version: OPENCODE_VERSION,
|
||||
pid: process.pid,
|
||||
urls: [],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
},
|
||||
})
|
||||
const controller = new AbortController()
|
||||
@@ -57,7 +67,7 @@ describe("mini command", () => {
|
||||
})
|
||||
const client = await connection.reconnect?.(controller.signal)
|
||||
if (!client) throw new Error("Expected a replacement client")
|
||||
await client.server.status()
|
||||
await client.server.info()
|
||||
|
||||
expect(client).not.toBe(connection.sdk)
|
||||
expect(signal).toBe(controller.signal)
|
||||
@@ -147,8 +157,13 @@ describe("mini command", () => {
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
requests.push(url.pathname)
|
||||
if (url.pathname === "/api/status")
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
if (url.pathname === "/api/info")
|
||||
return Response.json({
|
||||
version: OPENCODE_VERSION,
|
||||
pid: process.pid,
|
||||
urls: [],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
if (url.pathname === "/api/location")
|
||||
return Response.json({ directory: process.cwd(), project: { id: "global", directory: process.cwd() } })
|
||||
if (url.pathname === "/api/session") {
|
||||
@@ -190,7 +205,12 @@ describe("mini command", () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
if (new URL(request.url).pathname === "/api/session") return new Response("boom", { status: 500 })
|
||||
return Response.json({ version: "incompatible", pid: process.pid, urls: [] })
|
||||
return Response.json({
|
||||
version: "incompatible",
|
||||
pid: process.pid,
|
||||
urls: [],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -256,13 +256,14 @@ test("concurrent service processes elect one server", async () => {
|
||||
expect((await Bun.file(config).json()).password).toBe(info.password)
|
||||
expect(await Bun.file(registration + ".lock").exists()).toBe(false)
|
||||
expect(
|
||||
await fetch(new URL("/api/status", info.url), {
|
||||
await fetch(new URL("/api/info", info.url), {
|
||||
headers: { authorization: "Basic " + btoa(`opencode:${info.password}`) },
|
||||
}).then((response) => response.json()),
|
||||
).toEqual({
|
||||
version: info.version,
|
||||
pid: info.pid,
|
||||
urls: [info.url],
|
||||
paths: { tmp: path.join(os.tmpdir(), "opencode") },
|
||||
})
|
||||
const contender = Bun.spawn(command, { env, stderr: "pipe", stdout: "ignore" })
|
||||
try {
|
||||
@@ -337,7 +338,7 @@ test.each([
|
||||
const info = await waitForInfo(registration)
|
||||
await Promise.all(
|
||||
[...new Set([...cors, ...origins, "https://unlisted.example.com"])].map(async (origin) => {
|
||||
const response = await fetch(new URL("/api/status", info.url), {
|
||||
const response = await fetch(new URL("/api/info", info.url), {
|
||||
method: "OPTIONS",
|
||||
headers: { Origin: origin, "Access-Control-Request-Method": "GET" },
|
||||
})
|
||||
@@ -440,7 +441,10 @@ test("port contender recognizes an incumbent registered during the bind race", a
|
||||
fetch() {
|
||||
requests.count += 1
|
||||
if (requests.count === 2) recognizing.resolve()
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] }, { status: 503 })
|
||||
return Response.json(
|
||||
{ version: OPENCODE_VERSION, pid: process.pid, urls: [], paths: { tmp: "/tmp/opencode" } },
|
||||
{ status: 503 },
|
||||
)
|
||||
},
|
||||
})
|
||||
const registration = path.join(root, "state", "opencode", "service-local.json")
|
||||
@@ -575,7 +579,7 @@ async function waitForInfo(file: string, accept: (info: Info) => boolean = () =>
|
||||
|
||||
async function waitForFailed(info: Info) {
|
||||
for (let attempt = 0; attempt < 400; attempt++) {
|
||||
const status = await fetch(new URL("/api/status", info.url), {
|
||||
const status = await fetch(new URL("/api/info", info.url), {
|
||||
headers: { authorization: "Basic " + btoa(`opencode:${info.password}`) },
|
||||
})
|
||||
.then((response) => response.status)
|
||||
|
||||
@@ -35,8 +35,13 @@ describe("web UI", () => {
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest
|
||||
const pathname = new URL(request.url, "http://localhost").pathname
|
||||
if (pathname === "/api/status")
|
||||
return HttpServerResponse.jsonUnsafe({ version: "test", pid: 1, urls: [origin] })
|
||||
if (pathname === "/api/info")
|
||||
return HttpServerResponse.jsonUnsafe({
|
||||
version: "test",
|
||||
pid: 1,
|
||||
urls: [origin],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
return yield* Effect.fail(
|
||||
new HttpServerError.HttpServerError({
|
||||
reason: new HttpServerError.RouteNotFound({ request }),
|
||||
@@ -47,8 +52,13 @@ describe("web UI", () => {
|
||||
)
|
||||
const origin = HttpServer.formatAddress(http.address)
|
||||
|
||||
const status = yield* Effect.promise(() => fetch(`${origin}/api/status`))
|
||||
expect(yield* Effect.promise(() => status.json())).toEqual({ version: "test", pid: 1, urls: [origin] })
|
||||
const status = yield* Effect.promise(() => fetch(`${origin}/api/info`))
|
||||
expect(yield* Effect.promise(() => status.json())).toEqual({
|
||||
version: "test",
|
||||
pid: 1,
|
||||
urls: [origin],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
|
||||
const missing = yield* Effect.promise(() => fetch(`${origin}/api/missing`))
|
||||
expect(missing.status).toBe(404)
|
||||
|
||||
@@ -39,15 +39,16 @@ import type { Vcs } from "@opencode/schema/vcs"
|
||||
import type { WebSearch } from "@opencode/schema/websearch"
|
||||
import type { Config } from "@opencode/schema/config"
|
||||
|
||||
export type ServerStatusOutput = {
|
||||
export type ServerInfoOutput = {
|
||||
readonly version: string
|
||||
readonly pid: number
|
||||
readonly urls: ReadonlyArray<string>
|
||||
readonly paths: { readonly tmp: string }
|
||||
}
|
||||
export type ServerStatusOperation<E = never> = () => Effect.Effect<ServerStatusOutput, E>
|
||||
export type ServerInfoOperation<E = never> = () => Effect.Effect<ServerInfoOutput, E>
|
||||
|
||||
export interface ServerApi<E = never> {
|
||||
readonly status: ServerStatusOperation<E>
|
||||
readonly info: ServerInfoOperation<E>
|
||||
}
|
||||
|
||||
export type LocationGetInput = { readonly location?: { readonly directory?: string | undefined } | undefined }
|
||||
|
||||
@@ -5,7 +5,7 @@ import { HttpClientError } from "effect/unstable/http"
|
||||
import { HttpApiClient } from "effect/unstable/httpapi"
|
||||
import { ClientApi } from "../../contract"
|
||||
import type {
|
||||
ServerStatusOutput,
|
||||
ServerInfoOutput,
|
||||
LocationGetInput,
|
||||
LocationGetOutput,
|
||||
LocationReloadOutput,
|
||||
@@ -278,10 +278,10 @@ const preserveStream =
|
||||
<E, R>(stream: Stream.Stream<A, E, R>) =>
|
||||
stream
|
||||
|
||||
const EndpointServerStatus = (raw: RawClient["server.server"]) => () =>
|
||||
preserveEffect<ServerStatusOutput>()(raw["server.status"]({}).pipe(Effect.mapError(mapClientError)))
|
||||
const EndpointServerInfo = (raw: RawClient["server.server"]) => () =>
|
||||
preserveEffect<ServerInfoOutput>()(raw["server.info"]({}).pipe(Effect.mapError(mapClientError)))
|
||||
|
||||
const adaptGroupServer = (raw: RawClient["server.server"]) => ({ status: EndpointServerStatus(raw) })
|
||||
const adaptGroupServer = (raw: RawClient["server.server"]) => ({ info: EndpointServerInfo(raw) })
|
||||
|
||||
const EndpointLocationGet = (raw: RawClient["server.location"]) => (input?: LocationGetInput) =>
|
||||
preserveEffect<LocationGetOutput>()(
|
||||
|
||||
@@ -172,7 +172,7 @@ export const Info = Schema.Struct({
|
||||
})
|
||||
|
||||
const decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))
|
||||
const decodeStatus = Schema.decodeUnknownOption(
|
||||
const decodeInfo = Schema.decodeUnknownOption(
|
||||
Schema.Struct({
|
||||
version: Schema.String,
|
||||
pid: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
@@ -213,7 +213,7 @@ const probeResult = Effect.fnUntraced(function* (
|
||||
} satisfies Endpoint
|
||||
const signal = AbortSignal.timeout(timeout)
|
||||
const result = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/status", info.url), { headers: headers(endpoint), signal })
|
||||
fetch(new URL("/api/info", info.url), { headers: headers(endpoint), signal })
|
||||
.then(async (response) => ({
|
||||
response,
|
||||
body: response.status === 404 ? undefined : ((await response.json()) as unknown),
|
||||
@@ -225,7 +225,7 @@ const probeResult = Effect.fnUntraced(function* (
|
||||
)
|
||||
if ("cause" in result) return { service: undefined, timedOut: signal.aborted }
|
||||
const response = result.value.response
|
||||
// The previous V2 service exposes /api/health instead. Its authenticated 404 is enough
|
||||
// The previous V2 service exposes /api/status instead. Its authenticated 404 is enough
|
||||
// to recognize the registered daemon as incompatible and route it through replacement.
|
||||
if (response.status === 404)
|
||||
return {
|
||||
@@ -239,16 +239,16 @@ const probeResult = Effect.fnUntraced(function* (
|
||||
timedOut: false,
|
||||
}
|
||||
const body = result.value.body
|
||||
const status = decodeStatus(body)
|
||||
if (Option.isSome(status)) {
|
||||
if (status.value.pid !== info.pid) return { service: undefined, timedOut: false }
|
||||
if (info.version !== undefined && status.value.version !== info.version)
|
||||
const serverInfo = decodeInfo(body)
|
||||
if (Option.isSome(serverInfo)) {
|
||||
if (serverInfo.value.pid !== info.pid) return { service: undefined, timedOut: false }
|
||||
if (info.version !== undefined && serverInfo.value.version !== info.version)
|
||||
return { service: undefined, timedOut: false }
|
||||
return {
|
||||
service: {
|
||||
info,
|
||||
endpoint,
|
||||
version: status.value.version,
|
||||
version: serverInfo.value.version,
|
||||
state: response.ok ? "ready" : response.status === 500 ? "failed" : "waiting",
|
||||
compatible: true,
|
||||
} satisfies LocalService,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type {
|
||||
ServerStatusOutput,
|
||||
ServerInfoOutput,
|
||||
LocationGetInput,
|
||||
LocationGetOutput,
|
||||
LocationReloadOutput,
|
||||
@@ -398,9 +398,9 @@ export function make(options: ClientOptions) {
|
||||
|
||||
return {
|
||||
server: {
|
||||
status: (requestOptions?: RequestOptions) =>
|
||||
request<ServerStatusOutput>(
|
||||
{ method: "GET", path: `/api/status`, successStatus: 200, declaredStatuses: [400, 401], empty: false },
|
||||
info: (requestOptions?: RequestOptions) =>
|
||||
request<ServerInfoOutput>(
|
||||
{ method: "GET", path: `/api/info`, successStatus: 200, declaredStatuses: [400, 401], empty: false },
|
||||
requestOptions,
|
||||
),
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export type JsonValue = null | boolean | number | string | Array<JsonValue> | { [key: string]: JsonValue }
|
||||
|
||||
export type ServerStatus = { version: string; pid: number; urls: Array<string> }
|
||||
export type ServerInfo = { version: string; pid: number; urls: Array<string>; paths: { tmp: string } }
|
||||
|
||||
export type LocationPublicInfo = { directory: string; project: { id: string; directory: string; canonical: string } }
|
||||
|
||||
@@ -2655,7 +2655,7 @@ export type WorktreeError = {
|
||||
export const isWorktreeError = (value: unknown): value is WorktreeError =>
|
||||
typeof value === "object" && value !== null && "name" in value && value["name"] === "WorktreeError"
|
||||
|
||||
export type ServerStatusOutput = ServerStatus
|
||||
export type ServerInfoOutput = ServerInfo
|
||||
|
||||
export type LocationGetInput = {
|
||||
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
|
||||
|
||||
@@ -163,7 +163,7 @@ async function probeResult(info: Info, timeout = defaultEnsureTiming.requestTime
|
||||
: { type: "basic" as const, username: "opencode", password: info.password },
|
||||
} satisfies Endpoint
|
||||
const signal = AbortSignal.timeout(timeout)
|
||||
const result = await fetch(new URL("/api/status", info.url), { headers: headers(endpoint), signal })
|
||||
const result = await fetch(new URL("/api/info", info.url), { headers: headers(endpoint), signal })
|
||||
.then(async (response) => ({
|
||||
response,
|
||||
body: response.status === 404 ? undefined : ((await response.json()) as unknown),
|
||||
@@ -174,7 +174,7 @@ async function probeResult(info: Info, timeout = defaultEnsureTiming.requestTime
|
||||
)
|
||||
if ("cause" in result) return { service: undefined, timedOut: signal.aborted }
|
||||
const response = result.value.response
|
||||
// The previous V2 service exposes /api/health instead. Its authenticated 404 is enough
|
||||
// The previous V2 service exposes /api/status instead. Its authenticated 404 is enough
|
||||
// to recognize the registered daemon as incompatible and route it through replacement.
|
||||
if (response.status === 404)
|
||||
return {
|
||||
@@ -187,15 +187,16 @@ async function probeResult(info: Info, timeout = defaultEnsureTiming.requestTime
|
||||
} satisfies LocalService,
|
||||
timedOut: false,
|
||||
}
|
||||
const status = decodeStatus(result.value.body)
|
||||
if (status !== undefined) {
|
||||
if (status.pid !== info.pid) return { service: undefined, timedOut: false }
|
||||
if (info.version !== undefined && status.version !== info.version) return { service: undefined, timedOut: false }
|
||||
const serverInfo = decodeInfo(result.value.body)
|
||||
if (serverInfo !== undefined) {
|
||||
if (serverInfo.pid !== info.pid) return { service: undefined, timedOut: false }
|
||||
if (info.version !== undefined && serverInfo.version !== info.version)
|
||||
return { service: undefined, timedOut: false }
|
||||
return {
|
||||
service: {
|
||||
info,
|
||||
endpoint,
|
||||
version: status.version,
|
||||
version: serverInfo.version,
|
||||
state: response.ok ? "ready" : response.status === 500 ? "failed" : "waiting",
|
||||
compatible: true,
|
||||
} satisfies LocalService,
|
||||
@@ -205,7 +206,7 @@ async function probeResult(info: Info, timeout = defaultEnsureTiming.requestTime
|
||||
return { service: undefined, timedOut: false }
|
||||
}
|
||||
|
||||
function decodeStatus(input: unknown) {
|
||||
function decodeInfo(input: unknown) {
|
||||
if (typeof input !== "object" || input === null) return
|
||||
if (!("version" in input) || typeof input.version !== "string") return
|
||||
if (!("pid" in input) || typeof input.pid !== "number" || !Number.isInteger(input.pid) || input.pid < 0) return
|
||||
|
||||
@@ -592,12 +592,6 @@ export function createData(config: CreateDataInput) {
|
||||
|
||||
function handleEvent(event: OpenCodeEvent) {
|
||||
switch (event.type) {
|
||||
case "location.shutdown": {
|
||||
if (!event.location) return
|
||||
result.location.invalidate(event.location)
|
||||
refresh(() => result.location.sync(event.location))
|
||||
return
|
||||
}
|
||||
case "server.connected": {
|
||||
const updates = new Map<string, DataSessionStatus | undefined>()
|
||||
activeUpdates = updates
|
||||
|
||||
@@ -15,21 +15,31 @@ import {
|
||||
|
||||
const synced = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1) }
|
||||
|
||||
test("server.status decodes the readiness response", async () => {
|
||||
test("server.info decodes the readiness response", async () => {
|
||||
const httpClient = HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ version: "current", pid: 123, urls: ["http://localhost:3000"] }),
|
||||
Response.json({
|
||||
version: "current",
|
||||
pid: 123,
|
||||
urls: ["http://localhost:3000"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
const result = await Effect.gen(function* () {
|
||||
const client = yield* OpenCode.make({ baseUrl: "http://localhost:3000" })
|
||||
return yield* client.server.status()
|
||||
return yield* client.server.info()
|
||||
}).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.runPromise)
|
||||
|
||||
expect(result).toEqual({ version: "current", pid: 123, urls: ["http://localhost:3000"] })
|
||||
expect(result).toEqual({
|
||||
version: "current",
|
||||
pid: 123,
|
||||
urls: ["http://localhost:3000"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
})
|
||||
|
||||
test("vcs.base decodes nullable review-base metadata", async () => {
|
||||
|
||||
@@ -52,7 +52,7 @@ const server = Bun.serve({
|
||||
await writeFile(registration + ".prepared", JSON.stringify(handoff))
|
||||
return Response.json({ handoff })
|
||||
}
|
||||
if (pathname !== "/api/status") return new Response(null, { status: 404 })
|
||||
if (pathname !== "/api/info") return new Response(null, { status: 404 })
|
||||
requests += 1
|
||||
if (mode === "starting") await writeFile(registration + ".status-request", "")
|
||||
if (mode === "hanging") {
|
||||
@@ -65,10 +65,21 @@ const server = Bun.serve({
|
||||
return new Response(null, { status: 503 })
|
||||
}
|
||||
if (mode === "starting" && !(await Bun.file(registration + ".release").exists()))
|
||||
return Response.json({ version, pid: process.pid, urls: [server.url.toString()] }, { status: 503 })
|
||||
return Response.json(
|
||||
{ version, pid: process.pid, urls: [server.url.toString()], paths: { tmp: "/tmp/opencode" } },
|
||||
{ status: 503 },
|
||||
)
|
||||
if (mode === "failed-owner")
|
||||
return Response.json({ version, pid: process.pid, urls: [server.url.toString()] }, { status: 500 })
|
||||
return Response.json({ version, pid: process.pid, urls: [server.url.toString()] })
|
||||
return Response.json(
|
||||
{ version, pid: process.pid, urls: [server.url.toString()], paths: { tmp: "/tmp/opencode" } },
|
||||
{ status: 500 },
|
||||
)
|
||||
return Response.json({
|
||||
version,
|
||||
pid: process.pid,
|
||||
urls: [server.url.toString()],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -192,19 +192,29 @@ test("websearch.query uses the public HTTP contract", async () => {
|
||||
expect(await request?.json()).toEqual({ query: "opencode", providerID: "exa" })
|
||||
})
|
||||
|
||||
test("server.status uses the public HTTP contract", async () => {
|
||||
test("server.info uses the public HTTP contract", async () => {
|
||||
let request: Request | undefined
|
||||
const client = OpenCode.make({
|
||||
baseUrl: "http://localhost:3000",
|
||||
fetch: async (input) => {
|
||||
request = input instanceof Request ? input : new Request(input)
|
||||
return Response.json({ version: "2.0.0", pid: 1, urls: ["http://192.168.1.10:4096"] })
|
||||
return Response.json({
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: ["http://192.168.1.10:4096"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
expect(await client.server.status()).toEqual({ version: "2.0.0", pid: 1, urls: ["http://192.168.1.10:4096"] })
|
||||
expect(await client.server.info()).toEqual({
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: ["http://192.168.1.10:4096"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
expect(request?.method).toBe("GET")
|
||||
expect(request?.url).toBe("http://localhost:3000/api/status")
|
||||
expect(request?.url).toBe("http://localhost:3000/api/info")
|
||||
})
|
||||
|
||||
test("experimental wellknown integration add uses the public HTTP contract", async () => {
|
||||
@@ -686,7 +696,7 @@ test("event.subscribe reports heartbeat comments as stream activity", async () =
|
||||
})
|
||||
|
||||
// Moved from packages/app/e2e/regression/session-timeline-transport.spec.ts
|
||||
test("event transport passes through ordinary status requests", async () => {
|
||||
test("event transport passes through ordinary info requests", async () => {
|
||||
const requests: string[] = []
|
||||
const event = { id: "evt_connected", created: 1, type: "server.connected", data: {} }
|
||||
const client = OpenCode.make({
|
||||
@@ -699,16 +709,22 @@ test("event transport passes through ordinary status requests", async () => {
|
||||
headers: { "content-type": "text/event-stream" },
|
||||
})
|
||||
}
|
||||
return Response.json({ version: "2.0.0", pid: 1, urls: ["http://localhost:3000"] })
|
||||
return Response.json({
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: ["http://localhost:3000"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
},
|
||||
})
|
||||
await expect(client.event.subscribe()[Symbol.asyncIterator]().next()).resolves.toEqual({ done: false, value: event })
|
||||
await expect(client.server.status()).resolves.toEqual({
|
||||
await expect(client.server.info()).resolves.toEqual({
|
||||
version: "2.0.0",
|
||||
pid: 1,
|
||||
urls: ["http://localhost:3000"],
|
||||
paths: { tmp: "/tmp/opencode" },
|
||||
})
|
||||
expect(requests).toEqual(["/api/event", "/api/status"])
|
||||
expect(requests).toEqual(["/api/event", "/api/info"])
|
||||
})
|
||||
|
||||
test("event.subscribe terminates on malformed Promise SSE data", async () => {
|
||||
|
||||
@@ -300,5 +300,5 @@ function run<A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>) {
|
||||
}
|
||||
|
||||
async function status(url: string) {
|
||||
return fetch(new URL("/api/status", url), { signal: AbortSignal.timeout(1_000) }).then((response) => response.json())
|
||||
return fetch(new URL("/api/info", url), { signal: AbortSignal.timeout(1_000) }).then((response) => response.json())
|
||||
}
|
||||
|
||||
@@ -235,7 +235,7 @@ describe("OpenAPI.fromSpec", () => {
|
||||
path: "/api/fs/read/*",
|
||||
reason: "binary responses are not supported",
|
||||
})
|
||||
expect(toolAt(result.tools, "server.status")).not.toBeUndefined()
|
||||
expect(toolAt(result.tools, "server.info")).not.toBeUndefined()
|
||||
expect(toolAt(result.tools, "session.get")).not.toBeUndefined()
|
||||
expect(toolAt(result.tools, "session.create")).not.toBeUndefined()
|
||||
|
||||
@@ -978,10 +978,10 @@ describe("OpenAPI.fromSpec", () => {
|
||||
|
||||
expect(spec.security).toStrictEqual([])
|
||||
expect(isRecord(components.securitySchemes) ? Object.keys(components.securitySchemes) : []).toStrictEqual([])
|
||||
const status = toolAt(result.tools, "server.status")
|
||||
const statusInput = Tool.isTool(status) && isRecord(status.input) ? status.input : undefined
|
||||
expect(statusInput).toMatchObject({ type: "object", properties: {} })
|
||||
const input = isRecord(statusInput) ? statusInput : {}
|
||||
const info = toolAt(result.tools, "server.info")
|
||||
const infoInput = Tool.isTool(info) && isRecord(info.input) ? info.input : undefined
|
||||
expect(infoInput).toMatchObject({ type: "object", properties: {} })
|
||||
const input = isRecord(infoInput) ? infoInput : {}
|
||||
expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual([])
|
||||
})
|
||||
|
||||
@@ -994,7 +994,7 @@ describe("OpenAPI.fromSpec", () => {
|
||||
runtime
|
||||
.execute(
|
||||
`
|
||||
return search({ query: "server status", namespace: "opencode", limit: 1 })
|
||||
return search({ query: "server info", namespace: "opencode", limit: 1 })
|
||||
`,
|
||||
)
|
||||
.pipe(Effect.provide(layer)),
|
||||
@@ -1005,8 +1005,8 @@ describe("OpenAPI.fromSpec", () => {
|
||||
expect(result.value).toMatchObject({
|
||||
items: [
|
||||
{
|
||||
path: "tools.opencode.server.status",
|
||||
description: "Return the server identity, connection URLs, and readiness status.",
|
||||
path: "tools.opencode.server.info",
|
||||
description: "Return the server identity, connection URLs, paths, and readiness status.",
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
@@ -81,6 +81,8 @@ type ServerEntry = {
|
||||
// persisted session row, so their forms are owned by this opaque sentinel session identifier.
|
||||
const GLOBAL_ELICITATION_SESSION_ID = "global"
|
||||
const URL_ELICITATION_FIELD_KEY = "elicitation"
|
||||
// Connections remain Location-scoped, but shared remote endpoints should not receive concurrent startup bursts.
|
||||
const endpointLoads = KeyedMutex.makeUnsafe<string>()
|
||||
|
||||
type Data = {
|
||||
servers: Map<ServerName, Types.DeepMutable<Mcp.ServerConfig>>
|
||||
@@ -387,7 +389,7 @@ export const layer = (options?: Options) =>
|
||||
const { McpClient } = yield* Effect.promise(() => import("./client.js"))
|
||||
// List tools as part of connect so a failure here marks the server failed rather than
|
||||
// leaving it connected with a silently empty tool list and no path to recover.
|
||||
const result = yield* McpClient.connect(
|
||||
const load = McpClient.connect(
|
||||
name,
|
||||
entry.config,
|
||||
location.directory,
|
||||
@@ -399,8 +401,10 @@ export const layer = (options?: Options) =>
|
||||
// A stdio server is spawned on this location's execution plane, not the host's.
|
||||
Effect.provideService(Environment.Service, environment),
|
||||
Scope.provide(scope),
|
||||
Effect.exit,
|
||||
)
|
||||
const result = yield* (
|
||||
entry.config.type === "remote" ? endpointLoads.withLock(entry.config.url)(load) : load
|
||||
).pipe(Effect.exit)
|
||||
if (Exit.isSuccess(result)) {
|
||||
entry.client = result.value.connection
|
||||
entry.tools = result.value.tools.map((tool) => toTool(name, entry, tool))
|
||||
|
||||
@@ -46,10 +46,13 @@ project-local CLI configuration. Set `OPENCODE_CLI_CONFIG_CONTENT` to merge
|
||||
inline JSON over the global settings. Most preferences can also be changed from
|
||||
the TUI by pressing `Ctrl+P` and selecting **Open settings**.
|
||||
|
||||
Fetch the full [CLI configuration guide](https://opencode.ai/v2/docs/cli/config)
|
||||
before editing `cli.json`. It covers terminal-only settings such as themes,
|
||||
keybindings, terminal plugins, scrolling, attention alerts, diff presentation,
|
||||
and terminal integration. Do not put these settings in `opencode.json(c)`.
|
||||
### [Settings](https://opencode.ai/v2/docs/cli/config)
|
||||
|
||||
Fetch the full [CLI settings reference](https://opencode.ai/v2/docs/cli/config)
|
||||
before editing `cli.json`. It documents every terminal-only setting, accepted
|
||||
values, and examples, including themes, input, sessions, tabs, diffs, alerts,
|
||||
Mini, keybindings, terminal plugins, and debugging. Do not put these settings
|
||||
in `opencode.json(c)`.
|
||||
|
||||
### [Keybinds](https://opencode.ai/v2/docs/cli/keybinds)
|
||||
|
||||
@@ -93,7 +96,7 @@ Common configuration fields include `model`, `default_agent`, `permissions`,
|
||||
`references`, `formatter`, and `lsp`.
|
||||
|
||||
This configuration is distinct from `cli.json`. Use the
|
||||
[CLI configuration guide](https://opencode.ai/v2/docs/cli/config) for terminal
|
||||
[CLI settings reference](https://opencode.ai/v2/docs/cli/config) for terminal
|
||||
preferences, especially themes and keybindings.
|
||||
|
||||
Do not guess field names or shapes. Fetch the V2 configuration guide and its
|
||||
@@ -191,7 +194,7 @@ HTTP method and path or an OpenAPI operation ID.
|
||||
Call an endpoint with an HTTP method and path:
|
||||
|
||||
```sh
|
||||
opencode api get /api/status
|
||||
opencode api get /api/info
|
||||
```
|
||||
|
||||
Pass a request body with `--data` or `-d`, and additional headers with
|
||||
@@ -242,7 +245,7 @@ OpenCode runs a client and a background server. Start by determining whether a
|
||||
problem belongs to the client, the shared server, or one project.
|
||||
|
||||
- Check the service with `opencode service status` and verify the API with
|
||||
`opencode api get /api/status`.
|
||||
`opencode api get /api/info`.
|
||||
- Compare with `opencode --standalone`, which runs the TUI with a private
|
||||
server, to isolate shared-service issues.
|
||||
- Inspect `~/.local/share/opencode/log/opencode.log`. Filter `role=cli` for
|
||||
|
||||
@@ -74,7 +74,13 @@ const retryAfter = (input: Input) => {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const schedule = Schedule.max([Schedule.exponential("2 seconds"), Schedule.recurs(4)]).pipe(
|
||||
// Exponential from 2s capped at 10s per gap, for 10 retries: 2, 4, 8, then 10 × 7, about 84s of
|
||||
// waiting when every attempt fails (67–101s with jitter). `min` takes the faster schedule, so the
|
||||
// cap applies per gap; `max` with `recurs` bounds the count.
|
||||
const schedule = Schedule.max([
|
||||
Schedule.min([Schedule.exponential("2 seconds"), Schedule.spaced("10 seconds")]),
|
||||
Schedule.recurs(10),
|
||||
]).pipe(
|
||||
Schedule.jittered,
|
||||
Schedule.setInputType<Input>(),
|
||||
Schedule.modifyDelay(({ input, duration: delay }) => {
|
||||
|
||||
@@ -580,6 +580,12 @@ const scenario = (
|
||||
}),
|
||||
)
|
||||
|
||||
// Nominal retry gaps: exponential from 2s capped at 10s, for 10 retries.
|
||||
const RETRY_GAPS = [2_000, 4_000, 8_000, ...Array<number>(7).fill(10_000)]
|
||||
// Longest possible gap per retry (+20% jitter); advancing the clock by these always fires the retry.
|
||||
const RETRY_GAPS_MAX = RETRY_GAPS.map((gap) => gap * 1.2)
|
||||
const RETRY_ATTEMPTS = RETRY_GAPS.map((_, index) => index + 2)
|
||||
|
||||
// Subscribe before resuming; model requests can arrive before retry backoff is scheduled.
|
||||
const subscribeRetries = (s: Scenario) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -2676,8 +2682,8 @@ describe("SessionRunnerLLM", () => {
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(attempts).toEqual([2, 3, 4, 5])
|
||||
expect(s.requests).toHaveLength(6)
|
||||
expect(attempts).toEqual(RETRY_ATTEMPTS)
|
||||
expect(s.requests).toHaveLength(RETRY_ATTEMPTS.length + 2)
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({
|
||||
status: "failed",
|
||||
error: { type: "provider.transport", message: "Provider unavailable" },
|
||||
@@ -5476,28 +5482,34 @@ describe("SessionRunnerLLM", () => {
|
||||
LLMEvent.textStart({ id: "mixed-partial" }),
|
||||
LLMEvent.textDelta({ id: "mixed-partial", text: "Partial" }),
|
||||
)
|
||||
yield* s.llm.push(Stream.fail(failure), partial, Stream.fail(failure), partial, partial)
|
||||
// Alternate transparent failures and partial continuations until the retry allowance is spent.
|
||||
const outcomes = RETRY_GAPS.map((_, index) => (index % 2 === 0 ? Stream.fail(failure) : partial))
|
||||
yield* s.llm.push(...outcomes, partial)
|
||||
const run = yield* s.resume.pipe(Effect.forkChild)
|
||||
const identities: SessionMessage.ID[] = []
|
||||
for (const delay of [2_400, 4_800, 9_600, 19_200]) {
|
||||
for (const delay of RETRY_GAPS_MAX) {
|
||||
identities.push(yield* Queue.take(scheduled))
|
||||
yield* TestClock.adjust(delay)
|
||||
}
|
||||
expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
|
||||
expect(s.requests).toHaveLength(5)
|
||||
expect(identities[0]).toBe(identities[1])
|
||||
expect(identities[2]).toBe(identities[3])
|
||||
expect(identities[0]).not.toBe(identities[2])
|
||||
expect(s.requests).toHaveLength(RETRY_GAPS.length + 1)
|
||||
// A transparent retry keeps the assistant identity; a partial continuation starts a new one.
|
||||
for (const [index, identity] of identities.entries()) {
|
||||
if (index === 0) continue
|
||||
if (index % 2 === 1) expect(identity).toBe(identities[index - 1])
|
||||
else expect(identity).not.toBe(identities[index - 1])
|
||||
}
|
||||
const partials = outcomes.filter((outcome) => outcome === partial).length
|
||||
const messages = yield* s.context
|
||||
expect(messages.filter((message) => message.type === "assistant")).toHaveLength(3)
|
||||
expect(messages.filter((message) => message.type === "synthetic")).toHaveLength(2)
|
||||
expect(messages.filter((message) => message.type === "assistant")).toHaveLength(partials + 1)
|
||||
expect(messages.filter((message) => message.type === "synthetic")).toHaveLength(partials)
|
||||
const events = yield* recordedEventTypes(sessionID)
|
||||
expect(events.filter((type) => type === "session.retry.scheduled.1")).toHaveLength(4)
|
||||
expect(events.filter((type) => type === "session.step.failed.1")).toHaveLength(3)
|
||||
expect(events.filter((type) => type === "session.retry.scheduled.1")).toHaveLength(RETRY_GAPS.length)
|
||||
expect(events.filter((type) => type === "session.step.failed.1")).toHaveLength(partials + 1)
|
||||
},
|
||||
)
|
||||
|
||||
scenario("stops incomplete stream continuations after five total attempts", function* (s) {
|
||||
scenario("stops incomplete stream continuations once the retry allowance is spent", function* (s) {
|
||||
yield* s.admit("Exhaust partial continuations")
|
||||
const failure = incompleteStream()
|
||||
yield* s.llm.always(
|
||||
@@ -5511,30 +5523,30 @@ describe("SessionRunnerLLM", () => {
|
||||
|
||||
const scheduled = yield* subscribeRetries(s)
|
||||
const run = yield* s.resume.pipe(Effect.forkChild)
|
||||
for (const delay of [2_400, 4_800, 9_600, 19_200]) {
|
||||
for (const delay of RETRY_GAPS_MAX) {
|
||||
yield* Queue.take(scheduled)
|
||||
yield* TestClock.adjust(delay)
|
||||
}
|
||||
expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
|
||||
expect(s.requests).toHaveLength(5)
|
||||
expect(s.requests).toHaveLength(RETRY_GAPS.length + 1)
|
||||
const context = yield* s.context
|
||||
expect(context.filter((message) => message.type === "assistant")).toHaveLength(5)
|
||||
expect(context.filter((message) => message.type === "synthetic")).toHaveLength(4)
|
||||
expect(context.filter((message) => message.type === "assistant")).toHaveLength(RETRY_GAPS.length + 1)
|
||||
expect(context.filter((message) => message.type === "synthetic")).toHaveLength(RETRY_GAPS.length)
|
||||
})
|
||||
|
||||
scenario("stops after five total retry attempts", function* (s) {
|
||||
scenario("stops once the retry allowance is spent", function* (s) {
|
||||
yield* s.admit("Exhaust retries")
|
||||
const failure = providerUnavailable()
|
||||
yield* s.llm.always(Stream.fail(failure))
|
||||
|
||||
const scheduled = yield* subscribeRetries(s)
|
||||
const run = yield* s.resume.pipe(Effect.forkChild)
|
||||
for (const delay of [2_400, 4_800, 9_600, 19_200]) {
|
||||
for (const delay of RETRY_GAPS_MAX) {
|
||||
yield* Queue.take(scheduled)
|
||||
yield* TestClock.adjust(delay)
|
||||
}
|
||||
expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
|
||||
expect(s.requests).toHaveLength(5)
|
||||
expect(s.requests).toHaveLength(RETRY_GAPS.length + 1)
|
||||
|
||||
const retries = yield* s.db
|
||||
.select({ data: EventTable.data })
|
||||
@@ -5543,22 +5555,20 @@ describe("SessionRunnerLLM", () => {
|
||||
.orderBy(asc(EventTable.seq))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
for (const [index, range] of [
|
||||
[1_600, 2_400],
|
||||
[4_800, 7_200],
|
||||
[11_200, 16_800],
|
||||
[24_000, 36_000],
|
||||
].entries()) {
|
||||
expect(retries[index]?.data.at).toBeGreaterThanOrEqual(range[0]!)
|
||||
expect(retries[index]?.data.at).toBeLessThanOrEqual(range[1]!)
|
||||
// Each scheduled time falls within the jittered cumulative window for that retry.
|
||||
expect(retries).toHaveLength(RETRY_GAPS.length)
|
||||
let elapsed = 0
|
||||
for (const [index, gap] of RETRY_GAPS.entries()) {
|
||||
elapsed += gap
|
||||
expect(retries[index]?.data.at).toBeGreaterThanOrEqual(elapsed * 0.8)
|
||||
expect(retries[index]?.data.at).toBeLessThanOrEqual(elapsed * 1.2)
|
||||
}
|
||||
expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.step.started.1")).toHaveLength(5)
|
||||
expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.step.started.1")).toHaveLength(
|
||||
RETRY_GAPS.length + 1,
|
||||
)
|
||||
const assistant = requireAssistant(yield* s.context)
|
||||
expect(yield* recordedStepSettlementEvents(sessionID, assistant.id)).toMatchObject([
|
||||
{ type: "session.step.started.1" },
|
||||
{ type: "session.step.started.1" },
|
||||
{ type: "session.step.started.1" },
|
||||
{ type: "session.step.started.1" },
|
||||
...RETRY_GAPS.map(() => ({ type: "session.step.started.1" })),
|
||||
{ type: "session.step.started.1" },
|
||||
{ type: "session.step.failed.1" },
|
||||
])
|
||||
|
||||
@@ -6,7 +6,7 @@ export async function checkHealth(url: string, password?: string | null): Promis
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(new URL("/api/status", url), {
|
||||
const res = await fetch(new URL("/api/info", url), {
|
||||
method: "GET",
|
||||
headers,
|
||||
signal: AbortSignal.timeout(3000),
|
||||
|
||||
@@ -354,7 +354,7 @@ const waitReady = Effect.fn("Ssh.waitReady")(function* (http: SshHttp, authentic
|
||||
const checkHealth = Effect.fn("Ssh.checkHealth")(function* (http: SshHttp) {
|
||||
const client = yield* HttpClient.HttpClient
|
||||
return yield* client
|
||||
.get(`${http.url}/api/status`, {
|
||||
.get(`${http.url}/api/info`, {
|
||||
headers: { authorization: `Basic ${Buffer.from(`opencode:${http.password}`).toString("base64")}` },
|
||||
})
|
||||
.pipe(
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
"description": "Experimental HttpApi surface for selected instance routes."
|
||||
},
|
||||
"paths": {
|
||||
"/api/status": {
|
||||
"/api/info": {
|
||||
"get": {
|
||||
"tags": ["server"],
|
||||
"operationId": "server.status",
|
||||
"operationId": "server.info",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "ServerStatus",
|
||||
"description": "ServerInfo",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ServerStatus"
|
||||
"$ref": "#/components/schemas/ServerInfo"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,8 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Return the server identity, connection URLs, and readiness status.",
|
||||
"summary": "Get server status"
|
||||
"description": "Return the server identity, connection URLs, paths, and readiness status.",
|
||||
"summary": "Get server info"
|
||||
}
|
||||
},
|
||||
"/api/location": {
|
||||
@@ -121,6 +121,51 @@
|
||||
"summary": "Get location"
|
||||
}
|
||||
},
|
||||
"/api/location/reload": {
|
||||
"post": {
|
||||
"tags": ["location"],
|
||||
"operationId": "location.reload",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "<No Content>"
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "ServiceUnavailableError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ServiceUnavailableErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Shut down and rebuild every loaded location. Pending permissions and forms are cancelled; running sessions continue with fresh services at the next step boundary. Emits location.shutdown for client recovery and responds once all replacement builds settle.",
|
||||
"summary": "Reload locations"
|
||||
}
|
||||
},
|
||||
"/api/agent": {
|
||||
"get": {
|
||||
"tags": ["agent"],
|
||||
@@ -16554,7 +16599,7 @@
|
||||
"required": ["_tag", "type", "message"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ServerStatus": {
|
||||
"ServerInfo": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"version": {
|
||||
@@ -16569,9 +16614,19 @@
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"paths": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tmp": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["tmp"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["version", "pid", "urls"],
|
||||
"required": ["version", "pid", "urls", "paths"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ServiceUnavailableErrorEncoded": {
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
import { Schema } from "effect"
|
||||
import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi"
|
||||
|
||||
export const ServerStatus = Schema.Struct({
|
||||
export const ServerInfo = Schema.Struct({
|
||||
version: Schema.String,
|
||||
// 0 means the runtime has no OS process identity (e.g. workerd).
|
||||
pid: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
urls: Schema.Array(Schema.String),
|
||||
}).annotate({ identifier: "ServerStatus" })
|
||||
export type ServerStatus = typeof ServerStatus.Type
|
||||
paths: Schema.Struct({
|
||||
tmp: Schema.String,
|
||||
}),
|
||||
}).annotate({ identifier: "ServerInfo" })
|
||||
export type ServerInfo = typeof ServerInfo.Type
|
||||
|
||||
export const ServerGroup = HttpApiGroup.make("server.server")
|
||||
.add(
|
||||
HttpApiEndpoint.get("server.status", "/api/status", {
|
||||
success: ServerStatus,
|
||||
HttpApiEndpoint.get("server.info", "/api/info", {
|
||||
success: ServerInfo,
|
||||
}).annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "server.status",
|
||||
summary: "Get server status",
|
||||
description: "Return the server identity, connection URLs, and readiness status.",
|
||||
identifier: "server.info",
|
||||
summary: "Get server info",
|
||||
description: "Return the server identity, connection URLs, paths, and readiness status.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -98,7 +98,7 @@ export class OpenCodeDO {
|
||||
|
||||
async fetch() {
|
||||
const opencode = await this.opencode
|
||||
return Response.json(await opencode.server.status())
|
||||
return Response.json(await opencode.server.info())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -150,7 +150,7 @@ export class OpenCodeDO {
|
||||
if (this.configurations !== 1 || admitted.some(item => item.payload.text !== "Packed prompt:packed-thread")) {
|
||||
throw new Error("Packed instance configuration did not share or prepare prompts correctly")
|
||||
}
|
||||
return Response.json(await opencode.server.status())
|
||||
return Response.json(await opencode.server.info())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ for (const entrypoint of ["create", "layer"] as const) {
|
||||
).pipe(Effect.provideService(FetchHttpClient.Fetch, ambient))
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
expect(yield* client.server.status()).toMatchObject({ version: "transport-test" })
|
||||
expect(yield* client.server.info()).toMatchObject({ version: "transport-test" })
|
||||
const session = yield* client.sessions.create({
|
||||
location: Location.Ref.make({ directory: AbsolutePath.make(directory.path) }),
|
||||
})
|
||||
@@ -56,7 +56,7 @@ for (const entrypoint of ["create", "layer"] as const) {
|
||||
yield* Scope.close(scope, Exit.void)
|
||||
expect(
|
||||
Exit.isFailure(
|
||||
yield* client.server.status().pipe(Effect.provideService(FetchHttpClient.Fetch, ambient), Effect.exit),
|
||||
yield* client.server.info().pipe(Effect.provideService(FetchHttpClient.Fetch, ambient), Effect.exit),
|
||||
),
|
||||
).toBe(true)
|
||||
expect(calls).toEqual([])
|
||||
|
||||
@@ -4,13 +4,14 @@ import { Api } from "../api"
|
||||
import { ServerInfo } from "../server-info"
|
||||
|
||||
export const ServerHandler = HttpApiBuilder.group(Api, "server.server", (handlers) =>
|
||||
handlers.handle("server.status", () =>
|
||||
handlers.handle("server.info", () =>
|
||||
Effect.gen(function* () {
|
||||
const info = yield* ServerInfo.Service
|
||||
return {
|
||||
version: info.app.version ?? "unknown",
|
||||
pid: process.pid ?? 0,
|
||||
urls: info.urls(),
|
||||
paths: info.paths,
|
||||
}
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,7 @@ import { SessionRestart } from "@opencode/core/session/execution/restart"
|
||||
import { InstallationEvent } from "@opencode/schema/installation-event"
|
||||
import { hasPtyConnectTicketURL } from "@opencode/protocol/groups/pty"
|
||||
import { hasPersistentPtyConnectTicketURL } from "@opencode/protocol/groups/persistent-pty"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { Cause, Context, Effect, Exit, Latch, Layer, Option, Ref, Scope } from "effect"
|
||||
import {
|
||||
HttpMiddleware,
|
||||
@@ -70,7 +71,7 @@ export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
|
||||
// Request fibers may continue inbound trace context, but must not inherit the server startup parent.
|
||||
yield* bound.http
|
||||
.serve(
|
||||
dispatch(password, status, application, options.app?.version ?? "unknown", urls).pipe(
|
||||
dispatch(password, status, application, options.app?.version ?? "unknown", urls, Global.Path.tmp).pipe(
|
||||
HttpMiddleware.cors({ allowedOrigins: (origin) => isAllowedCorsOrigin(origin, options), maxAge: 86_400 }),
|
||||
),
|
||||
errorResponseLogger,
|
||||
@@ -182,18 +183,19 @@ function dispatch(
|
||||
application: Ref.Ref<Option.Option<App>>,
|
||||
version: string,
|
||||
urls: () => ReadonlyArray<string>,
|
||||
tmp: string,
|
||||
): App {
|
||||
const auth = ServerAuth.Config.of({ password: Option.some(password), username: "opencode" })
|
||||
return Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest
|
||||
const url = new URL(request.url, "http://localhost")
|
||||
if (request.method === "GET" && url.pathname === "/api/status") {
|
||||
if (!(yield* authorizedRequest(request, auth))) return unauthorized()
|
||||
return yield* statusResponse(status, version, urls)
|
||||
}
|
||||
const state = yield* status.current
|
||||
const app = yield* Ref.get(application)
|
||||
const ready = state.type === "ready" && Option.isSome(app)
|
||||
if (request.method === "GET" && url.pathname === "/api/info" && !ready) {
|
||||
if (!(yield* authorizedRequest(request, auth))) return unauthorized()
|
||||
return yield* infoResponse(status, version, urls, tmp)
|
||||
}
|
||||
if (
|
||||
(!ready || (!hasPtyConnectTicketURL(url) && !hasPersistentPtyConnectTicketURL(url))) &&
|
||||
!(yield* authorizedRequest(request, auth))
|
||||
@@ -211,14 +213,15 @@ function unauthorized() {
|
||||
})
|
||||
}
|
||||
|
||||
const statusResponse = Effect.fnUntraced(function* (
|
||||
const infoResponse = Effect.fnUntraced(function* (
|
||||
status: Status.Interface,
|
||||
version: string,
|
||||
urls: () => ReadonlyArray<string>,
|
||||
tmp: string,
|
||||
) {
|
||||
const state = yield* status.current
|
||||
return HttpServerResponse.jsonUnsafe(
|
||||
{ version, pid: process.pid, urls: urls() },
|
||||
{ version, pid: process.pid, urls: urls(), paths: { tmp } },
|
||||
{
|
||||
status: state.type === "ready" ? 200 : state.type === "failed" ? 500 : 503,
|
||||
headers: state.type === "starting" || state.type === "stopping" ? { "retry-after": "1" } : undefined,
|
||||
|
||||
@@ -169,7 +169,7 @@ function makeRoutes<AuthError, AuthServices>(
|
||||
WellKnown.Service,
|
||||
)(context),
|
||||
),
|
||||
ServerInfo.layer(serviceURLs, options.app),
|
||||
ServerInfo.layer(serviceURLs, Context.get(context, Global.Service).tmp, options.app),
|
||||
)
|
||||
const api = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
|
||||
Layer.provide(handlers.pipe(Layer.provide(services), Layer.provide(Layer.succeed(CorsConfig, options)))),
|
||||
|
||||
@@ -4,11 +4,15 @@ import type { ServerOptions } from "./options"
|
||||
|
||||
export class Service extends Context.Service<
|
||||
Service,
|
||||
{ readonly urls: () => ReadonlyArray<string>; readonly app: NonNullable<ServerOptions["app"]> }
|
||||
{
|
||||
readonly urls: () => ReadonlyArray<string>
|
||||
readonly app: NonNullable<ServerOptions["app"]>
|
||||
readonly paths: { readonly tmp: string }
|
||||
}
|
||||
>()("@opencode/server/ServerInfo") {}
|
||||
|
||||
export function layer(urls: () => ReadonlyArray<string>, app: ServerOptions["app"] = {}) {
|
||||
return Layer.succeed(Service, Service.of({ urls, app }))
|
||||
export function layer(urls: () => ReadonlyArray<string>, tmp: string, app: ServerOptions["app"] = {}) {
|
||||
return Layer.succeed(Service, Service.of({ urls, app, paths: { tmp } }))
|
||||
}
|
||||
|
||||
export function connectionURLs(value: string, requestedHostname?: string) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createServer } from "node:http"
|
||||
import path from "node:path"
|
||||
import { Agent } from "@opencode/schema/agent"
|
||||
import { Integration } from "@opencode/schema/integration"
|
||||
import { ServerStatus } from "@opencode/protocol/groups/server"
|
||||
import { ServerInfo } from "@opencode/protocol/groups/server"
|
||||
import { Effect, Schedule, Schema } from "effect"
|
||||
import { tmpdir } from "../../core/test/fixture/tmpdir"
|
||||
import { it } from "../../core/test/lib/effect"
|
||||
@@ -94,19 +94,20 @@ it.live("serves the HttpApi and enforces Basic auth like the Node server", () =>
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* ServerFetch.make({ ...options, password: "secret" })
|
||||
|
||||
const denied = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/status")))
|
||||
const denied = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))
|
||||
expect(denied.status).toBe(401)
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler(
|
||||
new Request("http://opencode.local/api/status", {
|
||||
new Request("http://opencode.local/api/info", {
|
||||
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
|
||||
}),
|
||||
),
|
||||
)
|
||||
expect(response.status).toBe(200)
|
||||
const body = yield* Effect.promise(() => response.json()).pipe(Effect.flatMap(Schema.decodeUnknownEffect(ServerStatus)))
|
||||
const body = yield* Effect.promise(() => response.json()).pipe(Effect.flatMap(Schema.decodeUnknownEffect(ServerInfo)))
|
||||
expect(body.version).toBe("test-version")
|
||||
expect(body.paths.tmp).toEndWith("opencode")
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -124,12 +125,12 @@ it.live("serves unauthenticated and answers CORS preflight when no password is c
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* ServerFetch.make(options)
|
||||
|
||||
const response = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/status")))
|
||||
const response = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
const preflight = yield* Effect.promise(() =>
|
||||
handler(
|
||||
new Request("http://opencode.local/api/status", {
|
||||
new Request("http://opencode.local/api/info", {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "http://localhost:3000",
|
||||
@@ -156,7 +157,7 @@ it.live("applies custom CORS origins to HTTP responses and PTY ticket checks", (
|
||||
const allowed = origin !== "https://untrusted.example.com"
|
||||
const preflight = yield* Effect.promise(() =>
|
||||
handler(
|
||||
new Request("http://opencode.local/api/status", {
|
||||
new Request("http://opencode.local/api/info", {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin,
|
||||
@@ -172,7 +173,7 @@ it.live("applies custom CORS origins to HTTP responses and PTY ticket checks", (
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler(
|
||||
new Request("http://opencode.local/api/status", {
|
||||
new Request("http://opencode.local/api/info", {
|
||||
headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
|
||||
}),
|
||||
),
|
||||
@@ -465,7 +466,7 @@ it.live("stays serviceable when the first request aborts", () =>
|
||||
|
||||
const aborted = yield* Effect.promise(() => {
|
||||
const controller = new AbortController()
|
||||
const first = handler(new Request("http://opencode.local/api/status", { signal: controller.signal }))
|
||||
const first = handler(new Request("http://opencode.local/api/info", { signal: controller.signal }))
|
||||
controller.abort()
|
||||
return first.then(
|
||||
() => "resolved" as const,
|
||||
@@ -474,7 +475,7 @@ it.live("stays serviceable when the first request aborts", () =>
|
||||
})
|
||||
expect(["resolved", "rejected"]).toContain(aborted)
|
||||
|
||||
const second = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/status")))
|
||||
const second = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))
|
||||
expect(second.status).toBe(200)
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -26,7 +26,7 @@ it.live("authenticates API and frontend requests while allowing browser prefligh
|
||||
),
|
||||
)
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/status", HttpServer.formatAddress(server.address)), {
|
||||
fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "http://localhost:3000",
|
||||
@@ -41,7 +41,7 @@ it.live("authenticates API and frontend requests while allowing browser prefligh
|
||||
expect(response.headers.get("access-control-allow-headers")).toBe("authorization")
|
||||
|
||||
const status = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/status", HttpServer.formatAddress(server.address)), {
|
||||
fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
|
||||
headers: {
|
||||
authorization: `Basic ${btoa("opencode:secret")}`,
|
||||
origin: "http://localhost:3000",
|
||||
@@ -59,7 +59,7 @@ it.live("authenticates API and frontend requests while allowing browser prefligh
|
||||
Effect.gen(function* () {
|
||||
const allowed = origin === "https://untrusted.example.com" ? null : origin
|
||||
const preflight = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/status", HttpServer.formatAddress(server.address)), {
|
||||
fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin,
|
||||
@@ -72,7 +72,7 @@ it.live("authenticates API and frontend requests while allowing browser prefligh
|
||||
expect(preflight.headers.get("access-control-allow-origin")).toBe(allowed)
|
||||
|
||||
const status = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/status", HttpServer.formatAddress(server.address)), {
|
||||
fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), {
|
||||
headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
|
||||
}),
|
||||
)
|
||||
@@ -81,7 +81,7 @@ it.live("authenticates API and frontend requests while allowing browser prefligh
|
||||
yield* Effect.promise(() => status.arrayBuffer())
|
||||
|
||||
const denied = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/status", HttpServer.formatAddress(server.address)), { headers: { origin } }),
|
||||
fetch(new URL("/api/info", HttpServer.formatAddress(server.address)), { headers: { origin } }),
|
||||
)
|
||||
expect(denied.status).toBe(401)
|
||||
expect(denied.headers.get("access-control-allow-origin")).toBe(allowed)
|
||||
|
||||
@@ -15,12 +15,12 @@ it.live("boots the workerd profile over durable object storage", () =>
|
||||
config: { content: "{}" },
|
||||
})
|
||||
|
||||
const unauthorized = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/status")))
|
||||
const unauthorized = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))
|
||||
expect(unauthorized.status).toBe(401)
|
||||
|
||||
const status = yield* Effect.promise(() =>
|
||||
handler(
|
||||
new Request("http://opencode.local/api/status", {
|
||||
new Request("http://opencode.local/api/info", {
|
||||
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -54,10 +54,10 @@ export function DevToolsBar() {
|
||||
)
|
||||
const groups = createMemo(() => DevTools.data().filter((group) => group.id !== "theme-performance"))
|
||||
const [server] = createResource(connected, async () => {
|
||||
const status = await client.api.server.status()
|
||||
const info = await client.api.server.info()
|
||||
return {
|
||||
health: status,
|
||||
address: status.urls[0] ? new URL(status.urls[0]).host : "Unknown",
|
||||
health: info,
|
||||
address: info.urls[0] ? new URL(info.urls[0]).host : "Unknown",
|
||||
}
|
||||
})
|
||||
const close = () => {
|
||||
|
||||
@@ -26,7 +26,7 @@ export function DialogPair(props: { credentials?: DialogPairCredentials }) {
|
||||
dialog.setCentered(true)
|
||||
|
||||
const [server] = createResource(() =>
|
||||
client.api.server.status().catch((error) => {
|
||||
client.api.server.info().catch((error) => {
|
||||
setLoadError(error)
|
||||
return undefined
|
||||
}),
|
||||
|
||||
@@ -34,6 +34,7 @@ import type {
|
||||
SessionMessageAssistantTool,
|
||||
SessionMessageUser,
|
||||
SessionInfo,
|
||||
ModelInfo,
|
||||
} from "@opencode/client"
|
||||
import { useLocal } from "../../context/local"
|
||||
import { Locale } from "../../util/locale"
|
||||
@@ -3167,6 +3168,7 @@ function Subagent(props: ToolProps) {
|
||||
const sessionID = createMemo(() => stringValue(props.metadata.sessionID) ?? stringValue(props.metadata.sessionId))
|
||||
const description = createMemo(() => stringValue(props.input.description))
|
||||
const continuation = createMemo(() => Boolean(stringValue(props.input.sessionID)))
|
||||
const model = createMemo(() => subagentModelLabel(stringValue(props.input.model), data.location.model.list()))
|
||||
const isRunning = createMemo(() => {
|
||||
const id = sessionID()
|
||||
return props.part.state.status === "running" || Boolean(id && data.session.status(id) === "running")
|
||||
@@ -3190,13 +3192,24 @@ function Subagent(props: ToolProps) {
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{continuation()
|
||||
? `Continue subagent — ${description() ?? "Subagent"}`
|
||||
: `${Locale.titlecase(stringValue(props.input.agent) ?? stringValue(props.input.subagent_type) ?? "General")} Subagent — ${description() ?? "Subagent"}`}
|
||||
{`${continuation() ? "Continue subagent" : `${Locale.titlecase(stringValue(props.input.agent) ?? stringValue(props.input.subagent_type) ?? "General")} Subagent`} — ${description() ?? "Subagent"}${model() ? ` · ${model()}` : ""}`}
|
||||
</InlineTool>
|
||||
)
|
||||
}
|
||||
|
||||
export function subagentModelLabel(
|
||||
value: string | undefined,
|
||||
models: readonly Pick<ModelInfo, "providerID" | "id" | "name">[] | undefined,
|
||||
) {
|
||||
if (!value) return
|
||||
const [reference, variant] = value.split("#")
|
||||
const separator = reference.indexOf("/")
|
||||
const providerID = separator === -1 ? "" : reference.slice(0, separator)
|
||||
const modelID = separator === -1 ? reference : reference.slice(separator + 1)
|
||||
const name = models?.find((item) => item.providerID === providerID && item.id === modelID)?.name
|
||||
return `${name ?? reference}${variant ? ` (${variant})` : ""}`
|
||||
}
|
||||
|
||||
export function isBackgroundSubagent(
|
||||
metadata: Record<string, unknown>,
|
||||
status: SessionMessageAssistantTool["state"]["status"],
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
parseDiagnostics,
|
||||
parseQuestionAnswers,
|
||||
parseQuestions,
|
||||
subagentModelLabel,
|
||||
toolDisplay,
|
||||
} from "../../../src/routes/session"
|
||||
|
||||
@@ -237,6 +238,14 @@ describe("TUI inline tool wrapping", () => {
|
||||
expect(isBackgroundSubagent({ status: "completed" }, "completed")).toBeFalse()
|
||||
})
|
||||
|
||||
test("labels only explicit subagent model overrides", () => {
|
||||
const models = [{ providerID: "anthropic", id: "claude-opus-4-1", name: "Claude Opus 4.1" }]
|
||||
expect(subagentModelLabel(undefined, models)).toBeUndefined()
|
||||
expect(subagentModelLabel("anthropic/claude-opus-4-1", models)).toBe("Claude Opus 4.1")
|
||||
expect(subagentModelLabel("anthropic/claude-opus-4-1#max", models)).toBe("Claude Opus 4.1 (max)")
|
||||
expect(subagentModelLabel("custom/reviewer", models)).toBe("custom/reviewer")
|
||||
})
|
||||
|
||||
test("snapshots consecutive grep, glob, and read rows at a narrow width", async () => {
|
||||
expect(await renderFrame(() => <Fixture />, { width: 72, height: 12 })).toMatchSnapshot()
|
||||
})
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
"description": "Experimental HttpApi surface for selected instance routes."
|
||||
},
|
||||
"paths": {
|
||||
"/api/status": {
|
||||
"/api/info": {
|
||||
"get": {
|
||||
"tags": ["server"],
|
||||
"operationId": "server.status",
|
||||
"operationId": "server.info",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "ServerStatus",
|
||||
"description": "ServerInfo",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ServerStatus"
|
||||
"$ref": "#/components/schemas/ServerInfo"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,8 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Return the server identity, connection URLs, and readiness status.",
|
||||
"summary": "Get server status"
|
||||
"description": "Return the server identity, connection URLs, paths, and readiness status.",
|
||||
"summary": "Get server info"
|
||||
}
|
||||
},
|
||||
"/api/location": {
|
||||
@@ -121,6 +121,51 @@
|
||||
"summary": "Get location"
|
||||
}
|
||||
},
|
||||
"/api/location/reload": {
|
||||
"post": {
|
||||
"tags": ["location"],
|
||||
"operationId": "location.reload",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "<No Content>"
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "ServiceUnavailableError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ServiceUnavailableErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Shut down and rebuild every loaded location. Pending permissions and forms are cancelled; running sessions continue with fresh services at the next step boundary. Emits location.shutdown for client recovery and responds once all replacement builds settle.",
|
||||
"summary": "Reload locations"
|
||||
}
|
||||
},
|
||||
"/api/agent": {
|
||||
"get": {
|
||||
"tags": ["agent"],
|
||||
@@ -16554,7 +16599,7 @@
|
||||
"required": ["_tag", "type", "message"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ServerStatus": {
|
||||
"ServerInfo": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"version": {
|
||||
@@ -16569,9 +16614,19 @@
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"paths": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tmp": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["tmp"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["version", "pid", "urls"],
|
||||
"required": ["version", "pid", "urls", "paths"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ServiceUnavailableErrorEncoded": {
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
"description": "Experimental HttpApi surface for selected instance routes."
|
||||
},
|
||||
"paths": {
|
||||
"/api/status": {
|
||||
"/api/info": {
|
||||
"get": {
|
||||
"tags": ["server"],
|
||||
"operationId": "server.status",
|
||||
"operationId": "server.info",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "ServerStatus",
|
||||
"description": "ServerInfo",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ServerStatus"
|
||||
"$ref": "#/components/schemas/ServerInfo"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,8 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Return the server identity, connection URLs, and readiness status.",
|
||||
"summary": "Get server status"
|
||||
"description": "Return the server identity, connection URLs, paths, and readiness status.",
|
||||
"summary": "Get server info"
|
||||
}
|
||||
},
|
||||
"/api/location": {
|
||||
@@ -121,6 +121,51 @@
|
||||
"summary": "Get location"
|
||||
}
|
||||
},
|
||||
"/api/location/reload": {
|
||||
"post": {
|
||||
"tags": ["location"],
|
||||
"operationId": "location.reload",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "<No Content>"
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "ServiceUnavailableError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ServiceUnavailableErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Shut down and rebuild every loaded location. Pending permissions and forms are cancelled; running sessions continue with fresh services at the next step boundary. Emits location.shutdown for client recovery and responds once all replacement builds settle.",
|
||||
"summary": "Reload locations"
|
||||
}
|
||||
},
|
||||
"/api/agent": {
|
||||
"get": {
|
||||
"tags": ["agent"],
|
||||
@@ -16554,7 +16599,7 @@
|
||||
"required": ["_tag", "type", "message"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ServerStatus": {
|
||||
"ServerInfo": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"version": {
|
||||
@@ -16569,9 +16614,19 @@
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"paths": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tmp": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["tmp"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["version", "pid", "urls"],
|
||||
"required": ["version", "pid", "urls", "paths"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ServiceUnavailableErrorEncoded": {
|
||||
|
||||
@@ -134,7 +134,7 @@ const program = Effect.gen(function* () {
|
||||
HttpClient.mapRequest(httpClient, (request) => HttpClientRequest.setHeaders(request, Service.headers(endpoint))),
|
||||
),
|
||||
)
|
||||
return yield* client.server.status()
|
||||
return yield* client.server.info()
|
||||
})
|
||||
|
||||
const health = await Effect.runPromise(
|
||||
|
||||
@@ -156,7 +156,7 @@ const client = OpenCode.make({
|
||||
headers: Service.headers(endpoint),
|
||||
})
|
||||
|
||||
const status = await client.server.status()
|
||||
const info = await client.server.info()
|
||||
```
|
||||
|
||||
`Service.ensure()` accepts an optional registration file, version, service
|
||||
|
||||
@@ -30,7 +30,7 @@ export class OpenCodeDO {
|
||||
|
||||
async fetch() {
|
||||
const opencode = await this.opencode
|
||||
return Response.json(await opencode.server.status())
|
||||
return Response.json(await opencode.server.info())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -38,7 +38,7 @@ The embedded host uses the same schema values, declared errors, request options,
|
||||
`@opencode/client/effect`.
|
||||
|
||||
```ts
|
||||
const status = yield* opencode.server.status()
|
||||
const info = yield* opencode.server.info()
|
||||
const sessions = yield* opencode.sessions.list()
|
||||
```
|
||||
|
||||
@@ -94,7 +94,7 @@ import { Effect } from "effect"
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const opencode = yield* OpenCode.Service
|
||||
return yield* opencode.server.status()
|
||||
return yield* opencode.server.info()
|
||||
})
|
||||
|
||||
const health = await Effect.runPromise(program.pipe(Effect.provide(OpenCode.layer())))
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
---
|
||||
title: "Config"
|
||||
title: "Settings"
|
||||
description: "Configure every OpenCode CLI and TUI setting."
|
||||
---
|
||||
|
||||
Most settings can also be changed from the OpenCode TUI. Press `Ctrl+P`, then select **Open settings**.
|
||||
CLI settings control the terminal clients only. They are separate from the server and project settings in
|
||||
`opencode.json(c)`.
|
||||
|
||||
Press `Ctrl+P`, then select **Open settings** to change common settings from the TUI.
|
||||
|
||||
<img src={`${import.meta.env.BASE_URL}assets/docs/cli/settings.png`} alt="OpenCode TUI settings dialog" />
|
||||
|
||||
The default CLI config location is:
|
||||
## Configuration file
|
||||
|
||||
OpenCode stores CLI settings in one global file:
|
||||
|
||||
```text
|
||||
~/.config/opencode/cli.json
|
||||
```
|
||||
|
||||
Set `$XDG_CONFIG_HOME` to use a different config directory:
|
||||
When `$XDG_CONFIG_HOME` is set, OpenCode uses:
|
||||
|
||||
```text
|
||||
$XDG_CONFIG_HOME/opencode/cli.json
|
||||
```
|
||||
|
||||
Add the published JSON Schema for editor validation and autocomplete:
|
||||
There is no project-local CLI settings file. Add the published JSON Schema for validation and autocomplete:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
@@ -26,7 +32,8 @@ Add the published JSON Schema for editor validation and autocomplete:
|
||||
}
|
||||
```
|
||||
|
||||
OpenCode includes this automatically when it creates or migrates your CLI config.
|
||||
OpenCode adds `$schema` when it creates or migrates this file. Unknown settings are rejected, and valid edits reload
|
||||
while the TUI is running.
|
||||
|
||||
## Inline config
|
||||
|
||||
@@ -39,87 +46,172 @@ OPENCODE_CLI_CONFIG_CONTENT='{"tabs":{"enabled":false}}' opencode
|
||||
OpenCode merges the inline settings over the global `cli.json`. Nested objects are merged, while arrays and scalar
|
||||
values from the environment replace global values. Inline settings remain authoritative while the variable is set.
|
||||
|
||||
## Theme
|
||||
## Appearance
|
||||
|
||||
Set the theme and color mode:
|
||||
Choose a theme, control interface motion, and override the terminal cursor:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"theme": {
|
||||
"name": "tokyonight",
|
||||
"mode": "system"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Values | Description |
|
||||
| ------ | ---------------------------- | ----------------------------------------------------------------- |
|
||||
| `name` | string | Selects the theme. |
|
||||
| `mode` | `system`, `dark`, or `light` | Selects the color mode. `system` follows the terminal appearance. |
|
||||
|
||||
See [Theme](/cli/theme) for theme configuration.
|
||||
|
||||
## Keybinds
|
||||
|
||||
Override bindings with the top-level `keybinds` object:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"keybinds": {
|
||||
"leader": "ctrl+x",
|
||||
"app.exit": "ctrl+c,ctrl+d,<leader>q",
|
||||
"app.debug": "none",
|
||||
"help.show": false
|
||||
},
|
||||
"leader": {
|
||||
"timeout": 2000
|
||||
"animations": true,
|
||||
"cursor": {
|
||||
"style": "block",
|
||||
"blinking": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See [Keybinds](/cli/keybinds) for every available binding.
|
||||
<div class="docs-table-scroll" role="region" aria-label="Appearance settings" tabIndex={0}>
|
||||
|
||||
## Plugins
|
||||
| Setting | Values | Description |
|
||||
| ----------------- | --------------------------------------- | ------------------------------------------------------------------------ |
|
||||
| `theme.name` | string | Selects a built-in, custom, or terminal-derived theme. |
|
||||
| `theme.mode` | `system`, `dark`, or `light` | Follows the terminal appearance or locks the theme to one color mode. |
|
||||
| `animations` | boolean | Enables interface animations. |
|
||||
| `cursor.style` | `block`, `underline`, `line`, `default` | Sets the cursor shape. `default` preserves the terminal's cursor shape. |
|
||||
| `cursor.blinking` | boolean | Controls cursor blinking. It has no effect when the style is `default`. |
|
||||
|
||||
Load terminal plugins in order:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"plugins": [
|
||||
"-opencode.notifications",
|
||||
{
|
||||
"package": "./plugins/status",
|
||||
"options": {
|
||||
"compact": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
See [Plugins](/cli/plugins) for packages, local plugins, options, and enablement directives.
|
||||
|
||||
## Scroll
|
||||
|
||||
Set scroll speed and acceleration:
|
||||
</div>
|
||||
|
||||
See [Theme](/cli/theme) for selecting and creating themes.
|
||||
|
||||
## Input
|
||||
|
||||
Configure mouse capture, scrolling, editor context, pastes, and prompt image previews:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"mouse": true,
|
||||
"scroll": {
|
||||
"speed": 2,
|
||||
"acceleration": true
|
||||
"speed": 3,
|
||||
"acceleration": false
|
||||
},
|
||||
"prompt": {
|
||||
"editor": true,
|
||||
"paste": "compact",
|
||||
"image_preview": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Values | Description |
|
||||
| -------------- | ------------------------ | --------------------------------- |
|
||||
| `speed` | number, at least `0.001` | Sets the distance per input tick. |
|
||||
| `acceleration` | boolean | Speeds up repeated scrolling. |
|
||||
<div class="docs-table-scroll" role="region" aria-label="Input settings" tabIndex={0}>
|
||||
|
||||
## Attention
|
||||
| Setting | Values | Description |
|
||||
| -------------------------- | ------------------------------- | --------------------------------------------------------------------------- |
|
||||
| `mouse` | boolean | Enables terminal mouse capture. |
|
||||
| `scroll.speed` | number, at least `0.001` | Sets the fixed distance per scroll input tick. |
|
||||
| `scroll.acceleration` | boolean | Accelerates repeated scrolling. When enabled, it takes precedence over speed. |
|
||||
| `prompt.editor` | boolean | Includes the active editor file or selection as prompt context. |
|
||||
| `prompt.paste` | `compact` or `full` | Shows large pastes as compact placeholders or as full text. |
|
||||
| `prompt.image_preview` | boolean | Shows image attachment previews above the prompt input. |
|
||||
|
||||
Configure notifications and sounds. Both are off by default and can be enabled independently:
|
||||
</div>
|
||||
|
||||
## Sessions
|
||||
|
||||
Configure how full-screen TUI sessions are presented and where new sessions start:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"session": {
|
||||
"sidebar": "auto",
|
||||
"scrollbar": false,
|
||||
"thinking": "hide",
|
||||
"grouping": "auto",
|
||||
"image_preview": false,
|
||||
"tps": true,
|
||||
"markdown": "rendered",
|
||||
"new_location": "launch",
|
||||
"permissions": "prompt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<div class="docs-table-scroll" role="region" aria-label="Session settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| ----------------------- | --------------------------- | ---------------------------------------------------------------------------- |
|
||||
| `session.sidebar` | `auto` or `hide` | Shows the sidebar when space permits or always hides it. |
|
||||
| `session.scrollbar` | boolean | Shows the transcript scrollbar. |
|
||||
| `session.thinking` | `show` or `hide` | Shows or hides model reasoning by default. |
|
||||
| `session.grouping` | `auto` or `none` | Groups related transcript items or renders each item separately. |
|
||||
| `session.image_preview` | boolean | Shows user attachment and tool-result images in the transcript. |
|
||||
| `session.tps` | boolean | Shows output tokens per second in assistant footers. |
|
||||
| `session.markdown` | `source` or `rendered` | Shows Markdown syntax markers or conceals them in rendered content. |
|
||||
| `session.new_location` | `launch` or `inherit` | Starts in the TUI launch directory or inherits the active session location. |
|
||||
| `session.permissions` | `prompt` or `autoaccept` | Prompts for permission requests or accepts every request automatically. |
|
||||
|
||||
</div>
|
||||
|
||||
## Tabs
|
||||
|
||||
Configure the persistent session tab strip:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"tabs": {
|
||||
"enabled": true,
|
||||
"scope": "cwd",
|
||||
"layout": "horizontal",
|
||||
"indicators": "status"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<div class="docs-table-scroll" role="region" aria-label="Tab settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| ----------------- | --------------------------- | ----------------------------------------------------------------------------- |
|
||||
| `tabs.enabled` | boolean | Uses a persistent tab strip instead of pinned quick-switch sessions. |
|
||||
| `tabs.scope` | `cwd` or `global` | Keeps separate tabs per working directory or shares them globally. |
|
||||
| `tabs.layout` | `horizontal` or `vertical` | Places tabs in a horizontal strip or a vertical sidebar. |
|
||||
| `tabs.indicators` | `status` or `numbers` | Shows status icons or always shows tab numbers. |
|
||||
|
||||
</div>
|
||||
|
||||
Number indicators retain status colors and background animations. Ctrl+number shortcuts switch tabs in either indicator
|
||||
mode.
|
||||
|
||||
## Diffs
|
||||
|
||||
Configure the initial diff scope and presentation:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"diffs": {
|
||||
"source": "branch",
|
||||
"wrap": "word",
|
||||
"tree": true,
|
||||
"single": false,
|
||||
"view": "auto"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<div class="docs-table-scroll" role="region" aria-label="Diff settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| -------------- | ----------------------------------- | ------------------------------------------------------------- |
|
||||
| `diffs.source` | `branch`, `committed`, or `working` | Sets the initial review scope. |
|
||||
| `diffs.wrap` | `word` or `none` | Wraps long lines at words or leaves them unwrapped. |
|
||||
| `diffs.tree` | boolean | Shows the diff file tree. |
|
||||
| `diffs.single` | boolean | Shows only the selected file patch. |
|
||||
| `diffs.view` | `auto`, `split`, or `unified` | Sets the layout. `auto` chooses from the available width. |
|
||||
|
||||
</div>
|
||||
|
||||
`branch` shows **All** branch and local changes, `committed` shows branch commits only, and `working` shows staged,
|
||||
unstaged, and untracked changes.
|
||||
|
||||
In `/diff`, press `d` to change the scope or choose a comparison branch from **Base**. These in-view choices last until
|
||||
the TUI exits and do not change `cli.json`.
|
||||
|
||||
## Alerts
|
||||
|
||||
Enable system notifications and attention sounds independently:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
@@ -135,73 +227,19 @@ Configure notifications and sounds. Both are off by default and can be enabled i
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Values | Description |
|
||||
| --------------- | ---------------------- | ---------------------------------------------------------------------------------------------------- |
|
||||
| `notifications` | boolean | Shows system notifications when the terminal is not focused. |
|
||||
| `sound` | boolean | Plays attention sounds. |
|
||||
| `volume` | number from `0` to `1` | Sets sound volume. |
|
||||
| `sound_pack` | string | Selects the active sound pack. |
|
||||
| `sounds` | object | Overrides files for `default`, `question`, `permission`, `error`, `done`, or `subagent_done` events. |
|
||||
<div class="docs-table-scroll" role="region" aria-label="Alert settings" tabIndex={0}>
|
||||
|
||||
## Session
|
||||
| Setting | Values | Description |
|
||||
| ------------------------ | ---------------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `attention.notifications` | boolean | Shows system notifications, normally when the terminal is not focused. |
|
||||
| `attention.sound` | boolean | Plays attention sounds. |
|
||||
| `attention.volume` | number from `0` to `1` | Sets sound volume. |
|
||||
| `attention.sound_pack` | string | Selects the active sound pack ID. |
|
||||
| `attention.sounds` | object | Overrides sound files for `default`, `question`, `permission`, `error`, `done`, or `subagent_done`. |
|
||||
|
||||
Choose whether the TUI prompts before granting permission requests:
|
||||
</div>
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"session": {
|
||||
"permissions": "prompt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Values | Description |
|
||||
| ------------- | ------------------------ | ----------------------------------------------------------------------- |
|
||||
| `permissions` | `prompt` or `autoaccept` | Prompts for permission requests or accepts every request automatically. |
|
||||
|
||||
## Diffs
|
||||
|
||||
Configure diff presentation:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"diffs": {
|
||||
"source": "branch",
|
||||
"wrap": "word",
|
||||
"tree": true,
|
||||
"single": false,
|
||||
"view": "auto"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Values | Description |
|
||||
| -------- | ----------------------------------- | ------------------------------------------------------------- |
|
||||
| `source` | `branch`, `committed`, or `working` | Sets the initial review scope. Defaults to `branch`. |
|
||||
| `wrap` | `word` or `none` | Sets line wrapping. |
|
||||
| `tree` | boolean | Shows the diff file tree. |
|
||||
| `single` | boolean | Shows only the selected file patch. |
|
||||
| `view` | `auto`, `split`, or `unified` | Sets the layout. `auto` chooses based on the available width. |
|
||||
|
||||
`branch` shows **All** (branch and local changes), `committed` shows **Committed** (branch commits only), and `working` shows **Uncommitted** (staged, unstaged, and untracked changes).
|
||||
|
||||
In `/diff`, press `d` to change the scope or choose a comparison branch from **Base**. OpenCode infers the base from local Git history when possible; otherwise it asks you to choose before loading a branch diff.
|
||||
|
||||
Your base choice for each branch and last selected scope survive closing and reopening the viewer, but reset when the TUI exits. These selections do not change `cli.json`.
|
||||
|
||||
## Tabs
|
||||
|
||||
Choose **Tabs > Indicators** in settings, or set `tabs.indicators` in `cli.json`:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"tabs": {
|
||||
"indicators": "numbers"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`status` (the default) shows status icons. `numbers` always shows tab numbers, retaining their status colors and background animations. Both modes work with horizontal and vertical tabs. Ctrl+number shortcuts switch tabs in either mode.
|
||||
An invalid or unreadable override falls back to the built-in sound for that event.
|
||||
|
||||
## Terminal
|
||||
|
||||
@@ -216,7 +254,158 @@ Configure terminal integration:
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Values | Description |
|
||||
| ------- | -------------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `title` | boolean | Updates the terminal window title. |
|
||||
| `copy` | `manual` or `select` | Sets manual copy or copy on selection. Defaults to `select` on macOS and Linux, and `manual` on Windows. |
|
||||
<div class="docs-table-scroll" role="region" aria-label="Terminal settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| ---------------- | -------------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `terminal.title` | boolean | Updates the terminal window title. |
|
||||
| `terminal.copy` | `manual` or `select` | Copies manually or immediately after selection. The platform default is `manual` on Windows and `select` elsewhere. |
|
||||
|
||||
</div>
|
||||
|
||||
## Mini
|
||||
|
||||
The `mini` group controls [`opencode mini`](/cli#mini), the minimal interactive interface:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"mini": {
|
||||
"thinking": "show",
|
||||
"tools": "hide",
|
||||
"shell_output": "hide",
|
||||
"turn_summary": "show",
|
||||
"footer": "show",
|
||||
"splash": "show",
|
||||
"work_spinner": "block-soft-slide",
|
||||
"mono": false,
|
||||
"replay": true,
|
||||
"replay_limit": 200
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<div class="docs-table-scroll" role="region" aria-label="Mini settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| ------------------- | ------------------------------ | ---------------------------------------------------------------------------------- |
|
||||
| `mini.thinking` | `show` or `hide` | Shows or hides model reasoning. |
|
||||
| `mini.tools` | `show` or `hide` | Shows or hides tool calls and the assistant text that precedes them. |
|
||||
| `mini.shell_output` | `show` or `hide` | Shows or hides raw shell tool output. |
|
||||
| `mini.turn_summary` | `show` or `hide` | Shows or hides the agent, model, and duration summary in scrollback. |
|
||||
| `mini.footer` | `show` or `hide` | Shows or hides persistent activity, model, usage, and context details. |
|
||||
| `mini.splash` | `show` or `hide` | Shows or hides entry and exit splash banners. |
|
||||
| `mini.work_spinner` | spinner ID | Selects the work animation in the footer. |
|
||||
| `mini.mono` | boolean | Uses monochrome ASCII output. |
|
||||
| `mini.replay` | boolean | Restores session history on resume and terminal resize. |
|
||||
| `mini.replay_limit` | positive integer | Limits replay to the newest messages. The default limit is `200`. |
|
||||
|
||||
</div>
|
||||
|
||||
Available spinner IDs are:
|
||||
|
||||
```text
|
||||
block-soft-slide block-soft-sweep block-low-comet block-low-duet
|
||||
block-shuttle block-bridge block-squeeze small-toggle
|
||||
square-toggle grow-shrink quadrant-orbit crosshatch
|
||||
density-wave seed
|
||||
```
|
||||
|
||||
Command-line `mini` replay flags override these settings for that invocation.
|
||||
|
||||
## Keybinds
|
||||
|
||||
Override a command binding and the leader-key timeout:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"keybinds": {
|
||||
"leader": "ctrl+x",
|
||||
"app.exit": ["ctrl+c", "ctrl+d", "<leader>q"],
|
||||
"prompt.paste": {
|
||||
"key": "ctrl+v",
|
||||
"event": "press",
|
||||
"preventDefault": false,
|
||||
"fallthrough": false
|
||||
},
|
||||
"help.show": false
|
||||
},
|
||||
"leader": {
|
||||
"timeout": 2000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<div class="docs-table-scroll" role="region" aria-label="Keybind settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| ----------------------- | ------------------------------------------------ | -------------------------------------------------------------------- |
|
||||
| `keybinds.leader` | binding value | Sets the key referenced by `<leader>` in other bindings. |
|
||||
| `keybinds.<command>` | binding value | Overrides the binding for one command ID. |
|
||||
| `keybinds.*.key` | key string or descriptor | Selects the key for an object binding. |
|
||||
| `keybinds.*.event` | `press` or `release` | Limits an object binding to one key event. |
|
||||
| `keybinds.*.preventDefault` | boolean | Controls whether the terminal's default key behavior is prevented. |
|
||||
| `keybinds.*.fallthrough` | boolean | Allows lower-priority handlers to receive the same event. |
|
||||
| `leader.timeout` | positive integer | Sets how many milliseconds to wait after the leader key. |
|
||||
|
||||
</div>
|
||||
|
||||
A binding value can be a string, an array of alternatives, or an object. Use `"none"` or `false` to disable a binding.
|
||||
See [Keybinds](/cli/keybinds) for accepted key syntax, every command ID, and every default binding.
|
||||
|
||||
## Plugins
|
||||
|
||||
Load terminal-only plugins in order:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"plugins": [
|
||||
"-opencode.notifications",
|
||||
{
|
||||
"package": "./plugins/status",
|
||||
"options": {
|
||||
"compact": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
<div class="docs-table-scroll" role="region" aria-label="Plugin settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| -------------------- | --------------- | --------------------------------------------------------------- |
|
||||
| `plugins` | array | Declares ordered enablement directives and external plugins. |
|
||||
| `plugins[].package` | string | Sets a package name, local path, or file URL. |
|
||||
| `plugins[].options` | object | Passes plugin-specific options to that plugin. |
|
||||
|
||||
</div>
|
||||
|
||||
See [Plugins](/cli/plugins) for package forms, local discovery, wildcards, and disable directives.
|
||||
|
||||
## Debug and experimental
|
||||
|
||||
Enable diagnostics or opt in to a currently available experiment:
|
||||
|
||||
```json title="cli.json"
|
||||
{
|
||||
"debug": {
|
||||
"devtools": false,
|
||||
"timing": false,
|
||||
"turn_tokens": "verbose"
|
||||
},
|
||||
"experimental": {}
|
||||
}
|
||||
```
|
||||
|
||||
<div class="docs-table-scroll" role="region" aria-label="Debug and experimental settings" tabIndex={0}>
|
||||
|
||||
| Setting | Values | Description |
|
||||
| ------------------- | ------------------------------- | ----------------------------------------------------------------------------------- |
|
||||
| `debug.devtools` | boolean | Shows the DevTools debug bar. |
|
||||
| `debug.timing` | boolean | Shows time-to-first-draw diagnostics in the debug bar. |
|
||||
| `debug.turn_tokens` | boolean or `verbose` | Shows per-turn token usage; `verbose` also includes tool call inputs. |
|
||||
| `experimental` | object of feature IDs to booleans | Enables or disables experiments that may change or be removed without notice. |
|
||||
|
||||
</div>
|
||||
|
||||
Only use feature IDs currently listed by the TUI's **Experiments** dialog. Unknown IDs have no effect.
|
||||
|
||||
@@ -8,7 +8,7 @@ OpenCode includes built-in light and dark themes. Choose a color scheme in setti
|
||||
|
||||
Press `Ctrl+P`, then select **Open settings** to change the theme and color mode.
|
||||
|
||||
You can also set them in your global [CLI config](/cli/config):
|
||||
You can also set them in your global [CLI settings](/cli/config):
|
||||
|
||||
```json title="~/.config/opencode/cli.json"
|
||||
{
|
||||
|
||||
@@ -46,4 +46,4 @@ plan that grants you access to the best open source models.
|
||||
|
||||
Make OpenCode your own by editing the [OpenCode config](/config), [loading plugins](/plugins), [connecting MCP
|
||||
servers](/mcp-servers), or [creating commands](/commands). For terminal interface themes and keybindings, see [CLI
|
||||
configuration](/cli/config).
|
||||
settings](/cli/config).
|
||||
|
||||
@@ -524,7 +524,7 @@ V2 replaces layered V1 `tui.json(c)` files with one global terminal client confi
|
||||
The terminal client owns this file; the background service does not load it. When `cli.json` is absent, the first V2
|
||||
terminal client startup migrates supported global `tui.json` settings and persisted preferences while leaving V1 files
|
||||
unchanged. Project-local client configuration is not migrated because V2 client configuration is global. See
|
||||
[CLI config](/cli/config) for current client settings.
|
||||
[CLI settings](/cli/config) for the current client settings reference.
|
||||
|
||||
## Plugins
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ opencode serve
|
||||
Check that the CLI can reach the background service after applying the settings:
|
||||
|
||||
```bash
|
||||
opencode api get /api/status
|
||||
opencode api get /api/info
|
||||
```
|
||||
|
||||
A successful health response verifies the local client-to-service connection. Run a normal provider request to verify the
|
||||
|
||||
@@ -15,7 +15,7 @@ set it directly in your global CLI config:
|
||||
```
|
||||
|
||||
Themes belong to the terminal client. Put theme selection in `cli.json`, not `opencode.json`. See
|
||||
[CLI config](/cli/config) for the config location and other terminal settings.
|
||||
[CLI settings](/cli/config) for the config location and other terminal settings.
|
||||
|
||||
## Modes
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ state. Start by determining whether an issue is in a client, the shared server,
|
||||
|
||||
## Check the background service
|
||||
|
||||
Show the current server status:
|
||||
Show the current server information:
|
||||
|
||||
```bash
|
||||
opencode service status
|
||||
@@ -21,7 +21,7 @@ opencode service status
|
||||
Verify that its API is healthy:
|
||||
|
||||
```bash
|
||||
opencode api get /api/status
|
||||
opencode api get /api/info
|
||||
```
|
||||
|
||||
If the service is stuck or unhealthy, restart it:
|
||||
@@ -117,7 +117,7 @@ On macOS and Linux, you can signal a running OpenCode process to capture diagnos
|
||||
from the health endpoint:
|
||||
|
||||
```bash
|
||||
opencode api get /api/status
|
||||
opencode api get /api/info
|
||||
```
|
||||
|
||||
Use the `pid` from the response with one of these signals:
|
||||
|
||||
@@ -69,7 +69,7 @@ export const docsSections: DocsSection[] = [
|
||||
items: [
|
||||
{ title: "Intro", slug: "cli" },
|
||||
{ title: "TUI", slug: "cli/tui" },
|
||||
{ title: "Config", slug: "cli/config" },
|
||||
{ title: "Settings", slug: "cli/config" },
|
||||
{ title: "Web", slug: "cli/web" },
|
||||
{ title: "Providers", slug: "cli/providers" },
|
||||
{ title: "Commands", slug: "cli/commands" },
|
||||
|
||||
Reference in New Issue
Block a user