fix(app): bound MCP elicitation and auto-approve requests with explicit machines (#62111)

This commit is contained in:
Luke Parker 2026-11-05 10:05:39 -06:00 • committed by GitHub
parent b8a9e8a73f
commit 50971aedbf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 1319 additions and 175 deletions

View file

@ -327,6 +327,135 @@ test("sends one permission reply and closes the dock when it lands, before permi
expect(replies).toEqual([{ decision: "once" }])
})
test("shows an auto-accepted permission in the dock once its replies stop answering", async ({ page }) => {
const permissionID = "permission-hung"
const attempts = { count: 0 }
await page.clock.install()
await mockWorkspace(page, {
name: "RequestDocks",
directory,
sessions: [{ id: sessionID, title }],
sessionPermissions: {
[sessionID]: [
{ id: permissionID, sessionID, action: "shell", resources: ["git status"], metadata: {}, save: [] },
],
},
seed: { settings: { permissions: { autoApprove: true } } },
})
// Every reply reaches the server and never answers.
await page.route(new RegExp(`/api/session/${sessionID}/permission/${permissionID}/reply(\\?|$)`), (route) => {
if (route.request().method() !== "POST") return route.fallback()
attempts.count++
})
await page.goto(sessionHref(sessionID))
await expectSessionTitle(page, title)
const permission = page.locator('[data-component="dock-prompt"][data-kind="permission"]')
// Each reply times out, then the next one starts after its retry delay.
await expect.poll(() => attempts.count).toBe(1)
await page.clock.fastForward(15_000)
await page.clock.fastForward(1_000)
await expect.poll(() => attempts.count).toBe(2)
await page.clock.fastForward(15_000)
await page.clock.fastForward(2_000)
await expect.poll(() => attempts.count).toBe(3)
await expect(permission).toHaveCount(0)
await page.clock.fastForward(15_000)
await expect(permission.getByText("git status")).toBeVisible()
expect(attempts.count).toBe(3)
})
test("keeps a typed MCP elicitation answer across a session switch and submits it once", async ({ page }) => {
const other = { id: "ses_request_docks_other", title: "Other request session" }
const form = {
id: "frm_mcp_draft",
sessionID,
title: "Deploy",
metadata: { kind: "mcp-elicitation", server: "release" },
fields: [{ key: "env", type: "string", title: "Environment" }],
}
const replies: unknown[] = []
await mockWorkspace(page, {
name: "RequestDocks",
directory,
sessions: [{ id: sessionID, title }, other],
forms: () => (replies.length > 0 ? [] : [form]),
onFormReply: (reply) => replies.push(reply.body),
seed: { tabs: [sessionID, other.id] },
})
await page.goto(sessionHref(sessionID))
await expectSessionTitle(page, title)
const dock = page.locator('[data-component="session-elicitation-dock"]')
const input = dock.getByRole("textbox", { name: "Environment", exact: true })
await input.fill("staging")
await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(other.id)}"])`).click()
await expectSessionTitle(page, other.title)
await expect(dock).toHaveCount(0)
await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(sessionID)}"])`).click()
await expectSessionTitle(page, title)
await expect(input).toHaveValue("staging")
await dock.getByRole("button", { name: "Submit", exact: true }).dblclick()
await expect(dock).toHaveCount(0)
await expect(page.locator('[data-component="composer"]')).toBeVisible()
expect(replies).toEqual([{ answer: { env: "staging" } }])
})
test("gives a Location elicitation's hung reply back after 30 s and closes it on form.replied", async ({ page }) => {
const form = {
id: "frm_mcp_global",
sessionID: "global",
title: "Deploy",
metadata: { kind: "mcp-elicitation", server: "release" },
fields: [{ key: "env", type: "string", title: "Environment" }],
}
const replies: { body: unknown; directory: string | undefined }[] = []
const transport = await installSseTransport(page, { server: SERVER, retry: 20 })
await page.clock.install()
await mockServer(page, { forms: [form] })
// The server takes the reply and never answers it.
await page.route(/\/api\/session\/global\/form\/frm_mcp_global\/reply(\?|$)/, (route) => {
if (route.request().method() !== "POST") return route.fallback()
replies.push({ body: route.request().postDataJSON(), directory: route.request().headers()["x-opencode-directory"] })
})
await page.goto(sessionHref(sessionID))
await transport.waitForConnection()
await expectSessionTitle(page, title)
const dock = page.locator('[data-component="session-elicitation-dock"]')
const input = dock.getByRole("textbox", { name: "Environment", exact: true })
const submit = dock.getByRole("button", { name: "Submit", exact: true })
await input.fill("prod")
await submit.dblclick()
await expect.poll(() => replies.length).toBe(1)
await expect(submit).toBeDisabled()
expect(replies).toEqual([{ body: { answer: { env: "prod" } }, directory: encodeURIComponent(directory) }])
await page.clock.fastForward(30_000)
await expect(submit).toBeEnabled()
await expect(input).toHaveValue("prod")
await expect(page.getByText("Request failed", { exact: true })).toBeVisible()
await transport.send({
id: "evt_form_replied_global",
created: 1700000004000,
type: "form.replied",
location: { directory },
data: { sessionID: "global", id: "frm_mcp_global", answer: { env: "prod" } },
})
await expect(dock).toHaveCount(0)
await expect(page.locator('[data-component="composer"]')).toBeVisible()
expect(replies).toHaveLength(1)
})
test("names the MCP tool, the hook's message and the full input in the permission dock", async ({ page }) => {
const body = "x".repeat(3000)
await mockServer(page, {

View file

@ -1203,9 +1203,11 @@ function mockHandlers(
...Object.entries(config.sessionPermissions ?? {}).flatMap(([id, list]) =>
currentPermissions(list).length > 0 && status[id]?.type !== "idle" ? [id] : [],
),
// Location elicitations (`sessionID: "global"`) belong to no Session.
...resolve(config.forms ?? []).flatMap((form) =>
Predicate.isObject(form) &&
Predicate.isString(form.sessionID) &&
form.sessionID !== "global" &&
status[form.sessionID]?.type !== "idle"
? [form.sessionID]
: [],

View file

@ -1,11 +1,19 @@
import { describe, expect, test } from "bun:test"
import {
AUTO_APPROVE_REPLY_TIMEOUT_MS,
AUTO_APPROVE_SWEEP_TIMEOUT_MS,
INITIAL_AUTO_APPROVE_STATE,
INITIAL_AUTO_APPROVE_SWEEP_STATE,
needsUser,
transitionAutoApprove,
transitionAutoApproveSweep,
type AutoApproveEffect,
type AutoApproveEvent,
type AutoApproveState,
type AutoApproveSweepEffect,
type AutoApproveSweepEvent,
type AutoApproveSweepState,
type AutoApproveSweepTransition,
type AutoApproveTransition,
} from "./auto-approve-machine"
@ -32,6 +40,14 @@ const waiting = (runId: string, attempt: number): AutoApproveState => ({
attempt,
})
const reply = (runId: string, attempt: number): AutoApproveEffect => ({
type: "reply",
sessionID: "ses_1",
runId,
attempt,
timeoutMs: AUTO_APPROVE_REPLY_TIMEOUT_MS,
})
const gaveUp: AutoApproveState = { status: "gave-up", projectID: "proj_1" }
function replay(events: AutoApproveEvent[], from = INITIAL_AUTO_APPROVE_STATE) {
@ -47,10 +63,7 @@ describe("transitionAutoApprove", () => {
const steps = replay([approve("r1"), { type: "reply.succeeded", runId: "r1", attempt: 0 }])
expect(steps.map((step) => step.state)).toEqual([replying("r1", 0), { status: "replied" }])
expect(steps.map((step) => step.effects)).toEqual([
[{ type: "reply", sessionID: "ses_1", runId: "r1", attempt: 0 }],
[],
])
expect(steps.map((step) => step.effects)).toEqual([[reply("r1", 0)], [{ type: "clear-reply-timer" }]])
})
test("surfaces the request in the dock once every retry fails", () => {
@ -72,16 +85,52 @@ describe("transitionAutoApprove", () => {
gaveUp,
])
expect(steps.map((step) => step.effects)).toEqual([
[{ type: "reply", sessionID: "ses_1", runId: "r1", attempt: 0 }],
[{ type: "schedule-retry", runId: "r1", attempt: 1, delayMs: 1000 }],
[{ type: "reply", sessionID: "ses_1", runId: "r1", attempt: 1 }],
[{ type: "schedule-retry", runId: "r1", attempt: 2, delayMs: 2000 }],
[{ type: "reply", sessionID: "ses_1", runId: "r1", attempt: 2 }],
[],
[reply("r1", 0)],
[{ type: "clear-reply-timer" }, { type: "schedule-retry", runId: "r1", attempt: 1, delayMs: 1000 }],
[reply("r1", 1)],
[{ type: "clear-reply-timer" }, { type: "schedule-retry", runId: "r1", attempt: 2, delayMs: 2000 }],
[reply("r1", 2)],
[{ type: "clear-reply-timer" }],
])
expect(steps.map((step) => needsUser(step.state, true))).toEqual([false, false, false, false, false, true])
})
// A reply that never answered used to keep its request hidden from the dock for good.
test("a reply that never answers times out through the retries and surfaces the request", () => {
const steps = replay([
approve("r1"),
{ type: "reply.timed-out", runId: "r1", attempt: 0 },
// The timed-out first reply settles late.
{ type: "reply.failed", runId: "r1", attempt: 0 },
{ type: "retry.due", runId: "r1", attempt: 1 },
{ type: "reply.timed-out", runId: "r1", attempt: 1 },
{ type: "retry.due", runId: "r1", attempt: 2 },
{ type: "reply.timed-out", runId: "r1", attempt: 2 },
])
expect(steps.map((step) => step.state)).toEqual([
replying("r1", 0),
waiting("r1", 1),
waiting("r1", 1),
replying("r1", 1),
waiting("r1", 2),
replying("r1", 2),
gaveUp,
])
expect(steps[2]?.state).toBe(steps[1]?.state)
expect(steps.map((step) => step.effects)).toEqual([
[reply("r1", 0)],
[{ type: "clear-reply-timer" }, { type: "schedule-retry", runId: "r1", attempt: 1, delayMs: 1000 }],
[],
[reply("r1", 1)],
[{ type: "clear-reply-timer" }, { type: "schedule-retry", runId: "r1", attempt: 2, delayMs: 2000 }],
[reply("r1", 2)],
[{ type: "clear-reply-timer" }],
])
expect(needsUser(steps.at(-2)!.state, true)).toBe(false)
expect(needsUser(steps.at(-1)!.state, true)).toBe(true)
})
test("recovers on a later attempt", () => {
const state = replay([
approve("r1"),
@ -113,7 +162,9 @@ describe("transitionAutoApprove", () => {
const stale: AutoApproveEvent[] = [
{ type: "reply.failed", runId: "r1", attempt: 0 },
{ type: "reply.succeeded", runId: "r1", attempt: 0 },
{ type: "reply.timed-out", runId: "r1", attempt: 0 },
{ type: "reply.failed", runId: "r2", attempt: 1 },
{ type: "reply.timed-out", runId: "r2", attempt: 1 },
{ type: "retry.due", runId: "r2", attempt: 0 },
]
@ -129,22 +180,42 @@ describe("transitionAutoApprove", () => {
expect(transitionAutoApprove(pausing, { type: "retry.due", runId: "r1", attempt: 1 }).state).toBe(pausing)
})
test.each<{ from: AutoApproveState; cancel: AutoApproveState; resolved: AutoApproveState; clears: boolean }>([
// Leaving a reply stops its timeout, so it never reports a timed-out attempt for a cycle that ended.
test.each<{
from: AutoApproveState
cancel: AutoApproveState
resolved: AutoApproveState
effects: AutoApproveEffect[]
}>([
{
from: INITIAL_AUTO_APPROVE_STATE,
cancel: INITIAL_AUTO_APPROVE_STATE,
resolved: INITIAL_AUTO_APPROVE_STATE,
clears: false,
effects: [],
},
{ from: replying("r1", 0), cancel: INITIAL_AUTO_APPROVE_STATE, resolved: { status: "replied" }, clears: false },
{ from: waiting("r1", 1), cancel: INITIAL_AUTO_APPROVE_STATE, resolved: { status: "replied" }, clears: true },
{ from: gaveUp, cancel: INITIAL_AUTO_APPROVE_STATE, resolved: { status: "replied" }, clears: false },
{ from: { status: "replied" }, cancel: { status: "replied" }, resolved: { status: "replied" }, clears: false },
{
from: replying("r1", 0),
cancel: INITIAL_AUTO_APPROVE_STATE,
resolved: { status: "replied" },
effects: [{ type: "clear-reply-timer" }],
},
{
from: waiting("r1", 1),
cancel: INITIAL_AUTO_APPROVE_STATE,
resolved: { status: "replied" },
effects: [{ type: "cancel-retry" }],
},
{ from: gaveUp, cancel: INITIAL_AUTO_APPROVE_STATE, resolved: { status: "replied" }, effects: [] },
{ from: { status: "replied" }, cancel: { status: "replied" }, resolved: { status: "replied" }, effects: [] },
])("cancel and resolved from $from.status", (input) => {
const effects: AutoApproveEffect[] = input.clears ? [{ type: "cancel-retry" }] : []
expect(transitionAutoApprove(input.from, { type: "cancel" })).toEqual({ state: input.cancel, effects })
expect(transitionAutoApprove(input.from, { type: "resolved" })).toEqual({ state: input.resolved, effects })
expect(transitionAutoApprove(input.from, { type: "cancel" })).toEqual({
state: input.cancel,
effects: input.effects,
})
expect(transitionAutoApprove(input.from, { type: "resolved" })).toEqual({
state: input.resolved,
effects: input.effects,
})
})
})
@ -158,3 +229,117 @@ test.each<{ state: AutoApproveState; on: boolean; off: boolean }>([
expect(needsUser(input.state, true)).toBe(input.on)
expect(needsUser(input.state, false)).toBe(input.off)
})
describe("transitionAutoApproveSweep", () => {
const run = (runId: string, attempt: number) => ({
type: "sweep.run" as const,
runId,
attempt,
timeoutMs: AUTO_APPROVE_SWEEP_TIMEOUT_MS,
})
function sweepReplay(
events: AutoApproveSweepEvent[],
from: AutoApproveSweepState = INITIAL_AUTO_APPROVE_SWEEP_STATE,
) {
return events.reduce<AutoApproveSweepTransition[]>((steps, event) => {
steps.push(transitionAutoApproveSweep(steps.at(-1)?.state ?? from, event))
return steps
}, [])
}
// A sweep stalled on one request used to hold its retries back for good.
test("a sweep that never finishes times out, retries and comes to rest", () => {
const steps = sweepReplay([
{ type: "sweep.start", runId: "s1" },
{ type: "sweep.timed-out", runId: "s1", attempt: 0 },
// The aborted sweep settles late.
{ type: "sweep.failed", runId: "s1", attempt: 0 },
{ type: "sweep.retry-due", runId: "s1", attempt: 1 },
{ type: "sweep.failed", runId: "s1", attempt: 1 },
{ type: "sweep.retry-due", runId: "s1", attempt: 2 },
{ type: "sweep.timed-out", runId: "s1", attempt: 2 },
])
expect(steps.map((step) => step.state)).toEqual([
{ status: "sweeping", runId: "s1", attempt: 0 },
{ status: "waiting-retry", runId: "s1", attempt: 1 },
{ status: "waiting-retry", runId: "s1", attempt: 1 },
{ status: "sweeping", runId: "s1", attempt: 1 },
{ status: "waiting-retry", runId: "s1", attempt: 2 },
{ status: "sweeping", runId: "s1", attempt: 2 },
INITIAL_AUTO_APPROVE_SWEEP_STATE,
])
expect(steps[2]?.state).toBe(steps[1]?.state)
expect(steps.map((step) => step.effects)).toEqual([
[run("s1", 0)],
[{ type: "sweep.abort" }, { type: "sweep.schedule-retry", runId: "s1", attempt: 1, delayMs: 1000 }],
[],
[run("s1", 1)],
[{ type: "sweep.abort" }, { type: "sweep.schedule-retry", runId: "s1", attempt: 2, delayMs: 2000 }],
[run("s1", 2)],
[{ type: "sweep.abort" }],
])
})
test("a complete sweep comes to rest", () => {
const steps = sweepReplay([
{ type: "sweep.start", runId: "s1" },
{ type: "sweep.succeeded", runId: "s1", attempt: 0 },
])
expect(steps.at(-1)).toEqual({ state: INITIAL_AUTO_APPROVE_SWEEP_STATE, effects: [{ type: "sweep.abort" }] })
})
test("a newer start replaces the sweep or its retry, and the old sweep's results are ignored", () => {
const sweeping: AutoApproveSweepState = { status: "sweeping", runId: "s1", attempt: 0 }
const restarted = transitionAutoApproveSweep(sweeping, { type: "sweep.start", runId: "s2" })
expect(restarted).toEqual({
state: { status: "sweeping", runId: "s2", attempt: 0 },
effects: [{ type: "sweep.abort" }, run("s2", 0)],
})
const stale: AutoApproveSweepEvent[] = [
{ type: "sweep.succeeded", runId: "s1", attempt: 0 },
{ type: "sweep.failed", runId: "s1", attempt: 0 },
{ type: "sweep.timed-out", runId: "s1", attempt: 0 },
{ type: "sweep.retry-due", runId: "s2", attempt: 0 },
]
stale.forEach((event) => {
const result = transitionAutoApproveSweep(restarted.state, event)
expect(result.state).toBe(restarted.state)
expect(result.effects).toEqual([])
})
expect(
transitionAutoApproveSweep(
{ status: "waiting-retry", runId: "s1", attempt: 1 },
{ type: "sweep.start", runId: "s2" },
),
).toEqual({
state: { status: "sweeping", runId: "s2", attempt: 0 },
effects: [{ type: "sweep.cancel-retry" }, run("s2", 0)],
})
})
test.each<{ from: AutoApproveSweepState; effects: AutoApproveSweepEffect[] }>([
{ from: { status: "sweeping", runId: "s1", attempt: 0 }, effects: [{ type: "sweep.abort" }] },
{ from: { status: "waiting-retry", runId: "s1", attempt: 1 }, effects: [{ type: "sweep.cancel-retry" }] },
])("cancel from $from.status", (input) => {
expect(transitionAutoApproveSweep(input.from, { type: "sweep.cancel" })).toEqual({
state: INITIAL_AUTO_APPROVE_SWEEP_STATE,
effects: input.effects,
})
})
test("cancel while idle changes nothing", () => {
const result = transitionAutoApproveSweep(INITIAL_AUTO_APPROVE_SWEEP_STATE, { type: "sweep.cancel" })
expect(result.state).toBe(INITIAL_AUTO_APPROVE_SWEEP_STATE)
expect(result.effects).toEqual([])
})
})

View file

@ -2,6 +2,15 @@ export const AUTO_APPROVE_RETRY_LIMIT = 2
export const AUTO_APPROVE_RETRY_DELAY_MS = 1000
// A reply hides its request from the dock while it runs, so one that never answers gives up on this attempt instead.
// Retrying is safe: the server answers a request it already settled with not found, which the data layer counts as
// replied.
export const AUTO_APPROVE_REPLY_TIMEOUT_MS = 15_000
// One sweep lists active sessions and then every location's requests through the shared request queue, so it gets
// more time than one reply before it counts as failed and retries.
export const AUTO_APPROVE_SWEEP_TIMEOUT_MS = 30_000
// One permission request's auto-approve lifecycle. `runId` names one approval cycle and `attempt` one reply within
// it, so a reply or timer from a cancelled or resolved cycle can never move a later one.
export type AutoApproveState =
@ -32,12 +41,21 @@ export type AutoApproveEvent =
}
| { readonly type: "reply.succeeded"; readonly runId: string; readonly attempt: number }
| { readonly type: "reply.failed"; readonly runId: string; readonly attempt: number }
| { readonly type: "reply.timed-out"; readonly runId: string; readonly attempt: number }
| { readonly type: "retry.due"; readonly runId: string; readonly attempt: number }
| { readonly type: "cancel" }
| { readonly type: "resolved" }
export type AutoApproveEffect =
| { readonly type: "reply"; readonly sessionID: string; readonly runId: string; readonly attempt: number }
| {
readonly type: "reply"
readonly sessionID: string
readonly runId: string
readonly attempt: number
readonly timeoutMs: number
}
// Stops waiting on the current reply. The request itself runs on; `runId` and `attempt` fence its late result.
| { readonly type: "clear-reply-timer" }
| { readonly type: "schedule-retry"; readonly runId: string; readonly attempt: number; readonly delayMs: number }
| { readonly type: "cancel-retry" }
@ -53,13 +71,14 @@ export function transitionAutoApprove(state: AutoApproveState, event: AutoApprov
if (event.type === "resolved") {
if (state.status === "pending" || state.status === "replied") return unchanged(state)
return changed({ status: "replied" }, state.status === "waiting-retry" ? [{ type: "cancel-retry" }] : [])
return changed({ status: "replied" }, stop(state))
}
// Turning auto-approve off ends the cycle, so a reply still in flight settles into nothing and schedules no retry.
if (event.type === "cancel") {
if (state.status === "pending" || state.status === "replied") return unchanged(state)
return changed(INITIAL_AUTO_APPROVE_STATE, state.status === "waiting-retry" ? [{ type: "cancel-retry" }] : [])
return changed(INITIAL_AUTO_APPROVE_STATE, stop(state))
}
// Store scans and sweeps approve repeatedly; only a request no cycle owns starts one. An exhausted request stays
@ -69,32 +88,32 @@ export function transitionAutoApprove(state: AutoApproveState, event: AutoApprov
return changed(
{ status: "replying", sessionID: event.sessionID, projectID: event.projectID, runId: event.runId, attempt: 0 },
[{ type: "reply", sessionID: event.sessionID, runId: event.runId, attempt: 0 }],
[reply(event.sessionID, event.runId, 0)],
)
}
if (event.type === "reply.succeeded") {
if (state.status !== "replying" || !current(state, event)) return unchanged(state)
return changed({ status: "replied" })
return changed({ status: "replied" }, [{ type: "clear-reply-timer" }])
}
if (event.type === "reply.failed") {
if (event.type === "reply.failed" || event.type === "reply.timed-out") {
if (state.status !== "replying" || !current(state, event)) return unchanged(state)
if (state.attempt >= AUTO_APPROVE_RETRY_LIMIT) return changed({ status: "gave-up", projectID: state.projectID })
if (state.attempt >= AUTO_APPROVE_RETRY_LIMIT)
return changed({ status: "gave-up", projectID: state.projectID }, [{ type: "clear-reply-timer" }])
const attempt = state.attempt + 1
return changed({ ...state, status: "waiting-retry", attempt }, [
{ type: "clear-reply-timer" },
{ type: "schedule-retry", runId: state.runId, attempt, delayMs: AUTO_APPROVE_RETRY_DELAY_MS * attempt },
])
}
if (state.status !== "waiting-retry" || !current(state, event)) return unchanged(state)
return changed({ ...state, status: "replying" }, [
{ type: "reply", sessionID: state.sessionID, runId: state.runId, attempt: state.attempt },
])
return changed({ ...state, status: "replying" }, [reply(state.sessionID, state.runId, state.attempt)])
}
// Whether a pending request waits on the user, so the permission dock shows it and every badge counts it.
@ -107,6 +126,103 @@ export function needsUser(state: AutoApproveState, autoApprove: boolean) {
return !autoApprove
}
// The connect sweep of one server: it finds requests asked while this client was disconnected, or before auto-approve
// turned on. A finished and an exhausted sweep both rest in `idle`; nothing tells them apart until the next start.
export type AutoApproveSweepState =
| { readonly status: "idle" }
| { readonly status: "sweeping"; readonly runId: string; readonly attempt: number }
| { readonly status: "waiting-retry"; readonly runId: string; readonly attempt: number }
export type AutoApproveSweepEvent =
| { readonly type: "sweep.start"; readonly runId: string }
| { readonly type: "sweep.succeeded"; readonly runId: string; readonly attempt: number }
| { readonly type: "sweep.failed"; readonly runId: string; readonly attempt: number }
| { readonly type: "sweep.timed-out"; readonly runId: string; readonly attempt: number }
| { readonly type: "sweep.retry-due"; readonly runId: string; readonly attempt: number }
| { readonly type: "sweep.cancel" }
export type AutoApproveSweepEffect =
| { readonly type: "sweep.run"; readonly runId: string; readonly attempt: number; readonly timeoutMs: number }
// Stops the current sweep's requests and its timeout.
| { readonly type: "sweep.abort" }
| {
readonly type: "sweep.schedule-retry"
readonly runId: string
readonly attempt: number
readonly delayMs: number
}
| { readonly type: "sweep.cancel-retry" }
export type AutoApproveSweepTransition = {
readonly state: AutoApproveSweepState
readonly effects: readonly AutoApproveSweepEffect[]
}
export const INITIAL_AUTO_APPROVE_SWEEP_STATE: AutoApproveSweepState = Object.freeze({ status: "idle" })
export function transitionAutoApproveSweep(
state: AutoApproveSweepState,
event: AutoApproveSweepEvent,
): AutoApproveSweepTransition {
// A newer connect or setting change replaces the sweep in progress, or the retry it waits for.
if (event.type === "sweep.start")
return sweepChanged({ status: "sweeping", runId: event.runId, attempt: 0 }, [
...stopSweep(state),
run(event.runId, 0),
])
if (event.type === "sweep.cancel") {
if (state.status === "idle") return sweepUnchanged(state)
return sweepChanged(INITIAL_AUTO_APPROVE_SWEEP_STATE, stopSweep(state))
}
if (event.type === "sweep.retry-due") {
if (state.status !== "waiting-retry" || !current(state, event)) return sweepUnchanged(state)
return sweepChanged({ status: "sweeping", runId: state.runId, attempt: state.attempt }, [
run(state.runId, state.attempt),
])
}
if (state.status !== "sweeping" || !current(state, event)) return sweepUnchanged(state)
// An incomplete sweep leaves pending requests hidden with no later trigger to recover them, so it retries a bounded
// number of times.
if (event.type === "sweep.succeeded" || state.attempt >= AUTO_APPROVE_RETRY_LIMIT)
return sweepChanged(INITIAL_AUTO_APPROVE_SWEEP_STATE, [{ type: "sweep.abort" }])
const attempt = state.attempt + 1
return sweepChanged({ status: "waiting-retry", runId: state.runId, attempt }, [
{ type: "sweep.abort" },
{ type: "sweep.schedule-retry", runId: state.runId, attempt, delayMs: AUTO_APPROVE_RETRY_DELAY_MS * attempt },
])
}
function reply(sessionID: string, runId: string, attempt: number): AutoApproveEffect {
return { type: "reply", sessionID, runId, attempt, timeoutMs: AUTO_APPROVE_REPLY_TIMEOUT_MS }
}
function stop(state: AutoApproveState): AutoApproveEffect[] {
if (state.status === "replying") return [{ type: "clear-reply-timer" }]
if (state.status === "waiting-retry") return [{ type: "cancel-retry" }]
return []
}
function run(runId: string, attempt: number): AutoApproveSweepEffect {
return { type: "sweep.run", runId, attempt, timeoutMs: AUTO_APPROVE_SWEEP_TIMEOUT_MS }
}
function stopSweep(state: AutoApproveSweepState): AutoApproveSweepEffect[] {
if (state.status === "sweeping") return [{ type: "sweep.abort" }]
if (state.status === "waiting-retry") return [{ type: "sweep.cancel-retry" }]
return []
}
function current(state: { runId: string; attempt: number }, event: { runId: string; attempt: number }) {
return state.runId === event.runId && state.attempt === event.attempt
}
@ -118,3 +234,14 @@ function changed(state: AutoApproveState, effects: readonly AutoApproveEffect[]
function unchanged(state: AutoApproveState): AutoApproveTransition {
return { state, effects: [] }
}
function sweepChanged(
state: AutoApproveSweepState,
effects: readonly AutoApproveSweepEffect[] = [],
): AutoApproveSweepTransition {
return { state, effects }
}
function sweepUnchanged(state: AutoApproveSweepState): AutoApproveSweepTransition {
return { state, effects: [] }
}

View file

@ -7,13 +7,15 @@ import { uuid } from "@opencode/util/uuid"
import type { ServerSDK } from "@/runtime/server/client"
import { projectSettingsKey, useSettings } from "@/settings/model"
import {
AUTO_APPROVE_RETRY_DELAY_MS,
AUTO_APPROVE_RETRY_LIMIT,
INITIAL_AUTO_APPROVE_STATE,
INITIAL_AUTO_APPROVE_SWEEP_STATE,
transitionAutoApprove,
transitionAutoApproveSweep,
type AutoApproveEffect,
type AutoApproveEvent,
type AutoApproveState,
type AutoApproveSweepEffect,
type AutoApproveSweepEvent,
} from "./auto-approve-machine"
const repliedLimit = 1000
@ -29,8 +31,12 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
// Requests in the initial `pending` state have no entry.
const [requests, setRequests] = createStore<Record<string, AutoApproveState | undefined>>({})
const timers = new Map<string, ReturnType<typeof setTimeout>>()
const replyTimers = new Map<string, ReturnType<typeof setTimeout>>()
const retries = new Map<string, ReturnType<typeof setTimeout>>()
const scope = new AbortController()
let sweepState = INITIAL_AUTO_APPROVE_SWEEP_STATE
let sweepRun: { controller: AbortController; timer: ReturnType<typeof setTimeout> } | undefined
let sweepRetry: ReturnType<typeof setTimeout> | undefined
const unsubscribe = [
input.sdk.event.on("permission.asked", (event) => {
@ -42,6 +48,7 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
onCleanup(() => {
abort(scope)
unsubscribe.forEach((stop) => stop())
dispatchSweep({ type: "sweep.cancel" })
// Back to pending, so replies still in flight settle into nothing and no retry is scheduled.
untrack(() => Object.keys(requests)).forEach((id) => dispatch(id, { type: "cancel" }))
})
@ -49,12 +56,11 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
// The event stream does not replay requests asked while this client was
// disconnected, and requests may already be pending before the setting turns
// on, so sweep on every connect while the setting is on. A newer connect or
// a change of the setting aborts the sweep and its scheduled retries.
// a change of the setting replaces the sweep and its scheduled retries.
createEffect(() => {
if (!enabled() || input.sdk.connection.status() !== "connected") return
const controller = new AbortController()
onCleanup(() => abort(controller))
void sweepWithRetry(controller.signal, 0)
const on = enabled() && input.sdk.connection.status() === "connected"
untrack(() => dispatchSweep(on ? { type: "sweep.start", runId: uuid() } : { type: "sweep.cancel" }))
})
// Approves pending requests that reach the local store, which is how a
@ -93,29 +99,83 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
}
function execute(requestID: string, effect: AutoApproveEffect) {
if (effect.type === "clear-reply-timer") {
clearTimeout(replyTimers.get(requestID))
replyTimers.delete(requestID)
return
}
if (effect.type === "reply") {
// A request another client already answered counts as replied.
const result = { runId: effect.runId, attempt: effect.attempt }
replyTimers.set(
requestID,
setTimeout(() => dispatch(requestID, { type: "reply.timed-out", ...result }), effect.timeoutMs),
)
// A request another client, or an earlier attempt whose response was lost, already answered counts as replied.
void input.data.session.permission.reply({ sessionID: effect.sessionID, requestID, decision: "once" }).then(
() => dispatch(requestID, { type: "reply.succeeded", runId: effect.runId, attempt: effect.attempt }),
() => dispatch(requestID, { type: "reply.failed", runId: effect.runId, attempt: effect.attempt }),
() => dispatch(requestID, { type: "reply.succeeded", ...result }),
() => dispatch(requestID, { type: "reply.failed", ...result }),
)
return
}
clearTimeout(timers.get(requestID))
timers.delete(requestID)
clearTimeout(retries.get(requestID))
retries.delete(requestID)
if (effect.type === "cancel-retry") return
timers.set(
retries.set(
requestID,
setTimeout(() => {
timers.delete(requestID)
retries.delete(requestID)
dispatch(requestID, { type: "retry.due", runId: effect.runId, attempt: effect.attempt })
}, effect.delayMs),
)
}
function dispatchSweep(event: AutoApproveSweepEvent) {
const result = transitionAutoApproveSweep(sweepState, event)
sweepState = result.state
result.effects.forEach(executeSweep)
}
function executeSweep(effect: AutoApproveSweepEffect) {
if (effect.type === "sweep.abort") {
clearTimeout(sweepRun?.timer)
abort(sweepRun?.controller)
sweepRun = undefined
return
}
if (effect.type === "sweep.run") {
const controller = new AbortController()
const result = { runId: effect.runId, attempt: effect.attempt }
sweepRun = {
controller,
timer: setTimeout(() => dispatchSweep({ type: "sweep.timed-out", ...result }), effect.timeoutMs),
}
void sweep(controller.signal).then(
(complete) => dispatchSweep({ type: complete ? "sweep.succeeded" : "sweep.failed", ...result }),
() => dispatchSweep({ type: "sweep.failed", ...result }),
)
return
}
clearTimeout(sweepRetry)
sweepRetry = undefined
if (effect.type === "sweep.cancel-retry") return
sweepRetry = setTimeout(() => {
sweepRetry = undefined
dispatchSweep({ type: "sweep.retry-due", runId: effect.runId, attempt: effect.attempt })
}, effect.delayMs)
}
function pruneReplied() {
const replied = untrack(() =>
Object.entries(requests).flatMap(([id, state]) => (state?.status === "replied" ? [id] : [])),
@ -125,30 +185,18 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
setRequests(produce((draft) => replied.slice(0, replied.length - repliedLimit).forEach((id) => delete draft[id])))
}
// An incomplete sweep leaves pending requests hidden with no later trigger
// to recover them, so retry it a bounded number of times.
async function sweepWithRetry(signal: AbortSignal, attempt: number) {
const complete = await sweep(signal)
if (complete || attempt >= AUTO_APPROVE_RETRY_LIMIT || signal.aborted) return
const timer = setTimeout(
() => void sweepWithRetry(signal, attempt + 1),
AUTO_APPROVE_RETRY_DELAY_MS * (attempt + 1),
)
signal.addEventListener("abort", () => clearTimeout(timer), { once: true })
}
async function sweep(signal: AbortSignal) {
const inventory = await sweepLocations()
const inventory = await sweepLocations(signal)
if (signal.aborted) return false
const listed = await Promise.all(
inventory.locations.map((location) =>
input.sdk.api.permission.request
.list({ location: { directory: location.directory } })
.list({ location: { directory: location.directory } }, { signal })
.then((pending) => {
if (!signal.aborted) pending.data.forEach((request) => consider(request, signal))
// A request already found still gets its project looked up if a slower location runs the sweep out.
if (!signal.aborted) pending.data.forEach((request) => consider(request, scope.signal))
return true
})
@ -166,8 +214,10 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
// external session.permission.create API can park a request on an idle
// session. A detached request on a session this client never loaded is the
// one case that stays uncovered.
async function sweepLocations() {
const active = await input.sdk.api.session.active().catch(() => undefined)
async function sweepLocations(signal: AbortSignal) {
const active = await input.sdk.api.session.active({ signal }).catch(() => undefined)
if (signal.aborted) return { locations: [], complete: false }
const ids = Object.keys(active ?? {})
// Resync every active session rather than trusting cached info: another
@ -195,9 +245,7 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
]
return {
locations: [
...new Map(locations.map((item) => [item.directory, item])).values(),
],
locations: [...new Map(locations.map((item) => [item.directory, item])).values()],
complete: active !== undefined && synced.every(Boolean),
}
}
@ -207,7 +255,7 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
function consider(permission: PermissionRequest, signal: AbortSignal) {
if (covers(undefined) || input.data.session.get(permission.sessionID)) return approve(permission)
void input.sdk.api.session
.get({ sessionID: permission.sessionID })
.get({ sessionID: permission.sessionID }, { signal })
.then((session) => {
if (!signal.aborted) approve(permission, session.projectID)
})

View file

@ -0,0 +1,129 @@
import { createMemo, createSignal, onCleanup, runWithOwner, untrack } from "solid-js"
import type { FormInfo, LocationRef } from "@opencode/client/promise"
import type { Data } from "@opencode/client/solid"
import type { ServerSDK } from "@/runtime/server/client"
import { ScopedKey } from "@/runtime/server/scope"
import { showToast } from "@/shell/notifications/toast"
import {
ELICITATION_REQUEST_TIMEOUT_MS,
buildElicitationAnswer,
createElicitationDockState,
elicitationFields,
isElicitationBusy,
selectElicitationDraft,
transitionElicitationDock,
type ElicitationDockEvent,
type ElicitationDraft,
} from "./elicitation-machine"
const ELICITATION_CACHE_LIMIT = 100
// Drafts of elicitations whose dock unmounted unanswered, newest last. Forms answered or cancelled while their dock is
// away never come back to read theirs, so the oldest give way past the limit.
const drafts = new Map<string, ElicitationDraft>()
export const elicitationCache = {
get: (key: string) => drafts.get(key),
set(key: string, draft: ElicitationDraft) {
drafts.delete(key)
drafts.set(key, draft)
if (drafts.size <= ELICITATION_CACHE_LIMIT) return
const oldest = drafts.keys().next()
if (!oldest.done) drafts.delete(oldest.value)
},
delete: (key: string) => void drafts.delete(key),
}
// The fields, answers and reply of one MCP elicitation dock. The data layer sends the reply: it addresses Location
// elicitations by directory, counts a form already settled elsewhere as sent, and drops the answered form from the list.
export function createElicitationDock(input: {
sdk: Pick<ServerSDK, "scope" | "event">
forms: Pick<Data["session"]["form"], "reply" | "cancel">
language: { t: (key: "common.requestFailed") => string }
request: () => FormInfo & { location?: LocationRef }
onSubmit: () => void
}) {
const serverSDK = input.sdk
const cacheKey = ScopedKey.from(serverSDK.scope, untrack(input.request).id)
const fields = createMemo(() => elicitationFields(input.request().fields))
const [dockState, setDockState] = createSignal(
createElicitationDockState(untrack(input.request).fields, elicitationCache.get(cacheKey)),
)
let timeout: ReturnType<typeof setTimeout> | undefined
const dispatch = (event: ElicitationDockEvent) => {
const prev = untrack(dockState)
const result = transitionElicitationDock(prev, event)
if (result.state !== prev) setDockState(result.state)
if (result.state.status === "disposed" && !result.state.unsent) unlisten()
result.effects.forEach((effect) => {
if (effect.type === "notify.submit") return input.onSubmit()
if (effect.type === "cache.save") return elicitationCache.set(cacheKey, effect.draft)
if (effect.type === "cache.delete") return elicitationCache.delete(cacheKey)
if (effect.type === "timeout.clear") return clearTimeout(timeout)
if (effect.type === "toast.fail")
return showToast({ title: input.language.t("common.requestFailed"), description: effect.error })
const request = untrack(input.request)
const attempt = effect.attempt
const action = effect.action
const target = { sessionID: request.sessionID, formID: request.id }
clearTimeout(timeout)
timeout = setTimeout(() => dispatch({ type: "request.timed-out", attempt }), ELICITATION_REQUEST_TIMEOUT_MS)
void Promise.try(() =>
action.type === "reply"
? input.forms.reply({ ...target, answer: action.answer }, request.location)
: input.forms.cancel(target, request.location),
).then(
() => dispatch({ type: "request.succeeded", attempt }),
(error) =>
dispatch({ type: "request.failed", attempt, error: error instanceof Error ? error.message : String(error) }),
)
})
}
const resolved = (event: { data: { id: string } }) => {
if (event.data.id === untrack(input.request).id) dispatch({ type: "resolved" })
}
// The form's settling events are heard until the reply settles, not only while the dock is mounted: a reply whose
// response stalls after the server accepted it ends on `form.replied`, not on a false timeout. Subscribed outside the
// owner, since the event bus otherwise drops the listeners when the dock unmounts.
const listeners = runWithOwner(null, () => [
serverSDK.event.on("form.replied", resolved),
serverSDK.event.on("form.cancelled", resolved),
])
const unlisten = () => listeners?.forEach((off) => off())
// A reply already sent keeps going without the dock, with its timeout, so a failure still reports and keeps the draft.
onCleanup(() => dispatch({ type: "disposed" }))
return {
fields,
busy: () => isElicitationBusy(dockState()),
draft: () => selectElicitationDraft(dockState()),
setText: (key: string, value: string) => dispatch({ type: "text.set", key, value }),
setNumber: (key: string, value: string) => dispatch({ type: "number.set", key, value }),
setFlag: (key: string, value: boolean) => dispatch({ type: "flag.set", key, value }),
toggle: (key: string, value: string, checked: boolean) => dispatch({ type: "list.toggle", key, value, checked }),
reply() {
const current = untrack(dockState)
if (current.status !== "answering") return
dispatch({ type: "send", action: { type: "reply", answer: buildElicitationAnswer(fields(), current.draft) } })
},
dismiss: () => dispatch({ type: "send", action: { type: "cancel" } }),
}
}

View file

@ -0,0 +1,209 @@
import { describe, expect, test } from "bun:test"
import type { FormInfo } from "@opencode/client/promise"
import {
buildElicitationAnswer,
createElicitationDockState,
isElicitationBusy,
selectElicitationDraft,
transitionElicitationDock,
type ElicitationDockEvent,
type ElicitationDockState,
type ElicitationDockTransition,
} from "./elicitation-machine"
const fields: FormInfo["fields"] = [
{ key: "name", type: "string", title: "Name", default: " Ada " },
{ key: "count", type: "integer", title: "Count" },
{ key: "ratio", type: "number", title: "Ratio" },
{ key: "notify", type: "boolean", title: "Notify" },
{
key: "areas",
type: "multiselect",
title: "Areas",
options: [
{ value: "app", label: "App" },
{ value: "tui", label: "TUI" },
],
},
{ key: "auth", type: "external", url: "https://example.com/authorize" },
]
const edits: ElicitationDockEvent[] = [
{ type: "text.set", key: "name", value: "Grace" },
{ type: "number.set", key: "count", value: "-" },
{ type: "number.set", key: "ratio", value: "0.5" },
{ type: "flag.set", key: "notify", value: true },
{ type: "list.toggle", key: "areas", value: "tui", checked: true },
]
const reply = { type: "reply", answer: { name: "Grace" } } as const
function replay(events: ElicitationDockEvent[], from: ElicitationDockState = createElicitationDockState(fields)) {
return events.reduce<ElicitationDockTransition[]>((steps, event) => {
steps.push(transitionElicitationDock(steps.at(-1)?.state ?? from, event))
return steps
}, [])
}
function last(events: ElicitationDockEvent[], from?: ElicitationDockState) {
return replay(events, from).at(-1)!
}
describe("transitionElicitationDock", () => {
// Two mutations used to run side by side, and the dock re-enabled as soon as the reply resolved.
test("one send claims the dock, a second one is ignored and it stays busy after the reply lands", () => {
const sending = last([{ type: "send", action: reply }])
expect(sending.state).toMatchObject({ status: "sending", attempt: 1, action: reply })
expect(sending.effects).toEqual([
{ type: "cache.delete" },
{ type: "request.send", attempt: 1, action: reply },
{ type: "notify.submit" },
])
expect(isElicitationBusy(sending.state)).toBe(true)
const again = transitionElicitationDock(sending.state, { type: "send", action: { type: "cancel" } })
expect(again.state).toBe(sending.state)
expect(again.effects).toEqual([])
const replied = transitionElicitationDock(sending.state, { type: "request.succeeded", attempt: 1 })
expect(replied.state.status).toBe("replied")
expect(replied.effects).toEqual([{ type: "timeout.clear" }])
expect(isElicitationBusy(replied.state)).toBe(true)
;[{ type: "send", action: reply } as const, { type: "send", action: { type: "cancel" } } as const].forEach(
(event) => expect(transitionElicitationDock(replied.state, event).state).toBe(replied.state),
)
})
// A hung request used to keep every control disabled.
test("a request that never settles gives the dock back with the draft, and its late result is ignored", () => {
const edited = last(edits).state
const timedOut = last(
[
{ type: "send", action: reply },
{ type: "request.timed-out", attempt: 1 },
],
edited,
)
expect(timedOut.state).toEqual({ status: "answering", attempt: 1, draft: selectElicitationDraft(edited) })
expect(timedOut.effects).toEqual([{ type: "timeout.clear" }, { type: "toast.fail", error: undefined }])
const late = transitionElicitationDock(timedOut.state, { type: "request.failed", attempt: 1, error: "aborted" })
expect(late.state).toBe(timedOut.state)
expect(late.effects).toEqual([])
const retry = transitionElicitationDock(timedOut.state, { type: "send", action: reply })
expect(retry.state).toMatchObject({ status: "sending", attempt: 2 })
expect(transitionElicitationDock(retry.state, { type: "request.succeeded", attempt: 1 }).state).toBe(retry.state)
})
test("a failed request reports its error and gives the dock back", () => {
const failed = last([
{ type: "send", action: { type: "cancel" } },
{ type: "request.failed", attempt: 1, error: "offline" },
])
expect(failed.state.status).toBe("answering")
expect(failed.effects).toEqual([{ type: "timeout.clear" }, { type: "toast.fail", error: "offline" }])
})
// Unmounting the dock (a tab switch, a form resync) used to drop every typed answer.
test("an unanswered dock keeps its draft for the next mount", () => {
const edited = last(edits).state
const disposed = transitionElicitationDock(edited, { type: "disposed" })
const draft = selectElicitationDraft(edited)
expect(disposed.state).toEqual({ status: "disposed", attempt: 0, unsent: undefined })
expect(disposed.effects).toEqual([{ type: "cache.save", draft }])
expect(createElicitationDockState(fields, draft)).toEqual({ status: "answering", attempt: 0, draft })
expect(draft).toEqual({
text: { name: "Grace" },
number: { count: "-", ratio: "0.5" },
flag: { notify: true },
list: { areas: ["tui"] },
})
})
test("a reply in flight when the dock unmounts keeps its draft until it settles", () => {
const edited = last(edits).state
const draft = selectElicitationDraft(edited)
const disposed = last([{ type: "send", action: reply }, { type: "disposed" }], edited)
expect(disposed).toEqual({ state: { status: "disposed", attempt: 1, unsent: draft }, effects: [] })
const settled: ElicitationDockState = { status: "disposed", attempt: 1, unsent: undefined }
expect(transitionElicitationDock(disposed.state, { type: "request.failed", attempt: 1, error: "offline" })).toEqual(
{
state: settled,
effects: [{ type: "timeout.clear" }, { type: "toast.fail", error: "offline" }, { type: "cache.save", draft }],
},
)
expect(transitionElicitationDock(disposed.state, { type: "request.timed-out", attempt: 1 })).toEqual({
state: settled,
effects: [{ type: "timeout.clear" }, { type: "toast.fail", error: undefined }, { type: "cache.save", draft }],
})
expect(transitionElicitationDock(disposed.state, { type: "request.succeeded", attempt: 1 })).toEqual({
state: settled,
effects: [{ type: "timeout.clear" }],
})
expect(transitionElicitationDock(disposed.state, { type: "resolved" })).toEqual({
state: settled,
effects: [{ type: "timeout.clear" }],
})
expect(transitionElicitationDock(disposed.state, { type: "request.failed", attempt: 0 }).state).toBe(disposed.state)
})
test("the form settling elsewhere closes the dock and drops its draft", () => {
expect(last([{ type: "resolved" }])).toEqual({
state: { status: "replied", attempt: 0, draft: selectElicitationDraft(createElicitationDockState(fields)) },
effects: [{ type: "cache.delete" }],
})
expect(last([{ type: "send", action: reply }, { type: "resolved" }]).effects).toEqual([
{ type: "timeout.clear" },
{ type: "cache.delete" },
])
const replied = last([{ type: "resolved" }]).state
const settled: ElicitationDockState = { status: "disposed", attempt: 0, unsent: undefined }
expect(transitionElicitationDock(replied, { type: "resolved" }).state).toBe(replied)
expect(transitionElicitationDock(settled, { type: "resolved" }).state).toBe(settled)
})
test("an edit that changes nothing keeps the same state", () => {
const state = createElicitationDockState(fields)
const unchanged: ElicitationDockEvent[] = [
{ type: "text.set", key: "name", value: " Ada " },
{ type: "number.set", key: "count", value: "" },
{ type: "flag.set", key: "notify", value: false },
{ type: "list.toggle", key: "areas", value: "app", checked: false },
]
unchanged.forEach((event) => expect(transitionElicitationDock(state, event).state).toBe(state))
})
})
test("buildElicitationAnswer", () => {
const draft = selectElicitationDraft(
last(
[
{ type: "number.set", key: "count", value: " 3 " },
{ type: "list.toggle", key: "areas", value: "app", checked: true },
],
createElicitationDockState([...fields, { key: "secret", type: "string", hidden: true, default: "x" }]),
).state,
)
expect(
buildElicitationAnswer([...fields, { key: "secret", type: "string", hidden: true, default: "x" }], draft),
).toEqual({ name: "Ada", count: 3, notify: false, areas: ["app"], auth: true })
})

View file

@ -0,0 +1,277 @@
import type { FormAnswer, FormInfo, FormValue } from "@opencode/client/promise"
// A reply or dismissal that never settles gives the dock back after this long, so it cannot stay disabled forever.
export const ELICITATION_REQUEST_TIMEOUT_MS = 30_000
export type ElicitationField = FormInfo["fields"][number]
// Number inputs keep their raw text so a half-typed value such as "-" is not discarded.
export type ElicitationDraft = {
readonly text: Readonly<Record<string, string>>
readonly number: Readonly<Record<string, string>>
readonly flag: Readonly<Record<string, boolean>>
readonly list: Readonly<Record<string, readonly string[]>>
}
export type ElicitationAction = { readonly type: "reply"; readonly answer: FormAnswer } | { readonly type: "cancel" }
export type ElicitationDockState =
| { readonly status: "answering"; readonly attempt: number; readonly draft: ElicitationDraft }
| {
readonly status: "sending"
readonly attempt: number
readonly draft: ElicitationDraft
readonly action: ElicitationAction
}
| { readonly status: "replied"; readonly attempt: number; readonly draft: ElicitationDraft }
// `unsent` is the draft of a reply still in flight when the dock went away, kept until the reply settles.
| { readonly status: "disposed"; readonly attempt: number; readonly unsent: ElicitationDraft | undefined }
export type ElicitationDockEvent =
| { readonly type: "text.set"; readonly key: string; readonly value: string }
| { readonly type: "number.set"; readonly key: string; readonly value: string }
| { readonly type: "flag.set"; readonly key: string; readonly value: boolean }
| { readonly type: "list.toggle"; readonly key: string; readonly value: string; readonly checked: boolean }
| { readonly type: "send"; readonly action: ElicitationAction }
| { readonly type: "request.succeeded"; readonly attempt: number }
| { readonly type: "request.failed"; readonly attempt: number; readonly error?: string }
| { readonly type: "request.timed-out"; readonly attempt: number }
// `form.replied` or `form.cancelled` arrived for this form.
| { readonly type: "resolved" }
| { readonly type: "disposed" }
export type ElicitationDockEffect =
| { readonly type: "notify.submit" }
| { readonly type: "cache.save"; readonly draft: ElicitationDraft }
| { readonly type: "cache.delete" }
| { readonly type: "request.send"; readonly attempt: number; readonly action: ElicitationAction }
// Stops waiting on the request. The request itself runs on; the attempt fences its late result.
| { readonly type: "timeout.clear" }
| { readonly type: "toast.fail"; readonly error?: string }
export type ElicitationDockTransition = {
readonly state: ElicitationDockState
readonly effects: readonly ElicitationDockEffect[]
}
const EMPTY_DRAFT: ElicitationDraft = Object.freeze({
text: Object.freeze({}),
number: Object.freeze({}),
flag: Object.freeze({}),
list: Object.freeze({}),
})
export function elicitationFields(fields: readonly ElicitationField[]) {
return fields.filter((field) => !("hidden" in field && field.hidden))
}
// Field defaults, overlaid by the draft a previous mount of the dock left behind.
export function createElicitationDockState(
fields: readonly ElicitationField[],
cached?: ElicitationDraft,
): ElicitationDockState {
return {
status: "answering",
attempt: 0,
draft: {
text: {
...Object.fromEntries(
fields.flatMap((field) => (field.type === "string" ? [[field.key, field.default ?? ""]] : [])),
),
...cached?.text,
},
number: {
...Object.fromEntries(
fields.flatMap((field) =>
(field.type === "number" || field.type === "integer") && field.default !== undefined
? [[field.key, String(field.default)]]
: [],
),
),
...cached?.number,
},
flag: {
...Object.fromEntries(
fields.flatMap((field) => (field.type === "boolean" ? [[field.key, field.default ?? false]] : [])),
),
...cached?.flag,
},
list: {
...Object.fromEntries(
fields.flatMap((field) => (field.type === "multiselect" ? [[field.key, [...(field.default ?? [])]]] : [])),
),
...cached?.list,
},
},
}
}
export function transitionElicitationDock(
state: ElicitationDockState,
event: ElicitationDockEvent,
): ElicitationDockTransition {
if (state.status === "disposed") return transitionDisposed(state, event)
if (event.type === "request.succeeded") {
if (state.status !== "sending" || state.attempt !== event.attempt) return unchanged(state)
return changed({ status: "replied", attempt: state.attempt, draft: state.draft }, [{ type: "timeout.clear" }])
}
if (event.type === "request.failed" || event.type === "request.timed-out") {
if (state.status !== "sending" || state.attempt !== event.attempt) return unchanged(state)
return changed({ status: "answering", attempt: state.attempt, draft: state.draft }, [
{ type: "timeout.clear" },
{ type: "toast.fail", error: event.type === "request.failed" ? event.error : undefined },
])
}
// The server settled the form, from this client or another one: nothing is left to send or keep.
if (event.type === "resolved") {
if (state.status === "replied") return unchanged(state)
return changed({ status: "replied", attempt: state.attempt, draft: state.draft }, [
...(state.status === "sending" ? [{ type: "timeout.clear" } as const] : []),
{ type: "cache.delete" },
])
}
// An unanswered form keeps its draft for when the dock comes back. A reply already sent finishes on its own, and
// keeps its draft until it settles, in case it fails.
if (event.type === "disposed") {
if (state.status === "answering")
return changed({ status: "disposed", attempt: state.attempt, unsent: undefined }, [
{ type: "cache.save", draft: state.draft },
])
return changed({
status: "disposed",
attempt: state.attempt,
unsent: state.status === "sending" ? state.draft : undefined,
})
}
// Submit, Dismiss, Escape and Cmd+Enter all land here, so only the first of them leaves `answering`.
if (state.status !== "answering") return unchanged(state)
// The request leaves before the dock's owner hears of the submit, which may unmount the dock.
if (event.type === "send") {
const attempt = state.attempt + 1
return changed({ status: "sending", attempt, draft: state.draft, action: event.action }, [
{ type: "cache.delete" },
{ type: "request.send", attempt, action: event.action },
{ type: "notify.submit" },
])
}
const draft = nextDraft(state.draft, event)
if (draft === state.draft) return unchanged(state)
return changed({ status: "answering", attempt: state.attempt, draft })
}
function nextDraft(
draft: ElicitationDraft,
event: Extract<ElicitationDockEvent, { type: "text.set" | "number.set" | "flag.set" | "list.toggle" }>,
): ElicitationDraft {
if (event.type === "text.set") {
if ((draft.text[event.key] ?? "") === event.value) return draft
return { ...draft, text: { ...draft.text, [event.key]: event.value } }
}
if (event.type === "number.set") {
if ((draft.number[event.key] ?? "") === event.value) return draft
return { ...draft, number: { ...draft.number, [event.key]: event.value } }
}
if (event.type === "flag.set") {
if ((draft.flag[event.key] ?? false) === event.value) return draft
return { ...draft, flag: { ...draft.flag, [event.key]: event.value } }
}
const current = draft.list[event.key] ?? []
if (current.includes(event.value) === event.checked) return draft
return {
...draft,
list: {
...draft.list,
[event.key]: event.checked ? [...current, event.value] : current.filter((value) => value !== event.value),
},
}
}
// A reply sent before the dock went away still settles: a failure or timeout reports it and keeps its draft for when
// the dock comes back; a success, or the form settling, drops the draft.
function transitionDisposed(
state: Extract<ElicitationDockState, { status: "disposed" }>,
event: ElicitationDockEvent,
): ElicitationDockTransition {
if (!state.unsent) return unchanged(state)
const settled: ElicitationDockState = { status: "disposed", attempt: state.attempt, unsent: undefined }
if (event.type === "resolved") return changed(settled, [{ type: "timeout.clear" }])
if (event.type !== "request.succeeded" && event.type !== "request.failed" && event.type !== "request.timed-out")
return unchanged(state)
if (event.attempt !== state.attempt) return unchanged(state)
if (event.type === "request.succeeded") return changed(settled, [{ type: "timeout.clear" }])
return changed(settled, [
{ type: "timeout.clear" },
{ type: "toast.fail", error: event.type === "request.failed" ? event.error : undefined },
{ type: "cache.save", draft: state.unsent },
])
}
/** True while a reply or dismissal is in flight, after it settles, and after the dock went away. */
export function isElicitationBusy(state: ElicitationDockState) {
return state.status !== "answering"
}
export function selectElicitationDraft(state: ElicitationDockState) {
return state.status === "disposed" ? (state.unsent ?? EMPTY_DRAFT) : state.draft
}
export function buildElicitationAnswer(fields: readonly ElicitationField[], draft: ElicitationDraft): FormAnswer {
return Object.fromEntries(
elicitationFields(fields).flatMap((field): Array<[string, FormValue]> => {
if (field.type === "external") return [[field.key, true]]
if (field.type === "boolean") return [[field.key, draft.flag[field.key] ?? false]]
if (field.type === "multiselect") {
const list = draft.list[field.key] ?? []
return list.length ? [[field.key, [...list]]] : []
}
const text = (field.type === "string" ? draft.text[field.key] : draft.number[field.key])?.trim()
if (!text) return []
return [[field.key, field.type === "string" ? text : Number(text)]]
}),
)
}
function changed(
state: ElicitationDockState,
effects: readonly ElicitationDockEffect[] = [],
): ElicitationDockTransition {
return { state, effects }
}
function unchanged(state: ElicitationDockState): ElicitationDockTransition {
return { state, effects: [] }
}

View file

@ -1,8 +1,6 @@
import { For, Match, Show, Switch as Branch, createMemo } from "solid-js"
import { For, Match, Show, Switch as Branch } from "solid-js"
import { Option, Schema } from "effect"
import { createStore } from "solid-js/store"
import { useMutation } from "@tanstack/solid-query"
import type { FormAnswer, FormInfo, FormStringField, FormValue, LocationRef } from "@opencode/client/promise"
import type { FormInfo, FormStringField, LocationRef } from "@opencode/client/promise"
import { Button } from "@opencode/ui/button"
import { Checkbox } from "@opencode/ui/checkbox"
import { Select } from "@opencode/ui/select"
@ -10,10 +8,11 @@ import { Switch } from "@opencode/ui/switch"
import { TextInput } from "@opencode/ui/text-input"
import { DockPrompt } from "@opencode/session-ui/dock-prompt"
import { LinkedText } from "@opencode/session-ui/linked-text"
import { showToast } from "@/shell/notifications/toast"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { useServerSDK } from "@/runtime/server/client"
import { useData } from "@/runtime/server/current"
import { createElicitationDock } from "./elicitation-controller"
import "./session-elicitation-dock.css"
type Field = FormInfo["fields"][number]
@ -31,80 +30,16 @@ export function SessionElicitationDock(props: {
}) {
const language = useLanguage()
const platform = usePlatform()
const data = useData()
const fields = createMemo(() => props.request.fields.filter((field) => !("hidden" in field && field.hidden)))
const message = () => Option.getOrUndefined(decodeMessage(props.request.metadata?.message))
// Number inputs keep their raw text so a half-typed value such as "-" is not discarded.
const [values, setValues] = createStore<{
text: Record<string, string>
number: Record<string, string>
flag: Record<string, boolean>
list: Record<string, string[]>
}>({
text: Object.fromEntries(
props.request.fields.flatMap((field) => (field.type === "string" ? [[field.key, field.default ?? ""]] : [])),
),
number: Object.fromEntries(
props.request.fields.flatMap((field) =>
(field.type === "number" || field.type === "integer") && field.default !== undefined
? [[field.key, String(field.default)]]
: [],
),
),
flag: Object.fromEntries(
props.request.fields.flatMap((field) => (field.type === "boolean" ? [[field.key, field.default ?? false]] : [])),
),
list: Object.fromEntries(
props.request.fields.flatMap((field) =>
field.type === "multiselect" ? [[field.key, [...(field.default ?? [])]]] : [],
),
),
const dock = createElicitationDock({
sdk: useServerSDK(),
forms: useData().session.form,
language,
request: () => props.request,
onSubmit: props.onSubmit,
})
const fail = (error: Error) => showToast({ title: language.t("common.requestFailed"), description: error.message })
const input = () => ({ sessionID: props.request.sessionID, formID: props.request.id })
const reply = useMutation(() => ({
mutationFn: (answer: FormAnswer) => data.session.form.reply({ ...input(), answer }, props.request.location),
onMutate: props.onSubmit,
onError: fail,
}))
const cancel = useMutation(() => ({
mutationFn: () => data.session.form.cancel(input(), props.request.location),
onMutate: props.onSubmit,
onError: fail,
}))
const sending = () => reply.isPending || cancel.isPending
const submit = () => {
if (sending()) return
reply.mutate(
Object.fromEntries(
fields().flatMap((field): Array<[string, FormValue]> => {
if (field.type === "external") return [[field.key, true]]
if (field.type === "boolean") return [[field.key, values.flag[field.key] ?? false]]
if (field.type === "multiselect") {
const list = values.list[field.key] ?? []
return list.length ? [[field.key, list]] : []
}
const text = (field.type === "string" ? values.text[field.key] : values.number[field.key])?.trim()
if (!text) return []
return [[field.key, field.type === "string" ? text : Number(text)]]
}),
),
)
}
const message = () => Option.getOrUndefined(decodeMessage(props.request.metadata?.message))
return (
<div data-component="session-elicitation-dock">
@ -115,15 +50,14 @@ export function SessionElicitationDock(props: {
if (event.key === "Escape") {
event.preventDefault()
if (!sending()) cancel.mutate()
dock.dismiss()
return
}
if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !event.altKey) {
event.preventDefault()
submit()
dock.reply()
}
}}
header={
@ -148,11 +82,11 @@ export function SessionElicitationDock(props: {
}
footer={
<>
<Button variant="ghost" size="large" disabled={sending()} onClick={() => cancel.mutate()}>
<Button variant="ghost" size="large" disabled={dock.busy()} onClick={dock.dismiss}>
{language.t("ui.common.dismiss")}
</Button>
<div data-slot="question-footer-actions">
<Button variant="submit" size="large" disabled={sending()} onClick={submit}>
<Button variant="submit" size="large" disabled={dock.busy()} onClick={dock.reply}>
{language.t("ui.common.submit")}
</Button>
</div>
@ -160,7 +94,7 @@ export function SessionElicitationDock(props: {
}
>
<div data-slot="elicitation-fields">
<For each={fields()}>
<For each={dock.fields()}>
{(field) => (
<div data-slot="elicitation-field">
<Branch>
@ -168,9 +102,9 @@ export function SessionElicitationDock(props: {
<Label field={field} />
<Switch
hideLabel
checked={values.flag[field.key] === true}
onChange={(checked) => setValues("flag", field.key, checked)}
disabled={sending()}
checked={dock.draft().flag[field.key] === true}
onChange={(checked) => dock.setFlag(field.key, checked)}
disabled={dock.busy()}
>
{field.title ?? field.key}
</Switch>
@ -181,10 +115,10 @@ export function SessionElicitationDock(props: {
type="number"
numeric
step={field.type === "integer" ? 1 : "any"}
value={values.number[field.key] ?? ""}
disabled={sending()}
value={dock.draft().number[field.key] ?? ""}
disabled={dock.busy()}
aria-label={field.title ?? field.key}
onInput={(event) => setValues("number", field.key, event.currentTarget.value)}
onInput={(event) => dock.setNumber(field.key, event.currentTarget.value)}
/>
</Match>
<Match when={field.type === "string" && field.options?.length ? field : undefined}>
@ -194,12 +128,12 @@ export function SessionElicitationDock(props: {
<Select
aria-label={select().title ?? select().key}
options={select().options ?? []}
current={select().options?.find((option) => option.value === values.text[select().key])}
current={select().options?.find((option) => option.value === dock.draft().text[select().key])}
value={(option) => option.value}
label={(option) => option.label}
onSelect={(option) => setValues("text", select().key, option?.value ?? "")}
onSelect={(option) => dock.setText(select().key, option?.value ?? "")}
placeholder={language.t("session.elicitation.selectPlaceholder")}
disabled={sending()}
disabled={dock.busy()}
/>
</>
)}
@ -210,11 +144,11 @@ export function SessionElicitationDock(props: {
<Label field={text()} />
<TextInput
type={inputType(text().format)}
value={values.text[text().key] ?? ""}
value={dock.draft().text[text().key] ?? ""}
placeholder={text().placeholder}
disabled={sending()}
disabled={dock.busy()}
aria-label={text().title ?? text().key}
onInput={(event) => setValues("text", text().key, event.currentTarget.value)}
onInput={(event) => dock.setText(text().key, event.currentTarget.value)}
/>
</>
)}
@ -226,15 +160,9 @@ export function SessionElicitationDock(props: {
<For each={multi().options}>
{(option) => (
<Checkbox
checked={(values.list[multi().key] ?? []).includes(option.value)}
disabled={sending()}
onChange={(checked) =>
setValues("list", multi().key, (current = []) =>
checked
? [...current, option.value]
: current.filter((value) => value !== option.value),
)
}
checked={(dock.draft().list[multi().key] ?? []).includes(option.value)}
disabled={dock.busy()}
onChange={(checked) => dock.toggle(multi().key, option.value, checked)}
>
{option.label}
</Checkbox>
@ -252,7 +180,7 @@ export function SessionElicitationDock(props: {
<Button
variant="neutral"
size="small"
disabled={sending()}
disabled={dock.busy()}
onClick={() => platform.openExternal(external().url)}
>
{language.t("common.open")}

View file

@ -118,9 +118,9 @@ export function SessionPreview(props: SessionPreviewProps) {
<SessionSurfaceState
{...props}
request={
props.request?.type === "question"
props.request?.type === "question" || props.request?.type === "elicitation"
? {
type: "question",
type: props.request.type,
value: { ...props.request.value, id: `${props.request.value.id}:${revision}` },
}
: props.request

View file

@ -0,0 +1,110 @@
import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test"
import { createRoot } from "solid-js"
import type { FormInfo } from "@opencode/client/promise"
import { toaster } from "@opencode/ui/toast"
import type { ServerScope } from "@/runtime/server/scope"
import { createElicitationDock, elicitationCache } from "@/session/requests/elicitation-controller"
import { ELICITATION_REQUEST_TIMEOUT_MS } from "@/session/requests/elicitation-machine"
// SAFETY: a scope is any string without a null byte.
const scope = "test-elicitation-dock" as ServerScope
const request: FormInfo = {
id: "frm_elicitation",
sessionID: "ses_elicitation",
title: "Deploy",
metadata: { kind: "mcp-elicitation" },
fields: [{ key: "env", type: "string", title: "Environment" }],
}
const cacheKey = `${scope}\u0000frm_elicitation`
// A data layer whose reply and dismissal never settle until the test settles them.
function setup() {
const listeners = new Map<string, (event: { data: { id: string } }) => void>()
const toasts: string[] = []
const pending: { reject: (error: Error) => void }[] = []
const send = () => new Promise<void>((_, reject) => void pending.push({ reject }))
const sdk = {
scope,
event: {
// SAFETY: the driver subscribes by type and reads only the form id of these events.
on: ((type: string, handler: (event: { data: { id: string } }) => void) => {
listeners.set(type, handler)
return () => listeners.delete(type)
}) as never,
},
}
const owned = createRoot((dispose) => ({
dock: createElicitationDock({
sdk,
forms: { reply: send, cancel: send },
// The failure toast's title is the only text the driver translates, so this records each failure toast.
language: { t: (key) => (toasts.push(key), key) },
request: () => request,
onSubmit: () => undefined,
}),
dispose,
}))
return { ...owned, listeners, toasts, pending }
}
// Lets a settled request's handlers run.
const settled = () =>
Promise.resolve()
.then(() => undefined)
.then(() => undefined)
.then(() => undefined)
describe("createElicitationDock", () => {
beforeEach(() => {
jest.useFakeTimers()
toaster.dismiss()
elicitationCache.delete(cacheKey)
})
afterEach(() => {
jest.clearAllTimers()
jest.useRealTimers()
toaster.dismiss()
})
test("a reply the server settles after the dock unmounted ends without a failure or a kept draft", async () => {
const owner = setup()
owner.dock.setText("env", "prod")
owner.dock.reply()
owner.dispose()
expect([...owner.listeners.keys()]).toEqual(["form.replied", "form.cancelled"])
owner.listeners.get("form.replied")?.({ data: { id: "frm_elicitation" } })
jest.advanceTimersByTime(ELICITATION_REQUEST_TIMEOUT_MS)
owner.pending[0]?.reject(new Error("late"))
await settled()
expect(owner.toasts).toEqual([])
expect(elicitationCache.get(cacheKey)).toBeUndefined()
expect(owner.listeners.size).toBe(0)
})
test("a dismissal that hangs after the dock unmounted reports one failure and keeps the draft", async () => {
const owner = setup()
owner.dock.setText("env", "prod")
owner.dock.dismiss()
owner.dispose()
jest.advanceTimersByTime(ELICITATION_REQUEST_TIMEOUT_MS)
// The data layer's own request ends later; the attempt already timed out.
owner.pending[0]?.reject(new Error("late"))
await settled()
expect(owner.pending).toHaveLength(1)
expect(owner.toasts).toEqual(["common.requestFailed"])
expect(elicitationCache.get(cacheKey)?.text).toEqual({ env: "prod" })
expect(owner.listeners.size).toBe(0)
})
})