mirror of
https://github.com/anomalyco/opencode.git
synced 2026-10-02 21:46:18 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13e9cbaca9 |
No files matched your search
@@ -115,7 +115,7 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre
|
||||
const acp = ACPConnection.make(app, stream)
|
||||
const connection = acp.connection
|
||||
const sessions = yield* ACPSessions.make({ client, connection, catalog })
|
||||
const capabilities = yield* Ref.make({ childSessionUpdates: false, formElicitation: false })
|
||||
const capabilities = yield* Ref.make({ childSessionUpdates: false })
|
||||
const turn = yield* ACPTurn.make({ client, connection, sessions, catalog, capabilities })
|
||||
yield* Deferred.succeed(ready, ACPService.make({ client, connection, catalog, sessions, capabilities, turn }))
|
||||
return acp.agent
|
||||
|
||||
@@ -2,8 +2,6 @@ import {
|
||||
methods,
|
||||
type AgentApp,
|
||||
type AnyMessage,
|
||||
type CreateElicitationRequest,
|
||||
type CreateElicitationResponse,
|
||||
type JsonRpcId,
|
||||
type RequestError,
|
||||
type RequestPermissionRequest,
|
||||
@@ -33,10 +31,6 @@ export interface Interface {
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
) => Effect.Effect<void, ACPError.Error | RequestError>
|
||||
/** Interruption cancels the client's request. */
|
||||
readonly createElicitation: (
|
||||
params: CreateElicitationRequest,
|
||||
) => Effect.Effect<CreateElicitationResponse, ACPError.Error | RequestError>
|
||||
/** Tracks an incoming request from now on and returns its `Responded`. */
|
||||
readonly responded: (requestId: JsonRpcId) => Effect.Effect<void>
|
||||
}
|
||||
@@ -71,10 +65,6 @@ export function make(app: AgentApp, stream: Stream) {
|
||||
agent.client.request(methods.client.session.requestPermission, params, { cancellationSignal: signal }),
|
||||
),
|
||||
extNotification: (method, params) => ACPPromise.promise(() => agent.client.notify(method, params)),
|
||||
createElicitation: (params) =>
|
||||
ACPPromise.promise((signal) =>
|
||||
agent.client.request(methods.client.elicitation.create, params, { cancellationSignal: signal }),
|
||||
),
|
||||
responded: (requestId) => {
|
||||
const responded = Deferred.makeUnsafe<void>()
|
||||
responses.set(requestId, responded)
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
import type {
|
||||
CreateElicitationResponse,
|
||||
ElicitationPropertySchema,
|
||||
ElicitationSchema,
|
||||
EnumOption,
|
||||
} from "@agentclientprotocol/sdk"
|
||||
import { isFormAlreadySettledError, isFormNotFoundError, type OpenCodeClient } from "@opencode/client/promise"
|
||||
import { Form } from "@opencode/schema/form"
|
||||
import { Cause, Effect, Option, Schema } from "effect"
|
||||
import type { ACPConnection } from "./connection"
|
||||
import type { ACPService } from "./service"
|
||||
|
||||
/** A form as the event stream carries it, with an unbranded ID. */
|
||||
export type AskedForm = Omit<Form.Info, "id"> & { readonly id: string }
|
||||
type InputField = Exclude<Form.Field, Form.ExternalField>
|
||||
type SelectField = Form.StringField | Form.MultiselectField
|
||||
|
||||
// Form mode must not collect secrets, so only forms from flows known not to ask for credentials are elicited.
|
||||
const ElicitedKind = Schema.Struct({ kind: Schema.Literals(["question", "websearch.provider"]) })
|
||||
const Credential = /password|passphrase|secret|token|api[_-]?key|credential|private[_-]?key/i
|
||||
const ToolSource = Schema.Struct({ tool: Schema.Struct({ id: Schema.String }) })
|
||||
|
||||
type Input = {
|
||||
readonly client: OpenCodeClient
|
||||
readonly connection: ACPConnection.Interface
|
||||
readonly form: AskedForm
|
||||
readonly requestedSchema: ElicitationSchema
|
||||
readonly clientSessionID: string
|
||||
readonly child?: { readonly id: string; readonly title?: string }
|
||||
/** Whether the asking tool call reached the client as a `session/update` tool call. */
|
||||
readonly toolCallSent: boolean
|
||||
/** Completes once the form is answered or cancelled elsewhere. */
|
||||
readonly settled: Effect.Effect<void>
|
||||
}
|
||||
|
||||
type Outcome = Form.Answer | "cancel" | "settled"
|
||||
|
||||
/**
|
||||
* Asks the client, then resolves the form on the server. Once `cancelled` completes, the client's request is
|
||||
* cancelled or never sent, and the form is cancelled. Once `settled` completes, the client's request is cancelled and
|
||||
* the server is left alone. Resolving on the server is uninterruptible.
|
||||
*/
|
||||
export const reply = Effect.fn("cli.acp.elicitation.reply")(function* (input: Input, cancelled: Effect.Effect<void>) {
|
||||
yield* Effect.uninterruptibleMask((restore) =>
|
||||
// The race starts racers in order and stops once one is done, so an earlier cancel never starts the ask.
|
||||
restore(
|
||||
cancelled.pipe(
|
||||
Effect.as("cancel" as const),
|
||||
Effect.raceFirst(input.settled.pipe(Effect.as("settled" as const))),
|
||||
Effect.raceFirst(ask(input)),
|
||||
),
|
||||
).pipe(
|
||||
Effect.tapCauseIf(Cause.hasDies, (cause) => Effect.logWarning("ACP elicitation failed", cause)),
|
||||
Effect.catchCause(() => Effect.succeed("cancel" as const)),
|
||||
Effect.flatMap((outcome) => respond(input, outcome)),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
/** Cancels a form, interrupting its session when the server can't cancel it. */
|
||||
export function cancel(client: OpenCodeClient, form: AskedForm) {
|
||||
return settle(() => client.session.form.cancel({ sessionID: form.sessionID, formID: form.id })).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.tryPromise(() => client.session.interrupt({ sessionID: form.sessionID })).pipe(Effect.ignore),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The form-mode schema for a form, or undefined when the form is cancelled instead: the client lacks form
|
||||
* elicitation, the form is not from an allowed flow or has a field that looks like a credential, or ACP can't
|
||||
* represent it faithfully. Unrepresentable forms have `external` fields, `when` conditions, a hidden required field
|
||||
* without a default, a default outside a field's options, or a free-text answer alongside options that must also
|
||||
* satisfy `required` or item bounds across both inputs. Hidden fields are not asked and answer with their default.
|
||||
*/
|
||||
export function requestedSchema(form: AskedForm, capabilities: ACPService.Capabilities): ElicitationSchema | undefined {
|
||||
if (!capabilities.formElicitation) return undefined
|
||||
if (Option.isNone(Schema.decodeUnknownOption(ElicitedKind)(form.metadata))) return undefined
|
||||
if (form.fields.some((field) => Credential.test(field.key) || Credential.test(field.title ?? ""))) return undefined
|
||||
const fields = form.fields.filter((field): field is InputField => field.type !== "external")
|
||||
if (fields.length !== form.fields.length || fields.some((field) => field.when?.length)) return undefined
|
||||
if (fields.some((field) => field.hidden && field.required && field.default === undefined)) return undefined
|
||||
const keys = new Set(fields.map((field) => field.key))
|
||||
const visible = fields.filter((field) => !field.hidden)
|
||||
if (!visible.every((field) => representable(field, keys))) return undefined
|
||||
return {
|
||||
type: "object",
|
||||
properties: Object.fromEntries(visible.flatMap(properties)),
|
||||
required: visible.filter((field) => field.required).map((field) => field.key),
|
||||
}
|
||||
}
|
||||
|
||||
/** The answer for an accepted response, or undefined when the user declined, cancelled, or sent invalid content. */
|
||||
export function answer(form: AskedForm, response: CreateElicitationResponse): Form.Answer | undefined {
|
||||
if (response.action !== "accept") return undefined
|
||||
const content = Schema.decodeUnknownOption(Form.Answer)(response.content ?? {})
|
||||
if (Option.isNone(content)) return undefined
|
||||
return Object.fromEntries(
|
||||
form.fields.flatMap((field) => {
|
||||
const value = fieldAnswer(field, content.value)
|
||||
return value === undefined ? [] : [[field.key, value]]
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const ask = Effect.fnUntraced(function* (input: Input) {
|
||||
const source = input.toolCallSent ? Schema.decodeUnknownOption(ToolSource)(input.form.metadata) : Option.none()
|
||||
const toolCallID = Option.getOrUndefined(Option.map(source, (metadata) => metadata.tool.id))
|
||||
const response = yield* input.connection.createElicitation({
|
||||
mode: "form",
|
||||
sessionId: input.clientSessionID,
|
||||
...(toolCallID ? { toolCallId: input.child ? `${input.child.id}:${toolCallID}` : toolCallID } : {}),
|
||||
message: input.child?.title ? `${input.child.title}: ${input.form.title}` : input.form.title,
|
||||
requestedSchema: input.requestedSchema,
|
||||
})
|
||||
return answer(input.form, response) ?? "cancel"
|
||||
})
|
||||
|
||||
function respond(input: Input, outcome: Outcome) {
|
||||
if (outcome === "settled") return Effect.void
|
||||
if (outcome === "cancel") return cancel(input.client, input.form)
|
||||
return settle(() =>
|
||||
input.client.session.form.reply({ sessionID: input.form.sessionID, formID: input.form.id, answer: outcome }),
|
||||
).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("ACP form reply failed", cause).pipe(Effect.andThen(cancel(input.client, input.form))),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// A form already answered or cancelled elsewhere needs nothing more.
|
||||
function settle(evaluate: () => Promise<void>) {
|
||||
return Effect.tryPromise({ try: evaluate, catch: (cause) => cause }).pipe(
|
||||
Effect.catch((cause) =>
|
||||
isFormAlreadySettledError(cause) || isFormNotFoundError(cause) ? Effect.void : Effect.fail(cause),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function representable(field: InputField, keys: ReadonlySet<string>) {
|
||||
if (field.type !== "string" && field.type !== "multiselect") return true
|
||||
if (!hasOptions(field)) return true
|
||||
const values = new Set(field.options?.map((option) => option.value))
|
||||
const defaults =
|
||||
field.default === undefined ? [] : typeof field.default === "string" ? [field.default] : field.default
|
||||
if (defaults.some((value) => !values.has(value))) return false
|
||||
if (!field.custom) return true
|
||||
if (field.required || keys.has(customKey(field))) return false
|
||||
return field.type === "string" || (field.minItems === undefined && field.maxItems === undefined)
|
||||
}
|
||||
|
||||
function properties(field: InputField): Array<[string, ElicitationPropertySchema]> {
|
||||
const base = { title: field.title, description: field.description }
|
||||
switch (field.type) {
|
||||
case "string": {
|
||||
if (!hasOptions(field)) return [[field.key, { type: "string", ...base, ...text(field), default: field.default }]]
|
||||
const select: ElicitationPropertySchema = {
|
||||
type: "string",
|
||||
...base,
|
||||
oneOf: options(field),
|
||||
default: field.default,
|
||||
}
|
||||
return field.custom ? [[field.key, select], other(field, "Type your own answer")] : [[field.key, select]]
|
||||
}
|
||||
case "multiselect": {
|
||||
const select: ElicitationPropertySchema = {
|
||||
type: "array",
|
||||
...base,
|
||||
items: { anyOf: options(field) },
|
||||
minItems: field.required ? Math.max(field.minItems ?? 0, 1) : field.minItems,
|
||||
maxItems: field.maxItems,
|
||||
default: field.default,
|
||||
}
|
||||
return field.custom ? [[field.key, select], other(field, "Add your own answer")] : [[field.key, select]]
|
||||
}
|
||||
case "number":
|
||||
case "integer":
|
||||
return [
|
||||
[
|
||||
field.key,
|
||||
{ type: field.type, ...base, minimum: field.minimum, maximum: field.maximum, default: field.default },
|
||||
],
|
||||
]
|
||||
case "boolean":
|
||||
return [[field.key, { type: "boolean", ...base, default: field.default }]]
|
||||
}
|
||||
}
|
||||
|
||||
// A free-text answer next to a field's options is a separate optional property that wins over the selection.
|
||||
function other(field: SelectField, description: string): [string, ElicitationPropertySchema] {
|
||||
return [
|
||||
customKey(field),
|
||||
{
|
||||
type: "string",
|
||||
title: `${field.title ?? field.key} (other)`,
|
||||
description,
|
||||
...(field.type === "string" ? text(field) : {}),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// Core rejects an empty string for a required field, so the client is told it needs at least one character.
|
||||
function text(field: Form.StringField) {
|
||||
return {
|
||||
format: field.format,
|
||||
minLength: field.required ? Math.max(field.minLength ?? 0, 1) : field.minLength,
|
||||
maxLength: field.maxLength,
|
||||
pattern: field.pattern,
|
||||
}
|
||||
}
|
||||
|
||||
function options(field: SelectField): EnumOption[] {
|
||||
return (field.options ?? []).map((option) => ({
|
||||
const: option.value,
|
||||
title: option.label,
|
||||
description: option.description,
|
||||
}))
|
||||
}
|
||||
|
||||
function fieldAnswer(field: Form.Field, content: Form.Answer) {
|
||||
if (field.type !== "external" && field.hidden) return field.default
|
||||
const value = content[field.key]
|
||||
if ((field.type !== "string" && field.type !== "multiselect") || !field.custom || !hasOptions(field)) return value
|
||||
const custom = content[customKey(field)]
|
||||
if (typeof custom !== "string" || custom.trim() === "") return value
|
||||
if (field.type === "string") return custom
|
||||
return Array.isArray(value) ? [...value, custom] : [custom]
|
||||
}
|
||||
|
||||
function hasOptions(field: SelectField) {
|
||||
return field.type === "multiselect" || field.options !== undefined
|
||||
}
|
||||
|
||||
function customKey(field: SelectField) {
|
||||
return `${field.key}_custom`
|
||||
}
|
||||
|
||||
export * as ACPElicitation from "./elicitation"
|
||||
@@ -51,9 +51,6 @@ export const AuthMethodID = "opencode-login"
|
||||
|
||||
export type Failure = ACPError.Error | RequestError | ACPCatalog.Error
|
||||
|
||||
/** What the client advertised in `initialize`. */
|
||||
export type Capabilities = { readonly childSessionUpdates: boolean; readonly formElicitation: boolean }
|
||||
|
||||
export interface Interface {
|
||||
readonly initialize: (input: InitializeRequest) => Effect.Effect<InitializeResponse>
|
||||
readonly authenticate: (input: AuthenticateRequest) => Effect.Effect<AuthenticateResponse, Failure>
|
||||
@@ -77,7 +74,7 @@ export function make(input: {
|
||||
readonly connection: ACPConnection.Interface
|
||||
readonly catalog: ACPCatalog.Interface
|
||||
readonly sessions: ACPSessions.Interface
|
||||
readonly capabilities: Ref.Ref<Capabilities>
|
||||
readonly capabilities: Ref.Ref<{ readonly childSessionUpdates: boolean }>
|
||||
readonly turn: ACPTurn.Interface
|
||||
}): Interface {
|
||||
const currentOptions = Effect.fnUntraced(function* (attached: Attached) {
|
||||
@@ -150,10 +147,8 @@ export function make(input: {
|
||||
|
||||
return {
|
||||
initialize: Effect.fnUntraced(function* (params) {
|
||||
const elicitation = params.clientCapabilities?.elicitation
|
||||
yield* Ref.set(input.capabilities, {
|
||||
childSessionUpdates: params.clientCapabilities?._meta?.[ACPTranslate.ChildSessionUpdatesCapability] === true,
|
||||
formElicitation: elicitation?.form !== undefined && elicitation.form !== null,
|
||||
})
|
||||
const authMethod: AuthMethod = {
|
||||
description: "Run `opencode auth login` in the terminal",
|
||||
|
||||
@@ -75,8 +75,6 @@ export type TurnState = {
|
||||
readonly compactions: ReadonlyMap<string, string>
|
||||
readonly children: ReadonlyMap<string, ChildSession>
|
||||
readonly openChildren: ReadonlySet<string>
|
||||
/** Forms asked of the client that the server has not yet answered or cancelled. */
|
||||
readonly forms: ReadonlySet<string>
|
||||
readonly finish?: SessionMessageAssistant["finish"]
|
||||
readonly usage?: { readonly turn: TokenUsageInfo; readonly last: TokenUsageInfo }
|
||||
readonly stepError?: SessionStructuredError
|
||||
@@ -84,7 +82,6 @@ export type TurnState = {
|
||||
}
|
||||
|
||||
type PermissionEvent = Extract<EventSubscribeOutput, { type: "permission.asked" }>
|
||||
type FormEvent = Extract<EventSubscribeOutput, { type: "form.created" }>
|
||||
|
||||
export type Output =
|
||||
| { readonly _tag: "SessionUpdate"; readonly update: SessionUpdate }
|
||||
@@ -95,14 +92,7 @@ export type Output =
|
||||
readonly tool?: Tool
|
||||
readonly child?: ChildSession
|
||||
}
|
||||
| {
|
||||
readonly _tag: "FormAsk"
|
||||
readonly form: FormEvent["data"]["form"]
|
||||
readonly child?: ChildSession
|
||||
/** Whether the form's session sends its tool calls to the client as `session/update` tool calls. */
|
||||
readonly toolCallSent: boolean
|
||||
}
|
||||
| { readonly _tag: "FormSettled"; readonly formID: string }
|
||||
| { readonly _tag: "FormCancel"; readonly sessionID: string; readonly formID: string }
|
||||
|
||||
export type Step = {
|
||||
readonly state: TurnState
|
||||
@@ -129,7 +119,6 @@ export const initial: TurnState = {
|
||||
compactions: new Map(),
|
||||
children: new Map(),
|
||||
openChildren: new Set(),
|
||||
forms: new Set(),
|
||||
}
|
||||
|
||||
export function step(state: TurnState, event: EventSubscribeOutput, ctx: Context): Step {
|
||||
@@ -162,22 +151,10 @@ export function step(state: TurnState, event: EventSubscribeOutput, ctx: Context
|
||||
}
|
||||
if (event.type === "form.created" && (event.data.form.sessionID === ctx.sessionID || child)) {
|
||||
return {
|
||||
state: { ...state, forms: new Set(state.forms).add(event.data.form.id) },
|
||||
outputs: [
|
||||
{
|
||||
_tag: "FormAsk",
|
||||
form: event.data.form,
|
||||
child,
|
||||
toolCallSent: ctx.mode === "turn" && (!child || !ctx.childUpdates),
|
||||
},
|
||||
],
|
||||
state,
|
||||
outputs: [{ _tag: "FormCancel", sessionID: event.data.form.sessionID, formID: event.data.form.id }],
|
||||
}
|
||||
}
|
||||
if ((event.type === "form.replied" || event.type === "form.cancelled") && state.forms.has(event.data.id)) {
|
||||
const forms = new Set(state.forms)
|
||||
forms.delete(event.data.id)
|
||||
return { state: { ...state, forms }, outputs: [{ _tag: "FormSettled", formID: event.data.id }] }
|
||||
}
|
||||
if (!eventSessionID || (eventSessionID !== ctx.sessionID && !child)) return { state, outputs: [] }
|
||||
if (matchesStart(event, ctx.start)) return { state: { ...state, started: true }, outputs: [] }
|
||||
if (!state.started) return { state, outputs: [] }
|
||||
|
||||
@@ -26,11 +26,9 @@ import { builtinCommands, type ACPCatalog, type Catalog } from "./catalog"
|
||||
import { currentModel } from "./config-option"
|
||||
import type { ACPConnection } from "./connection"
|
||||
import { promptContentToParts } from "./content"
|
||||
import { ACPElicitation } from "./elicitation"
|
||||
import { ACPError } from "./error"
|
||||
import { ACPPermission } from "./permission"
|
||||
import { ACPPromise } from "./promise"
|
||||
import type { ACPService } from "./service"
|
||||
import type { ACPSessions, Attached } from "./sessions"
|
||||
import { ACPTranslate } from "./translate"
|
||||
|
||||
@@ -73,12 +71,10 @@ type PermissionAsk = Extract<ACPTranslate.Output, { readonly _tag: "PermissionAs
|
||||
type Subscription = {
|
||||
readonly scope: Scope.Closeable
|
||||
readonly events: Queue.Dequeue<OpenCodeEvent, unknown>
|
||||
/** Runs permission and form asks one at a time in ask order, without holding back the rest of the stream. */
|
||||
readonly asks: Queue.Queue<Effect.Effect<void, ACPError.Error | RequestError>>
|
||||
/** Completed when the turn is cancelled; pending and later asks then resolve without the client. */
|
||||
/** Runs permission replies one at a time in ask order, without holding back the rest of the stream. */
|
||||
readonly permissions: Queue.Queue<Effect.Effect<void, ACPError.Error | RequestError>>
|
||||
/** Completed when the turn is cancelled; pending and later asks are then rejected. */
|
||||
readonly cancelled: Deferred.Deferred<void>
|
||||
/** Completed per asked form once the server reports it answered or cancelled. */
|
||||
readonly forms: Map<string, Deferred.Deferred<void>>
|
||||
}
|
||||
|
||||
export const make = Effect.fnUntraced(function* (input: {
|
||||
@@ -86,7 +82,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
readonly connection: ACPConnection.Interface
|
||||
readonly sessions: ACPSessions.Interface
|
||||
readonly catalog: ACPCatalog.Interface
|
||||
readonly capabilities: Ref.Ref<ACPService.Capabilities>
|
||||
readonly capabilities: Ref.Ref<{ readonly childSessionUpdates: boolean }>
|
||||
}) {
|
||||
const scope = yield* Effect.scope
|
||||
const drainTimeout = yield* CancelDrainTimeout
|
||||
@@ -101,11 +97,10 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
Stream.toQueue({ capacity: "unbounded" }),
|
||||
Scope.provide(subscriptionScope),
|
||||
),
|
||||
asks: yield* Queue.unbounded<Effect.Effect<void, ACPError.Error | RequestError>>(),
|
||||
permissions: yield* Queue.unbounded<Effect.Effect<void, ACPError.Error | RequestError>>(),
|
||||
cancelled: yield* Deferred.make<void>(),
|
||||
forms: new Map(),
|
||||
}
|
||||
yield* Queue.take(subscription.asks).pipe(
|
||||
yield* Queue.take(subscription.permissions).pipe(
|
||||
Effect.flatten,
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.logWarning("ACP permission reply failed", cause),
|
||||
@@ -123,10 +118,10 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
),
|
||||
)
|
||||
|
||||
// A turn settles only after the asks it saw have been resolved.
|
||||
const asksSettled = Effect.fnUntraced(function* (subscription: Subscription) {
|
||||
// A turn settles only after the permission asks it saw have been answered.
|
||||
const permissionsSettled = Effect.fnUntraced(function* (subscription: Subscription) {
|
||||
const settled = yield* Deferred.make<void>()
|
||||
yield* Queue.offer(subscription.asks, Deferred.succeed(settled, undefined).pipe(Effect.asVoid))
|
||||
yield* Queue.offer(subscription.permissions, Deferred.succeed(settled, undefined).pipe(Effect.asVoid))
|
||||
yield* Deferred.await(settled)
|
||||
})
|
||||
|
||||
@@ -154,37 +149,11 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
.extNotification(ACPTranslate.ChildSessionUpdateMethod, output.update)
|
||||
.pipe(Effect.ignoreCause)
|
||||
case "PermissionAsk":
|
||||
return Queue.offer(subscription.asks, reply(subscription, ctx, output)).pipe(Effect.asVoid)
|
||||
case "FormAsk":
|
||||
return Effect.gen(function* () {
|
||||
const capabilities = yield* Ref.get(input.capabilities)
|
||||
const requestedSchema = ACPElicitation.requestedSchema(output.form, capabilities)
|
||||
if (!requestedSchema) return yield* ACPElicitation.cancel(input.client, output.form)
|
||||
const settled = yield* Deferred.make<void>()
|
||||
subscription.forms.set(output.form.id, settled)
|
||||
yield* Queue.offer(
|
||||
subscription.asks,
|
||||
ACPElicitation.reply(
|
||||
{
|
||||
client: input.client,
|
||||
connection: input.connection,
|
||||
form: output.form,
|
||||
requestedSchema,
|
||||
clientSessionID: ctx.sessionID,
|
||||
child: output.child,
|
||||
toolCallSent: output.toolCallSent,
|
||||
settled: Deferred.await(settled),
|
||||
},
|
||||
Deferred.await(subscription.cancelled),
|
||||
),
|
||||
)
|
||||
})
|
||||
case "FormSettled":
|
||||
return Effect.suspend(() => {
|
||||
const settled = subscription.forms.get(output.formID)
|
||||
subscription.forms.delete(output.formID)
|
||||
return settled ? Deferred.succeed(settled, undefined) : Effect.void
|
||||
})
|
||||
return Queue.offer(subscription.permissions, reply(subscription, ctx, output)).pipe(Effect.asVoid)
|
||||
case "FormCancel":
|
||||
return Effect.tryPromise(() =>
|
||||
input.client.session.form.cancel({ sessionID: output.sessionID, formID: output.formID }),
|
||||
).pipe(Effect.catch(() => interruptServer(output.sessionID)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +168,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
yield* Ref.set(state, next.state)
|
||||
yield* Effect.forEach(next.outputs, (output) => interpret(subscription, ctx, output), { discard: true })
|
||||
if (next.terminal) {
|
||||
yield* asksSettled(subscription)
|
||||
yield* permissionsSettled(subscription)
|
||||
return next.terminal
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,468 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { AnyMessage, AnyRequest, CreateElicitationResponse } from "@agentclientprotocol/sdk"
|
||||
import { ACPElicitation } from "../../src/acp/elicitation"
|
||||
import {
|
||||
childCreated,
|
||||
delivered,
|
||||
durableEvent,
|
||||
ephemeralEvent,
|
||||
interrupted,
|
||||
startSession,
|
||||
succeeded,
|
||||
textDelta,
|
||||
toolStarted,
|
||||
toolSucceeded,
|
||||
} from "./wire-fixture"
|
||||
|
||||
const questions = (sessionID: string, id = "frm_question", tool = "call_question") =>
|
||||
ephemeralEvent("form.created", {
|
||||
form: {
|
||||
id,
|
||||
sessionID,
|
||||
title: "Questions",
|
||||
metadata: { kind: "question", tool: { messageID: "msg_tools", id: tool } },
|
||||
fields: [
|
||||
{
|
||||
key: "q0",
|
||||
title: "Runtime",
|
||||
description: "Which runtime?",
|
||||
type: "string",
|
||||
options: [
|
||||
{ value: "Bun", label: "Bun", description: "Fast" },
|
||||
{ value: "Node", label: "Node", description: "Stable" },
|
||||
],
|
||||
custom: true,
|
||||
},
|
||||
{
|
||||
key: "q1",
|
||||
title: "Goals",
|
||||
description: "What matters?",
|
||||
type: "multiselect",
|
||||
options: [{ value: "Fast", label: "Fast", description: "Speed" }],
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const capable = { childSessionUpdates: false, formElicitation: true }
|
||||
|
||||
const form = (
|
||||
fields: ACPElicitation.AskedForm["fields"],
|
||||
metadata: ACPElicitation.AskedForm["metadata"] = { kind: "question" },
|
||||
) => ({ id: "frm_test", sessionID: "ses_test", title: "Test", metadata, fields })
|
||||
|
||||
const accept = (content: Record<string, string | number | boolean | string[]>): CreateElicitationResponse => ({
|
||||
action: "accept",
|
||||
content,
|
||||
})
|
||||
|
||||
const pendingUntilAborted = (_request: unknown, signal: AbortSignal) =>
|
||||
new Promise<CreateElicitationResponse>((resolve) => {
|
||||
signal.addEventListener("abort", () => resolve({ action: "cancel" }), { once: true })
|
||||
})
|
||||
|
||||
const firstElicitationCancel = (received: readonly AnyMessage[]): AnyMessage => {
|
||||
const asked = received.find(
|
||||
(message): message is AnyRequest =>
|
||||
"method" in message && "id" in message && message.method === "elicitation/create",
|
||||
)
|
||||
return { jsonrpc: "2.0", method: "$/cancel_request", params: { requestId: asked?.id } }
|
||||
}
|
||||
|
||||
describe("acp elicitation mapping", () => {
|
||||
test("maps every representable field type", () => {
|
||||
expect(
|
||||
ACPElicitation.requestedSchema(
|
||||
form([
|
||||
{
|
||||
key: "email",
|
||||
title: "Email",
|
||||
description: "Work address",
|
||||
type: "string",
|
||||
format: "email",
|
||||
maxLength: 80,
|
||||
pattern: ".+@.+",
|
||||
placeholder: "you@example.com",
|
||||
default: "a@b.co",
|
||||
required: true,
|
||||
},
|
||||
{ key: "name", type: "string", minLength: 2 },
|
||||
{
|
||||
key: "plan",
|
||||
type: "string",
|
||||
options: [
|
||||
{ value: "pro", label: "Pro", description: "Paid" },
|
||||
{ value: "free", label: "Free" },
|
||||
],
|
||||
default: "free",
|
||||
},
|
||||
{ key: "ratio", type: "number", minimum: 0, maximum: 1, default: 0.5 },
|
||||
{ key: "count", type: "integer", minimum: 1, required: true },
|
||||
{ key: "confirm", type: "boolean", default: false },
|
||||
{
|
||||
key: "tags",
|
||||
type: "multiselect",
|
||||
options: [
|
||||
{ value: "a", label: "A" },
|
||||
{ value: "b", label: "B" },
|
||||
],
|
||||
maxItems: 2,
|
||||
default: ["a"],
|
||||
required: true,
|
||||
},
|
||||
{ key: "server", type: "string", format: "uri", hidden: true, default: "https://example.com" },
|
||||
]),
|
||||
capable,
|
||||
),
|
||||
).toEqual({
|
||||
type: "object",
|
||||
properties: {
|
||||
email: {
|
||||
type: "string",
|
||||
title: "Email",
|
||||
description: "Work address",
|
||||
format: "email",
|
||||
minLength: 1,
|
||||
maxLength: 80,
|
||||
pattern: ".+@.+",
|
||||
default: "a@b.co",
|
||||
},
|
||||
name: { type: "string", minLength: 2 },
|
||||
plan: {
|
||||
type: "string",
|
||||
oneOf: [
|
||||
{ const: "pro", title: "Pro", description: "Paid" },
|
||||
{ const: "free", title: "Free" },
|
||||
],
|
||||
default: "free",
|
||||
},
|
||||
ratio: { type: "number", minimum: 0, maximum: 1, default: 0.5 },
|
||||
count: { type: "integer", minimum: 1 },
|
||||
confirm: { type: "boolean", default: false },
|
||||
tags: {
|
||||
type: "array",
|
||||
items: {
|
||||
anyOf: [
|
||||
{ const: "a", title: "A" },
|
||||
{ const: "b", title: "B" },
|
||||
],
|
||||
},
|
||||
minItems: 1,
|
||||
maxItems: 2,
|
||||
default: ["a"],
|
||||
},
|
||||
},
|
||||
required: ["email", "count", "tags"],
|
||||
})
|
||||
})
|
||||
|
||||
test("adds a free-text property next to options that accept a custom answer", () => {
|
||||
expect(
|
||||
ACPElicitation.requestedSchema(
|
||||
form([
|
||||
{
|
||||
key: "q0",
|
||||
title: "Runtime",
|
||||
type: "string",
|
||||
options: [{ value: "Bun", label: "Bun" }],
|
||||
custom: true,
|
||||
maxLength: 20,
|
||||
},
|
||||
{ key: "q1", type: "multiselect", options: [{ value: "Fast", label: "Fast" }], custom: true },
|
||||
]),
|
||||
capable,
|
||||
)?.properties,
|
||||
).toEqual({
|
||||
q0: { type: "string", title: "Runtime", oneOf: [{ const: "Bun", title: "Bun" }] },
|
||||
q0_custom: { type: "string", title: "Runtime (other)", description: "Type your own answer", maxLength: 20 },
|
||||
q1: { type: "array", items: { anyOf: [{ const: "Fast", title: "Fast" }] } },
|
||||
q1_custom: { type: "string", title: "q1 (other)", description: "Add your own answer" },
|
||||
})
|
||||
})
|
||||
|
||||
test("cancels forms from unsupported clients, unknown flows, and credential-looking fields", () => {
|
||||
const fields: ACPElicitation.AskedForm["fields"] = [{ key: "name", type: "string" }]
|
||||
expect(ACPElicitation.requestedSchema(form(fields), { ...capable, formElicitation: false })).toBeUndefined()
|
||||
expect(ACPElicitation.requestedSchema(form(fields, { kind: "mcp-elicitation" }), capable)).toBeUndefined()
|
||||
expect(ACPElicitation.requestedSchema(form(fields, {}), capable)).toBeUndefined()
|
||||
expect(ACPElicitation.requestedSchema(form(fields, { kind: "websearch.provider" }), capable)).toBeDefined()
|
||||
const credentials: Array<ACPElicitation.AskedForm["fields"]> = [
|
||||
[{ key: "api_key", type: "string" }],
|
||||
[{ key: "q0", title: "GitHub token", type: "string" }],
|
||||
[{ key: "q0", title: "Password", type: "string", hidden: true, default: "" }],
|
||||
]
|
||||
expect(credentials.map((fields) => ACPElicitation.requestedSchema(form(fields), capable))).toEqual(
|
||||
credentials.map(() => undefined),
|
||||
)
|
||||
})
|
||||
|
||||
test("cancels forms it cannot represent faithfully", () => {
|
||||
const options = [{ value: "a", label: "A" }]
|
||||
const unrepresentable: Array<ACPElicitation.AskedForm["fields"]> = [
|
||||
[
|
||||
{ key: "mode", type: "boolean" },
|
||||
{ key: "detail", type: "string", when: [{ key: "mode", op: "eq", value: true }] },
|
||||
],
|
||||
[
|
||||
{ key: "mode", type: "boolean" },
|
||||
{ key: "detail", type: "string", hidden: true, default: "x", when: [{ key: "mode", op: "eq", value: true }] },
|
||||
],
|
||||
[{ key: "login", type: "external", url: "https://example.com/login" }],
|
||||
[{ key: "server", type: "string", hidden: true, required: true }],
|
||||
[{ key: "pick", type: "string", options, custom: true, required: true }],
|
||||
[{ key: "pick", type: "multiselect", options, custom: true, maxItems: 1 }],
|
||||
[{ key: "pick", type: "string", options, default: "b" }],
|
||||
[{ key: "pick", type: "multiselect", options, default: ["a", "b"] }],
|
||||
[
|
||||
{ key: "pick", type: "string", options, custom: true },
|
||||
{ key: "pick_custom", type: "string" },
|
||||
],
|
||||
]
|
||||
expect(unrepresentable.map((fields) => ACPElicitation.requestedSchema(form(fields), capable))).toEqual(
|
||||
unrepresentable.map(() => undefined),
|
||||
)
|
||||
expect(
|
||||
ACPElicitation.requestedSchema(
|
||||
form([
|
||||
{ key: "name", type: "string" },
|
||||
{ key: "pick", type: "string", options, default: "b", hidden: true },
|
||||
]),
|
||||
capable,
|
||||
)?.properties,
|
||||
).toEqual({ name: { type: "string" } })
|
||||
})
|
||||
|
||||
test("maps an accepted response back to answers", () => {
|
||||
const options = [{ value: "a", label: "A" }]
|
||||
const fields: ACPElicitation.AskedForm["fields"] = [
|
||||
{ key: "single", type: "string", options, custom: true },
|
||||
{ key: "multi", type: "multiselect", options, custom: true },
|
||||
{ key: "blank", type: "string", options, custom: true },
|
||||
{ key: "count", type: "integer" },
|
||||
{ key: "server", type: "string", hidden: true, default: "https://example.com" },
|
||||
{ key: "region", type: "string", hidden: true },
|
||||
]
|
||||
expect(
|
||||
ACPElicitation.answer(
|
||||
form(fields),
|
||||
accept({
|
||||
single: "a",
|
||||
single_custom: "typed",
|
||||
multi: ["a"],
|
||||
multi_custom: "extra",
|
||||
blank: "a",
|
||||
blank_custom: " ",
|
||||
count: 3,
|
||||
server: "https://other.example.com",
|
||||
unknown: true,
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
single: "typed",
|
||||
multi: ["a", "extra"],
|
||||
blank: "a",
|
||||
count: 3,
|
||||
server: "https://example.com",
|
||||
})
|
||||
expect(ACPElicitation.answer(form(fields), accept({ multi_custom: "only" }))).toEqual({
|
||||
multi: ["only"],
|
||||
server: "https://example.com",
|
||||
})
|
||||
expect(ACPElicitation.answer(form(fields), { action: "accept" })).toEqual({ server: "https://example.com" })
|
||||
})
|
||||
|
||||
test("has no answer unless the user accepted valid content", () => {
|
||||
const fields: ACPElicitation.AskedForm["fields"] = [{ key: "name", type: "string" }]
|
||||
expect(ACPElicitation.answer(form(fields), { action: "decline" })).toBeUndefined()
|
||||
expect(ACPElicitation.answer(form(fields), { action: "cancel" })).toBeUndefined()
|
||||
expect(ACPElicitation.answer(form(fields), { action: "_custom" })).toBeUndefined()
|
||||
expect(
|
||||
ACPElicitation.answer(form(fields), { action: "accept", content: { name: { nested: true } } }),
|
||||
).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe("acp elicitation over the wire", () => {
|
||||
test("answers a question form through elicitation and continues the turn", async () => {
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true },
|
||||
onPrompt: ({ sessionID, id }) => [
|
||||
delivered(sessionID, id),
|
||||
toolStarted(sessionID, "call_question", "question"),
|
||||
questions(sessionID),
|
||||
],
|
||||
elicitation: () => accept({ q0: "Bun", q1: ["Fast"], q1_custom: "Small" }),
|
||||
onFormReply: ({ sessionID, formID }) => [
|
||||
ephemeralEvent("form.replied", { sessionID, id: formID, answer: {} }),
|
||||
toolSucceeded(sessionID, "call_question", {}, "answered"),
|
||||
textDelta(sessionID, "msg_after", "thanks"),
|
||||
succeeded(sessionID),
|
||||
],
|
||||
})
|
||||
|
||||
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
|
||||
expect(acp.elicitations).toMatchObject([
|
||||
{ mode: "form", sessionId: acp.sessionId, toolCallId: "call_question", message: "Questions" },
|
||||
])
|
||||
expect(acp.server.repliedForms).toEqual([
|
||||
{ sessionID: acp.sessionId, formID: "frm_question", answer: { q0: "Bun", q1: ["Fast", "Small"] } },
|
||||
])
|
||||
expect(acp.server.cancelledForms).toEqual([])
|
||||
expect(acp.updates.some((item) => item.update.sessionUpdate === "agent_message_chunk")).toBe(true)
|
||||
})
|
||||
|
||||
test("cancels the form when the client declines, cancels, fails, or sends a wrong value type", async () => {
|
||||
const responses: Array<() => CreateElicitationResponse> = [
|
||||
() => ({ action: "decline" }),
|
||||
() => ({ action: "cancel" }),
|
||||
() => {
|
||||
throw new Error("elicitation UI failed")
|
||||
},
|
||||
() => ({ action: "accept", content: { q0: { nested: true } } }),
|
||||
]
|
||||
const ids = ["frm_decline", "frm_cancel", "frm_fail", "frm_invalid"]
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true },
|
||||
onPrompt: ({ sessionID, id }) => [delivered(sessionID, id), ...ids.map((form) => questions(sessionID, form))],
|
||||
elicitation: () => responses[acp.elicitations.length - 1](),
|
||||
onFormCancel: ({ sessionID }) => (acp.server.cancelledForms.length === ids.length ? [succeeded(sessionID)] : []),
|
||||
})
|
||||
|
||||
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
|
||||
expect(acp.elicitations).toHaveLength(ids.length)
|
||||
expect(acp.server.cancelledForms.map((item) => item.formID)).toEqual(ids)
|
||||
expect(acp.server.repliedForms).toEqual([])
|
||||
expect(acp.server.interrupts).toEqual([])
|
||||
})
|
||||
|
||||
test("cancels forms outside the allowed flows without asking", async () => {
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true },
|
||||
onPrompt: ({ sessionID, id }) => [
|
||||
delivered(sessionID, id),
|
||||
ephemeralEvent("form.created", {
|
||||
form: {
|
||||
id: "frm_plugin",
|
||||
sessionID,
|
||||
title: "Plugin",
|
||||
metadata: { kind: "plugin" },
|
||||
fields: [{ key: "name", type: "string" }],
|
||||
},
|
||||
}),
|
||||
],
|
||||
onFormCancel: ({ sessionID }) => [succeeded(sessionID)],
|
||||
})
|
||||
|
||||
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
|
||||
expect(acp.elicitations).toEqual([])
|
||||
expect(acp.server.cancelledForms).toEqual([{ sessionID: acp.sessionId, formID: "frm_plugin" }])
|
||||
})
|
||||
|
||||
test("cancelling the turn cancels its pending elicitation and the form, and never sends queued ones", async () => {
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true },
|
||||
onPrompt: ({ sessionID, id }) => [
|
||||
delivered(sessionID, id),
|
||||
questions(sessionID, "frm_pending"),
|
||||
questions(sessionID, "frm_queued"),
|
||||
],
|
||||
onInterrupt: ({ sessionID }) => [interrupted(sessionID)],
|
||||
elicitation: pendingUntilAborted,
|
||||
})
|
||||
|
||||
const prompt = acp.prompt(acp.sessionId, "hello")
|
||||
await acp.until(() => acp.elicitations.length === 1, "elicitation request")
|
||||
await acp.notify("session/cancel", { sessionId: acp.sessionId })
|
||||
|
||||
expect(await prompt).toMatchObject({ stopReason: "cancelled" })
|
||||
await acp.until(() => acp.server.cancelledForms.length === 2, "form cancellation")
|
||||
expect(acp.elicitations).toHaveLength(1)
|
||||
expect(acp.server.cancelledForms.map((item) => item.formID)).toEqual(["frm_pending", "frm_queued"])
|
||||
expect(acp.server.repliedForms).toEqual([])
|
||||
expect(acp.received).toContainEqual(firstElicitationCancel(acp.received))
|
||||
})
|
||||
|
||||
test("withdraws an elicitation for a form settled elsewhere and moves on to the next ask", async () => {
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true },
|
||||
onPrompt: ({ sessionID, id }) => [delivered(sessionID, id), questions(sessionID, "frm_elsewhere")],
|
||||
elicitation: (request, signal) =>
|
||||
acp.elicitations.length === 1 ? pendingUntilAborted(request, signal) : accept({ q0: "Node" }),
|
||||
onFormReply: ({ sessionID }) => [succeeded(sessionID)],
|
||||
})
|
||||
|
||||
const prompt = acp.prompt(acp.sessionId, "hello")
|
||||
await acp.until(() => acp.elicitations.length === 1, "elicitation request")
|
||||
acp.server.send(
|
||||
ephemeralEvent("form.replied", { sessionID: acp.sessionId, id: "frm_elsewhere", answer: { q0: "Bun" } }),
|
||||
questions(acp.sessionId, "frm_next"),
|
||||
)
|
||||
|
||||
expect((await prompt).stopReason).toBe("end_turn")
|
||||
expect(acp.received).toContainEqual(firstElicitationCancel(acp.received))
|
||||
expect(acp.elicitations).toHaveLength(2)
|
||||
expect(acp.server.repliedForms).toEqual([{ sessionID: acp.sessionId, formID: "frm_next", answer: { q0: "Node" } }])
|
||||
expect(acp.server.cancelledForms).toEqual([])
|
||||
expect(acp.server.interrupts).toEqual([])
|
||||
})
|
||||
|
||||
test("leaves the session alone when the user's answer arrives after the form settled", async () => {
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true },
|
||||
onPrompt: ({ sessionID, id }) => [delivered(sessionID, id), questions(sessionID)],
|
||||
elicitation: () => accept({ q0: "Bun" }),
|
||||
fetch: (request) => {
|
||||
if (!request.path.endsWith("/form/frm_question/reply")) return undefined
|
||||
acp.server.send(succeeded(acp.sessionId))
|
||||
return Response.json(
|
||||
{ _tag: "FormAlreadySettledError", id: "frm_question", message: "Form already settled: frm_question" },
|
||||
{ status: 409 },
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
|
||||
expect(acp.server.requests.filter((request) => request.path.endsWith("/reply"))).toHaveLength(1)
|
||||
expect(acp.server.cancelledForms).toEqual([])
|
||||
expect(acp.server.interrupts).toEqual([])
|
||||
})
|
||||
|
||||
test("prefixes a foreground child form's tool call and message with the child", async () => {
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true },
|
||||
onPrompt: ({ sessionID, id }) => [
|
||||
delivered(sessionID, id),
|
||||
childCreated("ses_child", sessionID, "Review code"),
|
||||
durableEvent("session.execution.started", { sessionID: "ses_child" }),
|
||||
questions("ses_child", "frm_child", "call_child"),
|
||||
],
|
||||
elicitation: () => accept({ q0: "Node" }),
|
||||
onFormReply: ({ sessionID }) => [succeeded(sessionID), succeeded(acp.sessionId)],
|
||||
})
|
||||
|
||||
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
|
||||
expect(acp.elicitations).toMatchObject([
|
||||
{ sessionId: acp.sessionId, toolCallId: "ses_child:call_child", message: "Review code: Questions" },
|
||||
])
|
||||
expect(acp.server.repliedForms).toEqual([{ sessionID: "ses_child", formID: "frm_child", answer: { q0: "Node" } }])
|
||||
})
|
||||
|
||||
test("omits the tool call when the child's tool calls only reach the client as child updates", async () => {
|
||||
await using acp = await startSession({
|
||||
capabilities: { elicitation: true, childSessionUpdates: true },
|
||||
onPrompt: ({ sessionID, id }) => [
|
||||
delivered(sessionID, id),
|
||||
childCreated("ses_child", sessionID, "Review code"),
|
||||
questions("ses_child", "frm_child", "call_child"),
|
||||
],
|
||||
elicitation: () => accept({ q0: "Node" }),
|
||||
onFormReply: ({ sessionID }) => [succeeded(sessionID), succeeded(acp.sessionId)],
|
||||
})
|
||||
|
||||
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
|
||||
expect(acp.elicitations).toHaveLength(1)
|
||||
expect(acp.elicitations[0]).toMatchObject({ sessionId: acp.sessionId, message: "Review code: Questions" })
|
||||
expect(acp.elicitations[0]).not.toHaveProperty("toolCallId")
|
||||
})
|
||||
})
|
||||
@@ -364,7 +364,6 @@ describe("acp turn events over the wire", () => {
|
||||
|
||||
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
|
||||
expect(acp.server.cancelledForms).toEqual([{ sessionID: acp.sessionId, formID: "frm_question" }])
|
||||
expect(acp.elicitations).toEqual([])
|
||||
})
|
||||
|
||||
test("reports locations for native edit, write, and patch tools (https://github.com/anomalyco/opencode/issues/49591)", async () => {
|
||||
|
||||
@@ -9,8 +9,6 @@ import {
|
||||
type AgentRequestResponsesByMethod,
|
||||
type AnyMessage,
|
||||
type ContentBlock,
|
||||
type CreateElicitationRequest,
|
||||
type CreateElicitationResponse,
|
||||
type McpServer,
|
||||
type RequestPermissionRequest,
|
||||
type RequestPermissionResponse,
|
||||
@@ -29,7 +27,6 @@ import {
|
||||
type SessionMessageInfo,
|
||||
type TokenUsageInfo,
|
||||
} from "@opencode/client/promise"
|
||||
import { Form } from "@opencode/schema/form"
|
||||
import type { BunRequest } from "bun"
|
||||
import { Duration, Effect, Exit, Logger, Option, Schema, Scope } from "effect"
|
||||
import { ACP } from "../../src/acp/agent"
|
||||
@@ -67,7 +64,6 @@ const ModelBody = Schema.Struct({
|
||||
})
|
||||
const AgentBody = Schema.Struct({ agent: Schema.String })
|
||||
const ReplyBody = Schema.Struct({ decision: Schema.Literals(["once", "always", "reject"]) })
|
||||
const FormReplyBody = Schema.Struct({ answer: Form.Answer })
|
||||
const McpBody = Schema.Struct({ config: Schema.Unknown })
|
||||
const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown))
|
||||
|
||||
@@ -122,24 +118,13 @@ export type WireOptions = {
|
||||
readonly decision: string
|
||||
}>
|
||||
readonly onFormCancel?: Hook<{ readonly sessionID: string; readonly formID: string }>
|
||||
readonly onFormReply?: Hook<FormReply>
|
||||
readonly permission?: (
|
||||
request: RequestPermissionRequest,
|
||||
signal: AbortSignal,
|
||||
) => RequestPermissionResponse | Promise<RequestPermissionResponse>
|
||||
readonly elicitation?: (
|
||||
request: CreateElicitationRequest,
|
||||
signal: AbortSignal,
|
||||
) => CreateElicitationResponse | Promise<CreateElicitationResponse>
|
||||
readonly cancelDrainTimeout?: Duration.Input
|
||||
}
|
||||
|
||||
type FormReply = {
|
||||
readonly sessionID: string
|
||||
readonly formID: string
|
||||
readonly answer: typeof FormReplyBody.Type.answer
|
||||
}
|
||||
|
||||
type CatalogKind = "model" | "default" | "agent" | "command"
|
||||
|
||||
export type Catalog = {
|
||||
@@ -154,7 +139,6 @@ export type InitializeOptions = {
|
||||
readonly writeTextFile?: boolean
|
||||
readonly childSessionUpdates?: boolean
|
||||
readonly terminalAuth?: boolean
|
||||
readonly elicitation?: boolean
|
||||
}
|
||||
|
||||
export const testModel = {
|
||||
@@ -385,7 +369,6 @@ export async function startWire(options: WireOptions = {}) {
|
||||
const permissions: RequestPermissionRequest[] = []
|
||||
const writes: WriteTextFileRequest[] = []
|
||||
const childUpdates: ChildUpdate[] = []
|
||||
const elicitations: CreateElicitationRequest[] = []
|
||||
// Client handlers record SDK-validated params; responses wait until they have seen every earlier agent message.
|
||||
const counts = { sent: 0, handled: 0 }
|
||||
const handled = <Value>(list: Value[], value: Value) => {
|
||||
@@ -421,10 +404,6 @@ export async function startWire(options: WireOptions = {}) {
|
||||
handled(permissions, ctx.params)
|
||||
return options.permission?.(ctx.params, ctx.signal) ?? { outcome: { outcome: "cancelled" } }
|
||||
})
|
||||
.onRequest("elicitation/create", (ctx) => {
|
||||
handled(elicitations, ctx.params)
|
||||
return options.elicitation?.(ctx.params, ctx.signal) ?? { action: "cancel" }
|
||||
})
|
||||
.onRequest("fs/write_text_file", (ctx) => {
|
||||
handled(writes, ctx.params)
|
||||
return {}
|
||||
@@ -480,7 +459,6 @@ export async function startWire(options: WireOptions = {}) {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
...(capabilities.writeTextFile ? { fs: { writeTextFile: true, readTextFile: false } } : {}),
|
||||
...(capabilities.elicitation ? { elicitation: { form: {} } } : {}),
|
||||
_meta: {
|
||||
...(capabilities.childSessionUpdates ? { "opencode/child-session-updates": true } : {}),
|
||||
...(capabilities.terminalAuth ? { "terminal-auth": true } : {}),
|
||||
@@ -497,7 +475,6 @@ export async function startWire(options: WireOptions = {}) {
|
||||
permissions,
|
||||
writes,
|
||||
childUpdates,
|
||||
elicitations,
|
||||
request,
|
||||
until,
|
||||
initialize,
|
||||
@@ -557,7 +534,6 @@ function startServer(options: WireOptions, changed: () => void) {
|
||||
const interrupts: string[] = []
|
||||
const replies: Array<{ readonly sessionID: string; readonly requestID: string; readonly decision: string }> = []
|
||||
const cancelledForms: Array<{ readonly sessionID: string; readonly formID: string }> = []
|
||||
const repliedForms: FormReply[] = []
|
||||
const mcp: Array<{ readonly name: string; readonly directory?: string; readonly config: unknown }> = []
|
||||
const fake = {
|
||||
requests,
|
||||
@@ -573,7 +549,6 @@ function startServer(options: WireOptions, changed: () => void) {
|
||||
interrupts,
|
||||
replies,
|
||||
cancelledForms,
|
||||
repliedForms,
|
||||
mcp,
|
||||
send(...events: ReadonlyArray<OpenCodeEvent>) {
|
||||
events.forEach((event) => {
|
||||
@@ -812,14 +787,6 @@ function startServer(options: WireOptions, changed: () => void) {
|
||||
return noContent()
|
||||
}),
|
||||
},
|
||||
"/api/session/:sessionID/form/:formID/reply": {
|
||||
POST: body(FormReplyBody, async (req, input) => {
|
||||
const reply = { sessionID: req.params.sessionID, formID: req.params.formID, answer: input.answer }
|
||||
fake.repliedForms.push(reply)
|
||||
await emit(options.onFormReply?.(reply))
|
||||
return noContent()
|
||||
}),
|
||||
},
|
||||
"/api/experimental/mcp/:name": {
|
||||
PUT: body(McpBody, (req, input, query) => {
|
||||
fake.mcp.push({ name: req.params.name, directory: query["location[directory]"], config: input.config })
|
||||
|
||||
@@ -2,7 +2,6 @@ import { MetaProvider, Title } from "@solidjs/meta"
|
||||
import { Router } from "@solidjs/router"
|
||||
import { FileRoutes } from "@solidjs/start/router"
|
||||
import { Suspense } from "solid-js"
|
||||
import { PatternRipple } from "./component/pattern-ripple"
|
||||
import { I18nProvider, useI18n } from "./context/i18n"
|
||||
import { LanguageProvider } from "./context/language"
|
||||
import { strip } from "./lib/language"
|
||||
@@ -24,7 +23,6 @@ export default function App() {
|
||||
<I18nProvider>
|
||||
<MetaProvider>
|
||||
<AppMeta />
|
||||
<PatternRipple />
|
||||
<Suspense>{props.children}</Suspense>
|
||||
</MetaProvider>
|
||||
</I18nProvider>
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { onCleanup, onMount } from "solid-js"
|
||||
|
||||
const PATTERNS = '[data-page="stats"] [data-slot$="-pattern"]'
|
||||
const RIPPLE = {
|
||||
duration: 4400,
|
||||
brightness: 50,
|
||||
trail: 400,
|
||||
trailBody: 100,
|
||||
front: 90,
|
||||
ease: 4,
|
||||
fade: 3.3,
|
||||
reach: 1.3,
|
||||
rearm: 400,
|
||||
}
|
||||
|
||||
type Ripple = { x: number; y: number; radius: number; start: number }
|
||||
|
||||
// Plays one soft wave of light across a dot pattern when the cursor moves onto its visible dots.
|
||||
export function PatternRipple() {
|
||||
onMount(() => {
|
||||
if (matchMedia("(prefers-reduced-motion: reduce)").matches) return
|
||||
|
||||
const ripples = new Map<HTMLElement, Ripple>()
|
||||
const leftAt = new WeakMap<HTMLElement, number>()
|
||||
const state = { current: undefined as HTMLElement | undefined, primed: false, running: false }
|
||||
|
||||
const frame = (now: number) => {
|
||||
ripples.forEach((ripple, el) => {
|
||||
const progress = (now - ripple.start) / RIPPLE.duration
|
||||
if (progress >= 1) {
|
||||
ripples.delete(el)
|
||||
el.style.removeProperty("--dot-ripple")
|
||||
return
|
||||
}
|
||||
el.style.setProperty("--dot-ripple", rippleGradient(ripple, progress))
|
||||
})
|
||||
if (ripples.size > 0) return requestAnimationFrame(frame)
|
||||
state.running = false
|
||||
}
|
||||
|
||||
const start = (el: HTMLElement, clientX: number, clientY: number) => {
|
||||
const box = el.getBoundingClientRect()
|
||||
const visible = visibleBox(el)
|
||||
ripples.set(el, {
|
||||
x: clientX - box.left,
|
||||
y: clientY - box.top,
|
||||
radius: Math.hypot(
|
||||
Math.max(clientX - visible.left, visible.right - clientX),
|
||||
Math.max(clientY - visible.top, visible.bottom - clientY),
|
||||
),
|
||||
start: performance.now(),
|
||||
})
|
||||
if (state.running) return
|
||||
state.running = true
|
||||
requestAnimationFrame(frame)
|
||||
}
|
||||
|
||||
// The pattern must be the top element under the cursor, so text cut-outs over a pattern count as off the dots.
|
||||
// A cursor already resting on a pattern when the page loads does not trigger a ripple.
|
||||
const move = (event: PointerEvent) => {
|
||||
const now = performance.now()
|
||||
const hit = document.elementFromPoint(event.clientX, event.clientY)
|
||||
const el = hit instanceof HTMLElement && hit.matches(PATTERNS) ? hit : undefined
|
||||
if (el !== state.current) {
|
||||
if (state.current) leftAt.set(state.current, now)
|
||||
if (el && state.primed && now - (leftAt.get(el) ?? -Infinity) >= RIPPLE.rearm) start(el, event.clientX, event.clientY)
|
||||
state.current = el
|
||||
}
|
||||
state.primed = true
|
||||
}
|
||||
|
||||
document.addEventListener("pointermove", move, { passive: true })
|
||||
onCleanup(() => document.removeEventListener("pointermove", move))
|
||||
})
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function rippleGradient(ripple: Ripple, progress: number) {
|
||||
const r = ripple.radius * RIPPLE.reach * (1 - (1 - progress) ** RIPPLE.ease)
|
||||
const alpha = RIPPLE.brightness * (1 - progress) ** RIPPLE.fade
|
||||
const mix = (amount: number) => `color-mix(in srgb, var(--stats-text) ${amount.toFixed(1)}%, transparent)`
|
||||
const at = (offset: number) => `${Math.max(0, r + offset).toFixed(1)}px`
|
||||
return `radial-gradient(circle at ${ripple.x}px ${ripple.y}px, transparent ${at(-RIPPLE.trail)}, ${mix((alpha * RIPPLE.trailBody) / 100)} ${at(-RIPPLE.trail / 2)}, ${mix(alpha)} ${at(0)}, transparent ${at(RIPPLE.front)})`
|
||||
}
|
||||
|
||||
// Some patterns are larger than their clipping container, so the ripple only needs to reach the visible part.
|
||||
function visibleBox(el: HTMLElement) {
|
||||
const box = el.getBoundingClientRect()
|
||||
const clip = el.parentElement?.getBoundingClientRect() ?? box
|
||||
return {
|
||||
left: Math.max(box.left, clip.left),
|
||||
top: Math.max(box.top, clip.top),
|
||||
right: Math.min(box.right, clip.right),
|
||||
bottom: Math.min(box.bottom, clip.bottom),
|
||||
}
|
||||
}
|
||||
@@ -674,7 +674,7 @@ body {
|
||||
[data-page="stats"] [data-slot="footer-pattern"] {
|
||||
height: 16px;
|
||||
overflow: hidden;
|
||||
background-color: var(--stats-hero-pattern);
|
||||
background: var(--stats-hero-pattern);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: center top;
|
||||
mask-repeat: repeat;
|
||||
@@ -883,18 +883,13 @@ body {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Ripple layer drawn by PatternRipple. Pattern rules set only background-color so this layer survives. */
|
||||
[data-page="stats"] [data-slot$="-pattern"] {
|
||||
background-image: var(--dot-ripple, none);
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-slot="hero-pattern"] {
|
||||
order: 2;
|
||||
flex: 0 0 auto;
|
||||
width: 100%;
|
||||
height: 16px;
|
||||
overflow: hidden;
|
||||
background-color: var(--stats-hero-pattern);
|
||||
background: var(--stats-hero-pattern);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-repeat: repeat;
|
||||
mask-size: 6px 6px;
|
||||
@@ -1099,6 +1094,7 @@ body {
|
||||
[data-page="stats"] [data-component="top-models-chart"] {
|
||||
--top-models-bar-gap: 12px;
|
||||
--top-models-dot-size: 6px;
|
||||
--top-models-dot-offset: 2px;
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-rows: 34px minmax(0, 1fr);
|
||||
@@ -1228,36 +1224,38 @@ body {
|
||||
padding-inline: calc(var(--top-models-bar-gap) / 2);
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
/* Resolved by absolutely positioned children against this slot's width. Three 2px dot columns span the bar, so this inset makes the gap between bars equal the gap between dot columns. */
|
||||
--top-models-bar-inset: calc((100% - 6px) / 6);
|
||||
}
|
||||
|
||||
/* Three dot columns aligned to the bar's left edge, center, and right edge, so they read as rising out of the bar. The SVG has no viewBox, so the 2px dot keeps its size while the cell stretches. */
|
||||
[data-page="stats"] [data-slot="top-models-bar"]::before {
|
||||
position: absolute;
|
||||
inset: 0 var(--top-models-bar-inset);
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
width: calc(100% - var(--top-models-bar-gap));
|
||||
transform: translateX(-50%);
|
||||
content: "";
|
||||
background: var(--stats-dot);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='2' height='2'/%3E%3C/svg%3E");
|
||||
mask-position: left top;
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: var(--top-models-dot-offset) top;
|
||||
mask-repeat: repeat;
|
||||
mask-size: calc((100% - 2px) / 2) var(--top-models-dot-size);
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='2' height='2'/%3E%3C/svg%3E");
|
||||
-webkit-mask-position: left top;
|
||||
mask-size: var(--top-models-dot-size) var(--top-models-dot-size);
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
-webkit-mask-position: var(--top-models-dot-offset) top;
|
||||
-webkit-mask-repeat: repeat;
|
||||
-webkit-mask-size: calc((100% - 2px) / 2) var(--top-models-dot-size);
|
||||
transition: background-color 120ms ease;
|
||||
-webkit-mask-size: var(--top-models-dot-size) var(--top-models-dot-size);
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-slot="top-models-bar"]:is(:hover, [data-active="true"])::before {
|
||||
background: color-mix(in srgb, var(--stats-dot), var(--stats-text) 25%);
|
||||
@supports (width: round(down, 100%, 1px)) {
|
||||
[data-page="stats"] [data-slot="top-models-bar"]::before {
|
||||
width: round(down, calc(100% - var(--top-models-bar-gap)), var(--top-models-dot-size));
|
||||
}
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-slot="top-models-stack"] {
|
||||
position: absolute;
|
||||
right: var(--top-models-bar-inset);
|
||||
right: calc(var(--top-models-bar-gap) / 2);
|
||||
bottom: 0;
|
||||
left: var(--top-models-bar-inset);
|
||||
left: calc(var(--top-models-bar-gap) / 2);
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
height: var(--top-models-bar-height);
|
||||
@@ -1877,7 +1875,7 @@ body {
|
||||
height: 16px;
|
||||
margin: 16px 0;
|
||||
overflow: hidden;
|
||||
background-color: var(--stats-hero-pattern);
|
||||
background: var(--stats-hero-pattern);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: center top;
|
||||
mask-repeat: repeat;
|
||||
@@ -2878,7 +2876,7 @@ body {
|
||||
width: 100%;
|
||||
height: 18px;
|
||||
overflow: hidden;
|
||||
background-color: var(--stats-hero-pattern);
|
||||
background: var(--stats-hero-pattern);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-repeat: repeat;
|
||||
mask-size: 6px 6px;
|
||||
@@ -3018,7 +3016,7 @@ body {
|
||||
min-width: 64px;
|
||||
height: 64px;
|
||||
overflow: hidden;
|
||||
background-color: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
background: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: center top;
|
||||
mask-repeat: repeat;
|
||||
@@ -3335,7 +3333,7 @@ body {
|
||||
width: 100%;
|
||||
height: 16px;
|
||||
overflow: hidden;
|
||||
background-color: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
background: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
mask-position: center top;
|
||||
-webkit-mask-position: center top;
|
||||
}
|
||||
@@ -3482,7 +3480,7 @@ body {
|
||||
width: 100%;
|
||||
height: 16px;
|
||||
overflow: hidden;
|
||||
background-color: var(--stats-line);
|
||||
background: var(--stats-line);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: center top;
|
||||
mask-repeat: repeat;
|
||||
@@ -3956,7 +3954,7 @@ body {
|
||||
height: 16px;
|
||||
margin-bottom: 40px;
|
||||
overflow: hidden;
|
||||
background-color: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
background: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: center top;
|
||||
mask-repeat: repeat;
|
||||
@@ -4081,7 +4079,7 @@ body {
|
||||
height: 16px;
|
||||
margin-bottom: 40px;
|
||||
overflow: hidden;
|
||||
background-color: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
background: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: center top;
|
||||
mask-repeat: repeat;
|
||||
@@ -4547,6 +4545,7 @@ body {
|
||||
[data-page="stats"] [data-component="model-usage-chart"] {
|
||||
--model-usage-bar-gap: 6px;
|
||||
--model-usage-dot-size: 6px;
|
||||
--model-usage-dot-offset: 2px;
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-rows: 40px minmax(0, 1fr);
|
||||
@@ -4604,36 +4603,38 @@ body {
|
||||
padding-inline: calc(var(--model-usage-bar-gap) / 2);
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
/* Resolved by absolutely positioned children against this slot's width. Three 2px dot columns span the bar, so this inset makes the gap between bars equal the gap between dot columns. */
|
||||
--model-usage-bar-inset: calc((100% - 6px) / 6);
|
||||
}
|
||||
|
||||
/* Three dot columns aligned to the bar's left edge, center, and right edge, so they read as rising out of the bar. The SVG has no viewBox, so the 2px dot keeps its size while the cell stretches. */
|
||||
[data-page="stats"] [data-slot="model-usage-column"]::before {
|
||||
position: absolute;
|
||||
inset: 0 var(--model-usage-bar-inset);
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
width: calc(100% - var(--model-usage-bar-gap));
|
||||
transform: translateX(-50%);
|
||||
content: "";
|
||||
background: var(--stats-dot);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='2' height='2'/%3E%3C/svg%3E");
|
||||
mask-position: left top;
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: var(--model-usage-dot-offset) top;
|
||||
mask-repeat: repeat;
|
||||
mask-size: calc((100% - 2px) / 2) var(--model-usage-dot-size);
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='2' height='2'/%3E%3C/svg%3E");
|
||||
-webkit-mask-position: left top;
|
||||
mask-size: var(--model-usage-dot-size) var(--model-usage-dot-size);
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
-webkit-mask-position: var(--model-usage-dot-offset) top;
|
||||
-webkit-mask-repeat: repeat;
|
||||
-webkit-mask-size: calc((100% - 2px) / 2) var(--model-usage-dot-size);
|
||||
transition: background-color 120ms ease;
|
||||
-webkit-mask-size: var(--model-usage-dot-size) var(--model-usage-dot-size);
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-slot="model-usage-column"]:is(:hover, [data-active="true"])::before {
|
||||
background: color-mix(in srgb, var(--stats-dot), var(--stats-text) 25%);
|
||||
@supports (width: round(down, 100%, 1px)) {
|
||||
[data-page="stats"] [data-slot="model-usage-column"]::before {
|
||||
width: round(down, calc(100% - var(--model-usage-bar-gap)), var(--model-usage-dot-size));
|
||||
}
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-slot="model-usage-bar"] {
|
||||
position: absolute;
|
||||
right: var(--model-usage-bar-inset);
|
||||
right: calc(var(--model-usage-bar-gap) / 2);
|
||||
bottom: 0;
|
||||
left: var(--model-usage-bar-inset);
|
||||
left: calc(var(--model-usage-bar-gap) / 2);
|
||||
z-index: 1;
|
||||
height: var(--model-usage-fill);
|
||||
min-height: 0;
|
||||
@@ -5689,7 +5690,7 @@ body {
|
||||
height: 16px;
|
||||
margin-inline: -40px;
|
||||
overflow: hidden;
|
||||
background-color: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
background: color-mix(in srgb, var(--stats-text) 10%, transparent);
|
||||
mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E");
|
||||
mask-position: center top;
|
||||
mask-repeat: repeat;
|
||||
@@ -8195,8 +8196,7 @@ body {
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-component="model-usage-chart"] {
|
||||
/* 18px puts three 2px dot columns 6px apart, matching the 6px bar gap. */
|
||||
--model-usage-mobile-bar-width: 18px;
|
||||
--model-usage-mobile-bar-width: 16px;
|
||||
--model-usage-mobile-edge-space: 48px;
|
||||
--model-usage-mobile-track-width: calc(
|
||||
var(--model-usage-count) * (var(--model-usage-mobile-bar-width) + var(--model-usage-bar-gap)) +
|
||||
@@ -8237,7 +8237,7 @@ body {
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-slot="model-usage-column"]::before {
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
[data-page="stats"] [data-slot="model-usage-bar"] {
|
||||
|
||||
@@ -153,6 +153,8 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
|
||||
|
||||
const repository = createModelPreferenceRepository(path.join(paths.state, "model.json"))
|
||||
const pendingSelectionCommits = new Map<string, { agentID: string; selection: string }>()
|
||||
// Recents are shared, but an open session's fallback is local until a durable selection replaces it.
|
||||
const fallbackBySessionAgent = new Map<string, Map<string, ModelSelection>>()
|
||||
const selectionKey = (value: ModelSelection) =>
|
||||
`${modelPreferenceKey(value)}:${normalizeModelVariant(value.variant) ?? "default"}`
|
||||
|
||||
@@ -267,6 +269,7 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
|
||||
const selected = [
|
||||
selectionState.selectionBySessionAgent[sessionID]?.[current.id],
|
||||
!session?.agent || session.agent === current.id ? durableSelection(sessionID) : undefined,
|
||||
fallbackBySessionAgent.get(sessionID)?.get(current.id),
|
||||
].find((selection) => selection && isModelValid(selection))
|
||||
if (selected) {
|
||||
const info = models()?.find((item) => item.providerID === selected.providerID && item.id === selected.modelID)
|
||||
@@ -276,7 +279,12 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
|
||||
}
|
||||
}
|
||||
const model = newSessionModel()
|
||||
return model && preferredSelection(model)
|
||||
if (!model) return
|
||||
const fallback = preferredSelection(model)
|
||||
const byAgent = fallbackBySessionAgent.get(sessionID) ?? new Map<string, ModelSelection>()
|
||||
byAgent.set(current.id, fallback)
|
||||
fallbackBySessionAgent.set(sessionID, byAgent)
|
||||
return fallback
|
||||
}
|
||||
|
||||
function setSessionSelection(sessionID: string, agentID: string, selection: ModelSelection | undefined) {
|
||||
@@ -344,6 +352,7 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
|
||||
onCleanup(
|
||||
event.on("session.deleted", (evt) => {
|
||||
pendingSelectionCommits.delete(evt.data.sessionID)
|
||||
fallbackBySessionAgent.delete(evt.data.sessionID)
|
||||
setSelectionState("selectionBySessionAgent", evt.data.sessionID, undefined)
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { agent, model, renderLocal, session } from "../fixture/local"
|
||||
import { json } from "../fixture/tui-client"
|
||||
import { createModelPreferenceRepository } from "../../src/model-preference"
|
||||
import path from "node:path"
|
||||
|
||||
test("cycles all recent models in a stable order in both directions", async () => {
|
||||
await using setup = await renderLocal({
|
||||
@@ -80,6 +82,34 @@ test("agent and model drafts are isolated across sessions and survive navigation
|
||||
expect(setup.local.model.selection()).toEqual({ providerID: "provider", modelID: "first", variant: "low" })
|
||||
})
|
||||
|
||||
test("a model selected in another instance updates recents without changing this session's model", async () => {
|
||||
await using setup = await renderLocal({
|
||||
models: [model("first", ["high"]), model("second")],
|
||||
preferences: { recent: [{ providerID: "provider", modelID: "first" }] },
|
||||
sessions: [session("ses_first"), session("ses_second")],
|
||||
fetch: selectionMessage,
|
||||
})
|
||||
await Promise.all([setup.data.session.sync("ses_first"), setup.data.session.sync("ses_second")])
|
||||
setup.route.navigate({ type: "session", sessionID: "ses_first" })
|
||||
expect(setup.local.model.selection()).toEqual({ providerID: "provider", modelID: "first", variant: undefined })
|
||||
|
||||
const repository = createModelPreferenceRepository(path.join(setup.state, "model.json"))
|
||||
await repository.addRecent({ providerID: "provider", modelID: "second" })
|
||||
await repository.setFavorite({ providerID: "provider", modelID: "second" }, true)
|
||||
await repository.saveVariant({ providerID: "provider", modelID: "first" }, "high")
|
||||
for (let i = 0; i < 100 && setup.local.model.recent()[0]?.modelID !== "second"; i++) await Bun.sleep(10)
|
||||
expect(setup.local.model.recent()[0]?.modelID).toBe("second")
|
||||
expect(setup.local.model.favorite()[0]?.modelID).toBe("second")
|
||||
expect(setup.local.model.selection()).toEqual({ providerID: "provider", modelID: "first", variant: undefined })
|
||||
|
||||
setup.route.navigate({ type: "session", sessionID: "ses_second" })
|
||||
expect(setup.local.model.current()?.modelID).toBe("second")
|
||||
setup.route.navigate({ type: "session", sessionID: "ses_first" })
|
||||
expect(setup.local.model.current()?.modelID).toBe("first")
|
||||
await publishSelection(setup, "build", "second")
|
||||
expect(setup.local.model.current()?.modelID).toBe("second")
|
||||
})
|
||||
|
||||
test("falls back from an unavailable session model without changing durable state", async () => {
|
||||
const selected = { providerID: "provider", id: "missing", variant: "high" }
|
||||
await using setup = await renderLocal({
|
||||
|
||||
Reference in new issue
Block a user