| 1 | //! One plain-language line per gated tool call (E6). |
| 2 | //! |
| 3 | //! An approval card used to carry the model's raw JSON arguments and a static |
| 4 | //! tool description. [`approval_summary`] derives a short sentence from the |
| 5 | //! tool name and its arguments alone — never from model prose — so every |
| 6 | //! client can show the same first line ("Search the web for 'espresso'") and |
| 7 | //! put the raw arguments behind it. Paths are shown relative to the |
| 8 | //! workspace when they sit inside it. |
| 9 | |
| 10 | use std::path::Path; |
| 11 | |
| 12 | use codewhale_localization::{Locale, MessageId, tr}; |
| 13 | use serde_json::Value; |
| 14 | |
| 15 | /// Longest quoted argument a summary carries before it is cut with `…`. |
| 16 | const MAX_QUOTED_CHARS: usize = 80; |
| 17 | |
| 18 | /// Summarize a gated tool call for an approval prompt, in English — the |
| 19 | /// wire form every runtime client receives. |
| 20 | #[must_use] |
| 21 | pub fn approval_summary(tool_name: &str, input: &Value, workspace: Option<&Path>) -> String { |
| 22 | approval_summary_in(Locale::En, tool_name, input, workspace) |
| 23 | } |
| 24 | |
| 25 | /// Summarize a gated tool call in `locale`, so a translated approval card |
| 26 | /// leads with the same plain sentence the English one does. Commands, paths, |
| 27 | /// URLs and queries are carried verbatim; only the sentence around them is |
| 28 | /// translated. |
| 29 | #[must_use] |
| 30 | pub fn approval_summary_in( |
| 31 | locale: Locale, |
| 32 | tool_name: &str, |
| 33 | input: &Value, |
| 34 | workspace: Option<&Path>, |
| 35 | ) -> String { |
| 36 | let name = codewhale_execpolicy::canonical_action::canonical_action_alias(tool_name, input); |
| 37 | let text = |key: &str| { |
| 38 | input |
| 39 | .get(key) |
| 40 | .and_then(Value::as_str) |
| 41 | .map(str::trim) |
| 42 | .filter(|value| !value.is_empty()) |
| 43 | }; |
| 44 | let path = |key: &str| text(key).map(|raw| relative_path(raw, workspace)); |
| 45 | let msg = |id: MessageId| tr(locale, id).into_owned(); |
| 46 | let with = |id: MessageId, slot: &str, value: &str| { |
| 47 | tr(locale, id).replace(&format!("{{{slot}}}"), value) |
| 48 | }; |
| 49 | |
| 50 | let credential_uploads: Vec<_> = |
| 51 | crate::core::authority::auto_review::credential_upload_texts(tool_name, input) |
| 52 | .into_iter() |
| 53 | .filter_map(|(command, uploads)| { |
| 54 | let uploads: Vec<String> = uploads |
| 55 | .into_iter() |
| 56 | .filter(|upload| { |
| 57 | upload != crate::core::authority::auto_review::UNPARSED_CREDENTIAL_UPLOAD |
| 58 | }) |
| 59 | .collect(); |
| 60 | (!uploads.is_empty()).then_some((command, uploads)) |
| 61 | }) |
| 62 | .collect(); |
| 63 | if let Some((command, _)) = credential_uploads.first() { |
| 64 | let uploads: Vec<&str> = credential_uploads |
| 65 | .iter() |
| 66 | .flat_map(|(_, uploads)| uploads.iter().map(String::as_str)) |
| 67 | .collect(); |
| 68 | let uploads = code(&clip_to(&uploads.join(", "), MAX_QUOTED_CHARS / 2)); |
| 69 | let template = tr(locale, MessageId::ApprovalSummaryUploadCredentials); |
| 70 | let (before, after) = template |
| 71 | .split_once("`{command}`") |
| 72 | .unwrap_or((&*template, "")); |
| 73 | return format!( |
| 74 | "{}{}{}", |
| 75 | before.replace("{credentials}", &uploads), |
| 76 | code(&clip_command(command, MAX_QUOTED_CHARS)), |
| 77 | after.replace("{credentials}", &uploads), |
| 78 | ); |
| 79 | } |
| 80 | |
| 81 | match name { |
| 82 | "exec_shell" | "task_shell_start" => match text("command") { |
| 83 | Some(command) => run_command_summary(locale, command), |
| 84 | None => msg(MessageId::ApprovalSummaryRunShell), |
| 85 | }, |
| 86 | "exec_shell_wait" | "exec_wait" => msg(MessageId::ApprovalSummaryShellWait), |
| 87 | "exec_shell_interact" | "exec_interact" => msg(MessageId::ApprovalSummaryShellInput), |
| 88 | "exec_shell_cancel" => msg(MessageId::ApprovalSummaryShellStop), |
| 89 | "task_shell_wait" if crate::tools::tasks::task_shell_wait_requests_cancel(input) => { |
| 90 | msg(MessageId::ApprovalSummaryShellStop) |
| 91 | } |
| 92 | "write_file" => match path("path") { |
| 93 | Some(path) => with(MessageId::ApprovalSummaryWritePath, "path", &path), |
| 94 | None => msg(MessageId::ApprovalSummaryWriteFile), |
| 95 | }, |
| 96 | "edit_file" | "fim_edit" => match path("path") { |
| 97 | Some(path) => with(MessageId::ApprovalSummaryEditPath, "path", &path), |
| 98 | None => msg(MessageId::ApprovalSummaryEditFile), |
| 99 | }, |
| 100 | "apply_patch" => patch_summary(locale, input, workspace), |
| 101 | "read_file" => match path("path") { |
| 102 | Some(path) => with(MessageId::ApprovalSummaryReadPath, "path", &path), |
| 103 | None => msg(MessageId::ApprovalSummaryReadFile), |
| 104 | }, |
| 105 | "list_dir" => match path("path") { |
| 106 | Some(path) => with(MessageId::ApprovalSummaryListPath, "path", &path), |
| 107 | None => msg(MessageId::ApprovalSummaryListWorkspace), |
| 108 | }, |
| 109 | "fetch_url" | "web.fetch" | "web_fetch" => match text("url") { |
| 110 | Some(url) => with(MessageId::ApprovalSummaryFetchUrl, "url", &clip(url)), |
| 111 | None => msg(MessageId::ApprovalSummaryFetchPage), |
| 112 | }, |
| 113 | "web_search" => match text("query").or_else(|| text("q")) { |
| 114 | Some(query) => with(MessageId::ApprovalSummarySearchQuery, "query", &clip(query)), |
| 115 | None => msg(MessageId::ApprovalSummarySearchWeb), |
| 116 | }, |
| 117 | "web.run" => web_run_summary(locale, input), |
| 118 | "run_verifiers" if locale == Locale::En => "Run the project's checks".to_string(), |
| 119 | "run_verifiers" => with(MessageId::ApprovalSummaryUseTool, "name", name), |
| 120 | "run_tests" => match text("args") { |
| 121 | Some(args) => run_command_summary(locale, &format!("cargo test {args}")), |
| 122 | None if locale == Locale::En => "Run the project's tests".to_string(), |
| 123 | None => with(MessageId::ApprovalSummaryUseTool, "name", name), |
| 124 | }, |
| 125 | name if name.starts_with("mcp_") => mcp_summary(locale, name, input, workspace), |
| 126 | // Delegated work runs later without the person watching, so every |
| 127 | // client's summary names the authority it asks for, not only the TUI |
| 128 | // card. |
| 129 | name if is_delegated_work_tool(name) => { |
| 130 | let base = generic_summary(locale, name, input, workspace); |
| 131 | let zh = locale == Locale::ZhHans; |
| 132 | let separator = if zh { ":" } else { ": " }; |
| 133 | let fields = delegated_authority_fields(name, input, zh) |
| 134 | .into_iter() |
| 135 | .map(|(label, value)| format!("{label}{separator}{value}")) |
| 136 | .collect::<Vec<_>>(); |
| 137 | if fields.is_empty() { |
| 138 | base |
| 139 | } else { |
| 140 | format!("{base} ({})", fields.join("; ")) |
| 141 | } |
| 142 | } |
| 143 | name => generic_summary(locale, name, input, workspace), |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | /// The summary for a tool with no dedicated sentence: its name and the most |
| 148 | /// telling argument. |
| 149 | fn generic_summary(locale: Locale, name: &str, input: &Value, workspace: Option<&Path>) -> String { |
| 150 | let with = |id: MessageId, slot: &str, value: &str| { |
| 151 | tr(locale, id).replace(&format!("{{{slot}}}"), value) |
| 152 | }; |
| 153 | match (locale, argument_hint(input, workspace)) { |
| 154 | (Locale::En, Some(hint)) => format!("{}: {hint}", humanize(name)), |
| 155 | (Locale::En, None) => format!("Use the {name} tool"), |
| 156 | (_, Some(hint)) => { |
| 157 | format!( |
| 158 | "{}: {hint}", |
| 159 | with(MessageId::ApprovalSummaryUseName, "name", name) |
| 160 | ) |
| 161 | } |
| 162 | (_, None) => with(MessageId::ApprovalSummaryUseTool, "name", name), |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | fn is_delegated_work_tool(tool_name: &str) -> bool { |
| 167 | matches!( |
| 168 | tool_name, |
| 169 | "task_create" | "automation_create" | "automation_update" | "send_later" |
| 170 | ) |
| 171 | } |
| 172 | |
| 173 | fn flag_word(value: bool, zh: bool) -> &'static str { |
| 174 | match (value, zh) { |
| 175 | (true, false) => "on", |
| 176 | (false, false) => "off", |
| 177 | (true, true) => "开启", |
| 178 | (false, true) => "关闭", |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | /// Labeled authority fields a delegated-work call asks for: shell access, |
| 183 | /// trust mode, auto-approval, mode and the directories it would run in. |
| 184 | /// Shown for every such call, whatever its stakes or key order, so the card |
| 185 | /// never hides what the later run is allowed to do. |
| 186 | pub fn delegated_authority_fields( |
| 187 | tool_name: &str, |
| 188 | params: &Value, |
| 189 | zh: bool, |
| 190 | ) -> Vec<(String, String)> { |
| 191 | if !is_delegated_work_tool(tool_name) { |
| 192 | return Vec::new(); |
| 193 | } |
| 194 | let mut fields = Vec::new(); |
| 195 | let flags: [(&str, &str, &str); 3] = [ |
| 196 | ("trust_mode", "Trust mode", "信任模式"), |
| 197 | ("allow_shell", "Shell", "Shell"), |
| 198 | ("auto_approve", "Auto-approve", "自动批准"), |
| 199 | ]; |
| 200 | for (key, en, zh_label) in flags { |
| 201 | let Some(value) = params.get(key) else { |
| 202 | continue; |
| 203 | }; |
| 204 | let rendered = match value.as_bool() { |
| 205 | Some(flag) => flag_word(flag, zh).to_string(), |
| 206 | None => truncate_string_value(&value.to_string(), 40), |
| 207 | }; |
| 208 | fields.push((if zh { zh_label } else { en }.to_string(), rendered)); |
| 209 | } |
| 210 | for (keys, en, zh_label) in [ |
| 211 | (&["mode"][..], "Mode", "模式"), |
| 212 | (&["workspace", "cwds"][..], "Workspace", "工作区"), |
| 213 | ] { |
| 214 | if let Some(value) = param_preview(params, keys, 120) { |
| 215 | fields.push((if zh { zh_label } else { en }.to_string(), value)); |
| 216 | } |
| 217 | } |
| 218 | fields |
| 219 | } |
| 220 | |
| 221 | pub fn param_preview(params: &Value, keys: &[&str], max_len: usize) -> Option<String> { |
| 222 | let Value::Object(map) = params else { |
| 223 | return None; |
| 224 | }; |
| 225 | |
| 226 | for key in keys { |
| 227 | let Some(value) = map.get(*key) else { |
| 228 | continue; |
| 229 | }; |
| 230 | match value { |
| 231 | Value::String(text) => return Some(truncate_string_value(text, max_len)), |
| 232 | Value::Number(number) => return Some(number.to_string()), |
| 233 | Value::Bool(flag) => return Some(flag.to_string()), |
| 234 | Value::Array(items) if !items.is_empty() => { |
| 235 | let preview = items |
| 236 | .iter() |
| 237 | .take(3) |
| 238 | .map(|item| match item { |
| 239 | Value::String(text) => truncate_string_value(text, max_len / 2), |
| 240 | other => truncate_string_value(&other.to_string(), max_len / 2), |
| 241 | }) |
| 242 | .collect::<Vec<_>>() |
| 243 | .join(", "); |
| 244 | return Some(truncate_string_value(&preview, max_len)); |
| 245 | } |
| 246 | other => return Some(truncate_string_value(&other.to_string(), max_len)), |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | None |
| 251 | } |
| 252 | |
| 253 | pub fn truncate_string_value(value: &str, max_len: usize) -> String { |
| 254 | if value.chars().count() <= max_len { |
| 255 | return value.to_string(); |
| 256 | } |
| 257 | let truncated: String = value.chars().take(max_len).collect(); |
| 258 | format!("{truncated}...") |
| 259 | } |
| 260 | |
| 261 | fn run_command_summary(locale: Locale, command: &str) -> String { |
| 262 | tr(locale, MessageId::ApprovalSummaryRunCommand).replace( |
| 263 | "`{command}`", |
| 264 | &code(&clip_command(command, MAX_QUOTED_CHARS)), |
| 265 | ) |
| 266 | } |
| 267 | |
| 268 | /// Quote a command for a heading. A backtick inside it would end a single |
| 269 | /// backtick span early, so such a command is fenced with doubled backticks. |
| 270 | fn code(line: &str) -> String { |
| 271 | if line.contains('`') { |
| 272 | format!("`` {line} ``") |
| 273 | } else { |
| 274 | format!("`{line}`") |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | /// The first argument that says what a tool acts on, for tools without a |
| 279 | /// dedicated line. |
| 280 | fn argument_hint(input: &Value, workspace: Option<&Path>) -> Option<String> { |
| 281 | // `command` first: when a call carries one, what runs is the thing to |
| 282 | // consent to, whatever path it also names. |
| 283 | const KEYS: [&str; 10] = [ |
| 284 | "command", "path", "file", "url", "query", "q", "name", "app", "title", "target", |
| 285 | ]; |
| 286 | KEYS.iter().find_map(|key| { |
| 287 | let raw = input.get(*key)?.as_str()?.trim(); |
| 288 | if raw.is_empty() { |
| 289 | return None; |
| 290 | } |
| 291 | Some(match *key { |
| 292 | "path" | "file" => relative_path(raw, workspace), |
| 293 | "url" => url_display(raw, workspace), |
| 294 | "command" => code(&clip_command(raw, MAX_QUOTED_CHARS)), |
| 295 | "query" | "q" => format!("'{}'", clip(raw)), |
| 296 | _ => clip(raw), |
| 297 | }) |
| 298 | }) |
| 299 | } |
| 300 | |
| 301 | /// `create_issue` → `Create issue`. |
| 302 | fn humanize(name: &str) -> String { |
| 303 | let spaced = name.replace(['_', '-', '.'], " "); |
| 304 | let mut chars = spaced.trim().chars(); |
| 305 | match chars.next() { |
| 306 | Some(first) => first.to_uppercase().chain(chars).collect(), |
| 307 | None => name.to_string(), |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | /// A URL as a person would name it: a `file://` URL inside the workspace is |
| 312 | /// its relative path, anything else is the URL itself. |
| 313 | fn url_display(raw: &str, workspace: Option<&Path>) -> String { |
| 314 | let local = raw |
| 315 | .strip_prefix("file://localhost/") |
| 316 | .map(|rest| format!("/{rest}")) |
| 317 | .or_else(|| raw.strip_prefix("file:///").map(|rest| format!("/{rest}"))); |
| 318 | match local { |
| 319 | Some(path) => { |
| 320 | let path = path |
| 321 | .split(['?', '#']) |
| 322 | .next() |
| 323 | .unwrap_or_default() |
| 324 | .to_string(); |
| 325 | let decoded = urlencoding::decode(&path) |
| 326 | .map(|decoded| decoded.into_owned()) |
| 327 | .unwrap_or(path); |
| 328 | relative_path(&decoded, workspace) |
| 329 | } |
| 330 | None => clip(raw), |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | fn web_run_summary(locale: Locale, input: &Value) -> String { |
| 335 | let first = |key: &str, field: &str| { |
| 336 | input |
| 337 | .get(key) |
| 338 | .and_then(Value::as_array) |
| 339 | .and_then(|items| items.first()) |
| 340 | .and_then(|item| item.get(field)) |
| 341 | .and_then(Value::as_str) |
| 342 | .map(str::trim) |
| 343 | .filter(|value| !value.is_empty()) |
| 344 | .map(str::to_string) |
| 345 | }; |
| 346 | let count = |key: &str| input.get(key).and_then(Value::as_array).map_or(0, Vec::len); |
| 347 | let more = |key: &str| match count(key) { |
| 348 | 0 | 1 => String::new(), |
| 349 | n => tr(locale, MessageId::ApprovalSummaryMore).replace("{count}", &(n - 1).to_string()), |
| 350 | }; |
| 351 | let with = |id: MessageId, slot: &str, value: &str| { |
| 352 | tr(locale, id).replace(&format!("{{{slot}}}"), &clip(value)) |
| 353 | }; |
| 354 | if let Some(query) = first("search_query", "q") { |
| 355 | return with(MessageId::ApprovalSummarySearchQuery, "query", &query) |
| 356 | + &more("search_query"); |
| 357 | } |
| 358 | if let Some(query) = first("image_query", "q") { |
| 359 | return with(MessageId::ApprovalSummaryImageQuery, "query", &query) + &more("image_query"); |
| 360 | } |
| 361 | if let Some(target) = first("open", "ref_id") { |
| 362 | return with(MessageId::ApprovalSummaryOpenTarget, "target", &target) + &more("open"); |
| 363 | } |
| 364 | if count("click") > 0 { |
| 365 | return tr(locale, MessageId::ApprovalSummaryFollowLink).into_owned(); |
| 366 | } |
| 367 | if let Some(pattern) = first("find", "pattern") { |
| 368 | return with(MessageId::ApprovalSummaryFindOnPage, "pattern", &pattern); |
| 369 | } |
| 370 | if count("screenshot") > 0 { |
| 371 | return tr(locale, MessageId::ApprovalSummaryScreenshot).into_owned(); |
| 372 | } |
| 373 | tr(locale, MessageId::ApprovalSummaryBrowse).into_owned() |
| 374 | } |
| 375 | |
| 376 | fn patch_summary(locale: Locale, input: &Value, workspace: Option<&Path>) -> String { |
| 377 | let apply_patch = || tr(locale, MessageId::ApprovalSummaryApplyPatch).into_owned(); |
| 378 | let Ok(preflight) = codewhale_tools::patch_preflight::preflight_apply_patch(input) else { |
| 379 | return apply_patch(); |
| 380 | }; |
| 381 | let mut paths: Vec<String> = preflight |
| 382 | .touched_files |
| 383 | .iter() |
| 384 | .map(|raw| relative_path(raw, workspace)) |
| 385 | .collect(); |
| 386 | paths.sort_unstable(); |
| 387 | paths.dedup(); |
| 388 | match paths.as_slice() { |
| 389 | [] => apply_patch(), |
| 390 | [one] => tr(locale, MessageId::ApprovalSummaryEditPath).replace("{path}", one), |
| 391 | [first, rest @ ..] => tr(locale, MessageId::ApprovalSummaryEditPathMore) |
| 392 | .replace("{path}", first) |
| 393 | .replace("{count}", &rest.len().to_string()), |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | fn mcp_summary(locale: Locale, name: &str, input: &Value, workspace: Option<&Path>) -> String { |
| 398 | // `mcp_<server>_<tool>`; server names may themselves hold `_`, so this is |
| 399 | // presentation only and never a policy decision. |
| 400 | let rest = name.trim_start_matches("mcp_"); |
| 401 | let (server, tool) = match mcp_server_and_tool(rest) { |
| 402 | Some(parts) => parts, |
| 403 | None => return tr(locale, MessageId::ApprovalSummaryUseName).replace("{name}", rest), |
| 404 | }; |
| 405 | let server = server_display(server); |
| 406 | if locale != Locale::En { |
| 407 | return tr(locale, MessageId::ApprovalSummaryMcpTool) |
| 408 | .replace("{tool}", tool) |
| 409 | .replace("{server}", &server); |
| 410 | } |
| 411 | let text = |key: &str| { |
| 412 | input |
| 413 | .get(key) |
| 414 | .and_then(Value::as_str) |
| 415 | .map(str::trim) |
| 416 | .filter(|value| !value.is_empty()) |
| 417 | }; |
| 418 | let target = |keys: &[&str]| keys.iter().find_map(|key| text(key)).map(clip); |
| 419 | // Verbs that say what will happen on the person's computer, whichever |
| 420 | // server provides them; the server still closes the line. |
| 421 | let action = match tool { |
| 422 | "browser" | "browser_start" | "browser_navigate" | "browser_click" | "browser_type" |
| 423 | | "browser_screenshot" | "browser_status" | "browser_stop" => { |
| 424 | let verb = tool |
| 425 | .strip_prefix("browser_") |
| 426 | .or_else(|| text("action")) |
| 427 | .unwrap_or("start"); |
| 428 | Some(match (verb, text("url")) { |
| 429 | ("start" | "navigate", Some(url)) => format!( |
| 430 | "Open {} in a controlled browser", |
| 431 | url_display(url, workspace) |
| 432 | ), |
| 433 | ("start", None) => "Start a controlled browser".to_string(), |
| 434 | ("click", _) => match text("selector") { |
| 435 | Some(selector) => { |
| 436 | format!("Click `{}` in the controlled browser", clip(selector)) |
| 437 | } |
| 438 | None => "Click in the controlled browser".to_string(), |
| 439 | }, |
| 440 | ("type", _) => match text("text") { |
| 441 | Some(typed) => format!("Type '{}' in the controlled browser", clip(typed)), |
| 442 | None => "Type in the controlled browser".to_string(), |
| 443 | }, |
| 444 | ("screenshot", _) => "Screenshot the controlled browser page".to_string(), |
| 445 | ("status", _) => "Check the controlled browser".to_string(), |
| 446 | ("stop", _) => "Close the controlled browser tab".to_string(), |
| 447 | _ => "Use the controlled browser".to_string(), |
| 448 | }) |
| 449 | } |
| 450 | "open_application" => Some(match target(&["name", "bundle_id", "url"]) { |
| 451 | Some(app) => format!("Open {app}"), |
| 452 | None => "Open an application".to_string(), |
| 453 | }), |
| 454 | "kill_app" => Some(match target(&["name", "bundle_id"]) { |
| 455 | Some(app) => format!("Quit {app}"), |
| 456 | None => "Quit an application".to_string(), |
| 457 | }), |
| 458 | "list_apps" => Some("List apps on this computer".to_string()), |
| 459 | "list_windows" => Some("List windows on this computer".to_string()), |
| 460 | "screenshot" => Some("Take a screenshot".to_string()), |
| 461 | "get_app_state" => Some("Read an app's screen contents".to_string()), |
| 462 | "app_script" => Some("Run a script in an app".to_string()), |
| 463 | "request_access" => Some("Check computer-control access".to_string()), |
| 464 | "type" => Some(match text("text") { |
| 465 | Some(typed) => format!("Type '{}'", clip(typed)), |
| 466 | None => "Type text".to_string(), |
| 467 | }), |
| 468 | "key" => Some(match text("key").or_else(|| text("keys")) { |
| 469 | Some(key) => format!("Press {}", clip(key)), |
| 470 | None => "Press a key".to_string(), |
| 471 | }), |
| 472 | _ => None, |
| 473 | }; |
| 474 | let action = action.unwrap_or_else(|| match argument_hint(input, workspace) { |
| 475 | Some(hint) => format!("{}: {hint}", humanize(tool)), |
| 476 | None => humanize(tool), |
| 477 | }); |
| 478 | format!("{action} ({server})") |
| 479 | } |
| 480 | |
| 481 | /// Split `<server>_<tool>`. A plugin-qualified server |
| 482 | /// (`plugin-<len>-<plugin>-<server>`) is length-prefixed, so its end is known |
| 483 | /// even when the name holds `_`. |
| 484 | fn mcp_server_and_tool(rest: &str) -> Option<(&str, &str)> { |
| 485 | if let Some((_, server_and_tool)) = crate::mcp::split_qualified_plugin_server_name(rest) |
| 486 | && let Some((_, tool)) = server_and_tool.split_once('_') |
| 487 | && !tool.is_empty() |
| 488 | { |
| 489 | let server_len = rest.len() - tool.len() - 1; |
| 490 | return Some((&rest[..server_len], tool)); |
| 491 | } |
| 492 | match rest.split_once('_') { |
| 493 | Some((server, tool)) if !server.is_empty() && !tool.is_empty() => Some((server, tool)), |
| 494 | _ => None, |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | /// A server as a person would name it: an included plugin shows its title |
| 499 | /// (`plugin-12-computer-use-computer` → `Computer Use`), never the wire key. |
| 500 | fn server_display(server: &str) -> String { |
| 501 | match crate::mcp::split_qualified_plugin_server_name(server) { |
| 502 | Some((plugin, _)) => plugin |
| 503 | .split(['-', '_']) |
| 504 | .filter(|word| !word.is_empty()) |
| 505 | .map(|word| { |
| 506 | let mut chars = word.chars(); |
| 507 | chars |
| 508 | .next() |
| 509 | .map(|first| first.to_uppercase().chain(chars).collect::<String>()) |
| 510 | .unwrap_or_default() |
| 511 | }) |
| 512 | .collect::<Vec<_>>() |
| 513 | .join(" "), |
| 514 | None => server.to_string(), |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | /// Show `raw` relative to `workspace` when it names a path inside it. |
| 519 | fn relative_path(raw: &str, workspace: Option<&Path>) -> String { |
| 520 | let candidate = Path::new(raw); |
| 521 | if let Some(workspace) = workspace |
| 522 | && candidate.has_root() |
| 523 | && let Ok(relative) = candidate.strip_prefix(workspace) |
| 524 | { |
| 525 | let shown = relative.display().to_string(); |
| 526 | return if shown.is_empty() { |
| 527 | ".".to_string() |
| 528 | } else { |
| 529 | clip(&shown) |
| 530 | }; |
| 531 | } |
| 532 | // A relative path is already workspace-relative; drop a leading `./`. |
| 533 | if let Ok(relative) = candidate.strip_prefix(".") |
| 534 | && !relative.as_os_str().is_empty() |
| 535 | { |
| 536 | return clip(&relative.display().to_string()); |
| 537 | } |
| 538 | clip(raw) |
| 539 | } |
| 540 | |
| 541 | fn clip(value: &str) -> String { |
| 542 | clip_to(value, MAX_QUOTED_CHARS) |
| 543 | } |
| 544 | |
| 545 | /// One line, whitespace collapsed. Line breaks stay visible: `a\nb` joined |
| 546 | /// with a space would read as one command with arguments on an approval card. |
| 547 | fn single_line(value: &str) -> String { |
| 548 | value |
| 549 | .lines() |
| 550 | .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" ")) |
| 551 | .filter(|line| !line.is_empty()) |
| 552 | .collect::<Vec<_>>() |
| 553 | .join(" ⏎ ") |
| 554 | } |
| 555 | |
| 556 | fn clip_to(value: &str, max: usize) -> String { |
| 557 | let single_line = single_line(value); |
| 558 | if single_line.chars().count() <= max { |
| 559 | return single_line; |
| 560 | } |
| 561 | let mut clipped: String = single_line.chars().take(max.saturating_sub(1)).collect(); |
| 562 | clipped.push('…'); |
| 563 | clipped |
| 564 | } |
| 565 | |
| 566 | /// Clip a command keeping both ends: the program leads, and a trailing |
| 567 | /// `| sh` or `; rm -rf …` stays on the heading instead of falling past the cut. |
| 568 | fn clip_command(value: &str, max: usize) -> String { |
| 569 | let single_line = single_line(value); |
| 570 | let chars: Vec<char> = single_line.chars().collect(); |
| 571 | if chars.len() <= max { |
| 572 | return single_line; |
| 573 | } |
| 574 | let keep = max.saturating_sub(1); |
| 575 | let head = keep - keep / 3; |
| 576 | let tail = keep / 3; |
| 577 | let mut clipped: String = chars[..head].iter().collect(); |
| 578 | clipped.push('…'); |
| 579 | clipped.extend(&chars[chars.len() - tail..]); |
| 580 | clipped |
| 581 | } |
| 582 | |
| 583 | #[cfg(test)] |
| 584 | mod tests { |
| 585 | use super::*; |
| 586 | use serde_json::json; |
| 587 | |
| 588 | // The approval card for the model's stop call must say a command is being |
| 589 | // stopped, not show a bare tool name beside a task id. |
| 590 | #[test] |
| 591 | fn task_shell_wait_cancel_is_summarized_as_stopping_a_command() { |
| 592 | let stop = approval_summary_in( |
| 593 | Locale::En, |
| 594 | "task_shell_wait", |
| 595 | &json!({"task_id": "shell_1", "cancel": true}), |
| 596 | None, |
| 597 | ); |
| 598 | assert_eq!(stop, "Stop a running shell command"); |
| 599 | let poll = approval_summary_in( |
| 600 | Locale::En, |
| 601 | "task_shell_wait", |
| 602 | &json!({"task_id": "shell_1", "cancel": false, "gate": "test"}), |
| 603 | None, |
| 604 | ); |
| 605 | assert_ne!(poll, stop); |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn delegated_work_summary_names_the_authority_it_asks_for() { |
| 610 | let summary = approval_summary( |
| 611 | "tasks", |
| 612 | &json!({ |
| 613 | "action": "create", |
| 614 | "prompt": "tidy up", |
| 615 | "trust_mode": true, |
| 616 | "allow_shell": false, |
| 617 | "workspace": "sub/dir" |
| 618 | }), |
| 619 | None, |
| 620 | ); |
| 621 | assert!(summary.contains("Trust mode: on"), "{summary}"); |
| 622 | assert!(summary.contains("Shell: off"), "{summary}"); |
| 623 | assert!(summary.contains("Workspace: sub/dir"), "{summary}"); |
| 624 | |
| 625 | let summary = approval_summary( |
| 626 | "automation", |
| 627 | &json!({"action": "update", "automation_id": "a1", "auto_approve": true, "cwds": ["/x"]}), |
| 628 | None, |
| 629 | ); |
| 630 | assert!(summary.contains("Auto-approve: on"), "{summary}"); |
| 631 | assert!(summary.contains("Workspace: /x"), "{summary}"); |
| 632 | |
| 633 | let summary = approval_summary( |
| 634 | "send_later", |
| 635 | &json!({"action": "schedule", "delay_minutes": 5, "message": "m", "workspace": "/elsewhere"}), |
| 636 | None, |
| 637 | ); |
| 638 | assert!(summary.contains("Workspace: /elsewhere"), "{summary}"); |
| 639 | |
| 640 | let zh = approval_summary_in( |
| 641 | Locale::ZhHans, |
| 642 | "automation", |
| 643 | &json!({"action": "create", "name": "n", "trust_mode": true}), |
| 644 | None, |
| 645 | ); |
| 646 | assert!(zh.contains("信任模式:开启"), "{zh}"); |
| 647 | } |
| 648 | |
| 649 | #[test] |
| 650 | fn web_run_search_names_the_query() { |
| 651 | let summary = approval_summary( |
| 652 | "web.run", |
| 653 | &json!({"search_query": [{"q": "best espresso machine"}, {"q": "reviews"}]}), |
| 654 | None, |
| 655 | ); |
| 656 | assert_eq!( |
| 657 | summary, |
| 658 | "Search the web for 'best espresso machine' (+1 more)" |
| 659 | ); |
| 660 | } |
| 661 | |
| 662 | #[test] |
| 663 | fn file_paths_are_workspace_relative() { |
| 664 | let workspace = Path::new("/work/repo"); |
| 665 | assert_eq!( |
| 666 | approval_summary( |
| 667 | "write_file", |
| 668 | &json!({"path": "/work/repo/notes/espresso.md", "content": "x"}), |
| 669 | Some(workspace), |
| 670 | ), |
| 671 | "Write notes/espresso.md" |
| 672 | ); |
| 673 | // Outside the workspace stays absolute, so the card never hides where |
| 674 | // a write lands. |
| 675 | assert_eq!( |
| 676 | approval_summary("edit_file", &json!({"path": "/etc/hosts"}), Some(workspace)), |
| 677 | "Edit /etc/hosts" |
| 678 | ); |
| 679 | // The model-facing `File{action}` family resolves to the same line. |
| 680 | assert_eq!( |
| 681 | approval_summary( |
| 682 | "File", |
| 683 | &json!({"action": "write", "path": "/work/repo/a.txt"}), |
| 684 | Some(workspace), |
| 685 | ), |
| 686 | "Write a.txt" |
| 687 | ); |
| 688 | } |
| 689 | |
| 690 | #[test] |
| 691 | fn shell_and_fallbacks_are_plain_and_bounded() { |
| 692 | assert_eq!( |
| 693 | approval_summary( |
| 694 | "exec_shell", |
| 695 | &json!({"command": "cargo test -p tui"}), |
| 696 | None |
| 697 | ), |
| 698 | "Run `cargo test -p tui`" |
| 699 | ); |
| 700 | assert_eq!( |
| 701 | approval_summary( |
| 702 | "exec_shell", |
| 703 | &json!({"command": "cargo test\n\nrm -rf target"}), |
| 704 | None |
| 705 | ), |
| 706 | "Run `cargo test ⏎ rm -rf target`", |
| 707 | "a second command line never reads as arguments of the first" |
| 708 | ); |
| 709 | let long = "x".repeat(500); |
| 710 | let summary = approval_summary("exec_shell", &json!({ "command": long }), None); |
| 711 | assert!(summary.chars().count() < 100, "{summary}"); |
| 712 | assert_eq!( |
| 713 | approval_summary("mcp_github_create_issue", &json!({}), None), |
| 714 | "Create issue (github)" |
| 715 | ); |
| 716 | assert_eq!( |
| 717 | approval_summary("mcp_github_create_issue", &json!({"title": "Fix it"}), None), |
| 718 | "Create issue: Fix it (github)" |
| 719 | ); |
| 720 | assert_eq!( |
| 721 | approval_summary("some_tool", &json!({"a": 1}), None), |
| 722 | "Use the some_tool tool" |
| 723 | ); |
| 724 | } |
| 725 | |
| 726 | /// Desktop QA 2026-09-23 bug 3: the card read "Use browser from |
| 727 | /// plugin-12-computer-use-computer" for opening a file in the workspace. |
| 728 | #[test] |
| 729 | fn computer_use_browser_names_the_page_not_the_wire_key() { |
| 730 | let workspace = Path::new("/w/demo/field-notes"); |
| 731 | let summary = approval_summary( |
| 732 | "mcp_plugin-12-computer-use-computer_browser", |
| 733 | &json!({"action": "start", "url": "file:///w/demo/field-notes/field-guide.html"}), |
| 734 | Some(workspace), |
| 735 | ); |
| 736 | assert_eq!( |
| 737 | summary, |
| 738 | "Open field-guide.html in a controlled browser (Computer Use)" |
| 739 | ); |
| 740 | assert!(!summary.contains("plugin-12"), "{summary}"); |
| 741 | assert_eq!( |
| 742 | approval_summary( |
| 743 | "mcp_codewhale-cu_browser_navigate", |
| 744 | &json!({"url": "http://127.0.0.1:8000/field%20guide.html"}), |
| 745 | None, |
| 746 | ), |
| 747 | "Open http://127.0.0.1:8000/field%20guide.html in a controlled browser (codewhale-cu)" |
| 748 | ); |
| 749 | assert_eq!( |
| 750 | approval_summary("mcp_codewhale-cu_list_apps", &json!({}), None), |
| 751 | "List apps on this computer (codewhale-cu)" |
| 752 | ); |
| 753 | assert_eq!( |
| 754 | approval_summary( |
| 755 | "mcp_plugin-12-computer-use-computer_open_application", |
| 756 | &json!({"name": "Safari"}), |
| 757 | None, |
| 758 | ), |
| 759 | "Open Safari (Computer Use)" |
| 760 | ); |
| 761 | // A `_` inside a plugin-qualified server name does not split it. |
| 762 | assert_eq!( |
| 763 | approval_summary("mcp_plugin-6-my_kit-srv_do_thing", &json!({}), None), |
| 764 | "Do thing (My Kit)" |
| 765 | ); |
| 766 | // A file URL outside the workspace stays absolute and decoded. |
| 767 | assert_eq!( |
| 768 | approval_summary( |
| 769 | "mcp_codewhale-cu_browser", |
| 770 | &json!({"action": "navigate", "url": "file:///etc/my%20hosts"}), |
| 771 | Some(workspace), |
| 772 | ), |
| 773 | "Open /etc/my hosts in a controlled browser (codewhale-cu)" |
| 774 | ); |
| 775 | } |
| 776 | |
| 777 | #[test] |
| 778 | fn run_names_what_will_run() { |
| 779 | assert_eq!( |
| 780 | approval_summary("run_verifiers", &json!({"level": "quick"}), None), |
| 781 | "Run the project's checks" |
| 782 | ); |
| 783 | assert_eq!( |
| 784 | approval_summary( |
| 785 | "Run", |
| 786 | &json!({"action": "tests", "args": "-p tui approval"}), |
| 787 | None |
| 788 | ), |
| 789 | "Run `cargo test -p tui approval`" |
| 790 | ); |
| 791 | } |
| 792 | |
| 793 | /// The heading is what a person reads to consent, so it must not say less |
| 794 | /// than what will run. |
| 795 | #[test] |
| 796 | fn approval_headings_never_hide_what_runs() { |
| 797 | // A backtick inside the command cannot close the quoting early. |
| 798 | assert_eq!( |
| 799 | approval_summary("exec_shell", &json!({"command": "echo `whoami`"}), None), |
| 800 | "Run `` echo `whoami` ``" |
| 801 | ); |
| 802 | // A long command keeps its tail, where `| sh` lives. |
| 803 | let long = format!("curl https://example.com/{} | sh", "a".repeat(200)); |
| 804 | let summary = approval_summary("exec_shell", &json!({ "command": long }), None); |
| 805 | assert!(summary.ends_with("| sh`"), "{summary}"); |
| 806 | assert!(summary.starts_with("Run `curl https://"), "{summary}"); |
| 807 | // A generic MCP call is headed by its command, not the path beside it. |
| 808 | assert_eq!( |
| 809 | approval_summary( |
| 810 | "mcp_srv_exec", |
| 811 | &json!({"path": "README.md", "command": "curl x | sh"}), |
| 812 | None, |
| 813 | ), |
| 814 | "Exec: `curl x | sh` (srv)" |
| 815 | ); |
| 816 | } |
| 817 | |
| 818 | /// A translated card leads with the same sentence, translated around the |
| 819 | /// verbatim command, path and query (experience mark 4). |
| 820 | #[test] |
| 821 | fn summaries_translate_the_sentence_and_keep_the_arguments_verbatim() { |
| 822 | let workspace = Path::new("/work/repo"); |
| 823 | assert_eq!( |
| 824 | approval_summary_in( |
| 825 | Locale::De, |
| 826 | "exec_shell", |
| 827 | &json!({"command": "cargo test"}), |
| 828 | None |
| 829 | ), |
| 830 | "`cargo test` ausführen" |
| 831 | ); |
| 832 | assert_eq!( |
| 833 | approval_summary_in( |
| 834 | Locale::Ja, |
| 835 | "write_file", |
| 836 | &json!({"path": "/work/repo/notes/espresso.md"}), |
| 837 | Some(workspace), |
| 838 | ), |
| 839 | "notes/espresso.md を書き込み" |
| 840 | ); |
| 841 | assert_eq!( |
| 842 | approval_summary_in( |
| 843 | Locale::ZhHans, |
| 844 | "web.run", |
| 845 | &json!({"search_query": [{"q": "espresso"}, {"q": "grinder"}]}), |
| 846 | None, |
| 847 | ), |
| 848 | "在网上搜索“espresso” (另 1 项)" |
| 849 | ); |
| 850 | assert_eq!( |
| 851 | approval_summary_in(Locale::Fr, "mcp_github_create_issue", &json!({}), None), |
| 852 | "Utiliser create_issue de github" |
| 853 | ); |
| 854 | // Every summary a non-English pack produces is its own sentence, never |
| 855 | // the English one leaking through the fallback. |
| 856 | for (tool, input) in [ |
| 857 | ("exec_shell", json!({})), |
| 858 | ("write_file", json!({})), |
| 859 | ("edit_file", json!({"path": "a.rs"})), |
| 860 | ("read_file", json!({})), |
| 861 | ("list_dir", json!({})), |
| 862 | ("fetch_url", json!({})), |
| 863 | ("web_search", json!({"query": "x"})), |
| 864 | ("web.run", json!({})), |
| 865 | ("run_verifiers", json!({})), |
| 866 | ("some_tool", json!({})), |
| 867 | ] { |
| 868 | let english = approval_summary(tool, &input, None); |
| 869 | for locale in [ |
| 870 | Locale::De, |
| 871 | Locale::Ja, |
| 872 | Locale::Ru, |
| 873 | Locale::Hi, |
| 874 | Locale::ZhHant, |
| 875 | ] { |
| 876 | let translated = approval_summary_in(locale, tool, &input, None); |
| 877 | assert_ne!(translated, english, "{locale:?} {tool}"); |
| 878 | assert!(!translated.contains('{'), "{locale:?} {tool}: {translated}"); |
| 879 | } |
| 880 | } |
| 881 | } |
| 882 | } |
| 883 |