返回 CodeWhale
previews.rs
根目录 / crates / tui / src / tui / approval / previews.rs
1 //! Shell, file-write, edit, and apply-patch approval previews.
2 //!
3 //! Preview generation stays separate from modal state so bounded formatting
4 //! and exact detail-pager rendering can be reviewed without changing approval
5 //! decisions or persistence semantics.
6
7 use std::borrow::Cow;
8
9 use serde_json::Value;
10
11 use codewhale_execpolicy::canonical_action::canonical_action_alias;
12 use codewhale_localization::{Locale, MessageId, tr};
13 use codewhale_tools::patch_preflight::{NormalizedApplyPatchInput, normalize_apply_patch_input};
14
15 pub(super) fn file_write_preview_lines(tool_name: &str, params: &Value) -> Option<Vec<String>> {
16 match canonical_action_alias(tool_name, params) {
17 "write_file" => {
18 let content = param_text(params, &["content"])?;
19 Some(prefixed_preview_lines(
20 "proposed content",
21 "+ ",
22 &content,
23 5,
24 ))
25 }
26 "edit_file" => {
27 // Keep the per-frame card preview bounded. The details pager builds the
28 // complete version lazily when the reviewer asks for it.
29 edit_file_preview_lines(params, 3)
30 }
31 "apply_patch" => match normalize_apply_patch_input(params) {
32 Ok(NormalizedApplyPatchInput::Patch(patch)) => apply_patch_preview_lines(patch),
33 Ok(NormalizedApplyPatchInput::Replacement { entries, .. }) => {
34 changes_preview_lines(entries)
35 }
36 Err(_) => None,
37 },
38 _ => None,
39 }
40 .filter(|lines| !lines.is_empty())
41 }
42
43 fn edit_file_preview_lines(params: &Value, max_lines: usize) -> Option<Vec<String>> {
44 if let Some(edits) = params.get("edits").and_then(Value::as_array) {
45 // One edit gets the whole per-side budget. Several share the card, so
46 // each shows its first changed line and a count of the rest.
47 let numbered = edits.len() > 1;
48 let per_side = if numbered { 1 } else { max_lines };
49 let mut lines = Vec::new();
50 for (index, edit) in edits.iter().take(max_lines).enumerate() {
51 let old = param_text(edit, &["oldText"])?;
52 let new = param_text(edit, &["newText"])?;
53 if numbered {
54 lines.push(format!("edit {}", index + 1));
55 }
56 push_changed_lines(&mut lines, &old, &new, per_side);
57 }
58 if edits.len() > max_lines {
59 lines.push(format!("... (+{} more edits)", edits.len() - max_lines));
60 }
61 return (!lines.is_empty()).then_some(lines);
62 }
63 let search = param_text(params, &["search"])?;
64 let replace = param_text(params, &["replace"])?;
65 let mut lines = Vec::new();
66 push_changed_lines(&mut lines, &search, &replace, max_lines);
67 Some(lines)
68 }
69
70 /// Append what an edit removes (`- `) and adds (`+ `), bounded per side.
71 ///
72 /// Lines both sides share at the start and end are left out, and the rows
73 /// carry no sub-labels: the card has room for only a few preview rows, so
74 /// they go to the change itself. The details pager keeps the exact full text.
75 fn push_changed_lines(lines: &mut Vec<String>, old: &str, new: &str, max_lines: usize) {
76 let old: Vec<&str> = old.lines().collect();
77 let new: Vec<&str> = new.lines().collect();
78 let shared = old.len().min(new.len());
79 let mut head = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
80 let mut tail = old
81 .iter()
82 .rev()
83 .zip(new.iter().rev())
84 .take(shared - head)
85 .take_while(|(a, b)| a == b)
86 .count();
87 if old.len() == new.len() && head == old.len() {
88 // Same lines on both sides (a line-ending-only edit): there is no
89 // changed region to narrow to, so show both sides whole.
90 head = 0;
91 tail = 0;
92 }
93 for (prefix, side) in [
94 ("- ", &old[head..old.len() - tail]),
95 ("+ ", &new[head..new.len() - tail]),
96 ] {
97 lines.extend(
98 side.iter()
99 .take(max_lines)
100 .map(|line| format!("{prefix}{line}")),
101 );
102 if side.len() > max_lines {
103 lines.push(format!("... (+{} more lines)", side.len() - max_lines));
104 }
105 }
106 }
107
108 pub(super) fn exact_edit_file_preview_lines(params: &Value, locale: Locale) -> Option<Vec<String>> {
109 if let Some(edits) = params.get("edits").and_then(Value::as_array) {
110 let mut lines = Vec::new();
111 for (index, edit) in edits.iter().enumerate() {
112 let old = param_text(edit, &["oldText"])?;
113 let new = param_text(edit, &["newText"])?;
114 lines.push(format!("edit {}", index + 1));
115 lines.push(tr(locale, MessageId::ApprovalLabelReplaceThis).into_owned());
116 lines.extend(exact_preview_body_lines("- ", &old));
117 lines.push(tr(locale, MessageId::ApprovalLabelWithThis).into_owned());
118 lines.extend(exact_preview_body_lines("+ ", &new));
119 }
120 return (!lines.is_empty()).then_some(lines);
121 }
122 let search = param_text(params, &["search"])?;
123 let replace = param_text(params, &["replace"])?;
124 let mut lines = vec![tr(locale, MessageId::ApprovalLabelReplaceThis).into_owned()];
125 lines.extend(exact_preview_body_lines("- ", &search));
126 lines.push(tr(locale, MessageId::ApprovalLabelWithThis).into_owned());
127 lines.extend(exact_preview_body_lines("+ ", &replace));
128 Some(lines)
129 }
130
131 fn exact_preview_body_lines(prefix: &str, content: &str) -> Vec<String> {
132 if content.is_empty() {
133 return vec![format!("{prefix}\"\"")];
134 }
135
136 content
137 .split_inclusive('\n')
138 .map(|chunk| {
139 let (body, ending) = if let Some(body) = chunk.strip_suffix("\r\n") {
140 (body, "\\r\\n")
141 } else if let Some(body) = chunk.strip_suffix('\n') {
142 (body, "\\n")
143 } else {
144 (chunk, "")
145 };
146 exact_preview_body_line(prefix, body, ending)
147 })
148 .collect()
149 }
150
151 fn exact_preview_body_line(prefix: &str, body: &str, ending: &str) -> String {
152 let mut line = String::with_capacity(prefix.len() + body.len() + ending.len() + 2);
153 line.push_str(prefix);
154 line.push('"');
155 for ch in body.chars() {
156 match ch {
157 '\\' => line.push_str("\\\\"),
158 '"' => line.push_str("\\\""),
159 ' ' => line.push_str("\\x20"),
160 '\t' => line.push_str("\\t"),
161 '\r' => line.push_str("\\r"),
162 ch if ch.is_whitespace() || ch.is_control() => line.extend(ch.escape_unicode()),
163 ch => line.push(ch),
164 }
165 }
166 line.push_str(ending);
167 line.push('"');
168 line
169 }
170
171 fn prefixed_preview_lines(
172 header: &str,
173 prefix: &str,
174 content: &str,
175 max_lines: usize,
176 ) -> Vec<String> {
177 let mut lines = vec![header.to_string()];
178 if content.is_empty() {
179 lines.push(format!("{prefix}<empty>"));
180 return lines;
181 }
182
183 let total = content.lines().count();
184 for line in content.lines().take(max_lines) {
185 lines.push(format!("{prefix}{line}"));
186 }
187 if total > max_lines {
188 lines.push(format!("... (+{} more lines)", total - max_lines));
189 }
190 lines
191 }
192
193 fn push_preview_line(lines: &mut Vec<String>, line: impl Into<String>, limit: usize) -> bool {
194 if lines.len() >= limit {
195 return false;
196 }
197 lines.push(line.into());
198 true
199 }
200
201 fn append_preview_truncation(lines: &mut Vec<String>, line: String, limit: usize) {
202 if push_preview_line(lines, line.clone(), limit) {
203 return;
204 }
205 if let Some(last) = lines.last_mut() {
206 *last = line;
207 }
208 }
209
210 pub(super) fn apply_patch_preview_lines(patch: &str) -> Option<Vec<String>> {
211 const PREVIEW_LIMIT: usize = 7;
212
213 let mut lines = Vec::new();
214 let mut omitted = 0usize;
215 for line in patch.lines().filter(|line| !line.trim().is_empty()) {
216 let is_diff_header = line.starts_with("diff --git ")
217 || line.starts_with("--- ")
218 || line.starts_with("+++ ")
219 || line.starts_with("@@");
220 let is_change_line = (line.starts_with('+') && !line.starts_with("+++"))
221 || (line.starts_with('-') && !line.starts_with("---"));
222 if is_diff_header || is_change_line {
223 if !push_preview_line(&mut lines, line, PREVIEW_LIMIT) {
224 omitted += 1;
225 }
226 } else {
227 omitted += 1;
228 }
229 }
230
231 if lines.is_empty() {
232 omitted = 0;
233 for line in patch.lines().filter(|line| !line.trim().is_empty()) {
234 if !push_preview_line(&mut lines, line, PREVIEW_LIMIT) {
235 omitted += 1;
236 }
237 }
238 }
239
240 if omitted > 0 {
241 if lines.len() >= PREVIEW_LIMIT {
242 omitted += 1;
243 }
244 append_preview_truncation(
245 &mut lines,
246 format!("... (+{omitted} more patch lines)"),
247 PREVIEW_LIMIT,
248 );
249 }
250 if lines.is_empty() { None } else { Some(lines) }
251 }
252
253 fn changes_preview_lines(changes: &[Value]) -> Option<Vec<String>> {
254 const PREVIEW_LIMIT: usize = 7;
255
256 let mut lines = Vec::new();
257 let mut rendered_changes = 0usize;
258 for (idx, change) in changes.iter().enumerate() {
259 let path = change
260 .get("path")
261 .and_then(Value::as_str)
262 .unwrap_or("<file>");
263 let content = change.get("content").and_then(Value::as_str).unwrap_or("");
264 if idx > 0 && !push_preview_line(&mut lines, String::new(), PREVIEW_LIMIT) {
265 break;
266 }
267 if !push_preview_line(&mut lines, format!("file: {path}"), PREVIEW_LIMIT) {
268 break;
269 }
270 rendered_changes += 1;
271 for line in prefixed_preview_lines("replacement content", "+ ", content, PREVIEW_LIMIT)
272 .into_iter()
273 .skip(1)
274 {
275 if !push_preview_line(&mut lines, line, PREVIEW_LIMIT) {
276 break;
277 }
278 }
279 if lines.len() >= PREVIEW_LIMIT {
280 break;
281 }
282 }
283 let skipped_changes = changes.len().saturating_sub(rendered_changes);
284 if skipped_changes > 0 {
285 append_preview_truncation(
286 &mut lines,
287 format!("... (+{skipped_changes} more files)"),
288 PREVIEW_LIMIT,
289 );
290 }
291 if lines.is_empty() { None } else { Some(lines) }
292 }
293
294 pub(super) fn param_text(params: &Value, keys: &[&str]) -> Option<String> {
295 let Value::Object(map) = params else {
296 return None;
297 };
298
299 for key in keys {
300 let Some(value) = map.get(*key) else {
301 continue;
302 };
303 match value {
304 Value::String(text) => return Some(text.clone()),
305 Value::Number(number) => return Some(number.to_string()),
306 Value::Bool(flag) => return Some(flag.to_string()),
307 other => return Some(other.to_string()),
308 }
309 }
310
311 None
312 }
313
314 pub(super) fn localize_detail_label(label: &str, locale: Locale) -> Cow<'static, str> {
315 match label {
316 "Command" => tr(locale, MessageId::ApprovalLabelCommand),
317 "Dir" => tr(locale, MessageId::ApprovalLabelDir),
318 "File" => tr(locale, MessageId::ApprovalLabelFile),
319 "Preview" => tr(locale, MessageId::ApprovalLabelPreview),
320 "proposed content" => tr(locale, MessageId::ApprovalLabelProposedContent),
321 "replace this" => tr(locale, MessageId::ApprovalLabelReplaceThis),
322 "with this" => tr(locale, MessageId::ApprovalLabelWithThis),
323 "replacement content" => tr(locale, MessageId::ApprovalLabelReplacementContent),
324 "Path" => tr(locale, MessageId::ApprovalLabelPath),
325 "Target" => tr(locale, MessageId::ApprovalLabelTarget),
326 "Input" => tr(locale, MessageId::ApprovalLabelInput),
327 "Action" => tr(locale, MessageId::ApprovalLabelAction),
328 "Type" => tr(locale, MessageId::ApprovalLabelType),
329 "Prompt" => tr(locale, MessageId::ApprovalLabelPrompt),
330 _ if locale != Locale::ZhHans => label.to_string().into(),
331 "Goal" => "目标".into(),
332 "Children" => "子任务".into(),
333 "Writes" => "写入".into(),
334 "Shell" => "Shell".into(),
335 "Network" => "网络".into(),
336 "Budget" => "预算".into(),
337 "Trust mode" => "信任模式".into(),
338 "Auto-approve" => "自动批准".into(),
339 "Mode" => "模式".into(),
340 "Workspace" => "工作区".into(),
341 _ => label.to_string().into(),
342 }
343 }
344
345 pub(super) fn localize_preview_shell_line(
346 tool_name: &str,
347 line: &str,
348 locale: Locale,
349 ) -> Cow<'static, str> {
350 match tool_name {
351 "write_file" if line == "proposed content" => localize_detail_label(line, locale),
352 _ => line.to_string().into(),
353 }
354 }
355
356 pub(crate) fn format_shell_command_for_approval(command: &str) -> Vec<String> {
357 if let Some(preview) = parse_printf_write_file_command(command) {
358 return format_printf_write_file_preview(preview);
359 }
360
361 let mut out = Vec::new();
362 for raw_line in command.lines() {
363 split_shell_display_line(raw_line, &mut out);
364 }
365 if out.is_empty() && !command.trim().is_empty() {
366 out.push(command.trim().to_string());
367 }
368 out
369 }
370
371 fn split_shell_display_line(line: &str, out: &mut Vec<String>) {
372 let mut quote: Option<char> = None;
373 let mut escaped = false;
374 let mut current = String::new();
375 let mut chars = line.chars().peekable();
376
377 while let Some(ch) = chars.next() {
378 if escaped {
379 current.push(ch);
380 escaped = false;
381 continue;
382 }
383
384 if ch == '\\' {
385 current.push(ch);
386 escaped = true;
387 continue;
388 }
389
390 if matches!(ch, '"' | '\'') {
391 if quote == Some(ch) {
392 quote = None;
393 } else if quote.is_none() {
394 quote = Some(ch);
395 }
396 current.push(ch);
397 continue;
398 }
399
400 if quote.is_none() {
401 match ch {
402 '&' if chars.peek() == Some(&'&') => {
403 chars.next();
404 push_shell_clause(out, &mut current, Some("&&"));
405 continue;
406 }
407 '|' if chars.peek() == Some(&'|') => {
408 chars.next();
409 push_shell_clause(out, &mut current, Some("||"));
410 continue;
411 }
412 '|' => {
413 push_shell_clause(out, &mut current, Some("|"));
414 continue;
415 }
416 ';' => {
417 push_shell_clause(out, &mut current, Some(";"));
418 continue;
419 }
420 _ => {}
421 }
422 }
423
424 current.push(ch);
425 }
426
427 push_shell_clause(out, &mut current, None);
428 }
429
430 fn push_shell_clause(out: &mut Vec<String>, current: &mut String, operator: Option<&str>) {
431 let trimmed = current.trim();
432 if trimmed.is_empty() {
433 if let Some(operator) = operator {
434 out.push(operator.to_string());
435 }
436 } else if let Some(operator) = operator {
437 out.push(format!("{trimmed} {operator}"));
438 } else {
439 out.push(trimmed.to_string());
440 }
441 current.clear();
442 }
443
444 #[derive(Debug, Clone, PartialEq, Eq)]
445 struct PrintfWriteFilePreview {
446 target: String,
447 lines: Vec<String>,
448 }
449
450 fn parse_printf_write_file_command(command: &str) -> Option<PrintfWriteFilePreview> {
451 // A chained or substituted command is not a plain file write: collapsing
452 // it into `printf > target` would hide everything after the operator
453 // from the approval card. Scan the whole command (not the halves around
454 // the redirect) so quote state is never read from a mid-string split.
455 // shlex and the scanners below only understand POSIX quoting. Bash's
456 // ANSI-C and locale quotes need their original command shown in full.
457 if command.contains("$'") || command.contains("$\"") || has_unquoted_shell_control(command) {
458 return None;
459 }
460 let (before_redirect, after_redirect) = split_unquoted_redirect(command)?;
461 let before_redirect = before_redirect.trim();
462 if !before_redirect.starts_with("printf") {
463 return None;
464 }
465
466 let tokens = shlex::split(before_redirect)?;
467 if tokens.first()?.as_str() != "printf" {
468 return None;
469 }
470 let target_parts = shlex::split(after_redirect.trim())?;
471 if target_parts.len() != 1 {
472 return None;
473 }
474 let target = target_parts
475 .into_iter()
476 .next()?
477 .trim_matches(|ch| ch == '"' || ch == '\'')
478 .to_string();
479 if target.is_empty() {
480 return None;
481 }
482
483 let args = &tokens[1..];
484 if args.is_empty() {
485 return None;
486 }
487 let values = if args.len() >= 2 && args[0].contains('%') {
488 &args[1..]
489 } else {
490 args
491 };
492 let mut lines = Vec::new();
493 for value in values {
494 let normalized = value.replace("\\n", "\n");
495 for line in normalized.lines() {
496 lines.push(line.to_string());
497 }
498 }
499 if lines.is_empty() {
500 lines.push(String::new());
501 }
502
503 Some(PrintfWriteFilePreview { target, lines })
504 }
505
506 fn format_printf_write_file_preview(preview: PrintfWriteFilePreview) -> Vec<String> {
507 const MAX_PREVIEW_LINES: usize = 12;
508 let mut out = vec![format!("printf > {}", preview.target)];
509 let total = preview.lines.len();
510 for line in preview.lines.into_iter().take(MAX_PREVIEW_LINES) {
511 out.push(format!(" {line}"));
512 }
513 if total > MAX_PREVIEW_LINES {
514 out.push(format!(" ... (+{} more lines)", total - MAX_PREVIEW_LINES));
515 }
516 out
517 }
518
519 /// Whether `text` holds shell syntax that runs or chains another command:
520 /// an unquoted `;`, `&`, `|`, newline, `(` (subshell, `$(`, `<(`), or a
521 /// command substitution (`$(` / backtick) even inside double quotes.
522 fn has_unquoted_shell_control(text: &str) -> bool {
523 let mut quote: Option<char> = None;
524 let mut escaped = false;
525 let mut prev: Option<char> = None;
526 for ch in text.chars() {
527 if escaped {
528 escaped = false;
529 prev = None;
530 continue;
531 }
532 match quote {
533 Some('\'') => {
534 if ch == '\'' {
535 quote = None;
536 }
537 }
538 Some(_) => match ch {
539 '\\' => escaped = true,
540 '"' => quote = None,
541 '`' => return true,
542 '(' if prev == Some('$') => return true,
543 _ => {}
544 },
545 None => match ch {
546 '\\' => escaped = true,
547 '\'' | '"' => quote = Some(ch),
548 ';' | '&' | '|' | '`' | '(' | '\n' | '\r' => return true,
549 _ => {}
550 },
551 }
552 prev = Some(ch);
553 }
554 false
555 }
556
557 fn split_unquoted_redirect(command: &str) -> Option<(&str, &str)> {
558 let mut quote: Option<char> = None;
559 let mut escaped = false;
560 for (idx, ch) in command.char_indices() {
561 if escaped {
562 escaped = false;
563 continue;
564 }
565 if ch == '\\' && quote != Some('\'') {
566 escaped = true;
567 continue;
568 }
569 if matches!(ch, '"' | '\'') {
570 if quote == Some(ch) {
571 quote = None;
572 } else if quote.is_none() {
573 quote = Some(ch);
574 }
575 continue;
576 }
577 if quote.is_none() && ch == '>' {
578 return Some((&command[..idx], &command[idx + ch.len_utf8()..]));
579 }
580 }
581 None
582 }
583
584 pub(super) struct DockedPromptParts {
585 pub verb: String,
586 pub subject: String,
587 pub outside_workspace: bool,
588 }
589
590 pub(super) fn docked_prompt_parts(
591 tool_name: &str,
592 params: &Value,
593 workspace: &std::path::Path,
594 summary: &str,
595 ) -> DockedPromptParts {
596 let semantic = canonical_action_alias(tool_name, params);
597 let workspace_str = workspace.to_string_lossy();
598 let repo_name = workspace
599 .file_name()
600 .and_then(|name| name.to_str())
601 .filter(|name| !name.is_empty())
602 .unwrap_or("repo");
603 let raw_path = param_text(params, &["path", "target", "destination"]);
604 let rel_path = raw_path
605 .as_deref()
606 .map(|raw| codewhale_util::utils::workspace_relative(raw, workspace));
607 let outside_workspace = raw_path.as_deref().is_some_and(|raw| {
608 !raw.trim().is_empty()
609 && codewhale_execpolicy::normalize_workspace_relative_path(raw, workspace_str.as_ref())
610 .is_none()
611 });
612
613 match semantic {
614 "exec_shell" | "task_shell_start" => DockedPromptParts {
615 verb: "Run".to_string(),
616 subject: param_text(params, &["command", "cmd"]).unwrap_or_else(|| summary.to_string()),
617 outside_workspace: false,
618 },
619 "write_file" => DockedPromptParts {
620 verb: if outside_workspace {
621 format!("Write outside {repo_name}")
622 } else {
623 "Write".to_string()
624 },
625 subject: rel_path.unwrap_or_else(|| summary.to_string()),
626 outside_workspace,
627 },
628 "edit_file" | "fim_edit" => DockedPromptParts {
629 verb: if outside_workspace {
630 format!("Edit outside {repo_name}")
631 } else {
632 "Edit".to_string()
633 },
634 subject: rel_path.unwrap_or_else(|| summary.to_string()),
635 outside_workspace,
636 },
637 "apply_patch" => {
638 let patch_outside =
639 match codewhale_tools::patch_preflight::preflight_apply_patch(params) {
640 Ok(preflight) => preflight.touched_files.iter().any(|path| {
641 codewhale_execpolicy::normalize_workspace_relative_path(
642 path,
643 workspace_str.as_ref(),
644 )
645 .is_none()
646 }),
647 Err(_) => false,
648 };
649 let subject = match codewhale_tools::patch_preflight::preflight_apply_patch(params) {
650 Ok(preflight) if !preflight.touched_files.is_empty() => preflight
651 .touched_files
652 .into_iter()
653 .map(|p| codewhale_util::utils::workspace_relative(&p, workspace))
654 .collect::<Vec<_>>()
655 .join(", "),
656 _ => rel_path.unwrap_or_else(|| summary.to_string()),
657 };
658 DockedPromptParts {
659 verb: if patch_outside {
660 format!("Patch outside {repo_name}")
661 } else {
662 "Patch".to_string()
663 },
664 subject,
665 outside_workspace: patch_outside,
666 }
667 }
668 "read_file" | "list_dir" => DockedPromptParts {
669 verb: if semantic == "list_dir" {
670 "List".to_string()
671 } else {
672 "Read".to_string()
673 },
674 subject: rel_path.unwrap_or_else(|| summary.to_string()),
675 outside_workspace,
676 },
677 "fetch_url" | "web.fetch" | "web_fetch" => DockedPromptParts {
678 verb: "Fetch".to_string(),
679 subject: param_text(params, &["url"]).unwrap_or_else(|| summary.to_string()),
680 outside_workspace: false,
681 },
682 "web_search" => DockedPromptParts {
683 verb: "Search".to_string(),
684 subject: param_text(params, &["query", "q"]).unwrap_or_else(|| summary.to_string()),
685 outside_workspace: false,
686 },
687 "workflow" => {
688 let goal = params
689 .get("plan")
690 .and_then(|plan| plan.get("goal"))
691 .and_then(Value::as_str)
692 .map(str::to_string)
693 .unwrap_or_else(|| summary.to_string());
694 DockedPromptParts {
695 verb: "Workflow".to_string(),
696 subject: goal,
697 outside_workspace: false,
698 }
699 }
700 "agent" => DockedPromptParts {
701 verb: "Agent".to_string(),
702 subject: param_text(params, &["prompt", "task", "action"])
703 .unwrap_or_else(|| summary.to_string()),
704 outside_workspace: false,
705 },
706 name if name.starts_with("mcp_") => DockedPromptParts {
707 verb: "MCP".to_string(),
708 subject: param_text(params, &["command", "cmd", "path", "url", "query", "q"])
709 .map(|arg| format!("{name} {arg}"))
710 .unwrap_or_else(|| name.to_string()),
711 outside_workspace: false,
712 },
713 _ => {
714 let subject = param_text(
715 params,
716 &["command", "cmd", "path", "url", "q", "query", "ref_id"],
717 )
718 .map(|arg| format!("{tool_name} {arg}"))
719 .unwrap_or_else(|| {
720 if summary.trim().is_empty() {
721 tool_name.to_string()
722 } else {
723 summary.to_string()
724 }
725 });
726 DockedPromptParts {
727 verb: String::new(),
728 subject,
729 outside_workspace: false,
730 }
731 }
732 }
733 }
734
735 pub(super) fn receipt_subject(
736 tool_name: &str,
737 params: &Value,
738 workspace: &std::path::Path,
739 summary: &str,
740 ) -> String {
741 let parts = docked_prompt_parts(tool_name, params, workspace, summary);
742 let semantic = canonical_action_alias(tool_name, params);
743 match semantic {
744 "exec_shell" | "task_shell_start" => parts.subject,
745 "write_file" | "edit_file" | "fim_edit" | "apply_patch" => {
746 format!("{} {}", parts.verb.to_ascii_lowercase(), parts.subject)
747 }
748 _ if parts.verb.is_empty() => parts.subject,
749 _ => format!("{} {}", parts.verb.to_ascii_lowercase(), parts.subject),
750 }
751 }
752
752 lines RUST