feat(config): add experimental updates

This commit is contained in:
Dax Raad
2026-09-13 19:41:06 -04:00
Unverified
parent c2cf497e19
commit 763cac8080
19 changed files with 433 additions and 7 deletions
+1
View File
@@ -101,6 +101,7 @@ Review endpoints in document order. For each endpoint, select one disposition an
| [x] 022 | `GET` | `/api/config/preferences` | `config.preferences` | Remove | Redundant special projection of global config. |
| [x] 023 | `PATCH` | `/api/config/preferences` | `config.updatePreferences` | Remove | Redundant field-specific config mutation API. |
| [ ] 024 | `GET` | `/api/config/shell` | `config.shells` | | |
| [x] 024a | `PATCH` | `/api/experimental/config` | `experimental.config.update` | Change | Experimental global config mutation; initially accepts only `shell`. |
## Group 3: Credentials, integrations, MCP, and web search
@@ -24,6 +24,14 @@ test.beforeEach(async ({ page }) => {
sandboxes,
},
provider: { all: [], connected: [], default: {} },
configEntries: [
{ type: "document", path: "/home/test/.config/opencode/opencode.jsonc", info: { shell: "/bin/zsh" } },
{ type: "directory", path: "/home/test/.config/opencode" },
],
shells: [
{ path: "/bin/zsh", name: "zsh", acceptable: true },
{ path: "/bin/bash", name: "bash", acceptable: true },
],
sessions: sandboxes.map((directory, index) => ({
id: `ses_settings_${index + 1}`,
title: `Workspace ${index + 1} session`,
@@ -81,6 +89,14 @@ test("single-server settings expose scoped pages without a server picker", async
await expect(connection.locator(".settings-servers-row")).toHaveCSS("padding-top", "20px")
await expect(connection.locator(".settings-servers-lead")).toHaveCSS("column-gap", "4px")
await expect(connection.locator(".settings-servers-copy")).toHaveCSS("row-gap", "6px")
await expect(settings.getByRole("heading", { name: "Preferences", exact: true })).toBeVisible()
await expect(settings.getByText("Terminal shell", { exact: true })).toBeVisible()
await settings.getByText("zsh", { exact: true }).click()
const updated = page.waitForRequest(
(request) => request.method() === "PATCH" && new URL(request.url()).pathname === "/api/experimental/config",
)
await page.getByRole("option", { name: "bash", exact: true }).click()
expect((await updated).postDataJSON()).toEqual({ shell: "/bin/bash" })
})
test("project settings open as a nested autosaving view", async ({ page }) => {
+6
View File
@@ -78,6 +78,12 @@ const Group = HttpApiGroup.make("mock")
}),
)
.add(HttpApiEndpoint.get("configShells", "/api/config/shell", { success: Json }))
.add(
HttpApiEndpoint.patch("configUpdate", "/api/experimental/config", {
payload: Schema.Struct({ shell: Schema.NullOr(Schema.String) }),
success: HttpApiSchema.NoContent,
}),
)
.add(HttpApiEndpoint.get("websearchProviders", "/api/websearch/provider", { success: Json }))
.add(
HttpApiEndpoint.get("worktreeList", "/api/worktree", {
+4 -1
View File
@@ -11,6 +11,7 @@ export interface MockServerConfig {
integrationMethods?: Record<string, unknown[]>
onConnectKey?: (input: { integrationID: string; body: unknown }) => void
shells?: unknown[]
configEntries?: unknown[]
websearchProviders?: unknown[]
directory: string
project: unknown
@@ -197,6 +198,7 @@ const corsHeaders = {
function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, string>; nextCursor: number }) {
const noContent = Effect.succeed(HttpApiSchema.NoContent.make())
const delay = config.messageDelay === undefined ? Effect.void : Effect.sleep(Duration.millis(config.messageDelay))
const configEntries = config.configEntries ?? []
return HttpApiBuilder.group(MockApi, "mock", (handlers) =>
handlers
.handleRaw("event", () => {
@@ -218,7 +220,7 @@ function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, st
)
.handleAll({
status: () => Effect.succeed({ version: "2.0.0", pid: 1, urls: config.server ? [config.server] : [] }),
config: () => Effect.succeed([]),
config: () => Effect.succeed(configEntries),
reference: () =>
Effect.succeed({
location: {
@@ -284,6 +286,7 @@ function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, st
})
},
configShells: () => Effect.succeed(config.shells ?? []),
configUpdate: () => noContent,
websearchProviders: () => Effect.succeed({ location: location(config), data: config.websearchProviders ?? [] }),
worktreeList: () =>
Effect.succeed([
@@ -1,4 +1,4 @@
import { createMemo, onMount, type Accessor } from "solid-js"
import { createMemo, createResource, onMount, type Accessor } from "solid-js"
import type { ColorScheme } from "@opencode/ui/theme/context"
import { useTheme } from "@opencode/ui/theme/context"
import {
@@ -15,10 +15,59 @@ import {
} from "@/settings/model"
import { playSoundById, SOUND_OPTIONS } from "@/shell/notifications/sound"
import { createSoundPreviewController } from "./behavior"
import { ServerConnection } from "@/runtime/server/registry"
import { useServerCtx } from "@/runtime/server/runtime"
import { useLanguage } from "@/runtime/i18n/language"
import { showToast } from "@/shell/notifications/toast"
export { createShellOptions, createSoundPreviewController } from "./behavior"
export type { ShellOption, ShellSelectOption } from "./behavior"
export function createServerShellController(server: Accessor<ServerConnection.Any>) {
const language = useLanguage()
const serverCtx = useServerCtx(server)
const source = () => ServerConnection.key(server())
const [state, actions] = createResource(
source,
async () => {
const context = serverCtx()
const [entries, shells] = await Promise.all([
context.sdk.api.config.get().catch(() => []),
context.sdk.api.config.shells().catch(() => []),
])
const boundary = entries.findIndex((entry) => entry.type === "directory")
const global = boundary === -1 ? entries : entries.slice(0, boundary)
return {
shells,
shell: global
.flatMap((entry) => (entry.type === "document" && entry.info.shell !== undefined ? [entry.info.shell] : []))
.at(-1),
}
},
{ initialValue: { shells: [], shell: undefined } },
)
return {
shells: () => state.latest.shells,
current: () => state.latest.shell ?? "",
select: (value: string) => {
if (value === (state.latest.shell ?? "")) return
const previous = state.latest
actions.mutate({ ...previous, shell: value || undefined })
void serverCtx()
.sdk.api.config.update({ shell: value || null })
.catch((error: unknown) => {
actions.mutate(previous)
showToast({
variant: "error",
title: language.t("common.requestFailed"),
description: error instanceof Error ? error.message : language.t("common.requestFailed"),
})
})
},
}
}
export function createAppearanceSettingsController() {
const settings = useSettings()
const theme = useTheme()
@@ -114,5 +163,7 @@ export function createSoundSettingsController() {
}
}
export type ShellSettingsController = ReturnType<typeof createServerShellController>
export type AppearanceSettingsController = ReturnType<typeof createAppearanceSettingsController>
export type SoundSettingsController = ReturnType<typeof createSoundSettingsController>
+37 -1
View File
@@ -18,7 +18,12 @@ import { formatKeybind } from "@/shell/commands/command"
import { ExternalLink } from "@/runtime/platform/external-link"
import { SettingsList } from "@/settings/list"
import { SettingsRow } from "@/settings/row"
import { createAppearanceSettingsController, type AppearanceSettingsController } from "./controllers"
import {
createAppearanceSettingsController,
createShellOptions,
type AppearanceSettingsController,
type ShellSettingsController,
} from "./controllers"
import "@/settings/settings.css"
const schemeOptions: ("system" | "light" | "dark")[] = ["system", "light", "dark"]
@@ -91,6 +96,37 @@ const WorkspaceDestinationSetting: Component = () => {
)
}
export const ShellSetting: Component<{ controller: ShellSettingsController }> = (props) => {
const language = useLanguage()
const options = createMemo(() =>
createShellOptions({
shells: props.controller.shells(),
current: props.controller.current(),
}),
)
return (
<SettingsRow
title={language.t("settings.general.row.shell.title")}
description={language.t("settings.general.row.shell.description")}
>
<Select
data-action="settings-shell"
options={options()}
current={options().find((option) => option.value === props.controller.current()) ?? options()[0]}
placement="bottom-end"
gutter={6}
value={(option) => option.id}
label={(option) => {
if (option.id === "auto") return language.t("settings.general.row.shell.autoDefault")
if (!option.terminalOnly) return option.name
return `${option.name} (${language.t("settings.general.row.shell.terminalOnly")})`
}}
onSelect={(option) => option && props.controller.select(option.value)}
/>
</SettingsRow>
)
}
const TerminalPlacementSetting: Component = () => {
const language = useLanguage()
const settings = useSettings()
@@ -10,6 +10,8 @@ import { DialogServer } from "@/servers/connect/dialog"
import { AddServerMenu, WslServerSettings } from "@/servers/wsl/settings"
import { SshServerSettings } from "@/servers/ssh/settings"
import { SettingsList } from "@/settings/list"
import { ShellSetting } from "@/settings/general/general"
import { createServerShellController } from "@/settings/general/controllers"
import type { SettingsServer } from "./inventory"
import "@/settings/settings.css"
@@ -89,7 +91,24 @@ export const SettingsServerGeneral: Component<{
</Show>
</SettingsList>
</section>
<Show when={props.entry.connection} keyed>
{(server) => <ServerShell server={server} />}
</Show>
</div>
</>
)
}
function ServerShell(props: { server: ServerConnection.Any }) {
const language = useLanguage()
const controller = createServerShellController(() => props.server)
return (
<section class="settings-section">
<h3 class="settings-section-title">{language.t("settings.tab.preferences")}</h3>
<SettingsList>
<ShellSetting controller={controller} />
</SettingsList>
</section>
)
}
+5
View File
@@ -2314,9 +2314,14 @@ export type ConfigShellsOutput = ReadonlyArray<{
}>
export type ConfigShellsOperation<E = never> = () => Effect.Effect<ConfigShellsOutput, E>
export type ConfigUpdateInput = { readonly shell: string | null }
export type ConfigUpdateOutput = void
export type ConfigUpdateOperation<E = never> = (input: ConfigUpdateInput) => Effect.Effect<ConfigUpdateOutput, E>
export interface ConfigApi<E = never> {
readonly get: ConfigGetOperation<E>
readonly shells: ConfigShellsOperation<E>
readonly update: ConfigUpdateOperation<E>
}
export interface AppApi<E = never> {
@@ -264,6 +264,8 @@ import type {
ConfigGetInput,
ConfigGetOutput,
ConfigShellsOutput,
ConfigUpdateInput,
ConfigUpdateOutput,
} from "../api/api.js"
import { ClientError } from "./client-error.js"
@@ -1556,9 +1558,15 @@ const EndpointConfigGet = (raw: RawClient["server.config"]) => (input?: ConfigGe
const EndpointConfigShells = (raw: RawClient["server.config"]) => () =>
preserveEffect<ConfigShellsOutput>()(raw["config.shells"]({}).pipe(Effect.mapError(mapClientError)))
const EndpointConfigUpdate = (raw: RawClient["server.config"]) => (input: ConfigUpdateInput) =>
preserveEffect<ConfigUpdateOutput>()(
raw["config.update"]({ payload: { shell: input["shell"] } }).pipe(Effect.mapError(mapClientError)),
)
const adaptGroupConfig = (raw: RawClient["server.config"]) => ({
get: EndpointConfigGet(raw),
shells: EndpointConfigShells(raw),
update: EndpointConfigUpdate(raw),
})
const adaptClient = (raw: RawClient) => ({
@@ -260,6 +260,8 @@ import type {
ConfigGetInput,
ConfigGetOutput,
ConfigShellsOutput,
ConfigUpdateInput,
ConfigUpdateOutput,
} from "./types.js"
import { ClientError } from "./client-error.js"
@@ -2157,6 +2159,18 @@ export function make(options: ClientOptions) {
{ method: "GET", path: `/api/config/shell`, successStatus: 200, declaredStatuses: [400, 401], empty: false },
requestOptions,
),
update: (input: ConfigUpdateInput, requestOptions?: RequestOptions) =>
request<ConfigUpdateOutput>(
{
method: "PATCH",
path: `/api/experimental/config`,
body: { shell: input["shell"] },
successStatus: 204,
declaredStatuses: [400, 401],
empty: true,
},
requestOptions,
),
},
}
}
@@ -6210,3 +6210,7 @@ export type ConfigGetInput = {
export type ConfigGetOutput = Array<ConfigEntry>
export type ConfigShellsOutput = Array<ConfigShellOption>
export type ConfigUpdateInput = { readonly shell: { readonly shell: string | null }["shell"] }
export type ConfigUpdateOutput = void
+28 -2
View File
@@ -3,9 +3,9 @@ export * as Config from "./config.js"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import path from "path"
import { isDeepStrictEqual } from "node:util"
import { type ParseError, parse } from "jsonc-parser"
import { applyEdits, modify, type ParseError, parse } from "jsonc-parser"
import { Context, Effect, FiberMap, Layer, Option, PubSub, Ref, Schema, Semaphore, Stream } from "effect"
import { Directory, Document, Info, type Entry, Event } from "@opencode/schema/config"
import { Directory, Document, Info, type Patch, type Entry, Event } from "@opencode/schema/config"
import { Credential } from "./credential.js"
import { Bus } from "./bus.js"
import { Watcher } from "./filesystem/watcher.js"
@@ -38,6 +38,8 @@ export interface Interface {
* source files they parse and rebuild their own state.
*/
readonly changes: () => Stream.Stream<Watcher.Update>
/** Updates supported global config fields while preserving unrelated JSONC content. */
readonly update?: (patch: Patch) => Effect.Effect<void, FSUtil.Error>
}
export const Options = Schema.Struct({
@@ -96,6 +98,7 @@ export const layer = (options?: Options) =>
const globalService = yield* Global.Service
const wellknown = yield* WellKnown.Service
const reloadLock = Semaphore.makeUnsafe(1)
const updateLock = Semaphore.makeUnsafe(1)
const decodeOptions = { errors: "all", onExcessProperty: "ignore", propertyOrder: "original" } as const
const decodeInfo = Schema.decodeUnknownOption(Info, decodeOptions)
const parseInfo = Effect.fn("Config.parseInfo")(function* (text: string, source: string) {
@@ -323,6 +326,28 @@ export const layer = (options?: Options) =>
)
yield* reloadLock.withPermit(reconcile(initial))
const update = Effect.fn("Config.update")(
function* (patch: Patch) {
const directory = initial.global ?? AbsolutePath.make(globalService.config)
const candidates = ConfigDiscovery.names.map((name) => path.join(directory, name))
const filepath = (yield* Effect.filter(candidates, fs.isFile)).at(-1) ?? path.join(directory, "opencode.jsonc")
const text = (yield* fs.readFileStringSafe(filepath)) ?? "{}\n"
const updated = yield* Effect.try({
try: () =>
applyEdits(
text,
modify(text, ["shell"], patch.shell ?? undefined, {
formattingOptions: { tabSize: 2, insertSpaces: true },
}),
),
catch: (cause) => new FSUtil.FileSystemError({ method: "config.update", cause }),
})
yield* fs.writeWithDirs(filepath, updated.endsWith("\n") ? updated : `${updated}\n`)
yield* requestReload
},
(effect) => updateLock.withPermit(effect),
)
return Service.of({
entries: Effect.fnUntraced(function* () {
return configs
@@ -333,6 +358,7 @@ export const layer = (options?: Options) =>
agents: Effect.filter(sources.agents, fs.isDir),
}),
changes: () => Stream.fromPubSub(updates),
update,
})
}),
)
+62
View File
@@ -12768,6 +12768,51 @@
"description": "Return shells available to terminal and agent execution.",
"summary": "List available shells"
}
},
"/api/experimental/config": {
"patch": {
"tags": ["config"],
"operationId": "experimental.config.update",
"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"
}
}
}
}
},
"description": "Patch supported fields in the highest-precedence global configuration document.",
"summary": "Update global configuration",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Config.Patch"
}
}
},
"required": true
}
}
}
},
"components": {
@@ -13581,6 +13626,23 @@
},
"additionalProperties": false
},
"Config.Patch": {
"type": "object",
"properties": {
"shell": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
}
},
"required": ["shell"],
"additionalProperties": false
},
"Config.Plugin.EntryEncoded": {
"type": "object",
"properties": {
+13 -1
View File
@@ -1,7 +1,7 @@
import { Config } from "@opencode/schema/config"
import { ConfigShell } from "@opencode/schema/config/shell"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi"
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
export const ConfigGroup = HttpApiGroup.make("server.config")
@@ -31,4 +31,16 @@ export const ConfigGroup = HttpApiGroup.make("server.config")
}),
),
)
.add(
HttpApiEndpoint.patch("config.update", "/api/experimental/config", {
payload: Config.Patch,
success: HttpApiSchema.NoContent,
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.config.update",
summary: "Update global configuration",
description: "Patch supported fields in the highest-precedence global configuration document.",
}),
),
)
.annotateMerge(OpenApi.annotations({ title: "config", description: "Location-scoped configuration routes." }))
+5
View File
@@ -109,6 +109,11 @@ export class Info extends Schema.Class<Info>("Config.Info")({
experimental: ConfigExperimental.Info.pipe(optional),
}) {}
export const Patch = Schema.Struct({
shell: Schema.NullOr(Schema.String),
}).annotate({ identifier: "Config.Patch" })
export interface Patch extends Schema.Schema.Type<typeof Patch> {}
export class Document extends Schema.Class<Document>("Config.Document")({
type: Schema.Literal("document"),
path: AbsolutePath.pipe(optional),
+8
View File
@@ -7,6 +7,14 @@ import { Api } from "../api"
export const ConfigHandler = HttpApiBuilder.group(Api, "server.config", (handlers) =>
handlers
.handle("config.get", () => Config.Service.use((config) => config.entries()))
.handle(
"config.update",
Effect.fn(function* (ctx) {
const config = yield* Config.Service
if (!config.update) return yield* Effect.die(new Error("Config updates are unavailable"))
return yield* config.update(ctx.payload).pipe(Effect.orDie)
}),
)
.handle(
"config.shells",
Effect.fn(function* () {
+27 -1
View File
@@ -59,12 +59,38 @@ it.live("returns ordered config entries for the requested directory", () =>
}),
)
it.live("lists available shells", () =>
it.live("updates the global shell without replacing unrelated JSONC", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-config-shells-")))
const global = path.join(tmp.path, "global")
const config = path.join(global, "opencode.jsonc")
yield* Effect.promise(() => fs.mkdir(global, { recursive: true }))
yield* Effect.promise(() =>
fs.writeFile(
config,
`{
// keep this comment
"model": "provider/model",
"shell": "bash"
}
`,
),
)
const server = yield* startServer(global)
const response = yield* Effect.promise(() =>
fetch(new URL("/api/experimental/config", server.base), {
method: "PATCH",
headers: { ...server.headers, "content-type": "application/json" },
body: JSON.stringify({ shell: "/bin/zsh" }),
}),
)
expect(response.status).toBe(204)
const text = yield* Effect.promise(() => fs.readFile(config, "utf8"))
expect(text).toContain("// keep this comment")
expect(text).toContain('"model": "provider/model"')
expect(text).toContain('"shell": "/bin/zsh"')
const shells = yield* Effect.promise(() =>
fetch(new URL("/api/config/shell", server.base), { headers: server.headers }),
)
+62
View File
@@ -12768,6 +12768,51 @@
"description": "Return shells available to terminal and agent execution.",
"summary": "List available shells"
}
},
"/api/experimental/config": {
"patch": {
"tags": ["config"],
"operationId": "experimental.config.update",
"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"
}
}
}
}
},
"description": "Patch supported fields in the highest-precedence global configuration document.",
"summary": "Update global configuration",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Config.Patch"
}
}
},
"required": true
}
}
}
},
"components": {
@@ -13581,6 +13626,23 @@
},
"additionalProperties": false
},
"Config.Patch": {
"type": "object",
"properties": {
"shell": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
}
},
"required": ["shell"],
"additionalProperties": false
},
"Config.Plugin.EntryEncoded": {
"type": "object",
"properties": {
+62
View File
@@ -12768,6 +12768,51 @@
"description": "Return shells available to terminal and agent execution.",
"summary": "List available shells"
}
},
"/api/experimental/config": {
"patch": {
"tags": ["config"],
"operationId": "experimental.config.update",
"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"
}
}
}
}
},
"description": "Patch supported fields in the highest-precedence global configuration document.",
"summary": "Update global configuration",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Config.Patch"
}
}
},
"required": true
}
}
}
},
"components": {
@@ -13581,6 +13626,23 @@
},
"additionalProperties": false
},
"Config.Patch": {
"type": "object",
"properties": {
"shell": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
}
},
"required": ["shell"],
"additionalProperties": false
},
"Config.Plugin.EntryEncoded": {
"type": "object",
"properties": {