Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): expose Ask responses (#8648)
Thinh Le6c60d56d4e31
diff --git a/src-tauri/src/core/agent/interaction.rs b/src-tauri/src/core/agent/interaction.rsindex 4c8b97cd3..51381e8be 100644--- a/src-tauri/src/core/agent/interaction.rs+++ b/src-tauri/src/core/agent/interaction.rs@@ -139,6 +139,23 @@ impl AskRequest {}Ok(())}++ pub(crate) fn render_results(&self, results: &[QuestionResult]) -> String {+ results+ .iter()+ .map(|result| {+ let answer = result+ .custom_input+ .clone()+ .unwrap_or_else(|| result.selected.join(", "));+ format!(+ "User response for {}: {answer}",+ serde_json::to_string(&result.id).expect("question ids serialize")+ )+ })+ .collect::<Vec<_>>()+ .join("\n")+ }}pub(crate) fn ask_tool_schema() -> Value {diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 7b40e8ef9..43ad62d3f 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -453,9 +453,7 @@ impl CompositeToolInvoker {}match receiver.await {Ok(Ok(results)) => match request.validate_results(&results) {- Ok(()) => serde_json::to_string(&results).unwrap_or_else(|error| {- format!("ERROR: could not encode ask response: {error}")- }),+ Ok(()) => request.render_results(&results),Err(error) => format!("ERROR: invalid ask response: {error}"),},Ok(Err(AskError::Cancelled)) | Err(_) => {@@ -1495,10 +1493,16 @@ fn build_completion_request("messages".to_string(),serde_json::Value::Array(conversation_messages.to_vec()),);- let tool_choice = match forced_tool_choice {- Some(name) => serde_json::json!({ "type": "function", "function": { "name": name } }),- None => serde_json::json!("auto"),- };+ let tool_choice = forced_tool_choice+ .filter(|name| {+ openai_tools+ .iter()+ .any(|tool| tool["function"]["name"].as_str() == Some(*name))+ })+ .map_or_else(+ || serde_json::json!("auto"),+ |name| serde_json::json!({ "type": "function", "function": { "name": name } }),+ );completion_map.insert("tool_choice".to_string(), tool_choice);if !openai_tools.is_empty() {completion_map.insert(@@ -2168,7 +2172,7 @@ mod tests {&tx,&json!({}),"m",- &[],+ &[crate::core::agent::todo::todo_tool_schema()],convo,8,&mut budget,@@ -2194,6 +2198,27 @@ mod tests {);}+ #[test]+ fn forced_tool_choice_requires_an_advertised_tool() {+ let messages = vec![json!({ "role": "user", "content": "build a flappy bird clone" })];+ let ask_only = vec![crate::core::agent::interaction::ask_tool_schema()];++ let ask_request =+ build_completion_request("m", &messages, &ask_only, &json!({}), Some("todo"));+ assert_eq!(+ ask_request["tool_choice"], "auto",+ "a named tool_choice must not select a tool omitted from tools"+ );++ let todo = crate::core::agent::todo::todo_tool_schema();+ let todo_request =+ build_completion_request("m", &messages, &[todo], &json!({}), Some("todo"));+ assert_eq!(+ todo_request["tool_choice"],+ json!({ "type": "function", "function": { "name": "todo" } })+ );+ }+fn mutating_tool_call_completion(id: &str, name: &str) -> serde_json::Value {json!({"choices": [{@@ -3154,7 +3179,7 @@ mod tests {}#[tokio::test]- async fn ask_waits_for_and_returns_a_structured_response() {+ async fn ask_waits_for_and_returns_model_readable_response() {let root = unique_project_root();let (tx, mut rx) = mpsc::unbounded_channel();let permissions: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));@@ -3186,9 +3211,41 @@ mod tests {.unwrap();let out = task.await.unwrap();- let result: serde_json::Value = serde_json::from_str(&out[0].content).unwrap();- assert_eq!(result[0]["id"], "scope");- assert_eq!(result[0]["selected"][0], "Small");+ assert_eq!(out[0].content, "User response for \"scope\": Small");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn ask_returns_custom_response_as_clear_model_text() {+ let root = unique_project_root();+ let (tx, mut rx) = mpsc::unbounded_channel();+ let permissions: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let asks = crate::core::agent::interaction::new_registry();+ let mut invoker = build_prompting_invoker(root.clone(), tx, permissions);+ invoker.ask_requests = Some(asks.clone());++ let task = tokio::spawn(async move { invoker.invoke(&[ask_call()]).await.unwrap() });+ let request_id = match rx.recv().await.unwrap() {+ StreamEvent::AskRequest { request_id, .. } => request_id,+ event => panic!("expected ask_request, got {event:?}"),+ };+ crate::core::agent::interaction::respond(+ &asks,+ &request_id,+ Ok(vec![crate::core::agent::interaction::QuestionResult {+ id: "scope".into(),+ selected: Vec::new(),+ custom_input: Some("CUSTOM-SENTINEL-4829".into()),+ }]),+ )+ .await+ .unwrap();++ let out = task.await.unwrap();+ assert_eq!(+ out[0].content,+ "User response for \"scope\": CUSTOM-SENTINEL-4829"+ );let _ = std::fs::remove_dir_all(&root);}@@ -3219,8 +3276,7 @@ mod tests {.unwrap();let out = task.await.unwrap();- let result: serde_json::Value = serde_json::from_str(&out[0].content).unwrap();- assert_eq!(result[0]["custom_input"], "custom answer");+ assert_eq!(out[0].content, "User response for \"scope\": custom answer");let _ = std::fs::remove_dir_all(&root);}