From de41651a5e37a9eb3135a525c4bf90dacf2c1b9e Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 2 Dec 2026 13:36:43 +0800 Subject: [PATCH] fix(agents): ask AskUserQuestion forms one question at a time (#7396) claude-agent-acp now sends AskUserQuestion as an ACP form (a choice field per question, each followed by a text field for a typed answer), and OMP's ask tool sends the same shape. They were shown as a plain form with every question stacked above the composer, at up to half the window, which in a short Agents panel left the conversation no room to scroll. Such forms are now shown as the question card in the conversation, one question at a time with Previous/Next, option descriptions and previews; the answers are turned back into the form's values (picked options as the choice, typed text in its companion field; Skip declines). Other forms stay forms, and a long one waiting above the composer now leaves the conversation a share of the panel and scrolls within itself. Fixes #7359 --- crates/ide-agent/src/elicitation.rs | 183 ++++++++++++++++++++++++- crates/ide-agent/src/lib.rs | 10 +- crates/ide-agent/src/tests.rs | 70 ++++++++++ e2e/agentFormHeight.spec.ts | 85 ++++++++++++ src/features/agents/Session.module.css | 5 + 5 files changed, 349 insertions(+), 4 deletions(-) create mode 100644 e2e/agentFormHeight.spec.ts diff --git a/crates/ide-agent/src/elicitation.rs b/crates/ide-agent/src/elicitation.rs index b2f1e0d43..c54ad3937 100644 --- a/crates/ide-agent/src/elicitation.rs +++ b/crates/ide-agent/src/elicitation.rs @@ -1,7 +1,10 @@ //! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the //! user's answer as the `elicitation/create` response. -use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption}; +use crate::model::{ + AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion, + AgentQuestionOption, +}; use serde::Deserialize; use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor}; use serde_json::{Map, Value, json}; @@ -10,6 +13,9 @@ use serde_json::{Map, Value, json}; /// anything else cancels it. const DECLINE: &str = "decline"; +/// What the question card sends for Skip. +const SKIP: &str = "reject"; + /// The form `elicitation/create` asks for; `Err` when it asks for something else. pub(crate) fn form_of(params: &Value) -> Result { if params.get("mode").and_then(Value::as_str) != Some("form") { @@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option { } } +/// The questions a form asks when it is an agent's question tool in form shape: every field +/// a choice, each followed by its own text field for a typed answer, named after it +/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` + +/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one +/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers +/// back into the form's values. `None` for any other form. +pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option> { + let choices = form.fields.len() / 2; + if choices == 0 || form.fields.len() % 2 == 1 { + return None; + } + let properties = params.pointer("/requestedSchema/properties"); + form.fields + .chunks(2) + .map(|pair| { + let [choice, text] = pair else { return None }; + let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices) + && !choice.options.is_empty() + && text.kind == AgentFormFieldKind::Text + && text.name.len() > choice.name.len() + && text.name.starts_with(&choice.name); + if !asks { + return None; + } + let (title, description) = (choice.title.trim(), choice.description.trim()); + let (header, question) = if choices == 1 && !message.is_empty() { + (if title == message || title == choice.name { "" } else { title }, message) + } else if description.is_empty() { + ("", title) + } else { + (if title == choice.name { "" } else { title }, description) + }; + let schema = properties.and_then(|p| p.get(&choice.name)); + let options = choice + .options + .iter() + .map(|option| AgentQuestionOption { + label: option.label.clone(), + description: option.description.clone(), + preview: schema.and_then(|s| option_preview(s, &option.value)), + }) + .collect(); + Some(AgentQuestion { + answer_key: Some(choice.name.clone()), + header: header.to_owned(), + question: question.to_owned(), + multi_select: choice.kind == AgentFormFieldKind::Choices, + options, + }) + }) + .collect() +} + +/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`). +fn option_preview(schema: &Value, value: &str) -> Option { + let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf")); + listed? + .as_array()? + .iter() + .find(|o| o.get("const").and_then(Value::as_str) == Some(value))? + .pointer("/_meta/_claude~1askUserQuestionOption/preview")? + .as_str() + .map(str::to_owned) +} + +/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked +/// labels and the typed text): picked options as the choice's values, the text in the field +/// beside it. The question card's Skip declines the form; nothing passes through. +pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option { + let reply = reply?; + if reply == SKIP { + return Some(DECLINE.to_owned()); + } + let Ok(answers) = serde_json::from_str::>(reply) else { return Some(reply.to_owned()) }; + let mut values = Map::new(); + for pair in form.fields.chunks(2) { + let [choice, text] = pair else { continue }; + let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str); + let (mut picked, mut typed) = (Vec::new(), Vec::new()); + for item in items { + match choice.options.iter().find(|o| o.label == item) { + Some(option) => picked.push(json!(option.value)), + None => typed.push(item), + } + } + values.insert(choice.name.clone(), Value::Array(picked)); + values.insert(text.name.clone(), json!([typed.join("\n")])); + } + Some(Value::Object(values).to_string()) +} + /// A form is submitted from its own card; this option only names a declined form. pub(crate) fn options() -> Vec { vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }] @@ -295,6 +392,90 @@ mod tests { assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b"); } + /// What claude-agent-acp sends for `AskUserQuestion` with two questions. + fn claude_questions() -> Value { + json!({ + "sessionId": "s", "mode": "form", "message": "Please answer the following questions.", + "requestedSchema": { "type": "object", "properties": { + "question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?", + "oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)", + "description": "Tracks tasks", + "_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } }, + { "const": "Util only", "title": "Util only" }] }, + "question_0_custom": { "type": "string", "title": "Other" }, + "question_1": { "type": "array", "title": "Targets", "description": "Who receives it?", + "items": { "anyOf": [{ "const": "Members", "title": "Members" }, + { "const": "Tags", "title": "Tags" }] } }, + "question_1_custom": { "type": "string", "title": "Other" } + } } + }) + } + + fn in_order(params: &Value, names: &[&str]) -> AgentForm { + let mut form = form_of(params).unwrap(); + form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name)); + form + } + + #[test] + fn a_question_tool_form_is_asked_as_questions() { + let params = claude_questions(); + let form = in_order(¶ms, &["question_0", "question_0_custom", "question_1", "question_1_custom"]); + let questions = questions_of(&form, ¶ms, "Please answer the following questions.").unwrap(); + let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") }; + assert_eq!( + ( + delivery.answer_key.as_deref(), + delivery.header.as_str(), + delivery.question.as_str(), + delivery.multi_select + ), + (Some("question_0"), "Delivery", "How should it ship?", false) + ); + assert_eq!(delivery.options[0].description, "Tracks tasks"); + assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```")); + assert_eq!(delivery.options[1].preview, None); + assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true)); + + let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] }); + let reply = answer_questions(&form, Some(&reply.to_string())); + let (response, chosen) = answer(&form, reply.as_deref()); + assert_eq!( + response, + json!({ "action": "accept", "content": { + "question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"] + } }) + ); + assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags"); + assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE)); + assert_eq!(answer_questions(&form, None), None); + } + + #[test] + fn a_single_question_reads_from_the_message() { + let params = ask(); + let form = in_order(¶ms, &["q0", "q0__other"]); + let questions = questions_of(&form, ¶ms, "Which database?").unwrap(); + assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?")); + assert_eq!(questions[0].options[0].label, "Postgres"); + let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string())); + assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } })); + } + + #[test] + fn other_forms_stay_forms() { + let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": { + "size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] } + } } })) + .unwrap(); + assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None); + let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": { + "size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" } + } } })) + .unwrap(); + assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None); + } + #[test] fn declining_and_dismissing_send_no_content() { let form = form_of(&ask()).unwrap(); diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 67f141728..d6836e35a 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -6204,6 +6204,7 @@ impl Task { } let id = self.next_permission.fetch_add(1, Ordering::Relaxed); let message = params.get("message").and_then(Value::as_str).unwrap_or_default().trim().to_owned(); + let questions = elicitation::questions_of(&form, params, &message); let (tx, rx) = std::sync::mpsc::channel(); let entry = { let mut file = self.file.lock(); @@ -6218,8 +6219,8 @@ impl Task { title, command: None, options: elicitation::options(), - questions: Vec::new(), - form: Some(form.clone()), + questions: questions.clone().unwrap_or_default(), + form: if questions.is_some() { None } else { Some(form.clone()) }, chosen: None, }); self.permissions.lock().insert(id, tx); @@ -6233,7 +6234,10 @@ impl Task { self.mark_dirty([(None, entry)]); self.emit_task(); self.emit_attention_if_input_pending(epoch); - let reply = rx.recv().ok().flatten(); + let mut reply = rx.recv().ok().flatten(); + if questions.is_some() { + reply = elicitation::answer_questions(&form, reply.as_deref()); + } let (response, chosen) = elicitation::answer(&form, reply.as_deref()); if self.shared.shut_down_since(epoch) { return Ok(response); diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index fc2c240eb..c58c52947 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -426,6 +426,28 @@ impl Handler for FakeAgent { self.say(&session, &format!("form {answer}")); return Ok(json!({ "stopReason": "end_turn" })); } + if text == "question form" { + // claude-agent-acp's `AskUserQuestion`, sent as a form. + let peer = self.latest(); + let answer: Value = tokio::runtime::Handle::current() + .block_on(peer.request( + "elicitation/create", + json!({"sessionId": session, "mode": "form", + "message": "Please answer the following questions.", + "requestedSchema": {"type": "object", "properties": { + "question_0": {"type": "string", "title": "Layout", "description": "Which layout?", + "oneOf": [{"const": "List", "title": "List"}, {"const": "Grid", "title": "Grid"}]}, + "question_0_custom": {"type": "string", "title": "Other"}, + "question_1": {"type": "array", "title": "Checks", "description": "Which checks?", + "items": {"anyOf": [{"const": "Disk", "title": "Disk"}, + {"const": "GPU", "title": "GPU"}]}}, + "question_1_custom": {"type": "string", "title": "Other"}}}}), + None, + )) + .unwrap(); + self.say(&session, &format!("form {answer}")); + return Ok(json!({ "stopReason": "end_turn" })); + } if text == "ask" { let peer = self.latest(); let answer: Value = tokio::runtime::Handle::current() @@ -3930,6 +3952,54 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are } } +/// claude-agent-acp asks `AskUserQuestion` as a form: it is shown as the question card, one +/// question at a time, and the card's answers fill the form (#7359). +#[tokio::test(flavor = "multi_thread")] +async fn a_question_tool_form_is_asked_as_questions() { + let answers = json!({"question_0": ["Grid", "with thumbnails"], "question_1": ["Disk", "GPU"]}).to_string(); + for (reply, said) in [ + ( + answers.as_str(), + r#"form {"action":"accept","content":{"question_0":"Grid","question_0_custom":"with thumbnails","question_1":["Disk","GPU"]}}"#, + ), + ("reject", r#"form {"action":"decline"}"#), + ] { + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let task = mgr + .create(NewAgentTask { + project_root: None, + prompt: text("question form"), + provider: "cursor".into(), + isolation: Isolation::Local, + base: None, + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await; + let (id, questions) = mgr + .entries(&task.id, None) + .unwrap() + .into_iter() + .find_map(|entry| match entry { + AgentEntry::Permission { id, questions, form: None, chosen: None, .. } if !questions.is_empty() => { + Some((id, questions)) + } + _ => None, + }) + .unwrap(); + let asked: Vec<_> = + questions.iter().map(|q| (q.answer_key.as_deref(), q.question.as_str(), q.multi_select)).collect(); + assert_eq!(asked, [(Some("question_0"), "Which layout?", false), (Some("question_1"), "Which checks?", true)]); + mgr.respond(&task.id, id, Some(reply.to_owned())).unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + let entries = mgr.entries(&task.id, None).unwrap(); + assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}"); + mgr.shutdown(); + } +} + #[tokio::test(flavor = "multi_thread")] async fn cursor_approval_choice_applies_before_first_prompt() { let tmp = tempfile::tempdir().unwrap(); diff --git a/e2e/agentFormHeight.spec.ts b/e2e/agentFormHeight.spec.ts new file mode 100644 index 000000000..269728f36 --- /dev/null +++ b/e2e/agentFormHeight.spec.ts @@ -0,0 +1,85 @@ +import type { AgentEntry, AgentTask } from "../src/bindings"; +import { expect, test } from "./fixtures"; + +const task: AgentTask = { + id: "form-height", + title: "Form", + provider: "cursor", + status: "needsInput", + isolation: "local", + model: null, + cwd: "/dev/acme-api", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 0, + updatedMs: 0, + config: [], + commands: [], + usage: null, + queue: [], +}; + +const field = (i: number) => ({ + name: `field_${i}`, + title: `Field ${i}`, + description: "Something the agent needs to know before it goes on.", + required: false, + kind: "text" as const, + options: [], + default: [], + min: null, + max: null, +}); + +const form: AgentEntry = { + type: "permission", + id: 1, + title: "Fill in the details", + command: null, + options: [{ id: "decline", name: "Decline", kind: "reject_once" }], + questions: [], + form: { fields: Array.from({ length: 12 }, (_, i) => field(i)) }, + chosen: null, +}; + +// #7359: a long form waiting above the composer scrolls within itself and leaves the +// conversation part of a short session, instead of half the window. +test("a long pinned form leaves room for the conversation", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1100, height: 560 }); + await page.evaluate( + async ({ task, form }) => { + const storePath = "/src/features/agents/store.ts"; + const store = await import(/* @vite-ignore */ storePath); + const entries: AgentEntry[] = [ + { type: "user", text: "Set up the project.", attachments: [] }, + { type: "agent", text: "I need a few details first." }, + form, + ]; + store.useAgents.setState({ + loaded: true, + error: null, + tasks: new Map([[task.id, task]]), + entries: new Map([[task.id, entries]]), + sessionLocation: "editor", + }); + store.openTask(task.id); + }, + { task, form }, + ); + const card = page.getByRole("form", { name: "Fill in the details" }); + await expect(card).toBeVisible(); + const sizes = await card.evaluate((el) => { + const conversation = el.closest("[class*='_conversation_']")!; + const stream = conversation.querySelector("[class*='_streamArea_']")!; + return { + conversation: conversation.getBoundingClientRect().height, + stream: stream.getBoundingClientRect().height, + scrolls: el.scrollHeight > el.clientHeight, + }; + }); + expect(sizes.stream).toBeGreaterThanOrEqual(Math.min(sizes.conversation * 0.35, 200) - 1); + expect(sizes.scrolls).toBe(true); + await expect(card.getByRole("button", { name: "Submit" })).toBeAttached(); +}); diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index 01dabc0b7..69a5bb2fd 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -1764,6 +1764,11 @@ .fitWidth .questionCardPinned { max-width: none; } +/* In a panel shorter than the window, half the window would leave the conversation no room: it + keeps a share of the panel, and the card scrolls in what is left (#7359). */ +.conversation:has(.questionCardPinned) .streamArea { + min-height: min(35%, 200px); +} .questionTabCheck { flex: none; color: var(--accent);