Compare commits

...

8 Commits

28 changed files with 617 additions and 212 deletions
+17 -15
View File
@@ -599,8 +599,8 @@
},
"peerDependencies": {
"@opencode/theme": "workspace:*",
"@opentui/core": ">=0.5.13",
"@opentui/solid": ">=0.5.13",
"@opentui/core": ">=0.5.14",
"@opentui/solid": ">=0.5.14",
"solid-js": ">=1.9.0",
},
"optionalPeers": [
@@ -1117,9 +1117,9 @@
"@npmcli/arborist": "9.4.0",
"@octokit/rest": "22.0.0",
"@openauthjs/openauth": "0.0.0-20250322224806",
"@opentui/core": "0.5.13",
"@opentui/keymap": "0.5.13",
"@opentui/solid": "0.5.13",
"@opentui/core": "0.5.14",
"@opentui/keymap": "0.5.14",
"@opentui/solid": "0.5.14",
"@pierre/diffs": "1.5.1",
"@playwright/test": "1.59.1",
"@sentry/solid": "10.71.0",
@@ -2255,25 +2255,27 @@
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
"@opentui/core": ["@opentui/core@0.5.13", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.5.13", "@opentui/core-darwin-x64": "0.5.13", "@opentui/core-linux-arm64": "0.5.13", "@opentui/core-linux-arm64-musl": "0.5.13", "@opentui/core-linux-x64": "0.5.13", "@opentui/core-linux-x64-musl": "0.5.13", "@opentui/core-win32-arm64": "0.5.13", "@opentui/core-win32-x64": "0.5.13" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-3XNXJx3J9I+Ce170oh7GJ3leBZZA7QYv4OAhwiMCPQtKMkhy3Wra99NM26HXcEGme0zjkkJLownwLLnxuc0U/Q=="],
"@opentui/core": ["@opentui/core@0.5.14", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.5.14", "@opentui/core-darwin-x64": "0.5.14", "@opentui/core-linux-arm64": "0.5.14", "@opentui/core-linux-arm64-musl": "0.5.14", "@opentui/core-linux-x64": "0.5.14", "@opentui/core-linux-x64-musl": "0.5.14", "@opentui/core-win32-arm64": "0.5.14", "@opentui/core-win32-x64": "0.5.14" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-tfQ+PWQyeBnYloB3diEcPqbILv14xemH5jjAEICfPuyNDtGBqrjhUtThrhbvFRuPMcj6IEeXrAk6VE8e91h0kg=="],
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.5.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5X9U2v5qn4+vKj31zpn0RMoBV3Q9ttdM4t5KN41NPg6XgtIOZgKwox5yOsvBaiQ1KGbuk5wMvXCxfWJ30Mj/nw=="],
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.5.14", "", { "os": "darwin", "cpu": "arm64" }, "sha512-wWmw41wRMBoI0lN9mgyzGRwYujwwfNkBP6jYM99k4Bx2XkeSZ3sCeu5bwX9vEJPYqjiBShbDhc0NnVSP7NwzVg=="],
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.5.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-9IgQHLKSn3quVsU0gibkRjOPegv1QH4573KWYXQNDmSxBXw84Nd1mDNsbK9f72SblAILhOCYK685pmk3X/z0Ig=="],
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.5.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-7smHKDH8IhUaBsgYuAClMl2mHWu+yjpMrtdw3wEvBVtCzKMrHi/TJ5PtydO+IfUzR3BXpVubdbR1irD8BTcR/w=="],
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.5.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-jMXGEpB/2Ch/IR0QzYBM5eCr1tUzicxoTP1AbMCbOduJXcGRCHTWqIdQIgRErwPF92gBcDIs4JugSn/Jd0Ki7g=="],
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.5.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-xH1hP+NaLySEJeZkl21NlkZBMddMfQ1jU8NeX1AEBc2GNBOvDXU4Ud/xw87SrAvU1xG9K7/9C4oy4AmIMEpVGg=="],
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.5.13", "", { "os": "linux", "cpu": "x64" }, "sha512-7ytcKy7pQxvQer3PADGYNK+HRhSDyhZvp475GRBEhlBJIdhdL8PNU6hjd2R1dnieifiW7Mpc4EiC1kGKe69gYg=="],
"@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.5.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-mnBBAuTb92NiRLAjOD755tS8/tNQemDztbg9tMvoCT90G52FtVrRb31Ge6OrYqfm0c9DkZGhEBOhunsId/4zSA=="],
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.5.13", "", { "os": "linux", "cpu": "x64" }, "sha512-C2ZC7WA7YH/GS+rJnbeVGe6Kxeor0aTD2qcS6l32KmN4XuY7TXm192XJMfxxnKaTA6oKp3mW27ezolJKUcGtMw=="],
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.5.14", "", { "os": "linux", "cpu": "x64" }, "sha512-Hkk4kaDGMcn9bmJFJPW3/QOGGbPuWe3sCFV/CkiVb4+bCvcTm7EXQr4QTAA63BYy2dKE5bUFUi1zZlyeMkWpnA=="],
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.5.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-IB6eLh6I/gYXrJ0AYxZpD+Dr+yfZJck0ZfLnIapbD+fykaT0umOtvc/BL+CtlC/aSc7jpe0q4eXdn6XIA8HtLw=="],
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.5.14", "", { "os": "linux", "cpu": "x64" }, "sha512-ngJ+U2grOGEteeQvZdAJNqn09M+At5mfWInauK5aS427bea1yLo+e6hor/CRmbn9SxEEF+SwoyekaOrLPWyU7w=="],
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.5.13", "", { "os": "win32", "cpu": "x64" }, "sha512-FCucDN8A4iFDPdwqLK99ISs42pcbcObkxhN1jtsnmcYM9/Ptron7Hhapx2ObQWYjSrJNnntmfZQd2ewpE8YqTQ=="],
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.5.14", "", { "os": "win32", "cpu": "arm64" }, "sha512-T9kNqKXg2jysmTsyyZ1A8LBQotFBM+iPjzyRslxyexqrs8a1UcmxbApEo+COtxQuqukMTbvwyqEdAT8vcmxEkQ=="],
"@opentui/keymap": ["@opentui/keymap@0.5.13", "", { "dependencies": { "@opentui/core": "0.5.13" }, "peerDependencies": { "@opentui/react": "0.5.13", "@opentui/solid": "0.5.13", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-bbpQ5N8000CuvVDhptGuHxUE92sivChjUjLkvYT1VnLlDTiGbQ4mPsHfnqsaEokc7O7jBcoJXJQsLxw7rO/qkg=="],
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.5.14", "", { "os": "win32", "cpu": "x64" }, "sha512-mqKSkab8VdMLSmMdocna7+BTyMoIutkVXOV9lfmPrBO2g7Np5c6c4SJ4QIVZqPvast11XyT0/7FfXOYLKAS72w=="],
"@opentui/solid": ["@opentui/solid@0.5.13", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.5.13", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-MGMYQYeoZNn9uq3zsLPqq/G+nBQXgGwpylsrYux0nJ+C+6oflDEE6t8huSTZaAUizC/3WG8sVSVFutczeRbnPg=="],
"@opentui/keymap": ["@opentui/keymap@0.5.14", "", { "dependencies": { "@opentui/core": "0.5.14" }, "peerDependencies": { "@opentui/react": "0.5.14", "@opentui/solid": "0.5.14", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-YGTAvRrpQTbRNV7GH0UxRuCSPxwnSooVdB+qPHHP+3ywc93+lhekljgP8dRivl32f3CiMqqm96Uj2PgwKxkC0Q=="],
"@opentui/solid": ["@opentui/solid@0.5.14", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.5.14", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-bBRl34mZ0wFGhjHX6y1VNiZmJ3DSm2DVPm0PNSVDpvq9qxRHuywEPTCn/Lgte0C9450tgf11cDqcE3pR9cZwVA=="],
"@oslojs/asn1": ["@oslojs/asn1@1.0.0", "", { "dependencies": { "@oslojs/binary": "1.0.0" } }, "sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA=="],
+3 -3
View File
@@ -52,9 +52,9 @@
"@octokit/rest": "22.0.0",
"@hono/standard-validator": "0.2.0",
"@hono/zod-validator": "0.4.2",
"@opentui/core": "0.5.13",
"@opentui/keymap": "0.5.13",
"@opentui/solid": "0.5.13",
"@opentui/core": "0.5.14",
"@opentui/keymap": "0.5.14",
"@opentui/solid": "0.5.14",
"@tanstack/solid-virtual": "3.13.37",
"@shikijs/stream": "4.4.3",
"@standard-schema/spec": "1.1.0",
+4
View File
@@ -21,6 +21,8 @@ const patterns = [
/exceeds the context window/i,
/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,
/input token count.*exceeds the maximum/i,
// Amazon Nova on Bedrock reports this as a mid-stream validationException.
/number of input tokens exceeds maximum length/i,
/tokens in request more than max tokens allowed/i,
/maximum prompt length is \d+/i,
/reduce the length of the messages/i,
@@ -30,6 +32,8 @@ const patterns = [
/exceeds the limit of \d+/i,
/exceeds the available context size/i,
/greater than the context length/i,
// Hugging Face Text Generation Inference, e.g. Together
/`inputs` tokens \+ `max_new_tokens` must be <= \d+/i,
/context window exceeds limit/i,
/exceeded model token limit/i,
/context[_ ]length[_ ]exceeded/i,
+18
View File
@@ -13,6 +13,7 @@ describe("provider error classification", () => {
"Prompt has 5,958,968 tokens, but the configured context size is 256,000 tokens",
"Range of input length should be [1, 129024]",
"Too many tokens",
"Input validation error: `inputs` tokens + `max_new_tokens` must be <= 131073. Given: 600035 `inputs` tokens and 16 `max_new_tokens`",
"Token limit exceeded",
]
@@ -366,6 +367,23 @@ describe("provider error rawBody classification", () => {
expect(reason._tag === "InvalidRequest" ? reason.classification : reason._tag).toBe("context-overflow")
})
test("classifies Amazon Nova input token rejections as context overflow", () => {
const message =
"The model returned the following errors: Input Tokens Exceeded: Number of input tokens exceeds maximum length. Please update the input to try again."
const reason = classifyProviderFailure({
message,
rawBody: JSON.stringify({
headers: {
":exception-type": { type: "string", value: "validationException" },
":content-type": { type: "string", value: "application/json" },
":message-type": { type: "string", value: "exception" },
},
body: JSON.stringify({ message }),
}),
})
expect(reason._tag === "InvalidRequest" ? reason.classification : reason._tag).toBe("context-overflow")
})
test("classifies Google invalid API keys as authentication failures", () => {
const rawBody = JSON.stringify({
error: {
+139
View File
@@ -0,0 +1,139 @@
import type { CommandInfo, ModelInfo, ModelRef, OpenCodeClient, OpenCodeEvent } from "@opencode/client/promise"
import { FSUtil } from "@opencode/util/fs-util"
import type { ConfigOptionProvider } from "./config-option"
export type Catalog = {
readonly providers: ConfigOptionProvider[]
readonly models: ModelInfo[]
readonly defaultModel: ModelRef
readonly modes: Array<{ id: string; name: string; description?: string }>
readonly defaultModeID: string
readonly commands: CommandInfo[]
}
export type Live = {
readonly cwd: string
current: Catalog
}
// Provider, integration, and credential changes reach the catalog through model.updated.
const reloadOn = new Set<OpenCodeEvent["type"]>(["model.updated", "agent.updated", "command.updated"])
export function make(input: {
readonly client: OpenCodeClient
readonly signal?: AbortSignal
readonly changed: (live: Live, previous: Catalog) => Promise<unknown>
}) {
const entries = new Map<string, Promise<Live>>()
const running = new Map<Live, Promise<void>>()
const queued = new Set<Live>()
let subscribed: Promise<void> | undefined
const get = (cwd: string) => {
const key = FSUtil.resolve(cwd)
const cached = entries.get(key)
if (cached) return cached
// Subscribe before the first read so an update between the read and the subscription is not lost.
const loaded = subscribe()
.then(() => load(input.client, cwd))
.then((current): Live => ({ cwd, current }))
.catch((error) => {
entries.delete(key)
throw error
})
entries.set(key, loaded)
return loaded
}
const reload = (live: Live) => {
const current = running.get(live)
if (current) {
queued.add(live)
return current
}
const run = (async () => {
do {
queued.delete(live)
const next = await load(input.client, live.cwd).catch(() => undefined)
if (!next) break
const previous = live.current
live.current = next
await input.changed(live, previous).catch(() => {})
} while (queued.has(live))
running.delete(live)
})()
running.set(live, run)
return run
}
const subscribe = () =>
(subscribed ??= new Promise<void>((ready) => {
void (async () => {
for await (const event of input.client.event.subscribe({ signal: input.signal })) {
if (event.type === "server.connected") ready()
if (!reloadOn.has(event.type)) continue
const directory = event.location?.directory
const targets = directory === undefined ? [...entries.values()] : [entries.get(FSUtil.resolve(directory))]
targets.forEach((entry) => void entry?.then(reload, () => {}))
}
})()
.catch(() => {})
.finally(ready)
}))
return { get, reload }
}
async function load(client: OpenCodeClient, cwd: string): Promise<Catalog> {
const location = { directory: cwd }
// Some providers discover models in the background after plugin startup begins.
const deadline = Date.now() + 5_000
let missing = "No models are available"
while (Date.now() < deadline) {
const [modelResult, defaultResult, agentResult, commandResult] = await Promise.all([
client.model.list({ location }),
client.model.default({ location }),
client.agent.list({ location }),
client.command.list({ location }),
])
const models = modelResult.data.filter((model) => model.enabled)
const preferred = defaultResult.data
// Parallel reads can straddle initialization; select only from this model list.
const defaultModel = preferred
? models.find((model) => model.providerID === preferred.providerID && model.id === preferred.id)
: models[0]
const agents = agentResult.data.filter((agent) => agent.mode !== "subagent" && !agent.hidden)
const defaultAgent = agents.find((agent) => agent.mode === "primary") ?? agents[0]
if (defaultModel && defaultAgent) {
return {
providers: providers(models),
models,
defaultModel: {
providerID: defaultModel.providerID,
id: defaultModel.id,
variant: defaultModel.variants.find((variant) => variant.id === "default")?.id,
},
modes: agents.map((agent) => ({ id: agent.id, name: agent.name, description: agent.description })),
defaultModeID: defaultAgent.id,
commands: commandResult.data,
}
}
missing = defaultModel ? "No primary agents are available" : "No models are available"
await Bun.sleep(25)
}
throw new Error(missing)
}
function providers(models: readonly ModelInfo[]): ConfigOptionProvider[] {
return Array.from(new Set(models.map((model) => model.providerID)))
.toSorted()
.map((providerID) => ({
id: providerID,
name: providerID,
models: models
.filter((model) => model.providerID === providerID)
.map((model) => ({ id: model.id, name: model.name, variants: model.variants.map((variant) => variant.id) })),
}))
}
export * as ACPCatalog from "./catalog"
+107 -138
View File
@@ -1,7 +1,7 @@
import { isDeepStrictEqual } from "node:util"
import {
isSessionNotFoundError,
type CommandInfo,
type ModelInfo,
type ModelRef,
type OpenCodeClient,
type SessionInfo,
@@ -40,12 +40,8 @@ import type {
} from "@agentclientprotocol/sdk"
import { OPENCODE_VERSION } from "../version"
import { SessionMessage } from "@opencode/schema/session-message"
import {
buildConfigOptions,
DEFAULT_VARIANT_VALUE,
parseModelSelection,
type ConfigOptionProvider,
} from "./config-option"
import { ACPCatalog, type Catalog } from "./catalog"
import { buildConfigOptions, DEFAULT_VARIANT_VALUE, parseModelSelection } from "./config-option"
import type { ACPConnection } from "./connection"
import { promptContentToParts } from "./content"
import {
@@ -61,22 +57,14 @@ import { ACPError } from "./error"
export const AuthMethodID = "opencode-login"
type Catalog = {
readonly providers: ConfigOptionProvider[]
readonly models: ModelInfo[]
readonly defaultModel: ModelRef
readonly modes: Array<{ id: string; name: string; description?: string }>
readonly defaultModeID: string
readonly commands: CommandInfo[]
}
// Model and mode are unset while the session follows the server defaults.
type Attached = {
readonly id: string
readonly cwd: string
readonly abort: AbortController
catalog: Catalog
model: ModelRef
modeID: string
readonly catalog: ACPCatalog.Live
model?: ModelRef
modeID?: string
}
type PreparedPrompt = {
@@ -109,21 +97,55 @@ export function make(input: {
readonly connection: ACPConnection.Connection
}): Interface {
const sessions = new Map<string, Attached>()
const catalogs = new Map<string, Promise<Catalog>>()
const registeredMcp = new Map<string, Set<string>>()
const active = new Map<string, { readonly control: TurnControl; readonly turn: Promise<PromptResponse> }>()
const capabilities = { writeTextFile: false, childSessionUpdates: false }
const catalog = (cwd: string) => {
const cached = catalogs.get(cwd)
if (cached) return cached
const loaded = loadCatalog(input.client, cwd).catch((error) => {
catalogs.delete(cwd)
throw error
const catalogs = ACPCatalog.make({
client: input.client,
signal: input.connection.signal,
changed: (live, previous) =>
Promise.all(
Array.from(sessions.values())
.filter((state) => state.catalog === live)
.map(async (state) => {
const options = configOptions(state)
if (!isDeepStrictEqual(options, configOptions(state, previous))) {
await input.connection.sessionUpdate({
sessionId: state.id,
update: { sessionUpdate: "config_option_update", configOptions: options },
})
}
if (!isDeepStrictEqual(live.current.commands, previous.commands)) await sendCommands(state)
}),
),
})
const sendCommands = (state: Attached) =>
input.connection.sessionUpdate({
sessionId: state.id,
update: {
sessionUpdate: "available_commands_update",
availableCommands: state.catalog.current.commands.map((command) => ({
name: command.name,
description: command.description ?? "",
})),
},
})
const withReload = <A>(state: Attached, select: () => Promise<A>) =>
select().catch(async (error: unknown) => {
if (
!(
error instanceof ACPError.InvalidModelError ||
error instanceof ACPError.InvalidModeError ||
error instanceof ACPError.InvalidEffortError
)
)
throw error
await catalogs.reload(state.catalog)
return select()
})
catalogs.set(cwd, loaded)
return loaded
}
const requireSession = async (sessionID: string) => {
const current = sessions.get(sessionID)
@@ -147,27 +169,19 @@ export function make(input: {
}
const attach = async (session: SessionInfo, cwd: string, mcpServers: readonly McpServer[]) => {
const currentCatalog = await catalog(cwd)
const catalog = await catalogs.get(cwd)
sessions.get(session.id)?.abort.abort()
const state: Attached = {
id: session.id,
cwd,
abort: new AbortController(),
catalog: currentCatalog,
model: session.model ?? currentCatalog.defaultModel,
modeID: session.agent ?? currentCatalog.defaultModeID,
catalog,
model: session.model,
modeID: session.agent,
}
sessions.set(session.id, state)
await registerMcpServers(input.client, registeredMcp, state, mcpServers)
await input.connection.sessionUpdate({
sessionId: state.id,
update: {
sessionUpdate: "available_commands_update",
availableCommands: [
...state.catalog.commands.map((command) => ({ name: command.name, description: command.description ?? "" })),
],
},
})
await sendCommands(state)
return state
}
@@ -175,14 +189,16 @@ export function make(input: {
await replayMessages(input.connection, state.id, state.cwd, await messages(input.client, state.id))
}
const configOptions = (state: Attached) =>
buildConfigOptions({
providers: state.catalog.providers,
currentModel: { providerID: state.model.providerID, modelID: state.model.id },
currentVariant: state.model.variant,
modes: state.catalog.modes,
currentModeId: state.modeID,
const configOptions = (state: Attached, catalog = state.catalog.current) => {
const model = currentModel(state, catalog)
return buildConfigOptions({
providers: catalog.providers,
currentModel: { providerID: model.providerID, modelID: model.id },
currentVariant: model.variant,
modes: catalog.modes,
currentModeId: state.modeID ?? catalog.defaultModeID,
})
}
return {
initialize: async (params) => {
@@ -216,12 +232,10 @@ export function make(input: {
return {}
},
newSession: async (params) => {
const currentCatalog = await catalog(params.cwd)
const created = await input.client.session.create({
location: { directory: params.cwd },
agent: currentCatalog.defaultModeID,
model: currentCatalog.defaultModel,
})
// Load before creating so a catalog failure leaves no session behind. Agent and model stay unset
// so the server resolves its defaults after plugins activate.
await catalogs.get(params.cwd)
const created = await input.client.session.create({ location: { directory: params.cwd } })
const state = await attach(created, params.cwd, params.mcpServers)
return { sessionId: state.id, configOptions: configOptions(state) }
},
@@ -279,37 +293,38 @@ export function make(input: {
},
setSessionConfigOption: async (params) => {
const state = await requireSession(params.sessionId)
if (typeof params.value !== "string") throw new ACPError.InvalidConfigOptionError({ configId: params.configId })
switch (params.configId) {
case "model": {
const selected = requireModel(state.catalog, params.value, state.model)
state.model = selected
await input.client.session.switchModel({ sessionID: state.id, model: selected })
break
const value = params.value
if (typeof value !== "string") throw new ACPError.InvalidConfigOptionError({ configId: params.configId })
await withReload(state, async () => {
switch (params.configId) {
case "model": {
const selected = requireModel(state.catalog.current, value, currentModel(state))
state.model = selected
await input.client.session.switchModel({ sessionID: state.id, model: selected })
return
}
case "effort": {
const current = currentModel(state)
const model = state.catalog.current.models.find(
(item) => item.providerID === current.providerID && item.id === current.id,
)
if (!model || (value !== DEFAULT_VARIANT_VALUE && !model.variants.some((variant) => variant.id === value)))
throw new ACPError.InvalidEffortError({ effort: value })
state.model = { ...current, variant: value }
await input.client.session.switchModel({ sessionID: state.id, model: state.model })
return
}
case "mode":
return selectMode(input.client, state, value)
default:
throw new ACPError.InvalidConfigOptionError({ configId: params.configId })
}
case "effort": {
const model = state.catalog.models.find(
(item) => item.providerID === state.model.providerID && item.id === state.model.id,
)
if (
!model ||
(params.value !== DEFAULT_VARIANT_VALUE && !model.variants.some((variant) => variant.id === params.value))
)
throw new ACPError.InvalidEffortError({ effort: params.value })
state.model = { ...state.model, variant: params.value }
await input.client.session.switchModel({ sessionID: state.id, model: state.model })
break
}
case "mode":
await selectMode(input.client, state, params.value)
break
default:
throw new ACPError.InvalidConfigOptionError({ configId: params.configId })
}
})
return { configOptions: configOptions(state) }
},
setSessionMode: async (params) => {
await selectMode(input.client, await requireSession(params.sessionId), params.modeId)
const state = await requireSession(params.sessionId)
await withReload(state, () => selectMode(input.client, state, params.modeId))
return {}
},
prompt: async (params, signal) => {
@@ -321,7 +336,7 @@ export function make(input: {
})
}
const messageID = SessionMessage.ID.create()
const prepared = preparePrompt(state.catalog, params.prompt, messageID)
const prepared = preparePrompt(state.catalog.current, params.prompt, messageID)
const control: TurnControl = { cancelled: false, admission: new AbortController() }
const extNotification = input.connection.extNotification
const childSessionUpdate =
@@ -410,58 +425,6 @@ function turnStart(messageID: string, slash: PreparedPrompt["slash"]): TurnStart
return { type: "input", id: messageID }
}
async function loadCatalog(client: OpenCodeClient, cwd: string): Promise<Catalog> {
const location = { directory: cwd }
// Some providers discover models in the background after plugin startup begins.
const deadline = Date.now() + 5_000
let missing = "No models are available"
while (Date.now() < deadline) {
const [modelResult, defaultResult, agentResult, commandResult] = await Promise.all([
client.model.list({ location }),
client.model.default({ location }),
client.agent.list({ location }),
client.command.list({ location }),
])
const models = modelResult.data.filter((model) => model.enabled)
const preferred = defaultResult.data
// Parallel reads can straddle initialization; select only from this model list.
const defaultModel = preferred
? models.find((model) => model.providerID === preferred.providerID && model.id === preferred.id)
: models[0]
const agents = agentResult.data.filter((agent) => agent.mode !== "subagent" && !agent.hidden)
const defaultAgent = agents.find((agent) => agent.mode === "primary") ?? agents[0]
if (defaultModel && defaultAgent) {
return {
providers: providers(models),
models,
defaultModel: {
providerID: defaultModel.providerID,
id: defaultModel.id,
variant: defaultModel.variants.find((variant) => variant.id === "default")?.id,
},
modes: agents.map((agent) => ({ id: agent.id, name: agent.name, description: agent.description })),
defaultModeID: defaultAgent.id,
commands: commandResult.data,
}
}
missing = defaultModel ? "No primary agents are available" : "No models are available"
await Bun.sleep(25)
}
throw new Error(missing)
}
function providers(models: readonly ModelInfo[]): ConfigOptionProvider[] {
return Array.from(new Set(models.map((model) => model.providerID)))
.toSorted()
.map((providerID) => ({
id: providerID,
name: providerID,
models: models
.filter((model) => model.providerID === providerID)
.map((model) => ({ id: model.id, name: model.name, variants: model.variants.map((variant) => variant.id) })),
}))
}
function requireModel(catalog: Catalog, modelID: string, current: ModelRef): ModelRef {
const selected = parseModelSelection(modelID, catalog.providers)
const model = catalog.models.find(
@@ -480,8 +443,13 @@ function requireModel(catalog: Catalog, modelID: string, current: ModelRef): Mod
return { providerID: model.providerID, id: model.id, variant }
}
function currentModel(state: Attached, catalog = state.catalog.current) {
return state.model ?? catalog.defaultModel
}
async function selectMode(client: OpenCodeClient, state: Attached, modeID: string) {
if (!state.catalog.modes.some((mode) => mode.id === modeID)) throw new ACPError.InvalidModeError({ mode: modeID })
if (!state.catalog.current.modes.some((mode) => mode.id === modeID))
throw new ACPError.InvalidModeError({ mode: modeID })
state.modeID = modeID
await client.session.switchAgent({ sessionID: state.id, agent: modeID })
}
@@ -567,8 +535,9 @@ async function sendUsageUpdate(
used?: number,
) {
if (!used) return
const model = session.catalog.models.find(
(item) => item.providerID === session.model.providerID && item.id === session.model.id,
const current = currentModel(session)
const model = session.catalog.current.models.find(
(item) => item.providerID === current.providerID && item.id === current.id,
)
if (!model?.limit.context) return
const info = await client.session.get({ sessionID: session.id })
+13 -2
View File
@@ -67,6 +67,9 @@ type FormRequest = Extract<V2Event, { type: "form.created" }>["data"]["form"]
// attached client must not cancel input that may belong to another session.
const GLOBAL_FORM_SESSION_ID = "global"
const QUESTION_CANCELLED_FEEDBACK =
"This non-interactive run cannot ask the user questions, so the question was cancelled. Continue without an answer; make reasonable assumptions and state them."
const PERMISSION_REJECTED_FEEDBACK =
"This non-interactive run cannot ask the user for permission, so the request was rejected. Continue without this action."
@@ -182,15 +185,23 @@ export async function runNonInteractivePrompt(input: Input) {
}
}
const cancelForm = async (request: Pick<FormRequest, "id" | "sessionID">) => {
const cancelForm = async (request: Pick<FormRequest, "id" | "sessionID" | "metadata">) => {
// Nobody can answer a question here. Outside V1 compatibility, cancel it with a message so the
// question tool fails as ordinary model-visible output and the model continues without an answer.
const continuing = request.metadata?.kind === "question" && input.compatibility !== "v1"
try {
await input.client.session.form.cancel(
{ sessionID: request.sessionID, formID: request.id },
{
sessionID: request.sessionID,
formID: request.id,
...(continuing ? { message: QUESTION_CANCELLED_FEEDBACK } : {}),
},
...formRequestOptions(request.sessionID === GLOBAL_FORM_SESSION_ID ? input.location : undefined),
)
} catch (error) {
if (!formAlreadySettled(error)) throw error
}
if (continuing) return
formCancelled = true
if (input.compatibility !== "v1") process.exitCode = 1
}
+138 -27
View File
@@ -1,6 +1,14 @@
import { describe, expect, test } from "bun:test"
import type { McpServer, SessionConfigOption } from "@agentclientprotocol/sdk"
import { makeACPFixture, makeSession, secondModel, testModel } from "./service-fixture"
import {
buildAgent,
makeACPFixture,
makeSession,
planAgent,
reviewCommand,
secondModel,
testModel,
} from "./service-fixture"
import { flattenSelectOptions, requireSelectOption } from "./subprocess"
describe("acp service directory behavior", () => {
@@ -27,12 +35,7 @@ describe("acp service directory behavior", () => {
expect(currentValue(first[0], "model")).toBe("test/test-model")
expect(currentValue(first[0], "mode")).toBe("build")
expect(
[
"/api/model",
"/api/model/default",
"/api/agent",
"/api/command",
].map((path) =>
["/api/model", "/api/model/default", "/api/agent", "/api/command"].map((path) =>
fixture.requests
.filter((request) => request.path === path)
.map((request) => request.query["location[directory]"]),
@@ -48,21 +51,9 @@ describe("acp service directory behavior", () => {
.filter((request) => request.method === "POST" && request.path === "/api/session")
.map((request) => request.body),
).toEqual([
{
agent: "build",
model: { providerID: "test", id: "test-model", variant: "default" },
location: { directory: "/workspace" },
},
{
agent: "build",
model: { providerID: "test", id: "test-model", variant: "default" },
location: { directory: "/workspace" },
},
{
agent: "build",
model: { providerID: "test", id: "test-model", variant: "default" },
location: { directory: "/other" },
},
{ location: { directory: "/workspace" } },
{ location: { directory: "/workspace" } },
{ location: { directory: "/other" } },
])
expect(
fixture.updates.map((item) =>
@@ -70,11 +61,116 @@ describe("acp service directory behavior", () => {
? item.update.availableCommands.map((command) => command.name)
: [],
),
).toEqual([
["review"],
["review"],
["review"],
])
).toEqual([["review"], ["review"], ["review"]])
})
test("follows server defaults and refreshes the catalog when location plugins finish activating", async () => {
const configured = { ...buildAgent, id: "copilot-build", name: "copilot-build" }
const catalog = { agents: [buildAgent, planAgent], commands: [reviewCommand] }
let created = 0
await using fixture = makeACPFixture({
fetch(request) {
const location = { directory: request.query["location[directory]"] ?? "/workspace" }
if (request.path === "/api/agent") return Response.json({ location, data: catalog.agents })
if (request.path === "/api/command") return Response.json({ location, data: catalog.commands })
if (request.method !== "POST" || request.path !== "/api/session") return undefined
created++
return Response.json({ data: { ...makeSession(`ses_${created}`), agent: undefined, model: undefined } })
},
})
const first = await fixture.service.newSession({ cwd: "/workspace", mcpServers: [] })
expect(currentValue(first, "mode")).toBe("build")
expect(currentValue(first, "model")).toBe("test/test-model")
const agentReads = () => fixture.requests.filter((request) => request.path === "/api/agent").length
const reads = agentReads()
fixture.send({ id: "evt_other", created: 1, type: "agent.updated", location: { directory: "/other" }, data: {} })
catalog.agents = [configured, buildAgent, planAgent]
catalog.commands = [reviewCommand, { name: "ship", description: "Ship it" }]
fixture.send({
id: "evt_agent",
created: 2,
type: "agent.updated",
location: { directory: "/workspace" },
data: {},
})
const update = await until(() =>
fixture.updates.find(
(item) => item.sessionId === first.sessionId && item.update.sessionUpdate === "config_option_update",
),
)
expect(update.update.sessionUpdate === "config_option_update" && modeOption(update.update.configOptions)).toEqual({
currentValue: "copilot-build",
options: ["copilot-build", "build", "plan"],
})
const commands = await until(() =>
fixture.updates.findLast(
(item) =>
item.sessionId === first.sessionId &&
item.update.sessionUpdate === "available_commands_update" &&
item.update.availableCommands.length === 2,
),
)
expect(
commands.update.sessionUpdate === "available_commands_update" &&
commands.update.availableCommands.map((command) => command.name),
).toEqual(["review", "ship"])
expect(agentReads()).toBe(reads + 1)
const second = await fixture.service.newSession({ cwd: "/workspace", mcpServers: [] })
expect(currentValue(second, "mode")).toBe("copilot-build")
expect(
fixture.requests
.filter((request) => request.method === "POST" && request.path === "/api/session")
.map((request) => request.body),
).toEqual([{ location: { directory: "/workspace" } }, { location: { directory: "/workspace" } }])
})
test("reloads the catalog before rejecting a model or mode it has not seen", async () => {
const configured = { ...planAgent, id: "copilot-build", name: "copilot-build" }
const catalog = { models: [testModel], agents: [buildAgent, planAgent] }
await using fixture = makeACPFixture({
defaultModel: testModel,
fetch(request) {
const location = { directory: request.query["location[directory]"] ?? "/workspace" }
if (request.path === "/api/model") return Response.json({ location, data: catalog.models })
if (request.path === "/api/agent") return Response.json({ location, data: catalog.agents })
if (request.method === "POST" && request.path === "/api/session") {
return Response.json({ data: makeSession("ses_reload") })
}
if (
request.method === "POST" &&
(request.path === "/api/session/ses_reload/model" || request.path === "/api/session/ses_reload/agent")
) {
return new Response(null, { status: 204 })
}
return undefined
},
})
const session = await fixture.service.newSession({ cwd: "/workspace", mcpServers: [] })
catalog.models = [testModel, secondModel]
catalog.agents = [buildAgent, planAgent, configured]
const model = await fixture.service.setSessionConfigOption({
sessionId: session.sessionId,
configId: "model",
value: "test/second-model",
})
await fixture.service.setSessionMode({ sessionId: session.sessionId, modeId: "copilot-build" })
const missing = await fixture.service
.setSessionConfigOption({ sessionId: session.sessionId, configId: "mode", value: "missing" })
.catch((error: unknown) => error)
expect(currentValue(model, "model")).toBe("test/second-model")
expect(
fixture.requests
.filter((request) => request.path === "/api/session/ses_reload/agent")
.map((request) => request.body),
).toEqual([{ agent: "copilot-build" }])
expect(missing).toMatchObject({ _tag: "ACPInvalidModeError" })
expect(fixture.requests.filter((request) => request.path === "/api/agent")).toHaveLength(3)
})
test.each(["empty", "missing the default"])(
@@ -300,6 +396,21 @@ describe("acp service directory behavior", () => {
})
})
function modeOption(options: SessionConfigOption[]) {
const mode = requireSelectOption(options, "mode")
return { currentValue: mode.currentValue, options: flattenSelectOptions(mode).map((option) => option.value) }
}
async function until<Value>(read: () => Value | undefined) {
const deadline = Date.now() + 2_000
while (Date.now() < deadline) {
const value = read()
if (value !== undefined) return value
await Bun.sleep(5)
}
throw new Error("timed out waiting for ACP update")
}
function currentValue(
result: { readonly configOptions?: readonly SessionConfigOption[] | null } | undefined,
id: string,
+1
View File
@@ -184,6 +184,7 @@ export function makeACPFixture(options: FixtureOptions = {}) {
service,
requests,
updates,
send: context.send,
async [Symbol.asyncDispose]() {
eventController?.close()
await server.stop(true)
@@ -26,11 +26,7 @@ describe("acp service lifecycle", () => {
method: "POST",
path: "/api/session",
query: {},
body: {
location: { directory: "/workspace" },
agent: "build",
model: { providerID: "test", id: "second-model" },
},
body: { location: { directory: "/workspace" } },
})
expect(currentValue(created, "effort")).toBe("default")
})
+5 -1
View File
@@ -1414,7 +1414,11 @@ export type SessionFormReplyOperation<E = never> = (
input: SessionFormReplyInput,
) => Effect.Effect<SessionFormReplyOutput, E>
export type SessionFormCancelInput = { readonly sessionID: string; readonly formID: Form.ID }
export type SessionFormCancelInput = {
readonly sessionID: string
readonly formID: Form.ID
readonly message?: string | undefined
}
export type SessionFormCancelOutput = void
export type SessionFormCancelOperation<E = never> = (
input: SessionFormCancelInput,
@@ -735,9 +735,10 @@ const EndpointSessionFormReply = (raw: RawClient["server.session"]) => (input: S
const EndpointSessionFormCancel = (raw: RawClient["server.session"]) => (input: SessionFormCancelInput) =>
preserveEffect<SessionFormCancelOutput>()(
raw["session.form.cancel"]({ params: { sessionID: input["sessionID"], formID: input["formID"] } }).pipe(
Effect.mapError(mapClientError),
),
raw["session.form.cancel"]({
params: { sessionID: input["sessionID"], formID: input["formID"] },
query: { message: input["message"] },
}).pipe(Effect.mapError(mapClientError)),
)
const EndpointSessionEnvironment = (raw: RawClient["server.session"]) => (input: SessionEnvironmentInput) =>
@@ -1058,6 +1058,7 @@ export function make(options: ClientOptions) {
{
method: "DELETE",
path: `/api/session/${encodeURIComponent(input.sessionID)}/form/${encodeURIComponent(input.formID)}`,
query: { message: input["message"] },
successStatus: 204,
declaredStatuses: [400, 401, 404, 409],
empty: true,
@@ -1897,7 +1897,10 @@ export type FormField =
| FormMultiselectField
| FormExternalField
export type FormState = { status: "pending" } | { status: "answered"; answer: FormAnswer } | { status: "cancelled" }
export type FormState =
| { status: "pending" }
| { status: "answered"; answer: FormAnswer }
| { status: "cancelled"; message?: string }
export type CredentialKey = {
type: "key"
@@ -5460,6 +5463,7 @@ export type SessionFormReplyOutput = void
export type SessionFormCancelInput = {
readonly sessionID: { readonly sessionID: string; readonly formID: string }["sessionID"]
readonly formID: { readonly sessionID: string; readonly formID: string }["formID"]
readonly message?: { readonly message?: string | undefined }["message"]
}
export type SessionFormCancelOutput = void
+10 -3
View File
@@ -74,6 +74,10 @@ export interface ReplyInput {
readonly answer: Answer
}
export interface CancelOptions {
readonly message?: string
}
export interface ListInput {
readonly sessionID?: Form.Info["sessionID"]
}
@@ -86,7 +90,7 @@ export interface Interface {
readonly list: (input?: ListInput) => Effect.Effect<ReadonlyArray<Info>>
readonly state: (id: ID) => Effect.Effect<State, NotFoundError>
readonly reply: (input: ReplyInput) => Effect.Effect<void, AlreadySettledError | InvalidAnswerError | NotFoundError>
readonly cancel: (id: ID) => Effect.Effect<void, AlreadySettledError | NotFoundError>
readonly cancel: (id: ID, options?: CancelOptions) => Effect.Effect<void, AlreadySettledError | NotFoundError>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Form") {}
@@ -192,12 +196,15 @@ export const layer = Layer.effect(
),
)
const cancel = Effect.fn("Form.cancel")((id: ID) =>
const cancel = Effect.fn("Form.cancel")((id: ID, options?: CancelOptions) =>
Effect.uninterruptible(
Effect.gen(function* () {
const entry = yield* requireEntry(id)
if (entry.state.status !== "pending") return yield* new AlreadySettledError({ id })
const next: TerminalState = { status: "cancelled" }
const next: TerminalState = {
status: "cancelled",
...(options?.message === undefined ? {} : { message: options.message }),
}
yield* bus.publish(Form.Event.Cancelled, { id, sessionID: entry.form.sessionID })
yield* Cache.set(forms, id, { ...entry, state: next })
yield* Deferred.succeed(entry.deferred, next)
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -213,7 +213,6 @@ export type InternalPlugin = Plugin<Requirements | Scope.Scope>
const pre = [
ToolInputRepairPlugin.Plugin,
ConfigWorktreePlugin.Plugin,
BrowserPlugin,
ConfigMcpPlugin.Plugin,
McpCodeModeDefaultsPlugin.Plugin,
WellKnownPlugin.Plugin,
@@ -251,6 +250,7 @@ const post = [
ConfigInstructionPlugin.Plugin,
ConfigReferencePlugin.Plugin,
ConfigAgentPlugin.Plugin,
BrowserPlugin,
ConfigCommandPlugin.Plugin,
ConfigCompactionPlugin.Plugin,
ConfigFormatterPlugin.Plugin,
@@ -90,6 +90,10 @@ export const Plugin = {
// Deliberate defect tunnel (see Permission.assert): a dismissal must dodge
// leaf `mapError` blankets so it never becomes model-facing tool output; it
// resurfaces as a typed failure at SessionModelRequest.executeTool.
// A dismissal with a message (e.g. from a non-interactive client) is ordinary
// model-facing feedback: the model continues instead of the step ending.
if (state.status === "cancelled" && state.message !== undefined)
return Effect.fail(new ToolFailure({ message: state.message }))
if (state.status === "cancelled") return Effect.die(new CancelledError())
const output = {
answers: input.questions.map((_, index): Question.Answer => {
+31 -1
View File
@@ -19,9 +19,38 @@ type Attachment = {
export type Connection = Effect.Success<ReturnType<typeof make>>
export const make = Effect.fn("BrowserConnection.make")(function* (
ctx: Pick<Context, "rpc" | "session" | "location" | "event">,
ctx: Pick<Context, "agent" | "rpc" | "session" | "location" | "event">,
) {
const browsers = new Map<Session.ID, Attachment>()
// Appended after config, so every agent hides the browser until an attachment allows it.
yield* ctx.agent.transform((editor) =>
editor.list().forEach((agent) => agent.permissions.push({ action: "browser", resource: "*", effect: "deny" })),
)
// Each attachment adds and removes its own allow, so a replaced attachment keeps the new one's.
const grant = (sessionID: Session.ID) =>
Effect.acquireRelease(
ctx.session.get({ sessionID }).pipe(
Effect.flatMap((session) =>
ctx.session.update({
sessionID,
permissions: [...(session.permissions ?? []), { action: "browser", resource: "*", effect: "allow" }],
}),
),
Effect.orDie,
),
() =>
ctx.session.get({ sessionID }).pipe(
Effect.flatMap((session) => {
const permissions = session.permissions ?? []
const index = permissions.findIndex(
(rule) => rule.action === "browser" && rule.resource === "*" && rule.effect === "allow",
)
if (index === -1) return Effect.void
return ctx.session.update({ sessionID, permissions: permissions.toSpliced(index, 1) })
}),
Effect.ignore,
),
)
let active = true
const close = (sessionID: Session.ID, reason: "closed" | "replaced" = "closed") =>
Effect.gen(function* () {
@@ -69,6 +98,7 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
}),
(browser) => (browsers.get(input.sessionID) === browser ? close(input.sessionID) : Effect.void),
)
yield* grant(input.sessionID)
yield* rpc.events
.emit("control", { type: "attached", connectionID: input.connectionID, version: 4 })
.pipe(Effect.orDie)
+2 -2
View File
@@ -39,8 +39,8 @@
},
"peerDependencies": {
"@opencode/theme": "workspace:*",
"@opentui/core": ">=0.5.13",
"@opentui/solid": ">=0.5.13",
"@opentui/core": ">=0.5.14",
"@opentui/solid": ">=0.5.14",
"solid-js": ">=1.9.0"
},
"peerDependenciesMeta": {
+19 -1
View File
@@ -4566,7 +4566,7 @@
}
}
},
"description": "Cancel a pending form.",
"description": "Cancel a pending form, optionally telling the asker why it was not answered.",
"summary": "Cancel form"
}
},
@@ -4591,6 +4591,21 @@
"pattern": "^frm_"
},
"required": true
},
{
"name": "message",
"in": "query",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
},
"required": false
}
],
"security": [],
@@ -14170,6 +14185,9 @@
"status": {
"type": "string",
"enum": ["cancelled"]
},
"message": {
"type": "string"
}
},
"required": ["status"],
+2 -1
View File
@@ -855,6 +855,7 @@ export const makeSessionGroup = <
.add(
HttpApiEndpoint.delete("session.form.cancel", "/api/session/:sessionID/form/:formID", {
params: { sessionID: Schema.String, formID: Form.ID },
query: Schema.Struct({ message: Schema.optional(Schema.String) }),
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, FormAlreadySettledError, FormNotFoundError],
})
@@ -863,7 +864,7 @@ export const makeSessionGroup = <
OpenApi.annotations({
identifier: "session.form.cancel",
summary: "Cancel form",
description: "Cancel a pending form.",
description: "Cancel a pending form, optionally telling the asker why it was not answered.",
}),
),
)
+2 -1
View File
@@ -149,7 +149,8 @@ export type Answer = typeof Answer.Type
export const State = Schema.Union([
Schema.Struct({ status: Schema.Literal("pending") }),
Schema.Struct({ status: Schema.Literal("answered"), answer: Answer }),
Schema.Struct({ status: Schema.Literal("cancelled") }),
// A message tells the asker why nobody answered, e.g. a non-interactive client.
Schema.Struct({ status: Schema.Literal("cancelled"), message: Schema.String.pipe(optional) }),
])
.pipe(Schema.toTaggedUnion("status"))
.annotate({ identifier: "Form.State" })
+1 -1
View File
@@ -692,7 +692,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
"session.form.cancel",
Effect.fn(function* (ctx) {
const owned = yield* requireOwnedForm(ctx.params.sessionID, ctx.params.formID)
yield* owned.form.cancel(ctx.params.formID).pipe(
yield* owned.form.cancel(ctx.params.formID, { message: ctx.query.message }).pipe(
Effect.catchTags({
"Form.AlreadySettledError": (error) =>
new FormAlreadySettledError({ id: error.id, message: error.message }),
@@ -260,9 +260,7 @@ function InstructionsGroup(props: GroupProps) {
Instructions: {files()} {files() === 1 ? "file" : "files"}
</InlineToolRow>
<Show when={disclosure.expanded()}>
<box flexDirection="column" gap={1} marginTop={1}>
<Children {...props} nodes={props.node.children} mode="normal" />
</box>
<Children {...props} nodes={props.node.children} mode="normal" />
</Show>
</GroupAnchor>
)
@@ -153,6 +153,55 @@ test("retains nested expansion state and registers exact headers and parts", asy
expect(anchors.list()).toEqual([])
})
test("expanded instructions stay adjacent to their summary and each other", async () => {
const anchors = createTimelineAnchors()
const [expanded, setExpanded] = createStore<Record<string, boolean>>({})
const messages: SessionMessageInfo[] = ["AGENTS.md", "packages/tui/AGENTS.md"].map((path) => ({
type: "synthetic",
id: path,
text: "Instructions",
description: `Loaded ${path}`,
metadata: { instruction: { paths: [path] } },
time: { created: 1 },
}))
const row: SessionGroup = {
type: "group",
kind: "instructions",
size: messages.length,
completed: true,
children: messages.map((message) => ({
type: "entry",
size: 1,
entry: { type: "message", messageID: message.id },
})),
}
const app = await mount({
row,
anchors,
config: createTuiResolvedConfig({ animations: false }),
expanded: (id) => expanded[id],
setExpanded: (id, value) => setExpanded(id, value),
message: (id) => messages.find((message) => message.id === id),
entry: (entry) => <text>{entry.type === "message" ? `Loaded ${entry.messageID}` : ""}</text>,
})
try {
app.renderer.start()
await app.waitForFrame((frame) => frame.includes("Instructions: 2 files"))
expect(app.captureCharFrame()).not.toContain("Loaded AGENTS.md")
await app.mockMouse.click(4, anchors.get({ type: "group", groupID: groupID(row, 0)! })?.node.y ?? -1)
await app.renderOnce()
expect(
app
.captureCharFrame()
.split("\n")
.map((line) => line.trim())
.join("\n"),
).toContain("◈ Instructions: 2 files\nLoaded AGENTS.md\nLoaded packages/tui/AGENTS.md")
} finally {
app.renderer.destroy()
}
})
test("a low activity group with nothing finished stays collapsed behind a status", async () => {
const config = createTuiResolvedConfig({ animations: false })
const shell = (id: string) => ({
+19 -1
View File
@@ -4566,7 +4566,7 @@
}
}
},
"description": "Cancel a pending form.",
"description": "Cancel a pending form, optionally telling the asker why it was not answered.",
"summary": "Cancel form"
}
},
@@ -4591,6 +4591,21 @@
"pattern": "^frm_"
},
"required": true
},
{
"name": "message",
"in": "query",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
},
"required": false
}
],
"security": [],
@@ -14170,6 +14185,9 @@
"status": {
"type": "string",
"enum": ["cancelled"]
},
"message": {
"type": "string"
}
},
"required": ["status"],
+19 -1
View File
@@ -4566,7 +4566,7 @@
}
}
},
"description": "Cancel a pending form.",
"description": "Cancel a pending form, optionally telling the asker why it was not answered.",
"summary": "Cancel form"
}
},
@@ -4591,6 +4591,21 @@
"pattern": "^frm_"
},
"required": true
},
{
"name": "message",
"in": "query",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
},
"required": false
}
],
"security": [],
@@ -14170,6 +14185,9 @@
"status": {
"type": "string",
"enum": ["cancelled"]
},
"message": {
"type": "string"
}
},
"required": ["status"],