SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Assistant: say when a Claude reply hit the length limit or was declined, not that the model lacks tools (#9495) (#9500)
AsTechEvolves23587433e2c6
diff --git a/assets/locales/pending/agent-chat-stop-reason.json b/assets/locales/pending/agent-chat-stop-reason.jsonnew file mode 100644index 0000000000..f4c8e7c209--- /dev/null+++ b/assets/locales/pending/agent-chat-stop-reason.json@@ -0,0 +1,34 @@+{+ "en": {+ "ui.agent_chat_reply_cut_off": "The reply reached its length limit before it finished, so it may be incomplete. Ask the agent to go on, or for a shorter answer.",+ "ui.agent_chat_reply_declined": "The model declined to answer this message."+ },+ "ar": {+ "ui.agent_chat_reply_cut_off": "بلغ الرد حد طوله قبل أن يكتمل، لذا قد يكون ناقصًا. اطلب من الوكيل أن يتابع، أو أن يجيب بإيجاز أكبر.",+ "ui.agent_chat_reply_declined": "رفض النموذج الإجابة عن هذه الرسالة."+ },+ "de": {+ "ui.agent_chat_reply_cut_off": "Die Antwort hat ihre Längengrenze erreicht, bevor sie fertig war, und ist daher vielleicht unvollständig. Bitten Sie den Agenten weiterzumachen oder kürzer zu antworten.",+ "ui.agent_chat_reply_declined": "Das Modell hat abgelehnt, auf diese Nachricht zu antworten."+ },+ "he": {+ "ui.agent_chat_reply_cut_off": "התשובה הגיעה למגבלת האורך שלה לפני שהסתיימה, ולכן ייתכן שהיא חלקית. יש לבקש מהסוכן להמשיך, או לענות בקצרה יותר.",+ "ui.agent_chat_reply_declined": "המודל סירב לענות על ההודעה הזו."+ },+ "ja": {+ "ui.agent_chat_reply_cut_off": "応答が終わる前に長さの上限に達したため、不完全な可能性があります。続けるか、もっと短く答えるようエージェントに頼んでください。",+ "ui.agent_chat_reply_declined": "モデルはこのメッセージへの回答を断りました。"+ },+ "ko": {+ "ui.agent_chat_reply_cut_off": "응답이 끝나기 전에 길이 한도에 도달해 불완전할 수 있습니다. 에이전트에게 계속하거나 더 짧게 답하라고 요청하세요.",+ "ui.agent_chat_reply_declined": "모델이 이 메시지에 대한 답변을 거절했습니다."+ },+ "vi": {+ "ui.agent_chat_reply_cut_off": "Câu trả lời đã chạm giới hạn độ dài trước khi xong nên có thể chưa đầy đủ. Hãy yêu cầu AI Agent tiếp tục, hoặc trả lời ngắn hơn.",+ "ui.agent_chat_reply_declined": "Mô hình đã từ chối trả lời tin nhắn này."+ },+ "zh": {+ "ui.agent_chat_reply_cut_off": "回复在完成前达到了长度上限,可能不完整。请让智能体继续,或请它回答得更简短。",+ "ui.agent_chat_reply_declined": "模型拒绝回答这条消息。"+ }+}diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rsindex 0c8535992d..38bc005796 100644--- a/crates/ui-egui/src/agent_chat/api_client.rs+++ b/crates/ui-egui/src/agent_chat/api_client.rs@@ -504,7 +504,7 @@ fn go_reply_from_parts(text: Vec<(bool, String)>, calls: Vec<Call>, kept_calls:if !kept_calls.is_empty() {assistant["tool_calls"] = Value::Array(kept_calls);}- Reply { text, calls, assistant }+ Reply { text, calls, assistant, stop: "" }}/// Shared text + capped tool-call accumulator for the three Go reply parsers.@@ -914,7 +914,7 @@ impl Worker {}self.history.push(reply.assistant);if reply.calls.is_empty() {- self.emit(Event::TurnEnded { reason: String::new() });+ self.emit(Event::TurnEnded { reason: reply.stop.into() });return;}// Anthropic takes every result of a round in one user message; OpenAI takes one@@ -1332,6 +1332,19 @@ struct Reply {/// The assistant message to keep in the history, in the endpoint's own shape. Tool calls are/// capped to the ones the loop answers, so every call kept here gets a result.assistant: Value,+ /// Why the answer stopped, as the turn-end reason the chat knows: empty for a normal end,+ /// `max_tokens` for an answer cut off at its length limit, `refusal` when the model declined.+ stop: &'static str,+}++/// The turn-end reason for an Anthropic `stop_reason` or an OpenAI `finish_reason`. Anything+/// else, including a value a server made up, is a normal end.+fn stop_reason(reason: Option<&str>) -> &'static str {+ match reason {+ Some("max_tokens" | "length") => "max_tokens",+ Some("refusal" | "content_filter") => "refusal",+ _ => "",+ }}/// The answer in the endpoint's shape.@@ -1363,8 +1376,16 @@ fn sanitize_reasoning_details(details: Option<&Value>) -> Option<Value> {fn openai_reply(body: &Value) -> Reply {let message = body.pointer("/choices/0/message").cloned().unwrap_or(Value::Null);let text = message.get("content").and_then(Value::as_str).filter(|t| !t.is_empty()).map(|t| vec![(false, t.to_string())]).unwrap_or_default();- // No more than the loop answers: every call kept here must get a `tool` message.- let raw: Vec<Value> = message.get("tool_calls").and_then(Value::as_array).map(|a| a.iter().take(32).cloned().collect()).unwrap_or_default();+ let refused = message.get("refusal").and_then(Value::as_str).is_some_and(|r| !r.trim().is_empty());+ let stop = if refused { "refusal" } else { stop_reason(body.pointer("/choices/0/finish_reason").and_then(Value::as_str)) };+ // No more than the loop answers: every call kept here must get a `tool` message. A call cut+ // off at the length limit is incomplete, so none is run or kept.+ let raw: Vec<Value> = message+ .get("tool_calls")+ .and_then(Value::as_array)+ .filter(|_| stop != "max_tokens")+ .map(|a| a.iter().take(32).cloned().collect())+ .unwrap_or_default();let calls = raw.iter().enumerate()@@ -1390,11 +1411,12 @@ fn openai_reply(body: &Value) -> Reply {if !raw.is_empty() {assistant["tool_calls"] = Value::Array(raw);}- Reply { text, calls, assistant }+ Reply { text, calls, assistant, stop }}fn anthropic_reply(body: &Value) -> Reply {let content = body.get("content").cloned().unwrap_or(Value::Null);+ let stop = stop_reason(body.get("stop_reason").and_then(Value::as_str));let mut text = Vec::new();let mut calls = Vec::new();let assistant = match &content {@@ -1417,6 +1439,8 @@ fn anthropic_reply(body: &Value) -> Reply {}kept.push(block.clone());}+ // A call cut off at the length limit has incomplete input: not run, not kept.+ Some("tool_use") if stop == "max_tokens" => {}Some("tool_use") if calls.len() < 32 => {calls.push(Call {id: block.get("id").and_then(Value::as_str).map_or_else(|| format!("toolu-{i}"), str::to_string),@@ -1444,7 +1468,7 @@ fn anthropic_reply(body: &Value) -> Reply {}_ => json!({"role": "assistant", "content": content.clone()}),};- Reply { text, calls, assistant }+ Reply { text, calls, assistant, stop }}/// Keeps the newest `keep` pictures of the view in the history and swaps every older one for a@@ -2674,6 +2698,59 @@ mod tests {assert_eq!(capped.assistant["content"].as_array().unwrap().len(), 32);}+ /// Why an answer stopped reaches the turn's end: cut off at the length limit, or declined,+ /// in either protocol (#9495). A call cut off mid-way is neither run nor kept in the history.+ #[test]+ fn answers_say_why_they_stopped() {+ let thinking = json!({"type": "thinking", "thinking": "", "signature": "s"});+ let call = json!({"type": "tool_use", "id": "t1", "name": "measure", "input": {}});+ for (reason, stop) in [("end_turn", ""), ("tool_use", ""), ("max_tokens", "max_tokens"), ("refusal", "refusal"), ("made_up", "")] {+ assert_eq!(anthropic_reply(&json!({"content": [thinking], "stop_reason": reason})).stop, stop, "{reason}");+ }+ assert_eq!(anthropic_reply(&json!({"content": [thinking]})).stop, "");+ let cut = anthropic_reply(&json!({"content": [thinking, call], "stop_reason": "max_tokens"}));+ assert!(cut.calls.is_empty());+ assert_eq!(cut.assistant["content"], json!([thinking]));++ let openai = |finish: &str, message: Value| openai_reply(&json!({"choices": [{"message": message, "finish_reason": finish}]}));+ let calls = json!([{"id": "c1", "type": "function", "function": {"name": "measure", "arguments": "{\"a\""}}]);+ assert_eq!(openai("stop", json!({"content": "Hi"})).stop, "");+ assert_eq!(openai("content_filter", json!({"content": null})).stop, "refusal");+ assert_eq!(openai("stop", json!({"content": null, "refusal": "I can't help with that."})).stop, "refusal");+ let cut = openai("length", json!({"content": null, "tool_calls": calls}));+ assert_eq!(cut.stop, "max_tokens");+ assert!(cut.calls.is_empty());+ assert!(cut.assistant.get("tool_calls").is_none());+ }++ /// The loop ends the turn with the reason: an answer that is only thinking, cut off at the+ /// length limit, ends as `max_tokens`, not as a normal end with nothing said.+ #[test]+ fn a_cut_off_answer_ends_the_turn_as_max_tokens() {+ let http: HttpFn = Arc::new(move |r: &HttpRequest| {+ if r.method == "GET" {+ return Ok((200, b"{\"data\":[]}".to_vec()));+ }+ let body = json!({"content": [{"type": "thinking", "thinking": "", "signature": "s"}], "stop_reason": "max_tokens"});+ Ok((200, body.to_string().into_bytes()))+ });+ let cfg = ApiConfig {+ name: "Test".into(),+ protocol: Protocol::Anthropic,+ base_url: "http://localhost:1".into(),+ model: "m".into(),+ key: Some("sk-secret".into()),+ http,+ request_timeout_s: 300,+ };+ let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) };+ let mut b = ApiBackend::start(cfg, ctx).unwrap();+ b.prompt(&[PromptPart::Text("look closer".into())]);+ let events = wait_for_turn(&mut b);+ b.shutdown(true);+ assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "max_tokens"), "{events:?}");+ }+#[test]fn anthropic_urls_take_the_base_with_or_without_v1() {assert_eq!(endpoint("https://api.anthropic.com", "messages"), "https://api.anthropic.com/v1/messages");diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rsindex 2fd57e3ea1..4899225da5 100644--- a/crates/ui-egui/src/agent_chat/mod.rs+++ b/crates/ui-egui/src/agent_chat/mod.rs@@ -706,8 +706,12 @@ impl AgentChat {if std::mem::take(&mut self.discard_end) {return Some(Outcome::TurnEnd);}- if !matches!(reason.as_str(), "" | "auth" | "error") {- self.notice(format!("({reason})"), false);+ match reason.as_str() {+ "" | "auth" | "error" => {}+ // Not a missing tool: the answer ran out of room, or the model declined (#9495).+ "max_tokens" => self.notice(tr("ui.agent_chat_reply_cut_off").to_string(), false),+ "refusal" => self.notice(tr("ui.agent_chat_reply_declined").to_string(), false),+ _ => self.notice(format!("({reason})"), false),}return Some(Outcome::TurnEnd);}diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rsindex 0d4d4080f7..0426529df1 100644--- a/crates/ui-egui/src/agent_chat/tests.rs+++ b/crates/ui-egui/src/agent_chat/tests.rs@@ -2657,6 +2657,27 @@ fn no_tool_turn_warning_leaves_answers_and_incomplete_turns_quiet() {}}+/// A turn that ends with nothing shown because the reply hit its length limit, or the model+/// declined, says so instead of blaming tool support (#9495).+#[test]+fn a_cut_off_or_declined_reply_says_so_instead_of_blaming_tools() {+ for (reason, said) in [("max_tokens", "ui.agent_chat_reply_cut_off"), ("refusal", "ui.agent_chat_reply_declined")] {+ let (mut app, _, _) = app_with_script();+ app.agent_chat.tools_port = Some(12345);+ start_turn(&mut app, "Make a box".into(), false, None, vec![]);+ app.agent_chat.on_event(Event::TurnEnded { reason: reason.into() });+ end_turn(&mut app);+ assert!(status(&app)["turnWarning"].is_null(), "{reason}");+ let notices: Vec<&str> = app+ .agent_chat+ .items+ .iter()+ .filter_map(|i| if let Item::Notice { text, error: false } = i { Some(text.as_str()) } else { None })+ .collect();+ assert_eq!(notices, [tr(said)], "{reason}");+ }+}+// ---- Tool calls in words (#1457) ----fn in_mm() -> summary::Units<'static> {diff --git a/docs/agent-chat.md b/docs/agent-chat.mdindex 7b313b39f7..c4898d0768 100644--- a/docs/agent-chat.md+++ b/docs/agent-chat.md@@ -263,6 +263,10 @@ short notice when the reply was empty, or when an explicit edit request receivedOrdinary answers to questions do not show it. Edit requests are recognised conservatively fromEnglish opening words such as “make”, “rename”, or “can you move”; other phrasing may stay quiet.Cancelled and failed turns keep their existing messages. Text describing a call is never run.+A reply that stopped at its length limit, or that the model declined, says that instead of the+tool-calling notice: an endpoint reports it as `max_tokens` or `refusal` (Anthropic), or as+`length`, `content_filter` or a refusal (OpenAI-compatible). A tool call cut off at the length+limit is not run.### An agent inside WSL (Windows)