Compare commits

..

2 Commits

Author SHA1 Message Date
Kit Langton 7cc63f99d8 refactor(tui): drop legacy slot names, migrate builtins to region claims 2026-08-08 20:22:05 -04:00
Kit Langton 8239ae886f feat(tui): region structure for plugin slot placement 2026-08-08 20:21:41 -04:00
33 changed files with 614 additions and 873 deletions
+1 -1
View File
@@ -86,7 +86,7 @@ export interface ProviderFailure {
// Keep HTTP failures and provider-reported stream failures on one typed path so
// session retry policy never needs provider-specific string matching.
export function classifyProviderFailure(input: ProviderFailure) {
export function classifyProviderFailure(input: ProviderFailure): AIError["reason"] {
const body = input.http?.body ?? ""
const codes = [input.code, ...providerCodes(body), ...providerCodes(input.message)]
.filter((code): code is string => code !== undefined)
+5 -39
View File
@@ -185,15 +185,15 @@ const secretValues = (request: HttpClientRequest.HttpClientRequest) => {
// Two passes: structural (redact `"name": "value"` and `name=value` patterns
// for any field name that looks sensitive) plus literal (replace any actual
// secret values we sent in the request, in case the response echoes one back).
const redactBody = (body: string, secrets: ReadonlySet<string>) =>
Array.from(secrets).reduce(
const redactBody = (body: string, request: HttpClientRequest.HttpClientRequest) =>
Array.from(secretValues(request)).reduce(
(text, secret) => text.split(secret).join(REDACTED),
body.replace(REDACT_JSON_FIELD, `$1"${REDACTED}"`).replace(REDACT_QUERY_FIELD, `$1${REDACTED}`),
)
const responseBody = (body: string | void, secrets: ReadonlySet<string>) => {
const responseBody = (body: string | void, request: HttpClientRequest.HttpClientRequest) => {
if (body === undefined) return {}
const redacted = redactBody(body, secrets)
const redacted = redactBody(body, request)
if (redacted.length <= BODY_LIMIT) return { body: redacted }
return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true }
}
@@ -240,7 +240,7 @@ const statusError =
const headers = normalizedHeaders(response.headers)
const retryAfter = retryAfterMs(headers)
const rateLimit = rateLimitDetails(headers, retryAfter)
const details = responseBody(body, secretValues(request))
const details = responseBody(body, request)
return yield* new AIError({
module: "RequestExecutor",
method: "execute",
@@ -261,40 +261,6 @@ const statusError =
})
})
// Classifies an HTTP failure captured outside the executor (for example by the
// AI SDK's own fetch) onto the same reason types and redacted HttpContext that
// executor-driven requests produce. The originating request is not available on
// that path, so the method is assumed (language model calls are always POST),
// request headers are empty, and only structural body redaction applies.
export const classifyHttpFailure = (input: {
readonly message: string
readonly url: string
readonly status?: number | undefined
readonly responseHeaders?: Record<string, string> | undefined
readonly responseBody?: string | undefined
}) => {
const headers = normalizedHeaders(Headers.fromInput(input.responseHeaders))
const retryAfter = retryAfterMs(headers)
const rateLimit = rateLimitDetails(headers, retryAfter)
const details = responseBody(input.responseBody ?? undefined, new Set<string>())
return classifyProviderFailure({
message: input.message,
status: input.status,
retryAfterMs: retryAfter,
rateLimit,
http: new HttpContext({
request: new HttpRequestDetails({ method: "POST", url: redactUrl(input.url), headers: {} }),
response:
input.status === undefined
? undefined
: new HttpResponseDetails({ status: input.status, headers: redactHeaders(Headers.fromInput(headers), []) }),
...details,
requestId: requestId(headers),
rateLimit,
}),
})
}
const toHttpError = (redactedNames: ReadonlyArray<string | RegExp>) => (error: unknown) => {
const transportError = (input: {
readonly message: string
+5 -140
View File
@@ -474,34 +474,7 @@ export type Endpoint5_31Output =
readonly location?: Location.Ref | undefined
readonly data: {
readonly sessionID: Session.ID
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly http?:
| {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?:
| { readonly status: number; readonly headers: { readonly [x: string]: string } }
| undefined
readonly body?: string | undefined
readonly bodyTruncated?: boolean | undefined
readonly requestId?: string | undefined
readonly rateLimit?:
| {
readonly retryAfterMs?: number | undefined
readonly limit?: { readonly [x: string]: string } | undefined
readonly remaining?: { readonly [x: string]: string } | undefined
readonly reset?: { readonly [x: string]: string } | undefined
}
| undefined
}
| undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
}
}
| {
@@ -628,34 +601,7 @@ export type Endpoint5_31Output =
readonly data: {
readonly sessionID: Session.ID
readonly assistantMessageID: SessionMessage.ID
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly http?:
| {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?:
| { readonly status: number; readonly headers: { readonly [x: string]: string } }
| undefined
readonly body?: string | undefined
readonly bodyTruncated?: boolean | undefined
readonly requestId?: string | undefined
readonly rateLimit?:
| {
readonly retryAfterMs?: number | undefined
readonly limit?: { readonly [x: string]: string } | undefined
readonly remaining?: { readonly [x: string]: string } | undefined
readonly reset?: { readonly [x: string]: string } | undefined
}
| undefined
}
| undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
readonly cost?: (number & Brand.Brand<"Money.USD">) | undefined
readonly tokens?:
| {
@@ -817,34 +763,7 @@ export type Endpoint5_31Output =
readonly sessionID: Session.ID
readonly assistantMessageID: SessionMessage.ID
readonly id: string
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly http?:
| {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?:
| { readonly status: number; readonly headers: { readonly [x: string]: string } }
| undefined
readonly body?: string | undefined
readonly bodyTruncated?: boolean | undefined
readonly requestId?: string | undefined
readonly rateLimit?:
| {
readonly retryAfterMs?: number | undefined
readonly limit?: { readonly [x: string]: string } | undefined
readonly remaining?: { readonly [x: string]: string } | undefined
readonly reset?: { readonly [x: string]: string } | undefined
}
| undefined
}
| undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
readonly content?:
| readonly [
(
@@ -884,34 +803,7 @@ export type Endpoint5_31Output =
readonly assistantMessageID: SessionMessage.ID
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly http?:
| {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?:
| { readonly status: number; readonly headers: { readonly [x: string]: string } }
| undefined
readonly body?: string | undefined
readonly bodyTruncated?: boolean | undefined
readonly requestId?: string | undefined
readonly rateLimit?:
| {
readonly retryAfterMs?: number | undefined
readonly limit?: { readonly [x: string]: string } | undefined
readonly remaining?: { readonly [x: string]: string } | undefined
readonly reset?: { readonly [x: string]: string } | undefined
}
| undefined
}
| undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
}
}
| {
@@ -961,34 +853,7 @@ export type Endpoint5_31Output =
readonly data: {
readonly sessionID: Session.ID
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly http?:
| {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?:
| { readonly status: number; readonly headers: { readonly [x: string]: string } }
| undefined
readonly body?: string | undefined
readonly bodyTruncated?: boolean | undefined
readonly requestId?: string | undefined
readonly rateLimit?:
| {
readonly retryAfterMs?: number | undefined
readonly limit?: { readonly [x: string]: string } | undefined
readonly remaining?: { readonly [x: string]: string } | undefined
readonly reset?: { readonly [x: string]: string } | undefined
}
| undefined
}
| undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
readonly inputID?: SessionMessage.ID | undefined
}
}
+13 -291
View File
@@ -102,24 +102,7 @@ export type ToolTextContent = { type: "text"; text: string }
export type ToolFileContent = { type: "file"; uri: string; mime: string; name?: string | null }
export type SessionStructuredError = {
type: string
message: string
status?: number
http?: {
request: { method: string; url: string; headers: { [x: string]: string } }
response?: { status: number; headers: { [x: string]: string } }
body?: string
bodyTruncated?: boolean
requestId?: string
rateLimit?: {
retryAfterMs?: number
limit?: { [x: string]: string }
remaining?: { [x: string]: string }
reset?: { [x: string]: string }
}
}
}
export type SessionStructuredError = { type: string; message: string; status?: number }
export type SessionMessageCompactionRunning = {
type: "compaction"
@@ -2706,31 +2689,7 @@ export type SessionImportInput = {
| {
readonly status: "error"
readonly input: { readonly [x: string]: JsonValue }
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: {
readonly status: number
readonly headers: { readonly [x: string]: string }
}
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly content?: readonly [
(
| { readonly type: "text"; readonly text: string }
@@ -2765,53 +2724,11 @@ export type SessionImportInput = {
readonly reasoning: number
readonly cache: { readonly read: number; readonly write: number }
}
readonly error?: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
readonly retry?: {
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
}
| (
@@ -2842,28 +2759,7 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly status: "failed"
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
)
>
@@ -3044,31 +2940,7 @@ export type SessionImportInput = {
| {
readonly status: "error"
readonly input: { readonly [x: string]: JsonValue }
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: {
readonly status: number
readonly headers: { readonly [x: string]: string }
}
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly content?: readonly [
(
| { readonly type: "text"; readonly text: string }
@@ -3103,53 +2975,11 @@ export type SessionImportInput = {
readonly reasoning: number
readonly cache: { readonly read: number; readonly write: number }
}
readonly error?: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
readonly retry?: {
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
}
| (
@@ -3180,28 +3010,7 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly status: "failed"
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
)
>
@@ -3382,31 +3191,7 @@ export type SessionImportInput = {
| {
readonly status: "error"
readonly input: { readonly [x: string]: JsonValue }
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: {
readonly status: number
readonly headers: { readonly [x: string]: string }
}
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly content?: readonly [
(
| { readonly type: "text"; readonly text: string }
@@ -3441,53 +3226,11 @@ export type SessionImportInput = {
readonly reasoning: number
readonly cache: { readonly read: number; readonly write: number }
}
readonly error?: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
readonly retry?: {
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
}
| (
@@ -3518,28 +3261,7 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly status: "failed"
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly http?: {
readonly request: {
readonly method: string
readonly url: string
readonly headers: { readonly [x: string]: string }
}
readonly response?: { readonly status: number; readonly headers: { readonly [x: string]: string } }
readonly body?: string
readonly bodyTruncated?: boolean
readonly requestId?: string
readonly rateLimit?: {
readonly retryAfterMs?: number
readonly limit?: { readonly [x: string]: string }
readonly remaining?: { readonly [x: string]: string }
readonly reset?: { readonly [x: string]: string }
}
}
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
)
>
+2 -52
View File
@@ -1,7 +1,6 @@
export * as AISDK from "./aisdk"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { APICallError } from "@ai-sdk/provider"
import type {
JSONSchema7,
JSONValue,
@@ -23,7 +22,6 @@ import {
LanguageModel,
ProviderID,
ProviderMetadata,
TransportReason,
ToolResultValue,
UnknownProviderReason,
type ContentPart,
@@ -31,7 +29,7 @@ import {
type ToolDefinition,
type UsageInput,
} from "@opencode-ai/ai"
import { Auth, Endpoint, RequestExecutor, type AnyRoute } from "@opencode-ai/ai/route"
import { Auth, Endpoint, type AnyRoute } from "@opencode-ai/ai/route"
import { ProviderShared } from "@opencode-ai/ai/protocols/shared"
import { Cause, Context, Effect, Layer, Option, Schema, Scope, Stream } from "effect"
import type { ID, Info } from "./model"
@@ -725,9 +723,7 @@ function llmError(method: string, error: unknown) {
const reason =
error instanceof AIError
? new InvalidProviderOutputReason({ message: error.message })
: APICallError.isInstance(error)
? apiCallErrorReason(error)
: new UnknownProviderReason({ message: unknownErrorMessage(error) })
: new UnknownProviderReason({ message: error instanceof Error ? error.message : String(error) })
return new AIError({
module: "AISDK",
method,
@@ -735,50 +731,4 @@ function llmError(method: string, error: unknown) {
})
}
function apiCallErrorReason(error: APICallError) {
const reason = RequestExecutor.classifyHttpFailure({
message: unknownErrorMessage(error),
url: error.url,
status: error.statusCode,
responseHeaders: error.responseHeaders,
responseBody: error.responseBody,
})
if (error.statusCode !== undefined || !error.isRetryable) return reason
return new TransportReason({
message: reason.message,
kind: error.name,
url: error.url,
http: reason.http,
})
}
const ProviderErrorBody = Schema.Struct({
message: Schema.optionalKey(Schema.String),
code: Schema.optionalKey(Schema.String),
error: Schema.optionalKey(
Schema.Struct({
message: Schema.optionalKey(Schema.String),
code: Schema.optionalKey(Schema.String),
}),
),
})
const decodeErrorData = Schema.decodeUnknownOption(ProviderErrorBody)
const decodeErrorBody = Schema.decodeUnknownOption(Schema.fromJsonString(ProviderErrorBody))
// AI SDK errors such as AI_APICallError can carry an empty message while still
// holding structured provider details. Derive a safe non-empty fallback from
// recognized error fields only; never surface the raw response payload.
function unknownErrorMessage(error: unknown) {
const message = error instanceof Error ? error.message : String(error)
if (message.trim() !== "") return message
if (!APICallError.isInstance(error)) return "Provider request failed"
const body =
Option.getOrUndefined(decodeErrorData(error.data)) ?? Option.getOrUndefined(decodeErrorBody(error.responseBody))
const detail = body?.error ?? body
if (detail?.message) return detail.message
const prefix =
error.statusCode === undefined ? "Provider request failed" : `Provider request failed with HTTP ${error.statusCode}`
return detail?.code ? `${prefix}: ${detail.code}` : prefix
}
export const node = makeLocationNode({ service: Service, layer: locationLayer, deps: [] })
@@ -60,12 +60,7 @@ export function toSessionError(cause: unknown): SessionError.Error {
}
function providerError(type: string, reason: AIError["reason"]): SessionError.Error {
const http = "http" in reason ? reason.http : undefined
const status = http?.response?.status ?? ("status" in reason ? reason.status : undefined)
return {
type,
message: reason.message,
...(status === undefined ? {} : { status }),
...(http === undefined ? {} : { http }),
}
const status =
("http" in reason ? reason.http?.response?.status : undefined) ?? ("status" in reason ? reason.status : undefined)
return { type, message: reason.message, ...(status === undefined ? {} : { status }) }
}
-131
View File
@@ -1,8 +1,5 @@
import { APICallError } from "@ai-sdk/provider"
import type { LanguageModelV3, LanguageModelV3StreamPart } from "@ai-sdk/provider"
import { AISDK } from "@opencode-ai/core/aisdk"
import { SessionRunnerRetry } from "@opencode-ai/core/session/runner/retry"
import { toSessionError } from "@opencode-ai/core/session/to-session-error"
import { Model } from "@opencode-ai/core/model"
import { Provider } from "@opencode-ai/core/provider"
import { LLM, AIError, LLMEvent, Message } from "@opencode-ai/ai"
@@ -340,131 +337,3 @@ it.effect("keeps malformed provider-executed AI SDK input terminal", () =>
expect(error.message).toContain("Invalid JSON input for aisdk tool call web_search")
}),
)
const failingModel = (failure: unknown): LanguageModelV3 => ({
specificationVersion: "v3",
provider: "test",
modelId: "test",
supportedUrls: {},
doGenerate: () => Promise.reject(new Error("Unexpected non-streaming request")),
doStream: () => Promise.reject(failure),
})
const streamFailure = (failure: unknown) =>
Effect.gen(function* () {
const aisdk = yield* AISDK.Service
yield* aisdk.hook.sdk((event) => {
event.sdk = { languageModel: () => failingModel(failure) }
})
const resolved = yield* aisdk.model(model("test-ai-sdk"))
return yield* LLMClient.generate(LLM.request({ model: resolved, prompt: "Hello" })).pipe(
Effect.provide(client),
Effect.flip,
)
})
it.effect("preserves non-empty AI SDK error messages", () =>
Effect.gen(function* () {
const error = yield* streamFailure(new Error("Bad Request"))
expect(error).toBeInstanceOf(AIError)
expect(error.reason).toMatchObject({ _tag: "UnknownProvider", message: "Bad Request" })
}),
)
const apiCallError = (input: Partial<ConstructorParameters<typeof APICallError>[0]>) =>
new APICallError({
message: "",
url: "https://api.example.com/chat",
requestBodyValues: { messages: [{ role: "user", content: "private prompt" }] },
responseHeaders: { authorization: "Bearer secret-token" },
...input,
})
it.effect("derives status and code when the AI SDK error message is empty", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
apiCallError({
statusCode: 404,
responseBody: '{"error":{"message":"","code":"not_found"}}',
data: { error: { message: "", code: "not_found" } },
}),
)
expect(error.reason.message).toBe("Provider request failed with HTTP 404: not_found")
expect(error.reason.message).not.toContain("secret-token")
expect(error.reason.message).not.toContain("private prompt")
const projected = toSessionError(error)
expect(projected.type).toBe("provider.invalid-request")
expect(projected.status).toBe(404)
expect(projected.message).not.toBe("")
expect(projected.http?.body).toBe('{"error":{"message":"","code":"not_found"}}')
}),
)
it.effect("persists redacted HTTP context from AI SDK call errors", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
apiCallError({
statusCode: 404,
responseBody: '{"error":{"message":"","code":"not_found"}}',
}),
)
expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
const http = toSessionError(error).http
expect(http?.request.url).toBe("https://api.example.com/chat")
expect(http?.response?.status).toBe(404)
expect(http?.response?.headers["authorization"]).toBe("<redacted>")
expect(http?.body).toBe('{"error":{"message":"","code":"not_found"}}')
}),
)
it.effect("classifies retryable AI SDK failures with retry-after details", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
apiCallError({
statusCode: 429,
responseHeaders: { "retry-after": "7" },
}),
)
expect(error.reason).toMatchObject({ _tag: "RateLimit", retryAfterMs: 7000 })
}),
)
it.effect("retries status-less AI SDK transport failures", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
apiCallError({
message: "Cannot connect to API: connection refused",
isRetryable: true,
}),
)
expect(error.reason).toMatchObject({ _tag: "Transport", kind: "AI_APICallError" })
expect(SessionRunnerRetry.isRetryable(error)).toBeTrue()
expect(toSessionError(error).http?.request.url).toBe("https://api.example.com/chat")
}),
)
it.effect("prefers a structured provider message over the code fallback", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
apiCallError({
statusCode: 404,
data: { error: { message: "The requested model does not exist", code: "not_found" } },
}),
)
expect(error.reason.message).toBe("The requested model does not exist")
}),
)
it.effect("falls back to the status alone for malformed response bodies", () =>
Effect.gen(function* () {
const error = yield* streamFailure(
apiCallError({
statusCode: 502,
isRetryable: false,
responseBody: "<html>Bad Gateway</html>",
}),
)
expect(error.reason).toMatchObject({ _tag: "ProviderInternal", status: 502 })
expect(error.reason.message).toBe("Provider request failed with HTTP 502")
}),
)
+1 -2
View File
@@ -74,7 +74,7 @@ describe("toSessionError", () => {
})
})
test("preserves provider HTTP context", () => {
test("preserves provider HTTP status", () => {
const http = new HttpContext({
request: new HttpRequestDetails({ method: "POST", url: "https://example.com", headers: {} }),
response: new HttpResponseDetails({ status: 413, headers: {} }),
@@ -83,7 +83,6 @@ describe("toSessionError", () => {
type: "provider.invalid-request",
message: "too large",
status: 413,
http,
})
expect(toSessionError(llm(new ProviderInternalReason({ message: "bad gateway", status: 502 })))).toEqual({
type: "provider.internal",
+1 -9
View File
@@ -1316,15 +1316,7 @@ export function write(
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
{ concurrency: 8, discard: true },
)
// Format the manifest with the same prettier settings as the repo-wide
// format pass, so `check:generated` stays clean after the generate bot
// reformats the tree.
const manifestJson = JSON.stringify(output.files.map((file) => file.path).sort())
const manifestContent = yield* Effect.tryPromise({
try: () => format(manifestJson, { filepath: manifest, parser: "json", printWidth: 120 }),
catch: (error) => new GenerationError({ reason: `Failed to format ${manifest}: ${String(error)}` }),
})
yield* fs.writeFileString(manifest, manifestContent)
yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n")
})
}
+1 -1
View File
@@ -16,7 +16,7 @@ describe("HttpApiCodegen.write", () => {
expect(writes).toEqual([
{ path: "/generated/session.ts", content: "export const session = {}\n" },
{ path: "/generated/.httpapi-codegen.json", content: '["session.ts"]\n' },
{ path: "/generated/.httpapi-codegen.json", content: '[\n "session.ts"\n]\n' },
])
}).pipe(
Effect.provideService(
+47 -16
View File
@@ -150,24 +150,54 @@ export interface Page {
readonly render: (input: { readonly data?: Record<string, any> }) => JSX.Element
}
export interface SlotMap {
readonly app: Readonly<Record<string, never>>
readonly "home.footer": Readonly<Record<string, never>>
readonly "prompt.footer.end": {
readonly sessionID?: string
readonly mode: "normal" | "shell"
/**
* The host UI's extensible regions. Each region publishes an input (reactive
* props passed to every claim render) and a part vocabulary: the stable ids
* of host furniture that placements may anchor to. Part ids are documented
* API — coarse, few, and kept stable across host refactors.
*/
export interface RegionMap {
readonly app: { readonly input: Readonly<Record<string, never>>; readonly part: never }
readonly "home.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
readonly "prompt.footer": {
readonly input: { readonly sessionID?: string; readonly mode: "normal" | "shell" }
readonly part: "status" | "file"
}
readonly "session.composer.top": {
readonly sessionID: string
}
readonly "sidebar.content": {
readonly sessionID: string
}
readonly "sidebar.footer": Readonly<Record<string, never>>
readonly "session.composer.top": { readonly input: { readonly sessionID: string }; readonly part: never }
readonly "sidebar.content": { readonly input: { readonly sessionID: string }; readonly part: never }
readonly "sidebar.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
}
export type RegionName = keyof RegionMap
export type SlotName = keyof SlotMap
export type Slot<Name extends SlotName = SlotName> = (props: SlotMap[Name]) => JSX.Element
/**
* Where a claim lands in a region's structure. Exactly one of:
* - `at`: the region's edge — `"end"` is the ceremony-free default position
* - `before` / `after`: adjacent to a host part, wherever the host keeps it
* - `replace`: take over one part — or the whole region by naming it.
* Replace is takeover: anything anchored inside the replaced subtree is
* suppressed and recorded, never silently dropped. At the same target the
* last-enabled claim wins; an ancestor takeover beats a descendant one
* regardless of order.
* A placement aimed at a part the host no longer publishes degrades to the
* region's end (after end-edge claims) rather than disappearing.
*
* The `?: never` fields make the variants mutually exclusive: a claim with
* two placement keys is a type error, not a silent priority pick.
*/
export type RegionPlacement<Name extends RegionName = RegionName> =
| { readonly at: "start" | "end"; readonly before?: never; readonly after?: never; readonly replace?: never }
| { readonly before: RegionMap[Name]["part"]; readonly at?: never; readonly after?: never; readonly replace?: never }
| { readonly after: RegionMap[Name]["part"]; readonly at?: never; readonly before?: never; readonly replace?: never }
| {
readonly replace: RegionMap[Name]["part"] | Name
readonly at?: never
readonly before?: never
readonly after?: never
}
export type RegionClaim<Name extends RegionName = RegionName> = RegionPlacement<Name> & {
readonly render: (input: RegionMap[Name]["input"]) => JSX.Element
}
export interface App {
readonly version: string
@@ -394,7 +424,8 @@ export interface UI {
/** Closes an open tab, or the active tab when omitted, and returns false when no tab matched. */
close(sessionID?: string): boolean
}
readonly slot: <Name extends SlotName>(name: Name, render: Slot<Name>) => () => void
/** Claims a place in a region's structure; see RegionPlacement. */
readonly slot: <Name extends RegionName>(region: Name, claim: RegionClaim<Name>) => () => void
}
export interface Context {
-24
View File
@@ -3,33 +3,9 @@ export * as SessionError from "./session-error.js"
import { Schema } from "effect"
import { optional } from "./schema.js"
const HttpRateLimitDetails = Schema.Struct({
retryAfterMs: Schema.Finite.pipe(optional),
limit: Schema.Record(Schema.String, Schema.String).pipe(optional),
remaining: Schema.Record(Schema.String, Schema.String).pipe(optional),
reset: Schema.Record(Schema.String, Schema.String).pipe(optional),
})
const HttpContext = Schema.Struct({
request: Schema.Struct({
method: Schema.String,
url: Schema.String,
headers: Schema.Record(Schema.String, Schema.String),
}),
response: Schema.Struct({
status: Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 599 })),
headers: Schema.Record(Schema.String, Schema.String),
}).pipe(optional),
body: Schema.String.pipe(optional),
bodyTruncated: Schema.Boolean.pipe(optional),
requestId: Schema.String.pipe(optional),
rateLimit: HttpRateLimitDetails.pipe(optional),
})
export interface Error extends Schema.Schema.Type<typeof Error> {}
export const Error = Schema.Struct({
type: Schema.String,
message: Schema.String,
status: Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 599 })).pipe(optional),
http: HttpContext.pipe(optional),
}).annotate({ identifier: "Session.StructuredError" })
@@ -12,18 +12,6 @@ describe("SessionError", () => {
const values: SessionError.Error[] = [
{ type: "provider.rate-limit", message: "Slow down" },
{ type: "provider.auth", message: "Authentication failed" },
{
type: "provider.internal",
message: "Unavailable",
status: 503,
http: {
request: { method: "POST", url: "https://api.example.com/chat", headers: {} },
response: { status: 503, headers: { "retry-after": "5" } },
body: '{"error":{"code":"unavailable"}}',
requestId: "request-1",
rateLimit: { retryAfterMs: 5_000 },
},
},
{ type: "provider.future-condition", message: "A future provider failure" },
{ type: "unknown", message: "Unexpected" },
]
+2 -2
View File
@@ -87,7 +87,7 @@ import { PromptRefProvider, usePromptRef } from "./context/prompt"
import { Config, ConfigProvider, useConfig } from "./config"
import { PluginProvider, usePlugin, type PackageResolver } from "./plugin/context"
import { tuiPluginDirectories } from "./plugin/discovery"
import { PluginRoute, PluginSlot } from "./plugin/render"
import { PluginRoute, Region } from "./plugin/render"
import { CommandPaletteDialog } from "./component/command-palette"
import { COMMAND_PALETTE_COMMAND, Keymap, type KeymapCommand } from "./context/keymap"
@@ -1225,7 +1225,7 @@ function App(props: { pair?: DialogPairCredentials }) {
</Match>
</Switch>
</box>
<PluginSlot name="app" input={{}} mode="all" />
<Region name="app" input={{}} />
</Show>
</box>
</box>
+87 -70
View File
@@ -53,7 +53,7 @@ import { useData } from "../../context/data"
import { useLocation } from "../../context/location"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { abbreviateHome } from "../../runtime"
import { PluginSlot } from "../../plugin/render"
import { Region } from "../../plugin/render"
import type { SessionPending } from "@opencode-ai/schema/session-pending"
export type PromptProps = {
@@ -1631,76 +1631,93 @@ export function Prompt(props: PromptProps) {
/>
</box>
<box width="100%" flexDirection="row" justifyContent="space-between" gap={2}>
<box flexGrow={1} flexShrink={1} minWidth={0}>
<Switch>
<Match when={status() === "running"}>
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
<box marginLeft={1}>
<Show when={config.animations ?? true} fallback={<text fg={theme.text.subdued}>[]</text>}>
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
</Show>
</box>
<text
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
wrapMode="none"
truncate
flexShrink={1}
>
esc{" "}
<span
style={{
fg: store.interrupt > 0 ? theme.background.action.primary.default : theme.text.subdued,
}}
>
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
</span>
</text>
</box>
</Match>
<Match when={move.progress()}>
{(progress) => (
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<Spinner color={theme.hue.accent[500]}>
{progress()}
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
</Spinner>
</box>
)}
</Match>
<Match when={move.pendingNew()}>
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
(new working copy)
</text>
</box>
</Match>
<Match when={true}>
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
{(location) => (
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
{location()}
</text>
)}
</Show>
</Match>
</Switch>
</box>
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
{(file) => (
<text
wrapMode="none"
truncate
flexShrink={1}
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
>
{file()}
</text>
)}
</Show>
<PluginSlot
name="prompt.footer.end"
<Region
name="prompt.footer"
input={{ sessionID: props.sessionID, mode: store.mode }}
mode="replace"
parts={[
{
id: "status",
render: () => (
<box flexGrow={1} flexShrink={1} minWidth={0}>
<Switch>
<Match when={status() === "running"}>
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
<box marginLeft={1}>
<Show
when={config.animations ?? true}
fallback={<text fg={theme.text.subdued}>[]</text>}
>
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
</Show>
</box>
<text
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
wrapMode="none"
truncate
flexShrink={1}
>
esc{" "}
<span
style={{
fg:
store.interrupt > 0
? theme.background.action.primary.default
: theme.text.subdued,
}}
>
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
</span>
</text>
</box>
</Match>
<Match when={move.progress()}>
{(progress) => (
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<Spinner color={theme.hue.accent[500]}>
{progress()}
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
</Spinner>
</box>
)}
</Match>
<Match when={move.pendingNew()}>
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
(new working copy)
</text>
</box>
</Match>
<Match when={true}>
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
{(location) => (
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
{location()}
</text>
)}
</Show>
</Match>
</Switch>
</box>
),
},
{
id: "file",
render: () => (
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
{(file) => (
<text
wrapMode="none"
truncate
flexShrink={1}
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
>
{file()}
</text>
)}
</Show>
),
},
]}
/>
</box>
</box>
@@ -62,6 +62,8 @@ function View(props: { context: Plugin.Context }) {
export default Plugin.define({
id: "opencode.home-footer",
setup(context) {
context.ui.slot("home.footer", () => <View context={context} />)
// Root takeover: an external plugin replacing home.footer wins (last-
// enabled) and this builtin shows as suppressed, not silently gone.
context.ui.slot("home.footer", { replace: "home.footer", render: () => <View context={context} /> })
},
})
@@ -85,8 +85,9 @@ export function PromptFooter(props: { context: Plugin.Context; sessionID?: strin
export default Plugin.define({
id: "opencode.prompt-footer",
setup(context) {
context.ui.slot("prompt.footer.end", (props) => (
<PromptFooter context={context} sessionID={props.sessionID} mode={props.mode} />
))
context.ui.slot("prompt.footer", {
at: "end",
render: (props) => <PromptFooter context={context} sessionID={props.sessionID} mode={props.mode} />,
})
},
})
@@ -44,6 +44,9 @@ export function SidebarContext(props: { context: Plugin.Context; sessionID: stri
export default Plugin.define({
id: "internal:sidebar-context",
setup(context) {
context.ui.slot("sidebar.content", (props) => <SidebarContext context={context} sessionID={props.sessionID} />)
context.ui.slot("sidebar.content", {
at: "end",
render: (props) => <SidebarContext context={context} sessionID={props.sessionID} />,
})
},
})
@@ -19,6 +19,6 @@ function View(props: { context: Plugin.Context }) {
export default Plugin.define({
id: "opencode.sidebar-footer",
setup(context) {
context.ui.slot("sidebar.footer", () => <View context={context} />)
context.ui.slot("sidebar.footer", { replace: "sidebar.footer", render: () => <View context={context} /> })
},
})
@@ -73,6 +73,9 @@ function View(props: { context: Plugin.Context; sessionID: string }) {
export default Plugin.define({
id: "internal:sidebar-mcp",
setup(context) {
context.ui.slot("sidebar.content", (props) => <View context={context} sessionID={props.sessionID} />)
context.ui.slot("sidebar.content", {
at: "end",
render: (props) => <View context={context} sessionID={props.sessionID} />,
})
},
})
@@ -1090,6 +1090,6 @@ export default Plugin.define({
name: ROUTE,
render: () => <DiffViewer context={context} />,
})
context.ui.slot("app", () => <Commands context={context} />)
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
},
})
@@ -85,6 +85,6 @@ function Commands(props: { context: Plugin.Context }) {
export default Plugin.define({
id,
setup(context) {
context.ui.slot("app", () => <Commands context={context} />)
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
},
})
@@ -137,6 +137,6 @@ export default Plugin.define({
return <StorybookIndex context={context} />
},
})
context.ui.slot("app", () => <Commands context={context} />)
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
},
})
+47 -8
View File
@@ -1,6 +1,26 @@
import { PluginContextProvider } from "@opencode-ai/plugin/tui"
import type { JSX } from "solid-js"
import type { Context, Dialog, Page, Slot, SlotMap, Toast } from "@opencode-ai/plugin/tui/context"
import type {
Context,
Dialog,
Page,
RegionClaim,
RegionMap,
RegionName,
Toast,
} from "@opencode-ai/plugin/tui/context"
import type { Placement } from "./structure"
// Region inputs erased to their union: the registry stores one render shape
// regardless of which region a claim targets.
export type RegionRender = (input: RegionMap[RegionName]["input"]) => JSX.Element
// A registered claim as stored by the plugin provider's registry.
export type SlotClaim = {
readonly region: RegionName
readonly placement: Placement
readonly render: RegionRender
}
import { infoStringToFiletype, type MarkdownCodeBlockRenderer } from "@opentui/core"
import { useRenderer } from "@opentui/solid"
import { useClient } from "../context/client"
@@ -29,12 +49,14 @@ export type Dispose = () => Promise<void>
export type Registry = {
has(kind: "routes" | "slots" | "markdown", name: string): boolean
set(kind: "routes", name: string, page: Page): void
set(kind: "slots", name: string, slot: Slot): void
set(kind: "slots", name: string, claim: SlotClaim): void
set(kind: "markdown", name: string, render: MarkdownCodeBlockRenderer): void
remove(kind: "routes" | "slots" | "markdown", name: string): void
active(): boolean
}
// The host services a plugin context adapts. Collected once by the provider
// (hooks must run during component setup) and shared by every activation.
export function usePluginHost() {
@@ -70,6 +92,7 @@ export function createPluginContext(input: {
}): Context {
const host = input.host
let context: Context
let claims = 0
// Every dialog and registered render is wrapped so plugin components can
// reach their own context through usePlugin().
const provide = (render: () => JSX.Element) => (
@@ -184,12 +207,28 @@ export function createPluginContext(input: {
return true
},
},
slot(name, render) {
if (input.registry.has("slots", name)) throw new Error(`Slot already registered: ${name}`)
// The registration map erases the slot-specific input type.
input.registry.set("slots", name, ((slotInput: SlotMap[typeof name]) =>
provide(() => render(slotInput))) as Slot)
return registration("slots", name)
slot(name: RegionName, value: RegionClaim) {
// Keys are counter-suffixed so one plugin may claim several places
// in the same region; order within the plugin is registration order.
const key = `${name}#${claims++}`
// Rebuilt field-by-field rather than rest-spread so malformed input
// from untyped plugins normalizes to exactly one placement key — a
// claim carrying two keys would match twice in the resolver.
const placement: Placement =
value.at !== undefined
? { at: value.at }
: value.before !== undefined
? { before: value.before }
: value.after !== undefined
? { after: value.after }
: { replace: value.replace }
input.registry.set("slots", key, {
region: name,
placement,
// The registration map erases the region-specific input type.
render: (slotInput) => provide(() => (value.render as RegionRender)(slotInput)),
})
return registration("slots", key)
},
},
}
+29 -22
View File
@@ -14,15 +14,16 @@ import {
import path from "path"
import { stat } from "fs/promises"
import { fileURLToPath, pathToFileURL } from "url"
import type { Page, Slot, SlotName } from "@opencode-ai/plugin/tui/context"
import { createStore, produce, reconcile as reconcileStore } from "solid-js/store"
import type { Page } from "@opencode-ai/plugin/tui/context"
import type { Claim } from "./structure"
import { createStore, produce, reconcile as reconcileStore, unwrap } from "solid-js/store"
import { isDeepEqual } from "remeda"
import "#runtime-plugin-support"
import { useConfig } from "../config"
import { useTuiLifecycle } from "../context/runtime"
import { errorMessage } from "../util/error"
import { builtins } from "./builtins"
import { createPluginContext, usePluginHost, type Dispose } from "./api"
import { createPluginContext, usePluginHost, type Dispose, type RegionRender, type SlotClaim } from "./api"
import { createSourceWatcher } from "./watch"
import { discoverTuiPlugins, freshSpecifier, localSource } from "./discovery"
@@ -46,9 +47,7 @@ type Value = {
readonly list: () => ReadonlyArray<State>
readonly registered: () => ReadonlyArray<RegisteredPlugin>
readonly route: (id: string, name: string) => Page["render"] | undefined
readonly slot: <Name extends SlotName>(
name: Name,
) => ReadonlyArray<{ readonly id: string; readonly render: Slot<Name> }>
readonly claims: (region: string) => ReadonlyArray<Claim<RegionRender>>
readonly markdown: () => MarkdownOptions["renderNode"]
readonly activate: (id: string) => Promise<boolean>
readonly deactivate: (id: string) => Promise<boolean>
@@ -62,7 +61,7 @@ type Registration = {
options?: Readonly<Record<string, any>>
active: boolean
routes: Record<string, Page>
slots: Record<string, Slot>
slots: Record<string, SlotClaim>
markdown: Record<string, MarkdownCodeBlockRenderer>
cleanups: Dispose[]
}
@@ -119,7 +118,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
owned,
registry: {
has: (kind, name) => Boolean(store.registrations[id]?.[kind][name]),
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | Slot | MarkdownCodeBlockRenderer) =>
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | SlotClaim | MarkdownCodeBlockRenderer) =>
setStore("registrations", id, kind, name, () => value),
remove: (kind, name) =>
setStore(
@@ -387,7 +386,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
host.toast.show({ variant: "error", title: "Plugin", message: `${state.target}: ${state.error}` })
setStore("states", reconcileStore(states))
}
const slotItems = new WeakMap<Slot, { readonly id: string; readonly render: Slot }>()
const slotItems = new WeakMap<RegionRender, Claim<RegionRender>>()
createEffect(
on(
() => JSON.stringify(config.data.plugins ?? []),
@@ -436,19 +435,27 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
active: plugin.active,
})),
route: (id, name) => store.registrations[id]?.routes[name]?.render,
slot: (name) =>
Object.entries(store.registrations).flatMap(([id, registration]) => {
const render = registration.active ? registration.slots[name] : undefined
if (!render) return []
// <For> diffs rows by reference; a stable wrapper per render
// function keeps untouched plugins' slot rows (and their state)
// alive across other plugins' reloads.
const cached = slotItems.get(render)
if (cached) return [cached]
const item = { id, render }
slotItems.set(render, item)
return [item]
}),
// Claims come back in enable order: registration-store key order
// across plugins (generations preserve key positions in place), then
// registration order within one plugin. The resolver's last-wins
// rules depend on it.
claims: (region) =>
Object.entries(store.registrations).flatMap(([id, registration]) =>
Object.entries(registration.active ? registration.slots : {}).flatMap(([key, slot]) => {
if (slot.region !== region) return []
// <For> diffs rows by reference; a stable claim per render
// function keeps untouched plugins' slot rows (and their
// state) alive across other plugins' reloads.
const cached = slotItems.get(slot.render)
if (cached) return [cached]
// Placements are immutable once registered; unwrap the store
// proxy so the resolver's `in` checks hit plain objects
// instead of subscribing tracked scopes to every key probe.
const item = { key: `${id}/${key}`, plugin: id, placement: unwrap(slot.placement), render: slot.render }
slotItems.set(slot.render, item)
return [item]
}),
),
markdown,
// Manual dialog toggles join the same chain as reconciles so a
// toggle mid-reload cannot mix registrations across generations.
+62 -22
View File
@@ -9,7 +9,9 @@ import {
type JSX,
type ParentProps,
} from "solid-js"
import type { SlotMap, SlotName } from "@opencode-ai/plugin/tui/context"
import type { RegionMap, RegionName } from "@opencode-ai/plugin/tui/context"
import type { RegionRender } from "./api"
import { resolveStructure, type Entry, type Part } from "./structure"
import { useRoute } from "../context/route"
import { useToast } from "../ui/toast"
import { errorMessage } from "../util/error"
@@ -64,31 +66,69 @@ export function PluginRoute(props: { readonly fallback: (id: string, name: strin
)
}
export function PluginSlot<Name extends SlotName>(props: {
type HostRender = () => JSX.Element
// One extensible area of the host UI: the host's parts plus every active
// plugin claim, resolved into one ordered child list. Placement policy —
// takeover suppression, last-enabled-wins, missing-anchor degradation —
// lives in resolveStructure; this component only renders the result.
export function Region<Name extends RegionName>(props: {
readonly name: Name
readonly input: SlotMap[Name]
readonly mode: "all" | "replace"
readonly input: RegionMap[Name]["input"]
readonly parts?: ReadonlyArray<Part<HostRender, RegionMap[Name]["part"]>>
}) {
const plugins = usePlugin()
const renderers = createMemo(() => {
const items = plugins.slot(props.name)
if (props.mode === "replace") return items.slice(-1)
return items
})
// resolveStructure builds fresh entry objects each run, but <For> diffs
// rows by reference: cache entries so untouched rows (and the plugin
// state inside them) survive unrelated claim changes. Part entries key on
// their documented-stable id — render-function identity would break if
// the compiled parts prop ever rebuilt its closures. Claim entries key on
// the render function (weakly, so hot-reloaded generations collect).
const partEntries = new Map<string, Entry<HostRender, RegionRender>>()
const claimEntries = new WeakMap<RegionRender, Entry<HostRender, RegionRender>>()
const entries = createMemo(
() =>
resolveStructure<HostRender, RegionRender>({
region: props.name,
parts: props.parts ?? [],
claims: plugins.claims(props.name),
}).entries.map((entry) => {
if (entry.kind === "part") {
const cached = partEntries.get(entry.id)
if (cached) return cached
partEntries.set(entry.id, entry)
return entry
}
const cached = claimEntries.get(entry.claim.render)
if (cached) return cached
claimEntries.set(entry.claim.render, entry)
return entry
}),
[] as ReadonlyArray<Entry<HostRender, RegionRender>>,
// Rows are reference-stable, so an elementwise comparison makes a claim
// change in some other region a complete no-op for this one.
{ equals: (a, b) => a.length === b.length && a.every((entry, index) => entry === b[index]) },
)
return (
<For each={renderers()}>
{(item) => (
<PluginBoundary id={item.id} where={`slot ${props.name}`}>
{
// Component semantics: the render body runs once and untracked, so
// signals and intervals created inside are stable, while props stay
// reactive through the merged getter. A bare item.render(props.input)
// call would run inside the host's tracked scope and re-execute the
// whole body (resetting plugin state) on every tracked read.
createComponent(item.render, mergeProps(() => props.input) as SlotMap[Name])
}
</PluginBoundary>
)}
<For each={entries()}>
{(entry) =>
// A row's entry object is cached, so its kind never changes within
// the row's lifetime — a plain branch is safe here.
entry.kind === "part" ? (
entry.render()
) : (
<PluginBoundary id={entry.claim.plugin} where={`region ${props.name}`}>
{
// Component semantics: the render body runs once and untracked, so
// signals and intervals created inside are stable, while props stay
// reactive through the merged getter. A bare render(props.input)
// call would run inside the host's tracked scope and re-execute the
// whole body (resetting plugin state) on every tracked read.
createComponent(entry.claim.render, mergeProps(() => props.input) as RegionMap[RegionName]["input"])
}
</PluginBoundary>
)
}
</For>
)
}
+125
View File
@@ -0,0 +1,125 @@
// Pure resolution of a region's structure: the host's part tree plus plugin
// claims in, an ordered render list plus suppressions out. No solid, no I/O —
// every policy rule (takeover, hierarchy-beats-timeline, last-enabled-wins,
// missing-anchor degradation) is testable as a data transform.
// Mirrors the public RegionPlacement type (plugin package) with part ids
// erased to strings so the resolver stays independent of the region map.
// Keep the two unions' variants in sync.
export type Placement =
| { readonly at: "start" | "end" }
| { readonly before: string }
| { readonly after: string }
| { readonly replace: string }
// One plugin's registered slot, in enable order within the claims array.
export type Claim<Render> = {
readonly key: string
readonly plugin: string
readonly placement: Placement
readonly render: Render
}
// Host furniture: a leaf renders, a container groups — never both. Part ids
// are the stable anchor vocabulary and must be unique within a region.
export type Part<Render, Id extends string = string> =
| { readonly id: Id; readonly render: Render; readonly parts?: never }
| { readonly id: Id; readonly parts: ReadonlyArray<Part<Render, Id>>; readonly render?: never }
export type Entry<PartRender, ClaimRender> =
| { readonly kind: "part"; readonly id: string; readonly render: PartRender }
| { readonly kind: "claim"; readonly claim: Claim<ClaimRender> }
export function resolveStructure<PartRender extends {}, ClaimRender>(input: {
readonly region: string
readonly parts: ReadonlyArray<Part<PartRender>>
readonly claims: ReadonlyArray<Claim<ClaimRender>>
}): {
readonly entries: ReadonlyArray<Entry<PartRender, ClaimRender>>
readonly suppressed: ReadonlyArray<{ readonly claim: Claim<ClaimRender>; readonly by: Claim<ClaimRender> }>
readonly degraded: ReadonlyArray<Claim<ClaimRender>>
} {
// Root takeover: the region's content is the winning claim, full stop.
// Every other claim — including edge-anchored ones — is suppressed, so a
// theme can never be silently decorated by chips it didn't plan for.
const takeover = input.claims
.filter((claim) => "replace" in claim.placement && claim.placement.replace === input.region)
.at(-1)
if (takeover)
return {
entries: [{ kind: "claim", claim: takeover }],
suppressed: input.claims.filter((claim) => claim !== takeover).map((claim) => ({ claim, by: takeover })),
degraded: [],
}
const known = new Set<string>()
const register = (parts: ReadonlyArray<Part<PartRender>>) => {
for (const part of parts) {
known.add(part.id)
if (part.parts !== undefined) register(part.parts)
}
}
register(input.parts)
const entries: Entry<PartRender, ClaimRender>[] = []
const suppressed: { claim: Claim<ClaimRender>; by: Claim<ClaimRender> }[] = []
// A container takeover orphans everything anchored to (or replacing) the
// parts inside it. Recorded so the host can surface it (plugins dialog,
// in a follow-up) — never silently dropped.
const suppressSubtree = (parts: ReadonlyArray<Part<PartRender>>, by: Claim<ClaimRender>) => {
for (const part of parts) {
for (const claim of input.claims) if (anchor(claim.placement) === part.id) suppressed.push({ claim, by })
if (part.parts !== undefined) suppressSubtree(part.parts, by)
}
}
const walk = (parts: ReadonlyArray<Part<PartRender>>) => {
for (const part of parts) {
for (const claim of input.claims)
if ("before" in claim.placement && claim.placement.before === part.id) entries.push({ kind: "claim", claim })
// Replacing keeps the part's position: before/after anchors on the
// replaced id stay valid, only the content (and subtree) changes hands.
const replacers = input.claims.filter(
(claim) => "replace" in claim.placement && claim.placement.replace === part.id,
)
const winner = replacers.at(-1)
if (winner) {
for (const loser of replacers.slice(0, -1)) suppressed.push({ claim: loser, by: winner })
entries.push({ kind: "claim", claim: winner })
// Hierarchy beats timeline: claims into the subtree lose to the
// container's winner no matter when they were enabled.
if (part.parts !== undefined) suppressSubtree(part.parts, winner)
}
if (!winner && part.parts !== undefined) walk(part.parts)
if (!winner && part.render !== undefined) entries.push({ kind: "part", id: part.id, render: part.render })
for (const claim of input.claims)
if ("after" in claim.placement && claim.placement.after === part.id) entries.push({ kind: "claim", claim })
}
}
for (const claim of input.claims)
if ("at" in claim.placement && claim.placement.at === "start") entries.push({ kind: "claim", claim })
walk(input.parts)
for (const claim of input.claims)
if ("at" in claim.placement && claim.placement.at === "end") entries.push({ kind: "claim", claim })
// A claim aimed at a part the host no longer publishes degrades to the
// region's end rather than vanishing: an anchor rename must never silently
// cost a plugin its render. Degraded claims land after end-edge claims,
// in enable order.
const degraded = input.claims.filter((claim) => {
const id = anchor(claim.placement)
return id !== undefined && !known.has(id)
})
for (const claim of degraded) entries.push({ kind: "claim", claim })
return { entries, suppressed, degraded }
}
function anchor(placement: Placement) {
if ("before" in placement) return placement.before
if ("after" in placement) return placement.after
if ("replace" in placement) return placement.replace
return undefined
}
+2 -2
View File
@@ -9,7 +9,7 @@ import { useEditorContext } from "../context/editor"
import { useData } from "../context/data"
import { useLocation } from "../context/location"
import { FormPrompt } from "./session/form"
import { PluginSlot } from "../plugin/render"
import { Region } from "../plugin/render"
import { useTerminalDimensions } from "@opentui/solid"
let once = false
@@ -91,7 +91,7 @@ export function Home() {
<box flexGrow={1} minHeight={0} />
</box>
<box width="100%" flexShrink={0}>
<PluginSlot name="home.footer" input={{}} mode="replace" />
<Region name="home.footer" input={{}} />
</box>
<Show when={forms()[0]?.id} keyed>
{(_) => {
+2 -2
View File
@@ -82,7 +82,7 @@ import { collapseToolOutput } from "../../util/collapse-tool-output"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { usePathFormatter } from "../../context/path-format"
import { useLocation } from "../../context/location"
import { PluginSlot } from "../../plugin/render"
import { Region } from "../../plugin/render"
import { usePlugin } from "../../plugin/context"
import {
cacheReuseDrop,
@@ -1072,7 +1072,7 @@ export function Session() {
<Show when={!composer.open && !disabled() && queuedPrompts().length > 0}>
<QueuedPromptDock prompts={queuedPrompts()} onOpen={openQueuedPrompts} />
</Show>
<PluginSlot name="session.composer.top" input={{ sessionID: route.sessionID }} mode="all" />
<Region name="session.composer.top" input={{ sessionID: route.sessionID }} />
<Composer
sessionID={route.sessionID}
open={composer.open || (!!session()?.parentID && forms().length === 0)}
+3 -3
View File
@@ -2,7 +2,7 @@ import { useData } from "../../context/data"
import { createMemo, Show } from "solid-js"
import { useTheme } from "../../context/theme"
import { useConfig } from "../../config"
import { PluginSlot } from "../../plugin/render"
import { Region } from "../../plugin/render"
import { withTimestampedFallback } from "@opencode-ai/util/session-title-fallback"
import { getScrollAcceleration } from "../../util/scroll"
@@ -52,12 +52,12 @@ export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
<text fg={theme.text.subdued}>{session()!.location.workspaceID}</text>
</Show>
</box>
<PluginSlot name="sidebar.content" input={{ sessionID: props.sessionID }} mode="all" />
<Region name="sidebar.content" input={{ sessionID: props.sessionID }} />
</box>
</scrollbox>
<box flexShrink={0} gap={1} paddingTop={1}>
<PluginSlot name="sidebar.footer" input={{}} mode="replace" />
<Region name="sidebar.footer" input={{}} />
</box>
</box>
</Show>
@@ -8,8 +8,8 @@ import type {
KeymapCommand,
KeymapLayer,
Page,
RegionClaim,
Route,
Slot,
} from "@opencode-ai/plugin/tui/context"
import { ThemeProvider, useThemes } from "../../../src/context/theme"
import { ConfigProvider } from "../../../src/config"
@@ -142,7 +142,7 @@ async function renderDiffViewer(vcsDiff: unknown[], height = 20, initialRoute?:
const commands = new Map<string, KeymapCommand>()
let current = initialRoute ?? startRoute
let renderDiff: Page["render"] | undefined
let renderCommands: Slot | undefined
let renderCommands: RegionClaim<"app">["render"] | undefined
let vcsDiffInput: unknown
const config = createTuiResolvedConfig()
const transport = createFetch((url) => {
@@ -199,8 +199,8 @@ async function renderDiffViewer(vcsDiff: unknown[], height = 20, initialRoute?:
},
current: () => current,
},
slot(_name: string, render: Slot) {
renderCommands = render
slot(_name: string, claim: RegionClaim<"app">) {
renderCommands = claim.render
return () => {}
},
},
+5 -2
View File
@@ -140,8 +140,11 @@ import { appendFile } from "node:fs/promises"
export default {
id: "test.crash",
setup: async (context: any) => {
context.ui.slot("home.footer", () => {
throw new Error("boom")
context.ui.slot("home.footer", {
replace: "home.footer",
render: () => {
throw new Error("boom")
},
})
await appendFile(${JSON.stringify(markerCrash)}, "setup\\n")
},
+148
View File
@@ -0,0 +1,148 @@
import { expect, test } from "bun:test"
import type { RegionClaim } from "@opencode-ai/plugin/tui/context"
import { resolveStructure, type Claim, type Part, type Placement } from "../src/plugin/structure"
// Type-level canaries, checked by `bun typecheck`: the placement sum and the
// part union are exclusive — nonsense shapes must not compile.
export const canaries = () => {
const claims: RegionClaim<"prompt.footer">[] = []
claims.push({ at: "end", render: () => null })
// @ts-expect-error two placement keys cannot coexist
claims.push({ at: "end", before: "status", render: () => null })
// @ts-expect-error replace does not combine with an anchor
claims.push({ replace: "status", after: "file", render: () => null })
// @ts-expect-error a part is a leaf or a container, never both
const hybrid: Part<string> = { id: "x", render: "x", parts: [] }
return { claims, hybrid }
}
// The resolver is generic over render types; strings make ordering
// assertions read as layouts.
function claim(plugin: string, placement: Placement, render?: string): Claim<string> {
return { key: `${plugin}/${render ?? JSON.stringify(placement)}`, plugin, placement, render: render ?? plugin }
}
function layout(result: ReturnType<typeof resolveStructure<string, string>>) {
return result.entries.map((entry) => (entry.kind === "part" ? entry.id : entry.claim.render))
}
const footer: Part<string>[] = [
{ id: "status", render: "status" },
{ id: "file", render: "file" },
]
const tree: Part<string>[] = [
{ id: "left", parts: [{ id: "mode", render: "mode" }] },
{
id: "right",
parts: [
{ id: "directory", render: "directory" },
{ id: "model", render: "model" },
{ id: "tokens", render: "tokens" },
],
},
]
test("no claims renders the host parts in order", () => {
const result = resolveStructure<string, string>({ region: "prompt.footer", parts: footer, claims: [] })
expect(layout(result)).toEqual(["status", "file"])
expect(result.suppressed).toEqual([])
expect(result.degraded).toEqual([])
})
test("edge claims land at the region's edges, several in enable order", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [
claim("a", { at: "end" }, "a1"),
claim("b", { at: "start" }, "b1"),
claim("a", { at: "end" }, "a2"),
],
})
expect(layout(result)).toEqual(["b1", "status", "file", "a1", "a2"])
})
test("before and after anchor to a part, wherever the host keeps it", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { after: "status" }, "chip"), claim("b", { before: "status" }, "vim")],
})
expect(layout(result)).toEqual(["vim", "status", "chip", "file"])
})
test("a missing anchor degrades to the end instead of disappearing", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { after: "tokens" }, "chip")],
})
expect(layout(result)).toEqual(["status", "file", "chip"])
expect(result.degraded.map((item) => item.render)).toEqual(["chip"])
})
test("replacing a part swaps content but keeps the position and its anchors", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { replace: "status" }, "fancy-status"), claim("b", { after: "status" }, "chip")],
})
expect(layout(result)).toEqual(["fancy-status", "chip", "file"])
expect(result.suppressed).toEqual([])
})
test("same target: the last-enabled claim wins and the loser is recorded", () => {
const first = claim("a", { replace: "status" }, "first")
const second = claim("b", { replace: "status" }, "second")
const result = resolveStructure({ region: "prompt.footer", parts: footer, claims: [first, second] })
expect(layout(result)).toEqual(["second", "file"])
expect(result.suppressed).toEqual([{ claim: first, by: second }])
})
test("container takeover suppresses everything anchored in the subtree", () => {
const takeover = claim("theme", { replace: "right" }, "my-right")
const chip = claim("pr", { after: "model" }, "chip")
const inner = claim("x", { replace: "tokens" }, "cost")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [takeover, chip, inner] })
expect(layout(result)).toEqual(["mode", "my-right"])
expect(result.suppressed).toEqual([
{ claim: chip, by: takeover },
{ claim: inner, by: takeover },
])
})
test("hierarchy beats timeline: an ancestor takeover wins over a later descendant claim", () => {
// The descendant replace was enabled after the container takeover; the
// container still wins because its target contains the descendant's.
const inner = claim("x", { replace: "model" }, "swap-model")
const outer = claim("theme", { replace: "right" }, "my-right")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [outer, inner] })
expect(layout(result)).toEqual(["mode", "my-right"])
expect(result.suppressed).toEqual([{ claim: inner, by: outer }])
})
test("root takeover: nothing original survives, all other claims suppressed", () => {
const theme = claim("powerline", { replace: "prompt.footer" }, "powerline")
const chip = claim("pr", { at: "end" }, "chip")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [chip, theme] })
expect(layout(result)).toEqual(["powerline"])
expect(result.suppressed).toEqual([{ claim: chip, by: theme }])
})
test("root takeover at the same node: last enabled wins", () => {
const first = claim("a", { replace: "home.footer" }, "first")
const second = claim("b", { replace: "home.footer" }, "second")
const result = resolveStructure<string, string>({ region: "home.footer", parts: [], claims: [first, second] })
expect(layout(result)).toEqual(["second"])
expect(result.suppressed).toEqual([{ claim: first, by: second }])
})
test("containers flatten in order and anchors on a container wrap its whole span", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: tree,
claims: [claim("a", { before: "right" }, "divider"), claim("b", { after: "right" }, "clock")],
})
expect(layout(result)).toEqual(["mode", "divider", "directory", "model", "tokens", "clock"])
})