From 02f9fff2a99cd5acaea7828cc08b5ff0994db0bf Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 11:36:59 +0000 Subject: [PATCH 1/3] crates: keep every claude question answerable, show declined mcp forms, and stop offering deny rules that allow - askuserquestion fields are keyed by position instead of question text. a question with a newline or over the id limit used to be dropped, which could leave a card with nothing to answer. answers still reach claude keyed by the full question text. - a declined mcp elicitation or unsupported dialog is an error notice, so it shows in the chat with the server and what it asked. as a warning it only reached the logs and the tool silently didn't run. - a permission suggestion with a deny rule is no longer offered: its only way back is an allow answer, which would run the tool the person refused. --- .../harness/claude/plan-mode-blocks.json | 2 +- .../harness/claude/turn-tools-approvals.json | 4 +- .../agent-driver-claude/src/harness/mapper.rs | 190 ++++++++++++++++-- 3 files changed, 179 insertions(+), 17 deletions(-) diff --git a/crates/agent-bridge/tests/fixtures/harness/claude/plan-mode-blocks.json b/crates/agent-bridge/tests/fixtures/harness/claude/plan-mode-blocks.json index fb382d10e..260f94a89 100644 --- a/crates/agent-bridge/tests/fixtures/harness/claude/plan-mode-blocks.json +++ b/crates/agent-bridge/tests/fixtures/harness/claude/plan-mode-blocks.json @@ -318,7 +318,7 @@ "form": { "fields": [ { - "id": "How should the empty state look?", + "id": "q0", "header": "Empty state", "prompt": "How should the empty state look?", "input": { diff --git a/crates/agent-bridge/tests/fixtures/harness/claude/turn-tools-approvals.json b/crates/agent-bridge/tests/fixtures/harness/claude/turn-tools-approvals.json index 4147d12df..e45b87b76 100644 --- a/crates/agent-bridge/tests/fixtures/harness/claude/turn-tools-approvals.json +++ b/crates/agent-bridge/tests/fixtures/harness/claude/turn-tools-approvals.json @@ -211,7 +211,7 @@ "form": { "fields": [ { - "id": "Which package manager should the fix use?", + "id": "q0", "header": "Package manager", "prompt": "Which package manager should the fix use?", "input": { @@ -357,7 +357,7 @@ { "name": "answer the question form", "interaction": "req-ask-1", - "response": {"kind": "answers", "answers": [{"field": "Which package manager should the fix use?", "values": ["pnpm"]}]}, + "response": {"kind": "answers", "answers": [{"field": "q0", "values": ["pnpm"]}]}, "native": { "type": "control_response", "response": { diff --git a/crates/agent-driver-claude/src/harness/mapper.rs b/crates/agent-driver-claude/src/harness/mapper.rs index ad59780d6..62ab0ebb3 100644 --- a/crates/agent-driver-claude/src/harness/mapper.rs +++ b/crates/agent-driver-claude/src/harness/mapper.rs @@ -1083,11 +1083,12 @@ impl ClaudeMapper { "dialog kind {} is not supported", dialog.dialog_kind )), + // Shown in the chat: the person should know Claude asked. events: vec![notice( - NoticeLevel::Warning, - "request_user_dialog", + NoticeLevel::Error, + "Request declined", Some(format!( - "Claude asked for a {} dialog Inline cannot show", + "Claude asked for a {} dialog Inline can't show yet, so it was declined.", dialog.dialog_kind )), request, @@ -1095,10 +1096,12 @@ impl ClaudeMapper { }, IncomingRequest::Elicitation(raw) => RequestMapped::Reply { response: Ok(json!({"action": "decline"})), + // Shown in the chat: declining silently left people wondering + // why the tool didn't run. events: vec![notice( - NoticeLevel::Warning, - "elicitation", - raw["message"].as_str().map(str::to_string), + NoticeLevel::Error, + "Request declined", + Some(elicitation_declined_text(&raw)), request, )], }, @@ -1181,7 +1184,10 @@ impl ClaudeMapper { )); } ( - PermissionDecision::answer_questions(input, answers_map(answers)), + PermissionDecision::answer_questions( + input, + answers_map(&pending.request, answers), + ), None, ) } @@ -1241,6 +1247,28 @@ fn item_id(id: &str) -> ItemId { .unwrap_or_else(|_| ItemId::new(uuid::Uuid::new_v4().to_string()).expect("uuid id")) } +/// What a declined MCP elicitation asked, for the chat. +fn elicitation_declined_text(raw: &Value) -> String { + let server = raw["mcp_server_name"] + .as_str() + .or_else(|| raw["server_name"].as_str()) + .filter(|name| !name.trim().is_empty()); + let asked = raw["message"] + .as_str() + .map(|message| message.trim().chars().take(300).collect::()) + .filter(|message| !message.is_empty()); + let from = server.map_or_else( + || "An MCP server".to_owned(), + |name| format!("The {name} MCP server"), + ); + match asked { + Some(asked) => format!( + "{from} asked for input Inline can't show yet, so it was declined: \u{201c}{asked}\u{201d}" + ), + None => format!("{from} asked for input Inline can't show yet, so it was declined."), + } +} + fn notice(level: NoticeLevel, code: &str, message: Option, native: &Value) -> Event { Event::Notice(Notice { level, @@ -1635,15 +1663,24 @@ fn child_status(status: Option<&str>) -> ChildStatus { } } +/// A question's field ID: its position, since its text may hold newlines or +/// be longer than an ID may be (such a question used to be dropped, which +/// could leave nothing to answer). Answers map back to the text Claude keys +/// them by in `answers_map`. +fn question_field(index: usize) -> Option { + FieldId::new(format!("q{index}")).ok() +} + fn question_form(permission: &PermissionRequest) -> QuestionForm { QuestionForm { title: permission.title.clone(), fields: permission .questions() .into_iter() - .filter_map(|question| { + .enumerate() + .filter_map(|(index, question)| { Some(FormField { - id: FieldId::new(question.question.as_str()).ok()?, + id: question_field(index)?, header: question.header.clone(), prompt: question.question.clone(), input: FieldInput::Select { @@ -1669,14 +1706,23 @@ fn question_form(permission: &PermissionRequest) -> QuestionForm { } } -fn answers_map(answers: &[FieldAnswer]) -> Map { +/// Claude keys answers by question text. +fn answers_map(permission: &PermissionRequest, answers: &[FieldAnswer]) -> Map { + let questions = permission.questions(); answers .iter() .map(|answer| { - ( - answer.field.as_str().to_string(), - json!(answer.values.join(", ")), - ) + let key = answer + .field + .as_str() + .strip_prefix('q') + .and_then(|index| index.parse::().ok()) + .and_then(|index| questions.get(index)) + .map_or_else( + || answer.field.as_str().to_string(), + |question| question.question.clone(), + ); + (key, json!(answer.values.join(", "))) }) .collect() } @@ -1730,6 +1776,11 @@ fn approval_decisions( }]; if permission.suppress_always_allow_rule != Some(true) { for (index, suggestion) in permission.permission_suggestions.iter().enumerate() { + // A deny rule only travels with an allow answer, which would run + // the tool the person just refused; "No" covers this one call. + if suggestion["behavior"] == "deny" { + continue; + } let Ok(id) = DecisionId::new(format!("{SUGGESTION_PREFIX}{index}")) else { continue; }; @@ -2163,6 +2214,117 @@ mod tests { ); } + #[test] + fn a_long_or_multiline_question_keeps_its_field_and_its_answer_key() { + let mut mapper = ClaudeMapper::new(None); + let long = format!("Which plan?\n{}", "detail ".repeat(400)); + let RequestMapped::Interaction(events) = mapper.request( + "q1", + &json!({"subtype": "can_use_tool", "tool_name": "AskUserQuestion", "tool_use_id": "t1", + "input": {"questions": [ + {"question": long, "header": "Plan", "multiSelect": false, + "options": [{"label": "A", "description": ""}, {"label": "B", "description": ""}]}, + {"question": "Ship it?", "header": "Ship", "multiSelect": false, + "options": [{"label": "Yes", "description": ""}, {"label": "No", "description": ""}]} + ]}}), + ) else { + panic!("interaction"); + }; + let Some(Event::Interaction(interaction)) = events.last() else { + panic!("interaction event"); + }; + let InteractionKind::Question { form } = &interaction.kind else { + panic!("question"); + }; + // Both questions are asked, the long one included. + assert_eq!(form.fields.len(), 2); + let plan = mapper + .answer( + &InteractionId::new("q1").unwrap(), + &InteractionResponse::Answers { + answers: form + .fields + .iter() + .zip(["B", "Yes"]) + .map(|(field, value)| FieldAnswer { + field: field.id.clone(), + values: vec![value.into()], + }) + .collect(), + }, + UserId(1), + ) + .unwrap(); + // Claude reads answers keyed by the full question text. + assert_eq!( + plan.response["updatedInput"]["answers"][long.as_str()], + json!("B") + ); + assert_eq!( + plan.response["updatedInput"]["answers"]["Ship it?"], + json!("Yes") + ); + } + + #[test] + fn a_deny_rule_suggestion_is_not_offered_as_an_answer_that_allows() { + let mut mapper = ClaudeMapper::new(None); + let RequestMapped::Interaction(events) = mapper.request( + "r1", + &json!({"subtype": "can_use_tool", "tool_name": "Bash", "tool_use_id": "t1", + "input": {"command": "rm -rf build"}, + "permission_suggestions": [ + {"type": "addRules", "behavior": "deny", "destination": "localSettings", + "rules": [{"toolName": "Bash", "ruleContent": "rm -rf:*"}]}, + {"type": "addRules", "behavior": "allow", "destination": "localSettings", + "rules": [{"toolName": "Bash", "ruleContent": "make:*"}]} + ]}), + ) else { + panic!("interaction"); + }; + let Some(Event::Interaction(interaction)) = events.last() else { + panic!("interaction event"); + }; + let InteractionKind::Approval { decisions, .. } = &interaction.kind else { + panic!("approval"); + }; + let labels: Vec<&str> = decisions + .iter() + .map(|decision| decision.label.as_str()) + .collect(); + assert!( + labels.iter().all(|label| !label.contains("always deny")), + "{labels:?}" + ); + assert!( + labels.iter().any(|label| label.contains("make:*")), + "{labels:?}" + ); + } + + #[test] + fn a_declined_mcp_form_is_shown_in_the_chat() { + let mut mapper = ClaudeMapper::new(None); + let RequestMapped::Reply { response, events } = mapper.request( + "e1", + &json!({"subtype": "elicitation", "mcp_server_name": "coolify", + "message": "Confirm the deploy?", "mode": "form", "requested_schema": {}}), + ) else { + panic!("reply"); + }; + assert_eq!(response.unwrap(), json!({"action": "decline"})); + let Some(Event::Notice(notice)) = events.first() else { + panic!("notice"); + }; + // Only errors reach the chat; this one must. + assert_eq!(notice.level, NoticeLevel::Error); + let text = notice.message.as_deref().unwrap_or_default(); + assert!( + text.contains("coolify") && text.contains("Confirm the deploy?"), + "{text}" + ); + } + fn running_turn(t1: &str) -> ClaudeMapper { let mut mapper = ClaudeMapper::new(None); mapper.sent(&InputId::new(t1).unwrap(), true); From e561c9e2d07e9129dbf93f72e90286e08bcb3af7 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 11:36:59 +0000 Subject: [PATCH 2/3] cli: cancel a request whose card inline refuses instead of pointing at a terminal a card inline refused twice left its request pending and told the person to "continue in the terminal", which a bridge user doesn't have, so the turn waited forever. the request is now cancelled as the owner, the way a released session cancels its open requests, and the chat says it was declined so the agent goes on. a form card skips the plain-text retry, which kept no way to answer it. tapping a card from before a restart now says the request is no longer pending instead of doing nothing. --- cli/src/bridge/v2/work.rs | 60 ++++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/cli/src/bridge/v2/work.rs b/cli/src/bridge/v2/work.rs index 7fe669cea..a6f9a05ab 100644 --- a/cli/src/bridge/v2/work.rs +++ b/cli/src/bridge/v2/work.rs @@ -1236,7 +1236,10 @@ impl Actor { self.pick(message_id, actor, &i, f, label).await } ActionData::Decision { i, d } => { - let card = self.cards.get(&message_id).cloned()?; + let Some(card) = self.cards.get(&message_id).cloned() else { + // A card from before a restart: its request ended with the old session. + return Some(NOT_PENDING.to_owned()); + }; if card.interaction.as_str() != i { return Some(NOT_PENDING.to_owned()); } @@ -3041,7 +3044,10 @@ impl Actor { return; } crate::telemetry::report_bridge_output_refused(kind); - if !outgoing.fallback { + // Plain text keeps an approval's buttons but not a form, which could + // then never be answered. + let has_form = matches!(&outgoing.card, Some((_, Some(_)))); + if !outgoing.fallback && !has_form { let random_id = outgoing.random_id.wrapping_add(1).max(1); self.outbox.push_front(Outgoing { doc: plain_fallback(&outgoing.doc), @@ -3051,18 +3057,52 @@ impl Actor { }); return; } - let what = if kind == "card" { - "a request for you" - } else { - "an answer" + let agent = self.agent.agent_name.clone(); + let Some((interaction, _)) = outgoing.card else { + self.notice(&format!( + "{agent} had an answer Inline couldn't show. Ask {agent} to send it again, shorter." + )) + .await; + return; }; - self.notice(&format!( - "{} had {what} Inline couldn't show. Continue in the terminal to see it.", - self.agent.agent_name - )) + // A request nobody can see can't be answered: cancel it, so the agent + // goes on instead of waiting for an answer that never comes. There is + // no terminal to answer it in. + let cancelled = self.cancel_unshowable(interaction).await; + self.notice(&if cancelled { + format!( + "{agent} asked for something Inline couldn't show, so it was declined and {agent} goes on. Ask again in a simpler way if you need it." + ) + } else { + format!( + "{agent} asked for something Inline couldn't show. Stop the turn with /stop to go on." + ) + }) .await; } + /// Cancels a request whose card Inline refused, as the owner, the way a + /// released session cancels its open requests. + async fn cancel_unshowable(&mut self, interaction: InteractionId) -> bool { + let Some(session) = self.held_session() else { + return false; + }; + match session + .control(Op::Answer { + interaction, + response: InteractionResponse::Cancel, + by: UserId(self.agent.owner_user_id), + }) + .await + { + Ok(_) => true, + Err(error) => { + log::warn!(target: "inline::bridge::v2", "chat={} cannot cancel a refused request: {error:?}", self.chat_id); + false + } + } + } + async fn flush_outbox(&mut self) { while let Some(outgoing) = self.outbox.pop_front() { // Persist before the first attempt, including a closed card's replacement. From c71b05878b146bbf23c562bb4c359bdb7d45b4a2 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 14:20:00 +0000 Subject: [PATCH 3/3] cli: cancel only a refused request this session still has open, keep single-choice questions answerable as text, and post no ghost card from the pre-merge review: - the cancel posted the refused card again as a new "answered by" message, since closing it rendered a card update for a card never shown. the renderer now forgets the interaction before the cancel. - a request from before a restart (or one that ended while its card was retried) is left alone: its id could name another request of the new session, and there is nothing to answer. - a request that ended meanwhile gets no "/stop" notice. - only a form drawn as fields skips the plain-text retry; single-choice questions keep their buttons as text, as before. - a declined mcp form quotes at most 160 characters of the server's message. --- cli/src/bridge/v2/render.rs | 14 +++++ cli/src/bridge/v2/work.rs | 51 ++++++++++++------- .../agent-driver-claude/src/harness/mapper.rs | 2 +- 3 files changed, 49 insertions(+), 18 deletions(-) diff --git a/cli/src/bridge/v2/render.rs b/cli/src/bridge/v2/render.rs index bb365460b..8f196bd08 100644 --- a/cli/src/bridge/v2/render.rs +++ b/cli/src/bridge/v2/render.rs @@ -218,6 +218,20 @@ impl Renderer { /// The answers being sent to an open question, so its closed card keeps /// what was asked and what was answered. Secret answers are dropped here. + /// Whether `interaction` is open in this session (its card was rendered + /// and it hasn't closed). False for one from before a restart. + pub(crate) fn is_open(&self, interaction: &InteractionId) -> bool { + self.interactions.contains_key(interaction) + } + + /// Drops an interaction whose card Inline never showed, so closing it + /// renders nothing (there is no card to update). + pub(crate) fn forget(&mut self, interaction: &InteractionId) { + self.interactions.remove(interaction); + self.card_diffs.remove(interaction); + self.card_answers.remove(interaction); + } + pub(crate) fn note_answers(&mut self, interaction: &InteractionId, answers: &[FieldAnswer]) { let Some(Interaction { kind: InteractionKind::Question { form }, diff --git a/cli/src/bridge/v2/work.rs b/cli/src/bridge/v2/work.rs index a6f9a05ab..1f180b7ac 100644 --- a/cli/src/bridge/v2/work.rs +++ b/cli/src/bridge/v2/work.rs @@ -601,6 +601,14 @@ struct Outgoing { plan: bool, } +/// What cancelling a request whose card Inline refused came to. +enum Cancelled { + Yes, + /// It ended (answered, interrupted) while its card was retried. + AlreadyEnded, + No, +} + /// An input the harness may or may not have. #[derive(Clone, Copy, Debug)] struct Uncertain { @@ -3044,10 +3052,11 @@ impl Actor { return; } crate::telemetry::report_bridge_output_refused(kind); - // Plain text keeps an approval's buttons but not a form, which could - // then never be answered. - let has_form = matches!(&outgoing.card, Some((_, Some(_)))); - if !outgoing.fallback && !has_form { + // Plain text keeps the buttons (an approval's, a single choice's) but + // not a form drawn as fields, which could then never be answered. + let unanswerable_as_text = + matches!(&outgoing.card, Some((_, Some(form))) if !render::pickable(form)); + if !outgoing.fallback && !unanswerable_as_text { let random_id = outgoing.random_id.wrapping_add(1).max(1); self.outbox.push_front(Outgoing { doc: plain_fallback(&outgoing.doc), @@ -3065,27 +3074,34 @@ impl Actor { .await; return; }; + // Only a request this session still has open: one from before a + // restart, or that ended while the card was retried, needs nothing, + // and its ID could name another request of the new session. + if !self.renderer.is_open(&interaction) { + return; + } + // Its card was never shown, so closing it must not post one. + self.renderer.forget(&interaction); // A request nobody can see can't be answered: cancel it, so the agent // goes on instead of waiting for an answer that never comes. There is // no terminal to answer it in. - let cancelled = self.cancel_unshowable(interaction).await; - self.notice(&if cancelled { - format!( + let text = match self.cancel_unshowable(interaction).await { + Cancelled::Yes => format!( "{agent} asked for something Inline couldn't show, so it was declined and {agent} goes on. Ask again in a simpler way if you need it." - ) - } else { - format!( + ), + Cancelled::AlreadyEnded => return, + Cancelled::No => format!( "{agent} asked for something Inline couldn't show. Stop the turn with /stop to go on." - ) - }) - .await; + ), + }; + self.notice(&text).await; } /// Cancels a request whose card Inline refused, as the owner, the way a /// released session cancels its open requests. - async fn cancel_unshowable(&mut self, interaction: InteractionId) -> bool { + async fn cancel_unshowable(&mut self, interaction: InteractionId) -> Cancelled { let Some(session) = self.held_session() else { - return false; + return Cancelled::No; }; match session .control(Op::Answer { @@ -3095,10 +3111,11 @@ impl Actor { }) .await { - Ok(_) => true, + Ok(_) => Cancelled::Yes, + Err(OpError::InteractionNotPending) => Cancelled::AlreadyEnded, Err(error) => { log::warn!(target: "inline::bridge::v2", "chat={} cannot cancel a refused request: {error:?}", self.chat_id); - false + Cancelled::No } } } diff --git a/crates/agent-driver-claude/src/harness/mapper.rs b/crates/agent-driver-claude/src/harness/mapper.rs index 62ab0ebb3..1ba302350 100644 --- a/crates/agent-driver-claude/src/harness/mapper.rs +++ b/crates/agent-driver-claude/src/harness/mapper.rs @@ -1255,7 +1255,7 @@ fn elicitation_declined_text(raw: &Value) -> String { .filter(|name| !name.trim().is_empty()); let asked = raw["message"] .as_str() - .map(|message| message.trim().chars().take(300).collect::()) + .map(|message| message.trim().chars().take(160).collect::()) .filter(|message| !message.is_empty()); let from = server.map_or_else( || "An MCP server".to_owned(),