Show OpenCode choice questions in chat (#38872)

* Show OpenCode choice questions in chat

* Preserve form replies for omitted fields and cover rendered questions

* Keep cross-process form tests out of renderer typecheck
This commit is contained in:
Brennan Benson
2026-11-06 02:13:58 -08:00
committed by GitHub
parent 2648941358
commit b3b97d8068
11 changed files with 551 additions and 59 deletions
+1
View File
@@ -1,6 +1,7 @@
{
"extends": "./tsconfig.web.json",
"exclude": [
"../src/renderer/src/components/native-chat/NativeChatAcpQuestionCard.test.tsx",
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
"../src/renderer/src/components/terminal-pane/pty-agent-pane-launch.test.ts",
"../src/renderer/src/components/github-item-dialog/load-item-details/work-item-details-target-contract.test.tsx",
+1
View File
@@ -1,6 +1,7 @@
{
"extends": "./tsconfig.web.json",
"include": [
"../src/renderer/src/components/native-chat/NativeChatAcpQuestionCard.test.tsx",
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
"../src/renderer/src/components/terminal-pane/pty-agent-pane-launch.test.ts",
+1
View File
@@ -11,6 +11,7 @@
"../src/shared/**/*"
],
"exclude": [
"../src/renderer/src/components/native-chat/NativeChatAcpQuestionCard.test.tsx",
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
"../src/renderer/src/components/terminal-pane/pty-agent-pane-launch.test.ts",
"../src/renderer/src/components/github-item-dialog/load-item-details/work-item-details-target-contract.test.tsx",
@@ -102,6 +102,7 @@ function normalizeToolUpdate(update: ToolCallUpdate): ToolCallUpdate {
}
export const OPENCODE_ACP_DIALECT: AcpDialect = {
clientCapabilities: { elicitation: { form: {} } },
effortChangesModel: true,
normalizeToolUpdate,
promptFailure
+15 -41
View File
@@ -1,44 +1,8 @@
import { describe, expect, it } from 'vitest'
import { acpFormElicitationPresentation } from './acp-form-elicitation'
import { recordedOmpAskForm as ask } from './acp-omp-ask-form.test-fixture'
describe('OMP ask forms', () => {
// Verbatim `elicitation/create` from OMP 18.16.0's `ask` with three questions.
const ask = {
mode: 'form',
sessionId: 'session-1',
message: 'Answer 3 questions',
requestedSchema: {
type: 'object',
properties: {
q0: {
type: 'string',
title: 'Which database?',
description: 'DB',
oneOf: [
{ const: 'Postgres', title: 'Postgres', description: 'relational' },
{ const: 'SQLite', title: 'SQLite' },
{ const: 'Mongo', title: 'Mongo' }
],
default: 'SQLite'
},
q0__other: { type: 'string', title: 'Other (type your own)' },
q1: {
type: 'array',
title: 'Which features?',
items: {
anyOf: [
{ const: 'Auth', title: 'Auth' },
{ const: 'Billing', title: 'Billing' },
{ const: 'Search', title: 'Search' }
]
}
},
q1__other: { type: 'string', title: 'Other (type your own)' },
q2__other: { type: 'string', title: 'Other (type your own)' }
}
}
}
it('asks every question on one card and answers in the form OMP reads', () => {
const presentation = acpFormElicitationPresentation(ask)
expect(presentation.body).toMatchObject({
@@ -46,8 +10,8 @@ describe('OMP ask forms', () => {
questions: [
{
id: 'q1',
question: 'Which database?',
header: 'DB',
question: 'Answer 3 questions\n\nWhich database?\n\nDB',
header: 'Which database?',
multiSelect: false,
options: [
{ id: 'o1', label: 'Postgres', description: 'relational' },
@@ -56,8 +20,18 @@ describe('OMP ask forms', () => {
],
freeTextQuestionId: 'q1'
},
{ id: 'q2', question: 'Which features?', multiSelect: true, freeTextQuestionId: 'q2' },
{ id: 'q3', question: 'Other (type your own)', options: [], freeTextQuestionId: 'q3' }
{
id: 'q2',
question: 'Answer 3 questions\n\nWhich features?',
multiSelect: true,
freeTextQuestionId: 'q2'
},
{
id: 'q3',
question: 'Answer 3 questions\n\nOther (type your own)',
options: [],
freeTextQuestionId: 'q3'
}
]
})
expect(
+53 -17
View File
@@ -9,8 +9,7 @@ import { pendingAcpResolution, type AcpRequestPresentation } from './acp-dialect
import { AcpRpcError } from './acp-errors'
export const ACP_FORM_ELICITATION_METHOD = 'elicitation/create'
// OMP pairs each choice field `qN` with a free-text `qN__other`.
const OTHER_SUFFIX = '__other'
const OTHER_SUFFIXES = ['__other', '_custom'] as const
const NOT_SHOWN_ANSWER = `Not shown to the user: Orca shows at most ${MAX_JOURNAL_GROUPED_PROMPT_QUESTIONS} questions at once. Ask again.`
const choiceSchema = z.looseObject({
@@ -22,6 +21,7 @@ const propertySchema = z.looseObject({
type: z.enum(['string', 'boolean', 'array']),
title: z.string().optional(),
description: z.string().optional(),
format: z.string().optional(),
default: z.unknown().optional(),
enum: z.array(z.string()).optional(),
oneOf: z.array(choiceSchema).optional(),
@@ -32,7 +32,10 @@ const propertySchema = z.looseObject({
const formSchema = z.object({
mode: z.literal('form'),
message: z.string(),
requestedSchema: z.looseObject({ properties: z.record(z.string(), propertySchema) })
requestedSchema: z.looseObject({
properties: z.record(z.string(), propertySchema),
required: z.array(z.string()).optional()
})
})
type Choice = { value: string; label: string; description?: string }
@@ -41,7 +44,10 @@ type Field = { key: string; otherKey?: string; choices?: Choice[]; question: Age
const unsupportedForm = () => new AcpRpcError(-32602, 'Unsupported ACP elicitation form')
// A form field with no choices becomes a text answer; enums and arrays become pickable options.
function fieldChoices(property: z.infer<typeof propertySchema>): Choice[] | undefined {
function fieldChoices(
property: z.infer<typeof propertySchema>,
hasOther: boolean
): Choice[] | undefined {
if (property.type === 'boolean') {
return [
{ value: 'true', label: 'Yes' },
@@ -56,13 +62,13 @@ function fieldChoices(property: z.infer<typeof propertySchema>): Choice[] | unde
label: choice.title || choice.const,
...(choice.description ? { description: choice.description } : {})
})) ?? values?.map((value) => ({ value, label: value }))
if (choices?.length === 0 || (property.type === 'array' && !choices)) {
if ((choices?.length === 0 && !hasOther) || (property.type === 'array' && !choices)) {
throw unsupportedForm()
}
return choices
}
/** Presents a form elicitation (OMP's `ask` batch, select, confirm, input) as one question card. */
/** Keeps form field identity while presenting choices and text on the existing question card. */
export function acpFormElicitationPresentation(params: unknown): AcpRequestPresentation {
const parsed = formSchema.safeParse(params)
if (!parsed.success) {
@@ -70,22 +76,46 @@ export function acpFormElicitationPresentation(params: unknown): AcpRequestPrese
}
const { message, requestedSchema } = parsed.data
const properties = requestedSchema.properties
const keys = Object.keys(properties).filter(
(key) =>
!(key.endsWith(OTHER_SUFFIX) && Object.hasOwn(properties, key.slice(0, -OTHER_SUFFIX.length)))
)
const required = new Set(requestedSchema.required)
const otherKeys = new Map<string, string>()
for (const [key, property] of Object.entries(properties)) {
if (
required.has(key) ||
(property.type !== 'string' && property.type !== 'array') ||
!(property.enum || property.oneOf || property.type === 'array')
) {
continue
}
const otherKey = OTHER_SUFFIXES.map((suffix) => key + suffix).find((candidate) => {
const other = properties[candidate]
return (
other?.type === 'string' &&
!other.enum &&
!other.oneOf &&
other.format === undefined &&
!required.has(candidate)
)
})
if (otherKey) {
otherKeys.set(key, otherKey)
}
}
const companions = new Set(otherKeys.values())
const keys = Object.keys(properties).filter((key) => !companions.has(key))
if (keys.length === 0) {
throw unsupportedForm()
}
const fields: Field[] = keys.slice(0, MAX_JOURNAL_GROUPED_PROMPT_QUESTIONS).map((key, index) => {
const property = properties[key]!
const otherKey = Object.hasOwn(properties, key + OTHER_SUFFIX) ? key + OTHER_SUFFIX : undefined
const choices = fieldChoices(property)
const otherKey = otherKeys.get(key)
const choices = fieldChoices(property, otherKey !== undefined)
const id = `q${index + 1}`
const question: AgentJournalQuestion = {
id,
question: keys.length === 1 ? message : property.title || message,
...(choices && property.description ? { header: property.description } : {}),
question: [...new Set([message, property.title, property.description].filter(Boolean))].join(
'\n\n'
),
...(property.title ? { header: property.title } : {}),
multiSelect: property.type === 'array',
options: (choices ?? []).map((choice, choiceIndex) => ({
id: `o${choiceIndex + 1}`,
@@ -112,7 +142,7 @@ export function acpFormElicitationPresentation(params: unknown): AcpRequestPrese
const first = questions.length === 1 && !questions[0]!.multiSelect ? questions[0]! : undefined
const body = {
kind: 'question' as const,
question: message,
question: first?.question ?? message,
options: first?.options ?? [],
...(first?.freeTextQuestionId ? { freeTextQuestionId: first.freeTextQuestionId } : {}),
...(first?.freeTextInput ? { freeTextInput: first.freeTextInput } : {}),
@@ -152,9 +182,15 @@ export function acpFormElicitationPresentation(params: unknown): AcpRequestPrese
}
}
for (const key of keys.slice(MAX_JOURNAL_GROUPED_PROMPT_QUESTIONS)) {
const otherKey = key.endsWith(OTHER_SUFFIX) ? key : key + OTHER_SUFFIX
if (Object.hasOwn(properties, otherKey)) {
const otherKey = otherKeys.get(key)
if (otherKey) {
content[otherKey] = NOT_SHOWN_ANSWER
} else if (
properties[key]!.type === 'string' &&
!properties[key]!.enum &&
!properties[key]!.oneOf
) {
content[key] = NOT_SHOWN_ANSWER
}
}
return { action: 'accept', content }
+1 -1
View File
@@ -213,7 +213,7 @@ function openCodeLaunchSpec(
...row,
// No bypass flag; full access approves permission requests individually.
args: () => ['acp'],
// Disable unsupported question forms: 1.x waits forever; 2.x drops them.
// 1.x cannot answer ACP questions; 2.x ignores this guard and negotiates form support.
env: { OPENCODE_CLIENT: 'acp', OPENCODE_ENABLE_QUESTION_TOOL: 'false' },
scrubEnvironment: scrubOpenCodeAcpEnvironment,
dialect: OPENCODE_ACP_DIALECT,
@@ -0,0 +1,36 @@
// Verbatim `elicitation/create` from OMP 18.16.0's `ask` with three questions.
export const recordedOmpAskForm = {
mode: 'form',
sessionId: 'session-1',
message: 'Answer 3 questions',
requestedSchema: {
type: 'object',
properties: {
q0: {
type: 'string',
title: 'Which database?',
description: 'DB',
oneOf: [
{ const: 'Postgres', title: 'Postgres', description: 'relational' },
{ const: 'SQLite', title: 'SQLite' },
{ const: 'Mongo', title: 'Mongo' }
],
default: 'SQLite'
},
q0__other: { type: 'string', title: 'Other (type your own)' },
q1: {
type: 'array',
title: 'Which features?',
items: {
anyOf: [
{ const: 'Auth', title: 'Auth' },
{ const: 'Billing', title: 'Billing' },
{ const: 'Search', title: 'Search' }
]
}
},
q1__other: { type: 'string', title: 'Other (type your own)' },
q2__other: { type: 'string', title: 'Other (type your own)' }
}
}
}
@@ -0,0 +1,172 @@
import { describe, expect, it } from 'vitest'
import { acpFormElicitationPresentation } from './acp-form-elicitation'
import forms from './fixtures/opencode-v2-question-forms.json'
// OpenCode 2.2.5 ACP recordings; only session/tool identities were replaced.
describe('OpenCode question forms', () => {
it('keeps the full single question for current and legacy clients and returns original values', () => {
const form = acpFormElicitationPresentation(forms.single)
expect(form.body).toMatchObject({
question: 'Questions\n\nStorage\n\nWhich storage?',
questions: [
{
question: 'Questions\n\nStorage\n\nWhich storage?',
header: 'Storage',
freeTextQuestionId: 'q1'
}
]
})
expect(form.reply({ kind: 'option', optionId: 'o2' })).toEqual({
action: 'accept',
content: { q0: 'Postgres' }
})
expect(
form.reply({
kind: 'answers',
answers: [{ questionId: 'q1', optionIds: [], other: 'DuckDB' }]
})
).toEqual({ action: 'accept', content: { q0_custom: 'DuckDB' } })
expect(form.reply(null)).toEqual({ action: 'cancel' })
})
it.each(['single', 'multi'])(
'keeps an empty %s choice answerable under its custom key',
(kind) => {
const form = acpFormElicitationPresentation({
...forms.empty,
requestedSchema: {
...forms.empty.requestedSchema,
properties: {
...forms.empty.requestedSchema.properties,
q0:
kind === 'single'
? forms.empty.requestedSchema.properties.q0
: { type: 'array', title: 'Name', items: { anyOf: [] } }
}
}
})
expect(form.body).toMatchObject({
questions: [{ options: [], freeTextQuestionId: 'q1' }]
})
expect(
form.reply({
kind: 'answers',
answers: [{ questionId: 'q1', optionIds: [], other: 'Atlas' }]
})
).toEqual({
action: 'accept',
content: kind === 'single' ? { q0_custom: 'Atlas' } : { q0: [], q0_custom: 'Atlas' }
})
expect(() =>
form.reply({
kind: 'answers',
answers: [{ questionId: 'q1', optionIds: [], other: ' ' }]
})
).toThrow('answer every offered question')
}
)
it('keeps a required choice separate from custom text and rejects closed empty choices', () => {
const form = acpFormElicitationPresentation({
...forms.single,
requestedSchema: { ...forms.single.requestedSchema, required: ['q0'] }
})
expect(() =>
form.reply({
kind: 'answers',
answers: [
{ questionId: 'q1', optionIds: [], other: 'DuckDB' },
{ questionId: 'q2', optionIds: [], other: 'separate' }
]
})
).toThrow('answer every offered question')
expect(() =>
acpFormElicitationPresentation({
...forms.empty,
requestedSchema: { properties: { q0: forms.empty.requestedSchema.properties.q0 } }
})
).toThrow('Unsupported ACP elicitation form')
const confirmation = acpFormElicitationPresentation({
...forms.single,
requestedSchema: {
properties: {
...forms.single.requestedSchema.properties,
q0: { ...forms.single.requestedSchema.properties.q0, type: 'boolean' }
}
}
})
expect(
confirmation.reply({
kind: 'answers',
answers: [
{ questionId: 'q1', optionIds: ['o1'] },
{ questionId: 'q2', optionIds: [], other: 'independent note' }
]
})
).toEqual({ action: 'accept', content: { q0: true, q0_custom: 'independent note' } })
})
it('tells the agent which overflow question was not shown using its original custom key', () => {
const form = acpFormElicitationPresentation({
...forms.single,
requestedSchema: {
properties: Object.fromEntries(
[0, 1, 2, 3, 4].flatMap((index) => [
[`q${index}`, forms.single.requestedSchema.properties.q0],
[`q${index}_custom`, forms.single.requestedSchema.properties.q0_custom]
])
)
}
})
expect(
form.reply({
kind: 'answers',
answers: ['q1', 'q2', 'q3', 'q4'].map((questionId) => ({ questionId, optionIds: ['o1'] }))
})
).toEqual({
action: 'accept',
content: {
q0: 'SQLite',
q1: 'SQLite',
q2: 'SQLite',
q3: 'SQLite',
q4_custom: 'Not shown to the user: Orca shows at most 4 questions at once. Ask again.'
}
})
})
it('shows and returns the web-search provider decision', () => {
const form = acpFormElicitationPresentation(forms.websearch)
expect(form.body).toMatchObject({
question: 'Web Search\n\nAllow OpenCode to search the web for up-to-date information?'
})
expect(form.reply({ kind: 'option', optionId: 'o3' })).toEqual({
action: 'accept',
content: { choice: 'disable' }
})
})
it('does not reject offered answers because an unshown field has no choices', () => {
const form = acpFormElicitationPresentation({
...forms.single,
requestedSchema: {
properties: {
q0: forms.single.requestedSchema.properties.q0,
q1: forms.single.requestedSchema.properties.q0,
q2: forms.single.requestedSchema.properties.q0,
q3: forms.single.requestedSchema.properties.q0,
q4: { type: 'string', oneOf: [] }
}
}
})
expect(
form.reply({
kind: 'answers',
answers: ['q1', 'q2', 'q3', 'q4'].map((questionId) => ({ questionId, optionIds: ['o1'] }))
})
).toEqual({
action: 'accept',
content: { q0: 'SQLite', q1: 'SQLite', q2: 'SQLite', q3: 'SQLite' }
})
})
})
@@ -0,0 +1,151 @@
{
"single": {
"message": "Questions",
"mode": "form",
"requestedSchema": {
"properties": {
"q0": {
"description": "Which storage?",
"oneOf": [
{
"const": "SQLite",
"description": "SQLite",
"title": "SQLite"
},
{
"const": "Postgres",
"description": "Postgres",
"title": "Postgres"
}
],
"title": "Storage",
"type": "string"
},
"q0_custom": {
"description": "Type your own answer",
"title": "Storage (other)",
"type": "string"
}
},
"required": [],
"type": "object"
},
"sessionId": "<session-1>",
"toolCallId": "<tool-1>"
},
"batch": {
"message": "Questions",
"mode": "form",
"requestedSchema": {
"properties": {
"q0": {
"description": "Which storage?",
"oneOf": [
{
"const": "SQLite",
"description": "SQLite",
"title": "SQLite"
},
{
"const": "Postgres",
"description": "Postgres",
"title": "Postgres"
}
],
"title": "Storage",
"type": "string"
},
"q0_custom": {
"description": "Type your own answer",
"title": "Storage (other)",
"type": "string"
},
"q1": {
"description": "Which features?",
"items": {
"anyOf": [
{
"const": "Search",
"description": "Search",
"title": "Search"
},
{
"const": "Export",
"description": "Export",
"title": "Export"
},
{
"const": "Sync",
"description": "Sync",
"title": "Sync"
}
]
},
"title": "Features",
"type": "array"
},
"q1_custom": {
"description": "Add your own answer",
"title": "Features (other)",
"type": "string"
}
},
"required": [],
"type": "object"
},
"sessionId": "<session-1>",
"toolCallId": "<tool-1>"
},
"empty": {
"message": "Questions",
"mode": "form",
"requestedSchema": {
"properties": {
"q0": {
"description": "What is the project name?",
"oneOf": [],
"title": "Name",
"type": "string"
},
"q0_custom": {
"description": "Type your own answer",
"title": "Name (other)",
"type": "string"
}
},
"required": [],
"type": "object"
},
"sessionId": "<session-1>",
"toolCallId": "<tool-1>"
},
"websearch": {
"message": "Web Search",
"mode": "form",
"requestedSchema": {
"properties": {
"choice": {
"description": "Allow OpenCode to search the web for up-to-date information?",
"oneOf": [
{
"const": "allow",
"title": "Allow search via Exa, Firecrawl, Parallel, Tavily, TinyFish"
},
{
"const": "choose",
"title": "Choose another provider"
},
{
"const": "disable",
"title": "Disable web search"
}
],
"type": "string"
}
},
"required": ["choice"],
"type": "object"
},
"sessionId": "<session-1>"
}
}
@@ -0,0 +1,119 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { NativeChatQuestionCard } from './NativeChatQuestionCard'
import { projectStructuredQuestion } from '../../../../../mobile/src/session/mobile-structured-agent-prompts'
import { encodeAgentSessionQuestionAnswers } from '../../../../shared/agent-session/agent-session-question-answer'
import {
structuredQuestionAnswers,
structuredQuestionCard
} from '../../../../shared/structured-agent-question-card'
import { acpFormElicitationPresentation } from '../../../../main/acp/acp-form-elicitation'
import { recordedOmpAskForm } from '../../../../main/acp/acp-omp-ask-form.test-fixture'
import openCodeForms from '../../../../main/acp/fixtures/opencode-v2-question-forms.json'
import type { AskPrompt } from '../../../../shared/native-chat/input/native-chat-ask-types'
let container: HTMLDivElement
let root: ReturnType<typeof createRoot>
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
})
function render(prompt: AskPrompt, onAnswer: () => void, allowOther: readonly boolean[]): void {
act(() =>
root.render(
<NativeChatQuestionCard
prompt={prompt}
onAnswer={onAnswer}
onCancel={() => {}}
allowOther={allowOther}
/>
)
)
}
function cardTitle(): string | null | undefined {
return container.querySelector('[data-testid="native-chat-question-card-title"]')?.textContent
}
it.each([
{
form: openCodeForms.single,
message: 'Questions',
title: 'Storage',
description: 'Which storage?'
},
{
form: openCodeForms.batch,
message: 'Questions',
title: 'Storage',
description: 'Which storage?'
},
{
form: recordedOmpAskForm,
message: 'Answer 3 questions',
title: 'Which database?',
description: 'DB'
},
{
form: {
...recordedOmpAskForm,
requestedSchema: {
properties: {
q0: recordedOmpAskForm.requestedSchema.properties.q0,
q0__other: recordedOmpAskForm.requestedSchema.properties.q0__other
}
}
},
message: 'Answer 3 questions',
title: 'Which database?',
description: 'DB'
}
])(
'shows the form message and full field instructions on the card: $title',
({ form, message, title, description }) => {
const presentation = acpFormElicitationPresentation(form)
if (presentation.body.kind !== 'question') {
throw new Error('expected a question')
}
const card = structuredQuestionCard(presentation.body.questions!)
render(card.prompt, () => {}, card.allowOther)
expect(cardTitle()).toContain(message)
expect(cardTitle()).toContain(title)
expect(cardTitle()).toContain(description)
}
)
it('roundtrips a phone batch with selected and custom multi answers through the shared encoding', () => {
const form = acpFormElicitationPresentation(openCodeForms.batch)
if (form.body.kind !== 'question') {
throw new Error('expected a question')
}
const projected = projectStructuredQuestion({
itemId: 'question-1',
revision: 2,
sequence: 1,
observedAt: 1,
body: form.body
})!
const questions = projected.questions!
expect(structuredQuestionCard(questions).prompt.questions).toMatchObject([
{ question: 'Questions\n\nStorage\n\nWhich storage?' },
{ question: 'Questions\n\nFeatures\n\nWhich features?', multiSelect: true }
])
const answers = structuredQuestionAnswers(questions, [
{ indices: [0] },
{ indices: [0, 2], other: 'Offline' }
])!
expect(
form.reply({ kind: 'option', optionId: encodeAgentSessionQuestionAnswers(answers) })
).toEqual({
action: 'accept',
content: { q0: 'SQLite', q1: ['Search', 'Sync'], q1_custom: 'Offline' }
})
})