diff --git a/Cargo.lock b/Cargo.lock index bff363501ec..73f41630965 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3696,6 +3696,7 @@ dependencies = [ "tokio-stream", "tokio-util", "toml", + "unicode-width", "url", "urlencoding", "uuid", diff --git a/crates/jcode-app-core/Cargo.toml b/crates/jcode-app-core/Cargo.toml index 886fdcc1418..611271765f6 100644 --- a/crates/jcode-app-core/Cargo.toml +++ b/crates/jcode-app-core/Cargo.toml @@ -46,6 +46,7 @@ chrono = { version = "0.4", features = ["serde"] } regex = "1" urlencoding = "2" # URL encoding for web search uuid = { version = "1", features = ["v4", "v5"] } +unicode-width = "0.2" # display-cell width for compact UI limits jcode-applet-types = { path = "../jcode-applet-types" } # Embeddings (local inference) live in jcode-base; this crate forwards the diff --git a/crates/jcode-app-core/src/agent/elicitation.rs b/crates/jcode-app-core/src/agent/elicitation.rs index 150c21c56dd..6b03f8261cc 100644 --- a/crates/jcode-app-core/src/agent/elicitation.rs +++ b/crates/jcode-app-core/src/agent/elicitation.rs @@ -1,7 +1,9 @@ -//! Session UI capability changes invalidate the provider's locked tool surface. +//! Session UI capability changes register form tools and invalidate the locked +//! provider tool surface. use super::*; impl Agent { pub(crate) async fn set_form_capabilities(&mut self, desktop: bool, applet: bool) { + self.register_ask_user().await; if self.ui_capabilities == (desktop, applet) { return; } @@ -16,8 +18,13 @@ impl Agent { .await; } let mut allowed = self.allowed_tools.clone(); - if applet && let Some(allowed) = allowed.as_mut() { - allowed.insert("applet".into()); + if let Some(allowed) = allowed.as_mut() { + if applet { + allowed.insert("applet".into()); + } + if desktop { + allowed.insert("user_response".into()); + } } self._tool_policy_registration = crate::tool::register_session_tool_policy( &self.session.id, @@ -26,4 +33,32 @@ impl Agent { ); self.invalidate_sdk_tools(); } + + /// Register `ask_user` once any form-capable client attaches, before the + /// `(desktop, applet)` early return: a TUI reports `(false, false)`. + /// + /// The registry is the source of truth, so `Agent` needs no extra field and + /// detaching never unregisters the tool. Registration invalidates the locked + /// surface once, because the first request may already have locked it. + async fn register_ask_user(&mut self) { + if !crate::elicitation::global().forms(&self.session.id) { + return; + } + if self + .registry + .tool_names() + .await + .iter() + .any(|name| name == "ask_user") + { + return; + } + self.registry + .register( + "ask_user".into(), + Arc::new(crate::elicitation::ask_user::AskUserTool), + ) + .await; + self.invalidate_sdk_tools(); + } } diff --git a/crates/jcode-app-core/src/agent/turn_execution.rs b/crates/jcode-app-core/src/agent/turn_execution.rs index 448554e8975..a20a7e5e148 100644 --- a/crates/jcode-app-core/src/agent/turn_execution.rs +++ b/crates/jcode-app-core/src/agent/turn_execution.rs @@ -677,6 +677,12 @@ impl Agent { { allowed.insert("applet".into()); } + if self.ui_capabilities.0 + && enabled.is_none() + && let Some(allowed) = allowed.as_mut() + { + allowed.insert("user_response".into()); + } let mut tools = self.registry.definitions(allowed.as_ref()).await; if enabled.is_none() && !self.disabled_tools.is_empty() { tools.retain(|tool| { @@ -1156,6 +1162,7 @@ impl Agent { if let Some(allowed) = self.allowed_tools.as_ref() && !self.registry.tool_is_allowed(allowed, name) && !(name == "applet" && self.ui_capabilities.1) + && !(name == "user_response" && self.ui_capabilities.0) { return Err(anyhow::anyhow!("Tool '{}' is not allowed", name)); } diff --git a/crates/jcode-app-core/src/agent_tests/elicitation.rs b/crates/jcode-app-core/src/agent_tests/elicitation.rs index e8bb5fbf7bc..b9eb9e2f4ef 100644 --- a/crates/jcode-app-core/src/agent_tests/elicitation.rs +++ b/crates/jcode-app-core/src/agent_tests/elicitation.rs @@ -1,4 +1,14 @@ use super::*; + +fn attach_form_client( + session: &str, + connection: &str, +) -> tokio::sync::mpsc::UnboundedReceiver { + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + crate::elicitation::global().attach(connection, session, true, false, false, tx); + rx +} + #[tokio::test] async fn applet_elicitation_capability_updates_locked_tool_surface() { let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty()); @@ -45,3 +55,131 @@ async fn applet_elicitation_capability_updates_locked_tool_surface() { assert!(agent.locked_tools.is_none()); assert!(!agent.tool_names().await.iter().any(|n| n == "applet")); } + +#[tokio::test] +async fn ask_user_registers_for_a_form_capable_client_and_survives_detach() { + let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty()); + let session = agent.session_id().to_string(); + assert!(agent.locked_tools.is_none()); + let _ = agent.tool_definitions().await; + assert!(agent.locked_tools.is_some()); + + // Headless: no form-capable attachment, so the tool stays unregistered. + agent.set_form_capabilities(false, false).await; + assert!( + !agent + .tool_names() + .await + .iter() + .any(|name| name == "ask_user") + ); + + let _rx = attach_form_client(&session, "ask-user-capability-connection"); + agent.set_form_capabilities(false, false).await; + assert!( + agent.locked_tools.is_none(), + "first registration must unlock the frozen surface" + ); + assert!( + agent + .tool_names() + .await + .iter() + .any(|name| name == "ask_user") + ); + + // Already registered: a later capability change must not unlock again. + let _ = agent.tool_definitions().await; + assert!(agent.locked_tools.is_some()); + agent.set_form_capabilities(false, false).await; + assert!(agent.locked_tools.is_some()); + + // Detach keeps the registry entry: no unregister, no cache churn. + crate::elicitation::global().detach("ask-user-capability-connection"); + agent.set_form_capabilities(false, true).await; + assert!( + agent + .tool_names() + .await + .iter() + .any(|name| name == "ask_user") + ); + agent.set_form_capabilities(false, false).await; + assert!( + agent + .tool_names() + .await + .iter() + .any(|name| name == "ask_user") + ); +} + +#[tokio::test] +async fn ask_user_is_offered_on_the_next_request_after_a_late_attach() { + let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty()); + let session = agent.session_id().to_string(); + let first = agent.tool_definitions().await; + assert!(!first.iter().any(|tool| tool.name == "ask_user")); + assert!(agent.locked_tools.is_some()); + + let _rx = attach_form_client(&session, "ask-user-late-connection"); + agent.set_form_capabilities(false, false).await; + let next = agent.tool_definitions().await; + assert!(next.iter().any(|tool| tool.name == "ask_user")); +} + +#[tokio::test] +async fn ask_user_is_not_forced_into_an_explicit_allowlist() { + let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty()); + agent.allowed_tools = Some(["bash".to_string()].into_iter().collect()); + let session = agent.session_id().to_string(); + let _rx = attach_form_client(&session, "ask-user-allowlist-connection"); + agent.set_form_capabilities(false, false).await; + assert!( + agent + .registry + .tool_names() + .await + .iter() + .any(|name| name == "ask_user"), + "the tool is registered" + ); + assert!( + !agent + .tool_definitions() + .await + .iter() + .any(|tool| tool.name == "ask_user"), + "an explicit allowlist is respected" + ); +} + +#[tokio::test] +async fn hibernation_wake_keeps_registry_and_offered_tools_in_agreement() { + let _env = crate::storage::lock_test_env(); + let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty()); + let session = agent.session_id().to_string(); + let _rx = attach_form_client(&session, "ask-user-hibernation-connection"); + agent.set_form_capabilities(false, false).await; + let frozen = agent.tool_definitions().await; + assert!(frozen.iter().any(|tool| tool.name == "ask_user")); + + crate::elicitation::global().detach("ask-user-hibernation-connection"); + let _ = agent.hibernate_idle_caches(); + let registered = agent + .registry + .tool_names() + .await + .iter() + .any(|name| name == "ask_user"); + let offered = agent + .tool_definitions() + .await + .iter() + .any(|tool| tool.name == "ask_user"); + assert_eq!( + offered, registered, + "the frozen surface and the registry must agree after an idle wake" + ); + assert!(offered); +} diff --git a/crates/jcode-app-core/src/elicitation.rs b/crates/jcode-app-core/src/elicitation.rs index b8aa491d7b7..9ae30e22e0c 100644 --- a/crates/jcode-app-core/src/elicitation.rs +++ b/crates/jcode-app-core/src/elicitation.rs @@ -1,4 +1,6 @@ //! Session-scoped form broker. A single mutex makes validation and winning atomic. +pub mod ask_user; + use crate::protocol::{ ServerEvent, elicitation::{ElicitationResolution, ElicitationResponse, FormElicitation, FormSchema}, @@ -75,6 +77,14 @@ impl Broker { ServerEvent::ElicitationRequest(pending.request.clone()), ); } + // Mark the end of replay even when nothing was pending. Reconcile + // drafts against this boundary, never against a quiet interval. + send( + &events, + ServerEvent::ElicitationReplayComplete { + session_id: session.into(), + }, + ); } state.connections.insert( connection.into(), @@ -102,6 +112,14 @@ impl Broker { .filter(|c| c.session == session) .fold((false, false), |(d, a), c| (d || c.desktop, a || c.applet)) } + /// True when at least one live, form-capable connection is attached to the session. + pub fn forms(&self, session: &str) -> bool { + let state = self.state.lock().unwrap_or_else(|p| p.into_inner()); + state + .connections + .values() + .any(|c| c.session == session && c.forms && !c.events.is_closed()) + } pub fn start( self: &Arc, session: &str, @@ -292,11 +310,21 @@ mod tests { broker.attach(id, "s", true, true, false, tx); rx } + fn expect_replay_complete(event: Option, session: &str) { + match event { + Some(ServerEvent::ElicitationReplayComplete { session_id }) => { + assert_eq!(session_id, session); + } + other => panic!("expected replay completion for {session}, got {other:?}"), + } + } #[tokio::test] async fn fanout_first_valid_reply_wins_and_invalid_reply_stays_pending() { let broker = Arc::new(Broker::default()); let mut a = attach(&broker, "a"); let mut b = attach(&broker, "b"); + expect_replay_complete(a.recv().await, "s"); + expect_replay_complete(b.recv().await, "s"); let ticket = broker .start("s", None, "Question".into(), schema()) .unwrap() @@ -353,6 +381,7 @@ mod tests { async fn reconnect_catches_up_and_turn_cancel_withdraws() { let broker = Arc::new(Broker::default()); let mut a = attach(&broker, "a"); + expect_replay_complete(a.recv().await, "s"); let ticket = broker .start("s", None, "Question".into(), schema()) .unwrap() @@ -364,6 +393,7 @@ mod tests { b.recv().await, Some(ServerEvent::ElicitationRequest(_)) )); + expect_replay_complete(b.recv().await, "s"); assert_eq!( ticket.wait(async {}, Duration::from_secs(1)).await, ElicitOutcome::Cancelled @@ -386,6 +416,7 @@ mod tests { .is_none() ); let mut a = attach(&broker, "a"); + expect_replay_complete(a.recv().await, "s"); let ticket = broker .start("s", None, "Question".into(), schema()) .unwrap() @@ -417,4 +448,40 @@ mod tests { )); assert!(broker.state.lock().unwrap().pending.is_empty()); } + #[tokio::test] + async fn replay_requests_precede_replay_complete() { + let broker = Arc::new(Broker::default()); + let mut a = attach(&broker, "a"); + expect_replay_complete(a.recv().await, "s"); + let ticket = broker + .start("s", None, "Question".into(), schema()) + .unwrap() + .unwrap(); + assert!(matches!( + a.recv().await, + Some(ServerEvent::ElicitationRequest(_)) + )); + broker.detach("a"); + let mut b = attach(&broker, "b"); + match b.recv().await { + Some(ServerEvent::ElicitationRequest(request)) => { + assert_eq!(request.session_id, "s"); + } + other => panic!("expected replayed request first, got {other:?}"), + } + expect_replay_complete(b.recv().await, "s"); + assert!(b.try_recv().is_err()); + drop(ticket); + } + #[tokio::test] + async fn empty_replay_completes_and_non_form_attach_does_not() { + let broker = Arc::new(Broker::default()); + let mut a = attach(&broker, "a"); + expect_replay_complete(a.recv().await, "s"); + assert!(a.try_recv().is_err()); + + let (tx, mut plain) = mpsc::unbounded_channel(); + broker.attach("plain", "s", false, true, false, tx); + assert!(plain.try_recv().is_err()); + } } diff --git a/crates/jcode-app-core/src/elicitation/ask_user.rs b/crates/jcode-app-core/src/elicitation/ask_user.rs new file mode 100644 index 00000000000..14960be9888 --- /dev/null +++ b/crates/jcode-app-core/src/elicitation/ask_user.rs @@ -0,0 +1,891 @@ +//! `ask_user`: Claude's `AskUserQuestion` input compiled into one ACP flat form. +//! +//! The broker validates each field independently, so this module owns the +//! cross-field "Other" normalisation and the escaped tool-result formatting. +use crate::elicitation::ElicitOutcome; +use crate::protocol::elicitation::FormSchema; +use crate::tool::{Tool, ToolContext, ToolOutput}; +use anyhow::{Result, anyhow, bail}; +use async_trait::async_trait; +use serde_json::{Map, Value, json}; +use std::collections::HashSet; +use std::time::Duration; +use unicode_width::UnicodeWidthStr; + +/// Root and per-field layout tag. Clients must ignore keys they do not know. +const TAG: &str = "jcode.dev/askUser"; +/// Reserved choice that stands in for free-form "Other" text. +const OTHER: &str = "__other__"; +/// Maximum code points for the optional `q{i}_other` and `q{i}_notes` fields. +const MAX_TEXT: usize = 8192; +const TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60); + +pub struct AskUserTool; + +#[async_trait] +impl Tool for AskUserTool { + fn name(&self) -> &str { + "ask_user" + } + + fn description(&self) -> &str { + "Ask the user one to four structured questions and block until they answer. \ + Each question has 2-4 options and is single-select or multi-select. The user \ + can always choose Other and add free-form text and notes. Use this when you \ + need a decision, preference or missing detail before continuing." + } + + fn parameters_schema(&self) -> Value { + json!({ + "type": "object", + "properties": { + "questions": { + "type": "array", + "minItems": 1, + "maxItems": 4, + "items": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "The complete question to ask the user. Clear, specific, and ending with a question mark." + }, + "header": { + "type": "string", + "description": "Very short label shown as the question tab (at most 12 display characters)." + }, + "options": { + "type": "array", + "minItems": 2, + "maxItems": 4, + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "description": "Display text for the option (1-5 words)." + }, + "description": { + "type": "string", + "description": "Explanation of what this option means or what happens if it is chosen." + }, + "preview": { + "type": "string", + "description": "Optional preview content shown while the option is highlighted." + } + }, + "required": ["label", "description"] + } + }, + "multiSelect": { + "type": "boolean", + "description": "Allow the user to select more than one option." + } + }, + "required": ["question", "header", "options", "multiSelect"] + } + }, + "answers": { + "type": "object", + "description": "Ignored. Accepted for Claude AskUserQuestion compatibility." + }, + "annotations": { + "type": "object", + "description": "Ignored. Accepted for Claude AskUserQuestion compatibility." + }, + "metadata": { + "type": "object", + "description": "Ignored. Accepted for Claude AskUserQuestion compatibility." + } + }, + "required": ["questions"] + }) + } + + async fn execute(&self, input: Value, ctx: ToolContext) -> Result { + let questions = parse_questions(&input)?; + let schema = build_form(&questions)?; + let message = if questions.len() == 1 { + "The agent has a question.".to_string() + } else { + format!("The agent has {} questions.", questions.len()) + }; + let Some(ticket) = crate::elicitation::global() + .start( + &ctx.session_id, + Some(ctx.tool_call_id.clone()), + message, + schema, + ) + .map_err(|error| anyhow!(error))? + else { + bail!( + "No attached client can display questions; ask the user in your normal reply instead." + ); + }; + let outcome = ticket.wait(interrupted(&ctx), TIMEOUT).await; + format_outcome(&questions, outcome).map(ToolOutput::new) + } +} + +struct OptionItem { + label: String, + description: String, + preview: Option, +} + +struct Question { + question: String, + header: String, + options: Vec, + multi_select: bool, +} + +/// Validate the model-facing shape before anything reaches the broker. +fn parse_questions(input: &Value) -> Result> { + let list = input + .get("questions") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("`questions` must be an array"))?; + if list.is_empty() || list.len() > 4 { + bail!("ask_user needs 1-4 questions"); + } + let mut question_texts = HashSet::new(); + let mut questions = Vec::with_capacity(list.len()); + for value in list { + let question = text_field(value, "question")?; + let header = text_field(value, "header")?; + if UnicodeWidthStr::width(header.as_str()) > 12 { + bail!("question header `{header}` exceeds 12 display cells"); + } + if !question_texts.insert(question.clone()) { + bail!("duplicate question text `{question}`"); + } + let options = value + .get("options") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("`options` must be an array"))?; + if options.len() < 2 || options.len() > 4 { + bail!("each question needs 2-4 options"); + } + let mut labels = HashSet::new(); + let mut parsed = Vec::with_capacity(options.len()); + for option in options { + let label = text_field(option, "label")?; + if label == "Other" || label == OTHER { + bail!("`{label}` is a reserved option label"); + } + if !labels.insert(label.clone()) { + bail!("duplicate option label `{label}`"); + } + let description = option + .get("description") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + let preview = option + .get("preview") + .and_then(Value::as_str) + .map(str::to_string); + if let Some(preview) = &preview + && preview.len() > MAX_TEXT + { + bail!("option preview exceeds {MAX_TEXT} bytes"); + } + parsed.push(OptionItem { + label, + description, + preview, + }); + } + let multi_select = value + .get("multiSelect") + .and_then(Value::as_bool) + .unwrap_or(false); + questions.push(Question { + question, + header, + options: parsed, + multi_select, + }); + } + Ok(questions) +} + +fn text_field(value: &Value, key: &str) -> Result { + value + .get(key) + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| anyhow!("`{key}` must be a string")) +} + +/// Questions become `q1..q4`, each with optional `q{i}_other` and `q{i}_notes`. +fn build_form(questions: &[Question]) -> Result { + let mut properties = Map::new(); + let mut required = Vec::with_capacity(questions.len()); + for (index, question) in questions.iter().enumerate() { + let field = format!("q{}", index + 1); + let other_field = format!("{field}_other"); + let notes_field = format!("{field}_notes"); + let mut choices: Vec = question + .options + .iter() + .map(|option| { + let mut choice = json!({"const": option.label, "title": option.label}); + if !option.description.is_empty() { + choice["description"] = json!(option.description); + } + if let Some(preview) = &option.preview { + choice["_meta"] = json!({"preview": preview}); + } + choice + }) + .collect(); + choices.push(json!({"const": OTHER, "title": "Other"})); + let mut property = if question.multi_select { + json!({ + "type": "array", + "minItems": 1, + "title": question.header, + "description": question.question, + "items": {"anyOf": choices} + }) + } else { + json!({ + "type": "string", + "title": question.header, + "description": question.question, + "oneOf": choices + }) + }; + let mut field_meta = Map::new(); + field_meta.insert( + TAG.into(), + json!({ + "header": question.header, + "otherField": other_field, + "notesField": notes_field + }), + ); + property["_meta"] = Value::Object(field_meta); + properties.insert(field.clone(), property); + properties.insert( + other_field, + json!({"type": "string", "title": "Other", "maxLength": MAX_TEXT}), + ); + properties.insert( + notes_field, + json!({"type": "string", "title": "Notes", "maxLength": MAX_TEXT}), + ); + required.push(Value::String(field)); + } + let mut meta = Map::new(); + meta.insert(TAG.into(), json!({"version": 1})); + let schema = FormSchema(json!({ + "type": "object", + "properties": properties, + "required": required, + "_meta": meta + })); + schema.validate().map_err(|error| anyhow!(error))?; + Ok(schema) +} + +fn format_outcome(questions: &[Question], outcome: ElicitOutcome) -> Result { + match outcome { + ElicitOutcome::Accepted(content) => format_answers(questions, &content), + ElicitOutcome::Declined => { + Ok("User declined to answer your questions; proceed with best judgment.".into()) + } + ElicitOutcome::Cancelled => { + Ok("The question was cancelled before the user answered.".into()) + } + ElicitOutcome::Expired => Ok("The question expired before the user answered.".into()), + ElicitOutcome::Unsupported => Err(anyhow!( + "No attached client can display questions; ask the user in your normal reply instead." + )), + } +} + +/// One escaped line per question, with JSON arrays preserved for multi-select. +fn format_answers(questions: &[Question], content: &Map) -> Result { + let mut lines = Vec::with_capacity(questions.len()); + for (index, question) in questions.iter().enumerate() { + let field = format!("q{}", index + 1); + let other = content + .get(&format!("{field}_other")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|text| !text.is_empty()) + .map(str::to_string); + let notes = content + .get(&format!("{field}_notes")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|text| !text.is_empty()) + .map(str::to_string); + let selected = content.get(&field); + let (answer, also_wrote) = if question.multi_select { + let labels = selected + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("answer for `{field}` must be an array"))?; + let mut values = Vec::with_capacity(labels.len() + 1); + let mut substituted = false; + for label in labels.iter().filter_map(Value::as_str) { + if label == OTHER { + substituted = true; + values.push(Value::String( + other + .clone() + .unwrap_or_else(|| "Other (no text given)".into()), + )); + } else { + values.push(Value::String(label.into())); + } + } + if let Some(text) = &other + && !substituted + { + values.push(Value::String(text.clone())); + } + (Value::Array(values), None) + } else { + let label = selected + .and_then(Value::as_str) + .ok_or_else(|| anyhow!("answer for `{field}` must be a string"))?; + if label == OTHER { + ( + Value::String( + other + .clone() + .unwrap_or_else(|| "Other (no text given)".into()), + ), + None, + ) + } else { + (Value::String(label.into()), other.clone()) + } + }; + let mut line = format!( + "{}={}", + serde_json::to_string(&question.question)?, + serde_json::to_string(&answer)? + ); + if let Some(text) = &also_wrote { + line.push_str(&format!( + " (user also wrote: {})", + serde_json::to_string(text)? + )); + } + if let Some(text) = ¬es { + line.push_str(&format!(" (user notes: {})", serde_json::to_string(text)?)); + let previews = selected_previews(question, selected); + if !previews.is_empty() { + line.push_str(&format!( + " (previews for {})", + serde_json::to_string(&previews)? + )); + } + } + lines.push(line); + } + let mut output = String::from("User has answered your questions:\n"); + for line in lines { + output.push_str(&line); + output.push('\n'); + } + output.push_str("You can now continue with the user's answers in mind."); + Ok(output) +} + +/// Labels among the selection whose options carry a preview, in selection order. +fn selected_previews(question: &Question, selected: Option<&Value>) -> Vec { + let labels: Vec<&str> = match selected { + Some(Value::String(label)) => vec![label.as_str()], + Some(Value::Array(values)) => values.iter().filter_map(Value::as_str).collect(), + _ => Vec::new(), + }; + labels + .into_iter() + .filter(|label| *label != OTHER) + .filter(|label| { + question + .options + .iter() + .any(|option| option.label == *label && option.preview.is_some()) + }) + .map(str::to_string) + .collect() +} + +async fn interrupted(ctx: &ToolContext) { + match &ctx.graceful_shutdown_signal { + Some(signal) => { + if !signal.is_set() { + signal.notified().await; + } + } + None => std::future::pending::<()>().await, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::ServerEvent; + use crate::protocol::elicitation::ElicitationResponse; + use serde_json::json; + use tokio::sync::mpsc as tokio_mpsc; + + fn option(label: &str, description: &str) -> Value { + json!({"label": label, "description": description}) + } + + fn question(text: &str, header: &str, options: Value, multi: bool) -> Value { + json!({ + "question": text, + "header": header, + "options": options, + "multiSelect": multi + }) + } + + fn input(questions: Value) -> Value { + json!({"questions": questions}) + } + + fn parse(value: &Value) -> Vec { + parse_questions(value).unwrap() + } + + fn content(value: Value) -> Map { + value.as_object().unwrap().clone() + } + + fn answer_line(output: &str, index: usize) -> &str { + output.lines().nth(index + 1).unwrap() + } + + fn decode_answer(line: &str) -> Value { + let rest = &line[line.find('=').unwrap() + 1..]; + serde_json::Deserializer::from_str(rest) + .into_iter::() + .next() + .unwrap() + .unwrap() + } + + fn ctx(session: &str) -> ToolContext { + ToolContext { + session_id: session.into(), + message_id: "message".into(), + tool_call_id: "call".into(), + working_dir: None, + stdin_request_tx: None, + graceful_shutdown_signal: None, + execution_mode: crate::tool::ToolExecutionMode::AgentTurn, + } + } + + #[test] + fn form_schema_uses_flat_fields_with_meta_tags() { + let questions = parse(&input(json!([ + question( + "Pick one", + "Pick", + json!([option("A", "first"), option("B", "second")]), + false + ), + question( + "Pick many", + "Many", + json!([option("C", "third"), option("D", "fourth")]), + true + ) + ]))); + let schema = build_form(&questions).unwrap(); + let value = &schema.0; + assert_eq!(value["type"], "object"); + assert_eq!(value["_meta"][TAG]["version"], 1); + assert_eq!(value["required"], json!(["q1", "q2"])); + + let single = &value["properties"]["q1"]; + assert_eq!(single["type"], "string"); + assert_eq!(single["title"], "Pick"); + assert_eq!(single["description"], "Pick one"); + assert_eq!(single["oneOf"][0]["const"], "A"); + assert_eq!(single["oneOf"][0]["description"], "first"); + assert_eq!(single["oneOf"][2]["const"], OTHER); + assert_eq!(single["oneOf"][2]["title"], "Other"); + assert_eq!(single["_meta"][TAG]["header"], "Pick"); + assert_eq!(single["_meta"][TAG]["otherField"], "q1_other"); + assert_eq!(single["_meta"][TAG]["notesField"], "q1_notes"); + + let multi = &value["properties"]["q2"]; + assert_eq!(multi["type"], "array"); + assert_eq!(multi["minItems"], 1); + assert_eq!(multi["items"]["anyOf"][1]["const"], "D"); + assert_eq!(multi["items"]["anyOf"][2]["const"], OTHER); + + assert_eq!(value["properties"]["q1_other"]["maxLength"], 8192); + assert_eq!(value["properties"]["q1_notes"]["maxLength"], 8192); + assert_eq!(value["properties"]["q2_other"]["maxLength"], 8192); + assert_eq!(value["properties"]["q2_notes"]["maxLength"], 8192); + } + + #[test] + fn previews_land_in_option_meta() { + let questions = parse(&input(json!([question( + "Pick one", + "Pick", + json!([ + json!({"label":"A","description":"a","preview":"full text"}), + option("B", "b") + ]), + false + )]))); + let schema = build_form(&questions).unwrap(); + assert_eq!( + schema.0["properties"]["q1"]["oneOf"][0]["_meta"]["preview"], + "full text" + ); + assert!( + schema.0["properties"]["q1"]["oneOf"][1] + .get("_meta") + .is_none() + ); + } + + #[test] + fn input_checks_reject_bad_shapes() { + let good = question( + "Pick", + "Pick", + json!([option("A", "a"), option("B", "b")]), + false, + ); + for bad in [ + input(json!([])), + input(json!([good.clone(), good.clone()])), + input(json!([question( + "Pick", + "Pick", + json!([option("A", "a")]), + false + )])), + input(json!([question( + "Pick", + "Pick", + json!([ + option("A", "a"), + option("B", "b"), + option("C", "c"), + option("D", "d"), + option("E", "e") + ]), + false + )])), + input(json!([question( + "Pick", + "Pick", + json!([option("A", "a"), option("A", "b")]), + false + )])), + input(json!([question( + "Pick", + "Pick", + json!([option("Other", "a"), option("B", "b")]), + false + )])), + input(json!([question( + "Pick", + "Pick", + json!([option(OTHER, "a"), option("B", "b")]), + false + )])), + input(json!([question( + "Pick", + "Unicode width is not bytes", + json!([option("A", "a"), option("B", "b")]), + false + )])), + input(json!([question( + "Pick", + "Pick", + json!([ + json!({"label":"A","description":"a","preview":"x".repeat(8193)}), + option("B", "b") + ]), + false + )])), + ] { + assert!(parse_questions(&bad).is_err(), "{bad}"); + } + assert!(parse_questions(&input(json!([good]))).is_ok()); + } + + #[test] + fn header_limit_counts_display_cells() { + let twelve = "็•Œ".repeat(6); + let thirteen = "็•Œ".repeat(7); + let build = |header: &str| { + input(json!([question( + "Pick", + header, + json!([option("A", "a"), option("B", "b")]), + false + )])) + }; + assert!(parse_questions(&build(&twelve)).is_ok()); + assert!(parse_questions(&build(&thirteen)).is_err()); + } + + #[test] + fn over_limit_schema_strings_are_rejected_by_validation() { + let questions = parse(&input(json!([question( + "Pick", + "Pick", + json!([option("A", &"x".repeat(9000)), option("B", "b")]), + false + )]))); + assert!(build_form(&questions).is_err()); + } + + #[test] + fn other_rules_table_is_normalised() { + let one = parse(&input(json!([question( + "One", + "One", + json!([option("A", "a"), option("B", "b")]), + false + )]))); + let many = parse(&input(json!([question( + "Many", + "Many", + json!([option("A", "a"), option("B", "b")]), + true + )]))); + + let single = |value: Value| format_answers(&one, &content(value)).unwrap(); + let multi = |value: Value| format_answers(&many, &content(value)).unwrap(); + let first = |output: String| decode_answer(answer_line(&output, 0)).clone(); + + assert_eq!(first(single(json!({"q1": "A"}))), json!("A")); + + let with_text = single(json!({"q1": "A", "q1_other": " typed "})); + assert_eq!(decode_answer(answer_line(&with_text, 0)), json!("A")); + assert!(answer_line(&with_text, 0).contains("(user also wrote: \"typed\")")); + + assert_eq!( + decode_answer(answer_line( + &single(json!({"q1": OTHER, "q1_other": "typed"})), + 0 + )), + json!("typed") + ); + assert_eq!( + decode_answer(answer_line(&single(json!({"q1": OTHER})), 0)), + json!("Other (no text given)") + ); + + let multi_text = multi(json!({"q1": ["A", "B"], "q1_other": "typed"})); + assert_eq!( + decode_answer(answer_line(&multi_text, 0)), + json!(["A", "B", "typed"]) + ); + assert!(!answer_line(&multi_text, 0).contains("user also wrote")); + + assert_eq!( + decode_answer(answer_line( + &multi(json!({"q1": ["A", OTHER], "q1_other": "typed"})), + 0 + )), + json!(["A", "typed"]) + ); + assert_eq!( + decode_answer(answer_line(&multi(json!({"q1": [OTHER]})), 0)), + json!(["Other (no text given)"]) + ); + } + + #[test] + fn result_escapes_values_and_keeps_selection_boundaries() { + let question_text = "Pick, \"one\"\nใชใซ ๐ŸŽ‰"; + let questions = parse(&input(json!([question( + question_text, + "Pick", + json!([option("B, C", "x"), option("D\"E", "y")]), + true + )]))); + let notes = "keep line 1\nthen line 2"; + let output = format_answers( + &questions, + &content(json!({"q1": ["B, C", "D\"E"], "q1_notes": notes})), + ) + .unwrap(); + let line = answer_line(&output, 0); + assert!(line.starts_with(&serde_json::to_string(question_text).unwrap())); + assert_eq!(decode_answer(line), json!(["B, C", "D\"E"])); + assert!(line.contains(&format!( + "user notes: {}", + serde_json::to_string(notes).unwrap() + ))); + assert!(output.starts_with("User has answered your questions:\n")); + assert!(output.ends_with("You can now continue with the user's answers in mind.")); + } + + #[test] + fn notes_name_previewed_options() { + let questions = parse(&input(json!([question( + "Pick", + "Pick", + json!([ + json!({"label":"A","description":"a","preview":"preview A"}), + json!({"label":"B","description":"b","preview":"preview B"}) + ]), + true + )]))); + let output = format_answers( + &questions, + &content(json!({"q1": ["B", "A"], "q1_notes": "because"})), + ) + .unwrap(); + let line = answer_line(&output, 0); + assert!(line.contains("user notes: \"because\"")); + assert!(line.contains("(previews for [\"B\",\"A\"])")); + } + + #[test] + fn max_length_boundary_counts_code_points_not_bytes() { + let questions = parse(&input(json!([question( + "Pick", + "Pick", + json!([option("A", "a"), option("B", "b")]), + false + )]))); + let schema = build_form(&questions).unwrap(); + let exactly = "็•Œ".repeat(MAX_TEXT); + assert!(exactly.len() > MAX_TEXT); + assert!( + schema + .check_content(&content(json!({"q1": "A", "q1_other": exactly}))) + .is_ok() + ); + let over = "็•Œ".repeat(MAX_TEXT + 1); + assert!( + schema + .check_content(&content(json!({"q1": "A", "q1_other": over}))) + .is_err() + ); + assert!( + schema + .check_content(&content( + json!({"q1": "A", "q1_notes": "็•Œ".repeat(MAX_TEXT + 1)}) + )) + .is_err() + ); + } + + #[test] + fn terminal_outcomes_say_what_happened() { + let questions = parse(&input(json!([question( + "Pick", + "Pick", + json!([option("A", "a"), option("B", "b")]), + false + )]))); + assert!( + format_outcome(&questions, ElicitOutcome::Declined) + .unwrap() + .contains("declined") + ); + assert!( + format_outcome(&questions, ElicitOutcome::Cancelled) + .unwrap() + .contains("cancelled") + ); + assert!( + format_outcome(&questions, ElicitOutcome::Expired) + .unwrap() + .contains("expired") + ); + assert!(format_outcome(&questions, ElicitOutcome::Unsupported).is_err()); + } + + #[tokio::test] + async fn broker_round_trip_with_fake_connection() { + const SESSION: &str = "ask-user-round-trip-session"; + const CONNECTION: &str = "ask-user-round-trip-connection"; + let (tx, mut rx) = tokio_mpsc::unbounded_channel(); + crate::elicitation::global().attach(CONNECTION, SESSION, true, false, false, tx); + assert!(matches!( + rx.recv().await, + Some(ServerEvent::ElicitationReplayComplete { session_id }) if session_id == SESSION + )); + + let input = input(json!([ + question( + "Which one?", + "Pick", + json!([option("A", "a"), option("B", "b")]), + false + ), + question( + "Which many?", + "Many", + json!([option("C", "c"), option("D", "d")]), + true + ) + ])); + let handle = tokio::spawn(async move { AskUserTool.execute(input, ctx(SESSION)).await }); + let Some(ServerEvent::ElicitationRequest(request)) = rx.recv().await else { + panic!("expected an elicitation request"); + }; + assert_eq!(request.message, "The agent has 2 questions."); + assert_eq!(request.session_id, SESSION); + assert_eq!(request.tool_call_id.as_deref(), Some("call")); + assert_eq!( + request.requested_schema.0["properties"]["q1"]["type"], + "string" + ); + assert_eq!( + request.requested_schema.0["properties"]["q2"]["type"], + "array" + ); + + crate::elicitation::global() + .respond( + CONNECTION, + SESSION, + &request.elicitation_id, + ElicitationResponse::Accept { + content: Some(content(json!({"q1": "A", "q2": ["C"], "q1_notes": "ok"}))), + }, + ) + .unwrap(); + let output = handle.await.unwrap().unwrap().output; + assert_eq!(decode_answer(answer_line(&output, 0)), json!("A")); + assert!(answer_line(&output, 0).contains("user notes: \"ok\"")); + assert_eq!(decode_answer(answer_line(&output, 1)), json!(["C"])); + + crate::elicitation::global().detach(CONNECTION); + } + + #[tokio::test] + async fn no_form_client_is_an_error_telling_the_model_to_ask_directly() { + const SESSION: &str = "ask-user-headless-session"; + let input = input(json!([question( + "Pick", + "Pick", + json!([option("A", "a"), option("B", "b")]), + false + )])); + let error = AskUserTool + .execute(input, ctx(SESSION)) + .await + .unwrap_err() + .to_string(); + assert!(error.contains("normal reply"), "{error}"); + } +} diff --git a/crates/jcode-protocol/src/elicitation.rs b/crates/jcode-protocol/src/elicitation.rs index e0df8e90581..71cb2767dbc 100644 --- a/crates/jcode-protocol/src/elicitation.rs +++ b/crates/jcode-protocol/src/elicitation.rs @@ -316,6 +316,16 @@ mod wire_tests { let encoded = serde_json::to_value(&event).unwrap(); let decoded: ServerEvent = serde_json::from_value(encoded.clone()).unwrap(); assert_eq!(serde_json::to_value(decoded).unwrap(), encoded); + let event = ServerEvent::ElicitationReplayComplete { + session_id: "s".into(), + }; + let encoded = serde_json::to_value(&event).unwrap(); + assert_eq!( + encoded, + json!({"type": "elicitation_replay_complete", "session_id": "s"}) + ); + let decoded: ServerEvent = serde_json::from_value(encoded.clone()).unwrap(); + assert_eq!(serde_json::to_value(decoded).unwrap(), encoded); let legacy: Request = serde_json::from_value(json!({"type":"subscribe","id":1})).unwrap(); let encoded = serde_json::to_value(legacy).unwrap(); assert!(encoded.get("supports_elicitation_form").is_none()); diff --git a/crates/jcode-protocol/src/wire/events.rs b/crates/jcode-protocol/src/wire/events.rs index c85472999e8..6b8271b3a35 100644 --- a/crates/jcode-protocol/src/wire/events.rs +++ b/crates/jcode-protocol/src/wire/events.rs @@ -1183,6 +1183,13 @@ pub enum ServerEvent { /// Tool call ID this is associated with tool_call_id: String, }, + + /// The daemon finished replaying pending elicitation forms to this + /// attachment. Daemon-internal: it marks the end of reconnect + /// reconciliation, including an empty replay set, so a client can discard + /// drafts it was not re-sent. + #[serde(rename = "elicitation_replay_complete")] + ElicitationReplayComplete { session_id: String }, } impl ServerEvent { diff --git a/crates/jcode-tui/src/tui/app/input.rs b/crates/jcode-tui/src/tui/app/input.rs index 9d6159916b0..74645559ccf 100644 --- a/crates/jcode-tui/src/tui/app/input.rs +++ b/crates/jcode-tui/src/tui/app/input.rs @@ -3501,6 +3501,9 @@ impl App { /// Handle bracketed paste: store text content (image URLs are still detected inline) pub(super) fn handle_paste(&mut self, text: String) { self.wake_idle_hibernation(); + if crate::tui::ask_form::handle_paste(self, &text) { + return; + } handle_paste(self, text); } diff --git a/crates/jcode-tui/src/tui/app/remote.rs b/crates/jcode-tui/src/tui/app/remote.rs index efdef383b2a..395e33d0181 100644 --- a/crates/jcode-tui/src/tui/app/remote.rs +++ b/crates/jcode-tui/src/tui/app/remote.rs @@ -1097,6 +1097,9 @@ pub(super) fn handle_disconnect( "handle_disconnect: session={:?}, remote_session_id={:?}, reason={:?}, detail={}", app.resume_session_id, app.remote_session_id, reason, detail )); + // The form must not capture keys or paste while there is no transport to + // answer on; drafts are kept for replay after reconnect. + crate::tui::ask_form::on_connection_lost(); // A disconnect can drop the final auth catalog completion event. Keep any // queued prompt for reconnect, but release the transient model-setup gate so // it cannot remain blocked forever waiting for an event that was lost. diff --git a/crates/jcode-tui/src/tui/app/remote/key_handling/key_events.rs b/crates/jcode-tui/src/tui/app/remote/key_handling/key_events.rs index 20998bc967d..4a34d6744a1 100644 --- a/crates/jcode-tui/src/tui/app/remote/key_handling/key_events.rs +++ b/crates/jcode-tui/src/tui/app/remote/key_handling/key_events.rs @@ -91,6 +91,28 @@ pub(super) async fn handle_remote_key_internal( return Ok(()); } + // The question form outranks copy-selection and the composer while it owns + // input. It records the request id of a sent answer so its `Done`/`Error` + // acknowledgement is claimed instead of settling the turn. + match crate::tui::ask_form::handle_key(app, code, modifiers, text_input.as_deref()) { + crate::tui::ask_form::KeyOutcome::Ignored => {} + crate::tui::ask_form::KeyOutcome::Consumed => return Ok(()), + crate::tui::ask_form::KeyOutcome::Send { + session_id, + elicitation_id, + response, + } => { + match remote + .send_elicitation_response(&session_id, &elicitation_id, response) + .await + { + Ok(id) => crate::tui::ask_form::record_response_id(app, id), + Err(error) => crate::tui::ask_form::send_failed(app, &error.to_string()), + } + return Ok(()); + } + } + // Copy-selection mode owns the keyboard, mirroring the local path in // `input::handle_modal_key`. Without this, Enter/Y fell through to the // composer in client mode: Enter submitted the draft and letters were diff --git a/crates/jcode-tui/src/tui/app/remote/server_events.rs b/crates/jcode-tui/src/tui/app/remote/server_events.rs index 41c6c641b40..c7a7d6f3236 100644 --- a/crates/jcode-tui/src/tui/app/remote/server_events.rs +++ b/crates/jcode-tui/src/tui/app/remote/server_events.rs @@ -156,6 +156,9 @@ use history_fingerprint::last_applied_history_fingerprint; use history_fingerprint::record_applied_history_fingerprint; use history_fingerprint::should_skip_identical_history_payload; #[cfg(test)] +#[path = "server_events/ask_form_tests.rs"] +mod ask_form_tests; +#[cfg(test)] #[path = "server_events/history_dedup_tests.rs"] mod history_dedup_tests; @@ -241,6 +244,12 @@ pub(in crate::tui::app) fn handle_server_event( } event => (event, None), }; + // Claim form traffic, including the `Done`/`Error` acknowledgements of our + // own answers and replay completion, before terminal handling can settle an + // unrelated observed turn. + if crate::tui::ask_form::on_event(app, &event) { + return true; + } if identity.is_none() && app.remote_turn_fence.scoped() && matches!( diff --git a/crates/jcode-tui/src/tui/app/remote/server_events/ask_form_tests.rs b/crates/jcode-tui/src/tui/app/remote/server_events/ask_form_tests.rs new file mode 100644 index 00000000000..565cd85483c --- /dev/null +++ b/crates/jcode-tui/src/tui/app/remote/server_events/ask_form_tests.rs @@ -0,0 +1,537 @@ +//! Integration tests for the `ask_user` form hooks in `handle_server_event`. +//! +//! The form module is driven through its exported entry points, exactly as +//! `key_events.rs` and `handle_server_event` drive it, so these tests cover the +//! wiring rather than lane B's renderer. + +use super::*; +use crate::protocol::ServerEvent; +use crate::protocol::elicitation::{ + ElicitationResolution, ElicitationResponse, FormElicitation, FormSchema, +}; +use crate::tui::ask_form::{self, KeyOutcome}; +use crate::tui::backend::RemoteConnection; +use ratatui::crossterm::event::{KeyCode, KeyModifiers}; +use serde_json::json; + +const SESSION: &str = "session-a"; + +fn schema() -> FormSchema { + FormSchema(json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "required": ["q1"], + "properties": { + "q1": { + "type": "string", + "title": "Pick", + "description": "Which one?", + "_meta": {"jcode.dev/askUser": {"header": "Pick", "otherField": "q1_other"}}, + "oneOf": [ + {"const": "a", "title": "A"}, + {"const": "b", "title": "B"}, + {"const": "__other__", "title": "Other"} + ] + }, + "q1_other": {"type": "string", "maxLength": 8192} + } + })) +} + +fn untagged_schema() -> FormSchema { + FormSchema(json!({ + "type": "object", + "required": ["x"], + "properties": {"x": {"type": "string"}} + })) +} + +fn request(session: &str, elicitation_id: &str) -> ServerEvent { + ServerEvent::ElicitationRequest(FormElicitation { + elicitation_id: elicitation_id.into(), + session_id: session.into(), + tool_call_id: Some("call-1".into()), + message: "The agent has a question.".into(), + requested_schema: schema(), + }) +} + +fn history(session: &str) -> ServerEvent { + ServerEvent::History { + id: 1, + session_id: session.to_string(), + messages: vec![], + messages_base_count: None, + images_unchanged: false, + images: vec![], + provider_name: None, + provider_model: None, + subagent_model: None, + agent_model_overrides: Default::default(), + autoreview_enabled: None, + autojudge_enabled: None, + available_models: vec![], + available_model_routes: vec![], + mcp_servers: vec![], + skills: vec![], + total_tokens: None, + token_usage_totals: None, + all_sessions: vec![], + client_count: Some(1), + // Matches the canary attachment `Fixture::new` models, so a history + // refresh does not re-enable the first-run suggestion cards. + is_canary: Some(true), + reload_recovery: None, + server_version: None, + server_name: None, + server_icon: None, + server_has_update: Some(false), + was_interrupted: None, + connection_type: None, + status_detail: None, + upstream_provider: None, + provider_oauth_email: None, + provider_oauth_account_label: None, + resolved_credential: None, + available_reasoning_efforts: None, + reasoning_effort: None, + service_tier: None, + available_service_tiers: None, + compaction_mode: crate::config::CompactionMode::Reactive, + activity: None, + side_panel: crate::side_panel::SidePanelSnapshot::default(), + applets: Default::default(), + } +} + +struct Fixture { + app: crate::tui::app::App, + remote: RemoteConnection, + // `RemoteConnection::dummy` opens a tokio Unix socket pair, which needs a + // reactor for the lifetime of the connection. + _runtime: tokio::runtime::Runtime, +} + +impl Fixture { + fn new(session: &str) -> Self { + ask_form::reset_for_test(); + let mut app = crate::tui::app::tests::create_test_app(); + app.is_remote = true; + app.remote_session_id = Some(session.to_string()); + ask_form::on_remote_loop_start(&mut app); + // GitHub runners have no provider credentials, which makes + // `suggestion_prompts()` return the login hint and the first-run + // welcome outrank the form, so key assertions would depend on the + // machine's auth state. Canary builds suppress the suggestion cards; + // use that to model an established attached session deterministically. + app.session.is_canary = true; + assert!( + !app.onboarding_welcome_active(), + "ask_form fixtures must not start on the first-run welcome screen" + ); + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let remote = { + let _guard = runtime.enter(); + RemoteConnection::dummy() + }; + Self { + app, + remote, + _runtime: runtime, + } + } + + fn feed(&mut self, event: ServerEvent) -> bool { + let handled = handle_server_event(&mut self.app, event, &mut self.remote); + assert!( + !self.app.onboarding_welcome_active(), + "fixture left the first-run welcome screen, which outranks the form" + ); + handled + } + + fn key(&mut self, code: KeyCode) -> KeyOutcome { + ask_form::handle_key(&mut self.app, code, KeyModifiers::NONE, None) + } + + fn notice(&self) -> Option { + self.app + .status_notice + .as_ref() + .map(|(text, _)| text.clone()) + } +} + +fn expect_consumed(outcome: KeyOutcome) { + assert_eq!(outcome, KeyOutcome::Consumed); +} + +fn expect_ignored(outcome: KeyOutcome) { + assert_eq!(outcome, KeyOutcome::Ignored); +} + +fn expect_send(outcome: KeyOutcome) -> ElicitationResponse { + match outcome { + KeyOutcome::Send { response, .. } => response, + other => panic!("expected a response, got {other:?}"), + } +} + +fn select_first_question_answer(app: &mut crate::tui::app::App, digit: char) { + expect_consumed(ask_form::handle_key( + app, + KeyCode::Char(digit), + KeyModifiers::NONE, + None, + )); +} + +fn go_to_submit(app: &mut crate::tui::app::App) { + expect_consumed(ask_form::handle_key( + app, + KeyCode::Right, + KeyModifiers::NONE, + None, + )); +} + +/// Answer question one and submit the summary tab, recording `request_id` as +/// the acknowledgement owner exactly like the key hook does. +fn answer_and_submit(app: &mut crate::tui::app::App, request_id: u64) -> ElicitationResponse { + select_first_question_answer(app, '1'); + go_to_submit(app); + let response = expect_send(ask_form::handle_key( + app, + KeyCode::Enter, + KeyModifiers::NONE, + None, + )); + ask_form::record_response_id(app, request_id); + response +} + +fn accept_content(response: &ElicitationResponse) -> &serde_json::Map { + match response { + ElicitationResponse::Accept { + content: Some(content), + } => content, + other => panic!("expected an accepted response, got {other:?}"), + } +} + +#[test] +fn claimed_done_does_not_settle_an_observed_turn() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + answer_and_submit(&mut fixture.app, 42); + + // An observed turn: no local request id, an unscoped fence. + fixture.app.is_processing = true; + fixture.app.streaming.streaming_text = "observed output".into(); + fixture.app.status = crate::tui::ProcessingStatus::Streaming; + + assert!(fixture.feed(ServerEvent::Done { id: 42 })); + assert!(fixture.app.is_processing, "claimed Done settled the turn"); + assert!(matches!( + fixture.app.status, + crate::tui::ProcessingStatus::Streaming + )); + assert_eq!(fixture.app.streaming.streaming_text, "observed output"); +} + +#[test] +fn claimed_error_reopens_the_form_without_a_transcript_error() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + answer_and_submit(&mut fixture.app, 7); + let transcript = fixture.app.display_messages().len(); + + assert!(fixture.feed(ServerEvent::Error { + id: 7, + message: "answer rejected".into(), + retry_after_secs: None, + })); + assert_eq!(fixture.app.display_messages().len(), transcript); + assert_eq!( + fixture.notice().as_deref(), + Some("The answer was rejected: answer rejected") + ); + + // Editing resumes: leave the summary tab and submit again. + expect_consumed(fixture.key(KeyCode::Left)); + go_to_submit(&mut fixture.app); + let response = expect_send(fixture.key(KeyCode::Enter)); + assert_eq!(accept_content(&response).get("q1"), Some(&json!("a"))); +} + +#[test] +fn same_session_history_preserves_forms_drafts_and_response_ids() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '1'); + + fixture.feed(history(SESSION)); + go_to_submit(&mut fixture.app); + let response = expect_send(fixture.key(KeyCode::Enter)); + assert_eq!(accept_content(&response).get("q1"), Some(&json!("a"))); + ask_form::record_response_id(&mut fixture.app, 77); + + // A later refresh still keeps the response ownership. + fixture.feed(history(SESSION)); + fixture.app.is_processing = true; + fixture.app.streaming.streaming_text = "observed".into(); + fixture.app.status = crate::tui::ProcessingStatus::Streaming; + assert!(fixture.feed(ServerEvent::Done { id: 77 })); + assert!(fixture.app.is_processing); + + assert!(fixture.feed(ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Accepted, + })); + expect_ignored(fixture.key(KeyCode::Char('1'))); +} + +#[test] +fn connection_replacement_freezes_then_restores_a_replayed_form() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '2'); + + ask_form::on_connection_replaced(&mut fixture.app); + expect_ignored(fixture.key(KeyCode::Char('1'))); + + // The broker replays the identical form, then ends replay. + assert!(fixture.feed(request(SESSION, "e1"))); + assert!(fixture.feed(ServerEvent::ElicitationReplayComplete { + session_id: SESSION.into(), + })); + + go_to_submit(&mut fixture.app); + let response = expect_send(fixture.key(KeyCode::Enter)); + assert_eq!(accept_content(&response).get("q1"), Some(&json!("b"))); +} + +#[test] +fn empty_replay_after_a_reload_discards_drafts() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '1'); + + ask_form::on_connection_replaced(&mut fixture.app); + assert!(fixture.feed(ServerEvent::ElicitationReplayComplete { + session_id: SESSION.into(), + })); + expect_ignored(fixture.key(KeyCode::Char('1'))); + assert_eq!( + fixture.notice().as_deref(), + Some("1 question form(s) were lost while reconnecting.") + ); +} + +#[test] +fn replay_before_history_stages_the_new_session() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "old"))); + select_first_question_answer(&mut fixture.app, '1'); + + // A reconnect is followed by replay for the new attachment before its + // History has been processed: the app still reports the old session. + ask_form::on_connection_replaced(&mut fixture.app); + assert!(fixture.feed(request("session-b", "new"))); + expect_ignored(fixture.key(KeyCode::Char('1'))); + + fixture.feed(history("session-b")); + assert_eq!(fixture.app.remote_session_id.as_deref(), Some("session-b")); + expect_consumed(fixture.key(KeyCode::Char('1'))); +} + +#[test] +fn resolved_while_disconnected_removes_the_draft() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '1'); + + ask_form::on_connection_replaced(&mut fixture.app); + assert!(fixture.feed(ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Accepted, + })); + assert!(fixture.feed(ServerEvent::ElicitationReplayComplete { + session_id: SESSION.into(), + })); + expect_ignored(fixture.key(KeyCode::Char('1'))); +} + +#[test] +fn loop_teardown_clears_state() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '1'); + + ask_form::on_remote_loop_exit(); + expect_ignored(fixture.key(KeyCode::Char('1'))); + + // A fresh loop does not inherit the previous loop's form. + ask_form::on_remote_loop_start(&mut fixture.app); + expect_ignored(fixture.key(KeyCode::Char('1'))); +} + +#[test] +fn resolution_before_acknowledgement_stays_resolved() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + answer_and_submit(&mut fixture.app, 9); + + assert!(fixture.feed(ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Accepted, + })); + assert_eq!(fixture.notice().as_deref(), Some("Answer submitted.")); + expect_ignored(fixture.key(KeyCode::Char('1'))); + + // A late rejection must not resurrect the closed form. + assert!(fixture.feed(ServerEvent::Error { + id: 9, + message: "too late".into(), + retry_after_secs: None, + })); + expect_ignored(fixture.key(KeyCode::Char('1'))); +} + +#[test] +fn late_acknowledgement_after_resolution_is_claimed() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + answer_and_submit(&mut fixture.app, 13); + assert!(fixture.feed(ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Accepted, + })); + let transcript = fixture.app.display_messages().len(); + assert!(fixture.feed(ServerEvent::Done { id: 13 })); + assert_eq!(fixture.app.display_messages().len(), transcript); + expect_ignored(fixture.key(KeyCode::Char('1'))); +} + +#[test] +fn another_client_resolving_during_submit_closes_the_form() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + answer_and_submit(&mut fixture.app, 11); + + // Another attachment wins while our answer is outstanding. + assert!(fixture.feed(ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Accepted, + })); + assert_eq!(fixture.notice().as_deref(), Some("Answer submitted.")); + expect_ignored(fixture.key(KeyCode::Enter)); + + // Our acknowledgement is claimed without resurrecting the closed form. + assert!(fixture.feed(ServerEvent::Done { id: 11 })); + expect_ignored(fixture.key(KeyCode::Enter)); +} + +#[test] +fn transport_send_failure_restores_the_draft_with_a_notice() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '1'); + go_to_submit(&mut fixture.app); + let _ = expect_send(fixture.key(KeyCode::Enter)); + + ask_form::send_failed(&mut fixture.app, "transport closed"); + assert_eq!( + fixture.notice().as_deref(), + Some("Could not send the answer: transport closed") + ); + + let response = expect_send(fixture.key(KeyCode::Enter)); + assert_eq!(accept_content(&response).get("q1"), Some(&json!("a"))); +} + +#[test] +fn duplicate_submit_is_ignored_while_a_response_is_outstanding() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '1'); + go_to_submit(&mut fixture.app); + let first = expect_send(fixture.key(KeyCode::Enter)); + + expect_consumed(fixture.key(KeyCode::Enter)); + expect_consumed(fixture.key(KeyCode::Char('2'))); + ask_form::record_response_id(&mut fixture.app, 21); + assert_eq!(accept_content(&first).get("q1"), Some(&json!("a"))); +} + +#[test] +fn untagged_forms_are_ignored_without_a_response() { + let mut fixture = Fixture::new(SESSION); + let event = ServerEvent::ElicitationRequest(FormElicitation { + elicitation_id: "applet".into(), + session_id: SESSION.into(), + tool_call_id: None, + message: "Applet form".into(), + requested_schema: untagged_schema(), + }); + assert!(fixture.feed(event)); + expect_ignored(fixture.key(KeyCode::Char('1'))); +} + +#[test] +fn connection_loss_hides_the_form_and_restores_its_draft() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + select_first_question_answer(&mut fixture.app, '1'); + + // No transport means no answers: keys and paste are released, not queued. + ask_form::on_connection_lost(); + expect_ignored(fixture.key(KeyCode::Char('2'))); + assert!(!ask_form::handle_paste( + &mut fixture.app, + "typed while away" + )); + + // The reconnect replays the same form and the confirmed answer survives. + ask_form::on_connection_replaced(&mut fixture.app); + assert!(fixture.feed(request(SESSION, "e1"))); + assert!(fixture.feed(ServerEvent::ElicitationReplayComplete { + session_id: SESSION.into(), + })); + go_to_submit(&mut fixture.app); + let response = expect_send(fixture.key(KeyCode::Enter)); + assert_eq!(accept_content(&response).get("q1"), Some(&json!("a"))); +} + +#[test] +fn submitted_form_reopens_after_the_connection_changes() { + let mut fixture = Fixture::new(SESSION); + assert!(fixture.feed(request(SESSION, "e1"))); + let first = answer_and_submit(&mut fixture.app, 7); + assert_eq!(accept_content(&first).get("q1"), Some(&json!("a"))); + + // Submitting swallows input until the server resolves or rejects it. + expect_consumed(fixture.key(KeyCode::Enter)); + + // The acknowledgement never arrived; the next connection must reopen the + // form instead of leaving it stuck on `Submitting` forever. + ask_form::on_connection_lost(); + ask_form::on_connection_replaced(&mut fixture.app); + assert!(fixture.feed(request(SESSION, "e1"))); + assert!(fixture.feed(ServerEvent::ElicitationReplayComplete { + session_id: SESSION.into(), + })); + assert!( + fixture + .notice() + .is_some_and(|notice| notice.contains("not acknowledged")), + "reopening should explain why the answer needs review" + ); + let second = expect_send(fixture.key(KeyCode::Enter)); + assert_eq!(accept_content(&second).get("q1"), Some(&json!("a"))); +} diff --git a/crates/jcode-tui/src/tui/app/run_shell.rs b/crates/jcode-tui/src/tui/app/run_shell.rs index a9b10e78156..7876277f83b 100644 --- a/crates/jcode-tui/src/tui/app/run_shell.rs +++ b/crates/jcode-tui/src/tui/app/run_shell.rs @@ -840,6 +840,17 @@ impl App { super::handterm_native_scroll::HandtermNativeScrollClient::connect_from_env(); let mut remote_state = remote::RemoteRunState::default(); + // Clears thread-local form state on every return path, including the + // `?` early returns below that bypass the end of the loop. + struct AskFormLoopGuard; + impl Drop for AskFormLoopGuard { + fn drop(&mut self) { + crate::tui::ask_form::on_remote_loop_exit(); + } + } + crate::tui::ask_form::on_remote_loop_start(&mut self); + let _ask_form_guard = AskFormLoopGuard; + 'outer: loop { if self.display_messages.is_empty() { if self.server_spawning { @@ -894,6 +905,11 @@ impl App { remote::ConnectOutcome::Retry => continue, remote::ConnectOutcome::Quit => break 'outer, }; + // Exactly once per new connection, before post-connect processing + // can deliver replayed forms. A second bump after + // `handle_post_connect` would make replay-complete discard forms + // that were already replayed into this generation. + crate::tui::ask_form::on_connection_replaced(&mut self); status_spinner_renderer.invalidate(); match remote::handle_post_connect( diff --git a/crates/jcode-tui/src/tui/app/tui_state.rs b/crates/jcode-tui/src/tui/app/tui_state.rs index 4231c7b1112..43e9acefe6b 100644 --- a/crates/jcode-tui/src/tui/app/tui_state.rs +++ b/crates/jcode-tui/src/tui/app/tui_state.rs @@ -2149,6 +2149,9 @@ impl crate::tui::TuiState for App { fn side_panel_fullscreen(&self) -> bool { self.side_panel_fullscreen } + fn pending_provider_failover_active(&self) -> bool { + self.pending_provider_failover.is_some() + } fn pin_images(&self) -> bool { self.pin_images && !self.side_panel_user_hidden } diff --git a/crates/jcode-tui/src/tui/ask_form/keys.rs b/crates/jcode-tui/src/tui/ask_form/keys.rs new file mode 100644 index 00000000000..ca9da2ce218 --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/keys.rs @@ -0,0 +1,533 @@ +//! Key handling for the focused `ask_user` form. + +use ratatui::crossterm::event::{KeyCode, KeyModifiers}; + +use crate::protocol::elicitation::ElicitationResponse; + +use super::KeyOutcome; +use super::ViewContext; +use super::state::{EditorFocus, EditorKind, Form, MAX_TEXT_CODE_POINTS, SendTarget, State}; + +/// Key handling result, including a status notice for the caller to publish +/// after the state borrow is released. +pub(super) struct KeyResult { + pub outcome: KeyOutcome, + pub notice: Option, +} + +impl KeyResult { + fn ignored() -> Self { + Self { + outcome: KeyOutcome::Ignored, + notice: None, + } + } + + fn consumed() -> Self { + Self { + outcome: KeyOutcome::Consumed, + notice: None, + } + } + + fn notified(notice: impl Into) -> Self { + Self { + outcome: KeyOutcome::Consumed, + notice: Some(notice.into()), + } + } + + fn send(form: &Form, response: ElicitationResponse) -> Self { + Self { + outcome: KeyOutcome::Send { + session_id: form.session.clone(), + elicitation_id: form.elicitation_id.clone(), + response, + }, + notice: None, + } + } +} + +pub(super) fn handle_key( + state: &mut State, + context: &ViewContext, + code: KeyCode, + modifiers: KeyModifiers, + text_input: Option<&str>, +) -> KeyResult { + // Ctrl-modified keys are never consumed: Ctrl-C must reach the interrupt + // handler even while the form covers the composer. + if modifiers.contains(KeyModifiers::CONTROL) { + return KeyResult::ignored(); + } + if !context.eligible(state) || state.forms.is_empty() { + return KeyResult::ignored(); + } + + let active = state.active; + let Some(form) = state.forms.get_mut(active) else { + return KeyResult::ignored(); + }; + + // Repeat input while a response is outstanding is ignored, never sent + // twice. + if form.submit == super::state::SubmitState::Submitting { + return KeyResult::consumed(); + } + + let result = if form.editor.is_some() { + handle_editor(form, code, modifiers, text_input) + } else { + handle_normal(form, code, modifiers) + }; + + if let KeyOutcome::Send { + session_id, + elicitation_id, + .. + } = &result.outcome + { + state.last_sent = Some(SendTarget { + session: session_id.clone(), + elicitation_id: elicitation_id.clone(), + }); + } + result +} + +fn handle_editor( + form: &mut Form, + code: KeyCode, + modifiers: KeyModifiers, + text_input: Option<&str>, +) -> KeyResult { + let Some(editor) = form.editor else { + return KeyResult::consumed(); + }; + if editor.question >= form.questions.len() { + form.editor = None; + return KeyResult::consumed(); + } + + let back = code == KeyCode::BackTab + || (code == KeyCode::Tab && modifiers.contains(KeyModifiers::SHIFT)); + if back { + form.editor = None; + form.move_tab(false); + return KeyResult::consumed(); + } + if code == KeyCode::Tab { + form.editor = None; + form.move_tab(true); + return KeyResult::consumed(); + } + if matches!(code, KeyCode::Enter | KeyCode::Esc) { + // Save and leave without declining. + form.editor = None; + return KeyResult::consumed(); + } + + let question = &mut form.questions[editor.question]; + let (text, cursor) = match editor.kind { + EditorKind::Other => (&mut question.other_text, &mut question.other_cursor), + EditorKind::Notes => (&mut question.notes, &mut question.notes_cursor), + }; + let mut rejected = false; + match code { + KeyCode::Left => *cursor = previous_grapheme_boundary(text, *cursor), + KeyCode::Right => *cursor = next_grapheme_boundary(text, *cursor), + KeyCode::Home => *cursor = line_start(text, *cursor), + KeyCode::End => *cursor = line_end(text, *cursor), + KeyCode::Backspace => { + let start = previous_grapheme_boundary(text, *cursor); + if start < *cursor { + text.replace_range(start..*cursor, ""); + *cursor = start; + } + } + KeyCode::Delete => { + let end = next_grapheme_boundary(text, *cursor); + if end > *cursor { + text.replace_range(*cursor..end, ""); + } + } + KeyCode::Char(_) => { + let insert = text_input + .map(str::to_string) + .unwrap_or_else(|| match code { + KeyCode::Char(character) => character.to_string(), + _ => String::new(), + }); + if !insert.is_empty() { + rejected = !insert_text(text, cursor, &insert); + } + } + _ => {} + } + + if rejected { + let notice = format!("Text limit is {MAX_TEXT_CODE_POINTS} characters; edit rejected."); + form.notice = Some(notice.clone()); + return KeyResult::notified(notice); + } + if form + .notice + .as_deref() + .is_some_and(|notice| notice.starts_with("Text limit")) + { + form.notice = None; + } + KeyResult::consumed() +} + +fn handle_normal(form: &mut Form, code: KeyCode, modifiers: KeyModifiers) -> KeyResult { + if form.is_submit_tab() { + return handle_summary(form, code, modifiers); + } + + match code { + KeyCode::Left => { + form.move_tab(false); + KeyResult::consumed() + } + KeyCode::Right => { + form.move_tab(true); + KeyResult::consumed() + } + KeyCode::Tab => { + form.move_tab(true); + KeyResult::consumed() + } + KeyCode::BackTab => { + form.move_tab(false); + KeyResult::consumed() + } + KeyCode::Up => { + move_highlight(form, false); + KeyResult::consumed() + } + KeyCode::Down => { + move_highlight(form, true); + KeyResult::consumed() + } + KeyCode::PageUp => { + scroll_body(form, false); + KeyResult::consumed() + } + KeyCode::PageDown => { + scroll_body(form, true); + KeyResult::consumed() + } + KeyCode::Char(' ') => { + let question = form.tab; + choose_row(form, question, current_highlight(form)); + KeyResult::consumed() + } + KeyCode::Char(character @ '1'..='9') => { + let row = character as usize - '1' as usize; + let question = form.tab; + if row + < form + .questions + .get(question) + .map(super::state::Question::rows) + .unwrap_or(0) + { + if let Some(question_state) = form.questions.get_mut(question) { + question_state.highlight = row; + } + form.reveal_highlight = true; + choose_row(form, question, row); + } + KeyResult::consumed() + } + KeyCode::Char('n') => { + let question = form.tab; + if form + .questions + .get(question) + .is_some_and(|question| question.notes_field.is_some()) + { + if let Some(question) = form.questions.get_mut(question) { + question.notes_cursor = question.notes.len(); + } + form.editor = Some(EditorFocus { + question, + kind: EditorKind::Notes, + }); + KeyResult::consumed() + } else { + KeyResult::notified("This question has no notes field.") + } + } + KeyCode::Char('p') => { + let question = form.tab; + if form + .questions + .get(question) + .and_then(super::state::Question::preview_for_highlight) + .is_some() + { + form.preview_focus = !form.preview_focus; + form.preview_scroll = 0; + KeyResult::consumed() + } else { + KeyResult::notified("This option has no preview.") + } + } + KeyCode::Enter => { + let question = form.tab; + let multi = form + .questions + .get(question) + .is_some_and(|question| question.multi); + let highlighted_other = form + .questions + .get(question) + .is_some_and(super::state::Question::highlight_is_other); + // Single-select Other opens its editor instead of advancing. In a + // multi-select question Enter only advances; Space is what toggles + // a row, Other included. + if highlighted_other && !multi { + choose_row(form, question, current_highlight(form)); + return KeyResult::consumed(); + } + if !multi { + choose_row(form, question, current_highlight(form)); + } + form.move_tab(true); + KeyResult::consumed() + } + KeyCode::Esc => decline(form), + KeyCode::Char(_) => { + // Printable keys outside an editor are shortcuts only. Swallow + // them so they cannot type into the composer hidden behind the + // form. + KeyResult::consumed() + } + _ => KeyResult::consumed(), + } +} + +fn handle_summary(form: &mut Form, code: KeyCode, modifiers: KeyModifiers) -> KeyResult { + let submit = form.submit_tab(); + let back = code == KeyCode::BackTab + || (code == KeyCode::Tab && modifiers.contains(KeyModifiers::SHIFT)); + match code { + KeyCode::Up => { + form.summary_index = form.summary_index.saturating_sub(1); + KeyResult::consumed() + } + KeyCode::Down => { + form.summary_index = (form.summary_index + 1).min(submit); + KeyResult::consumed() + } + KeyCode::Left => { + form.move_tab(false); + KeyResult::consumed() + } + KeyCode::Right | KeyCode::Tab => { + if back { + form.move_tab(false); + } else { + form.move_tab(true); + } + KeyResult::consumed() + } + KeyCode::BackTab => { + form.move_tab(false); + KeyResult::consumed() + } + KeyCode::Enter => { + if form.summary_index == submit { + submit_form(form) + } else { + form.tab = form.summary_index; + form.editor = None; + form.preview_focus = false; + KeyResult::consumed() + } + } + KeyCode::Esc => decline(form), + KeyCode::Char(_) => KeyResult::consumed(), + _ => KeyResult::consumed(), + } +} + +fn current_highlight(form: &Form) -> usize { + form.questions + .get(form.tab) + .map(|question| question.highlight) + .unwrap_or(0) +} + +fn move_highlight(form: &mut Form, forward: bool) { + let Some(question) = form.current_question_mut() else { + return; + }; + let rows = question.rows(); + if rows == 0 { + return; + } + let next = if forward { + (question.highlight + 1).min(rows - 1) + } else { + question.highlight.saturating_sub(1) + }; + if next != question.highlight { + question.highlight = next; + form.preview_scroll = 0; + form.reveal_highlight = true; + } +} + +fn scroll_body(form: &mut Form, forward: bool) { + let page = form.last_body_height.max(1); + if form.preview_focus { + let max = form + .last_preview_lines + .saturating_sub(form.last_body_height.max(1)); + form.preview_scroll = if forward { + (form.preview_scroll + page).min(max) + } else { + form.preview_scroll.saturating_sub(page) + }; + } else { + let max = form + .last_body_lines + .saturating_sub(form.last_body_height.max(1)); + form.body_scroll = if forward { + (form.body_scroll + page).min(max) + } else { + form.body_scroll.saturating_sub(page) + }; + } + form.reveal_highlight = false; +} + +/// Select or toggle one option row. Opens the Other editor when that row was +/// chosen. +fn choose_row(form: &mut Form, question_index: usize, row: usize) { + let Some(question) = form.questions.get_mut(question_index) else { + return; + }; + if row < question.options.len() { + let value = question.options[row].value.clone(); + if question.multi { + if !question.selected.remove(&value) { + question.selected.insert(value); + } + } else { + question.confirmed = Some(value); + } + return; + } + + let Some(other) = question.other.clone() else { + return; + }; + let already_selected = question.multi && question.selected.contains(&other.value); + if question.multi { + if already_selected { + question.selected.remove(&other.value); + } else { + question.selected.insert(other.value); + } + } else { + question.confirmed = Some(other.value); + } + + if already_selected { + if form.editor.is_some_and(|editor| { + editor.question == question_index && editor.kind == EditorKind::Other + }) { + form.editor = None; + } + return; + } + + let cursor = form.questions[question_index].other_text.len(); + form.questions[question_index].other_cursor = cursor; + form.editor = Some(EditorFocus { + question: question_index, + kind: EditorKind::Other, + }); +} + +fn decline(form: &mut Form) -> KeyResult { + form.mark_submitting(); + KeyResult::send(form, ElicitationResponse::Decline) +} + +fn submit_form(form: &mut Form) -> KeyResult { + if !form.all_answered() { + let notice = "Answer every question before submitting.".to_string(); + form.notice = Some(notice.clone()); + return KeyResult::notified(notice); + } + match form.checked_content() { + Ok(content) => { + form.mark_submitting(); + KeyResult::send( + form, + ElicitationResponse::Accept { + content: Some(content), + }, + ) + } + Err(error) => { + form.notice = Some(error.clone()); + KeyResult::notified(error) + } + } +} + +/// Insert text at a byte cursor, rejecting (not truncating) anything that +/// would exceed the code-point limit. +pub(super) fn insert_text(text: &mut String, cursor: &mut usize, insert: &str) -> bool { + let candidate_points = text.chars().count() + insert.chars().count(); + if candidate_points > MAX_TEXT_CODE_POINTS { + return false; + } + *cursor = (*cursor).min(text.len()); + text.insert_str(*cursor, insert); + *cursor += insert.len(); + true +} + +fn previous_grapheme_boundary(text: &str, cursor: usize) -> usize { + use unicode_segmentation::UnicodeSegmentation; + let cursor = cursor.min(text.len()); + text[..cursor] + .grapheme_indices(true) + .next_back() + .map(|(index, _)| index) + .unwrap_or(0) +} + +fn next_grapheme_boundary(text: &str, cursor: usize) -> usize { + use unicode_segmentation::UnicodeSegmentation; + let cursor = cursor.min(text.len()); + text[cursor..] + .graphemes(true) + .next() + .map(|grapheme| cursor + grapheme.len()) + .unwrap_or(text.len()) +} + +fn line_start(text: &str, cursor: usize) -> usize { + let cursor = cursor.min(text.len()); + text[..cursor] + .rfind('\n') + .map(|index| index + 1) + .unwrap_or(0) +} + +fn line_end(text: &str, cursor: usize) -> usize { + let cursor = cursor.min(text.len()); + text[cursor..] + .find('\n') + .map(|offset| cursor + offset) + .unwrap_or(text.len()) +} diff --git a/crates/jcode-tui/src/tui/ask_form/mod.rs b/crates/jcode-tui/src/tui/ask_form/mod.rs new file mode 100644 index 00000000000..ddd2fe4a0ac --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/mod.rs @@ -0,0 +1,346 @@ +//! TUI `ask_user` question form. +//! +//! This module is deliberately self-contained: it owns state, rendering, key +//! handling, paste handling and reconnect reconciliation, and is wired into +//! the rest of the TUI through a handful of calls from `ui.rs`, +//! `key_events.rs`, `input.rs` and `server_events.rs`. +//! +//! State is a `thread_local!` scoped to one remote-loop instance, one +//! connection generation and one session. There is no `App` field. +//! +//! v1 renders tagged forms only: the schema root must carry +//! `_meta["jcode.dev/askUser"]`. Untagged and applet forms are ignored without +//! a response, so another attached client can still answer them. + +mod keys; +mod paste; +mod reconcile; +mod render; +mod schema; +mod state; + +#[cfg(test)] +mod tests; + +use ratatui::crossterm::event::{KeyCode, KeyModifiers}; + +use crate::protocol::ServerEvent; +use crate::tui::TuiState; +use crate::tui::app::App; + +use state::State; + +/// Outcome of routing a key into the form. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum KeyOutcome { + /// The form is not focused (or must not consume this key); later handlers + /// should run normally. + Ignored, + /// The form consumed the key and nothing else should. + Consumed, + /// Send this response; `record_response_id` follows a successful send. + Send { + session_id: String, + elicitation_id: String, + response: crate::protocol::elicitation::ElicitationResponse, + }, +} + +/// A focused view of the app surface the module is allowed to consult. +/// +/// Render, keys and paste all build this through [`FocusProbe`]. Keeping the +/// predicate in one place is what makes them agree about focus. +#[derive(Debug, Clone, Default)] +pub(super) struct ViewContext { + pub session: Option, + pub replay: bool, + pub blocked: Option<&'static str>, +} + +impl ViewContext { + pub(super) fn from_probe(probe: &(impl FocusProbe + ?Sized)) -> Self { + Self { + session: probe.probe_session(), + replay: probe.probe_replay(), + blocked: focus_block(probe), + } + } + + /// The form may render, capture keys and take paste only when it belongs + /// to the current session, its connection is attached and no other UI + /// owns input. + pub(in crate::tui::ask_form) fn eligible(&self, state: &State) -> bool { + !self.replay + && self.blocked.is_none() + && state.attached + && state.loop_live + && state.session.is_some() + && state.session == self.session + } +} + +/// The UI modes that outrank the question form. Ordered by precedence, matching +/// the TUI's key handlers and `draw_inner`'s overlays. +fn focus_block(probe: &(impl FocusProbe + ?Sized)) -> Option<&'static str> { + // The failover prompt owns keys before every other route. + if probe.probe_provider_failover() { + return Some("provider failover"); + } + if probe.probe_prompt_history() { + return Some("history search"); + } + if probe.probe_onboarding() { + return Some("onboarding"); + } + if probe.probe_copy_selection() { + return Some("copy selection"); + } + if probe.probe_commit_log() { + return Some("commit log"); + } + if probe.probe_changelog() { + return Some("changelog"); + } + if probe.probe_help() { + return Some("help"); + } + if probe.probe_model_status() { + return Some("model status"); + } + if probe.probe_panel_image() { + return Some("image preview"); + } + if probe.probe_session_picker() { + return Some("session picker"); + } + if probe.probe_login_picker() { + return Some("login picker"); + } + if probe.probe_account_picker() { + return Some("account picker"); + } + if probe.probe_usage_overlay() { + return Some("usage overlay"); + } + if probe.probe_inline_interactive() { + return Some("picker"); + } + if probe.probe_pending_login() { + return Some("login"); + } + if probe.probe_swarm_page() { + return Some("swarm page"); + } + if probe.probe_side_panel_fullscreen() { + return Some("side panel"); + } + None +} + +/// Everything the focus predicate reads, expressed as booleans so tests can +/// exercise every precedence source without constructing a full `App`. +pub(super) trait FocusProbe { + fn probe_session(&self) -> Option; + fn probe_replay(&self) -> bool; + fn probe_prompt_history(&self) -> bool; + fn probe_onboarding(&self) -> bool; + fn probe_copy_selection(&self) -> bool; + fn probe_commit_log(&self) -> bool; + fn probe_changelog(&self) -> bool; + fn probe_help(&self) -> bool; + fn probe_model_status(&self) -> bool; + fn probe_panel_image(&self) -> bool; + fn probe_session_picker(&self) -> bool; + fn probe_login_picker(&self) -> bool; + fn probe_account_picker(&self) -> bool; + fn probe_usage_overlay(&self) -> bool; + fn probe_inline_interactive(&self) -> bool; + fn probe_pending_login(&self) -> bool; + fn probe_swarm_page(&self) -> bool; + fn probe_side_panel_fullscreen(&self) -> bool; + fn probe_provider_failover(&self) -> bool; +} + +impl FocusProbe for T { + fn probe_session(&self) -> Option { + self.current_session_id() + } + fn probe_replay(&self) -> bool { + TuiState::is_replay(self) + } + fn probe_prompt_history(&self) -> bool { + self.prompt_history_search().is_some() + } + fn probe_onboarding(&self) -> bool { + self.onboarding_welcome_active() + } + fn probe_copy_selection(&self) -> bool { + self.copy_selection_mode() + } + fn probe_commit_log(&self) -> bool { + self.commit_log_overlay().is_some() + } + fn probe_changelog(&self) -> bool { + self.changelog_scroll().is_some() + } + fn probe_help(&self) -> bool { + self.help_scroll().is_some() + } + fn probe_model_status(&self) -> bool { + self.model_status_overlay().is_some() + } + fn probe_panel_image(&self) -> bool { + self.panel_image_preview().is_some() + } + fn probe_session_picker(&self) -> bool { + self.session_picker_overlay().is_some() + } + fn probe_login_picker(&self) -> bool { + self.login_picker_overlay().is_some() + } + fn probe_account_picker(&self) -> bool { + self.account_picker_overlay().is_some() + } + fn probe_usage_overlay(&self) -> bool { + self.usage_overlay().is_some() + } + fn probe_inline_interactive(&self) -> bool { + self.inline_interactive_state().is_some() + } + fn probe_pending_login(&self) -> bool { + self.login_input_hint().is_some() + } + fn probe_swarm_page(&self) -> bool { + self.swarm_panel_full_page() + } + fn probe_side_panel_fullscreen(&self) -> bool { + self.side_panel_fullscreen() + } + fn probe_provider_failover(&self) -> bool { + self.pending_provider_failover_active() + } +} + +/// Route a key into the focused form. Never holds a state borrow across an +/// await: this is a synchronous state transition that returns what to send. +/// +/// Ctrl-modified keys are never consumed, so Ctrl-C still reaches the normal +/// interrupt handler. +pub(crate) fn handle_key( + app: &mut App, + code: KeyCode, + modifiers: KeyModifiers, + text_input: Option<&str>, +) -> KeyOutcome { + let context = ViewContext::from_probe(app); + let result = + state::with(|state| keys::handle_key(state, &context, code, modifiers, text_input)); + if let Some(notice) = result.notice { + app.set_status_notice(notice); + } + result.outcome +} + +/// Route pasted text into the focused form editor, or open the selected Other +/// editor. Returns false so normal paste routing continues when the form has +/// no text target. +pub(crate) fn handle_paste(app: &mut App, text: &str) -> bool { + let context = ViewContext::from_probe(app); + let result = state::with(|state| paste::handle_paste(state, &context, text)); + if let Some(notice) = result.notice { + app.set_status_notice(notice); + } + result.consumed +} + +/// Consume server events owned by this module. +/// +/// Must not respond while replaying history (`app.is_replay()`). `History` is +/// deliberately not replay completion: same-session refreshes preserve forms, +/// drafts and response ownership. +pub(crate) fn on_event(app: &mut App, event: &ServerEvent) -> bool { + if let ServerEvent::ElicitationReplayComplete { session_id } = event { + // Reconcile at the app level so the exported entry point owns the + // state borrow. Recorded history never answers or discards drafts. + if TuiState::is_replay(app) { + return false; + } + on_replay_complete(app, session_id); + return true; + } + let context = ViewContext::from_probe(app); + let result = state::with(|state| reconcile::handle_event(state, &context, event)); + if let Some(notice) = result.notice { + app.set_status_notice(notice); + } + result.consumed +} + +/// Render at the end of `draw_inner`. Takes `&dyn TuiState`, never `App`. +pub(crate) fn render(frame: &mut ratatui::Frame, app: &dyn TuiState) { + let context = ViewContext::from_probe(app); + let area = frame.area(); + state::with(|state| render::render_view(frame, state, &context, area)); +} + +/// Record the request id returned by `send_elicitation_response`. +pub(crate) fn record_response_id(_app: &mut App, request_id: u64) { + state::with(|state| reconcile::record_response_id(state, request_id)); +} + +/// A transport send failure: restore editing, keep the draft, show a notice. +pub(crate) fn send_failed(app: &mut App, message: &str) { + let context = ViewContext::from_probe(app); + let applied = state::with(|state| reconcile::send_failed(state, &context, message)); + if applied { + app.set_status_notice(format!("Could not send the answer: {message}")); + } +} + +/// Reconciliation entry point for `ServerEvent::ElicitationReplayComplete`. +pub(crate) fn on_replay_complete(app: &mut App, session_id: &str) { + let context = ViewContext::from_probe(app); + let notice = state::with(|state| reconcile::on_replay_complete(state, &context, session_id)); + if let Some(notice) = notice { + app.set_status_notice(notice); + } +} + +/// A remote loop starts with a clean scope. +pub(crate) fn on_remote_loop_start(app: &mut App) { + let session = ViewContext::from_probe(app).session; + state::with(|state| { + state.reset(); + state.loop_live = true; + state.generation = 1; + state.attached = true; + state.session = session; + }); +} + +/// The remote loop ended. Nothing survives into the next loop or the +/// non-remote path. +pub(crate) fn on_remote_loop_exit() { + state::with(State::reset); +} + +/// The transport dropped. Hide the panel and release keys and paste until the +/// reconnect succeeds, but keep drafts for replay. +pub(crate) fn on_connection_lost() { + state::with(|state| state.attached = false); +} + +/// A new attachment replaces the connection: hide the panel, freeze drafts and +/// drop response ownership from the old generation. +pub(crate) fn on_connection_replaced(app: &mut App) { + let session = ViewContext::from_probe(app).session; + let reopened = state::with(|state| reconcile::connection_replaced(state, session.as_deref())); + if reopened > 0 { + app.set_status_notice(format!( + "{reopened} answer(s) were not acknowledged before the connection changed; review and submit again." + )); + } +} + +#[cfg(test)] +pub(crate) use state::reset_for_test; diff --git a/crates/jcode-tui/src/tui/ask_form/paste.rs b/crates/jcode-tui/src/tui/ask_form/paste.rs new file mode 100644 index 00000000000..e9a3f11d90a --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/paste.rs @@ -0,0 +1,118 @@ +//! Paste routing for the focused `ask_user` form. + +use super::ViewContext; +use super::keys::insert_text; +use super::state::{EditorFocus, EditorKind, Form, MAX_TEXT_CODE_POINTS, State}; + +pub(super) struct PasteResult { + pub consumed: bool, + pub notice: Option, +} + +impl PasteResult { + fn ignored() -> Self { + Self { + consumed: false, + notice: None, + } + } + + fn consumed() -> Self { + Self { + consumed: true, + notice: None, + } + } + + fn rejected() -> Self { + Self { + consumed: true, + notice: Some(format!( + "Text limit is {MAX_TEXT_CODE_POINTS} characters; paste rejected." + )), + } + } +} + +/// True when the paste was consumed by a focused form editor (or opened the +/// selected Other editor). When the form has no text target this returns false +/// so normal paste routing continues to the composer, with a status notice +/// pointing at the covered destination. +pub(super) fn handle_paste(state: &mut State, context: &ViewContext, text: &str) -> PasteResult { + if text.is_empty() || !context.eligible(state) || state.forms.is_empty() { + return PasteResult::ignored(); + } + + let active = state.active; + let Some(form) = state.forms.get_mut(active) else { + return PasteResult::ignored(); + }; + + if form.submit == super::state::SubmitState::Submitting { + // No editor writes while a response is outstanding. + return PasteResult::consumed(); + } + + if let Some(editor) = form.editor { + return if paste_into_editor(form, editor, text) { + PasteResult::consumed() + } else { + PasteResult::rejected() + }; + } + + let question_index = form.tab; + let highlighted_other = form + .current_question() + .is_some_and(super::state::Question::highlight_is_other); + if highlighted_other && let Some(editor) = select_other(form, question_index) { + return if paste_into_editor(form, editor, text) { + PasteResult::consumed() + } else { + PasteResult::rejected() + }; + } + + PasteResult { + consumed: false, + notice: Some( + "Paste went to the composer behind the question form; press n or choose Other to type here." + .to_string(), + ), + } +} + +fn select_other(form: &mut Form, question_index: usize) -> Option { + let question = form.questions.get_mut(question_index)?; + let other = question.other.clone()?; + if question.multi { + question.selected.insert(other.value); + } else { + question.confirmed = Some(other.value); + } + question.other_cursor = question.other_text.len(); + let editor = EditorFocus { + question: question_index, + kind: EditorKind::Other, + }; + form.editor = Some(editor); + Some(editor) +} + +fn paste_into_editor(form: &mut Form, editor: EditorFocus, text: &str) -> bool { + let Some(question) = form.questions.get_mut(editor.question) else { + return true; + }; + let (target, cursor) = match editor.kind { + EditorKind::Other => (&mut question.other_text, &mut question.other_cursor), + EditorKind::Notes => (&mut question.notes, &mut question.notes_cursor), + }; + if !insert_text(target, cursor, text) { + form.notice = Some(format!( + "Text limit is {MAX_TEXT_CODE_POINTS} characters; paste rejected." + )); + return false; + } + form.notice = None; + true +} diff --git a/crates/jcode-tui/src/tui/ask_form/reconcile.rs b/crates/jcode-tui/src/tui/ask_form/reconcile.rs new file mode 100644 index 00000000000..6679af8e8a5 --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/reconcile.rs @@ -0,0 +1,259 @@ +//! Lifecycle and reconnect reconciliation for the `ask_user` form. +//! +//! The daemon's form broker is in memory, so a reload drops pending forms +//! without a resolution. A reconnect replays what is still pending and then +//! emits `ElicitationReplayComplete` (added to the protocol in lane C). Between +//! those two points forms are frozen drafts; replay restores them only against +//! an identical schema. + +use crate::protocol::ServerEvent; +use crate::protocol::elicitation::ElicitationResolution; + +use super::ViewContext; +use super::schema; +use super::state::{Form, ResponseOwner, State, SubmitState}; + +pub(super) struct EventResult { + pub consumed: bool, + pub notice: Option, +} + +impl EventResult { + fn ignored() -> Self { + Self { + consumed: false, + notice: None, + } + } + + fn consumed() -> Self { + Self { + consumed: true, + notice: None, + } + } + + fn notified(notice: impl Into) -> Self { + Self { + consumed: true, + notice: Some(notice.into()), + } + } +} + +pub(super) fn handle_event( + state: &mut State, + context: &ViewContext, + event: &ServerEvent, +) -> EventResult { + // Never answer while replaying recorded history. + if context.replay { + return EventResult::ignored(); + } + + match event { + ServerEvent::ElicitationRequest(request) => { + if !adopt_session(state, Some(&request.session_id), context) { + return EventResult::ignored(); + } + state.attached = true; + + // v1 shows tagged `ask_user` forms only. Applet and other forms + // are ignored without a response so another attached client can + // still answer them. + if !schema::is_tagged(&request.requested_schema.0) { + return EventResult::consumed(); + } + + let generation = state.generation; + if let Some(index) = state.find_form(&request.session_id, &request.elicitation_id) { + if state.forms[index].schema == request.requested_schema { + // Replayed identical form: restore the draft untouched. + state.forms[index].message = request.message.clone(); + state.forms[index].seen_generation = Some(generation); + } else { + let replacement = Form::new(request, generation); + match replacement { + Some(form) => state.forms[index] = form, + None => { + state.forms.remove(index); + if state.active >= state.forms.len() { + state.active = state.forms.len().saturating_sub(1); + } + } + } + } + } else if let Some(form) = Form::new(request, generation) { + if state.forms.is_empty() { + state.active = 0; + } + state.forms.push(form); + } + EventResult::consumed() + } + ServerEvent::ElicitationResolved { + session_id, + elicitation_id, + outcome, + } => { + if state.session.as_deref() != Some(session_id) { + return EventResult::ignored(); + } + let Some(form) = state.remove_form(session_id, elicitation_id) else { + return EventResult::ignored(); + }; + let notice = match outcome { + ElicitationResolution::Accepted => { + if form.submit == SubmitState::Submitting { + "Answer submitted.".to_string() + } else { + "Question form answered elsewhere.".to_string() + } + } + ElicitationResolution::Declined => "Question form declined.".to_string(), + ElicitationResolution::Cancelled => "Question form cancelled.".to_string(), + ElicitationResolution::Expired => "Question form expired.".to_string(), + }; + EventResult::notified(notice) + } + ServerEvent::Done { id } => { + if state.responses.remove(id).is_some() { + EventResult::consumed() + } else { + EventResult::ignored() + } + } + ServerEvent::Error { id, message, .. } => { + let Some(owner) = state.responses.remove(id) else { + return EventResult::ignored(); + }; + let Some(index) = state.find_form(&owner.session, &owner.elicitation_id) else { + // Resolution wins: a resolved form is never resurrected. + return EventResult::consumed(); + }; + if state.forms[index].submit != SubmitState::Submitting { + return EventResult::consumed(); + } + state.forms[index].restore_editing_after_rejection(message.clone()); + EventResult::notified(format!("The answer was rejected: {message}")) + } + ServerEvent::History { session_id, .. } => { + // Not replay completion. Adopting a genuinely changed session + // clears the old session's drafts immediately, including replay + // that arrived before this History. An equal session keeps every + // form, draft and response id. Ignored so later handlers still see + // History. + adopt_session(state, Some(session_id), context); + EventResult::ignored() + } + // Everything else is not ours. `ElicitationReplayComplete` is handled + // by the module-level `on_event` entry point before this dispatch. + _ => EventResult::ignored(), + } +} + +pub(super) fn record_response_id(state: &mut State, request_id: u64) { + let Some(target) = state.last_sent.take() else { + return; + }; + state.responses.insert( + request_id, + ResponseOwner { + session: target.session, + elicitation_id: target.elicitation_id, + }, + ); +} + +pub(super) fn send_failed(state: &mut State, _context: &ViewContext, message: &str) -> bool { + let Some(target) = state.last_sent.as_ref() else { + return false; + }; + let session = target.session.clone(); + let elicitation_id = target.elicitation_id.clone(); + let Some(index) = state.find_form(&session, &elicitation_id) else { + // Resolution wins over a later local failure. + state.last_sent = None; + return false; + }; + if state.forms[index].submit != SubmitState::Submitting { + state.last_sent = None; + return false; + } + state.forms[index].restore_editing_after_rejection(message.to_string()); + state.last_sent = None; + true +} + +pub(super) fn connection_replaced(state: &mut State, app_session: Option<&str>) -> usize { + state.generation = state.generation.wrapping_add(1).max(1); + state.attached = false; + state.responses.clear(); + state.last_sent = None; + + if let Some(session) = app_session + && state.session.as_deref() != Some(session) + { + // A session change clears the old session's drafts immediately. + state.clear_forms(); + state.session = Some(session.to_string()); + return 0; + } + + // Same session: freeze drafts and wait for replay. + let mut reopened = 0; + for form in &mut state.forms { + form.seen_generation = None; + // The old transport died before acknowledging this answer. The server + // may or may not have received it; reopen the form so a rejection or + // replay can resolve it, and so a delivered-but-unacknowledged answer + // can be submitted again. + if matches!(form.submit, SubmitState::Submitting) { + form.submit = SubmitState::Idle; + reopened += 1; + } + } + reopened +} + +pub(super) fn on_replay_complete( + state: &mut State, + context: &ViewContext, + session_id: &str, +) -> Option { + if state.session.as_deref() != Some(session_id) + && !adopt_session(state, Some(session_id), context) + { + return None; + } + state.attached = true; + let dropped = state.discard_unreplayed(); + if dropped > 0 { + Some(format!( + "{dropped} question form(s) were lost while reconnecting." + )) + } else { + None + } +} + +/// Adopt a session that the attachment reports before `History` has updated +/// the app's current session. Returns false for an unrelated session. +fn adopt_session(state: &mut State, event_session: Option<&str>, context: &ViewContext) -> bool { + let Some(event_session) = event_session else { + return false; + }; + if state.session.as_deref() == Some(event_session) { + return true; + } + let state_is_current = state.session.as_deref() == context.session.as_deref(); + let event_is_current = context.session.as_deref() == Some(event_session); + if state.session.is_none() || context.session.is_none() || state_is_current || event_is_current + { + state.clear_forms(); + state.session = Some(event_session.to_string()); + true + } else { + false + } +} diff --git a/crates/jcode-tui/src/tui/ask_form/render.rs b/crates/jcode-tui/src/tui/ask_form/render.rs new file mode 100644 index 00000000000..550a2183232 --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/render.rs @@ -0,0 +1,775 @@ +//! Rendering for the `ask_user` form. +//! +//! The panel is bottom-anchored so the chat above stays visible. Chrome rows +//! (tabs and status) are always exactly one row and truncate with an ellipsis +//! measured in display cells; the question body scrolls as a whole. + +use ratatui::Frame; +use ratatui::layout::{Position, Rect}; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Clear, Paragraph}; +use unicode_segmentation::UnicodeSegmentation; +use unicode_width::UnicodeWidthStr; + +use super::ViewContext; +use super::state::{EditorKind, Form, Question, State, SubmitState}; + +pub(super) fn render_view(frame: &mut Frame, state: &mut State, context: &ViewContext, area: Rect) { + if !context.eligible(state) { + return; + } + let buffer_area = *frame.buffer_mut().area(); + let area = area.intersection(buffer_area); + if area.width == 0 || area.height == 0 { + return; + } + let height = panel_height(area.height); + if height == 0 { + return; + } + let active = state.active; + let Some(form) = state.forms.get_mut(active) else { + return; + }; + let rect = Rect::new(area.x, area.y + area.height - height, area.width, height); + frame.render_widget(Clear, rect); + draw_panel(frame, form, rect); +} + +/// At most 60% of the terminal rows. Terminals shorter than 12 rows use every +/// row available so the form can still show focused content. +pub(super) fn panel_height(height: u16) -> u16 { + if height == 0 { + 0 + } else if height < 12 { + height + } else { + ((u32::from(height) * 3) / 5).max(3).min(u32::from(height)) as u16 + } +} + +fn draw_panel(frame: &mut Frame, form: &mut Form, rect: Rect) { + if rect.width == 0 || rect.height == 0 { + return; + } + let show_tabs = rect.height >= 3; + let show_status = rect.height >= 2; + let body_height = rect + .height + .saturating_sub(u16::from(show_tabs)) + .saturating_sub(u16::from(show_status)); + let body_y = rect.y + u16::from(show_tabs); + + if show_tabs { + let line = tab_line(form, rect.width as usize); + frame.render_widget( + Paragraph::new(line), + Rect::new(rect.x, rect.y, rect.width, 1), + ); + } + + if body_height > 0 { + draw_body( + frame, + form, + Rect::new(rect.x, body_y, rect.width, body_height), + ); + } + + if show_status { + let line = status_line(form, rect.width as usize); + frame.render_widget( + Paragraph::new(line), + Rect::new(rect.x, rect.y + rect.height - 1, rect.width, 1), + ); + } +} + +fn draw_body(frame: &mut Frame, form: &mut Form, rect: Rect) { + let width = rect.width as usize; + let height = rect.height as usize; + let narrow = width < 100; + form.last_body_height = height; + + if narrow && form.preview_focus { + let preview = build_preview_lines(form, width); + form.last_preview_lines = preview.len(); + form.last_body_lines = preview.len(); + let max = preview.len().saturating_sub(height); + form.preview_scroll = form.preview_scroll.min(max); + draw_preview_pane( + frame, + &preview, + rect.x, + rect.y, + rect.width, + height, + form.preview_scroll, + ); + return; + } + + let (options_width, preview_width) = if narrow { + (width, 0) + } else { + let preview_width = width.saturating_sub(1) / 2; + (width.saturating_sub(preview_width + 1), preview_width) + }; + + let body = build_body(form, options_width); + form.last_body_lines = body.lines.len(); + + if form.reveal_highlight { + if let Some(start) = body.highlight_start(form) { + form.body_scroll = reveal_scroll(form.body_scroll, start, height); + } + form.reveal_highlight = false; + } + if let Some((row, _)) = body.cursor { + form.body_scroll = reveal_scroll(form.body_scroll, row, height); + } + let max = body.lines.len().saturating_sub(height); + form.body_scroll = form.body_scroll.min(max); + let scroll = form.body_scroll; + + for (offset, line) in body + .lines + .iter() + .skip(scroll) + .take(height) + .cloned() + .enumerate() + { + frame.render_widget( + Paragraph::new(line), + Rect::new(rect.x, rect.y + offset as u16, rect.width, 1), + ); + } + + if let Some((row, column)) = body.cursor + && row >= scroll + && row < scroll + height + && width > 0 + { + let x = rect.x + (column.min(width.saturating_sub(1))) as u16; + let y = rect.y + (row - scroll) as u16; + frame.set_cursor_position(Position::new(x, y)); + } + + if preview_width > 0 { + let preview = build_preview_lines(form, preview_width); + form.last_preview_lines = preview.len(); + let max = preview.len().saturating_sub(height); + form.preview_scroll = form.preview_scroll.min(max); + draw_preview_pane( + frame, + &preview, + rect.x + options_width as u16 + 1, + rect.y, + preview_width as u16, + height, + form.preview_scroll, + ); + } +} + +fn draw_preview_pane( + frame: &mut Frame, + lines: &[Line<'static>], + x: u16, + y: u16, + width: u16, + height: usize, + scroll: usize, +) { + if width == 0 || height == 0 { + return; + } + let total = lines.len(); + let clipped = total > height; + let content_rows = if clipped { + height.saturating_sub(1) + } else { + height + }; + let mut shown = 0usize; + for (offset, line) in lines + .iter() + .skip(scroll) + .take(content_rows) + .cloned() + .enumerate() + { + frame.render_widget( + Paragraph::new(line), + Rect::new(x, y + offset as u16, width, 1), + ); + shown += 1; + } + if clipped { + let remaining = total.saturating_sub(scroll + shown); + let line = Line::from(Span::styled( + format!("+{remaining} lines"), + Style::default() + .fg(Color::DarkGray) + .add_modifier(Modifier::DIM), + )); + frame.render_widget( + Paragraph::new(line), + Rect::new(x, y + content_rows as u16, width, 1), + ); + } +} + +fn reveal_scroll(scroll: usize, target: usize, height: usize) -> usize { + if height == 0 { + return 0; + } + if target < scroll { + target + } else if target >= scroll + height { + target + 1 - height + } else { + scroll + } +} + +struct Body { + lines: Vec>, + starts: Vec, + cursor: Option<(usize, usize)>, + summary: bool, +} + +impl Body { + fn highlight_start(&self, form: &Form) -> Option { + if self.summary { + self.starts.get(form.summary_index).copied() + } else { + form.current_question() + .and_then(|question| self.starts.get(question.highlight)) + .copied() + } + } +} + +fn build_body(form: &Form, width: usize) -> Body { + if width == 0 { + return Body { + lines: Vec::new(), + starts: Vec::new(), + cursor: None, + summary: false, + }; + } + if form.is_submit_tab() { + return build_summary(form, width); + } + build_options(form, width) +} + +fn build_options(form: &Form, width: usize) -> Body { + let Some(question) = form.current_question() else { + return Body { + lines: Vec::new(), + starts: Vec::new(), + cursor: None, + summary: false, + }; + }; + let mut lines = Vec::new(); + push_wrapped( + &mut lines, + &question.text, + width, + Style::default().add_modifier(Modifier::BOLD), + "", + "", + ); + lines.push(Line::default()); + let mut starts = Vec::with_capacity(question.rows()); + let mut cursor = None; + let editor = form.editor.filter(|editor| editor.question == form.tab); + + for (index, choice) in question.options.iter().enumerate() { + starts.push(lines.len()); + let highlighted = index == question.highlight; + let marker = if highlighted { "> " } else { " " }; + let check = if question.multi { + if question.selected.contains(&choice.value) { + "[x] " + } else { + "[ ] " + } + } else { + "" + }; + let style = if highlighted { + Style::default().add_modifier(Modifier::REVERSED) + } else { + Style::default() + }; + let prefix = format!("{marker}{}. {check}", index + 1); + push_wrapped( + &mut lines, + &choice.label, + width, + style, + &prefix, + &" ".repeat(display_width(&prefix)), + ); + if let Some(description) = &choice.description { + push_wrapped( + &mut lines, + description, + width, + Style::default() + .fg(Color::DarkGray) + .add_modifier(Modifier::DIM), + " ", + " ", + ); + } + } + + if let Some(other) = &question.other { + starts.push(lines.len()); + let row = question.options.len(); + let highlighted = question.highlight == row; + let marker = if highlighted { "> " } else { " " }; + let check = if question.multi { + if question.selected.contains(&other.value) { + "[x] " + } else { + "[ ] " + } + } else { + "" + }; + let style = if highlighted { + Style::default().add_modifier(Modifier::REVERSED) + } else { + Style::default() + }; + let prefix = format!("{marker}{}. {check}Other: ", row + 1); + match editor { + Some(editor) if editor.kind == EditorKind::Other => { + let available = width.saturating_sub(display_width(&prefix)).max(1); + let (editor_lines, (row, column)) = + layout_editor(&question.other_text, available, question.other_cursor); + for (index, text) in editor_lines.iter().enumerate() { + let lead = if index == 0 { + prefix.clone() + } else { + " ".repeat(display_width(&prefix)) + }; + lines.push(Line::from(Span::styled(format!("{lead}{text}"), style))); + } + cursor = Some(( + lines.len() - editor_lines.len() + row, + display_width(&prefix) + column, + )); + } + _ => { + let text = if question.other_text.trim().is_empty() { + "(type to answer)" + } else { + question.other_text.as_str() + }; + push_wrapped( + &mut lines, + text, + width, + style, + &prefix, + &" ".repeat(display_width(&prefix)), + ); + } + } + } + + if !question.notes.trim().is_empty() + || editor.is_some_and(|editor| editor.kind == EditorKind::Notes) + { + lines.push(Line::default()); + let prefix = "Notes: "; + match editor { + Some(editor) if editor.kind == EditorKind::Notes => { + let available = width.saturating_sub(display_width(prefix)).max(1); + let (editor_lines, (row, column)) = + layout_editor(&question.notes, available, question.notes_cursor); + for (index, text) in editor_lines.iter().enumerate() { + let lead = if index == 0 { + prefix.to_string() + } else { + " ".repeat(display_width(prefix)) + }; + lines.push(Line::from(Span::styled( + format!("{lead}{text}"), + Style::default() + .fg(Color::DarkGray) + .add_modifier(Modifier::DIM), + ))); + } + cursor = Some(( + lines.len() - editor_lines.len() + row, + display_width(prefix) + column, + )); + } + _ => push_wrapped( + &mut lines, + question.notes.trim(), + width, + Style::default() + .fg(Color::DarkGray) + .add_modifier(Modifier::DIM), + prefix, + " ", + ), + } + } + + Body { + lines, + starts, + cursor, + summary: false, + } +} + +fn build_summary(form: &Form, width: usize) -> Body { + let mut lines = Vec::new(); + let mut starts = Vec::with_capacity(form.question_count() + 1); + for (index, question) in form.questions.iter().enumerate() { + starts.push(lines.len()); + let selected = form.summary_index == index; + let marker = if selected { "> " } else { " " }; + let check = if question.answered() { "โœ“" } else { "ยท" }; + let style = if selected { + Style::default().add_modifier(Modifier::REVERSED) + } else { + Style::default() + }; + let prefix = format!("{marker}{check} {}. {}: ", index + 1, question.header); + push_wrapped( + &mut lines, + &question.answer_text(), + width, + style, + &prefix, + &" ".repeat(display_width(&prefix)), + ); + } + starts.push(lines.len()); + let selected = form.summary_index == form.submit_tab(); + let marker = if selected { "> " } else { " " }; + let suffix = if form.all_answered() { + "" + } else { + " (answer every question)" + }; + let style = if selected { + Style::default() + .add_modifier(Modifier::REVERSED) + .add_modifier(Modifier::BOLD) + } else if form.all_answered() { + Style::default().add_modifier(Modifier::BOLD) + } else { + Style::default() + .fg(Color::DarkGray) + .add_modifier(Modifier::DIM) + }; + lines.push(Line::from(Span::styled( + format!("{marker}[ Submit ]{suffix}"), + style, + ))); + + Body { + lines, + starts, + cursor: None, + summary: true, + } +} + +fn build_preview_lines(form: &Form, width: usize) -> Vec> { + let mut lines = Vec::new(); + lines.push(Line::from(Span::styled( + "Preview", + Style::default().add_modifier(Modifier::BOLD), + ))); + let preview = form + .current_question() + .and_then(Question::preview_for_highlight); + match preview { + Some(preview) => push_wrapped(&mut lines, preview, width, Style::default(), "", ""), + None => lines.push(Line::from(Span::styled( + "No preview for this option.", + Style::default() + .fg(Color::DarkGray) + .add_modifier(Modifier::DIM), + ))), + } + lines +} + +pub(super) fn tab_line(form: &Form, width: usize) -> Line<'static> { + if width == 0 { + return Line::default(); + } + let mut segments: Vec<(String, Style)> = Vec::with_capacity(form.question_count() + 1); + for (index, question) in form.questions.iter().enumerate() { + let check = if question.answered() { "โœ“" } else { "" }; + let text = format!("{}.{}{check}", index + 1, question.header); + segments.push((text, tab_style(form.tab == index))); + segments.push((" ".to_string(), Style::default())); + } + let submit = if form.all_answered() { + "Submitโœ“" + } else { + "Submit" + }; + segments.push((submit.to_string(), tab_style(form.tab == form.submit_tab()))); + // Drop the trailing separator so truncation does not waste cells. + if segments + .last() + .is_some_and(|(text, _)| text.trim().is_empty()) + { + segments.pop(); + } + compose_chrome(segments, width) +} + +fn tab_style(active: bool) -> Style { + if active { + Style::default() + .add_modifier(Modifier::REVERSED) + .add_modifier(Modifier::BOLD) + } else { + Style::default() + } +} + +pub(super) fn status_line(form: &Form, width: usize) -> Line<'static> { + if width == 0 { + return Line::default(); + } + let (left, style) = match &form.submit { + SubmitState::Submitting => ( + "submittingโ€ฆ".to_string(), + Style::default().fg(Color::Yellow), + ), + SubmitState::Rejected(message) => ( + format!("rejected: {message}"), + Style::default().fg(Color::Red), + ), + SubmitState::Idle => { + if let Some(notice) = &form.notice { + (notice.clone(), Style::default().fg(Color::Yellow)) + } else if let Some(editor) = form.editor { + let label = match editor.kind { + EditorKind::Other => "OTHER", + EditorKind::Notes => "NOTES", + }; + ( + format!("EDIT {label} ยท Enter save ยท Esc back"), + Style::default(), + ) + } else if form.preview_focus { + ( + "PREVIEW ยท p options ยท PgUp/PgDn scroll".to_string(), + Style::default(), + ) + } else { + ( + "OPTIONS ยท โ†‘โ†“ move ยท Space select ยท Enter next ยท n notes ยท p preview ยท Esc decline" + .to_string(), + Style::default(), + ) + } + } + }; + let answered = form + .questions + .iter() + .filter(|question| question.answered()) + .count(); + let right = if form.is_submit_tab() { + format!( + "{answered}/{} answered ยท Enter submit", + form.question_count() + ) + } else { + format!("{answered}/{} answered", form.question_count()) + }; + let combined = format!("{left} {right}"); + Line::from(Span::styled( + truncate_cells(&combined, width), + style.add_modifier(Modifier::DIM), + )) +} + +fn compose_chrome(segments: Vec<(String, Style)>, width: usize) -> Line<'static> { + let total: usize = segments.iter().map(|(text, _)| display_width(text)).sum(); + if total <= width { + let spans: Vec> = segments + .into_iter() + .map(|(text, style)| Span::styled(text, style)) + .collect(); + return Line::from(spans); + } + let budget = width.saturating_sub(1); + let mut used = 0usize; + let mut spans = Vec::new(); + for (text, style) in segments { + if used >= budget { + break; + } + let text_width = display_width(&text); + if used + text_width <= budget { + used += text_width; + spans.push(Span::styled(text, style)); + } else { + // Reserve the final cell for the single ellipsis appended below. + let truncated = truncate_raw(&text, budget - used); + used = budget; + spans.push(Span::styled(truncated, style)); + } + } + spans.push(Span::raw("โ€ฆ")); + Line::from(spans) +} + +fn push_wrapped( + lines: &mut Vec>, + text: &str, + width: usize, + style: Style, + first_prefix: &str, + rest_prefix: &str, +) { + if width == 0 { + return; + } + let first_width = width.saturating_sub(display_width(first_prefix)).max(1); + let wrapped = wrap_text(text, first_width); + for (index, part) in wrapped.iter().enumerate() { + let prefix = if index == 0 { + first_prefix + } else { + rest_prefix + }; + lines.push(Line::from(Span::styled(format!("{prefix}{part}"), style))); + } +} + +fn layout_editor(text: &str, width: usize, cursor: usize) -> (Vec, (usize, usize)) { + let width = width.max(1); + let mut lines = vec![String::new()]; + let mut row = 0usize; + let mut column = 0usize; + let mut offset = 0usize; + let mut cursor_position = None; + for grapheme in text.graphemes(true) { + if offset == cursor { + cursor_position = Some((row, column)); + } + if grapheme == "\n" { + lines.push(String::new()); + row += 1; + column = 0; + } else { + let grapheme_width = display_width(grapheme); + if column + grapheme_width > width && column > 0 { + lines.push(String::new()); + row += 1; + column = 0; + } + if let Some(line) = lines.last_mut() { + line.push_str(grapheme); + } + column += grapheme_width; + } + offset += grapheme.len(); + } + if cursor >= text.len() { + cursor_position = Some((row, column)); + } + (lines, cursor_position.unwrap_or((0, 0))) +} + +/// Wrap text to `width` display cells, preserving explicit newlines and +/// preferring a break at the last space on the line. +fn wrap_text(text: &str, width: usize) -> Vec { + if width == 0 { + return Vec::new(); + } + let mut output = Vec::new(); + for paragraph in text.split('\n') { + if paragraph.is_empty() { + output.push(String::new()); + continue; + } + if display_width(paragraph) <= width { + output.push(paragraph.to_string()); + continue; + } + let mut current = String::new(); + let mut current_width = 0usize; + let mut last_space = None; + for grapheme in paragraph.graphemes(true) { + let grapheme_width = display_width(grapheme); + if current_width + grapheme_width > width && !current.is_empty() { + if let Some(space) = last_space.filter(|space| *space > 0) { + let remainder = current[space + 1..].to_string(); + output.push(current[..space].to_string()); + current = remainder; + } else { + output.push(std::mem::take(&mut current)); + } + current_width = display_width(¤t); + last_space = current.rfind(' '); + } + if grapheme == " " { + last_space = Some(current.len()); + } + current.push_str(grapheme); + current_width += grapheme_width; + } + output.push(current); + } + output +} + +fn display_width(text: &str) -> usize { + UnicodeWidthStr::width(text) +} + +/// Truncate a single line to `width` display cells, ending with an ellipsis. +fn truncate_cells(text: &str, width: usize) -> String { + if width == 0 { + return String::new(); + } + if display_width(text) <= width { + return text.to_string(); + } + let mut output = truncate_raw(text, width.saturating_sub(1)); + output.push('โ€ฆ'); + output +} + +/// Truncate to at most `width` display cells without adding an ellipsis. +fn truncate_raw(text: &str, width: usize) -> String { + let mut output = String::new(); + let mut used = 0usize; + for grapheme in text.graphemes(true) { + let grapheme_width = display_width(grapheme); + if used + grapheme_width > width { + break; + } + output.push_str(grapheme); + used += grapheme_width; + } + output +} diff --git a/crates/jcode-tui/src/tui/ask_form/schema.rs b/crates/jcode-tui/src/tui/ask_form/schema.rs new file mode 100644 index 00000000000..72d3a914991 --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/schema.rs @@ -0,0 +1,235 @@ +//! Parsing for `ask_user` form schemas. +//! +//! The tool emits a flat ACP form whose schema root is tagged with +//! [`TAG`](super::TAG). This module converts that schema into the small model +//! the TUI renders: question text, single/multi-select options, the "Other" +//! text field and the per-question notes field. +//! +//! v1 intentionally ignores every form that is not tagged, including applet +//! forms. See `plans/active/ASK_USER_FORM.md`. + +use serde_json::Value; + +use super::state::{Choice, OtherField, Question, TAG}; + +/// True when the schema root carries the `ask_user` tag. +pub(super) fn is_tagged(schema: &Value) -> bool { + schema + .get("_meta") + .and_then(Value::as_object) + .and_then(|meta| meta.get(TAG)) + .is_some() +} + +/// Extract `q1`..`qN` questions in numeric order. +/// +/// Returns `None` when the tagged schema contains no usable question, so a +/// malformed form is ignored rather than rendered empty. +pub(super) fn parse_questions(schema: &Value) -> Option> { + if !is_tagged(schema) { + return None; + } + let properties = schema.get("properties")?.as_object()?; + let mut indexed: Vec<(u32, &str)> = properties + .keys() + .filter_map(|name| question_index(name).map(|index| (index, name.as_str()))) + .collect(); + indexed.sort_by_key(|(index, _)| *index); + + let mut questions = Vec::new(); + for (_, name) in indexed { + let Some(property) = properties.get(name) else { + continue; + }; + if let Some(question) = parse_question(name, property, properties) { + questions.push(question); + } + } + (!questions.is_empty()).then_some(questions) +} + +/// `q1` -> 1. Auxiliary fields (`q1_other`) deliberately do not match. +fn question_index(name: &str) -> Option { + let digits = name.strip_prefix('q')?; + if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let index: u32 = match digits.parse() { + Ok(index) => index, + Err(_) => return None, + }; + (1..=64).contains(&index).then_some(index) +} + +fn parse_question( + name: &str, + property: &Value, + properties: &serde_json::Map, +) -> Option { + let meta = property.get("_meta").and_then(Value::as_object); + let tool_meta = meta + .and_then(|meta| meta.get(TAG)) + .and_then(Value::as_object); + + let header = tool_meta + .and_then(|meta| meta.get("header")) + .and_then(Value::as_str) + .or_else(|| property.get("title").and_then(Value::as_str)) + .unwrap_or(name) + .to_string(); + let text = property + .get("description") + .and_then(Value::as_str) + .or_else(|| property.get("title").and_then(Value::as_str)) + .unwrap_or(header.as_str()) + .to_string(); + + let kind = property.get("type").and_then(Value::as_str)?; + let (multi, choices) = match kind { + "string" => (false, property.get("oneOf")?.as_array()?), + "array" => { + let items = property.get("items")?; + let choices = items + .get("anyOf") + .or_else(|| items.get("oneOf"))? + .as_array()?; + (true, choices) + } + _ => return None, + }; + + let mut options = Vec::new(); + let mut other_marker = None; + for choice in choices { + let Some(value) = choice.get("const").and_then(Value::as_str) else { + continue; + }; + let label = choice + .get("title") + .and_then(Value::as_str) + .unwrap_or(value) + .to_string(); + if value == "__other__" { + other_marker = Some(value.to_string()); + continue; + } + let preview = choice + .get("_meta") + .and_then(Value::as_object) + .and_then(|meta| meta.get("preview")) + .and_then(Value::as_str) + .map(str::to_string); + options.push(Choice { + value: value.to_string(), + label, + description: choice + .get("description") + .and_then(Value::as_str) + .map(str::to_string), + preview, + }); + } + + let other_field = tool_meta + .and_then(|meta| meta.get("otherField")) + .and_then(Value::as_str) + .filter(|field| properties.contains_key(*field)) + .map(str::to_string); + let other_value = other_marker.unwrap_or_else(|| "__other__".to_string()); + let other = other_field.map(|field| OtherField { + value: other_value, + field, + }); + + let notes_field = tool_meta + .and_then(|meta| meta.get("notesField")) + .and_then(Value::as_str) + .filter(|field| properties.contains_key(*field)) + .map(str::to_string); + + if options.is_empty() && other.is_none() { + return None; + } + + Some(Question::new( + name.to_string(), + header, + text, + multi, + options, + other, + notes_field, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parses_tagged_single_multi_other_and_notes() { + let schema = json!({ + "_meta": { "jcode.dev/askUser": {"version": 1} }, + "type": "object", + "properties": { + "q1": { + "type": "string", + "title": "Pick", + "description": "Which one?", + "_meta": { "jcode.dev/askUser": {"header": "One", "otherField": "q1_other", "notesField": "q1_notes"} }, + "oneOf": [ + {"const": "a", "title": "A", "description": "first", "_meta": {"preview": "A preview"}}, + {"const": "b", "title": "B"}, + {"const": "__other__", "title": "Other"} + ] + }, + "q1_other": {"type": "string"}, + "q1_notes": {"type": "string"}, + "q2": { + "type": "array", + "title": "Many", + "_meta": { "jcode.dev/askUser": {"header": "Two"} }, + "items": {"anyOf": [ + {"const": "x", "title": "X"}, + {"const": "y", "title": "Y"} + ]} + } + } + }); + assert!(is_tagged(&schema)); + let questions = parse_questions(&schema).expect("questions"); + assert_eq!(questions.len(), 2); + assert_eq!(questions[0].header, "One"); + assert_eq!(questions[0].text, "Which one?"); + assert!(!questions[0].multi); + assert_eq!(questions[0].options.len(), 2); + assert_eq!( + questions[0].options[0].preview.as_deref(), + Some("A preview") + ); + assert!(questions[0].other.is_some()); + assert_eq!(questions[0].notes_field.as_deref(), Some("q1_notes")); + assert!(questions[1].multi); + assert_eq!(questions[1].options.len(), 2); + assert!(questions[1].other.is_none()); + } + + #[test] + fn ignores_untagged_and_malformed_schemas() { + let untagged = json!({"type": "object", "properties": {"q1": {"type": "string", "oneOf": [{"const": "a"}]}}}); + assert!(!is_tagged(&untagged)); + assert!(parse_questions(&untagged).is_none()); + let empty = json!({"type": "object", "properties": {}}); + assert!(parse_questions(&empty).is_none()); + } + + #[test] + fn auxiliary_fields_are_not_questions() { + assert_eq!(question_index("q1"), Some(1)); + assert_eq!(question_index("q12"), Some(12)); + assert_eq!(question_index("q1_other"), None); + assert_eq!(question_index("q"), None); + assert_eq!(question_index("other"), None); + } +} diff --git a/crates/jcode-tui/src/tui/ask_form/state.rs b/crates/jcode-tui/src/tui/ask_form/state.rs new file mode 100644 index 00000000000..263e29478c4 --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/state.rs @@ -0,0 +1,603 @@ +//! Scoped state for the `ask_user` TUI form. +//! +//! All form state lives in a `thread_local!`; no `App` field is added. The +//! state is scoped to one remote-loop instance, one connection generation and +//! one session. Render, keys and paste all consult +//! [`ViewContext`](super::ViewContext) before touching it. + +use std::cell::RefCell; +use std::collections::{BTreeSet, HashMap}; + +use serde_json::json; +use serde_json::{Map, Value}; + +use crate::protocol::elicitation::{FormElicitation, FormSchema}; + +use super::schema; + +/// Schema tag shared by the tool and the TUI. Deliberately a private constant +/// in this crate; `jcode-protocol` does not know about it. +pub(crate) const TAG: &str = "jcode.dev/askUser"; + +/// Maximum number of Unicode code points accepted by one text editor. +pub(super) const MAX_TEXT_CODE_POINTS: usize = 8192; + +/// One selectable option from a tagged question. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Choice { + pub value: String, + pub label: String, + pub description: Option, + pub preview: Option, +} + +/// The automatically added "Other" free-text choice. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct OtherField { + /// The schema `const` for the Other choice (`__other__`). + pub value: String, + /// The sibling string field that carries the typed text. + pub field: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum EditorKind { + Other, + Notes, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct EditorFocus { + pub question: usize, + pub kind: EditorKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum SubmitState { + /// Normal editing. + Idle, + /// A response has been handed to the transport. + Submitting, + /// The server rejected the response; editing resumes with this message. + Rejected(String), +} + +/// Per-question answer and cursor state. +#[derive(Debug, Clone)] +pub(super) struct Question { + pub field: String, + pub header: String, + pub text: String, + pub multi: bool, + pub options: Vec, + pub other: Option, + pub notes_field: Option, + /// Highlighted row. This is *not* a confirmed selection. + pub highlight: usize, + /// Confirmed single-select value. + pub confirmed: Option, + /// Confirmed multi-select values. + pub selected: BTreeSet, + pub other_text: String, + pub notes: String, + pub other_cursor: usize, + pub notes_cursor: usize, +} + +impl Question { + pub(super) fn new( + field: String, + header: String, + text: String, + multi: bool, + options: Vec, + other: Option, + notes_field: Option, + ) -> Self { + Self { + field, + header, + text, + multi, + options, + other, + notes_field, + highlight: 0, + confirmed: None, + selected: BTreeSet::new(), + other_text: String::new(), + notes: String::new(), + other_cursor: 0, + notes_cursor: 0, + } + } + + /// Rows include the selectable options and, when present, the Other line. + pub(super) fn rows(&self) -> usize { + self.options.len() + usize::from(self.other.is_some()) + } + + pub(super) fn other_row(&self) -> Option { + self.other.as_ref().map(|_| self.options.len()) + } + + pub(super) fn highlight_is_other(&self) -> bool { + self.other_row() == Some(self.highlight) + } + + pub(super) fn other_value(&self) -> &str { + self.other + .as_ref() + .map(|other| other.value.as_str()) + .unwrap_or("__other__") + } + + pub(super) fn value_is_other(&self, value: &str) -> bool { + self.other.is_some() && value == self.other_value() + } + + pub(super) fn other_selected(&self) -> bool { + if self.multi { + self.selected.iter().any(|value| self.value_is_other(value)) + } else { + self.confirmed + .as_deref() + .is_some_and(|value| self.value_is_other(value)) + } + } + + pub(super) fn answered(&self) -> bool { + if self.multi { + let normal = self + .selected + .iter() + .any(|value| !self.value_is_other(value)); + normal || (self.other_selected() && !self.other_text.trim().is_empty()) + } else { + match self.confirmed.as_deref() { + None => false, + Some(value) if self.value_is_other(value) => !self.other_text.trim().is_empty(), + Some(_) => true, + } + } + } + + pub(super) fn selected_values(&self) -> Vec { + // A selected Other row with no text is not an answer; never emit it as + // one, or the tool has to render its "Other (no text given)" row. + let other_empty = self.other_text.trim().is_empty(); + self.selected + .iter() + .filter(|value| !(other_empty && self.value_is_other(value))) + .cloned() + .collect() + } + + pub(super) fn label_for(&self, value: &str) -> String { + self.options + .iter() + .find(|choice| choice.value == value) + .map(|choice| choice.label.clone()) + .unwrap_or_else(|| value.to_string()) + } + + /// Human-readable answer for the summary tab. + pub(super) fn answer_text(&self) -> String { + let mut answer = if self.multi { + let mut labels: Vec = self + .selected + .iter() + .filter(|value| !self.value_is_other(value)) + .map(|value| self.label_for(value)) + .collect(); + if self.other_selected() && !self.other_text.trim().is_empty() { + labels.push(other_answer_text(self)); + } + labels.join(", ") + } else if let Some(value) = self.confirmed.as_deref() { + if self.value_is_other(value) { + other_answer_text(self) + } else { + self.label_for(value) + } + } else { + String::new() + }; + if answer.trim().is_empty() { + return "not answered".to_string(); + } + if !self.notes.trim().is_empty() { + answer.push_str(" ยท notes: "); + answer.push_str(self.notes.trim()); + } + answer + } + + pub(super) fn preview_for_highlight(&self) -> Option<&str> { + self.options + .get(self.highlight) + .and_then(|choice| choice.preview.as_deref()) + } +} + +fn other_answer_text(question: &Question) -> String { + let text = question.other_text.trim(); + if text.is_empty() { + "Other".to_string() + } else { + text.to_string() + } +} + +/// One queued form. Replay restores this object when the schema is identical. +#[derive(Debug, Clone)] +pub(super) struct Form { + pub session: String, + pub elicitation_id: String, + pub message: String, + pub schema: FormSchema, + pub questions: Vec, + /// `0..questions.len()` are question tabs; `questions.len()` is Submit. + pub tab: usize, + /// Selected row on the Submit summary tab, `0..=questions.len()`. + pub summary_index: usize, + pub editor: Option, + pub preview_focus: bool, + pub submit: SubmitState, + pub notice: Option, + /// Generation in which this form was last received. `None` means it is + /// awaiting replay after a connection replacement. + pub seen_generation: Option, + pub body_scroll: usize, + pub preview_scroll: usize, + pub last_body_height: usize, + pub last_body_lines: usize, + pub last_preview_lines: usize, + pub reveal_highlight: bool, +} + +impl Form { + pub(super) fn new(request: &FormElicitation, generation: u64) -> Option { + let questions = schema::parse_questions(&request.requested_schema.0)?; + let first_unanswered = questions + .iter() + .position(|question| !question.answered()) + .unwrap_or(questions.len()); + let tab = first_unanswered; + let summary_index = if tab == questions.len() { + questions.len() + } else { + tab + }; + Some(Self { + session: request.session_id.clone(), + elicitation_id: request.elicitation_id.clone(), + message: request.message.clone(), + schema: request.requested_schema.clone(), + questions, + tab, + summary_index, + editor: None, + preview_focus: false, + submit: SubmitState::Idle, + notice: None, + seen_generation: Some(generation), + body_scroll: 0, + preview_scroll: 0, + last_body_height: 0, + last_body_lines: 0, + last_preview_lines: 0, + reveal_highlight: false, + }) + } + + pub(super) fn question_count(&self) -> usize { + self.questions.len() + } + + pub(super) fn submit_tab(&self) -> usize { + self.questions.len() + } + + pub(super) fn all_answered(&self) -> bool { + self.questions.iter().all(Question::answered) + } + + pub(super) fn first_unanswered(&self) -> Option { + self.questions + .iter() + .position(|question| !question.answered()) + } + + pub(super) fn is_submit_tab(&self) -> bool { + self.tab == self.submit_tab() + } + + pub(super) fn current_question(&self) -> Option<&Question> { + self.questions.get(self.tab) + } + + pub(super) fn current_question_mut(&mut self) -> Option<&mut Question> { + self.questions.get_mut(self.tab) + } + + /// Enter the Submit tab, focusing the summary entry the plan asks for. + #[cfg_attr(not(test), allow(dead_code))] + pub(super) fn focus_submit_tab(&mut self) { + self.tab = self.submit_tab(); + self.editor = None; + self.preview_focus = false; + self.summary_index = if self.all_answered() { + self.submit_tab() + } else { + self.first_unanswered().unwrap_or(0) + }; + } + + /// Move forward/back through question and Submit tabs. Answers are + /// untouched. Movement clamps at the first and last tab. + pub(super) fn move_tab(&mut self, forward: bool) { + let last = self.submit_tab(); + self.tab = if forward { + (self.tab + 1).min(last) + } else { + self.tab.saturating_sub(1) + }; + self.editor = None; + self.preview_focus = false; + if self.is_submit_tab() { + self.summary_index = if self.all_answered() { + self.submit_tab() + } else { + self.first_unanswered().unwrap_or(0) + }; + } + } + + pub(super) fn mark_submitting(&mut self) { + self.submit = SubmitState::Submitting; + self.editor = None; + self.notice = None; + } + + pub(super) fn restore_editing_after_rejection(&mut self, message: String) { + self.submit = SubmitState::Rejected(message.clone()); + self.editor = None; + self.notice = Some(message); + } + + /// Build the ACP content map, or explain why the form cannot be submitted. + pub(super) fn content(&self) -> Result, String> { + let mut content = Map::new(); + for (index, question) in self.questions.iter().enumerate() { + if !question.answered() { + return Err(format!("question {} still needs an answer", index + 1)); + } + let value = if question.multi { + json!(question.selected_values()) + } else { + let Some(confirmed) = question.confirmed.clone() else { + return Err(format!("question {} has no confirmed answer", index + 1)); + }; + Value::String(confirmed) + }; + content.insert(question.field.clone(), value); + if question.other_selected() + && !question.other_text.trim().is_empty() + && let Some(other) = &question.other + { + content.insert( + other.field.clone(), + Value::String(question.other_text.clone()), + ); + } + if let Some(notes_field) = &question.notes_field + && !question.notes.trim().is_empty() + { + content.insert(notes_field.clone(), Value::String(question.notes.clone())); + } + } + Ok(content) + } + + /// Local content validation, so a server rejection should only mean the + /// form no longer belongs to this attachment. + pub(super) fn checked_content(&self) -> Result, String> { + let content = self.content()?; + self.schema + .check_content(&content) + .map(|()| content) + .map_err(|error| format!("cannot submit: {error}")) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct ResponseOwner { + pub session: String, + pub elicitation_id: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct SendTarget { + pub session: String, + pub elicitation_id: String, +} + +/// All state in this module. Reset on remote-loop entry/exit and scoped to the +/// session and connection generation recorded here. +#[derive(Debug, Default)] +pub(super) struct State { + pub loop_live: bool, + pub generation: u64, + pub attached: bool, + pub session: Option, + pub forms: Vec
, + pub active: usize, + pub responses: HashMap, + /// The form handed to the transport by the most recent `Send`. + pub last_sent: Option, +} + +impl State { + pub(super) fn reset(&mut self) { + *self = Self::default(); + } + + #[cfg_attr(not(test), allow(dead_code))] + pub(super) fn active_form(&self) -> Option<&Form> { + self.forms.get(self.active) + } + + #[cfg_attr(not(test), allow(dead_code))] + pub(super) fn active_form_mut(&mut self) -> Option<&mut Form> { + let active = self.active; + self.forms.get_mut(active) + } + + pub(super) fn find_form(&self, session: &str, elicitation_id: &str) -> Option { + self.forms + .iter() + .position(|form| form.session == session && form.elicitation_id == elicitation_id) + } + + pub(super) fn remove_form(&mut self, session: &str, elicitation_id: &str) -> Option { + let index = self.find_form(session, elicitation_id)?; + let form = self.forms.remove(index); + if self.active >= self.forms.len() { + self.active = self.forms.len().saturating_sub(1); + } + Some(form) + } + + /// Drop every form that was not replayed in the current generation. + pub(super) fn discard_unreplayed(&mut self) -> usize { + let generation = self.generation; + let before = self.forms.len(); + self.forms + .retain(|form| form.seen_generation == Some(generation)); + if self.active >= self.forms.len() { + self.active = self.forms.len().saturating_sub(1); + } + before - self.forms.len() + } + + /// Clear every form and response ownership while keeping the lifecycle + /// scope (loop/generation/session). + pub(super) fn clear_forms(&mut self) { + self.forms.clear(); + self.active = 0; + self.responses.clear(); + self.last_sent = None; + } +} + +thread_local! { + static STATE: RefCell = RefCell::new(State::default()); +} + +pub(super) fn with(f: impl FnOnce(&mut State) -> R) -> R { + STATE.with(|state| f(&mut state.borrow_mut())) +} + +#[cfg(test)] +pub(crate) fn reset_for_test() { + STATE.with(|state| *state.borrow_mut() = State::default()); +} + +#[cfg(test)] +pub(super) fn snapshot(f: impl FnOnce(&State) -> R) -> R { + STATE.with(|state| f(&state.borrow())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::elicitation::{ElicitationResponse, FormSchema}; + use serde_json::json; + + fn schema() -> FormSchema { + FormSchema(json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "required": ["q1", "q2"], + "properties": { + "q1": { + "type": "string", + "title": "Pick", + "description": "Which?", + "_meta": {"jcode.dev/askUser": {"header": "Pick", "otherField": "q1_other"}}, + "oneOf": [ + {"const": "a", "title": "A"}, + {"const": "__other__", "title": "Other"} + ] + }, + "q1_other": {"type": "string"}, + "q2": { + "type": "array", + "title": "Many", + "items": {"anyOf": [{"const": "x", "title": "X"}, {"const": "y", "title": "Y"}]} + } + } + })) + } + + fn request() -> FormElicitation { + FormElicitation { + elicitation_id: "e".into(), + session_id: "s".into(), + tool_call_id: None, + message: "Questions".into(), + requested_schema: schema(), + } + } + + #[test] + fn form_starts_unanswered_with_first_question_focused() { + let form = Form::new(&request(), 1).expect("form"); + assert_eq!(form.tab, 0); + assert!(!form.questions[0].answered()); + assert_eq!(form.questions[0].highlight, 0); + assert!(form.questions[0].confirmed.is_none()); + assert!(form.questions[0].selected.is_empty()); + } + + #[test] + fn empty_other_is_unanswered_but_typed_other_answers() { + let mut form = Form::new(&request(), 1).expect("form"); + let question = &mut form.questions[0]; + question.confirmed = Some("__other__".into()); + assert!(!question.answered()); + question.other_text = " typed ".into(); + assert!(question.answered()); + } + + #[test] + fn content_only_includes_other_while_other_is_selected() { + let mut form = Form::new(&request(), 1).expect("form"); + form.questions[0].confirmed = Some("a".into()); + form.questions[0].other_text = "ignored".into(); + form.questions[1].selected.insert("x".into()); + let map = form.content().expect("content"); + assert_eq!(map.get("q1"), Some(&json!("a"))); + assert!(map.get("q1_other").is_none()); + assert_eq!(map.get("q2"), Some(&json!(["x"]))); + assert!(form.checked_content().is_ok()); + } + + #[test] + fn rejection_restores_editing_with_message() { + let mut form = Form::new(&request(), 1).expect("form"); + form.mark_submitting(); + assert_eq!(form.submit, SubmitState::Submitting); + form.restore_editing_after_rejection("nope".into()); + assert!(matches!(form.submit, SubmitState::Rejected(_))); + assert_eq!(form.notice.as_deref(), Some("nope")); + } + + #[test] + fn response_variants_are_constructible() { + // Keeps the exported response shape honest in this module's tests. + let accept = ElicitationResponse::Accept { content: None }; + assert!(!matches!(accept, ElicitationResponse::Decline)); + } +} diff --git a/crates/jcode-tui/src/tui/ask_form/tests/app.rs b/crates/jcode-tui/src/tui/ask_form/tests/app.rs new file mode 100644 index 00000000000..b9bae71c96e --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/tests/app.rs @@ -0,0 +1,187 @@ +//! Wrapper-level tests for the exported `ask_form` functions. +//! +//! These exercise the exact signatures lane C calls, using a real `App` built +//! by the test harness. Most behaviour is covered through the internal core in +//! `tests/mod.rs`; here we only prove the plumbing and session gating. + +use std::sync::Arc; + +use super::*; +use crate::protocol::ServerEvent; +use crate::provider::Provider; +use crate::tui::TuiState; +use crate::tui::app::App; +use crate::tui::ask_form::{ + KeyOutcome, handle_key, handle_paste, on_connection_replaced, on_event, on_remote_loop_exit, + on_remote_loop_start, on_replay_complete, record_response_id, send_failed, +}; +use anyhow::Result; + +struct MockProvider; + +#[async_trait::async_trait] +impl Provider for MockProvider { + async fn complete( + &self, + _messages: &[crate::message::Message], + _tools: &[crate::message::ToolDefinition], + _system: &str, + _resume_session_id: Option<&str>, + ) -> Result { + Err(anyhow::anyhow!("mock provider")) + } + + fn name(&self) -> &str { + "mock" + } + + fn fork(&self) -> Arc { + Arc::new(Self) + } +} + +fn ensure_test_jcode_home() { + use std::sync::OnceLock; + static TEST_HOME: OnceLock = OnceLock::new(); + if std::env::var_os("JCODE_HOME").is_some() { + return; + } + let path = TEST_HOME.get_or_init(|| { + let path = std::env::temp_dir().join(format!("jcode-ask-form-test-{}", std::process::id())); + let _ = std::fs::create_dir_all(&path); + path + }); + crate::env::set_var("JCODE_HOME", path); +} + +fn test_app() -> App { + ensure_test_jcode_home(); + let provider: Arc = Arc::new(MockProvider); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .expect("runtime"); + let registry = runtime.block_on(crate::tool::Registry::new(provider.clone())); + let mut app = App::new_for_test_harness(provider, registry); + // Keep the onboarding welcome from outranking the form on hosts with no + // stored credentials. + app.push_display_message(crate::tui::DisplayMessage::system("test")); + app +} + +fn session_of(app: &App) -> String { + app.current_session_id().expect("test session") +} + +#[test] +fn public_key_and_event_plumbing_sends_and_records_the_request_id() { + reset(); + let mut app = test_app(); + let session = session_of(&app); + on_remote_loop_start(&mut app); + + let request = form("e1", &session, single_schema()); + let event = ServerEvent::ElicitationRequest(request); + assert!(on_event(&mut app, &event)); + assert_eq!(form_count(), 1); + + // Digit confirms, Enter advances to Submit, Enter sends. + assert_eq!( + handle_key(&mut app, KeyCode::Char('1'), KeyModifiers::NONE, None), + KeyOutcome::Consumed + ); + assert_eq!( + handle_key(&mut app, KeyCode::Enter, KeyModifiers::NONE, None), + KeyOutcome::Consumed + ); + match handle_key(&mut app, KeyCode::Enter, KeyModifiers::NONE, None) { + KeyOutcome::Send { + session_id, + elicitation_id, + response, + } => { + assert_eq!(session_id, session); + assert_eq!(elicitation_id, "e1"); + assert!(matches!( + response, + crate::protocol::elicitation::ElicitationResponse::Accept { .. } + )); + } + other => panic!("expected send, got {other:?}"), + } + + record_response_id(&mut app, 77); + assert_eq!(response_ids(), vec![77]); + assert!(on_event(&mut app, &ServerEvent::Done { id: 77 })); + assert!(response_ids().is_empty()); +} + +#[test] +fn public_paste_render_and_reconnect_hooks() { + reset(); + let mut app = test_app(); + let session = session_of(&app); + on_remote_loop_start(&mut app); + assert!(on_event( + &mut app, + &ServerEvent::ElicitationRequest(form("e1", &session, schema_json())) + )); + + // Open notes and paste into the focused editor. + assert_eq!( + handle_key(&mut app, KeyCode::Char('n'), KeyModifiers::NONE, None), + KeyOutcome::Consumed + ); + assert!(handle_paste(&mut app, "note text")); + active(|form| assert_eq!(form.questions[0].notes, "note text")); + + // Render the real App through the exported `render` signature. + use ratatui::Terminal; + use ratatui::backend::TestBackend; + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal + .draw(|frame| crate::tui::ask_form::render(frame, &app)) + .expect("render"); + let buffer = terminal.backend().buffer().clone(); + assert!(first_nonblank_row(&buffer).is_some()); + + // Freeze, replay and complete. + on_connection_replaced(&mut app); + assert!(on_event( + &mut app, + &ServerEvent::ElicitationRequest(form("e1", &session, schema_json())) + )); + on_replay_complete(&mut app, &session); + assert_eq!(form_count(), 1); + + on_remote_loop_exit(); + assert_eq!(form_count(), 0); +} + +#[test] +fn public_send_failure_restores_editing() { + reset(); + let mut app = test_app(); + let session = session_of(&app); + on_remote_loop_start(&mut app); + assert!(on_event( + &mut app, + &ServerEvent::ElicitationRequest(form("e1", &session, single_schema())) + )); + assert_eq!( + handle_key(&mut app, KeyCode::Char('1'), KeyModifiers::NONE, None), + KeyOutcome::Consumed + ); + assert_eq!( + handle_key(&mut app, KeyCode::Enter, KeyModifiers::NONE, None), + KeyOutcome::Consumed + ); + assert!(matches!( + handle_key(&mut app, KeyCode::Enter, KeyModifiers::NONE, None), + KeyOutcome::Send { .. } + )); + send_failed(&mut app, "offline"); + active(|form| assert!(matches!(form.submit, SubmitState::Rejected(_)))); +} diff --git a/crates/jcode-tui/src/tui/ask_form/tests/keys.rs b/crates/jcode-tui/src/tui/ask_form/tests/keys.rs new file mode 100644 index 00000000000..ef97c20eb99 --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/tests/keys.rs @@ -0,0 +1,179 @@ +//! Editor, grapheme and paste tests for the `ask_user` form. + +use ratatui::crossterm::event::{KeyCode, KeyModifiers}; + +use super::*; +use crate::tui::ask_form::state::{EditorKind, MAX_TEXT_CODE_POINTS}; + +#[test] +fn editor_captures_shortcut_letters_as_text() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + for character in ['n', 'p', '1', ' '] { + assert_eq!( + key_with( + &context, + KeyCode::Char(character), + KeyModifiers::NONE, + Some(&character.to_string()) + ), + KeyOutcome::Consumed + ); + } + active(|form| { + assert_eq!(form.questions[0].notes, "np1 "); + assert_eq!( + form.editor.map(|editor| editor.kind), + Some(EditorKind::Notes) + ); + }); +} + +#[test] +fn text_input_is_preferred_over_the_key_code() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + key_with(&context, KeyCode::Char('x'), KeyModifiers::NONE, Some("รฉ")); + active(|form| assert_eq!(form.questions[0].notes, "รฉ")); +} + +#[test] +fn grapheme_edits_move_and_delete_whole_graphemes() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + + // Combined grapheme: e + combining acute. + key_with( + &context, + KeyCode::Char('e'), + KeyModifiers::NONE, + Some("e\u{301}"), + ); + // Emoji ZWJ sequence typed as one paste. + let family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ"; + assert!(paste_text(&context, family)); + active(|form| assert_eq!(form.questions[0].notes, format!("e\u{301}{family}"))); + + // Left moves over the whole family, right back to the end. + key(&context, KeyCode::Left); + active(|form| { + assert_eq!(form.questions[0].notes_cursor, "e\u{301}".len()); + }); + key(&context, KeyCode::Right); + active(|form| { + assert_eq!( + form.questions[0].notes_cursor, + format!("e\u{301}{family}").len() + ); + }); + + // Backspace removes the family in one edit. + key(&context, KeyCode::Backspace); + active(|form| assert_eq!(form.questions[0].notes, "e\u{301}")); + + // Backspace removes the combined grapheme in one edit. + key(&context, KeyCode::Backspace); + active(|form| { + assert!(form.questions[0].notes.is_empty()); + assert_eq!(form.questions[0].notes_cursor, 0); + }); +} + +#[test] +fn home_and_end_move_to_line_boundaries() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + assert!(paste_text(&context, "ab\ncd")); + // Cursor is at the end (byte 5). + key(&context, KeyCode::Home); + active(|form| assert_eq!(form.questions[0].notes_cursor, 3)); + key(&context, KeyCode::End); + active(|form| assert_eq!(form.questions[0].notes_cursor, 5)); + key(&context, KeyCode::Home); + key(&context, KeyCode::Backspace); + active(|form| assert_eq!(form.questions[0].notes, "abcd")); +} + +#[test] +fn paste_into_editor_preserves_newlines() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + assert!(paste_text(&context, "line 1\nline 2")); + active(|form| { + assert_eq!(form.questions[0].notes, "line 1\nline 2"); + assert_eq!(form.questions[0].notes_cursor, "line 1\nline 2".len()); + }); +} + +#[test] +fn paste_opens_the_selected_other_editor() { + reset(); + let context = install_default(); + // Highlight Other (third row; q1 has two normal options). + key(&context, KeyCode::Down); + key(&context, KeyCode::Down); + assert!(paste_text(&context, "typed answer")); + active(|form| { + assert_eq!(form.questions[0].confirmed.as_deref(), Some("__other__")); + assert_eq!(form.questions[0].other_text, "typed answer"); + assert_eq!( + form.editor, + Some(crate::tui::ask_form::state::EditorFocus { + question: 0, + kind: EditorKind::Other + }) + ); + }); +} + +#[test] +fn paste_without_a_text_target_returns_false_and_explains_where_it_went() { + reset(); + let context = install_default(); + // Highlight a normal option: no editor, no Other selection. + assert!(!paste_text(&context, "composer text")); + active(|form| { + assert!(form.questions[0].other_text.is_empty()); + assert!( + form.notice + .as_deref() + .is_some_and(|notice| notice.contains("composer")) + ); + }); +} + +#[test] +fn over_limit_paste_is_rejected_and_preserves_the_draft() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + assert!(paste_text(&context, "keep")); + let oversized = "x".repeat(MAX_TEXT_CODE_POINTS); + // Consumed (the form must not hand it to the composer) but rejected. + assert!(paste_text(&context, &oversized)); + active(|form| { + assert_eq!(form.questions[0].notes, "keep"); + assert!( + form.notice + .as_deref() + .is_some_and(|notice| notice.contains("Text limit")) + ); + }); +} + +#[test] +fn hidden_editor_cannot_take_paste() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + assert!(paste_text(&context, "visible")); + + let blocked = ViewContext::from_probe(&blocked_probe("session")); + assert!(!paste_text(&blocked, "hidden")); + active(|form| assert_eq!(form.questions[0].notes, "visible")); +} diff --git a/crates/jcode-tui/src/tui/ask_form/tests/mod.rs b/crates/jcode-tui/src/tui/ask_form/tests/mod.rs new file mode 100644 index 00000000000..2eb29e6f200 --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/tests/mod.rs @@ -0,0 +1,1061 @@ +//! Tests for the `ask_user` form module. +//! +//! Every test resets the thread-local state first. Rust's test harness runs +//! each test on its own thread, so `thread_local!` state is naturally isolated, +//! but the reset also keeps tests independent when run in a shared thread. + +mod app; +mod keys; +mod render; + +use ratatui::buffer::Buffer; +use ratatui::crossterm::event::{KeyCode, KeyModifiers}; +use ratatui::text::Line; +use serde_json::{Value, json}; +use unicode_width::UnicodeWidthStr; + +use super::keys as form_keys; +use super::render as form_render; +use super::state::{self, EditorKind, Form, MAX_TEXT_CODE_POINTS, SubmitState}; +use super::{FocusProbe, KeyOutcome, ViewContext, paste, reconcile}; +use crate::protocol::ServerEvent; +use crate::protocol::elicitation::{ElicitationResolution, FormElicitation, FormSchema}; + +pub(super) const SESSION: &str = "session-a"; + +pub(super) fn reset() { + super::reset_for_test(); +} + +pub(super) fn schema_json() -> Value { + json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "required": ["q1", "q2"], + "properties": { + "q1": { + "type": "string", + "title": "Pick", + "description": "Which option do you want?", + "_meta": {"jcode.dev/askUser": { + "header": "Pick", + "otherField": "q1_other", + "notesField": "q1_notes" + }}, + "oneOf": [ + {"const": "a", "title": "Alpha", "description": "First option", "_meta": {"preview": "Alpha preview\nline two"}}, + {"const": "b", "title": "Beta", "description": "Second option"}, + {"const": "__other__", "title": "Other"} + ] + }, + "q1_other": {"type": "string", "maxLength": 8192}, + "q1_notes": {"type": "string", "maxLength": 8192}, + "q2": { + "type": "array", + "title": "Many", + "description": "Pick several.", + "_meta": {"jcode.dev/askUser": { + "header": "Many", + "notesField": "q2_notes" + }}, + "items": {"anyOf": [ + {"const": "x", "title": "Xray", "description": "Ex"}, + {"const": "y", "title": "Yankee"} + ]} + }, + "q2_notes": {"type": "string", "maxLength": 8192} + } + }) +} + +pub(super) fn single_schema() -> Value { + json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "required": ["q1"], + "properties": { + "q1": { + "type": "string", + "title": "Pick", + "description": "Which one?", + "_meta": {"jcode.dev/askUser": {"header": "Pick", "otherField": "q1_other"}}, + "oneOf": [ + {"const": "a", "title": "Alpha"}, + {"const": "b", "title": "Beta"}, + {"const": "__other__", "title": "Other"} + ] + }, + "q1_other": {"type": "string"} + } + }) +} + +pub(super) fn multi_other_schema() -> Value { + json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "required": ["q1"], + "properties": { + "q1": { + "type": "array", + "title": "Many", + "description": "Pick as many as you like.", + "_meta": {"jcode.dev/askUser": { + "header": "Many", + "otherField": "q1_other" + }}, + "items": {"anyOf": [ + {"const": "a", "title": "Alpha"}, + {"const": "b", "title": "Beta"} + ]} + }, + "q1_other": {"type": "string"} + } + }) +} + +pub(super) fn form(id: &str, session: &str, schema: Value) -> FormElicitation { + FormElicitation { + elicitation_id: id.to_string(), + session_id: session.to_string(), + tool_call_id: None, + message: "The agent has questions.".to_string(), + requested_schema: FormSchema(schema), + } +} + +pub(super) fn context(session: &str) -> ViewContext { + ViewContext { + session: Some(session.to_string()), + replay: false, + blocked: None, + } +} + +pub(super) fn install(session: &str, form: FormElicitation) -> ViewContext { + let context = context(session); + state::with(|state| { + state.loop_live = true; + state.generation = 1; + state.attached = true; + state.session = Some(session.to_string()); + let event = ServerEvent::ElicitationRequest(form); + let result = reconcile::handle_event(state, &context, &event); + assert!(result.consumed, "request should be consumed"); + }); + context +} + +pub(super) fn install_default() -> ViewContext { + install(SESSION, form("e1", SESSION, schema_json())) +} + +pub(super) fn key_with( + context: &ViewContext, + code: KeyCode, + modifiers: KeyModifiers, + text: Option<&str>, +) -> KeyOutcome { + state::with(|state| form_keys::handle_key(state, context, code, modifiers, text).outcome) +} + +pub(super) fn key(context: &ViewContext, code: KeyCode) -> KeyOutcome { + key_with(context, code, KeyModifiers::NONE, None) +} + +pub(super) fn paste_text(context: &ViewContext, text: &str) -> bool { + state::with(|state| { + let result = paste::handle_paste(state, context, text); + if let Some(notice) = result.notice + && let Some(form) = state.active_form_mut() + { + form.notice = Some(notice); + } + result.consumed + }) +} + +pub(super) fn send_event(context: &ViewContext, event: &ServerEvent) -> (bool, Option) { + state::with(|state| { + let result = reconcile::handle_event(state, context, event); + (result.consumed, result.notice) + }) +} + +pub(super) fn active(f: impl FnOnce(&Form) -> R) -> R { + state::snapshot(|state| f(state.active_form().expect("active form"))) +} + +pub(super) fn active_mut(f: impl FnOnce(&mut Form) -> R) -> R { + state::with(|state| f(state.active_form_mut().expect("active form"))) +} + +pub(super) fn form_count() -> usize { + state::snapshot(|state| state.forms.len()) +} + +pub(super) fn response_ids() -> Vec { + state::snapshot(|state| state.responses.keys().copied().collect()) +} + +pub(super) fn answer_all(context: &ViewContext) { + // q1 single: choose Alpha; Enter advances. + assert_eq!(key(context, KeyCode::Char('1')), KeyOutcome::Consumed); + assert_eq!(key(context, KeyCode::Enter), KeyOutcome::Consumed); + // q2 multi: choose Xray and Yankee; Enter advances to Submit. + assert_eq!(key(context, KeyCode::Char('1')), KeyOutcome::Consumed); + assert_eq!(key(context, KeyCode::Char('2')), KeyOutcome::Consumed); + assert_eq!(key(context, KeyCode::Enter), KeyOutcome::Consumed); +} + +pub(super) fn line_width(line: &Line<'_>) -> usize { + line.spans + .iter() + .map(|span| UnicodeWidthStr::width(span.content.as_ref())) + .sum() +} + +pub(super) fn row_text(buffer: &Buffer, row: u16) -> String { + if row >= buffer.area.height { + return String::new(); + } + let mut text = String::new(); + for x in 0..buffer.area.width { + if let Some(cell) = buffer.cell((x, row)) { + text.push_str(cell.symbol()); + } + } + text.trim_end().to_string() +} + +pub(super) fn first_nonblank_row(buffer: &Buffer) -> Option { + (0..buffer.area.height).find(|row| !row_text(buffer, *row).is_empty()) +} + +// --------------------------------------------------------------------------- +// Key sequences and selection semantics +// --------------------------------------------------------------------------- + +#[test] +fn key_sequences_navigate_confirm_and_preserve_answers() { + reset(); + let context = install_default(); + + // Initial highlight is not a selection. + active(|form| { + assert_eq!(form.tab, 0); + assert_eq!(form.questions[0].highlight, 0); + assert!(form.questions[0].confirmed.is_none()); + }); + + // Down moves the highlight without confirming. + key(&context, KeyCode::Down); + active(|form| { + assert_eq!(form.questions[0].highlight, 1); + assert!(form.questions[0].confirmed.is_none()); + }); + + // Space confirms the highlighted choice. + key(&context, KeyCode::Char(' ')); + active(|form| assert_eq!(form.questions[0].confirmed.as_deref(), Some("b"))); + + // Right advances to the next tab without changing the answer. + key(&context, KeyCode::Right); + active(|form| assert_eq!(form.tab, 1)); + key(&context, KeyCode::Left); + active(|form| { + assert_eq!(form.tab, 0); + assert_eq!(form.questions[0].confirmed.as_deref(), Some("b")); + assert_eq!(form.questions[0].highlight, 1); + }); + + // Out-of-range digits do nothing. + key(&context, KeyCode::Char('9')); + active(|form| assert_eq!(form.questions[0].confirmed.as_deref(), Some("b"))); +} + +#[test] +fn multi_select_enter_advances_without_changing_selection() { + reset(); + let context = install_default(); + key(&context, KeyCode::Right); + active(|form| assert_eq!(form.tab, 1)); + + key(&context, KeyCode::Char('1')); + key(&context, KeyCode::Char('2')); + active(|form| { + let selected = &form.questions[1].selected; + assert!(selected.contains("x")); + assert!(selected.contains("y")); + }); + + // Space toggles the highlighted row. + key(&context, KeyCode::Up); + key(&context, KeyCode::Char(' ')); + active(|form| assert!(!form.questions[1].selected.contains("x"))); + + // Enter advances without changing the selection. + key(&context, KeyCode::Enter); + active(|form| { + assert!(form.is_submit_tab()); + assert!(!form.questions[1].selected.contains("x")); + assert!(form.questions[1].selected.contains("y")); + }); +} + +#[test] +fn multi_select_enter_on_the_other_row_only_advances() { + reset(); + let context = install(SESSION, form("e1", SESSION, multi_other_schema())); + + // The Other row is the third row in a two-option multi-select. + key(&context, KeyCode::Down); + key(&context, KeyCode::Down); + active(|form| assert_eq!(form.questions[0].highlight, 2)); + + key(&context, KeyCode::Enter); + active(|form| { + assert!(form.is_submit_tab()); + assert!(form.questions[0].selected.is_empty()); + assert!(form.editor.is_none()); + }); +} + +#[test] +fn multi_select_other_without_text_is_not_sent_as_an_answer() { + reset(); + let context = install(SESSION, form("e1", SESSION, multi_other_schema())); + + key(&context, KeyCode::Char('1')); + key(&context, KeyCode::Char('3')); + key(&context, KeyCode::Esc); + active(|form| { + let question = &form.questions[0]; + assert!(question.other_selected()); + assert!(question.other_text.trim().is_empty()); + assert!(question.answered()); + assert_eq!(question.answer_text(), "Alpha"); + let content = form.content().expect("Alpha answers the question"); + assert_eq!(content.get("q1"), Some(&json!(["a"]))); + assert!(!content.contains_key("q1_other")); + }); +} + +#[test] +fn shift_tab_and_revisit_preserve_editor_answers() { + reset(); + let context = install_default(); + + // Answer q1, move to q2, then Shift+Tab back. + key(&context, KeyCode::Char('1')); + key(&context, KeyCode::Enter); + key_with(&context, KeyCode::BackTab, KeyModifiers::SHIFT, None); + active(|form| { + assert_eq!(form.tab, 0); + assert_eq!(form.questions[0].confirmed.as_deref(), Some("a")); + }); + + // Revisit q2: the multi selection survives. + key(&context, KeyCode::Tab); + active(|form| assert_eq!(form.tab, 1)); +} + +#[test] +fn digits_select_other_and_open_its_editor() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('3')); + active(|form| { + assert_eq!(form.questions[0].confirmed.as_deref(), Some("__other__")); + assert_eq!( + form.editor, + Some(super::state::EditorFocus { + question: 0, + kind: EditorKind::Other + }) + ); + }); +} + +#[test] +fn escape_declines_only_outside_an_editor() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + active(|form| assert!(form.editor.is_some())); + + // Esc leaves the editor without declining. + assert_eq!(key(&context, KeyCode::Esc), KeyOutcome::Consumed); + active(|form| { + assert!(form.editor.is_none()); + assert_eq!(form.submit, SubmitState::Idle); + }); + + match key(&context, KeyCode::Esc) { + KeyOutcome::Send { response, .. } => { + assert!(matches!( + response, + crate::protocol::elicitation::ElicitationResponse::Decline + )); + } + other => panic!("expected decline, got {other:?}"), + } +} + +#[test] +fn submit_is_blocked_until_every_question_is_answered() { + reset(); + let context = install_default(); + // Jump to Submit without answering and focus the Submit entry. + active_mut(|form| form.focus_submit_tab()); + key(&context, KeyCode::Down); + key(&context, KeyCode::Down); + assert_eq!(key(&context, KeyCode::Enter), KeyOutcome::Consumed); + active(|form| assert_eq!(form.submit, SubmitState::Idle)); + assert!(form_count() == 1); + + // Answer q1 and q2, then submit. + active_mut(|form| form.tab = 0); + answer_all(&context); + active(|form| { + assert!(form.is_submit_tab()); + assert!(form.all_answered()); + }); + match key(&context, KeyCode::Enter) { + KeyOutcome::Send { + session_id, + elicitation_id, + response, + } => { + assert_eq!(session_id, SESSION); + assert_eq!(elicitation_id, "e1"); + match response { + crate::protocol::elicitation::ElicitationResponse::Accept { content } => { + let content = content.expect("content"); + assert_eq!(content.get("q1"), Some(&json!("a"))); + assert_eq!(content.get("q2"), Some(&json!(["x", "y"]))); + } + other => panic!("expected accept, got {other:?}"), + } + } + other => panic!("expected send, got {other:?}"), + } +} + +#[test] +fn empty_other_counts_as_unanswered_and_blocks_submit() { + reset(); + let context = install_default(); + // Select Other but type nothing. + key(&context, KeyCode::Char('3')); + // Leave the editor; q1 is still unanswered. + key(&context, KeyCode::Esc); + active_mut(|form| form.focus_submit_tab()); + key(&context, KeyCode::Down); + key(&context, KeyCode::Down); + assert_eq!(key(&context, KeyCode::Enter), KeyOutcome::Consumed); + active(|form| { + assert!(!form.questions[0].answered()); + assert_eq!(form.submit, SubmitState::Idle); + assert!(form.notice.is_some()); + }); +} + +#[test] +fn repeat_submit_is_dropped_after_send() { + reset(); + let context = install_default(); + answer_all(&context); + assert!(matches!( + key(&context, KeyCode::Enter), + KeyOutcome::Send { .. } + )); + // A second Enter while the response is outstanding must not send again. + assert_eq!(key(&context, KeyCode::Enter), KeyOutcome::Consumed); + assert_eq!(key(&context, KeyCode::Char('1')), KeyOutcome::Consumed); +} + +#[test] +fn ctrl_modified_keys_are_never_consumed() { + reset(); + let context = install_default(); + assert_eq!( + key_with(&context, KeyCode::Char('c'), KeyModifiers::CONTROL, None), + KeyOutcome::Ignored + ); + // The form editor did not receive the text. + key(&context, KeyCode::Char('n')); + assert_eq!( + key_with(&context, KeyCode::Char('c'), KeyModifiers::CONTROL, None), + KeyOutcome::Ignored + ); + active(|form| assert!(form.questions[0].notes.is_empty())); +} + +#[test] +fn notes_editor_reports_over_limit_edit_without_truncating() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + active_mut(|form| form.questions[0].notes = "x".repeat(MAX_TEXT_CODE_POINTS)); + assert_eq!( + key_with(&context, KeyCode::Char('y'), KeyModifiers::NONE, Some("y")), + KeyOutcome::Consumed + ); + active(|form| { + assert_eq!( + form.questions[0].notes.chars().count(), + MAX_TEXT_CODE_POINTS + ); + assert!( + form.notice + .as_deref() + .is_some_and(|notice| notice.contains("Text limit")) + ); + }); +} + +#[test] +fn summary_navigation_returns_to_a_question_and_submit_sends() { + reset(); + let context = install_default(); + answer_all(&context); + active(|form| { + assert!(form.is_submit_tab()); + assert_eq!(form.summary_index, form.submit_tab()); + }); + + // Up selects the last question entry; Enter returns to it. + key(&context, KeyCode::Up); + active(|form| assert_eq!(form.summary_index, 1)); + key(&context, KeyCode::Enter); + active(|form| assert_eq!(form.tab, 1)); + + // Revisit Submit and send from the Submit entry. + active_mut(|form| form.focus_submit_tab()); + assert!(matches!( + key(&context, KeyCode::Enter), + KeyOutcome::Send { .. } + )); +} + +// --------------------------------------------------------------------------- +// Events, reconnect and reconciliation +// --------------------------------------------------------------------------- + +#[test] +fn untagged_forms_are_ignored_without_a_response() { + reset(); + let context = context(SESSION); + let mut untagged = form( + "applet", + SESSION, + json!({ + "type": "object", + "properties": {"name": {"type": "string", "title": "Name"}} + }), + ); + untagged.message = "Applet".into(); + state::with(|state| { + state.loop_live = true; + state.generation = 1; + state.attached = true; + state.session = Some(SESSION.to_string()); + }); + let (consumed, _) = send_event(&context, &ServerEvent::ElicitationRequest(untagged)); + assert!(consumed); + assert_eq!(form_count(), 0); + assert!(state::snapshot(|state| state.last_sent.is_none())); +} + +#[test] +fn events_for_another_session_are_ignored() { + reset(); + install_default(); + let context = context("session-b"); + let (consumed, _) = send_event( + &context, + &ServerEvent::ElicitationRequest(form("e2", "session-c", schema_json())), + ); + assert!(!consumed); + assert_eq!(form_count(), 1); + assert_eq!( + state::snapshot(|state| state.session.clone()), + Some(SESSION.to_string()) + ); +} + +#[test] +fn history_preserves_forms_drafts_and_response_ids() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + key_with(&context, KeyCode::Char('h'), KeyModifiers::NONE, Some("h")); + key(&context, KeyCode::Esc); + answer_all(&context); + assert!(matches!( + key(&context, KeyCode::Enter), + KeyOutcome::Send { .. } + )); + state::with(|state| reconcile::record_response_id(state, 7)); + + // History is not replay completion. + let history: ServerEvent = serde_json::from_value(json!({ + "type": "history", + "id": 1, + "session_id": SESSION, + "messages": [] + })) + .expect("history event"); + let (consumed, _) = send_event(&context, &history); + assert!(!consumed); + assert_eq!(form_count(), 1); + assert_eq!(response_ids(), vec![7]); + active(|form| assert_eq!(form.questions[0].notes, "h")); +} + +#[test] +fn resolution_removes_the_form_and_late_acknowledgements_do_not_resurrect_it() { + reset(); + let context = install_default(); + answer_all(&context); + assert!(matches!( + key(&context, KeyCode::Enter), + KeyOutcome::Send { .. } + )); + state::with(|state| reconcile::record_response_id(state, 11)); + + let (consumed, notice) = send_event( + &context, + &ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Accepted, + }, + ); + assert!(consumed); + assert_eq!(notice.as_deref(), Some("Answer submitted.")); + assert_eq!(form_count(), 0); + + // Claimed but stale: consumed, nothing resurrected. + assert!( + send_event( + &context, + &ServerEvent::Error { + id: 11, + message: "late".into(), + retry_after_secs: None + } + ) + .0 + ); + assert_eq!(form_count(), 0); +} + +#[test] +fn claimed_error_reopens_a_pending_form_with_a_notice() { + reset(); + let context = install_default(); + answer_all(&context); + assert!(matches!( + key(&context, KeyCode::Enter), + KeyOutcome::Send { .. } + )); + state::with(|state| reconcile::record_response_id(state, 21)); + + let (consumed, notice) = send_event( + &context, + &ServerEvent::Error { + id: 21, + message: "nope".into(), + retry_after_secs: None, + }, + ); + assert!(consumed); + assert!( + notice + .as_deref() + .is_some_and(|notice| notice.contains("rejected")) + ); + assert_eq!(form_count(), 1); + active(|form| { + assert!(matches!(form.submit, SubmitState::Rejected(_))); + assert_eq!(form.notice.as_deref(), Some("nope")); + }); +} + +#[test] +fn claimed_done_is_consumed_and_forgets_the_response_id() { + reset(); + let context = install_default(); + answer_all(&context); + assert!(matches!( + key(&context, KeyCode::Enter), + KeyOutcome::Send { .. } + )); + state::with(|state| reconcile::record_response_id(state, 31)); + assert!(send_event(&context, &ServerEvent::Done { id: 31 }).0); + assert!(response_ids().is_empty()); + assert_eq!(form_count(), 1); +} + +#[test] +fn send_failure_keeps_the_draft_and_rejected_resolution_wins_later() { + reset(); + let context = install_default(); + answer_all(&context); + assert!(matches!( + key(&context, KeyCode::Enter), + KeyOutcome::Send { .. } + )); + let applied = state::with(|state| reconcile::send_failed(state, &context, "offline")); + assert!(applied); + active(|form| { + assert!(matches!(form.submit, SubmitState::Rejected(_))); + assert!(form.all_answered()); + }); + + // Resolution removes the form; a later failure is ignored. + assert!( + send_event( + &context, + &ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Cancelled, + } + ) + .0 + ); + assert_eq!(form_count(), 0); + assert!(!state::with(|state| reconcile::send_failed( + state, &context, "late" + ))); +} + +#[test] +fn connection_replacement_freezes_drafts_and_replay_restores_them() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + key_with(&context, KeyCode::Char('d'), KeyModifiers::NONE, Some("d")); + key(&context, KeyCode::Esc); + key(&context, KeyCode::Char('2')); + + state::with(|state| reconcile::connection_replaced(state, Some(SESSION))); + assert_eq!(form_count(), 1); + assert!(state::snapshot(|state| !state.attached)); + active(|form| assert!(form.seen_generation.is_none())); + // Hidden forms do not capture keys. + assert_eq!(key(&context, KeyCode::Enter), KeyOutcome::Ignored); + + // Identical replay restores selection, notes and tab. + let mut replayed = form("e1", SESSION, schema_json()); + replayed.message = "Again".into(); + let (consumed, _) = send_event(&context, &ServerEvent::ElicitationRequest(replayed)); + assert!(consumed); + assert_eq!(form_count(), 1); + active(|form| { + assert!(state_seen(form)); + assert_eq!(form.questions[0].notes, "d"); + assert_eq!(form.questions[0].confirmed.as_deref(), Some("b")); + }); + + let notice = state::with(|state| reconcile::on_replay_complete(state, &context, SESSION)); + assert!(notice.is_none()); + assert!(state::snapshot(|state| state.attached)); + assert_eq!(form_count(), 1); +} + +fn state_seen(form: &Form) -> bool { + form.seen_generation.is_some() +} + +#[test] +fn replay_complete_discards_unreplayed_forms() { + reset(); + let context = install_default(); + state::with(|state| { + state.forms.push( + Form::new(&form("e2", SESSION, schema_json()), state.generation).expect("second form"), + ); + }); + assert_eq!(form_count(), 2); + + state::with(|state| reconcile::connection_replaced(state, Some(SESSION))); + // Replay only the first form. + let (consumed, _) = send_event( + &context, + &ServerEvent::ElicitationRequest(form("e1", SESSION, schema_json())), + ); + assert!(consumed); + let notice = state::with(|state| reconcile::on_replay_complete(state, &context, SESSION)); + assert_eq!(form_count(), 1); + assert!( + notice + .as_deref() + .is_some_and(|notice| notice.contains("lost while reconnecting")) + ); +} + +#[test] +fn resolved_while_disconnected_removes_the_draft() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + key_with(&context, KeyCode::Char('x'), KeyModifiers::NONE, Some("x")); + state::with(|state| reconcile::connection_replaced(state, Some(SESSION))); + assert_eq!(form_count(), 1); + + let (consumed, notice) = send_event( + &context, + &ServerEvent::ElicitationResolved { + session_id: SESSION.into(), + elicitation_id: "e1".into(), + outcome: ElicitationResolution::Declined, + }, + ); + assert!(consumed); + assert_eq!(notice.as_deref(), Some("Question form declined.")); + assert_eq!(form_count(), 0); + + // Replay completion with nothing replayed keeps it gone. + state::with(|state| reconcile::on_replay_complete(state, &context, SESSION)); + assert_eq!(form_count(), 0); +} + +#[test] +fn session_change_clears_old_drafts_immediately() { + reset(); + install_default(); + state::with(|state| reconcile::connection_replaced(state, Some("session-b"))); + assert_eq!(form_count(), 0); + assert_eq!( + state::snapshot(|state| state.session.clone()), + Some("session-b".to_string()) + ); +} + +#[test] +fn replay_mode_never_answers_requests() { + reset(); + let context = ViewContext { + session: Some(SESSION.into()), + replay: true, + blocked: None, + }; + let (consumed, _) = send_event( + &context, + &ServerEvent::ElicitationRequest(form("e1", SESSION, schema_json())), + ); + assert!(!consumed); + assert_eq!(form_count(), 0); +} + +// --------------------------------------------------------------------------- +// Focus precedence +// --------------------------------------------------------------------------- + +#[derive(Default)] +struct FakeProbe { + session: Option, + replay: bool, + history: bool, + onboarding: bool, + copy_selection: bool, + commit_log: bool, + changelog: bool, + help: bool, + model_status: bool, + panel_image: bool, + session_picker: bool, + login_picker: bool, + account_picker: bool, + usage_overlay: bool, + inline_interactive: bool, + pending_login: bool, + swarm_page: bool, + side_panel: bool, + provider_failover: bool, +} + +impl FocusProbe for FakeProbe { + fn probe_session(&self) -> Option { + self.session.clone() + } + fn probe_replay(&self) -> bool { + self.replay + } + fn probe_prompt_history(&self) -> bool { + self.history + } + fn probe_onboarding(&self) -> bool { + self.onboarding + } + fn probe_copy_selection(&self) -> bool { + self.copy_selection + } + fn probe_commit_log(&self) -> bool { + self.commit_log + } + fn probe_changelog(&self) -> bool { + self.changelog + } + fn probe_help(&self) -> bool { + self.help + } + fn probe_model_status(&self) -> bool { + self.model_status + } + fn probe_panel_image(&self) -> bool { + self.panel_image + } + fn probe_session_picker(&self) -> bool { + self.session_picker + } + fn probe_login_picker(&self) -> bool { + self.login_picker + } + fn probe_account_picker(&self) -> bool { + self.account_picker + } + fn probe_usage_overlay(&self) -> bool { + self.usage_overlay + } + fn probe_inline_interactive(&self) -> bool { + self.inline_interactive + } + fn probe_pending_login(&self) -> bool { + self.pending_login + } + fn probe_swarm_page(&self) -> bool { + self.swarm_page + } + fn probe_side_panel_fullscreen(&self) -> bool { + self.side_panel + } + fn probe_provider_failover(&self) -> bool { + self.provider_failover + } +} + +fn blocked_probe(reason: &str) -> FakeProbe { + let mut probe = FakeProbe { + session: Some(SESSION.into()), + ..FakeProbe::default() + }; + match reason { + "history" => probe.history = true, + "onboarding" => probe.onboarding = true, + "copy" => probe.copy_selection = true, + "commit" => probe.commit_log = true, + "changelog" => probe.changelog = true, + "help" => probe.help = true, + "model" => probe.model_status = true, + "image" => probe.panel_image = true, + "session" => probe.session_picker = true, + "login-picker" => probe.login_picker = true, + "account" => probe.account_picker = true, + "usage" => probe.usage_overlay = true, + "inline" => probe.inline_interactive = true, + "login" => probe.pending_login = true, + "swarm" => probe.swarm_page = true, + "side" => probe.side_panel = true, + "failover" => probe.provider_failover = true, + other => panic!("unknown probe {other}"), + } + probe +} + +#[test] +fn every_higher_priority_ui_blocks_render_keys_and_paste() { + reset(); + install_default(); + for reason in [ + "history", + "onboarding", + "copy", + "commit", + "changelog", + "help", + "model", + "image", + "session", + "login-picker", + "account", + "usage", + "inline", + "login", + "swarm", + "side", + "failover", + ] { + let probe = blocked_probe(reason); + let context = ViewContext::from_probe(&probe); + assert!( + context.blocked.is_some(), + "{reason} should own focus, context {context:?}" + ); + assert_eq!( + key(&context, KeyCode::Enter), + KeyOutcome::Ignored, + "{reason}" + ); + assert!(!paste_text(&context, "hello"), "{reason}"); + } +} + +#[test] +fn picker_opened_during_note_editing_suspends_and_resumes_the_draft() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('n')); + key_with(&context, KeyCode::Char('d'), KeyModifiers::NONE, Some("d")); + + let blocked = ViewContext::from_probe(&blocked_probe("inline")); + assert_eq!(key(&blocked, KeyCode::Char('x')), KeyOutcome::Ignored); + assert!(!paste_text(&blocked, "hidden")); + active(|form| assert_eq!(form.questions[0].notes, "d")); + + // Closing the picker resumes the same editor. + key_with(&context, KeyCode::Char('y'), KeyModifiers::NONE, Some("y")); + active(|form| { + assert_eq!(form.questions[0].notes, "dy"); + assert_eq!( + form.editor, + Some(super::state::EditorFocus { + question: 0, + kind: EditorKind::Notes + }) + ); + }); +} + +#[test] +fn hidden_forms_do_not_render_or_take_paste() { + reset(); + install_default(); + let blocked = ViewContext::from_probe(&blocked_probe("history")); + let buffer = render_buffer(&blocked, 80, 24); + assert!(first_nonblank_row(&buffer).is_none()); + assert!(!paste_text(&blocked, "text")); +} + +// --------------------------------------------------------------------------- +// Flash helpers used by the render tests +// --------------------------------------------------------------------------- + +pub(super) fn render_buffer(context: &ViewContext, width: u16, height: u16) -> Buffer { + use ratatui::Terminal; + use ratatui::backend::TestBackend; + let backend = TestBackend::new(width, height); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal + .draw(|frame| { + state::with(|state| { + form_render::render_view(frame, state, context, frame.area()); + }); + }) + .expect("draw"); + terminal.backend().buffer().clone() +} diff --git a/crates/jcode-tui/src/tui/ask_form/tests/render.rs b/crates/jcode-tui/src/tui/ask_form/tests/render.rs new file mode 100644 index 00000000000..4bd5754de3b --- /dev/null +++ b/crates/jcode-tui/src/tui/ask_form/tests/render.rs @@ -0,0 +1,283 @@ +//! Rendering tests for the `ask_user` form. + +use ratatui::Terminal; +use ratatui::backend::TestBackend; +use ratatui::crossterm::event::KeyCode; +use ratatui::layout::Rect; +use serde_json::json; + +use super::*; +use crate::tui::ask_form::render as form_render; + +fn long_header_form() -> Form { + let schema = json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "properties": { + "q1": { + "type": "string", + "title": "้ธๆŠžใ—ใฆใใ ใ•ใ„", + "description": "Which option would you like to choose today?", + "_meta": {"jcode.dev/askUser": { + "header": "้ธๆŠž่‚ข ้ธๆŠž่‚ข ้ธๆŠž่‚ข ้ธๆŠž่‚ข ้ธๆŠž่‚ข ้ธๆŠž่‚ข ้ธๆŠž่‚ข ้ธๆŠž่‚ข" + }}, + "oneOf": [ + {"const": "a", "title": "Alpha option with a long label"}, + {"const": "b", "title": "Beta"} + ] + }, + "q2": { + "type": "string", + "title": "Emoji", + "description": "Emoji header question.", + "_meta": {"jcode.dev/askUser": {"header": "๐Ÿš€๐Ÿš€๐Ÿš€๐Ÿš€๐Ÿš€๐Ÿš€"}}, + "oneOf": [{"const": "x", "title": "Xray"}] + } + } + }); + Form::new(&super::form("e1", SESSION, schema), 1).expect("form") +} + +fn long_body_schema() -> serde_json::Value { + let long_question = (0..80) + .map(|index| format!("distinct body line {index}")) + .collect::>() + .join(" "); + let long_description = "A long description that must remain reachable. ".repeat(40); + json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "properties": { + "q1": { + "type": "string", + "title": "Long", + "description": long_question, + "_meta": {"jcode.dev/askUser": {"header": "Long"}}, + "oneOf": [ + {"const": "a", "title": "Alpha", "description": long_description}, + {"const": "b", "title": "Beta"} + ] + } + } + }) +} + +fn preview_heavy_schema(lines: usize) -> serde_json::Value { + let preview = (0..lines) + .map(|index| format!("preview line {index}")) + .collect::>() + .join("\n"); + json!({ + "_meta": {"jcode.dev/askUser": {"version": 1}}, + "type": "object", + "properties": { + "q1": { + "type": "string", + "title": "Preview", + "description": "Choose", + "_meta": {"jcode.dev/askUser": {"header": "Preview"}}, + "oneOf": [ + {"const": "a", "title": "Alpha", "_meta": {"preview": preview}}, + {"const": "b", "title": "Beta"} + ] + } + } + }) +} + +fn joined(line: &ratatui::text::Line<'_>) -> String { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect() +} + +#[test] +fn chrome_rows_never_exceed_width_with_cjk_and_emoji_headers() { + let form = long_header_form(); + for width in [40usize, 80, 120] { + let tab = form_render::tab_line(&form, width); + assert!( + line_width(&tab) <= width, + "tab width {} > {width}: {}", + line_width(&tab), + joined(&tab) + ); + let status = form_render::status_line(&form, width); + assert!( + line_width(&status) <= width, + "status width {} > {width}: {}", + line_width(&status), + joined(&status) + ); + } + // The narrow tab row truncates with an ellipsis measured in display cells. + let narrow = form_render::tab_line(&form, 40); + assert!(joined(&narrow).contains('โ€ฆ')); + assert!(line_width(&narrow) <= 40); +} + +#[test] +fn panel_height_caps_at_sixty_percent_and_uses_all_rows_below_12() { + assert_eq!(form_render::panel_height(0), 0); + assert_eq!(form_render::panel_height(10), 10); + assert_eq!(form_render::panel_height(11), 11); + assert_eq!(form_render::panel_height(12), 7); + assert_eq!(form_render::panel_height(15), 9); + assert_eq!(form_render::panel_height(24), 14); +} + +#[test] +fn render_at_80x24_40x15_and_80x10_is_bottom_anchored_and_height_capped() { + reset(); + let context = install_default(); + for (width, height) in [(80u16, 24u16), (40, 15), (80, 10)] { + let buffer = render_buffer(&context, width, height); + let top = height - form_render::panel_height(height); + let first = first_nonblank_row(&buffer).expect("panel content"); + assert!( + first >= top, + "{width}x{height}: content began at {first}, panel top {top}" + ); + assert!( + !row_text(&buffer, height - 1).is_empty(), + "{width}x{height}: status row should not be blank" + ); + active(|form| { + assert_eq!( + form.last_body_height as u16, + form_render::panel_height(height) - 2 + ); + }); + } +} + +#[test] +fn page_keys_scroll_the_whole_body_and_keep_content_reachable() { + reset(); + let context = install(SESSION, super::form("e1", SESSION, long_body_schema())); + let before = render_buffer(&context, 80, 24); + let (lines, body_height) = active(|form| (form.last_body_lines, form.last_body_height)); + assert!(lines > body_height, "long body should overflow: {lines}"); + + let top_row_before = row_text(&before, (24 - form_render::panel_height(24)) + 1); + assert_eq!(key(&context, KeyCode::PageDown), KeyOutcome::Consumed); + active(|form| assert!(form.body_scroll > 0)); + let after = render_buffer(&context, 80, 24); + let top_row_after = row_text(&after, (24 - form_render::panel_height(24)) + 1); + assert_ne!(top_row_before, top_row_after); + + // PageUp returns toward the top. + key(&context, KeyCode::PageUp); + active(|form| assert_eq!(form.body_scroll, 0)); +} + +#[test] +fn long_question_description_and_preview_stay_reachable() { + reset(); + let context = install(SESSION, super::form("e1", SESSION, long_body_schema())); + // Render once to establish geometry, then page to the end. + render_buffer(&context, 40, 15); + for _ in 0..200 { + key(&context, KeyCode::PageDown); + } + let (scroll, lines, body_height) = active(|form| { + ( + form.body_scroll, + form.last_body_lines, + form.last_body_height, + ) + }); + assert_eq!(scroll, lines.saturating_sub(body_height)); + let buffer = render_buffer(&context, 40, 15); + assert!(first_nonblank_row(&buffer).is_some()); +} + +#[test] +fn preview_is_beside_the_list_at_100_columns_and_toggles_below() { + reset(); + let context = install_default(); + + let wide = render_buffer(&context, 120, 24); + assert!( + (0..24).any(|row| row_text(&wide, row).contains("Preview")), + "wide layout should render a preview pane" + ); + + let narrow = render_buffer(&context, 80, 24); + assert!( + !(0..24).any(|row| row_text(&narrow, row).contains("Preview")), + "narrow layout starts on the options viewport" + ); + + assert_eq!(key(&context, KeyCode::Char('p')), KeyOutcome::Consumed); + active(|form| assert!(form.preview_focus)); + let toggled = render_buffer(&context, 80, 24); + assert!( + (0..24).any(|row| row_text(&toggled, row).contains("Preview")), + "p should show the preview viewport" + ); + let status = row_text(&toggled, 23); + assert!(status.contains("PREVIEW"), "status: {status}"); +} + +#[test] +fn clipped_preview_shows_a_remaining_line_count() { + reset(); + let context = install( + SESSION, + super::form("e1", SESSION, preview_heavy_schema(60)), + ); + let buffer = render_buffer(&context, 120, 24); + assert!( + (0..24).any(|row| row_text(&buffer, row).contains("+")), + "clipped preview should show +N lines" + ); +} + +#[test] +fn resize_while_editing_preserves_selection_text_and_cursor() { + reset(); + let context = install_default(); + key(&context, KeyCode::Char('3')); + assert!(paste_text(&context, "hello")); + render_buffer(&context, 120, 24); + active(|form| { + assert_eq!(form.questions[0].other_text, "hello"); + assert_eq!(form.questions[0].other_cursor, 5); + }); + + render_buffer(&context, 40, 15); + active(|form| { + assert_eq!(form.questions[0].confirmed.as_deref(), Some("__other__")); + assert_eq!(form.questions[0].other_text, "hello"); + assert_eq!(form.questions[0].other_cursor, 5); + assert!(form.body_scroll <= form.last_body_lines.saturating_sub(form.last_body_height)); + }); +} + +#[test] +fn tiny_viewports_degrade_without_underflow() { + reset(); + let context = install_default(); + + let one = render_buffer(&context, 80, 1); + assert!(!row_text(&one, 0).is_empty()); + + let two = render_buffer(&context, 80, 2); + assert!(!row_text(&two, 0).is_empty()); + assert!(!row_text(&two, 1).is_empty()); + + // Zero-sized area draws nothing. + let backend = TestBackend::new(1, 1); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal + .draw(|frame| { + state::with(|state| { + form_render::render_view(frame, state, &context, Rect::new(0, 0, 0, 0)); + }); + }) + .expect("zero render"); + let buffer = terminal.backend().buffer().clone(); + assert!(first_nonblank_row(&buffer).is_none()); +} diff --git a/crates/jcode-tui/src/tui/backend.rs b/crates/jcode-tui/src/tui/backend.rs index 9c7d60afef0..c105d151372 100644 --- a/crates/jcode-tui/src/tui/backend.rs +++ b/crates/jcode-tui/src/tui/backend.rs @@ -5,6 +5,7 @@ //! //! Also provides debug socket events for exposing full TUI state. +mod elicitation; mod ssh_sessions; use crate::message::ToolCall; @@ -436,7 +437,7 @@ impl RemoteConnection { system_prompt: None, supports_pdf_panels: false, supports_user_response: false, - supports_elicitation_form: false, + supports_elicitation_form: true, applet_elicitation: false, supports_server_failover: false, supports_turn_identity: true, diff --git a/crates/jcode-tui/src/tui/backend/elicitation.rs b/crates/jcode-tui/src/tui/backend/elicitation.rs new file mode 100644 index 00000000000..d3f0bbf93ac --- /dev/null +++ b/crates/jcode-tui/src/tui/backend/elicitation.rs @@ -0,0 +1,27 @@ +//! Elicitation responses for remote `ask_user` forms. +//! +//! A child module can read the private request-id counter and call the private +//! `send_request`, so no visibility change is needed on `RemoteConnection`. +use super::*; + +impl RemoteConnection { + /// Send one answer and return the request id its `Done`/`Error` + /// acknowledgement will carry. + pub(crate) async fn send_elicitation_response( + &mut self, + session_id: &str, + elicitation_id: &str, + response: crate::protocol::elicitation::ElicitationResponse, + ) -> Result { + let id = self.next_request_id; + self.next_request_id += 1; + self.send_request(Request::ElicitationResponse { + id, + session_id: session_id.to_string(), + elicitation_id: elicitation_id.to_string(), + response, + }) + .await?; + Ok(id) + } +} diff --git a/crates/jcode-tui/src/tui/mod.rs b/crates/jcode-tui/src/tui/mod.rs index d0ef8330058..5ae53bb036f 100644 --- a/crates/jcode-tui/src/tui/mod.rs +++ b/crates/jcode-tui/src/tui/mod.rs @@ -1,5 +1,6 @@ pub mod account_picker; pub(crate) mod app; +mod ask_form; pub mod justrust_status; #[derive(Clone)] @@ -1094,6 +1095,10 @@ pub trait TuiState { fn side_panel_fullscreen(&self) -> bool { false } + /// Whether the provider-failover prompt is waiting for a decision. + fn pending_provider_failover_active(&self) -> bool { + false + } /// Whether to pin read images to a side pane fn pin_images(&self) -> bool; /// Whether inline transcript images render expanded. When false, each diff --git a/crates/jcode-tui/src/tui/ui.rs b/crates/jcode-tui/src/tui/ui.rs index 1afe5ba91fe..1871dab2343 100644 --- a/crates/jcode-tui/src/tui/ui.rs +++ b/crates/jcode-tui/src/tui/ui.rs @@ -3802,6 +3802,8 @@ fn draw_inner(frame: &mut Frame, app: &dyn TuiState) { !app.auto_scroll_paused(), ); + crate::tui::ask_form::render(frame, app); + let frame_elapsed = total_start.elapsed(); if frame_elapsed >= Duration::from_millis(250) { crate::logging::warn(&format!( diff --git a/scripts/fork/code_size_budget.json b/scripts/fork/code_size_budget.json index 07c4354488e..1f8c0e77817 100644 --- a/scripts/fork/code_size_budget.json +++ b/scripts/fork/code_size_budget.json @@ -49,6 +49,7 @@ "crates/jcode-config-types/src/lib.rs": 1623, "crates/jcode-harness-api-server/src/translate.rs": 3620, "crates/jcode-import-core/src/lib.rs": 1645, + "crates/jcode-protocol/src/wire/events.rs": 1205, "crates/jcode-provider-anthropic-runtime/src/lib.rs": 2788, "crates/jcode-provider-anthropic/src/lib.rs": 1267, "crates/jcode-provider-bedrock/src/lib.rs": 1612, @@ -93,7 +94,7 @@ "crates/jcode-tui/src/tui/app/onboarding_flow_control.rs": 1821, "crates/jcode-tui/src/tui/app/remote.rs": 2314, "crates/jcode-tui/src/tui/app/remote/key_handling.rs": 2762, - "crates/jcode-tui/src/tui/app/remote/server_events.rs": 3434, + "crates/jcode-tui/src/tui/app/remote/server_events.rs": 3443, "crates/jcode-tui/src/tui/app/state_ui.rs": 2338, "crates/jcode-tui/src/tui/app/state_ui_input_helpers.rs": 1804, "crates/jcode-tui/src/tui/app/tui_lifecycle.rs": 1669, @@ -104,7 +105,7 @@ "crates/jcode-tui/src/tui/mod.rs": 2523, "crates/jcode-tui/src/tui/session_picker.rs": 2695, "crates/jcode-tui/src/tui/session_picker/loading.rs": 3102, - "crates/jcode-tui/src/tui/ui.rs": 3866, + "crates/jcode-tui/src/tui/ui.rs": 3868, "crates/jcode-tui/src/tui/ui_frame_metrics.rs": 1479, "crates/jcode-tui/src/tui/ui_header.rs": 1729, "crates/jcode-tui/src/tui/ui_inline_image.rs": 1797,