fix(ui): support inline custom answers for string choice fields in connect (#53625)

This commit is contained in:
Aiden Cline
2026-10-06 22:41:21 -05:00
committed by GitHub
Unverified
parent eebe9d370f
commit 1d610f90a0
2 changed files with 302 additions and 44 deletions
+128 -28
View File
@@ -3,6 +3,7 @@ import { Badge } from "@opencode/ui/badge"
import { useDialog } from "@opencode/ui/context/dialog"
import { Icon } from "@opencode/ui/icon"
import { List } from "@opencode/ui/list"
import { RadioGroup, RadioItem } from "@opencode/ui/radio"
import { Spinner } from "@opencode/ui/spinner"
import { TextField } from "@opencode/ui/text-field"
import { DialogBody, DialogHeader, DialogTitle, Dialog } from "@opencode/ui/dialog"
@@ -61,7 +62,7 @@ type IntegrationForm = NonNullable<ProviderConnectMethod["form"]>[number]
type StringForm = Extract<IntegrationForm, { type: "string" }>
export function useProviderConnectController() {
const [store, setStore] = createStore({ selected: undefined as string | undefined })
const [store, setStore] = createStore<{ selected?: string }>({})
const reset = () => setStore("selected", undefined)
return {
@@ -83,9 +84,13 @@ export const DialogConnectProvider: Component<{
const fallback = useProviderConnectController()
const controller = props.controller ?? fallback
const [state, setState] = createStore({
const [state, setState] = createStore<{
completed: boolean
modelProvider?: { id: string; name: string }
authorization: boolean
chatgptWelcome: boolean
}>({
completed: false,
modelProvider: undefined as { id: string; name: string } | undefined,
authorization: false,
chatgptWelcome: false,
})
@@ -216,10 +221,12 @@ function ProviderPicker(props: { directory?: string; onSelect: (provider: string
const integrations = useIntegrations(() => props.directory)
const language = useLanguage()
const [store, setStore] = createStore({
const [store, setStore] = createStore<{
filter: string
active?: string
connecting?: string
}>({
filter: "",
active: undefined as string | undefined,
connecting: undefined as string | undefined,
})
const featured = ["opencode-go", "opencode", "anthropic", "openai", "google", "openrouter", "vercel"]
@@ -421,16 +428,24 @@ function ProviderConnection(props: {
const isConsole = CONSOLE_PROVIDERS.has(props.provider)
const remote = isConsole && authServerName(sdk.server) !== undefined
const [state, setState] = createStore({
const [state, setState] = createStore<{
copied: boolean
copyFailed: boolean
firstConnection?: boolean
models: boolean
noModels: boolean
catalogPending: boolean
selectedModel: string
collapsed: Record<string, boolean>
}>({
copied: false,
copyFailed: false,
firstConnection: undefined as boolean | undefined,
models: false,
noModels: false,
// The workspace providers had not loaded when the wait ran out.
catalogPending: false,
selectedModel: "",
collapsed: {} as Record<string, boolean>,
collapsed: {},
})
const controller = createProviderConnectionController({
@@ -642,11 +657,22 @@ function ProviderConnection(props: {
function AuthFormView() {
const defaults = providerFormDefaults(controller.currentMethod()?.form)
const [formStore, setFormStore] = createStore({
const [formStore, setFormStore] = createStore<{
value: Record<string, string>
index: number
customOn: boolean
customText: string
}>({
value: Object.fromEntries(
Object.entries(defaults).flatMap(([key, value]) => (typeof value === "string" ? [[key, value]] : [])),
) as Record<string, string>,
(controller.currentMethod()?.form ?? []).flatMap((field) =>
field.type === "string" && field.key in defaults && field.default !== undefined
? [[field.key, field.default]]
: [],
),
),
index: 0,
customOn: false,
customText: "",
})
const fields = createMemo<StringForm[]>(() => {
@@ -677,14 +703,18 @@ function ProviderConnection(props: {
}
})
// Visible defaults prefill the field but enter the answer only once that field is answered,
// because the server rejects values for fields whose conditions are not met.
const answer = (field: StringForm) => formStore.value[field.key] ?? field.default
const valid = createMemo(() => {
const item = current()
if (!item || item.field.options) return false
if (!item || (item.field.options && !item.field.custom)) return false
if (!item.field.required) return true
return (formStore.value[item.field.key] ?? "").trim().length > 0
return (answer(item.field) ?? "").trim().length > 0
})
async function next(index: number, value: Record<string, string>) {
@@ -694,7 +724,7 @@ function ProviderConnection(props: {
const next = fields().findIndex((field, i) => i > index && matches(field, value))
if (next !== -1) {
setFormStore("index", next)
setFormStore({ index: next, customOn: false, customText: "" })
return
}
@@ -706,9 +736,10 @@ function ProviderConnection(props: {
e.preventDefault()
const item = current()
if (!item || item.field.options) return
if (!item || !valid()) return
const value = answer(item.field)
if (!valid()) return
if (value !== undefined) setFormStore("value", item.field.key, value)
await next(item.index, formStore.value)
}
@@ -730,6 +761,15 @@ function ProviderConnection(props: {
return field
})
const custom = () => {
const field = select()
if (!field?.custom) return false
const value = answer(field)
return formStore.customOn || (value !== undefined && !field.options?.some((option) => option.value === value))
}
return (
<form onSubmit={handleSubmit} class="flex flex-col items-start gap-4 px-3">
<Switch>
@@ -738,7 +778,7 @@ function ProviderConnection(props: {
type="text"
label={text()?.title ?? ""}
placeholder={text()?.placeholder}
value={text() ? (formStore.value[text()!.key] ?? "") : ""}
value={text() ? (answer(text()!) ?? "") : ""}
onChange={(value) => {
const field = text()
@@ -750,6 +790,62 @@ function ProviderConnection(props: {
{language.t("common.continue")}
</Button>
</Match>
<Match when={select()?.custom && select()}>
{(field) => (
<>
<div class="w-full flex flex-col gap-3">
<div class="text-14-regular text-text-base">{field().title}</div>
<RadioGroup
label={field().title}
hideLabel
description={field().description}
value={
custom()
? "custom"
: String(field().options?.findIndex((option) => option.value === answer(field())))
}
onChange={(value) => {
const option = field().options?.[Number(value)]
if (option) {
if (custom()) setFormStore("customText", answer(field()) ?? "")
setFormStore("customOn", false)
setFormStore("value", field().key, option.value)
return
}
setFormStore("customOn", true)
setFormStore("value", field().key, formStore.customText)
}}
>
<For each={field().options}>
{(option, index) => (
<RadioItem value={String(index())} label={option.label} description={option.description} />
)}
</For>
<RadioItem value="custom" label={language.t("ui.messagePart.option.typeOwnAnswer")} />
<Show when={custom()}>
<div class="pl-6">
<TextField
ref={(input: HTMLInputElement) => queueMicrotask(() => input.focus())}
type="text"
label={language.t("ui.messagePart.option.typeOwnAnswer")}
hideLabel
placeholder={field().placeholder ?? language.t("ui.question.custom.placeholder")}
value={answer(field()) ?? ""}
onChange={(value) => setFormStore("value", field().key, value)}
/>
</div>
</Show>
</RadioGroup>
</div>
<Button class="w-auto" type="submit" size="large" variant="contrast" disabled={!valid()}>
{language.t("common.continue")}
</Button>
</>
)}
</Match>
<Match when={item()?.field.options !== undefined}>
<div class="w-full flex flex-col gap-1.5">
<div class="text-14-regular text-text-base">{select()?.title}</div>
@@ -758,7 +854,7 @@ function ProviderConnection(props: {
class="px-3"
items={select()?.options ?? []}
key={(x) => x.value}
current={select()?.options?.find((x) => x.value === formStore.value[select()!.key])}
current={select()?.options?.find((x) => x.value === answer(select()!))}
onSelect={(value) => {
if (!value) return
const field = select()
@@ -876,9 +972,11 @@ function ProviderConnection(props: {
let apiKey: HTMLInputElement | undefined
const errorID = createUniqueId()
const [formStore, setFormStore] = createStore({
const [formStore, setFormStore] = createStore<{
value: string
error?: string
}>({
value: "",
error: undefined as string | undefined,
})
onMount(() => {
@@ -890,16 +988,16 @@ function ProviderConnection(props: {
if (!(e.currentTarget instanceof HTMLFormElement)) return
const value = new FormData(e.currentTarget).get("apiKey")
const apiKey = typeof value === "string" ? value : ""
const key = value instanceof File || value === null ? "" : value
if (!apiKey?.trim()) {
if (!key.trim()) {
setFormStore("error", language.t("provider.connect.apiKey.required"))
return
}
setFormStore("error", undefined)
await controller.auth.connectKey(apiKey)
await controller.auth.connectKey(key)
}
return (
@@ -954,9 +1052,11 @@ function ProviderConnection(props: {
let codeInput: HTMLInputElement | undefined
const errorID = createUniqueId()
const [formStore, setFormStore] = createStore({
const [formStore, setFormStore] = createStore<{
value: string
error?: string
}>({
value: "",
error: undefined as string | undefined,
})
onMount(() => {
@@ -968,9 +1068,9 @@ function ProviderConnection(props: {
if (!(e.currentTarget instanceof HTMLFormElement)) return
const value = new FormData(e.currentTarget).get("code")
const code = typeof value === "string" ? value : ""
const code = value instanceof File || value === null ? "" : value
if (!code?.trim()) {
if (!code.trim()) {
setFormStore("error", language.t("provider.connect.oauth.code.required"))
return
+174 -16
View File
@@ -1,4 +1,5 @@
import { TextAttributes } from "@opentui/core"
import { ScrollBoxRenderable, TextareaRenderable, TextAttributes } from "@opentui/core"
import { useTerminalDimensions } from "@opentui/solid"
import type {
ConnectionInfo,
IntegrationCommandConnectOutput,
@@ -12,7 +13,8 @@ import type {
LocationRef,
} from "@opencode/client"
import { openUrl } from "@opencode/util/open"
import { createEffect, createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { useClipboard } from "../context/clipboard"
import { useData } from "../context/data"
import { useClient } from "../context/client"
@@ -25,7 +27,15 @@ import { DialogSelect } from "../ui/dialog-select"
import { Link } from "../ui/link"
import { useToast } from "../ui/toast"
import { errorMessage } from "../util/error"
import { formLabel, formToggleMultiselect, formValidateValue, type FormAnswerField } from "../util/form"
import {
formInitialValues,
formLabel,
formRows,
formSelected,
formToggleMultiselect,
formValidateValue,
type FormAnswerField,
} from "../util/form"
const INTEGRATION_PRIORITY: Record<string, number> = {
"opencode-go": 0,
@@ -813,6 +823,13 @@ async function selectAnswer(
title: string,
field: Extract<FormAnswerField, { type: "boolean" | "string" }>,
): Promise<FormValue | undefined | typeof CANCELLED> {
if (field.type === "string" && field.custom)
return new Promise((resolve) => {
dialog.replace(
() => <StringChoiceField field={field} onSubmit={resolve} />,
() => resolve(CANCELLED),
)
})
const options =
field.type === "boolean"
? field.default === false
@@ -829,18 +846,12 @@ async function selectAnswer(
value: option.value as FormValue,
description: option.description,
}))
const choice = await new Promise<FormValue | typeof CUSTOM | undefined | typeof CANCELLED>((resolve) => {
return new Promise<FormValue | undefined | typeof CANCELLED>((resolve) => {
dialog.replace(
() => (
<DialogSelect<FormValue | typeof CUSTOM | undefined>
<DialogSelect<FormValue | undefined>
title={formLabel(field) || title}
options={[
...options,
...(field.type === "string" && field.custom
? [{ title: "Type your own answer", value: CUSTOM as typeof CUSTOM }]
: []),
...(!field.required ? [{ title: "Skip", value: undefined }] : []),
]}
options={[...options, ...(!field.required ? [{ title: "Skip", value: undefined }] : [])]}
current={field.type === "string" ? field.default : undefined}
onSelect={(option) => resolve(option.value)}
/>
@@ -848,11 +859,158 @@ async function selectAnswer(
() => resolve(CANCELLED),
)
})
if (choice === CUSTOM) {
if (field.type !== "string") return CANCELLED
return textAnswer(dialog, title, field, "")
}
function StringChoiceField(props: {
field: Extract<FormAnswerField, { type: "string" }>
onSubmit: (value: string | undefined) => void
}) {
const dialog = useDialog()
const theme = useTheme().surface("dialog")
const dimensions = useTerminalDimensions()
const rows = formRows(props.field)
const count = rows.length + (props.field.required ? 1 : 2)
const [store, setStore] = createStore({
selected: formSelected(props.field, props.field.default),
editing: false,
text: formInitialValues([props.field]).custom[props.field.key] ?? "",
error: "",
})
const [textarea, setTextarea] = createSignal<TextareaRenderable>()
let scroll: ScrollBoxRenderable | undefined
createEffect(() => {
const row = scroll?.getChildren()[store.selected]
if (row) scroll?.scrollChildIntoView(row.id)
})
const fg = (index: number) => (store.selected === index ? theme.text.formfield.focused : theme.text.formfield.base)
const submit = (value: string | undefined) => {
const invalid = formValidateValue(props.field, value)
if (invalid) return setStore("error", invalid)
props.onSubmit(value)
}
return choice
const select = (index: number) => {
setStore({ selected: index, error: "" })
if (index === rows.length) return setStore("editing", true)
submit(index < rows.length ? String(rows[index].value) : undefined)
}
const back = () => setStore({ editing: false, text: textarea()?.plainText ?? store.text, error: "" })
Keymap.createLayer(() => ({
mode: "modal",
enabled: !store.editing,
commands: [
{
id: "dialog.select.prev",
title: "Previous answer",
group: "Form",
run: () => setStore("selected", (store.selected + count - 1) % count),
},
{
id: "dialog.select.next",
title: "Next answer",
group: "Form",
run: () => setStore("selected", (store.selected + 1) % count),
},
{ id: "dialog.select.submit", title: "Select answer", group: "Form", run: () => select(store.selected) },
],
}))
Keymap.createLayer(() => ({
mode: "modal",
priority: 1,
target: textarea,
enabled: store.editing,
commands: [
{
id: "dialog.prompt.submit",
title: "Submit answer",
group: "Form",
run: () => submit(textarea()?.plainText.trim() || undefined),
},
{ bind: "escape", title: "Back to answers", group: "Form", run: back },
],
}))
return (
<box paddingLeft={4} paddingRight={4} paddingBottom={1} gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text fg={theme.text.base} attributes={TextAttributes.BOLD}>
{formLabel(props.field)}
</text>
<text fg={theme.text.muted} onMouseUp={() => (store.editing ? back() : dialog.clear())}>
esc
</text>
</box>
<Show when={props.field.description}>{(description) => <text fg={theme.text.muted}>{description()}</text>}</Show>
<scrollbox
gap={1}
height={Math.min(
count + rows.filter((row) => row.description).length,
Math.max(3, Math.floor(dimensions().height / 2) - 6),
)}
scrollbarOptions={{ visible: false }}
ref={(value: ScrollBoxRenderable) => {
scroll = value
}}
>
<For each={rows}>
{(row, index) => (
<box onMouseUp={() => select(index())}>
<text fg={fg(index())}>
{index() + 1}. {row.label}
</text>
<Show when={row.description}>
{(description) => (
<text paddingLeft={3} fg={theme.text.muted}>
{description()}
</text>
)}
</Show>
</box>
)}
</For>
<box flexDirection="row" gap={1} onMouseUp={() => select(rows.length)}>
<text fg={fg(rows.length)}>{rows.length + 1}.</text>
<Show
when={store.editing}
fallback={<text fg={fg(rows.length)}>{store.text || "Type your own answer"}</text>}
>
<textarea
height={1}
flexGrow={1}
wrapMode="none"
initialValue={store.text}
placeholder={props.field.placeholder ?? "Type your own answer"}
placeholderColor={theme.text.muted}
textColor={theme.text.formfield.focused}
focusedTextColor={theme.text.formfield.focused}
cursorColor={theme.text.formfield.focused}
ref={(value: TextareaRenderable) => {
setTextarea(value)
value.traits = { status: "ANSWER" }
queueMicrotask(() => {
if (value.isDestroyed) return
value.focus()
value.gotoLineEnd()
})
}}
onContentChange={() => {
const text = textarea()?.plainText ?? ""
setStore("text", text)
if (store.error && !formValidateValue(props.field, text.trim() || undefined)) setStore("error", "")
}}
/>
</Show>
</box>
<Show when={!props.field.required}>
<text fg={fg(rows.length + 1)} onMouseUp={() => select(rows.length + 1)}>
{rows.length + 2}. Skip
</text>
</Show>
</scrollbox>
<Show when={store.error}>{(error) => <text fg={theme.text.feedback.error.base}>{error()}</text>}</Show>
<text fg={theme.text.muted}>
{store.editing ? "enter submit · esc back" : "↑/↓ select · enter confirm · esc cancel"}
</text>
</box>
)
}
function textAnswer(