| 1 | //! TUI rendering helpers for chat history and tool output. |
| 2 | |
| 3 | use std::borrow::Cow; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::time::Instant; |
| 6 | |
| 7 | use ratatui::style::{Color, Modifier, Style}; |
| 8 | use ratatui::text::{Line, Span}; |
| 9 | use unicode_width::UnicodeWidthStr; |
| 10 | |
| 11 | use crate::tui::app::TranscriptSpacing; |
| 12 | use crate::tui::motion::MotionMode; |
| 13 | use codewhale_engine::runtime_handoff::is_turn_metadata_block; |
| 14 | use codewhale_engine::tools::plan::PlanSnapshot; |
| 15 | use codewhale_engine::tools::review::ReviewOutput; |
| 16 | use codewhale_localization::{Locale, MessageId, tr}; |
| 17 | use codewhale_models::{ContentBlock, Message}; |
| 18 | use codewhale_palette as palette; |
| 19 | use codewhale_tui_kit::diff_render; |
| 20 | use codewhale_tui_kit::ui_text::CopyLineSeparator; |
| 21 | |
| 22 | mod agent_activity; |
| 23 | mod approval_receipt; |
| 24 | mod archived_context; |
| 25 | mod automation; |
| 26 | mod checklist; |
| 27 | mod constants; |
| 28 | mod data_display; |
| 29 | mod file_mutation; |
| 30 | mod latex_render; |
| 31 | mod message; |
| 32 | mod plan; |
| 33 | pub(crate) mod text; |
| 34 | mod thinking; |
| 35 | mod tool_output; |
| 36 | mod tool_run; |
| 37 | mod turn_fold; |
| 38 | |
| 39 | pub use approval_receipt::{ApprovalReceiptCell, ApprovalReceiptOutcome}; |
| 40 | use archived_context::{parse_archived_context, render_archived_context}; |
| 41 | pub use automation::{AutomationCell, AutomationCellKind}; |
| 42 | pub(crate) use checklist::is_checklist_tool_name; |
| 43 | use checklist::{ |
| 44 | parse_checklist_snapshot, parse_update_prefix, render_checklist_card, |
| 45 | render_checklist_change_card, |
| 46 | }; |
| 47 | pub use data_display::DataDisplayCell; |
| 48 | |
| 49 | #[cfg(test)] |
| 50 | use checklist::{ChecklistChange, ChecklistItemSnapshot, ChecklistSnapshot}; |
| 51 | use constants::{ |
| 52 | ASSISTANT_GLYPH, CALM_HEADLINE_MIN_WIDTH, TOOL_COMMAND_LINE_LIMIT, TOOL_DONE_SYMBOL, |
| 53 | TOOL_FAILED_SYMBOL, TOOL_FAILURE_PREVIEW_LINES, TOOL_HEADER_SUMMARY_LIMIT, |
| 54 | TOOL_OUTPUT_LINE_LIMIT, TOOL_SUCCESS_OUTPUT_PREVIEW_LINES, TOOL_SUMMARY_CARD_LINES, |
| 55 | TRANSCRIPT_RAIL, USER_GLYPH, |
| 56 | }; |
| 57 | #[cfg(test)] |
| 58 | use constants::{TOOL_RUNNING_SYMBOLS, TOOL_STATUS_SYMBOL_MS}; |
| 59 | use message::{ |
| 60 | RenderedTranscriptLine, assistant_label_style_for, escape_note_backslashes, |
| 61 | hard_break_copy_lines, message_body_style, render_message, |
| 62 | render_message_with_copy_metadata_for_palette, |
| 63 | render_message_with_copy_metadata_for_palette_and_links, render_plain_message, |
| 64 | render_user_message, system_body_style, system_label_style, update_streaming_message_render, |
| 65 | user_body_style, user_label_style, |
| 66 | }; |
| 67 | #[cfg(test)] |
| 68 | pub(super) use thinking::render_thinking_with_analysis; |
| 69 | use thinking::{render_hidden_thinking_activity, render_thinking}; |
| 70 | use tool_output::{ |
| 71 | for_each_wrapped_text, render_exec_output_mode, render_tool_output_mode, wrap_plain_line, |
| 72 | wrap_text, |
| 73 | }; |
| 74 | |
| 75 | #[cfg(test)] |
| 76 | use agent_activity::extract_agent_id; |
| 77 | pub use file_mutation::FileMutationReceipt; |
| 78 | #[cfg(test)] |
| 79 | pub use file_mutation::{FileMutationFile, FileMutationOutcome}; |
| 80 | pub use plan::PlanUpdateCell; |
| 81 | #[cfg(test)] |
| 82 | use thinking::extract_reasoning_summary; |
| 83 | #[cfg(test)] |
| 84 | use tool_run::ToolRunActivitySummary; |
| 85 | #[cfg(test)] |
| 86 | pub use tool_run::detect_tool_runs; |
| 87 | pub use tool_run::{ToolRun, detect_tool_runs_from_slices, tool_run_summary}; |
| 88 | pub(crate) use turn_fold::superseded_todo_write_indices; |
| 89 | pub use turn_fold::{ |
| 90 | TurnFold, TurnFoldProjection, detect_turn_folds, turn_fold_changes, turn_fold_changes_in, |
| 91 | turn_fold_diff, turn_fold_headline, |
| 92 | }; |
| 93 | |
| 94 | #[cfg(test)] |
| 95 | use thinking::{REASONING_CURSOR, REASONING_OPENER, REASONING_RAIL}; |
| 96 | pub use tool_output::OutputProjection; |
| 97 | #[cfg(test)] |
| 98 | pub use tool_output::OutputRow; |
| 99 | pub(crate) use tool_output::output_looks_like_diff; |
| 100 | pub use tool_output::summarize_mcp_output; |
| 101 | |
| 102 | /// Render mode controlling compact live, bounded transcript, or explicit source output. |
| 103 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 104 | pub enum RenderMode { |
| 105 | /// Live in-stream view: thinking is collapsed to a summary, tool output is |
| 106 | /// truncated with a visible details-pager affordance. |
| 107 | Live, |
| 108 | /// Expanded transcript view with bounded tool-output display. |
| 109 | Transcript, |
| 110 | Source, |
| 111 | } |
| 112 | |
| 113 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 114 | pub(crate) enum CellFoldAction { |
| 115 | Expand, |
| 116 | Collapse, |
| 117 | } |
| 118 | |
| 119 | const FOLDED_CELL_PREVIEW_LINES: usize = 3; |
| 120 | |
| 121 | /// A user's explicit decision about one transcript cell. |
| 122 | /// |
| 123 | /// The absence of a `TranscriptFold` — `None` at a call site, no entry in |
| 124 | /// `App::cell_folds` — means the user has not touched that cell, so the |
| 125 | /// thinking display preferences decide a thinking cell's default; other |
| 126 | /// cells start expanded. An explicit intent is *absolute*: expanded or collapsed |
| 127 | /// outright, never "the opposite of whatever the preference currently says". |
| 128 | /// That is what lets a choice outlive a later preference change (#5847). |
| 129 | /// |
| 130 | /// Known limitation: the intent is per session and per virtual cell index. |
| 131 | /// It is not persisted across restarts, and destructive transcript edits drop |
| 132 | /// it along with the other per-index state (`prune_transcript_index_state`). |
| 133 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 134 | pub enum TranscriptFold { |
| 135 | /// The user expanded this cell; show the whole body whatever the |
| 136 | /// preference says. |
| 137 | Expanded, |
| 138 | /// The user collapsed this cell; show the preview whatever the |
| 139 | /// preference says. |
| 140 | Collapsed, |
| 141 | } |
| 142 | |
| 143 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 144 | pub(crate) struct TranscriptActionOwner { |
| 145 | pub cell_index: usize, |
| 146 | /// Rejects same-index replacements after destructive transcript changes. |
| 147 | pub identity_epoch: u64, |
| 148 | } |
| 149 | |
| 150 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 151 | pub(crate) struct CellFoldActionTarget { |
| 152 | pub owner: TranscriptActionOwner, |
| 153 | pub action: CellFoldAction, |
| 154 | } |
| 155 | |
| 156 | // === History Cells === |
| 157 | |
| 158 | /// Renderable history cell for user/assistant/system entries. |
| 159 | #[derive(Debug, Clone)] |
| 160 | pub enum HistoryCell { |
| 161 | User { |
| 162 | content: String, |
| 163 | }, |
| 164 | Assistant { |
| 165 | content: String, |
| 166 | streaming: bool, |
| 167 | }, |
| 168 | System { |
| 169 | content: String, |
| 170 | }, |
| 171 | /// Categorized engine-error cell. Severity drives the label glyph + color |
| 172 | /// (red for `Error`/`Critical`, amber for `Warning`, dim for `Info`) so |
| 173 | /// the user can prioritize at a glance. |
| 174 | Error { |
| 175 | message: String, |
| 176 | severity: codewhale_error_taxonomy::ErrorSeverity, |
| 177 | code: Option<String>, |
| 178 | }, |
| 179 | Thinking { |
| 180 | content: String, |
| 181 | streaming: bool, |
| 182 | duration_secs: Option<f32>, |
| 183 | }, |
| 184 | /// An `<archived_context>` seam block produced by the Flash seam manager |
| 185 | /// (issue #159). Rendered dimmed/italic with a level + range label so |
| 186 | /// the user can see at a glance where context seams exist. |
| 187 | ArchivedContext { |
| 188 | /// Seam level (1, 2, 3, or 0 for cycle-level). |
| 189 | level: u8, |
| 190 | /// Message range covered (e.g. "msg 0-128"). |
| 191 | range: String, |
| 192 | /// Token estimate string (e.g. "~2500"). |
| 193 | tokens: String, |
| 194 | /// Density label (e.g. "~2,500 tokens"). |
| 195 | density: String, |
| 196 | /// Model that produced the summary. |
| 197 | model: String, |
| 198 | /// RFC 3339 timestamp. |
| 199 | timestamp: String, |
| 200 | /// The summary text content. |
| 201 | summary: String, |
| 202 | }, |
| 203 | Tool(ToolCell), |
| 204 | /// Typed receipt for durable scheduled automations (fired / started / |
| 205 | /// completed / failed / coalesced / missed / expired / mutated) — the |
| 206 | /// one-line bulleted card that replaced bare-String `System` receipts |
| 207 | /// (AUTOMATION-VISIBILITY-SPEC §2.2). |
| 208 | Automation(AutomationCell), |
| 209 | ApprovalReceipt(ApprovalReceiptCell), |
| 210 | /// Live in-transcript card for sub-agent activity (issue #128). Owns |
| 211 | /// either a single `DelegateCard` or a multi-worker `FanoutCard`; the |
| 212 | /// UI re-binds it from the mailbox stream as envelopes arrive. |
| 213 | SubAgent(SubAgentCell), |
| 214 | } |
| 215 | |
| 216 | /// In-transcript sub-agent cell — either a single delegate or a fanout. |
| 217 | /// State mutates over the turn as mailbox envelopes are drained. |
| 218 | /// `Shelf` is a synthetic collapsed projector for concurrent live agents. |
| 219 | #[derive(Debug, Clone)] |
| 220 | pub enum SubAgentCell { |
| 221 | Delegate(crate::tui::widgets::agent_card::DelegateCard), |
| 222 | Fanout(crate::tui::widgets::agent_card::FanoutCard), |
| 223 | } |
| 224 | |
| 225 | impl SubAgentCell { |
| 226 | pub fn lines(&self, width: u16) -> Vec<Line<'static>> { |
| 227 | match self { |
| 228 | SubAgentCell::Delegate(card) => card.render_lines(width, &codewhale_palette::UI_THEME), |
| 229 | SubAgentCell::Fanout(card) => card.render_lines(width, &codewhale_palette::UI_THEME), |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 235 | pub struct TranscriptRenderOptions { |
| 236 | pub locale: Locale, |
| 237 | pub show_thinking: bool, |
| 238 | pub(crate) thinking_checkpoints: super::thinking_checkpoint::Checkpoints, |
| 239 | pub thinking_default_expanded: bool, |
| 240 | /// Collapsed completed-thought preview rows (settings.toml). |
| 241 | pub thinking_preview_lines: usize, |
| 242 | pub thinking_highlight: bool, |
| 243 | pub verbose: bool, |
| 244 | pub show_tool_details: bool, |
| 245 | pub inline_diff_mode: codewhale_runtime::settings::InlineDiffMode, |
| 246 | pub calm_mode: bool, |
| 247 | pub low_motion: bool, |
| 248 | pub motion_mode: MotionMode, |
| 249 | pub spacing: TranscriptSpacing, |
| 250 | /// Resolved application theme mode. This keeps cached markdown syntax |
| 251 | /// colors aligned with an explicit theme selection. |
| 252 | pub palette_mode: palette::PaletteMode, |
| 253 | /// Wrap cap (columns) for prose cells — user messages, assistant answers, |
| 254 | /// and reasoning/thinking blocks. `None` spends the full content width, |
| 255 | /// matching tool/status cells (#5436); `Some(n)` caps prose at `n` columns |
| 256 | /// for a bounded reading measure. Resolved once per render pass from |
| 257 | /// `[transcript] prose_measure` so the main cache and the full-screen |
| 258 | /// overlay agree on the same effective width. |
| 259 | pub(crate) prose_measure: Option<u16>, |
| 260 | /// This cell is a durable Work receipt that a later one has replaced. |
| 261 | /// |
| 262 | /// `todo_write` writes the whole list every time, so a long session grew a |
| 263 | /// stack of full checklist cards that could only be cleared by `/clear` or |
| 264 | /// `/new` — both of which also drop `api_messages` and the compaction |
| 265 | /// summary, so tidying the view cost the conversation (#5871). A |
| 266 | /// superseded snapshot collapses to its summary line in the live |
| 267 | /// transcript; the full card stays in the transcript overlay and in the |
| 268 | /// tool detail record, because the receipt that the tool ran is evidence. |
| 269 | pub(crate) superseded_work_receipt: bool, |
| 270 | /// This cell is the newest user turn in the transcript. Only it carries |
| 271 | /// the elevated-surface background; every older prompt renders on the |
| 272 | /// bare ground, so the eye lands on the turn in play. |
| 273 | pub(crate) newest_user_turn: bool, |
| 274 | } |
| 275 | |
| 276 | impl Default for TranscriptRenderOptions { |
| 277 | fn default() -> Self { |
| 278 | Self { |
| 279 | superseded_work_receipt: false, |
| 280 | newest_user_turn: false, |
| 281 | locale: Locale::En, |
| 282 | show_thinking: true, |
| 283 | thinking_checkpoints: Default::default(), |
| 284 | thinking_highlight: true, |
| 285 | thinking_default_expanded: false, |
| 286 | thinking_preview_lines: 2, |
| 287 | verbose: false, |
| 288 | show_tool_details: true, |
| 289 | inline_diff_mode: codewhale_runtime::settings::InlineDiffMode::Full, |
| 290 | calm_mode: false, |
| 291 | low_motion: false, |
| 292 | motion_mode: MotionMode::Full, |
| 293 | spacing: TranscriptSpacing::Spacious, |
| 294 | palette_mode: palette::PaletteMode::detect(), |
| 295 | prose_measure: None, |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | impl TranscriptRenderOptions { |
| 301 | /// Effective wrap width for a prose cell at the given content width. |
| 302 | /// |
| 303 | /// `prose_measure` caps the measure; without a cap the prose cell uses |
| 304 | /// the full content width, like tool/status cells. Applied only at the |
| 305 | /// live-transcript render entry points so the main cache and the |
| 306 | /// full-screen overlay agree on the same effective width. |
| 307 | #[must_use] |
| 308 | pub(crate) fn prose_width(self, width: u16) -> u16 { |
| 309 | match self.prose_measure { |
| 310 | Some(cap) => width.clamp(1, cap), |
| 311 | None => width.max(1), |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | #[must_use] |
| 316 | pub(crate) fn calm_cards(self) -> bool { |
| 317 | !self.show_tool_details || self.calm_mode |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | impl HistoryCell { |
| 322 | #[must_use] |
| 323 | pub(crate) fn has_live_motion(&self) -> bool { |
| 324 | match self { |
| 325 | HistoryCell::Assistant { streaming, .. } => *streaming, |
| 326 | HistoryCell::Tool(ToolCell::Generic(tool)) |
| 327 | if tool.name == "agent" && !agent_activity::is_agent_inspection(tool) => |
| 328 | { |
| 329 | false |
| 330 | } |
| 331 | HistoryCell::Tool(ToolCell::Exec(exec)) if exec.waiting.is_some() => false, |
| 332 | HistoryCell::Tool(tool) => tool.status() == Some(ToolStatus::Running), |
| 333 | HistoryCell::User { .. } |
| 334 | | HistoryCell::System { .. } |
| 335 | | HistoryCell::Error { .. } |
| 336 | | HistoryCell::Thinking { .. } |
| 337 | | HistoryCell::ArchivedContext { .. } |
| 338 | | HistoryCell::Automation(_) |
| 339 | | HistoryCell::ApprovalReceipt(_) |
| 340 | | HistoryCell::SubAgent(_) => false, |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | pub(crate) fn activity_sweep(&self) -> Option<ActivitySweep> { |
| 345 | match self { |
| 346 | HistoryCell::Tool(ToolCell::Exec(exec)) => (exec.status == ToolStatus::Running |
| 347 | && exec.waiting.is_none() |
| 348 | && exec.stale_elapsed_since_output_ms.is_none()) |
| 349 | .then_some(ActivitySweep::StatusOnly), |
| 350 | HistoryCell::Tool(_) if self.has_live_motion() => Some(ActivitySweep::VerbAndStatus), |
| 351 | _ => None, |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | /// Whether this cell is a completed (non-streaming) assistant answer — |
| 356 | /// the only variant a "copy the answer" affordance may serialize. |
| 357 | /// |
| 358 | /// This is the typed "final answer only" projection for copy surfaces: |
| 359 | /// everything else — user prompts, reasoning/thinking blocks, tool calls |
| 360 | /// and results, sub-agent transcripts, runtime status/system notes, and |
| 361 | /// archived-context seams — is excluded by construction, and a |
| 362 | /// still-streaming partial answer never qualifies. Pair it with |
| 363 | /// `history_cell_to_clipboard_text` for the canonical clean payload. |
| 364 | #[must_use] |
| 365 | pub fn is_completed_assistant_answer(&self) -> bool { |
| 366 | matches!( |
| 367 | self, |
| 368 | HistoryCell::Assistant { |
| 369 | streaming: false, |
| 370 | .. |
| 371 | } |
| 372 | ) |
| 373 | } |
| 374 | |
| 375 | #[allow(clippy::too_many_arguments)] |
| 376 | pub(crate) fn update_incremental_streaming_render( |
| 377 | &self, |
| 378 | width: u16, |
| 379 | options: TranscriptRenderOptions, |
| 380 | verified_append: bool, |
| 381 | cache: &mut codewhale_tui_kit::markdown_render::IncrementalMarkdownRenderCache, |
| 382 | lines: &mut Vec<Line<'static>>, |
| 383 | links: &mut Vec<Vec<codewhale_tui_kit::osc8::LineLink>>, |
| 384 | copy_separators: &mut Vec<CopyLineSeparator>, |
| 385 | copy_prefix_widths: &mut Vec<usize>, |
| 386 | ) -> Option<usize> { |
| 387 | let HistoryCell::Assistant { |
| 388 | content, |
| 389 | streaming: true, |
| 390 | } = self |
| 391 | else { |
| 392 | return None; |
| 393 | }; |
| 394 | if content.trim().is_empty() { |
| 395 | lines.clear(); |
| 396 | links.clear(); |
| 397 | copy_separators.clear(); |
| 398 | copy_prefix_widths.clear(); |
| 399 | *cache = codewhale_tui_kit::markdown_render::IncrementalMarkdownRenderCache::default(); |
| 400 | return Some(0); |
| 401 | } |
| 402 | let width = options.prose_width(width); |
| 403 | Some(update_streaming_message_render( |
| 404 | cache, |
| 405 | content, |
| 406 | width, |
| 407 | assistant_label_style_for(true, options.low_motion), |
| 408 | message_body_style(), |
| 409 | options.palette_mode, |
| 410 | verified_append, |
| 411 | lines, |
| 412 | links, |
| 413 | copy_separators, |
| 414 | copy_prefix_widths, |
| 415 | )) |
| 416 | } |
| 417 | |
| 418 | /// Render the cell into a set of terminal lines. |
| 419 | /// |
| 420 | /// This is the live-display path used by widgets that don't already pass |
| 421 | /// `TranscriptRenderOptions`. Tool output is capped, but thinking is shown |
| 422 | /// in full because callers using bare `lines()` historically expected the |
| 423 | /// uncollapsed body. For the in-stream transcript view prefer |
| 424 | /// `lines_with_options`; expanded display uses `transcript_lines` and |
| 425 | /// explicit copying uses the source projection. |
| 426 | pub fn lines(&self, width: u16) -> Vec<Line<'static>> { |
| 427 | match self { |
| 428 | HistoryCell::User { content } => render_user_message(content, width, false), |
| 429 | HistoryCell::Assistant { content, streaming } => render_message( |
| 430 | ASSISTANT_GLYPH, |
| 431 | assistant_label_style_for(*streaming, /*low_motion*/ false), |
| 432 | message_body_style(), |
| 433 | content, |
| 434 | width, |
| 435 | ), |
| 436 | HistoryCell::System { content } => render_message( |
| 437 | "Note", |
| 438 | system_label_style(), |
| 439 | system_body_style(), |
| 440 | &escape_note_backslashes(content), |
| 441 | width, |
| 442 | ), |
| 443 | HistoryCell::Error { |
| 444 | message, |
| 445 | severity, |
| 446 | code, |
| 447 | } => render_error_message(message, *severity, code.as_deref(), width, true), |
| 448 | HistoryCell::Thinking { |
| 449 | content, |
| 450 | streaming, |
| 451 | duration_secs, |
| 452 | } => render_thinking(content, width, *streaming, *duration_secs, false, false), |
| 453 | HistoryCell::Tool(cell) => cell.lines_with_motion(width, false), |
| 454 | HistoryCell::SubAgent(cell) => cell.lines(width), |
| 455 | HistoryCell::Automation(cell) => cell.render(width), |
| 456 | HistoryCell::ApprovalReceipt(cell) => cell.render(width), |
| 457 | HistoryCell::ArchivedContext { .. } => render_archived_context( |
| 458 | self, |
| 459 | width, |
| 460 | codewhale_tui_kit::markdown_render::detected_palette_mode(), |
| 461 | ), |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | #[cfg(test)] |
| 466 | pub fn lines_with_options( |
| 467 | &self, |
| 468 | width: u16, |
| 469 | options: TranscriptRenderOptions, |
| 470 | ) -> Vec<Line<'static>> { |
| 471 | self.lines_with_options_folded(width, options, None).0 |
| 472 | } |
| 473 | |
| 474 | /// Render with the user's explicit per-cell fold intent. |
| 475 | /// |
| 476 | /// Untouched ordinary cells are expanded. Thinking follows the session's |
| 477 | /// display preferences. An explicit choice outranks that baseline in both |
| 478 | /// directions, so changing a preference never rewrites it (#5847). |
| 479 | pub fn lines_with_options_folded( |
| 480 | &self, |
| 481 | width: u16, |
| 482 | options: TranscriptRenderOptions, |
| 483 | fold: Option<TranscriptFold>, |
| 484 | ) -> (Vec<Line<'static>>, Option<CellFoldAction>) { |
| 485 | if fold == Some(TranscriptFold::Collapsed) && !matches!(self, HistoryCell::Thinking { .. }) |
| 486 | { |
| 487 | let (lines, action) = self.lines_with_copy_metadata_folded(width, options, fold); |
| 488 | return ( |
| 489 | lines.into_iter().map(|rendered| rendered.line).collect(), |
| 490 | action, |
| 491 | ); |
| 492 | } |
| 493 | let mut fold_action = None; |
| 494 | let mut lines = match self { |
| 495 | HistoryCell::Thinking { |
| 496 | streaming, |
| 497 | duration_secs, |
| 498 | .. |
| 499 | } if !options.show_thinking => { |
| 500 | if *streaming { |
| 501 | render_hidden_thinking_activity( |
| 502 | width, |
| 503 | *duration_secs, |
| 504 | options.low_motion, |
| 505 | options.locale, |
| 506 | ) |
| 507 | } else { |
| 508 | Vec::new() |
| 509 | } |
| 510 | } |
| 511 | HistoryCell::Thinking { |
| 512 | content, |
| 513 | streaming, |
| 514 | duration_secs, |
| 515 | } => { |
| 516 | let collapsed = match fold { |
| 517 | Some(TranscriptFold::Expanded) => false, |
| 518 | Some(TranscriptFold::Collapsed) => true, |
| 519 | None => !(options.verbose || options.thinking_default_expanded), |
| 520 | }; |
| 521 | let (lines, expandable) = thinking::render_thinking_with_preview_limit( |
| 522 | content, |
| 523 | width, |
| 524 | *streaming, |
| 525 | *duration_secs, |
| 526 | collapsed, |
| 527 | options.low_motion, |
| 528 | options.thinking_highlight && !options.calm_mode, |
| 529 | options.locale, |
| 530 | if options.calm_mode { |
| 531 | 0 |
| 532 | } else { |
| 533 | options.thinking_preview_lines |
| 534 | }, |
| 535 | options.palette_mode, |
| 536 | options.thinking_checkpoints, |
| 537 | ); |
| 538 | fold_action = expandable.then_some(if collapsed { |
| 539 | CellFoldAction::Expand |
| 540 | } else { |
| 541 | CellFoldAction::Collapse |
| 542 | }); |
| 543 | lines |
| 544 | } |
| 545 | HistoryCell::Tool(ToolCell::PatchSummary(cell)) => cell.render( |
| 546 | width, |
| 547 | options.low_motion, |
| 548 | RenderMode::Live, |
| 549 | options.inline_diff_mode, |
| 550 | options.locale, |
| 551 | ), |
| 552 | HistoryCell::Tool(cell) |
| 553 | if options.calm_cards() |
| 554 | && (!cell.is_failed() || matches!(cell, ToolCell::Exec(_))) => |
| 555 | { |
| 556 | let mut lines = match cell { |
| 557 | ToolCell::Exec(exec) => { |
| 558 | exec.render_calm(width, options.low_motion, options.locale) |
| 559 | } |
| 560 | _ => { |
| 561 | cell.lines_with_motion_and_locale(width, options.low_motion, options.locale) |
| 562 | } |
| 563 | }; |
| 564 | if !cell.is_failed() && lines.len() > TOOL_SUMMARY_CARD_LINES { |
| 565 | lines.truncate(TOOL_SUMMARY_CARD_LINES.saturating_sub(1)); |
| 566 | lines.push(details_affordance_line( |
| 567 | &crate::tui::key_shortcuts::tool_details_shortcut_action_hint("details"), |
| 568 | Style::default().fg(palette::TEXT_DIM).italic(), |
| 569 | )); |
| 570 | } |
| 571 | lines |
| 572 | } |
| 573 | HistoryCell::Tool(cell) if options.superseded_work_receipt => { |
| 574 | // A durable Work receipt a later one replaced keeps its header |
| 575 | // — the progress reading — and drops the body (#5871). The full |
| 576 | // card stays in the transcript overlay and the detail record, |
| 577 | // so the evidence that the tool ran is not rewritten away. |
| 578 | let mut lines = |
| 579 | cell.lines_with_motion_and_locale(width, options.low_motion, options.locale); |
| 580 | lines.truncate(1); |
| 581 | lines.push(details_affordance_line( |
| 582 | &crate::tui::key_shortcuts::tool_details_shortcut_action_hint("details"), |
| 583 | Style::default().fg(palette::TEXT_DIM).italic(), |
| 584 | )); |
| 585 | lines |
| 586 | } |
| 587 | HistoryCell::Tool(cell) => { |
| 588 | cell.lines_with_motion_and_locale(width, options.low_motion, options.locale) |
| 589 | } |
| 590 | HistoryCell::User { content } => { |
| 591 | render_user_message(content, width, options.newest_user_turn) |
| 592 | } |
| 593 | HistoryCell::Assistant { content, streaming } => { |
| 594 | let mut lines: Vec<Line<'static>> = render_message_with_copy_metadata_for_palette( |
| 595 | ASSISTANT_GLYPH, |
| 596 | assistant_label_style_for(*streaming, options.low_motion), |
| 597 | message_body_style(), |
| 598 | content, |
| 599 | width, |
| 600 | options.palette_mode, |
| 601 | ) |
| 602 | .into_iter() |
| 603 | .map(|rendered| rendered.line) |
| 604 | .collect(); |
| 605 | if *streaming { |
| 606 | apply_hot_tail_to_last_line(&mut lines, options.low_motion); |
| 607 | } |
| 608 | lines |
| 609 | } |
| 610 | HistoryCell::System { .. } => self.lines(width), |
| 611 | HistoryCell::Error { |
| 612 | message, |
| 613 | severity, |
| 614 | code, |
| 615 | } => render_error_message(message, *severity, code.as_deref(), width, true), |
| 616 | HistoryCell::SubAgent(cell) => cell.lines(width), |
| 617 | HistoryCell::Automation(cell) => cell.render(width), |
| 618 | HistoryCell::ApprovalReceipt(cell) => cell.render(width), |
| 619 | HistoryCell::ArchivedContext { .. } => { |
| 620 | render_archived_context(self, width, options.palette_mode) |
| 621 | } |
| 622 | }; |
| 623 | if matches!(self, HistoryCell::Tool(_)) { |
| 624 | match options.motion_mode { |
| 625 | MotionMode::Reduced => apply_static_tool_markers( |
| 626 | &mut lines, |
| 627 | codewhale_tui_kit::spinner::BRAILLE_SPINNER_STILL_FRAME, |
| 628 | ), |
| 629 | MotionMode::Still => apply_static_tool_markers( |
| 630 | &mut lines, |
| 631 | codewhale_tui_kit::spinner::LIVE_STATIC_MARKER, |
| 632 | ), |
| 633 | MotionMode::Full => {} |
| 634 | } |
| 635 | } |
| 636 | (lines, fold_action) |
| 637 | } |
| 638 | |
| 639 | pub(crate) fn lines_with_copy_metadata( |
| 640 | &self, |
| 641 | width: u16, |
| 642 | options: TranscriptRenderOptions, |
| 643 | ) -> Vec<RenderedTranscriptLine> { |
| 644 | self.lines_with_copy_metadata_folded(width, options, None).0 |
| 645 | } |
| 646 | |
| 647 | pub(crate) fn lines_with_copy_metadata_folded( |
| 648 | &self, |
| 649 | width: u16, |
| 650 | options: TranscriptRenderOptions, |
| 651 | fold: Option<TranscriptFold>, |
| 652 | ) -> (Vec<RenderedTranscriptLine>, Option<CellFoldAction>) { |
| 653 | self.lines_with_copy_metadata_folded_and_links(width, options, fold, None) |
| 654 | } |
| 655 | |
| 656 | pub(crate) fn lines_with_copy_metadata_folded_and_links( |
| 657 | &self, |
| 658 | width: u16, |
| 659 | options: TranscriptRenderOptions, |
| 660 | fold: Option<TranscriptFold>, |
| 661 | link_resolver: Option<&mut codewhale_tui_kit::markdown_render::WorkspaceLinkResolver<'_>>, |
| 662 | ) -> (Vec<RenderedTranscriptLine>, Option<CellFoldAction>) { |
| 663 | if matches!(self, HistoryCell::Thinking { .. }) { |
| 664 | let (lines, action) = |
| 665 | self.lines_with_options_folded(options.prose_width(width), options, fold); |
| 666 | return (hard_break_copy_lines(lines), action); |
| 667 | } |
| 668 | let mut lines = match self { |
| 669 | HistoryCell::User { content } => hard_break_copy_lines(render_user_message( |
| 670 | content, |
| 671 | options.prose_width(width), |
| 672 | options.newest_user_turn, |
| 673 | )), |
| 674 | HistoryCell::Assistant { content, streaming } => { |
| 675 | let width = options.prose_width(width); |
| 676 | let resolver = if *streaming { None } else { link_resolver }; |
| 677 | let mut rendered = render_message_with_copy_metadata_for_palette_and_links( |
| 678 | ASSISTANT_GLYPH, |
| 679 | assistant_label_style_for(*streaming, options.low_motion), |
| 680 | message_body_style(), |
| 681 | content, |
| 682 | width, |
| 683 | options.palette_mode, |
| 684 | resolver, |
| 685 | ); |
| 686 | if *streaming && let Some(last) = rendered.last_mut() { |
| 687 | apply_hot_tail_to_line(&mut last.line, options.low_motion); |
| 688 | } |
| 689 | rendered |
| 690 | } |
| 691 | HistoryCell::System { content } => { |
| 692 | render_message_with_copy_metadata_for_palette_and_links( |
| 693 | "Note", |
| 694 | system_label_style(), |
| 695 | system_body_style(), |
| 696 | &escape_note_backslashes(content), |
| 697 | width, |
| 698 | options.palette_mode, |
| 699 | link_resolver, |
| 700 | ) |
| 701 | } |
| 702 | HistoryCell::Tool(_) => self |
| 703 | .lines_with_options_folded(width, options, None) |
| 704 | .0 |
| 705 | .into_iter() |
| 706 | .enumerate() |
| 707 | .map(|(index, line)| { |
| 708 | let copy_prefix_width = tool_copy_prefix_width(&line, index == 0); |
| 709 | RenderedTranscriptLine { |
| 710 | line, |
| 711 | links: Vec::new(), |
| 712 | copy_prefix_width, |
| 713 | copy_separator_after: CopyLineSeparator::Newline, |
| 714 | } |
| 715 | }) |
| 716 | .collect(), |
| 717 | HistoryCell::Thinking { .. } => unreachable!("reasoning handled above"), |
| 718 | _ => hard_break_copy_lines(self.lines_with_options_folded(width, options, None).0), |
| 719 | }; |
| 720 | if fold == Some(TranscriptFold::Collapsed) && !lines.is_empty() { |
| 721 | // Keep the cell in the rendered projection so Space can restore |
| 722 | // that same owner (#6876). This control row is separate from the |
| 723 | // body, whose copy separators and links must remain intact. |
| 724 | if lines.len() > FOLDED_CELL_PREVIEW_LINES { |
| 725 | lines.truncate(FOLDED_CELL_PREVIEW_LINES); |
| 726 | lines |
| 727 | .last_mut() |
| 728 | .expect("retained preview body") |
| 729 | .copy_separator_after = CopyLineSeparator::Newline; |
| 730 | } |
| 731 | let style = Style::default().fg(palette::TEXT_MUTED); |
| 732 | let header = Line::from(vec![ |
| 733 | Span::styled("…", style), |
| 734 | Span::styled(if width >= 3 { " ›" } else { "" }, style), |
| 735 | ]); |
| 736 | let header_width = header.width(); |
| 737 | lines.insert( |
| 738 | 0, |
| 739 | RenderedTranscriptLine { |
| 740 | line: header, |
| 741 | links: Vec::new(), |
| 742 | copy_prefix_width: header_width, |
| 743 | copy_separator_after: CopyLineSeparator::Newline, |
| 744 | }, |
| 745 | ); |
| 746 | return (lines, Some(CellFoldAction::Expand)); |
| 747 | } |
| 748 | (lines, None) |
| 749 | } |
| 750 | |
| 751 | /// Render the expanded transcript, including bounded tool-output previews. |
| 752 | pub fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> { |
| 753 | match self { |
| 754 | HistoryCell::User { content } => render_plain_message( |
| 755 | USER_GLYPH, |
| 756 | user_label_style(), |
| 757 | user_body_style(), |
| 758 | content, |
| 759 | width, |
| 760 | ), |
| 761 | HistoryCell::Assistant { content, streaming } => render_message( |
| 762 | ASSISTANT_GLYPH, |
| 763 | // Pager / clipboard surface — pin the glyph at full |
| 764 | // brightness so a screenshot reads the same as a live frame. |
| 765 | assistant_label_style_for(*streaming, /*low_motion*/ true), |
| 766 | message_body_style(), |
| 767 | content, |
| 768 | width, |
| 769 | ), |
| 770 | HistoryCell::System { .. } => self.lines(width), |
| 771 | HistoryCell::Error { |
| 772 | message, |
| 773 | severity, |
| 774 | code, |
| 775 | } => render_error_message(message, *severity, code.as_deref(), width, false), |
| 776 | HistoryCell::Thinking { |
| 777 | content, |
| 778 | streaming, |
| 779 | duration_secs, |
| 780 | } => render_thinking( |
| 781 | content, |
| 782 | width, |
| 783 | *streaming, |
| 784 | *duration_secs, |
| 785 | /*collapsed*/ false, |
| 786 | /*low_motion*/ false, |
| 787 | ), |
| 788 | HistoryCell::Tool(cell) => cell.transcript_lines(width), |
| 789 | HistoryCell::SubAgent(cell) => cell.lines(width), |
| 790 | HistoryCell::Automation(cell) => cell.render(width), |
| 791 | HistoryCell::ApprovalReceipt(cell) => cell.render(width), |
| 792 | HistoryCell::ArchivedContext { .. } => render_archived_context( |
| 793 | self, |
| 794 | width, |
| 795 | codewhale_tui_kit::markdown_render::detected_palette_mode(), |
| 796 | ), |
| 797 | } |
| 798 | } |
| 799 | } |
| 800 | |
| 801 | /// Convert a message into history cells for rendering. |
| 802 | #[must_use] |
| 803 | pub fn history_cells_from_message(msg: &Message) -> Vec<HistoryCell> { |
| 804 | history_cells_from_message_with_results(msg, &[]) |
| 805 | } |
| 806 | |
| 807 | pub fn history_cells_from_message_with_results( |
| 808 | msg: &Message, |
| 809 | messages: &[Message], |
| 810 | ) -> Vec<HistoryCell> { |
| 811 | // Model-facing Operate contract; the live receipt is the goal line. |
| 812 | if codewhale_engine::runtime_handoff::is_operate_contract_message(msg) { |
| 813 | return Vec::new(); |
| 814 | } |
| 815 | if codewhale_models::turn_classify::is_wire_compaction_checkpoint_message(msg) |
| 816 | && let Some(ContentBlock::Text { text, .. }) = msg.content.first() |
| 817 | { |
| 818 | return vec![HistoryCell::System { |
| 819 | content: text.clone(), |
| 820 | }]; |
| 821 | } |
| 822 | if let Some(display) = |
| 823 | codewhale_models::turn_classify::restored_subagent_checkpoint_display(msg) |
| 824 | { |
| 825 | return vec![HistoryCell::System { |
| 826 | content: display.to_string(), |
| 827 | }]; |
| 828 | } |
| 829 | // MCP server guidance is third-party text the model was shown; keep it |
| 830 | // auditable in the transcript rather than hiding it with other handoffs. |
| 831 | if let Some(guidance) = codewhale_engine::runtime_handoff::mcp_server_instructions_display(msg) |
| 832 | { |
| 833 | return vec![HistoryCell::System { |
| 834 | content: format!("MCP server guidance shown to the model:\n{guidance}"), |
| 835 | }]; |
| 836 | } |
| 837 | if let Some(instructions) = |
| 838 | codewhale_engine::runtime_handoff::extension_prompt_contributions_display(msg) |
| 839 | { |
| 840 | return vec![HistoryCell::System { |
| 841 | content: instructions.to_string(), |
| 842 | }]; |
| 843 | } |
| 844 | // Raw runtime handoffs have live tool/status receipts, not user cells. |
| 845 | if let Some(instructions) = codewhale_engine::runtime_handoff::constitution_display(msg) { |
| 846 | return vec![HistoryCell::System { |
| 847 | content: instructions.to_string(), |
| 848 | }]; |
| 849 | } |
| 850 | // Keep their model-facing payload intact and filter only the display. |
| 851 | if codewhale_engine::runtime_handoff::is_internal_runtime_handoff(msg) { |
| 852 | return Vec::new(); |
| 853 | } |
| 854 | |
| 855 | let mut cells = Vec::new(); |
| 856 | let runtime_owned = codewhale_models::turn_classify::is_runtime_owned_user_message(msg); |
| 857 | |
| 858 | for (block_index, block) in msg.content.iter().enumerate() { |
| 859 | match block { |
| 860 | ContentBlock::Text { text, .. } => { |
| 861 | if is_turn_metadata_block(msg, block_index, text) { |
| 862 | continue; |
| 863 | } |
| 864 | if text.starts_with("[tool_history_repair]") { |
| 865 | cells.push(HistoryCell::System { |
| 866 | content: text.clone(), |
| 867 | }); |
| 868 | continue; |
| 869 | } |
| 870 | // Check if this is an `<archived_context>` block. |
| 871 | if (msg.role == "assistant" |
| 872 | || msg.role == codewhale_models::INTERRUPTED_ASSISTANT_ROLE) |
| 873 | && let Some(archived) = parse_archived_context(text) |
| 874 | { |
| 875 | cells.push(archived); |
| 876 | continue; |
| 877 | } |
| 878 | match msg.role.as_str() { |
| 879 | "user" if runtime_owned => { |
| 880 | if let Some(HistoryCell::System { content }) = cells.last_mut() { |
| 881 | content.push('\n'); |
| 882 | content.push_str(text); |
| 883 | } else { |
| 884 | cells.push(HistoryCell::System { |
| 885 | content: format!("Runtime input:\n{text}"), |
| 886 | }); |
| 887 | } |
| 888 | } |
| 889 | "user" => { |
| 890 | if let Some(HistoryCell::User { content }) = cells.last_mut() { |
| 891 | if !content.is_empty() { |
| 892 | content.push('\n'); |
| 893 | } |
| 894 | content.push_str(text); |
| 895 | } else { |
| 896 | cells.push(HistoryCell::User { |
| 897 | content: text.clone(), |
| 898 | }); |
| 899 | } |
| 900 | } |
| 901 | "assistant" | codewhale_models::INTERRUPTED_ASSISTANT_ROLE => { |
| 902 | if let Some(HistoryCell::Assistant { content, .. }) = cells.last_mut() { |
| 903 | if !content.is_empty() { |
| 904 | content.push('\n'); |
| 905 | } |
| 906 | content.push_str(text); |
| 907 | } else { |
| 908 | cells.push(HistoryCell::Assistant { |
| 909 | content: if msg.role == codewhale_models::INTERRUPTED_ASSISTANT_ROLE |
| 910 | && !text.starts_with("[interrupted]") |
| 911 | { |
| 912 | format!("[interrupted] {text}") |
| 913 | } else { |
| 914 | text.clone() |
| 915 | }, |
| 916 | streaming: false, |
| 917 | }); |
| 918 | } |
| 919 | } |
| 920 | "system" => { |
| 921 | if let Some(HistoryCell::System { content }) = cells.last_mut() { |
| 922 | if !content.is_empty() { |
| 923 | content.push('\n'); |
| 924 | } |
| 925 | content.push_str(text); |
| 926 | } else { |
| 927 | cells.push(HistoryCell::System { |
| 928 | content: text.clone(), |
| 929 | }); |
| 930 | } |
| 931 | } |
| 932 | _ => {} |
| 933 | } |
| 934 | } |
| 935 | ContentBlock::Thinking { thinking, .. } => { |
| 936 | // Older sessions may contain this transport-only fallback from |
| 937 | // thinking-mode tool-call replay. It was never model output, |
| 938 | // so do not surface it when restoring their transcripts. |
| 939 | if thinking == "(reasoning omitted)" { |
| 940 | continue; |
| 941 | } |
| 942 | if let Some(HistoryCell::Thinking { content, .. }) = cells.last_mut() { |
| 943 | if !content.is_empty() { |
| 944 | content.push('\n'); |
| 945 | } |
| 946 | content.push_str(thinking); |
| 947 | } else { |
| 948 | cells.push(HistoryCell::Thinking { |
| 949 | content: thinking.clone(), |
| 950 | streaming: false, |
| 951 | duration_secs: None, |
| 952 | }); |
| 953 | } |
| 954 | } |
| 955 | ContentBlock::ToolUse { name, input, .. } if name == "update_plan" => { |
| 956 | let status = if messages.is_empty() { |
| 957 | ToolStatus::Success |
| 958 | } else { |
| 959 | let key = block |
| 960 | .tool_call_key() |
| 961 | .filter(|key| !key.as_str().trim().is_empty()); |
| 962 | match key.and_then(|key| { |
| 963 | messages |
| 964 | .iter() |
| 965 | .flat_map(|message| &message.content) |
| 966 | .find_map(|candidate| match candidate { |
| 967 | ContentBlock::ToolResult { is_error, .. } |
| 968 | if candidate.tool_call_key() == Some(key) => |
| 969 | { |
| 970 | Some(is_error.unwrap_or(false)) |
| 971 | } |
| 972 | _ => None, |
| 973 | }) |
| 974 | }) { |
| 975 | Some(false) => ToolStatus::Success, |
| 976 | Some(true) | None => ToolStatus::Failed, |
| 977 | } |
| 978 | }; |
| 979 | cells.push(HistoryCell::Tool(ToolCell::PlanUpdate(PlanUpdateCell { |
| 980 | snapshot: PlanSnapshot::from_tool_input(input), |
| 981 | status, |
| 982 | }))); |
| 983 | } |
| 984 | ContentBlock::ToolUse { name, input, .. } if name == "show_data" => { |
| 985 | cells.push(HistoryCell::Tool(ToolCell::DataDisplay( |
| 986 | DataDisplayCell::from_history(block, input, messages), |
| 987 | ))); |
| 988 | } |
| 989 | _ => {} |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | cells |
| 994 | } |
| 995 | |
| 996 | // === Tool Cells === |
| 997 | |
| 998 | /// Variants describing a tool result cell. |
| 999 | #[derive(Debug, Clone)] |
| 1000 | pub enum ToolCell { |
| 1001 | Exec(ExecCell), |
| 1002 | Exploring(ExploringCell), |
| 1003 | PlanUpdate(PlanUpdateCell), |
| 1004 | PatchSummary(PatchSummaryCell), |
| 1005 | Review(ReviewCell), |
| 1006 | Mcp(McpToolCell), |
| 1007 | ViewImage(ViewImageCell), |
| 1008 | WebSearch(WebSearchCell), |
| 1009 | DataDisplay(DataDisplayCell), |
| 1010 | Generic(GenericToolCell), |
| 1011 | } |
| 1012 | |
| 1013 | impl ToolCell { |
| 1014 | /// Whether this tool cell projects durable Work state rather than a |
| 1015 | /// transient action receipt. Transcript rhythm uses this semantic split |
| 1016 | /// to keep plans, checklists, and workflows legible without teaching the |
| 1017 | /// renderer about individual tool payloads. |
| 1018 | #[must_use] |
| 1019 | pub(crate) fn is_durable_work_receipt(&self) -> bool { |
| 1020 | matches!(self, ToolCell::PlanUpdate(_)) |
| 1021 | || matches!( |
| 1022 | self, |
| 1023 | ToolCell::Generic(cell) |
| 1024 | if cell.name == "workflow" || is_checklist_tool_name(&cell.name) |
| 1025 | ) |
| 1026 | } |
| 1027 | |
| 1028 | /// Status for cells that have a concrete lifecycle state. |
| 1029 | pub fn status(&self) -> Option<ToolStatus> { |
| 1030 | match self { |
| 1031 | ToolCell::Exec(cell) => Some(cell.status), |
| 1032 | ToolCell::Exploring(cell) => Some(cell.status()), |
| 1033 | ToolCell::PlanUpdate(cell) => Some(cell.status), |
| 1034 | ToolCell::PatchSummary(cell) => Some(cell.status), |
| 1035 | ToolCell::Review(cell) => Some(cell.status), |
| 1036 | ToolCell::Mcp(cell) => Some(cell.status), |
| 1037 | ToolCell::WebSearch(cell) => Some(cell.status), |
| 1038 | ToolCell::DataDisplay(cell) => Some(cell.status), |
| 1039 | ToolCell::Generic(cell) => Some(cell.status), |
| 1040 | ToolCell::ViewImage(_) => Some(ToolStatus::Success), |
| 1041 | } |
| 1042 | } |
| 1043 | |
| 1044 | #[must_use] |
| 1045 | pub fn is_success(&self) -> bool { |
| 1046 | self.status() == Some(ToolStatus::Success) |
| 1047 | } |
| 1048 | |
| 1049 | #[must_use] |
| 1050 | pub fn is_running(&self) -> bool { |
| 1051 | self.status().is_some_and(ToolStatus::is_active) |
| 1052 | } |
| 1053 | |
| 1054 | #[must_use] |
| 1055 | pub fn is_failed(&self) -> bool { |
| 1056 | self.status() == Some(ToolStatus::Failed) |
| 1057 | } |
| 1058 | |
| 1059 | /// Whether this cell should stay visible even inside a dense tool run. |
| 1060 | #[must_use] |
| 1061 | pub fn is_collapsible_guard(&self) -> bool { |
| 1062 | self.is_running() |
| 1063 | || self.is_failed() |
| 1064 | || matches!( |
| 1065 | self, |
| 1066 | ToolCell::Exec(_) |
| 1067 | | ToolCell::Mcp(_) |
| 1068 | | ToolCell::PatchSummary(_) |
| 1069 | | ToolCell::Review(_) |
| 1070 | | ToolCell::PlanUpdate(_) |
| 1071 | | ToolCell::DataDisplay(_) |
| 1072 | ) |
| 1073 | || matches!(self, ToolCell::Generic(cell) if tool_run::generic_tool_name_is_collapse_guard(&cell.name) || cell.is_diff) |
| 1074 | } |
| 1075 | |
| 1076 | /// Render the tool cell into lines. |
| 1077 | pub fn lines(&self, width: u16) -> Vec<Line<'static>> { |
| 1078 | self.lines_with_motion(width, false) |
| 1079 | } |
| 1080 | |
| 1081 | pub fn lines_with_motion(&self, width: u16, low_motion: bool) -> Vec<Line<'static>> { |
| 1082 | self.lines_with_motion_and_locale(width, low_motion, Locale::En) |
| 1083 | } |
| 1084 | |
| 1085 | pub fn lines_with_motion_and_locale( |
| 1086 | &self, |
| 1087 | width: u16, |
| 1088 | low_motion: bool, |
| 1089 | locale: Locale, |
| 1090 | ) -> Vec<Line<'static>> { |
| 1091 | self.render_with_locale(width, low_motion, RenderMode::Live, locale) |
| 1092 | } |
| 1093 | |
| 1094 | /// Expanded rendering with bounded tool-output previews. |
| 1095 | pub fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> { |
| 1096 | self.transcript_lines_with_locale(width, Locale::En) |
| 1097 | } |
| 1098 | |
| 1099 | pub fn transcript_lines_with_locale(&self, width: u16, locale: Locale) -> Vec<Line<'static>> { |
| 1100 | self.render_with_locale( |
| 1101 | width, |
| 1102 | /*low_motion*/ false, |
| 1103 | RenderMode::Transcript, |
| 1104 | locale, |
| 1105 | ) |
| 1106 | } |
| 1107 | |
| 1108 | pub(crate) fn source_lines(&self, width: u16) -> Vec<Line<'static>> { |
| 1109 | self.render_with_locale(width, false, RenderMode::Source, Locale::En) |
| 1110 | } |
| 1111 | |
| 1112 | fn render_with_locale( |
| 1113 | &self, |
| 1114 | width: u16, |
| 1115 | low_motion: bool, |
| 1116 | mode: RenderMode, |
| 1117 | locale: Locale, |
| 1118 | ) -> Vec<Line<'static>> { |
| 1119 | match self { |
| 1120 | ToolCell::Exec(cell) => cell.render_with_locale(width, low_motion, mode, locale), |
| 1121 | ToolCell::Exploring(cell) => cell.render_with_locale(width, low_motion, mode, locale), |
| 1122 | ToolCell::PlanUpdate(cell) => { |
| 1123 | cell.lines_with_motion_and_locale(width, low_motion, locale) |
| 1124 | } |
| 1125 | ToolCell::PatchSummary(cell) => cell.render( |
| 1126 | width, |
| 1127 | low_motion, |
| 1128 | mode, |
| 1129 | codewhale_runtime::settings::InlineDiffMode::Full, |
| 1130 | locale, |
| 1131 | ), |
| 1132 | ToolCell::Review(cell) => cell.render(width, low_motion, mode, locale), |
| 1133 | ToolCell::Mcp(cell) => cell.render(width, low_motion, mode, locale), |
| 1134 | ToolCell::ViewImage(cell) => { |
| 1135 | cell.lines_with_motion_and_locale(width, low_motion, locale) |
| 1136 | } |
| 1137 | ToolCell::WebSearch(cell) => { |
| 1138 | cell.lines_with_motion_and_locale(width, low_motion, locale) |
| 1139 | } |
| 1140 | ToolCell::DataDisplay(cell) => { |
| 1141 | cell.lines_with_motion_and_locale(width, low_motion, locale) |
| 1142 | } |
| 1143 | ToolCell::Generic(cell) => { |
| 1144 | cell.lines_with_mode_and_locale(width, low_motion, mode, locale) |
| 1145 | } |
| 1146 | } |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | /// Overall status for a tool execution. |
| 1151 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1152 | pub enum ToolStatus { |
| 1153 | Queued, |
| 1154 | Running, |
| 1155 | Success, |
| 1156 | Hydrated, |
| 1157 | Stopped, |
| 1158 | /// Terminal result with usable output that still needs attention. |
| 1159 | Warning, |
| 1160 | Failed, |
| 1161 | } |
| 1162 | |
| 1163 | impl ToolStatus { |
| 1164 | #[must_use] |
| 1165 | pub const fn is_active(self) -> bool { |
| 1166 | matches!(self, Self::Queued | Self::Running) |
| 1167 | } |
| 1168 | } |
| 1169 | |
| 1170 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1171 | pub enum ExecWait { |
| 1172 | Approval, |
| 1173 | } |
| 1174 | |
| 1175 | /// Shell command execution rendering data. |
| 1176 | #[derive(Debug, Clone)] |
| 1177 | pub struct ExecCell { |
| 1178 | pub command: String, |
| 1179 | pub description: Option<String>, |
| 1180 | pub status: ToolStatus, |
| 1181 | pub output: Option<String>, |
| 1182 | pub live_output: Option<String>, |
| 1183 | pub shell_task_id: Option<String>, |
| 1184 | pub owner_agent_id: Option<String>, |
| 1185 | pub owner_agent_name: Option<String>, |
| 1186 | pub started_at: Option<Instant>, |
| 1187 | pub duration_ms: Option<u64>, |
| 1188 | pub stale_elapsed_since_output_ms: Option<u64>, |
| 1189 | pub waiting: Option<ExecWait>, |
| 1190 | pub source: ExecSource, |
| 1191 | pub interaction: Option<String>, |
| 1192 | /// Cached output summary — avoids re-parsing JSON every frame. |
| 1193 | pub output_summary: Option<String>, |
| 1194 | } |
| 1195 | |
| 1196 | impl ExecCell { |
| 1197 | /// Render the execution cell into lines (live view, capped output). |
| 1198 | #[cfg(test)] |
| 1199 | pub fn lines_with_motion(&self, width: u16, low_motion: bool) -> Vec<Line<'static>> { |
| 1200 | self.render(width, low_motion, RenderMode::Live) |
| 1201 | } |
| 1202 | |
| 1203 | /// Foreground `exec_shell` blocking the turn. |
| 1204 | fn is_foreground_shell_wait(&self) -> bool { |
| 1205 | self.status.is_active() |
| 1206 | && self.source == ExecSource::Assistant |
| 1207 | && self.interaction.is_none() |
| 1208 | } |
| 1209 | |
| 1210 | #[cfg(test)] |
| 1211 | pub(super) fn render( |
| 1212 | &self, |
| 1213 | width: u16, |
| 1214 | low_motion: bool, |
| 1215 | mode: RenderMode, |
| 1216 | ) -> Vec<Line<'static>> { |
| 1217 | self.render_with_locale(width, low_motion, mode, Locale::En) |
| 1218 | } |
| 1219 | |
| 1220 | pub(super) fn render_with_locale( |
| 1221 | &self, |
| 1222 | width: u16, |
| 1223 | low_motion: bool, |
| 1224 | mode: RenderMode, |
| 1225 | locale: Locale, |
| 1226 | ) -> Vec<Line<'static>> { |
| 1227 | let mut lines = Vec::new(); |
| 1228 | let command_summary = command_header_summary(&self.command); |
| 1229 | // The header names the command, always. A long wait moves itself to |
| 1230 | // the background (see `execute_foreground_via_background`), so the |
| 1231 | // card never needs to advertise a key to rescue the turn. |
| 1232 | let header_summary = self |
| 1233 | .interaction |
| 1234 | .as_deref() |
| 1235 | .or(Some(command_summary.as_str())); |
| 1236 | let held_status = self.held_status(locale); |
| 1237 | let receipt = tool_receipt_label( |
| 1238 | crate::tui::widgets::tool_card::ToolFamily::Run, |
| 1239 | self.status, |
| 1240 | self.output.as_deref(), |
| 1241 | locale, |
| 1242 | ); |
| 1243 | let status_text = held_status.as_deref().map(Cow::Borrowed).unwrap_or(receipt); |
| 1244 | lines.push(render_tool_header_with_summary( |
| 1245 | "Shell", |
| 1246 | header_summary, |
| 1247 | if self.status == ToolStatus::Success || held_status.is_some() { |
| 1248 | Some(status_text.as_ref()) |
| 1249 | } else { |
| 1250 | None |
| 1251 | }, |
| 1252 | self.status, |
| 1253 | self.started_at, |
| 1254 | low_motion || held_status.is_some(), |
| 1255 | locale, |
| 1256 | )); |
| 1257 | |
| 1258 | lines.extend(self.description_lines(width, locale)); |
| 1259 | |
| 1260 | if mode != RenderMode::Source |
| 1261 | && self.interaction.is_none() |
| 1262 | && self.command.trim_end().lines().nth(1).is_some() |
| 1263 | && (self.is_foreground_shell_wait() |
| 1264 | || (mode == RenderMode::Live && self.status == ToolStatus::Success)) |
| 1265 | { |
| 1266 | lines.extend(render_command_mode( |
| 1267 | &self.command, |
| 1268 | width, |
| 1269 | mode, |
| 1270 | false, |
| 1271 | locale, |
| 1272 | )); |
| 1273 | } |
| 1274 | |
| 1275 | // A foreground shell wait stays a compact card — command, optional note, |
| 1276 | // spinner and running badge. Live output and artifact paths belong in the |
| 1277 | // Activity sidebar and `/jobs` detail surfaces. |
| 1278 | if self.is_foreground_shell_wait() && mode != RenderMode::Source { |
| 1279 | return wrap_card_rail(lines, self.status); |
| 1280 | } |
| 1281 | |
| 1282 | // Routine successes get a three-row glimpse (the opening row plus |
| 1283 | // two closing rows) so they take less space in the live transcript. |
| 1284 | // Failures and expanded display keep a larger bounded preview. |
| 1285 | if mode == RenderMode::Live |
| 1286 | && self |
| 1287 | .output |
| 1288 | .as_deref() |
| 1289 | .is_some_and(is_truncated_output_preview) |
| 1290 | { |
| 1291 | lines.push(render_spillover_annotation(width, locale)); |
| 1292 | return wrap_card_rail(lines, self.status); |
| 1293 | } |
| 1294 | if mode == RenderMode::Live && self.status == ToolStatus::Success { |
| 1295 | if self.interaction.is_none() |
| 1296 | && let Some(output) = self.output.as_ref().or(self.live_output.as_ref()) |
| 1297 | { |
| 1298 | lines.extend(render_exec_output_mode( |
| 1299 | output, |
| 1300 | width, |
| 1301 | TOOL_SUCCESS_OUTPUT_PREVIEW_LINES, |
| 1302 | mode, |
| 1303 | locale, |
| 1304 | true, |
| 1305 | )); |
| 1306 | } |
| 1307 | if let Some(duration_ms) = self.duration_ms |
| 1308 | && duration_ms >= 1000 |
| 1309 | { |
| 1310 | lines.extend(render_compact_kv( |
| 1311 | "time", |
| 1312 | &codewhale_command_contract::elapsed::format_elapsed_ms(duration_ms), |
| 1313 | Style::default().fg(palette::TEXT_DIM), |
| 1314 | width, |
| 1315 | )); |
| 1316 | } |
| 1317 | return wrap_card_rail(lines, self.status); |
| 1318 | } |
| 1319 | |
| 1320 | if self.status == ToolStatus::Success && self.source == ExecSource::User { |
| 1321 | lines.extend(render_compact_kv( |
| 1322 | "source", |
| 1323 | "started by you", |
| 1324 | Style::default().fg(palette::TEXT_MUTED), |
| 1325 | width, |
| 1326 | )); |
| 1327 | } |
| 1328 | |
| 1329 | if let Some(owner) = self |
| 1330 | .owner_agent_name |
| 1331 | .as_deref() |
| 1332 | .or(self.owner_agent_id.as_deref()) |
| 1333 | { |
| 1334 | lines.extend(render_compact_kv( |
| 1335 | "owner", |
| 1336 | owner, |
| 1337 | Style::default().fg(palette::TEXT_MUTED), |
| 1338 | width, |
| 1339 | )); |
| 1340 | } |
| 1341 | |
| 1342 | if mode == RenderMode::Source { |
| 1343 | lines.extend(render_command_mode( |
| 1344 | &self.command, |
| 1345 | width, |
| 1346 | mode, |
| 1347 | false, |
| 1348 | locale, |
| 1349 | )); |
| 1350 | } |
| 1351 | if let Some(interaction) = self.interaction.as_ref() { |
| 1352 | lines.extend(wrap_plain_line( |
| 1353 | &format!(" {interaction}"), |
| 1354 | Style::default().fg(palette::TEXT_MUTED), |
| 1355 | width, |
| 1356 | )); |
| 1357 | } else if mode != RenderMode::Source { |
| 1358 | lines.extend(render_command_mode( |
| 1359 | &self.command, |
| 1360 | width, |
| 1361 | mode, |
| 1362 | false, |
| 1363 | locale, |
| 1364 | )); |
| 1365 | } |
| 1366 | |
| 1367 | if self.interaction.is_none() || mode == RenderMode::Source { |
| 1368 | if let Some(output) = self.output.as_ref().or(self.live_output.as_ref()) { |
| 1369 | lines.extend(render_exec_output_mode( |
| 1370 | output, |
| 1371 | width, |
| 1372 | TOOL_OUTPUT_LINE_LIMIT, |
| 1373 | mode, |
| 1374 | locale, |
| 1375 | true, |
| 1376 | )); |
| 1377 | } else if !self.status.is_active() && mode != RenderMode::Live { |
| 1378 | // #3031: Suppress "(no output)" in compact/Live mode; |
| 1379 | // the success header is enough signal. |
| 1380 | lines.push(Line::from(Span::styled( |
| 1381 | " (no output)", |
| 1382 | Style::default().fg(palette::TEXT_MUTED).italic(), |
| 1383 | ))); |
| 1384 | } |
| 1385 | } |
| 1386 | |
| 1387 | if let Some(duration_ms) = self.duration_ms { |
| 1388 | // #3031: Suppress sub-second timing in compact mode. |
| 1389 | // Transcript mode always shows timing. |
| 1390 | if mode != RenderMode::Live || duration_ms >= 1000 { |
| 1391 | lines.extend(render_compact_kv( |
| 1392 | "time", |
| 1393 | &codewhale_command_contract::elapsed::format_elapsed_ms(duration_ms), |
| 1394 | Style::default().fg(palette::TEXT_DIM), |
| 1395 | width, |
| 1396 | )); |
| 1397 | } |
| 1398 | } |
| 1399 | |
| 1400 | wrap_card_rail(lines, self.status) |
| 1401 | } |
| 1402 | |
| 1403 | pub(super) fn render_calm( |
| 1404 | &self, |
| 1405 | width: u16, |
| 1406 | low_motion: bool, |
| 1407 | locale: Locale, |
| 1408 | ) -> Vec<Line<'static>> { |
| 1409 | let description = self.description_text(); |
| 1410 | let (mut lines, headline_clipped) = |
| 1411 | self.calm_header(description.as_deref(), width, low_motion, locale); |
| 1412 | let multi_line_command = self.command.trim_end().lines().nth(1).is_some(); |
| 1413 | |
| 1414 | if self.interaction.is_none() { |
| 1415 | let show_command = match self.status { |
| 1416 | ToolStatus::Failed => { |
| 1417 | description.is_some() || headline_clipped || multi_line_command |
| 1418 | } |
| 1419 | ToolStatus::Queued | ToolStatus::Running | ToolStatus::Success => { |
| 1420 | multi_line_command |
| 1421 | } |
| 1422 | ToolStatus::Hydrated | ToolStatus::Stopped | ToolStatus::Warning => false, |
| 1423 | }; |
| 1424 | if show_command { |
| 1425 | lines.extend(render_command_mode( |
| 1426 | &self.command, |
| 1427 | width, |
| 1428 | RenderMode::Live, |
| 1429 | true, |
| 1430 | locale, |
| 1431 | )); |
| 1432 | } else if description.is_some() { |
| 1433 | let more = if multi_line_command { " \u{2026}" } else { "" }; |
| 1434 | lines.push(render_card_detail_line_single( |
| 1435 | None, |
| 1436 | &truncate_text( |
| 1437 | &format!("$ {}{more}", command_header_summary(&self.command)), |
| 1438 | usize::from(width).saturating_sub(2), |
| 1439 | ), |
| 1440 | tool_value_style(), |
| 1441 | )); |
| 1442 | } |
| 1443 | } |
| 1444 | |
| 1445 | if self.is_foreground_shell_wait() { |
| 1446 | return lines; |
| 1447 | } |
| 1448 | if self |
| 1449 | .output |
| 1450 | .as_deref() |
| 1451 | .is_some_and(is_truncated_output_preview) |
| 1452 | { |
| 1453 | lines.push(render_spillover_annotation(width, locale)); |
| 1454 | return lines; |
| 1455 | } |
| 1456 | let output = self |
| 1457 | .interaction |
| 1458 | .is_none() |
| 1459 | .then(|| self.output.as_ref().or(self.live_output.as_ref())) |
| 1460 | .flatten(); |
| 1461 | if self.status == ToolStatus::Success { |
| 1462 | if let Some(output) = output { |
| 1463 | lines.extend(render_exec_output_mode( |
| 1464 | output, |
| 1465 | width, |
| 1466 | TOOL_SUCCESS_OUTPUT_PREVIEW_LINES, |
| 1467 | RenderMode::Live, |
| 1468 | locale, |
| 1469 | false, |
| 1470 | )); |
| 1471 | } |
| 1472 | return lines; |
| 1473 | } |
| 1474 | |
| 1475 | if let Some(owner) = self |
| 1476 | .owner_agent_name |
| 1477 | .as_deref() |
| 1478 | .or(self.owner_agent_id.as_deref()) |
| 1479 | { |
| 1480 | lines.extend(render_compact_kv( |
| 1481 | "owner", |
| 1482 | owner, |
| 1483 | Style::default().fg(palette::TEXT_MUTED), |
| 1484 | width, |
| 1485 | )); |
| 1486 | } |
| 1487 | if let Some(interaction) = self.interaction.as_ref() |
| 1488 | && headline_clipped |
| 1489 | { |
| 1490 | lines.extend(wrap_plain_line( |
| 1491 | &format!(" {interaction}"), |
| 1492 | Style::default().fg(palette::TEXT_MUTED), |
| 1493 | width, |
| 1494 | )); |
| 1495 | } |
| 1496 | if let Some(output) = output { |
| 1497 | lines.extend(render_exec_output_mode( |
| 1498 | output, |
| 1499 | width, |
| 1500 | TOOL_OUTPUT_LINE_LIMIT, |
| 1501 | RenderMode::Live, |
| 1502 | locale, |
| 1503 | false, |
| 1504 | )); |
| 1505 | } |
| 1506 | lines |
| 1507 | } |
| 1508 | |
| 1509 | fn calm_header( |
| 1510 | &self, |
| 1511 | description: Option<&str>, |
| 1512 | width: u16, |
| 1513 | low_motion: bool, |
| 1514 | locale: Locale, |
| 1515 | ) -> (Vec<Line<'static>>, bool) { |
| 1516 | let family = crate::tui::widgets::tool_card::ToolFamily::Run; |
| 1517 | let held = self.held_status(locale); |
| 1518 | let mark = format!( |
| 1519 | "{} ", |
| 1520 | status_symbol( |
| 1521 | self.started_at, |
| 1522 | self.status, |
| 1523 | low_motion || held.is_some(), |
| 1524 | family |
| 1525 | ) |
| 1526 | ); |
| 1527 | let (headline, headline_style) = if let Some(interaction) = self |
| 1528 | .interaction |
| 1529 | .as_deref() |
| 1530 | .and_then(normalize_header_summary) |
| 1531 | { |
| 1532 | (interaction, tool_title_style(self.status)) |
| 1533 | } else if let Some(description) = description { |
| 1534 | ( |
| 1535 | description.to_string(), |
| 1536 | tool_title_style(self.status).italic(), |
| 1537 | ) |
| 1538 | } else { |
| 1539 | let more = if self.command.trim_end().lines().nth(1).is_some() { |
| 1540 | " \u{2026}" |
| 1541 | } else { |
| 1542 | "" |
| 1543 | }; |
| 1544 | ( |
| 1545 | format!("$ {}{more}", command_header_summary(&self.command)), |
| 1546 | tool_title_style(self.status), |
| 1547 | ) |
| 1548 | }; |
| 1549 | |
| 1550 | let separator = Style::default().fg(palette::TEXT_DIM); |
| 1551 | let running_elapsed = (held.is_none() && self.status == ToolStatus::Running) |
| 1552 | .then(|| self.started_at.and_then(running_elapsed_label)) |
| 1553 | .flatten(); |
| 1554 | let state = held.or_else(|| match self.status { |
| 1555 | ToolStatus::Success => None, |
| 1556 | status => Some(tool_status_label(status, locale).to_string()), |
| 1557 | }); |
| 1558 | let mut suffix = Vec::new(); |
| 1559 | if let Some(state) = state { |
| 1560 | suffix.push(Span::styled(" \u{00B7} ", separator)); |
| 1561 | suffix.push(Span::styled(state, tool_status_style(self.status, family))); |
| 1562 | } |
| 1563 | if let Some(elapsed) = running_elapsed { |
| 1564 | suffix.push(Span::styled(format!(" {elapsed}"), separator)); |
| 1565 | } |
| 1566 | if let Some(duration) = self.finished_duration() { |
| 1567 | suffix.push(Span::styled(" \u{00B7} ", separator)); |
| 1568 | suffix.push(Span::styled(duration, separator)); |
| 1569 | } |
| 1570 | |
| 1571 | let mark_width = UnicodeWidthStr::width(mark.as_str()); |
| 1572 | let inline_budget = usize::from(width) |
| 1573 | .saturating_sub(mark_width + suffix.iter().map(Span::width).sum::<usize>()); |
| 1574 | let state_row = !suffix.is_empty() |
| 1575 | && inline_budget |
| 1576 | < codewhale_tui_kit::ui_text::text_display_width(&headline) |
| 1577 | .min(CALM_HEADLINE_MIN_WIDTH); |
| 1578 | let budget = if state_row { |
| 1579 | usize::from(width).saturating_sub(mark_width) |
| 1580 | } else { |
| 1581 | inline_budget |
| 1582 | } |
| 1583 | .min(TOOL_HEADER_SUMMARY_LIMIT); |
| 1584 | let shown = truncate_text(&headline, budget); |
| 1585 | let clipped = shown != headline; |
| 1586 | |
| 1587 | let mut spans = vec![ |
| 1588 | Span::styled( |
| 1589 | mark, |
| 1590 | Style::default().fg(tool_glyph_color(self.status, family)), |
| 1591 | ), |
| 1592 | Span::styled(shown, headline_style), |
| 1593 | ]; |
| 1594 | if state_row { |
| 1595 | suffix.remove(0); |
| 1596 | (vec![Line::from(spans), Line::from(suffix)], clipped) |
| 1597 | } else { |
| 1598 | spans.extend(suffix); |
| 1599 | (vec![Line::from(spans)], clipped) |
| 1600 | } |
| 1601 | } |
| 1602 | |
| 1603 | fn held_status(&self, locale: Locale) -> Option<String> { |
| 1604 | match (self.waiting, self.status) { |
| 1605 | (Some(ExecWait::Approval), status) if status.is_active() => Some( |
| 1606 | codewhale_localization::tr( |
| 1607 | locale, |
| 1608 | codewhale_localization::MessageId::ToolStatusWaitingForApproval, |
| 1609 | ) |
| 1610 | .into_owned(), |
| 1611 | ), |
| 1612 | _ => self |
| 1613 | .stale_elapsed_since_output_ms |
| 1614 | .map(|ms| stale_shell_status_label(ms, locale)), |
| 1615 | } |
| 1616 | } |
| 1617 | |
| 1618 | fn description_text(&self) -> Option<String> { |
| 1619 | let mut plain = String::new(); |
| 1620 | codewhale_sanitize::sanitize::strip_ansi_into(self.description.as_deref()?, &mut plain); |
| 1621 | normalize_header_summary(&plain) |
| 1622 | } |
| 1623 | |
| 1624 | fn description_lines(&self, width: u16, locale: Locale) -> Vec<Line<'static>> { |
| 1625 | let Some(description) = self.description_text() else { |
| 1626 | return Vec::new(); |
| 1627 | }; |
| 1628 | let label = codewhale_localization::tr( |
| 1629 | locale, |
| 1630 | codewhale_localization::MessageId::ToolDescriptionNote, |
| 1631 | ); |
| 1632 | render_card_detail_line( |
| 1633 | Some(label.as_ref()), |
| 1634 | &truncate_text(&description, TOOL_HEADER_SUMMARY_LIMIT), |
| 1635 | Style::default().fg(palette::TEXT_MUTED).italic(), |
| 1636 | width, |
| 1637 | ) |
| 1638 | } |
| 1639 | |
| 1640 | fn finished_duration(&self) -> Option<String> { |
| 1641 | if self.status.is_active() { |
| 1642 | return None; |
| 1643 | } |
| 1644 | self.duration_ms |
| 1645 | .filter(|duration_ms| *duration_ms >= 1000) |
| 1646 | .map(codewhale_command_contract::elapsed::format_elapsed_ms) |
| 1647 | } |
| 1648 | } |
| 1649 | |
| 1650 | /// Source of a shell command execution. |
| 1651 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1652 | pub enum ExecSource { |
| 1653 | User, |
| 1654 | Assistant, |
| 1655 | } |
| 1656 | |
| 1657 | /// Aggregate cell for tool exploration runs. |
| 1658 | #[derive(Debug, Clone)] |
| 1659 | pub struct ExploringCell { |
| 1660 | pub entries: Vec<ExploringEntry>, |
| 1661 | } |
| 1662 | |
| 1663 | impl ExploringCell { |
| 1664 | /// The cell's own lifecycle state, rolled up from its parallel entries. |
| 1665 | /// |
| 1666 | /// One derivation, used by the card header, by [`ToolCell::status`], and by |
| 1667 | /// the Activity surfaces — three copies of this fold had drifted apart, and |
| 1668 | /// the header's copy could not produce `Failed` at all, so a fan-out with a |
| 1669 | /// failed read painted itself `done` in the success colour. |
| 1670 | /// |
| 1671 | /// Precedence: any entry still running keeps the whole cell running; after |
| 1672 | /// that the loudest terminal state wins, so a single failure is never |
| 1673 | /// averaged away by its successful siblings. |
| 1674 | #[must_use] |
| 1675 | pub fn status(&self) -> ToolStatus { |
| 1676 | let any = |wanted: ToolStatus| self.entries.iter().any(|entry| entry.status == wanted); |
| 1677 | if any(ToolStatus::Running) { |
| 1678 | ToolStatus::Running |
| 1679 | } else if any(ToolStatus::Queued) { |
| 1680 | ToolStatus::Queued |
| 1681 | } else if any(ToolStatus::Failed) { |
| 1682 | ToolStatus::Failed |
| 1683 | } else if any(ToolStatus::Warning) { |
| 1684 | ToolStatus::Warning |
| 1685 | } else if any(ToolStatus::Stopped) { |
| 1686 | ToolStatus::Stopped |
| 1687 | } else if any(ToolStatus::Hydrated) { |
| 1688 | ToolStatus::Hydrated |
| 1689 | } else { |
| 1690 | ToolStatus::Success |
| 1691 | } |
| 1692 | } |
| 1693 | |
| 1694 | /// Render the exploring cell into lines. |
| 1695 | #[cfg(test)] |
| 1696 | pub fn lines_with_motion(&self, width: u16, low_motion: bool) -> Vec<Line<'static>> { |
| 1697 | self.lines_with_motion_and_locale(width, low_motion, Locale::En) |
| 1698 | } |
| 1699 | |
| 1700 | #[cfg(test)] |
| 1701 | pub fn lines_with_motion_and_locale( |
| 1702 | &self, |
| 1703 | width: u16, |
| 1704 | low_motion: bool, |
| 1705 | locale: Locale, |
| 1706 | ) -> Vec<Line<'static>> { |
| 1707 | self.render_with_locale(width, low_motion, RenderMode::Live, locale) |
| 1708 | } |
| 1709 | |
| 1710 | pub(super) fn render_with_locale( |
| 1711 | &self, |
| 1712 | width: u16, |
| 1713 | low_motion: bool, |
| 1714 | mode: RenderMode, |
| 1715 | locale: Locale, |
| 1716 | ) -> Vec<Line<'static>> { |
| 1717 | let mut lines = Vec::new(); |
| 1718 | let status = self.status(); |
| 1719 | let header_summary = exploring_header_summary(&self.entries); |
| 1720 | let multi_entry = self.entries.len() > 1; |
| 1721 | let header_state: Option<Cow<'static, str>> = (status == ToolStatus::Success).then(|| { |
| 1722 | if multi_entry { |
| 1723 | Cow::Borrowed("") |
| 1724 | } else { |
| 1725 | codewhale_localization::tr( |
| 1726 | locale, |
| 1727 | codewhale_localization::MessageId::ToolReceiptDone, |
| 1728 | ) |
| 1729 | } |
| 1730 | }); |
| 1731 | // Search-only exploration cards read with the `find` verb so a |
| 1732 | // completed grep renders `find done · Searching for …` instead of the |
| 1733 | // incoherent `read done · Searching …` (#4145). Read/list or mixed |
| 1734 | // cards keep the neutral `read` verb the Workspace card has always used. |
| 1735 | let family = exploring_card_family(&self.entries); |
| 1736 | let header = render_tool_header_with_family_and_summary( |
| 1737 | family, |
| 1738 | header_summary.as_deref(), |
| 1739 | header_state.as_deref(), |
| 1740 | status, |
| 1741 | None, |
| 1742 | low_motion, |
| 1743 | locale, |
| 1744 | ); |
| 1745 | let header_shows_label = !multi_entry |
| 1746 | && header_summary |
| 1747 | .as_deref() |
| 1748 | .is_some_and(|label| header_shows_in_full(&header, label, usize::from(width))); |
| 1749 | lines.push(header); |
| 1750 | |
| 1751 | // Dot-grid status strip — one glyph per entry, showing parallel |
| 1752 | // fanout at a glance: ●=done ◐=running ✕=failed. |
| 1753 | if self.entries.len() > 1 { |
| 1754 | let (done, running, failed, stopped) = self.entries.iter().fold( |
| 1755 | (0usize, 0usize, 0usize, 0usize), |
| 1756 | |(d, r, f, s), e| match e.status { |
| 1757 | ToolStatus::Success | ToolStatus::Hydrated => (d + 1, r, f, s), |
| 1758 | ToolStatus::Warning | ToolStatus::Failed => (d, r, f + 1, s), |
| 1759 | ToolStatus::Queued | ToolStatus::Running => (d, r + 1, f, s), |
| 1760 | ToolStatus::Stopped => (d, r, f, s + 1), |
| 1761 | }, |
| 1762 | ); |
| 1763 | // Each dot carries its own entry's state. Painting the strip one |
| 1764 | // flat colour made a failed parallel read indistinguishable from a |
| 1765 | // finished one, which is exactly the narration the cell is |
| 1766 | // supposed to make unnecessary. |
| 1767 | let mut dot_spans: Vec<Span<'static>> = vec![Span::raw(" ")]; |
| 1768 | dot_spans.extend(self.entries.iter().map(|e| { |
| 1769 | let glyph = match e.status { |
| 1770 | ToolStatus::Success | ToolStatus::Hydrated => "\u{25CF}", |
| 1771 | ToolStatus::Warning => "!", |
| 1772 | ToolStatus::Queued | ToolStatus::Stopped => codewhale_tui_kit::glyphs::NEUTRAL, |
| 1773 | ToolStatus::Running => "\u{25D0}", |
| 1774 | ToolStatus::Failed => "\u{2715}", |
| 1775 | }; |
| 1776 | Span::styled( |
| 1777 | glyph, |
| 1778 | Style::default().fg(tool_glyph_color(e.status, family)), |
| 1779 | ) |
| 1780 | })); |
| 1781 | let counts = [ |
| 1782 | (done, codewhale_localization::MessageId::WorkflowCountDone), |
| 1783 | ( |
| 1784 | running, |
| 1785 | codewhale_localization::MessageId::WorkflowCountRunning, |
| 1786 | ), |
| 1787 | ( |
| 1788 | failed, |
| 1789 | codewhale_localization::MessageId::WorkflowCountFailed, |
| 1790 | ), |
| 1791 | ( |
| 1792 | stopped, |
| 1793 | codewhale_localization::MessageId::WorkflowCountCancelled, |
| 1794 | ), |
| 1795 | ] |
| 1796 | .into_iter() |
| 1797 | .filter(|(count, _)| *count > 0) |
| 1798 | .map(|(count, id)| { |
| 1799 | codewhale_localization::tr(locale, id).replace("{count}", &count.to_string()) |
| 1800 | }) |
| 1801 | .collect::<Vec<_>>() |
| 1802 | .join(", "); |
| 1803 | dot_spans.push(Span::styled( |
| 1804 | format!(" {counts}"), |
| 1805 | Style::default().fg(tool_glyph_color(status, family)), |
| 1806 | )); |
| 1807 | lines.push(Line::from(dot_spans)); |
| 1808 | } |
| 1809 | |
| 1810 | for entry in &self.entries { |
| 1811 | if multi_entry { |
| 1812 | lines.extend(render_card_detail_line( |
| 1813 | None, |
| 1814 | &entry.label, |
| 1815 | tool_value_style(), |
| 1816 | width, |
| 1817 | )); |
| 1818 | } else if !header_shows_label { |
| 1819 | let prefix = tool_status_label(entry.status, locale); |
| 1820 | lines.extend(render_compact_kv( |
| 1821 | &prefix, |
| 1822 | &entry.label, |
| 1823 | tool_value_style(), |
| 1824 | width, |
| 1825 | )); |
| 1826 | } |
| 1827 | if let Some(error) = entry.error.as_deref() { |
| 1828 | if multi_entry { |
| 1829 | if let Some(reason) = error.lines().map(str::trim).find(|line| !line.is_empty()) |
| 1830 | { |
| 1831 | lines.extend(render_card_detail_line( |
| 1832 | None, |
| 1833 | reason, |
| 1834 | tool_value_style(), |
| 1835 | width, |
| 1836 | )); |
| 1837 | } |
| 1838 | } else { |
| 1839 | lines.extend(render_tool_output_mode( |
| 1840 | error, |
| 1841 | width, |
| 1842 | TOOL_FAILURE_PREVIEW_LINES, |
| 1843 | mode, |
| 1844 | locale, |
| 1845 | )); |
| 1846 | } |
| 1847 | } |
| 1848 | } |
| 1849 | lines |
| 1850 | } |
| 1851 | } |
| 1852 | |
| 1853 | /// Single entry for exploring tool output. |
| 1854 | #[derive(Debug, Clone)] |
| 1855 | pub struct ExploringEntry { |
| 1856 | pub label: String, |
| 1857 | pub search: bool, |
| 1858 | pub status: ToolStatus, |
| 1859 | pub error: Option<String>, |
| 1860 | } |
| 1861 | |
| 1862 | /// Calm outcome and exact evidence for a structured File mutation. |
| 1863 | #[derive(Debug, Clone)] |
| 1864 | pub struct PatchSummaryCell { |
| 1865 | pub path: String, |
| 1866 | pub summary: String, |
| 1867 | pub status: ToolStatus, |
| 1868 | pub error: Option<String>, |
| 1869 | pub receipt: Option<FileMutationReceipt>, |
| 1870 | } |
| 1871 | |
| 1872 | impl PatchSummaryCell { |
| 1873 | pub(super) fn render( |
| 1874 | &self, |
| 1875 | width: u16, |
| 1876 | low_motion: bool, |
| 1877 | mode: RenderMode, |
| 1878 | inline_diff_mode: codewhale_runtime::settings::InlineDiffMode, |
| 1879 | locale: Locale, |
| 1880 | ) -> Vec<Line<'static>> { |
| 1881 | let mut lines = Vec::new(); |
| 1882 | let header_summary = self |
| 1883 | .receipt |
| 1884 | .as_ref() |
| 1885 | .map(|receipt| { |
| 1886 | if inline_diff_mode == codewhale_runtime::settings::InlineDiffMode::Off { |
| 1887 | receipt.outcome_label(locale) |
| 1888 | } else { |
| 1889 | receipt.semantic_summary(locale) |
| 1890 | } |
| 1891 | }) |
| 1892 | .unwrap_or_else(|| self.path.clone()); |
| 1893 | lines.push(render_tool_header_with_summary( |
| 1894 | "File", |
| 1895 | Some(&header_summary), |
| 1896 | None, |
| 1897 | self.status, |
| 1898 | None, |
| 1899 | low_motion, |
| 1900 | locale, |
| 1901 | )); |
| 1902 | if self.status == ToolStatus::Success |
| 1903 | && let Some(receipt) = self.receipt.as_ref() |
| 1904 | { |
| 1905 | if mode == RenderMode::Source { |
| 1906 | lines.push(Line::from(receipt.inspect_text(locale))); |
| 1907 | } else { |
| 1908 | lines.extend(receipt.render_inline(width, inline_diff_mode, locale)); |
| 1909 | } |
| 1910 | } else { |
| 1911 | lines.extend(render_compact_kv( |
| 1912 | "file", |
| 1913 | &self.path, |
| 1914 | tool_value_style(), |
| 1915 | width, |
| 1916 | )); |
| 1917 | lines.extend(render_tool_output_mode( |
| 1918 | &self.summary, |
| 1919 | width, |
| 1920 | TOOL_COMMAND_LINE_LIMIT, |
| 1921 | mode, |
| 1922 | locale, |
| 1923 | )); |
| 1924 | } |
| 1925 | if let Some(error) = self.error.as_ref() { |
| 1926 | lines.extend(render_tool_output_mode( |
| 1927 | error, |
| 1928 | width, |
| 1929 | TOOL_COMMAND_LINE_LIMIT, |
| 1930 | mode, |
| 1931 | locale, |
| 1932 | )); |
| 1933 | } |
| 1934 | lines |
| 1935 | } |
| 1936 | } |
| 1937 | |
| 1938 | /// Cell for structured review output. |
| 1939 | #[derive(Debug, Clone)] |
| 1940 | pub struct ReviewCell { |
| 1941 | pub target: String, |
| 1942 | pub status: ToolStatus, |
| 1943 | pub output: Option<ReviewOutput>, |
| 1944 | pub error: Option<String>, |
| 1945 | } |
| 1946 | |
| 1947 | impl ReviewCell { |
| 1948 | pub(super) fn render( |
| 1949 | &self, |
| 1950 | width: u16, |
| 1951 | low_motion: bool, |
| 1952 | mode: RenderMode, |
| 1953 | locale: Locale, |
| 1954 | ) -> Vec<Line<'static>> { |
| 1955 | let mut lines = Vec::new(); |
| 1956 | lines.push(render_tool_header( |
| 1957 | "Review", |
| 1958 | None, |
| 1959 | self.status, |
| 1960 | None, |
| 1961 | low_motion, |
| 1962 | locale, |
| 1963 | )); |
| 1964 | |
| 1965 | if !self.target.trim().is_empty() { |
| 1966 | lines.extend(render_compact_kv( |
| 1967 | "target", |
| 1968 | self.target.trim(), |
| 1969 | tool_value_style(), |
| 1970 | width, |
| 1971 | )); |
| 1972 | } |
| 1973 | |
| 1974 | if self.status.is_active() { |
| 1975 | return lines; |
| 1976 | } |
| 1977 | |
| 1978 | if let Some(error) = self.error.as_ref() { |
| 1979 | lines.extend(render_tool_output_mode( |
| 1980 | error, |
| 1981 | width, |
| 1982 | TOOL_COMMAND_LINE_LIMIT, |
| 1983 | mode, |
| 1984 | locale, |
| 1985 | )); |
| 1986 | return lines; |
| 1987 | } |
| 1988 | |
| 1989 | let Some(output) = self.output.as_ref() else { |
| 1990 | return lines; |
| 1991 | }; |
| 1992 | |
| 1993 | if !output.summary.trim().is_empty() { |
| 1994 | lines.extend(wrap_plain_line( |
| 1995 | &format!("Summary: {}", output.summary.trim()), |
| 1996 | Style::default().fg(palette::TEXT_PRIMARY), |
| 1997 | width, |
| 1998 | )); |
| 1999 | } |
| 2000 | |
| 2001 | lines.push(Line::from("")); |
| 2002 | lines.push(Line::from(Span::styled( |
| 2003 | "Issues", |
| 2004 | Style::default() |
| 2005 | .fg(palette::WHALE_ACTION) |
| 2006 | .add_modifier(Modifier::BOLD), |
| 2007 | ))); |
| 2008 | if output.issues.is_empty() { |
| 2009 | lines.extend(wrap_plain_line( |
| 2010 | " (none)", |
| 2011 | Style::default().fg(palette::TEXT_MUTED), |
| 2012 | width, |
| 2013 | )); |
| 2014 | } else { |
| 2015 | for issue in &output.issues { |
| 2016 | let severity = issue.severity.trim().to_ascii_lowercase(); |
| 2017 | let color = review_severity_color(&severity); |
| 2018 | let location = format_review_location(issue.path.as_ref(), issue.line); |
| 2019 | let label = if location.is_empty() { |
| 2020 | format!(" - [{}] {}", severity, issue.title.trim()) |
| 2021 | } else { |
| 2022 | format!(" - [{}] {} ({})", severity, issue.title.trim(), location) |
| 2023 | }; |
| 2024 | lines.extend(wrap_plain_line(&label, Style::default().fg(color), width)); |
| 2025 | if !issue.description.trim().is_empty() { |
| 2026 | lines.extend(wrap_plain_line( |
| 2027 | &format!(" {}", issue.description.trim()), |
| 2028 | Style::default().fg(palette::TEXT_MUTED), |
| 2029 | width, |
| 2030 | )); |
| 2031 | } |
| 2032 | } |
| 2033 | } |
| 2034 | |
| 2035 | lines.push(Line::from("")); |
| 2036 | lines.push(Line::from(Span::styled( |
| 2037 | "Suggestions", |
| 2038 | Style::default() |
| 2039 | .fg(palette::WHALE_ACTION) |
| 2040 | .add_modifier(Modifier::BOLD), |
| 2041 | ))); |
| 2042 | if output.suggestions.is_empty() { |
| 2043 | lines.extend(wrap_plain_line( |
| 2044 | " (none)", |
| 2045 | Style::default().fg(palette::TEXT_MUTED), |
| 2046 | width, |
| 2047 | )); |
| 2048 | } else { |
| 2049 | for suggestion in &output.suggestions { |
| 2050 | let location = format_review_location(suggestion.path.as_ref(), suggestion.line); |
| 2051 | let label = if location.is_empty() { |
| 2052 | format!(" - {}", suggestion.suggestion.trim()) |
| 2053 | } else { |
| 2054 | format!(" - {} ({})", suggestion.suggestion.trim(), location) |
| 2055 | }; |
| 2056 | lines.extend(wrap_plain_line( |
| 2057 | &label, |
| 2058 | Style::default().fg(palette::TEXT_PRIMARY), |
| 2059 | width, |
| 2060 | )); |
| 2061 | } |
| 2062 | } |
| 2063 | |
| 2064 | if !output.overall_assessment.trim().is_empty() { |
| 2065 | lines.push(Line::from("")); |
| 2066 | lines.extend(wrap_plain_line( |
| 2067 | &format!("Overall: {}", output.overall_assessment.trim()), |
| 2068 | Style::default().fg(palette::TEXT_PRIMARY), |
| 2069 | width, |
| 2070 | )); |
| 2071 | } |
| 2072 | |
| 2073 | lines |
| 2074 | } |
| 2075 | } |
| 2076 | |
| 2077 | /// Cell representing an MCP tool execution. |
| 2078 | #[derive(Debug, Clone)] |
| 2079 | pub struct McpToolCell { |
| 2080 | pub tool: String, |
| 2081 | pub status: ToolStatus, |
| 2082 | pub content: Option<String>, |
| 2083 | pub is_image: bool, |
| 2084 | } |
| 2085 | |
| 2086 | impl McpToolCell { |
| 2087 | pub(super) fn render( |
| 2088 | &self, |
| 2089 | width: u16, |
| 2090 | low_motion: bool, |
| 2091 | mode: RenderMode, |
| 2092 | locale: Locale, |
| 2093 | ) -> Vec<Line<'static>> { |
| 2094 | let mut lines = Vec::new(); |
| 2095 | lines.push(render_tool_header_with_summary( |
| 2096 | "Tool", |
| 2097 | Some(&self.tool), |
| 2098 | None, |
| 2099 | self.status, |
| 2100 | None, |
| 2101 | low_motion, |
| 2102 | locale, |
| 2103 | )); |
| 2104 | |
| 2105 | if self.is_image { |
| 2106 | lines.extend(render_compact_kv( |
| 2107 | "result", |
| 2108 | "image", |
| 2109 | tool_value_style(), |
| 2110 | width, |
| 2111 | )); |
| 2112 | } |
| 2113 | |
| 2114 | if let Some(content) = self.content.as_ref() { |
| 2115 | if mode == RenderMode::Live && is_truncated_output_preview(content) { |
| 2116 | lines.push(render_spillover_annotation(width, locale)); |
| 2117 | return lines; |
| 2118 | } |
| 2119 | lines.extend(render_tool_output_mode( |
| 2120 | content, |
| 2121 | width, |
| 2122 | if self.status == ToolStatus::Failed { |
| 2123 | TOOL_FAILURE_PREVIEW_LINES |
| 2124 | } else { |
| 2125 | TOOL_COMMAND_LINE_LIMIT |
| 2126 | }, |
| 2127 | mode, |
| 2128 | locale, |
| 2129 | )); |
| 2130 | } |
| 2131 | lines |
| 2132 | } |
| 2133 | } |
| 2134 | |
| 2135 | /// Cell for image view actions. |
| 2136 | #[derive(Debug, Clone)] |
| 2137 | pub struct ViewImageCell { |
| 2138 | pub path: PathBuf, |
| 2139 | } |
| 2140 | |
| 2141 | impl ViewImageCell { |
| 2142 | /// Render the image view cell into lines. |
| 2143 | pub fn lines_with_motion_and_locale( |
| 2144 | &self, |
| 2145 | width: u16, |
| 2146 | low_motion: bool, |
| 2147 | locale: Locale, |
| 2148 | ) -> Vec<Line<'static>> { |
| 2149 | let path = self.path.display().to_string(); |
| 2150 | let header = render_tool_header_with_summary( |
| 2151 | "Image", |
| 2152 | Some(&path), |
| 2153 | None, |
| 2154 | ToolStatus::Success, |
| 2155 | None, |
| 2156 | low_motion, |
| 2157 | locale, |
| 2158 | ); |
| 2159 | let header_shows_path = header_shows_in_full(&header, &path, usize::from(width)); |
| 2160 | let mut lines = vec![header]; |
| 2161 | if !header_shows_path { |
| 2162 | lines.extend(render_compact_kv("path", &path, tool_value_style(), width)); |
| 2163 | } |
| 2164 | lines |
| 2165 | } |
| 2166 | } |
| 2167 | |
| 2168 | /// Cell for web search tool output. |
| 2169 | #[derive(Debug, Clone)] |
| 2170 | pub struct WebSearchCell { |
| 2171 | pub query: String, |
| 2172 | pub status: ToolStatus, |
| 2173 | pub summary: Option<String>, |
| 2174 | pub source: Option<String>, |
| 2175 | pub degraded: Option<String>, |
| 2176 | pub ref_count: usize, |
| 2177 | } |
| 2178 | |
| 2179 | impl WebSearchCell { |
| 2180 | /// Render the web search cell into lines. |
| 2181 | #[cfg(test)] |
| 2182 | pub fn lines_with_motion(&self, width: u16, low_motion: bool) -> Vec<Line<'static>> { |
| 2183 | self.lines_with_motion_and_locale(width, low_motion, Locale::En) |
| 2184 | } |
| 2185 | |
| 2186 | pub fn lines_with_motion_and_locale( |
| 2187 | &self, |
| 2188 | width: u16, |
| 2189 | low_motion: bool, |
| 2190 | locale: Locale, |
| 2191 | ) -> Vec<Line<'static>> { |
| 2192 | let mut lines = Vec::new(); |
| 2193 | let header = render_tool_header_with_summary( |
| 2194 | "Search", |
| 2195 | Some(&self.query), |
| 2196 | None, |
| 2197 | self.status, |
| 2198 | None, |
| 2199 | low_motion, |
| 2200 | locale, |
| 2201 | ); |
| 2202 | let header_shows_query = header_shows_in_full(&header, &self.query, usize::from(width)); |
| 2203 | lines.push(header); |
| 2204 | if !header_shows_query { |
| 2205 | lines.extend(render_compact_kv( |
| 2206 | "query", |
| 2207 | &self.query, |
| 2208 | tool_value_style(), |
| 2209 | width, |
| 2210 | )); |
| 2211 | } |
| 2212 | if let Some(source) = self.source.as_ref() { |
| 2213 | lines.extend(render_compact_kv( |
| 2214 | "source", |
| 2215 | source, |
| 2216 | tool_value_style(), |
| 2217 | width, |
| 2218 | )); |
| 2219 | } |
| 2220 | if let Some(degraded) = self.degraded.as_ref() { |
| 2221 | lines.extend(render_compact_kv( |
| 2222 | "degraded", |
| 2223 | degraded, |
| 2224 | tool_value_style(), |
| 2225 | width, |
| 2226 | )); |
| 2227 | } |
| 2228 | if self.ref_count > 0 { |
| 2229 | lines.extend(render_compact_kv( |
| 2230 | "citations", |
| 2231 | &self.ref_count.to_string(), |
| 2232 | tool_value_style(), |
| 2233 | width, |
| 2234 | )); |
| 2235 | } |
| 2236 | if let Some(summary) = self.summary.as_ref() { |
| 2237 | lines.extend(render_compact_kv( |
| 2238 | "result", |
| 2239 | summary, |
| 2240 | tool_value_style(), |
| 2241 | width, |
| 2242 | )); |
| 2243 | } |
| 2244 | lines |
| 2245 | } |
| 2246 | } |
| 2247 | |
| 2248 | /// Generic cell for tool output when no specialized rendering exists. |
| 2249 | #[derive(Debug, Clone)] |
| 2250 | pub struct GenericToolCell { |
| 2251 | pub name: String, |
| 2252 | pub status: ToolStatus, |
| 2253 | pub input_summary: Option<String>, |
| 2254 | pub output: Option<String>, |
| 2255 | /// Optional list of per-child prompts. When populated (by any future |
| 2256 | /// fan-out tool), each prompt is shown on its own indented row instead |
| 2257 | /// of the inline `args:` summary. `None` for ordinary tools. |
| 2258 | pub prompts: Option<Vec<String>>, |
| 2259 | /// Filesystem path to the full output's spillover file (#422/#423). |
| 2260 | /// Set by the tool-routing layer when `ToolResult.metadata` carried a |
| 2261 | /// `spillover_path` field. The truncation affordance includes the |
| 2262 | /// path so the user can `read_file` it (or Cmd+click in |
| 2263 | /// OSC 8-aware terminals — the path renders as a hyperlink when |
| 2264 | /// `tui.osc8_links` is enabled). |
| 2265 | pub spillover_path: Option<std::path::PathBuf>, |
| 2266 | // --- Pre-computed render cache (populated once at cell creation) --- |
| 2267 | /// Cached output summary — avoids re-parsing JSON every frame. |
| 2268 | pub output_summary: Option<String>, |
| 2269 | /// Whether the output looks like a unified diff (cached after first check). |
| 2270 | pub is_diff: bool, |
| 2271 | } |
| 2272 | |
| 2273 | fn should_show_raw_tool_name( |
| 2274 | name: &str, |
| 2275 | family: crate::tui::widgets::tool_card::ToolFamily, |
| 2276 | mode: RenderMode, |
| 2277 | ) -> bool { |
| 2278 | !matches!(mode, RenderMode::Live) |
| 2279 | || matches!(family, crate::tui::widgets::tool_card::ToolFamily::Generic) |
| 2280 | || name.starts_with("mcp_") |
| 2281 | } |
| 2282 | |
| 2283 | fn execute_tools_header_summary(output: &str) -> Option<String> { |
| 2284 | let value: serde_json::Value = serde_json::from_str(output).ok()?; |
| 2285 | let calls = codewhale_engine::receipts::parse_nested_calls(&value); |
| 2286 | if calls.is_empty() { |
| 2287 | return None; |
| 2288 | } |
| 2289 | let mut tool_counts: Vec<(&str, usize)> = Vec::new(); |
| 2290 | for call in &calls { |
| 2291 | if let Some((_, count)) = tool_counts |
| 2292 | .iter_mut() |
| 2293 | .find(|(name, _)| *name == call.tool.as_str()) |
| 2294 | { |
| 2295 | *count += 1; |
| 2296 | } else { |
| 2297 | tool_counts.push((call.tool.as_str(), 1)); |
| 2298 | } |
| 2299 | } |
| 2300 | let tool_list = tool_counts |
| 2301 | .iter() |
| 2302 | .map(|(name, count)| { |
| 2303 | if *count > 1 { |
| 2304 | format!("{name} x{count}") |
| 2305 | } else { |
| 2306 | (*name).to_string() |
| 2307 | } |
| 2308 | }) |
| 2309 | .collect::<Vec<_>>() |
| 2310 | .join(", "); |
| 2311 | let failed = calls.iter().filter(|call| !call.ok).count(); |
| 2312 | let total = calls.len(); |
| 2313 | let call_word = if total == 1 { "call" } else { "calls" }; |
| 2314 | if failed > 0 { |
| 2315 | Some(format!( |
| 2316 | "{total} {call_word}: {tool_list} · {failed} failed" |
| 2317 | )) |
| 2318 | } else { |
| 2319 | Some(format!("{total} {call_word}: {tool_list}")) |
| 2320 | } |
| 2321 | } |
| 2322 | |
| 2323 | fn format_execute_tools_failure(output: &str) -> Option<String> { |
| 2324 | let value: serde_json::Value = serde_json::from_str(output).ok()?; |
| 2325 | let obj = value.as_object()?; |
| 2326 | let body_error = obj |
| 2327 | .get("body") |
| 2328 | .and_then(|body| body.get("error")) |
| 2329 | .and_then(serde_json::Value::as_str) |
| 2330 | .map(str::trim) |
| 2331 | .filter(|s| !s.is_empty()); |
| 2332 | let failed_calls: Vec<String> = obj |
| 2333 | .get("calls") |
| 2334 | .and_then(serde_json::Value::as_array) |
| 2335 | .map(|calls| { |
| 2336 | calls |
| 2337 | .iter() |
| 2338 | .filter_map(|call| { |
| 2339 | let status = call.get("status").and_then(serde_json::Value::as_str); |
| 2340 | let ok = call |
| 2341 | .get("ok") |
| 2342 | .and_then(serde_json::Value::as_bool) |
| 2343 | .unwrap_or(false); |
| 2344 | let is_failed_or_refused = |
| 2345 | matches!(status, Some("failed" | "refused")) || (status.is_none() && !ok); |
| 2346 | if !is_failed_or_refused { |
| 2347 | return None; |
| 2348 | } |
| 2349 | let tool = call.get("tool").and_then(serde_json::Value::as_str)?; |
| 2350 | let label = status.unwrap_or("failed"); |
| 2351 | let note = call |
| 2352 | .get("note") |
| 2353 | .and_then(serde_json::Value::as_str) |
| 2354 | .map(str::trim) |
| 2355 | .filter(|s| !s.is_empty()); |
| 2356 | Some(match note { |
| 2357 | Some(note) => format!("{tool} ({label}): {note}"), |
| 2358 | None => format!("{tool} ({label})"), |
| 2359 | }) |
| 2360 | }) |
| 2361 | .collect() |
| 2362 | }) |
| 2363 | .unwrap_or_default(); |
| 2364 | if body_error.is_none() && failed_calls.is_empty() { |
| 2365 | return None; |
| 2366 | } |
| 2367 | let mut lines = Vec::new(); |
| 2368 | if let Some(error) = body_error { |
| 2369 | lines.push(error.to_string()); |
| 2370 | } |
| 2371 | lines.extend(failed_calls); |
| 2372 | Some(lines.join("\n")) |
| 2373 | } |
| 2374 | |
| 2375 | impl GenericToolCell { |
| 2376 | fn header_summary(&self) -> Option<String> { |
| 2377 | if self.name == "execute_tools" |
| 2378 | && let Some(output) = self.output.as_deref() |
| 2379 | && let Some(summary) = execute_tools_header_summary(output) |
| 2380 | { |
| 2381 | return Some(format!("execute_tools · {summary}")); |
| 2382 | } |
| 2383 | crate::tui::widgets::tool_card::tool_header_summary_for_name( |
| 2384 | &self.name, |
| 2385 | self.input_summary.as_deref(), |
| 2386 | ) |
| 2387 | } |
| 2388 | |
| 2389 | /// Render the generic tool cell into lines. |
| 2390 | /// |
| 2391 | /// `mode` controls multi-line output handling: `Live` caps at |
| 2392 | /// `TOOL_OUTPUT_LINE_LIMIT` rows with a "+N more" affordance; |
| 2393 | /// `Transcript` uses a larger bounded display projection. |
| 2394 | #[cfg(test)] |
| 2395 | pub fn lines_with_mode( |
| 2396 | &self, |
| 2397 | width: u16, |
| 2398 | low_motion: bool, |
| 2399 | mode: RenderMode, |
| 2400 | ) -> Vec<Line<'static>> { |
| 2401 | self.lines_with_mode_and_locale(width, low_motion, mode, Locale::En) |
| 2402 | } |
| 2403 | |
| 2404 | pub fn lines_with_mode_and_locale( |
| 2405 | &self, |
| 2406 | width: u16, |
| 2407 | low_motion: bool, |
| 2408 | mode: RenderMode, |
| 2409 | locale: Locale, |
| 2410 | ) -> Vec<Line<'static>> { |
| 2411 | if mode != RenderMode::Source { |
| 2412 | match self.name.as_str() { |
| 2413 | "activity_group" => { |
| 2414 | return agent_activity::render_activity_group(self, width, locale); |
| 2415 | } |
| 2416 | "turn_work" => return agent_activity::render_turn_work(self, width), |
| 2417 | "agent_line" => return agent_activity::render_agent_line(self, width), |
| 2418 | _ => {} |
| 2419 | } |
| 2420 | } |
| 2421 | |
| 2422 | // Issue #241: when the underlying tool is a checklist/todo update and |
| 2423 | // the output is parseable, render a purpose-built progress card |
| 2424 | // instead of dumping the JSON into the generic tool block. |
| 2425 | if mode != RenderMode::Source |
| 2426 | && let Some(lines) = self.try_render_as_checklist(width, low_motion, mode, locale) |
| 2427 | { |
| 2428 | return lines; |
| 2429 | } |
| 2430 | |
| 2431 | // #4038 / #4122: purpose-built workflow run card (compact in live, |
| 2432 | // expanded in transcript) shared with the WorkflowPanel state machine. |
| 2433 | if mode != RenderMode::Source |
| 2434 | && let Some(lines) = self.try_render_as_workflow(width, low_motion, mode, locale) |
| 2435 | { |
| 2436 | return lines; |
| 2437 | } |
| 2438 | |
| 2439 | // Sub-agent launch already gets a dedicated `DelegateCard` |
| 2440 | // that owns the live action tree, status, and final summary (#4133). |
| 2441 | // Spawns therefore render nothing here in either mode — one visible |
| 2442 | // artifact per delegated unit. Inspection/join calls (peek/status/ |
| 2443 | // wait) stay as a single compact line (#4112 dogfood A5). |
| 2444 | if mode != RenderMode::Source && self.name == "agent" { |
| 2445 | if agent_activity::is_agent_inspection(self) { |
| 2446 | return agent_activity::render_agent_compact(self, low_motion, locale); |
| 2447 | } |
| 2448 | // Spawn / start / run: suppress the generic tool card entirely. |
| 2449 | return Vec::new(); |
| 2450 | } |
| 2451 | |
| 2452 | // A call to a tool that doesn't exist carries exactly one useful |
| 2453 | // fact: the catalog error. The full name:/args:/result: block turns |
| 2454 | // each model slip into a four-line card (dogfood A5) — collapse it |
| 2455 | // to a single header line in both render modes. |
| 2456 | if mode != RenderMode::Source |
| 2457 | && self.status == ToolStatus::Failed |
| 2458 | && let Some(output) = self.output.as_deref() |
| 2459 | && output.contains("is not available in the current tool catalog") |
| 2460 | { |
| 2461 | let family = crate::tui::widgets::tool_card::tool_family_for_name(&self.name); |
| 2462 | let summary = truncate_text(output.trim(), 200); |
| 2463 | return wrap_card_rail( |
| 2464 | vec![render_tool_header_with_family_and_summary( |
| 2465 | family, |
| 2466 | Some(summary.as_str()), |
| 2467 | None, |
| 2468 | self.status, |
| 2469 | None, |
| 2470 | low_motion, |
| 2471 | locale, |
| 2472 | )], |
| 2473 | self.status, |
| 2474 | ); |
| 2475 | } |
| 2476 | |
| 2477 | // Live mode stays calm: successful tool calls collapse to one header |
| 2478 | // line, and non-read in-flight tools do the same. Failures keep their |
| 2479 | // body visible because error output is the useful part. |
| 2480 | if matches!(mode, RenderMode::Live) { |
| 2481 | let family = crate::tui::widgets::tool_card::tool_family_for_name(&self.name); |
| 2482 | let is_read_family = matches!( |
| 2483 | family, |
| 2484 | crate::tui::widgets::tool_card::ToolFamily::Read |
| 2485 | | crate::tui::widgets::tool_card::ToolFamily::Find |
| 2486 | ); |
| 2487 | let should_collapse = self.status == ToolStatus::Success |
| 2488 | || (self.status != ToolStatus::Failed && !is_read_family); |
| 2489 | if should_collapse || self.spillover_path.is_some() { |
| 2490 | let header_summary = self.header_summary(); |
| 2491 | let mut collapsed = vec![render_tool_header_with_family_and_summary( |
| 2492 | family, |
| 2493 | header_summary.as_deref(), |
| 2494 | Some( |
| 2495 | tool_receipt_label(family, self.status, self.output.as_deref(), locale) |
| 2496 | .as_ref(), |
| 2497 | ), |
| 2498 | self.status, |
| 2499 | None, |
| 2500 | low_motion, |
| 2501 | locale, |
| 2502 | )]; |
| 2503 | if self.spillover_path.is_some() { |
| 2504 | collapsed.push(render_spillover_annotation(width, locale)); |
| 2505 | } |
| 2506 | return wrap_card_rail(collapsed, self.status); |
| 2507 | } |
| 2508 | } |
| 2509 | |
| 2510 | let mut lines = Vec::new(); |
| 2511 | // Map the actual tool name (e.g. `agent`, `apply_patch`) to a |
| 2512 | // family rather than the catch-all `"Tool"` title — this is what |
| 2513 | // gives a `GenericToolCell` the right verb glyph (◐ delegate, ⋮⋮ |
| 2514 | // fanout, etc.) instead of falling back to the neutral bullet. |
| 2515 | let family = crate::tui::widgets::tool_card::tool_family_for_name(&self.name); |
| 2516 | let header_summary = self.header_summary(); |
| 2517 | let header = render_tool_header_with_family_and_summary( |
| 2518 | family, |
| 2519 | header_summary.as_deref(), |
| 2520 | Some(tool_receipt_label(family, self.status, self.output.as_deref(), locale).as_ref()), |
| 2521 | self.status, |
| 2522 | None, |
| 2523 | low_motion, |
| 2524 | locale, |
| 2525 | ); |
| 2526 | let header_has_args = self.input_summary.as_deref().is_some_and(|args| { |
| 2527 | header_repeats_args(&header, header_summary.as_deref(), args, usize::from(width)) |
| 2528 | }); |
| 2529 | lines.push(header); |
| 2530 | if should_show_raw_tool_name(&self.name, family, mode) |
| 2531 | && !crate::tui::widgets::tool_card::should_show_tool_name_in_header(&self.name, family) |
| 2532 | { |
| 2533 | lines.extend(render_compact_kv( |
| 2534 | "name", |
| 2535 | &self.name, |
| 2536 | tool_value_style(), |
| 2537 | width, |
| 2538 | )); |
| 2539 | } |
| 2540 | |
| 2541 | // Prefer per-prompt rows over the generic args summary when the tool |
| 2542 | // exposes a list of child prompts. One row per child with a `[i]` |
| 2543 | // index makes the fan-out legible without expanding JSON. |
| 2544 | let show_prompts = self.status.is_active() || self.output.is_none(); |
| 2545 | if show_prompts |
| 2546 | && let Some(prompts) = self.prompts.as_ref() |
| 2547 | && !prompts.is_empty() |
| 2548 | { |
| 2549 | for (idx, prompt) in prompts.iter().enumerate() { |
| 2550 | let label = if idx == 0 { "prompts" } else { "" }; |
| 2551 | let value = format!("[{idx}] {}", truncate_text(prompt.trim(), 200)); |
| 2552 | lines.extend(render_card_detail_line( |
| 2553 | if label.is_empty() { None } else { Some(label) }, |
| 2554 | &value, |
| 2555 | tool_value_style(), |
| 2556 | width, |
| 2557 | )); |
| 2558 | } |
| 2559 | } else { |
| 2560 | let show_args = (matches!( |
| 2561 | self.status, |
| 2562 | ToolStatus::Queued | ToolStatus::Running | ToolStatus::Failed |
| 2563 | ) || self.output.is_none()) |
| 2564 | && !header_has_args; |
| 2565 | if show_args && let Some(summary) = self.input_summary.as_ref() { |
| 2566 | lines.extend(render_compact_kv( |
| 2567 | "args", |
| 2568 | summary, |
| 2569 | tool_value_style(), |
| 2570 | width, |
| 2571 | )); |
| 2572 | } |
| 2573 | } |
| 2574 | |
| 2575 | if let Some(output) = self.output.as_ref() { |
| 2576 | if self.is_diff { |
| 2577 | let diff_summary = diff_render::diff_summary_label(output); |
| 2578 | lines.push(render_tool_header_with_summary( |
| 2579 | "Diff", |
| 2580 | diff_summary.as_deref(), |
| 2581 | None, |
| 2582 | self.status, |
| 2583 | None, |
| 2584 | low_motion, |
| 2585 | locale, |
| 2586 | )); |
| 2587 | if mode == RenderMode::Source { |
| 2588 | lines.push(Line::from(output.clone())); |
| 2589 | } else { |
| 2590 | let limit = if mode == RenderMode::Transcript { |
| 2591 | 512 |
| 2592 | } else if self.status == ToolStatus::Failed { |
| 2593 | TOOL_FAILURE_PREVIEW_LINES |
| 2594 | } else { |
| 2595 | TOOL_OUTPUT_LINE_LIMIT |
| 2596 | }; |
| 2597 | let rendered = diff_render::render_diff_bounded( |
| 2598 | output, |
| 2599 | width, |
| 2600 | limit, |
| 2601 | &diff_summary_labels(locale), |
| 2602 | ); |
| 2603 | lines.extend(rendered.lines); |
| 2604 | if rendered.omitted_rows > 0 { |
| 2605 | let detail_hint = |
| 2606 | crate::tui::key_shortcuts::tool_details_shortcut_action_hint("diff"); |
| 2607 | let body = tr(locale, MessageId::FileMutationMoreDiff) |
| 2608 | .replace("{count}", &rendered.omitted_body_rows.to_string()) |
| 2609 | .replace("{hint}", &detail_hint); |
| 2610 | let omitted = if rendered.omitted_summary_rows > 0 { |
| 2611 | format!( |
| 2612 | "{} {} · {body}", |
| 2613 | tr(locale, MessageId::ConfigChoiceDiffSummary), |
| 2614 | tr(locale, MessageId::ApprovalMoreLines) |
| 2615 | .replace("{count}", &rendered.omitted_summary_rows.to_string()) |
| 2616 | .trim_start() |
| 2617 | ) |
| 2618 | } else { |
| 2619 | body |
| 2620 | }; |
| 2621 | lines.push(details_affordance_line( |
| 2622 | &omitted, |
| 2623 | Style::default().fg(palette::TEXT_MUTED).italic(), |
| 2624 | )); |
| 2625 | } |
| 2626 | } |
| 2627 | } else { |
| 2628 | let limit = if self.status == ToolStatus::Failed { |
| 2629 | TOOL_FAILURE_PREVIEW_LINES |
| 2630 | } else { |
| 2631 | TOOL_OUTPUT_LINE_LIMIT |
| 2632 | }; |
| 2633 | if self.name == "execute_tools" |
| 2634 | && self.status == ToolStatus::Failed |
| 2635 | && mode != RenderMode::Source |
| 2636 | && let Some(formatted) = format_execute_tools_failure(output) |
| 2637 | { |
| 2638 | lines.extend(render_tool_output_mode( |
| 2639 | &formatted, width, limit, mode, locale, |
| 2640 | )); |
| 2641 | } else { |
| 2642 | lines.extend(render_tool_output_mode(output, width, limit, mode, locale)); |
| 2643 | } |
| 2644 | } |
| 2645 | |
| 2646 | if matches!(mode, RenderMode::Live) && self.spillover_path.is_some() { |
| 2647 | lines.push(render_spillover_annotation(width, locale)); |
| 2648 | } |
| 2649 | } |
| 2650 | wrap_card_rail(lines, self.status) |
| 2651 | } |
| 2652 | |
| 2653 | /// If this cell is a checklist/todo write/add/update and the output is |
| 2654 | /// parseable as a checklist snapshot, render a purpose-built checklist |
| 2655 | /// card instead of the generic `name: ... { json }` block (issue #241). |
| 2656 | fn try_render_as_checklist( |
| 2657 | &self, |
| 2658 | width: u16, |
| 2659 | low_motion: bool, |
| 2660 | mode: RenderMode, |
| 2661 | locale: Locale, |
| 2662 | ) -> Option<Vec<Line<'static>>> { |
| 2663 | if !is_checklist_tool_name(&self.name) { |
| 2664 | return None; |
| 2665 | } |
| 2666 | let output = self.output.as_ref()?; |
| 2667 | let snapshot = parse_checklist_snapshot(output)?; |
| 2668 | |
| 2669 | // Concise update rendering (#403). When the tool emits an |
| 2670 | // "Updated todo #N to STATUS" prefix line — which `todo_update` / |
| 2671 | // `checklist_update` always do on a successful match — render |
| 2672 | // only the changed item plus a `M/N · pct%` summary instead of |
| 2673 | // dumping the full list every time. The full list is still |
| 2674 | // reachable via `v` on the tool detail record. This keeps the |
| 2675 | // transcript scannable in long sessions. |
| 2676 | if matches!(mode, RenderMode::Live) |
| 2677 | && let Some(change) = parse_update_prefix(output) |
| 2678 | { |
| 2679 | return Some(render_checklist_change_card( |
| 2680 | &self.name, |
| 2681 | self.status, |
| 2682 | &snapshot, |
| 2683 | &change, |
| 2684 | width, |
| 2685 | low_motion, |
| 2686 | locale, |
| 2687 | )); |
| 2688 | } |
| 2689 | |
| 2690 | Some(render_checklist_card( |
| 2691 | &self.name, |
| 2692 | self.status, |
| 2693 | &snapshot, |
| 2694 | width, |
| 2695 | low_motion, |
| 2696 | mode, |
| 2697 | locale, |
| 2698 | )) |
| 2699 | } |
| 2700 | |
| 2701 | /// Render the `workflow` tool as the transcript's one row per run |
| 2702 | /// (#4122): while the run is live, the call that launched it is one |
| 2703 | /// `started` line naming the run; when it settles, |
| 2704 | /// `App::announce_settled_workflows` swaps that card's record for the |
| 2705 | /// finish, so the same row becomes the final state — outcome counts, |
| 2706 | /// elapsed, tokens — with the result or the reason under it. A card that |
| 2707 | /// returned a settled record (a foreground `run`, a `status` poll) shows |
| 2708 | /// only the finish. Live progress is the workbar's, not the transcript's. |
| 2709 | /// Transcript mode expands the finish card's phase/child detail. |
| 2710 | /// Status-list payloads keep a multi-run summary card. |
| 2711 | fn try_render_as_workflow( |
| 2712 | &self, |
| 2713 | width: u16, |
| 2714 | low_motion: bool, |
| 2715 | mode: RenderMode, |
| 2716 | locale: Locale, |
| 2717 | ) -> Option<Vec<Line<'static>>> { |
| 2718 | if self.name != "workflow" { |
| 2719 | return None; |
| 2720 | } |
| 2721 | let output = self.output.as_ref()?; |
| 2722 | let Ok(value) = serde_json::from_str::<serde_json::Value>(output) else { |
| 2723 | // A call the runtime refused (invalid plan, unknown fleet) never |
| 2724 | // started a run. It says why — the error's first sentence, wrapped |
| 2725 | // under the header — instead of echoing `action: start`; the full |
| 2726 | // error and validation feedback stay behind the details key. |
| 2727 | if self.status != ToolStatus::Failed { |
| 2728 | return None; |
| 2729 | } |
| 2730 | let reason = workflow_call_error_reason(output)?; |
| 2731 | let family = crate::tui::widgets::tool_card::tool_family_for_name("workflow"); |
| 2732 | let mut lines = vec![render_tool_header_with_family_and_summary( |
| 2733 | family, |
| 2734 | None, |
| 2735 | None, |
| 2736 | self.status, |
| 2737 | None, |
| 2738 | low_motion, |
| 2739 | locale, |
| 2740 | )]; |
| 2741 | lines.extend(render_card_detail_line( |
| 2742 | None, |
| 2743 | &reason, |
| 2744 | tool_value_style(), |
| 2745 | width, |
| 2746 | )); |
| 2747 | if !matches!(mode, RenderMode::Live) { |
| 2748 | lines.extend(render_tool_output_mode( |
| 2749 | output, |
| 2750 | width, |
| 2751 | TOOL_OUTPUT_LINE_LIMIT, |
| 2752 | mode, |
| 2753 | locale, |
| 2754 | )); |
| 2755 | } |
| 2756 | return Some(wrap_card_rail(lines, self.status)); |
| 2757 | }; |
| 2758 | let is_status_list = |
| 2759 | value.get("action").and_then(serde_json::Value::as_str) == Some("status"); |
| 2760 | if value.get("run_id").is_none() && !is_status_list { |
| 2761 | return None; |
| 2762 | } |
| 2763 | let family = crate::tui::widgets::tool_card::tool_family_for_name("workflow"); |
| 2764 | let mut lines = Vec::new(); |
| 2765 | |
| 2766 | if is_status_list { |
| 2767 | let runs = value.get("runs").and_then(serde_json::Value::as_array); |
| 2768 | let count = value |
| 2769 | .get("count") |
| 2770 | .and_then(serde_json::Value::as_u64) |
| 2771 | .unwrap_or_else(|| runs.map(|r| r.len() as u64).unwrap_or(0)); |
| 2772 | let header = format!("{count} run(s)"); |
| 2773 | lines.push(render_tool_header_with_family_and_summary( |
| 2774 | family, |
| 2775 | Some(header.as_str()), |
| 2776 | None, |
| 2777 | self.status, |
| 2778 | None, |
| 2779 | low_motion, |
| 2780 | locale, |
| 2781 | )); |
| 2782 | if let Some(runs) = runs { |
| 2783 | for run in runs { |
| 2784 | let run_id = run |
| 2785 | .get("run_id") |
| 2786 | .and_then(serde_json::Value::as_str) |
| 2787 | .unwrap_or("?"); |
| 2788 | let status = run |
| 2789 | .get("status") |
| 2790 | .and_then(serde_json::Value::as_str) |
| 2791 | .unwrap_or("?"); |
| 2792 | let children = run |
| 2793 | .get("child_count") |
| 2794 | .and_then(serde_json::Value::as_u64) |
| 2795 | .or_else(|| { |
| 2796 | run.get("child_ids") |
| 2797 | .and_then(serde_json::Value::as_array) |
| 2798 | .map(|a| a.len() as u64) |
| 2799 | }) |
| 2800 | .unwrap_or(0); |
| 2801 | lines.extend(render_card_detail_line( |
| 2802 | None, |
| 2803 | &format!("{run_id} · {status} · {children} child(ren)"), |
| 2804 | tool_value_style(), |
| 2805 | width, |
| 2806 | )); |
| 2807 | } |
| 2808 | } |
| 2809 | return Some(wrap_card_rail(lines, self.status)); |
| 2810 | } |
| 2811 | |
| 2812 | use crate::tui::widgets::workflow_panel::{WorkflowHistoryExtras, WorkflowPanel}; |
| 2813 | let mut panel = WorkflowPanel::from_run_json(&value)?; |
| 2814 | panel.locale = locale; |
| 2815 | let finish_card = value |
| 2816 | .get("transcript_line") |
| 2817 | .and_then(serde_json::Value::as_str) |
| 2818 | == Some("finished"); |
| 2819 | // A foreground `run` card returns the settled record itself, so it |
| 2820 | // carries its own finish; a detached start is finished by the card |
| 2821 | // `App::announce_settled_workflows` writes later. |
| 2822 | let owns_finish = |
| 2823 | finish_card || (!self.status.is_active() && panel.lifecycle.is_terminal()); |
| 2824 | if !owns_finish { |
| 2825 | // The start line: the run's name. Its progress lives in the |
| 2826 | // workbar, never here. A card that already holds the settled |
| 2827 | // record shows only the finish: the final state replaces |
| 2828 | // `started`, one row per run. |
| 2829 | let name = panel.short_title(); |
| 2830 | lines.push(render_tool_header_with_family_and_summary( |
| 2831 | family, |
| 2832 | Some(name.as_str()), |
| 2833 | Some( |
| 2834 | codewhale_localization::tr( |
| 2835 | locale, |
| 2836 | codewhale_localization::MessageId::WorkflowLineStarted, |
| 2837 | ) |
| 2838 | .as_ref(), |
| 2839 | ), |
| 2840 | if owns_finish { |
| 2841 | ToolStatus::Success |
| 2842 | } else { |
| 2843 | self.status |
| 2844 | }, |
| 2845 | None, |
| 2846 | low_motion, |
| 2847 | locale, |
| 2848 | )); |
| 2849 | } |
| 2850 | let finish = owns_finish.then(|| panel.finish_line()).flatten(); |
| 2851 | let Some((state, facts, detail)) = finish else { |
| 2852 | return Some(wrap_card_rail(lines, self.status)); |
| 2853 | }; |
| 2854 | let finish_status = match panel.lifecycle { |
| 2855 | crate::tui::widgets::workflow_panel::WorkflowPanelLifecycle::Succeeded => { |
| 2856 | ToolStatus::Success |
| 2857 | } |
| 2858 | crate::tui::widgets::workflow_panel::WorkflowPanelLifecycle::Degraded => { |
| 2859 | ToolStatus::Warning |
| 2860 | } |
| 2861 | _ => ToolStatus::Failed, |
| 2862 | }; |
| 2863 | lines.push(render_tool_header_with_family_and_summary( |
| 2864 | family, |
| 2865 | Some(facts.as_str()), |
| 2866 | Some(&state), |
| 2867 | finish_status, |
| 2868 | None, |
| 2869 | low_motion, |
| 2870 | locale, |
| 2871 | )); |
| 2872 | if let Some(detail) = detail { |
| 2873 | // Why a run fell short is the one fact worth reading: its first |
| 2874 | // sentence wraps instead of being cut. A success summary keeps to |
| 2875 | // one row, cut at a word boundary; the expand key shows the rest. |
| 2876 | let detail = if finish_status == ToolStatus::Failed { |
| 2877 | detail |
| 2878 | } else { |
| 2879 | let room = usize::from(width).saturating_sub(4).max(8); |
| 2880 | codewhale_tui_kit::ui_text::semantic_truncate(&detail, room) |
| 2881 | }; |
| 2882 | lines.extend(render_card_detail_line( |
| 2883 | None, |
| 2884 | &detail, |
| 2885 | tool_value_style(), |
| 2886 | width, |
| 2887 | )); |
| 2888 | } |
| 2889 | let expanded = !matches!(mode, RenderMode::Live); |
| 2890 | if expanded { |
| 2891 | let extras = WorkflowHistoryExtras { |
| 2892 | result_summary: panel.result_summary.clone(), |
| 2893 | source_path: panel.source_path.clone().or_else(|| { |
| 2894 | value |
| 2895 | .get("source_path") |
| 2896 | .and_then(serde_json::Value::as_str) |
| 2897 | .map(std::path::PathBuf::from) |
| 2898 | }), |
| 2899 | spillover_path: self.spillover_path.clone(), |
| 2900 | verification_summary: value |
| 2901 | .get("verification") |
| 2902 | .and_then(|v| v.get("summary")) |
| 2903 | .and_then(serde_json::Value::as_str) |
| 2904 | .map(str::to_string), |
| 2905 | }; |
| 2906 | for detail in panel.history_expanded_lines(width, &extras) { |
| 2907 | // history_expanded_lines omit the leading indent; re-use the |
| 2908 | // card detail path so rails and spacing stay consistent. |
| 2909 | let text: String = detail.spans.iter().map(|s| s.content.as_ref()).collect(); |
| 2910 | lines.extend(render_card_detail_line( |
| 2911 | None, |
| 2912 | &text, |
| 2913 | tool_value_style(), |
| 2914 | width, |
| 2915 | )); |
| 2916 | } |
| 2917 | } |
| 2918 | Some(wrap_card_rail(lines, finish_status)) |
| 2919 | } |
| 2920 | } |
| 2921 | |
| 2922 | /// The first sentence of a refused `workflow` call's error, without the |
| 2923 | /// dispatcher's `Error: Invalid input for tool 'workflow':` preamble, which |
| 2924 | /// names the tool the card already names. |
| 2925 | fn workflow_call_error_reason(output: &str) -> Option<String> { |
| 2926 | let first = output |
| 2927 | .lines() |
| 2928 | .map(str::trim) |
| 2929 | .find(|line| !line.is_empty())?; |
| 2930 | let first = first.strip_prefix("Error:").map_or(first, str::trim_start); |
| 2931 | let first = if first.starts_with("Invalid input for tool") { |
| 2932 | first.split_once("': ").map_or(first, |(_, rest)| rest) |
| 2933 | } else { |
| 2934 | first |
| 2935 | }; |
| 2936 | let reason = crate::tui::widgets::workflow_panel::first_sentence(first); |
| 2937 | (!reason.is_empty()).then_some(reason) |
| 2938 | } |
| 2939 | |
| 2940 | /// Render the inline annotation for a tool cell whose full output was |
| 2941 | /// retained internally and replaced by a bounded preview. The annotation |
| 2942 | /// stays calm and path-free: it only says the output was shortened and that |
| 2943 | /// the details shortcut opens the full retained output. |
| 2944 | fn render_spillover_annotation(width: u16, locale: Locale) -> Line<'static> { |
| 2945 | // Matches the model-facing preview footer (truncate.rs) and the existing |
| 2946 | // "Alt+V opens …" hint style (#3256): one quiet line, no handles or paths. |
| 2947 | let affordance = tr(locale, MessageId::ToolOutputShortened).replace( |
| 2948 | "{key}", |
| 2949 | &crate::tui::key_shortcuts::tool_details_shortcut_label(), |
| 2950 | ); |
| 2951 | let room = usize::from(width) |
| 2952 | .saturating_sub(UnicodeWidthStr::width(TRANSCRIPT_RAIL)) |
| 2953 | .max(8); |
| 2954 | details_affordance_line( |
| 2955 | &truncate_text(&affordance, room), |
| 2956 | Style::default().fg(palette::TEXT_MUTED).italic(), |
| 2957 | ) |
| 2958 | } |
| 2959 | |
| 2960 | /// Detect a truncated-output preview: the current model-facing footer (which |
| 2961 | /// names the artifact path and recovery instruction), the previous plain |
| 2962 | /// footer, or the legacy receipt header still present in older saved |
| 2963 | /// sessions. Live cards collapse to the expand affordance for all of them. |
| 2964 | fn is_truncated_output_preview(content: &str) -> bool { |
| 2965 | content.contains(codewhale_tools::names::SPILLOVER_RECOVERY_HINT) |
| 2966 | || content.contains(codewhale_engine::tools::truncate::SPILLOVER_PREVIEW_HINT) |
| 2967 | || content.trim_start().starts_with("[Exact evidence retained") |
| 2968 | } |
| 2969 | |
| 2970 | fn render_command_mode( |
| 2971 | command: &str, |
| 2972 | width: u16, |
| 2973 | mode: RenderMode, |
| 2974 | calm: bool, |
| 2975 | locale: Locale, |
| 2976 | ) -> Vec<Line<'static>> { |
| 2977 | let mut lines = Vec::new(); |
| 2978 | if mode == RenderMode::Source { |
| 2979 | lines.push(render_card_detail_line_single( |
| 2980 | Some("command"), |
| 2981 | command, |
| 2982 | tool_value_style(), |
| 2983 | )); |
| 2984 | return lines; |
| 2985 | } |
| 2986 | let cap = match mode { |
| 2987 | RenderMode::Live => TOOL_COMMAND_LINE_LIMIT, |
| 2988 | RenderMode::Transcript | RenderMode::Source => 512, |
| 2989 | }; |
| 2990 | let command = if calm { |
| 2991 | command.trim_start_matches("$ ") |
| 2992 | } else { |
| 2993 | command |
| 2994 | }; |
| 2995 | let wrap_width = width.saturating_sub(4).max(1) as usize; |
| 2996 | let mut count = 0usize; |
| 2997 | for line in command.lines() { |
| 2998 | for_each_wrapped_text(line, wrap_width, |chunk| { |
| 2999 | if count < cap && chunk.len() > 4 * 1024 { |
| 3000 | lines.push(render_spillover_annotation(width, locale)); |
| 3001 | } else if count < cap { |
| 3002 | if calm { |
| 3003 | let prompt = if count == 0 { "$ " } else { " " }; |
| 3004 | lines.extend(render_card_detail_line( |
| 3005 | None, |
| 3006 | &format!("{prompt}{chunk}"), |
| 3007 | tool_value_style(), |
| 3008 | width, |
| 3009 | )); |
| 3010 | } else { |
| 3011 | lines.extend(render_card_detail_line( |
| 3012 | if count == 0 { Some("command") } else { None }, |
| 3013 | chunk, |
| 3014 | tool_value_style(), |
| 3015 | width, |
| 3016 | )); |
| 3017 | } |
| 3018 | } |
| 3019 | count = count.saturating_add(1); |
| 3020 | }); |
| 3021 | } |
| 3022 | if count > cap { |
| 3023 | lines.push(details_affordance_line( |
| 3024 | &crate::tui::key_shortcuts::tool_details_shortcut_action_hint(&tr( |
| 3025 | locale, |
| 3026 | MessageId::ApprovalLabelCommand, |
| 3027 | )), |
| 3028 | Style::default().fg(palette::TEXT_MUTED), |
| 3029 | )); |
| 3030 | } |
| 3031 | lines |
| 3032 | } |
| 3033 | |
| 3034 | fn command_header_summary(command: &str) -> String { |
| 3035 | command |
| 3036 | .lines() |
| 3037 | .next() |
| 3038 | .unwrap_or(command) |
| 3039 | .trim_start_matches("$ ") |
| 3040 | .trim() |
| 3041 | .to_string() |
| 3042 | } |
| 3043 | |
| 3044 | pub(crate) fn diff_summary_labels(locale: Locale) -> diff_render::DiffSummaryLabels { |
| 3045 | diff_render::DiffSummaryLabels { |
| 3046 | summary: tr(locale, MessageId::DiffSummaryLine), |
| 3047 | file_one: tr(locale, MessageId::ActivityFileOne), |
| 3048 | file_many: tr(locale, MessageId::ActivityFileMany), |
| 3049 | hunk_one: tr(locale, MessageId::DiffHunkOne), |
| 3050 | hunk_many: tr(locale, MessageId::DiffHunkMany), |
| 3051 | } |
| 3052 | } |
| 3053 | |
| 3054 | fn exploring_header_summary(entries: &[ExploringEntry]) -> Option<String> { |
| 3055 | match entries { |
| 3056 | [] => None, |
| 3057 | [entry] => Some(entry.label.clone()), |
| 3058 | entries => Some(format!("{} items", entries.len())), |
| 3059 | } |
| 3060 | } |
| 3061 | |
| 3062 | /// Choose the verb family for an exploring card's header. A card whose entries |
| 3063 | /// are all searches reads with the `find` verb so the completed action agrees |
| 3064 | /// with its `Searching for …` labels (#4145); every other exploration mix keeps |
| 3065 | /// the neutral `read` verb the Workspace card uses. |
| 3066 | fn exploring_card_family(entries: &[ExploringEntry]) -> crate::tui::widgets::tool_card::ToolFamily { |
| 3067 | use crate::tui::widgets::tool_card::ToolFamily; |
| 3068 | let all_search = !entries.is_empty() && entries.iter().all(|entry| entry.search); |
| 3069 | if all_search { |
| 3070 | ToolFamily::Find |
| 3071 | } else { |
| 3072 | ToolFamily::Read |
| 3073 | } |
| 3074 | } |
| 3075 | |
| 3076 | fn render_compact_kv(label: &str, value: &str, style: Style, width: u16) -> Vec<Line<'static>> { |
| 3077 | render_card_detail_line(Some(label.trim_end_matches(':')), value, style, width) |
| 3078 | } |
| 3079 | |
| 3080 | /// Wrap rendered tool-card lines with card-rail glyphs (╭ │ ╰). |
| 3081 | /// First non-empty line gets `╭`, middle lines get `│`, last line gets `╰`. |
| 3082 | /// Single-line cards get a single `─` prefix. |
| 3083 | /// |
| 3084 | /// The rail is the card's border, so it carries the cell's own state: it is |
| 3085 | /// painted with [`tool_rail_color`], OMP's border rule. A running card is |
| 3086 | /// bordered in the action accent, a failed one in the error colour, and a |
| 3087 | /// settled one recedes to muted — which is what makes a tool cell legible |
| 3088 | /// without a neighbouring row narrating what the card already shows. The |
| 3089 | /// header glyph inside it follows [`tool_glyph_color`] instead, so a finished |
| 3090 | /// card still says what it was. |
| 3091 | fn wrap_card_rail(mut lines: Vec<Line<'static>>, status: ToolStatus) -> Vec<Line<'static>> { |
| 3092 | let n = lines.len(); |
| 3093 | if n == 0 { |
| 3094 | return lines; |
| 3095 | } |
| 3096 | let rail_style = Style::default().fg(tool_rail_color(status)); |
| 3097 | if n == 1 { |
| 3098 | lines[0].spans.insert(0, Span::styled("─ ", rail_style)); |
| 3099 | return lines; |
| 3100 | } |
| 3101 | for (i, line) in lines.iter_mut().enumerate() { |
| 3102 | let rail = if i == 0 { |
| 3103 | "\u{256D} " // ╭ |
| 3104 | } else if i == n - 1 { |
| 3105 | "\u{2570} " // ╰ |
| 3106 | } else { |
| 3107 | "\u{2502} " // │ |
| 3108 | }; |
| 3109 | line.spans.insert(0, Span::styled(rail, rail_style)); |
| 3110 | } |
| 3111 | lines |
| 3112 | } |
| 3113 | |
| 3114 | /// The legacy tool renderers accept only a low-motion boolean, which gives |
| 3115 | /// both Reduced and Still a mix of legacy static frames. Preserve that stable |
| 3116 | /// rendering path, then apply the central mode's exact fallback at the typed |
| 3117 | /// header span (never by rewriting user/tool output text). |
| 3118 | fn apply_static_tool_markers(lines: &mut [Line<'static>], marker: &'static str) { |
| 3119 | for (line_index, line) in lines.iter_mut().enumerate() { |
| 3120 | let mut index = 0; |
| 3121 | if line |
| 3122 | .spans |
| 3123 | .first() |
| 3124 | .is_some_and(|span| matches!(span.content.as_ref(), "─ " | "╭ " | "│ " | "╰ ")) |
| 3125 | { |
| 3126 | index = 1; |
| 3127 | } |
| 3128 | let Some(status) = line.spans.get(index).map(|span| span.content.as_ref()) else { |
| 3129 | continue; |
| 3130 | }; |
| 3131 | let family = line.spans.get(index + 1).map(|span| span.content.as_ref()); |
| 3132 | let header = line_index == 0 |
| 3133 | || family.is_some_and(|family| { |
| 3134 | family.ends_with(' ') && is_tool_family_glyph(family.trim_end()) |
| 3135 | }); |
| 3136 | if !status.ends_with(' ') || !is_tool_status_glyph(status.trim_end()) || !header { |
| 3137 | continue; |
| 3138 | } |
| 3139 | let mut chars = status.trim_end().chars(); |
| 3140 | if matches!(chars.next(), Some('\u{2800}'..='\u{28FF}')) && chars.next().is_none() { |
| 3141 | line.spans[index].content = format!("{marker} ").into(); |
| 3142 | } |
| 3143 | } |
| 3144 | } |
| 3145 | |
| 3146 | /// Return the width of tool-cell chrome that remains after the transcript |
| 3147 | /// cache removes the cell-local card rail. Labeled tool headers have two |
| 3148 | /// additional visual tokens (`✓`/spinner and the family glyph); a calm shell |
| 3149 | /// header has only its status mark, and only a spinner frame of it is chrome; |
| 3150 | /// detail rows have the thin transcript rail. Keeping this width with the |
| 3151 | /// rendered line avoids making selection copy infer chrome from glyph ranges, |
| 3152 | /// which can consume real code or CJK text that happens to begin with a |
| 3153 | /// box-drawing character. |
| 3154 | fn tool_copy_prefix_width(line: &Line<'static>, first_line: bool) -> usize { |
| 3155 | let spans = line.spans.as_slice(); |
| 3156 | let mut index = 0; |
| 3157 | |
| 3158 | // The cache removes these exact local card rails before flattening. |
| 3159 | if spans |
| 3160 | .first() |
| 3161 | .is_some_and(|span| matches!(span.content.as_ref(), "─ " | "╭ " | "│ " | "╰ ")) |
| 3162 | { |
| 3163 | index = 1; |
| 3164 | } |
| 3165 | |
| 3166 | // Detail rows and pager affordances use the transcript rail as their |
| 3167 | // first span. The live transcript's general rail accounting removes it; |
| 3168 | // do not report it again as cell-local copy chrome. |
| 3169 | if spans |
| 3170 | .get(index) |
| 3171 | .is_some_and(|span| span.content.as_ref() == TRANSCRIPT_RAIL) |
| 3172 | { |
| 3173 | return 0; |
| 3174 | } |
| 3175 | |
| 3176 | // A labeled tool header starts with `<status> <family> `; a calm shell |
| 3177 | // header starts with `<status> ` on the cell's first row. Only consume |
| 3178 | // these tokens in those positions, so output beginning with `✓` or a |
| 3179 | // braille character remains copyable content. |
| 3180 | let Some(status) = spans.get(index).map(|span| span.content.as_ref()) else { |
| 3181 | return 0; |
| 3182 | }; |
| 3183 | if !status.ends_with(' ') || !is_tool_status_glyph(status.trim_end()) { |
| 3184 | return 0; |
| 3185 | } |
| 3186 | if let Some(family) = spans.get(index + 1).map(|span| span.content.as_ref()) |
| 3187 | && family.ends_with(' ') |
| 3188 | && is_tool_family_glyph(family.trim_end()) |
| 3189 | { |
| 3190 | return UnicodeWidthStr::width(status) + UnicodeWidthStr::width(family); |
| 3191 | } |
| 3192 | let mark = status.trim_end(); |
| 3193 | if first_line |
| 3194 | && (mark == codewhale_tui_kit::spinner::LIVE_STATIC_MARKER |
| 3195 | || mark.chars().all(|ch| matches!(ch, '\u{2800}'..='\u{28FF}'))) |
| 3196 | { |
| 3197 | return UnicodeWidthStr::width(status); |
| 3198 | } |
| 3199 | 0 |
| 3200 | } |
| 3201 | |
| 3202 | fn is_tool_status_glyph(text: &str) -> bool { |
| 3203 | let mut chars = text.chars(); |
| 3204 | let Some(ch) = chars.next() else { |
| 3205 | return false; |
| 3206 | }; |
| 3207 | chars.next().is_none() |
| 3208 | && matches!( |
| 3209 | ch, |
| 3210 | '\u{2713}' // ✓ |
| 3211 | | '\u{2715}' // ✕ |
| 3212 | | '\u{00B7}' // · |
| 3213 | | '!' // terminal warning |
| 3214 | | '\u{203A}' // › static still-mode marker |
| 3215 | | '\u{2800}'..='\u{28FF}' // braille spinner frames |
| 3216 | ) |
| 3217 | } |
| 3218 | |
| 3219 | fn is_tool_family_glyph(text: &str) -> bool { |
| 3220 | use crate::tui::widgets::tool_card::{ToolFamily, family_glyph}; |
| 3221 | |
| 3222 | [ |
| 3223 | ToolFamily::Read, |
| 3224 | ToolFamily::Patch, |
| 3225 | ToolFamily::Run, |
| 3226 | ToolFamily::Find, |
| 3227 | ToolFamily::Delegate, |
| 3228 | ToolFamily::Fanout, |
| 3229 | ToolFamily::Rlm, |
| 3230 | ToolFamily::Verify, |
| 3231 | ToolFamily::Think, |
| 3232 | ToolFamily::Generic, |
| 3233 | ] |
| 3234 | .into_iter() |
| 3235 | .any(|family| family_glyph(family) == text) |
| 3236 | } |
| 3237 | |
| 3238 | fn review_severity_color(severity: &str) -> Color { |
| 3239 | match severity { |
| 3240 | "error" => palette::STATUS_ERROR, |
| 3241 | "warning" => palette::STATUS_WARNING, |
| 3242 | _ => palette::WHALE_ACTION, |
| 3243 | } |
| 3244 | } |
| 3245 | |
| 3246 | fn format_review_location(path: Option<&String>, line: Option<u32>) -> String { |
| 3247 | let path = path.map(|p| p.trim().to_string()).filter(|p| !p.is_empty()); |
| 3248 | match (path, line) { |
| 3249 | (Some(path), Some(line)) => format!("{path}:{line}"), |
| 3250 | (Some(path), None) => path, |
| 3251 | (None, Some(line)) => format!("line {line}"), |
| 3252 | (None, None) => String::new(), |
| 3253 | } |
| 3254 | } |
| 3255 | |
| 3256 | fn status_symbol( |
| 3257 | started_at: Option<Instant>, |
| 3258 | status: ToolStatus, |
| 3259 | low_motion: bool, |
| 3260 | family: crate::tui::widgets::tool_card::ToolFamily, |
| 3261 | ) -> String { |
| 3262 | match status { |
| 3263 | ToolStatus::Running if family == crate::tui::widgets::tool_card::ToolFamily::Verify => { |
| 3264 | codewhale_tui_kit::spinner::verification_tick_frame(started_at, low_motion).to_string() |
| 3265 | } |
| 3266 | ToolStatus::Running => { |
| 3267 | codewhale_tui_kit::spinner::braille_spinner_frame(started_at, low_motion).to_string() |
| 3268 | } |
| 3269 | ToolStatus::Success => TOOL_DONE_SYMBOL.to_string(), |
| 3270 | ToolStatus::Queued | ToolStatus::Hydrated | ToolStatus::Stopped => { |
| 3271 | codewhale_tui_kit::glyphs::NEUTRAL.to_string() |
| 3272 | } |
| 3273 | ToolStatus::Warning => "!".to_string(), |
| 3274 | ToolStatus::Failed => TOOL_FAILED_SYMBOL.to_string(), |
| 3275 | } |
| 3276 | } |
| 3277 | |
| 3278 | fn details_affordance_line(text: &str, style: Style) -> Line<'static> { |
| 3279 | Line::from(vec![ |
| 3280 | Span::styled( |
| 3281 | TRANSCRIPT_RAIL.to_string(), |
| 3282 | Style::default().fg(palette::TEXT_DIM), |
| 3283 | ), |
| 3284 | Span::styled(text.to_string(), style), |
| 3285 | ]) |
| 3286 | } |
| 3287 | |
| 3288 | fn truncate_text(text: &str, max_len: usize) -> String { |
| 3289 | codewhale_tui_kit::ui_text::truncate_line_to_width(text, max_len) |
| 3290 | } |
| 3291 | |
| 3292 | /// Label glyph for an error cell. `Critical`/`Error` get the loudest marker; |
| 3293 | /// `Warning` is softer; `Info` is neutral. Kept as ASCII so it survives any |
| 3294 | /// terminal font fallback. |
| 3295 | fn error_label_text(severity: codewhale_error_taxonomy::ErrorSeverity) -> &'static str { |
| 3296 | match severity { |
| 3297 | codewhale_error_taxonomy::ErrorSeverity::Critical |
| 3298 | | codewhale_error_taxonomy::ErrorSeverity::Error => "Error", |
| 3299 | codewhale_error_taxonomy::ErrorSeverity::Warning => "Warn", |
| 3300 | codewhale_error_taxonomy::ErrorSeverity::Info => "Info", |
| 3301 | } |
| 3302 | } |
| 3303 | |
| 3304 | /// Label color for an error cell — drives the leading rail glyph. |
| 3305 | fn error_label_style(severity: codewhale_error_taxonomy::ErrorSeverity) -> Style { |
| 3306 | let color = match severity { |
| 3307 | codewhale_error_taxonomy::ErrorSeverity::Critical |
| 3308 | | codewhale_error_taxonomy::ErrorSeverity::Error => palette::STATUS_ERROR, |
| 3309 | codewhale_error_taxonomy::ErrorSeverity::Warning => palette::STATUS_WARNING, |
| 3310 | codewhale_error_taxonomy::ErrorSeverity::Info => palette::TEXT_DIM, |
| 3311 | }; |
| 3312 | Style::default().fg(color).add_modifier(Modifier::BOLD) |
| 3313 | } |
| 3314 | |
| 3315 | /// Body color for an error cell — softer than the label so the rail draws |
| 3316 | /// the eye but the prose stays readable. |
| 3317 | fn error_body_style(severity: codewhale_error_taxonomy::ErrorSeverity) -> Style { |
| 3318 | let color = match severity { |
| 3319 | codewhale_error_taxonomy::ErrorSeverity::Critical |
| 3320 | | codewhale_error_taxonomy::ErrorSeverity::Error => palette::STATUS_ERROR, |
| 3321 | codewhale_error_taxonomy::ErrorSeverity::Warning => palette::STATUS_WARNING, |
| 3322 | codewhale_error_taxonomy::ErrorSeverity::Info => palette::TEXT_MUTED, |
| 3323 | }; |
| 3324 | Style::default().fg(color) |
| 3325 | } |
| 3326 | |
| 3327 | pub(crate) fn normalize_error_code(code: &str) -> Option<String> { |
| 3328 | let trimmed = code.trim().trim_matches(['[', ']']).trim(); |
| 3329 | (!trimmed.is_empty()).then(|| trimmed.to_string()) |
| 3330 | } |
| 3331 | |
| 3332 | pub(crate) fn display_error_code<'a>(message: &str, code: Option<&'a str>) -> Option<&'a str> { |
| 3333 | let code = code?.trim().trim_matches(['[', ']']).trim(); |
| 3334 | if code.is_empty() || contains_code_token(message, code) { |
| 3335 | return None; |
| 3336 | } |
| 3337 | Some(code) |
| 3338 | } |
| 3339 | |
| 3340 | fn contains_code_token(message: &str, code: &str) -> bool { |
| 3341 | let lower_message = message.to_ascii_lowercase(); |
| 3342 | let lower_code = code.to_ascii_lowercase(); |
| 3343 | let is_token_char = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'_'; |
| 3344 | let bytes = lower_message.as_bytes(); |
| 3345 | let mut start = 0; |
| 3346 | while let Some(offset) = lower_message[start..].find(&lower_code) { |
| 3347 | let match_start = start + offset; |
| 3348 | let match_end = match_start + lower_code.len(); |
| 3349 | let left_ok = match_start == 0 || !is_token_char(bytes[match_start - 1]); |
| 3350 | let right_ok = match_end == bytes.len() || !is_token_char(bytes[match_end]); |
| 3351 | if left_ok && right_ok { |
| 3352 | return true; |
| 3353 | } |
| 3354 | start = match_start |
| 3355 | + lower_message[match_start..] |
| 3356 | .chars() |
| 3357 | .next() |
| 3358 | .map_or(1, char::len_utf8); |
| 3359 | } |
| 3360 | false |
| 3361 | } |
| 3362 | |
| 3363 | /// Render an engine error without markdown interpretation. The live transcript |
| 3364 | /// advertises the dedicated full-error pager once the error wraps past four |
| 3365 | /// rows: terminal height, scroll position, and adjacent tool cards can |
| 3366 | /// otherwise make a multiline recovery instruction look like a clipped |
| 3367 | /// one-line failure. Transcript/pager mode omits the recursive affordance |
| 3368 | /// while preserving every character. |
| 3369 | fn render_error_message( |
| 3370 | message: &str, |
| 3371 | severity: codewhale_error_taxonomy::ErrorSeverity, |
| 3372 | code: Option<&str>, |
| 3373 | width: u16, |
| 3374 | show_full_error_affordance: bool, |
| 3375 | ) -> Vec<Line<'static>> { |
| 3376 | // Error messages are machine-generated and should not be run through |
| 3377 | // markdown rendering, which would mangle env-var names containing |
| 3378 | // underscores (e.g. CODEWHALE_ALLOW_INSECURE_HTTP would lose them as |
| 3379 | // italic markers). |
| 3380 | let label = error_label_text(severity); |
| 3381 | let label_style = error_label_style(severity); |
| 3382 | let body_style = error_body_style(severity); |
| 3383 | let badge = display_error_code(message, code).map(|value| format!("[{value}]")); |
| 3384 | let prefix_width = UnicodeWidthStr::width(label); |
| 3385 | let content_width = width.saturating_sub(2 + prefix_width as u16).max(1); |
| 3386 | let mut lines: Vec<Line<'static>> = match badge { |
| 3387 | None => message |
| 3388 | .split('\n') |
| 3389 | .flat_map(|line| wrap_plain_line(line, body_style, content_width)) |
| 3390 | .collect(), |
| 3391 | Some(badge) => { |
| 3392 | let badge_style = Style::default().fg(palette::TEXT_MUTED); |
| 3393 | let badge_width = UnicodeWidthStr::width(badge.as_str()); |
| 3394 | let mut raw_lines = message.split('\n'); |
| 3395 | let first_raw = raw_lines.next().unwrap_or(""); |
| 3396 | let mut lines = Vec::new(); |
| 3397 | let remaining_on_first = (content_width as usize).saturating_sub(badge_width + 1); |
| 3398 | if remaining_on_first >= 12 { |
| 3399 | let mut head_len = None; |
| 3400 | for_each_wrapped_text(first_raw, remaining_on_first, |part| { |
| 3401 | if head_len.is_none() { |
| 3402 | head_len = Some(part.len()); |
| 3403 | } |
| 3404 | }); |
| 3405 | let split = head_len.unwrap_or(first_raw.len()); |
| 3406 | let head = &first_raw[..split]; |
| 3407 | let tail = &first_raw[split..]; |
| 3408 | let mut first_spans = vec![Span::styled(badge, badge_style)]; |
| 3409 | if !head.is_empty() { |
| 3410 | first_spans.push(Span::raw(" ")); |
| 3411 | first_spans.push(Span::styled(head.to_string(), body_style)); |
| 3412 | } |
| 3413 | lines.push(Line::from(first_spans)); |
| 3414 | if !tail.is_empty() { |
| 3415 | lines.extend(wrap_plain_line(tail, body_style, content_width)); |
| 3416 | } |
| 3417 | } else { |
| 3418 | lines.push(Line::from(Span::styled(badge, badge_style))); |
| 3419 | if !first_raw.is_empty() { |
| 3420 | lines.extend(wrap_plain_line(first_raw, body_style, content_width)); |
| 3421 | } |
| 3422 | } |
| 3423 | for line in raw_lines { |
| 3424 | lines.extend(wrap_plain_line(line, body_style, content_width)); |
| 3425 | } |
| 3426 | lines |
| 3427 | } |
| 3428 | }; |
| 3429 | if let Some(first) = lines.get_mut(0) { |
| 3430 | first.spans.insert(0, Span::raw(" ")); |
| 3431 | first.spans.insert(0, Span::styled(label, label_style)); |
| 3432 | } |
| 3433 | let rail = format!("{}{}", '\u{258F}', " ".repeat(prefix_width)); |
| 3434 | let rail_style = Style::default().fg(palette::TEXT_DIM); |
| 3435 | for line in lines.iter_mut().skip(1) { |
| 3436 | line.spans.insert(0, Span::styled(rail.clone(), rail_style)); |
| 3437 | } |
| 3438 | if show_full_error_affordance && lines.len() > 4 { |
| 3439 | lines.push(details_affordance_line( |
| 3440 | &crate::tui::key_shortcuts::tool_details_shortcut_action_hint("full error"), |
| 3441 | Style::default().fg(palette::TEXT_MUTED).italic(), |
| 3442 | )); |
| 3443 | } |
| 3444 | lines |
| 3445 | } |
| 3446 | |
| 3447 | fn render_tool_header( |
| 3448 | title: &str, |
| 3449 | state: Option<&str>, |
| 3450 | status: ToolStatus, |
| 3451 | started_at: Option<Instant>, |
| 3452 | low_motion: bool, |
| 3453 | locale: Locale, |
| 3454 | ) -> Line<'static> { |
| 3455 | let family = crate::tui::widgets::tool_card::tool_family_for_title(title); |
| 3456 | render_tool_header_with_family_and_summary( |
| 3457 | family, None, state, status, started_at, low_motion, locale, |
| 3458 | ) |
| 3459 | } |
| 3460 | |
| 3461 | fn render_tool_header_with_summary( |
| 3462 | title: &str, |
| 3463 | summary: Option<&str>, |
| 3464 | state: Option<&str>, |
| 3465 | status: ToolStatus, |
| 3466 | started_at: Option<Instant>, |
| 3467 | low_motion: bool, |
| 3468 | locale: Locale, |
| 3469 | ) -> Line<'static> { |
| 3470 | let family = crate::tui::widgets::tool_card::tool_family_for_title(title); |
| 3471 | render_tool_header_with_family_and_summary( |
| 3472 | family, summary, state, status, started_at, low_motion, locale, |
| 3473 | ) |
| 3474 | } |
| 3475 | |
| 3476 | /// Render a tool-card header with an explicit verb family. Lets callers |
| 3477 | /// (e.g. `GenericToolCell`) bypass the legacy title→family mapping when |
| 3478 | /// they already know the actual tool name. |
| 3479 | fn render_tool_header_with_family_and_summary( |
| 3480 | family: crate::tui::widgets::tool_card::ToolFamily, |
| 3481 | summary: Option<&str>, |
| 3482 | state: Option<&str>, |
| 3483 | status: ToolStatus, |
| 3484 | started_at: Option<Instant>, |
| 3485 | low_motion: bool, |
| 3486 | locale: Locale, |
| 3487 | ) -> Line<'static> { |
| 3488 | let state_owned = match state { |
| 3489 | Some(state) => state.to_string(), |
| 3490 | None => tool_status_label(status, locale).into_owned(), |
| 3491 | }; |
| 3492 | |
| 3493 | let glyph = crate::tui::widgets::tool_card::family_glyph(family); |
| 3494 | let verb = crate::tui::widgets::tool_card::family_label(family, locale); |
| 3495 | |
| 3496 | let glyph_style = Style::default().fg(tool_glyph_color(status, family)); |
| 3497 | let mut spans = vec![ |
| 3498 | Span::styled( |
| 3499 | format!("{} ", status_symbol(started_at, status, low_motion, family)), |
| 3500 | glyph_style, |
| 3501 | ), |
| 3502 | Span::styled(format!("{glyph} "), glyph_style), |
| 3503 | Span::styled(verb.to_string(), tool_title_style(status)), |
| 3504 | ]; |
| 3505 | if !state_owned.is_empty() { |
| 3506 | spans.push(Span::styled(" ", Style::default())); |
| 3507 | spans.push(Span::styled(state_owned, tool_status_style(status, family))); |
| 3508 | } |
| 3509 | |
| 3510 | // #4148: don't let the summary echo the verb it sits next to — an |
| 3511 | // identity/summary that resolves to the family word itself would render a |
| 3512 | // duplicate like "delegate · delegate". When the summary collapses to the |
| 3513 | // verb, the verb already carries the signal, so drop the redundant tail. |
| 3514 | if let Some(summary) = summary |
| 3515 | .and_then(normalize_header_summary) |
| 3516 | .filter(|summary| !summary.eq_ignore_ascii_case(verb.as_ref())) |
| 3517 | { |
| 3518 | spans.push(Span::styled(" · ", Style::default().fg(palette::TEXT_DIM))); |
| 3519 | spans.push(Span::styled( |
| 3520 | truncate_text(&summary, TOOL_HEADER_SUMMARY_LIMIT), |
| 3521 | Style::default().fg(palette::TEXT_MUTED), |
| 3522 | )); |
| 3523 | } |
| 3524 | if state.is_none() |
| 3525 | && status == ToolStatus::Running |
| 3526 | && let Some(elapsed) = started_at.and_then(running_elapsed_label) |
| 3527 | { |
| 3528 | spans.push(Span::styled( |
| 3529 | format!(" {elapsed}"), |
| 3530 | Style::default().fg(palette::TEXT_DIM), |
| 3531 | )); |
| 3532 | } |
| 3533 | |
| 3534 | Line::from(spans) |
| 3535 | } |
| 3536 | |
| 3537 | fn header_shows_in_full(header: &Line<'static>, summary: &str, available: usize) -> bool { |
| 3538 | normalize_header_summary(summary).is_none_or(|summary| { |
| 3539 | codewhale_tui_kit::ui_text::text_display_width(&summary) <= TOOL_HEADER_SUMMARY_LIMIT |
| 3540 | }) && header.width() <= available |
| 3541 | } |
| 3542 | |
| 3543 | fn header_repeats_args( |
| 3544 | header: &Line<'static>, |
| 3545 | header_summary: Option<&str>, |
| 3546 | args: &str, |
| 3547 | available: usize, |
| 3548 | ) -> bool { |
| 3549 | let args = args.trim(); |
| 3550 | let shown = match args.split_once(": ") { |
| 3551 | Some((_, value)) if !args.contains(", ") => value.trim(), |
| 3552 | _ => args, |
| 3553 | }; |
| 3554 | header_summary.is_some_and(|summary| { |
| 3555 | (summary == shown || summary.ends_with(&format!(" \u{00B7} {shown}"))) |
| 3556 | && header_shows_in_full(header, summary, available) |
| 3557 | }) |
| 3558 | } |
| 3559 | |
| 3560 | fn normalize_header_summary(summary: &str) -> Option<String> { |
| 3561 | let normalized = summary |
| 3562 | .split_whitespace() |
| 3563 | .collect::<Vec<_>>() |
| 3564 | .join(" ") |
| 3565 | .trim() |
| 3566 | .to_string(); |
| 3567 | if normalized.is_empty() { |
| 3568 | None |
| 3569 | } else { |
| 3570 | Some(normalized) |
| 3571 | } |
| 3572 | } |
| 3573 | |
| 3574 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 3575 | pub(crate) enum ActivitySweep { |
| 3576 | VerbAndStatus, |
| 3577 | StatusOnly, |
| 3578 | } |
| 3579 | |
| 3580 | pub(crate) fn tool_header_sweep_extent( |
| 3581 | shape: ActivitySweep, |
| 3582 | line: &Line<'static>, |
| 3583 | line_in_cell: usize, |
| 3584 | ) -> Option<std::ops::Range<usize>> { |
| 3585 | let has_rail = line |
| 3586 | .spans |
| 3587 | .first() |
| 3588 | .is_some_and(|span| matches!(span.content.as_ref(), "─ " | "╭ " | "│ " | "╰ ")); |
| 3589 | match (shape, line_in_cell) { |
| 3590 | (ActivitySweep::StatusOnly, 0) if has_rail => { |
| 3591 | (line.spans.get(4).is_some_and(|span| span.content == " ") |
| 3592 | && line |
| 3593 | .spans |
| 3594 | .get(5) |
| 3595 | .is_some_and(|span| !span.content.trim().is_empty())) |
| 3596 | .then_some(5..6) |
| 3597 | } |
| 3598 | (ActivitySweep::StatusOnly, 0) => { |
| 3599 | let status_fg = tool_glyph_color( |
| 3600 | ToolStatus::Running, |
| 3601 | crate::tui::widgets::tool_card::ToolFamily::Run, |
| 3602 | ); |
| 3603 | (line.spans.len() >= 4 |
| 3604 | && line.spans[3].style.fg == Some(status_fg) |
| 3605 | && !line.spans[3].content.trim().is_empty()) |
| 3606 | .then_some(3..4) |
| 3607 | } |
| 3608 | (ActivitySweep::StatusOnly, 1) if !has_rail => { |
| 3609 | let status_fg = tool_glyph_color( |
| 3610 | ToolStatus::Running, |
| 3611 | crate::tui::widgets::tool_card::ToolFamily::Run, |
| 3612 | ); |
| 3613 | line.spans |
| 3614 | .first() |
| 3615 | .is_some_and(|span| { |
| 3616 | span.style.fg == Some(status_fg) |
| 3617 | && !span.content.starts_with(char::is_whitespace) |
| 3618 | && !span.content.trim().is_empty() |
| 3619 | }) |
| 3620 | .then_some(0..1) |
| 3621 | } |
| 3622 | (ActivitySweep::VerbAndStatus, 0) => { |
| 3623 | let base = usize::from(has_rail); |
| 3624 | let verb = base + 2; |
| 3625 | line.spans.get(verb)?; |
| 3626 | if line |
| 3627 | .spans |
| 3628 | .get(verb + 1) |
| 3629 | .is_some_and(|span| span.content == " ") |
| 3630 | && line.spans.get(verb + 2).is_some() |
| 3631 | { |
| 3632 | Some(verb..verb + 3) |
| 3633 | } else { |
| 3634 | Some(verb..verb + 1) |
| 3635 | } |
| 3636 | } |
| 3637 | _ => None, |
| 3638 | } |
| 3639 | } |
| 3640 | |
| 3641 | pub(crate) fn tool_header_settle_spans(tool: &ToolCell, line: &Line<'static>) -> Vec<usize> { |
| 3642 | let base = usize::from( |
| 3643 | line.spans |
| 3644 | .first() |
| 3645 | .is_some_and(|span| matches!(span.content.as_ref(), "─ " | "╭ " | "│ " | "╰ ")), |
| 3646 | ); |
| 3647 | let mut spans = vec![base]; |
| 3648 | if line |
| 3649 | .spans |
| 3650 | .get(base + 3) |
| 3651 | .is_some_and(|span| span.content == " ") |
| 3652 | { |
| 3653 | spans.extend([base + 1, base + 4]); |
| 3654 | } else if let (ToolCell::Exec(_), Some(status)) = (tool, tool.status()) { |
| 3655 | let status_fg = tool_glyph_color(status, crate::tui::widgets::tool_card::ToolFamily::Run); |
| 3656 | spans.extend((base + 2..line.spans.len()).find(|index| { |
| 3657 | line.spans[*index].style.fg == Some(status_fg) |
| 3658 | && line.spans[index - 1].content == " \u{00B7} " |
| 3659 | })); |
| 3660 | } |
| 3661 | spans.retain(|index| { |
| 3662 | line.spans |
| 3663 | .get(*index) |
| 3664 | .is_some_and(|span| !span.content.trim().is_empty()) |
| 3665 | }); |
| 3666 | spans |
| 3667 | } |
| 3668 | |
| 3669 | pub(crate) fn running_elapsed_label(started_at: Instant) -> Option<String> { |
| 3670 | let secs = started_at.elapsed().as_secs(); |
| 3671 | (secs >= 1).then(|| codewhale_command_contract::elapsed::format_elapsed_secs(secs)) |
| 3672 | } |
| 3673 | |
| 3674 | pub(crate) fn stale_shell_status_label(elapsed_since_output_ms: u64, locale: Locale) -> String { |
| 3675 | tr(locale, MessageId::ToolReceiptQuiet).replace( |
| 3676 | "{duration}", |
| 3677 | &codewhale_command_contract::elapsed::format_elapsed_ms(elapsed_since_output_ms), |
| 3678 | ) |
| 3679 | } |
| 3680 | |
| 3681 | fn render_card_detail_line( |
| 3682 | label: Option<&str>, |
| 3683 | value: &str, |
| 3684 | value_style: Style, |
| 3685 | width: u16, |
| 3686 | ) -> Vec<Line<'static>> { |
| 3687 | let label_text = label.map(|text| format!("{text}:")); |
| 3688 | let prefix_width = UnicodeWidthStr::width(TRANSCRIPT_RAIL) |
| 3689 | + label_text.as_deref().map_or(0, UnicodeWidthStr::width) |
| 3690 | + usize::from(label.is_some()); |
| 3691 | let content_width = usize::from(width).saturating_sub(prefix_width).max(1); |
| 3692 | |
| 3693 | let mut lines = Vec::new(); |
| 3694 | for (idx, part) in wrap_text(value, content_width).into_iter().enumerate() { |
| 3695 | let mut spans = vec![Span::styled( |
| 3696 | TRANSCRIPT_RAIL.to_string(), |
| 3697 | Style::default().fg(palette::TEXT_DIM), |
| 3698 | )]; |
| 3699 | if idx == 0 { |
| 3700 | if let Some(label_text) = label_text.as_deref() { |
| 3701 | spans.push(Span::styled( |
| 3702 | label_text.to_string(), |
| 3703 | tool_detail_label_style(), |
| 3704 | )); |
| 3705 | spans.push(Span::raw(" ")); |
| 3706 | } |
| 3707 | } else if let Some(label_text) = label_text.as_deref() { |
| 3708 | spans.push(Span::raw( |
| 3709 | " ".repeat(UnicodeWidthStr::width(label_text) + 1), |
| 3710 | )); |
| 3711 | } |
| 3712 | spans.push(Span::styled(part, value_style)); |
| 3713 | lines.push(Line::from(spans)); |
| 3714 | } |
| 3715 | lines |
| 3716 | } |
| 3717 | |
| 3718 | /// `render_card_detail_line_single` for a coloured row: one line, never |
| 3719 | /// wrapped, so an intact path or URL keeps the same hitbox with or without |
| 3720 | /// colour. |
| 3721 | fn render_card_detail_line_single_styled( |
| 3722 | label: Option<&str>, |
| 3723 | segments: &[tool_output::StyledSegment], |
| 3724 | value_style: Style, |
| 3725 | ) -> Line<'static> { |
| 3726 | let mut line = render_card_detail_line_single(label, "", value_style); |
| 3727 | line.spans.pop(); |
| 3728 | for (text, style) in segments { |
| 3729 | line.spans |
| 3730 | .push(Span::styled(text.clone(), value_style.patch(*style))); |
| 3731 | } |
| 3732 | line |
| 3733 | } |
| 3734 | |
| 3735 | fn render_card_detail_line_single( |
| 3736 | label: Option<&str>, |
| 3737 | value: &str, |
| 3738 | value_style: Style, |
| 3739 | ) -> Line<'static> { |
| 3740 | let label_text = label.map(|text| format!("{text}:")); |
| 3741 | let mut spans = vec![Span::styled( |
| 3742 | TRANSCRIPT_RAIL.to_string(), |
| 3743 | Style::default().fg(palette::TEXT_DIM), |
| 3744 | )]; |
| 3745 | if let Some(label_text) = label_text { |
| 3746 | spans.push(Span::styled(label_text, tool_detail_label_style())); |
| 3747 | spans.push(Span::raw(" ")); |
| 3748 | } |
| 3749 | spans.push(Span::styled(value.to_string(), value_style)); |
| 3750 | Line::from(spans) |
| 3751 | } |
| 3752 | |
| 3753 | // Tool-card ink. The transcript paints tool cards with the dark whale tokens |
| 3754 | // regardless of the selected theme, as every other cell in this file does by |
| 3755 | // reading the same `palette` constants directly. |
| 3756 | |
| 3757 | fn tool_title_style(status: ToolStatus) -> Style { |
| 3758 | if status == ToolStatus::Success { |
| 3759 | Style::default().fg(palette::TEXT_MUTED) |
| 3760 | } else { |
| 3761 | Style::default() |
| 3762 | .fg(palette::TEXT_SOFT) |
| 3763 | .add_modifier(Modifier::BOLD) |
| 3764 | } |
| 3765 | } |
| 3766 | |
| 3767 | /// Right-side status text ("running", "done", "issue"). Reads as the glyph it |
| 3768 | /// sits beside, not as the rail. |
| 3769 | fn tool_status_style( |
| 3770 | status: ToolStatus, |
| 3771 | family: crate::tui::widgets::tool_card::ToolFamily, |
| 3772 | ) -> Style { |
| 3773 | Style::default().fg(tool_glyph_color(status, family)) |
| 3774 | } |
| 3775 | |
| 3776 | /// Detail label style ("command:", "time:", step markers). |
| 3777 | fn tool_detail_label_style() -> Style { |
| 3778 | Style::default().fg(palette::TEXT_DIM) |
| 3779 | } |
| 3780 | |
| 3781 | /// Colour of a tool cell's **rail** — the card border. |
| 3782 | /// |
| 3783 | /// This is OMP's `output-block.ts` rule verbatim: a block takes a state and |
| 3784 | /// its border colour follows it. In-flight takes the action accent, a settled |
| 3785 | /// success recedes into muted text so finished work stops competing for the |
| 3786 | /// eye, and only warning and failure keep a loud colour. `Hydrated` is a |
| 3787 | /// stalled "loaded, not run", not live work, so it takes the hint |
| 3788 | /// colour instead of borrowing the running accent and reading as in-flight. |
| 3789 | /// |
| 3790 | /// The glyph and status word use the same lifecycle ink; the glyph shape |
| 3791 | /// preserves the tool's identity after its successful result settles. |
| 3792 | fn tool_rail_color(status: ToolStatus) -> Color { |
| 3793 | match status { |
| 3794 | ToolStatus::Running => palette::WHALE_ACTION, |
| 3795 | ToolStatus::Success | ToolStatus::Stopped => palette::TEXT_MUTED, |
| 3796 | ToolStatus::Queued | ToolStatus::Hydrated => palette::TEXT_DIM, |
| 3797 | ToolStatus::Warning => palette::WHALE_HUMAN, |
| 3798 | ToolStatus::Failed => palette::WHALE_ERROR, |
| 3799 | } |
| 3800 | } |
| 3801 | |
| 3802 | /// Settled success recedes; warning and failure retain their attention ink. |
| 3803 | fn tool_glyph_color( |
| 3804 | status: ToolStatus, |
| 3805 | _family: crate::tui::widgets::tool_card::ToolFamily, |
| 3806 | ) -> Color { |
| 3807 | tool_rail_color(status) |
| 3808 | } |
| 3809 | |
| 3810 | pub(crate) fn tool_status_label(status: ToolStatus, locale: Locale) -> Cow<'static, str> { |
| 3811 | tr( |
| 3812 | locale, |
| 3813 | match status { |
| 3814 | ToolStatus::Queued => MessageId::ToolStatusQueued, |
| 3815 | ToolStatus::Running => MessageId::ToolReceiptRunning, |
| 3816 | ToolStatus::Success => MessageId::ToolReceiptDone, |
| 3817 | ToolStatus::Hydrated => MessageId::ToolReceiptHydrated, |
| 3818 | ToolStatus::Stopped => MessageId::ToolReceiptStopped, |
| 3819 | ToolStatus::Warning => MessageId::ToolReceiptIssue, |
| 3820 | ToolStatus::Failed => MessageId::ToolReceiptFailed, |
| 3821 | }, |
| 3822 | ) |
| 3823 | } |
| 3824 | |
| 3825 | /// A finished read/find card can truthfully name how many rendered lines came |
| 3826 | /// back. Generic command output does not preserve typed stdout/stderr streams, |
| 3827 | /// so Run receipts stay at localized `done` instead of inventing per-stream |
| 3828 | /// counts from display text. |
| 3829 | pub(crate) fn tool_receipt_label( |
| 3830 | family: crate::tui::widgets::tool_card::ToolFamily, |
| 3831 | status: ToolStatus, |
| 3832 | output: Option<&str>, |
| 3833 | locale: Locale, |
| 3834 | ) -> Cow<'static, str> { |
| 3835 | if status != ToolStatus::Success { |
| 3836 | return tool_status_label(status, locale); |
| 3837 | } |
| 3838 | use crate::tui::widgets::tool_card::ToolFamily; |
| 3839 | match family { |
| 3840 | ToolFamily::Read | ToolFamily::Find => { |
| 3841 | let lines = output.map(count_output_lines).unwrap_or(0); |
| 3842 | if lines == 0 { |
| 3843 | codewhale_localization::tr( |
| 3844 | locale, |
| 3845 | codewhale_localization::MessageId::ToolReceiptDone, |
| 3846 | ) |
| 3847 | } else if lines == 1 { |
| 3848 | codewhale_localization::tr( |
| 3849 | locale, |
| 3850 | codewhale_localization::MessageId::ToolReceiptLinesSingular, |
| 3851 | ) |
| 3852 | } else { |
| 3853 | Cow::Owned( |
| 3854 | codewhale_localization::tr( |
| 3855 | locale, |
| 3856 | codewhale_localization::MessageId::ToolReceiptLinesPlural, |
| 3857 | ) |
| 3858 | .replace("{count}", &lines.to_string()), |
| 3859 | ) |
| 3860 | } |
| 3861 | } |
| 3862 | ToolFamily::Run => { |
| 3863 | codewhale_localization::tr(locale, codewhale_localization::MessageId::ToolReceiptDone) |
| 3864 | } |
| 3865 | _ => codewhale_localization::tr(locale, codewhale_localization::MessageId::ToolReceiptDone), |
| 3866 | } |
| 3867 | } |
| 3868 | |
| 3869 | fn count_output_lines(output: &str) -> usize { |
| 3870 | if output.is_empty() { |
| 3871 | 0 |
| 3872 | } else { |
| 3873 | output.lines().count() |
| 3874 | } |
| 3875 | } |
| 3876 | |
| 3877 | /// Default value style for tool detail rows. |
| 3878 | fn tool_value_style() -> Style { |
| 3879 | Style::default().fg(palette::TEXT_MUTED) |
| 3880 | } |
| 3881 | |
| 3882 | /// Find the first `path:line` reference in a rendered cell, else the first |
| 3883 | /// bare workspace file path, at line 1. |
| 3884 | /// |
| 3885 | /// Pure: it resolves and stats candidate paths but never launches anything. |
| 3886 | /// Spawning the editor belongs to `external_editor`, which owns the terminal |
| 3887 | /// handoff — this used to build its own `Command` and `spawn()` it detached |
| 3888 | /// while the TUI still held raw mode, the alt screen and mouse capture, and it |
| 3889 | /// did that once per matching line, so one click could leave N editors fighting |
| 3890 | /// the TUI for the same tty (#6235). |
| 3891 | /// |
| 3892 | /// Returns the first match rather than every match: a click is one request to |
| 3893 | /// open one file. |
| 3894 | pub(crate) fn first_file_line_reference(text: &str, workspace: &Path) -> Option<(PathBuf, u32)> { |
| 3895 | text.lines() |
| 3896 | .find_map(|line| file_line_reference(line, workspace)) |
| 3897 | .or_else(|| { |
| 3898 | text.lines() |
| 3899 | .find_map(|line| bare_file_reference(line, workspace)) |
| 3900 | }) |
| 3901 | } |
| 3902 | |
| 3903 | /// The first `path:line` on one line of text that names a file inside the |
| 3904 | /// workspace, as `(absolute path, line)`. |
| 3905 | /// |
| 3906 | /// Accepts the forms tools and models print: `src/a.rs:12`, `src/a.rs:12:5`, |
| 3907 | /// `--> src/a.rs:12:5` (rustc), `` `src/a.rs:12` `` and a reference inside a |
| 3908 | /// sentence or brackets. The text is model output, so it is not trusted to |
| 3909 | /// name a file: every candidate goes through [`workspace_file`], which |
| 3910 | /// refuses `..`, absolute paths outside the workspace and links. |
| 3911 | pub(crate) fn file_line_reference(line: &str, workspace: &Path) -> Option<(PathBuf, u32)> { |
| 3912 | reference_tokens(line).find_map(|token| { |
| 3913 | let (path_str, line_no) = split_path_line(token)?; |
| 3914 | if !looks_like_file_path(path_str) { |
| 3915 | return None; |
| 3916 | } |
| 3917 | let path_str = path_str.strip_prefix("./").unwrap_or(path_str); |
| 3918 | workspace_file(workspace, path_str).map(|absolute| (absolute, line_no)) |
| 3919 | }) |
| 3920 | } |
| 3921 | |
| 3922 | pub(crate) fn bare_file_reference(line: &str, workspace: &Path) -> Option<(PathBuf, u32)> { |
| 3923 | reference_tokens(line).find_map(|token| { |
| 3924 | let token = token.trim_end_matches(':'); |
| 3925 | if !looks_like_file_path(token) { |
| 3926 | return None; |
| 3927 | } |
| 3928 | let token = token.strip_prefix("./").unwrap_or(token); |
| 3929 | workspace_file(workspace, token).map(|absolute| (absolute, 1)) |
| 3930 | }) |
| 3931 | } |
| 3932 | |
| 3933 | fn reference_tokens(line: &str) -> impl Iterator<Item = &str> { |
| 3934 | line.split_whitespace().map(|token| { |
| 3935 | // Leading `.` stays: `./src/a.rs` is relative, not `/src/a.rs`. |
| 3936 | token |
| 3937 | .trim_start_matches(['`', '\'', '"', '(', '[', '<']) |
| 3938 | .trim_end_matches(['`', '\'', '"', ')', ']', '>', ',', ';', '.']) |
| 3939 | }) |
| 3940 | } |
| 3941 | |
| 3942 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 3943 | pub(crate) struct WorkspaceTarget { |
| 3944 | pub path: PathBuf, |
| 3945 | pub is_dir: bool, |
| 3946 | } |
| 3947 | |
| 3948 | pub(crate) fn workspace_target(workspace: &Path, raw: &str) -> Option<WorkspaceTarget> { |
| 3949 | let trailing_sep = raw.ends_with(['/', '\\']); |
| 3950 | let trimmed = raw.trim_end_matches(['/', '\\']); |
| 3951 | let trimmed = trimmed |
| 3952 | .strip_prefix("./") |
| 3953 | .or_else(|| trimmed.strip_prefix(".\\")) |
| 3954 | .unwrap_or(trimmed); |
| 3955 | if trimmed.is_empty() { |
| 3956 | return None; |
| 3957 | } |
| 3958 | let resolved_workspace = workspace.canonicalize().ok()?; |
| 3959 | let relative = codewhale_snapshot::workspace_relative_path(workspace, trimmed) |
| 3960 | .or_else(|| codewhale_snapshot::workspace_relative_path(&resolved_workspace, trimmed))?; |
| 3961 | let mut path = workspace.to_path_buf(); |
| 3962 | let mut is_file = false; |
| 3963 | let mut is_dir = false; |
| 3964 | let mut has_component = false; |
| 3965 | for component in relative.components() { |
| 3966 | has_component = true; |
| 3967 | path.push(component); |
| 3968 | let metadata = std::fs::symlink_metadata(&path).ok()?; |
| 3969 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) { |
| 3970 | return None; |
| 3971 | } |
| 3972 | is_file = metadata.is_file(); |
| 3973 | is_dir = metadata.is_dir(); |
| 3974 | } |
| 3975 | if !has_component || (!is_file && !is_dir) || (trailing_sep && !is_dir) { |
| 3976 | return None; |
| 3977 | } |
| 3978 | let inside = path.canonicalize().ok()?.starts_with(&resolved_workspace); |
| 3979 | inside.then_some(WorkspaceTarget { path, is_dir }) |
| 3980 | } |
| 3981 | |
| 3982 | /// The regular file `raw` names inside `workspace`, as |
| 3983 | /// `workspace.join(relative)`, or `None`. |
| 3984 | /// |
| 3985 | /// [`codewhale_snapshot::workspace_relative_path`] checks only the text, and |
| 3986 | /// `is_file()` follows links, so a link inside the workspace (`vendor -> /`, |
| 3987 | /// `notes.md -> ~/.ssh/config`) used to pass. Each part below the workspace |
| 3988 | /// is read with `symlink_metadata` and a link is refused, as |
| 3989 | /// `runtime_api::workspace::confined_directory` does, and the resolved path |
| 3990 | /// must still sit under the resolved workspace. Callers that act later check |
| 3991 | /// again at that point: this is a check at one moment, not a lock. |
| 3992 | pub(crate) fn workspace_file(workspace: &Path, raw: &str) -> Option<PathBuf> { |
| 3993 | workspace_target(workspace, raw) |
| 3994 | .filter(|target| !target.is_dir) |
| 3995 | .map(|target| target.path) |
| 3996 | } |
| 3997 | |
| 3998 | pub(crate) fn parse_workspace_link_candidate( |
| 3999 | raw: &str, |
| 4000 | workspace: &Path, |
| 4001 | ) -> Option<(WorkspaceTarget, Option<u32>)> { |
| 4002 | let candidate = raw.trim(); |
| 4003 | if candidate.is_empty() { |
| 4004 | return None; |
| 4005 | } |
| 4006 | if let Some((path_part, line)) = split_hash_line_fragment(candidate) |
| 4007 | && let Some(target) = workspace_target(workspace, path_part) |
| 4008 | { |
| 4009 | return (!target.is_dir).then_some((target, Some(line))); |
| 4010 | } |
| 4011 | if let Some((path_part, line)) = split_strict_path_line_col(candidate) |
| 4012 | && let Some(target) = workspace_target(workspace, path_part) |
| 4013 | { |
| 4014 | return (!target.is_dir).then_some((target, Some(line))); |
| 4015 | } |
| 4016 | workspace_target(workspace, candidate).map(|target| (target, None)) |
| 4017 | } |
| 4018 | |
| 4019 | fn split_hash_line_fragment(candidate: &str) -> Option<(&str, u32)> { |
| 4020 | let (path_part, fragment) = candidate.rsplit_once('#')?; |
| 4021 | if path_part.is_empty() { |
| 4022 | return None; |
| 4023 | } |
| 4024 | let rest = fragment |
| 4025 | .strip_prefix('L') |
| 4026 | .or_else(|| fragment.strip_prefix('l'))?; |
| 4027 | let (start_part, end_part) = match rest.split_once('-') { |
| 4028 | Some((start, end)) => ( |
| 4029 | start, |
| 4030 | Some( |
| 4031 | end.strip_prefix('L') |
| 4032 | .or_else(|| end.strip_prefix('l')) |
| 4033 | .unwrap_or(end), |
| 4034 | ), |
| 4035 | ), |
| 4036 | None => (rest, None), |
| 4037 | }; |
| 4038 | if start_part.is_empty() || !start_part.chars().all(|c| c.is_ascii_digit()) { |
| 4039 | return None; |
| 4040 | } |
| 4041 | if let Some(end) = end_part { |
| 4042 | if end.is_empty() || !end.chars().all(|c| c.is_ascii_digit()) { |
| 4043 | return None; |
| 4044 | } |
| 4045 | let end_line: u32 = end.parse().ok()?; |
| 4046 | if end_line == 0 { |
| 4047 | return None; |
| 4048 | } |
| 4049 | } |
| 4050 | let line = start_part.parse::<u32>().ok().filter(|line| *line > 0)?; |
| 4051 | Some((path_part, line)) |
| 4052 | } |
| 4053 | |
| 4054 | fn split_strict_path_line_col(candidate: &str) -> Option<(&str, u32)> { |
| 4055 | let (before_last, last) = candidate.rsplit_once(':')?; |
| 4056 | if last.is_empty() || !last.chars().all(|c| c.is_ascii_digit()) { |
| 4057 | return None; |
| 4058 | } |
| 4059 | if let Some((before_prev, prev)) = before_last.rsplit_once(':') |
| 4060 | && !before_prev.is_empty() |
| 4061 | && !prev.is_empty() |
| 4062 | && prev.chars().all(|c| c.is_ascii_digit()) |
| 4063 | { |
| 4064 | let line = prev.parse::<u32>().ok().filter(|line| *line > 0)?; |
| 4065 | let _col = last.parse::<u32>().ok().filter(|col| *col > 0)?; |
| 4066 | return Some((before_prev, line)); |
| 4067 | } |
| 4068 | if before_last.is_empty() { |
| 4069 | return None; |
| 4070 | } |
| 4071 | let line = last.parse::<u32>().ok().filter(|line| *line > 0)?; |
| 4072 | Some((before_last, line)) |
| 4073 | } |
| 4074 | |
| 4075 | pub(crate) fn file_uri_for_path(path: &Path) -> Option<String> { |
| 4076 | if !path.is_absolute() { |
| 4077 | return None; |
| 4078 | } |
| 4079 | let raw = path.to_str()?; |
| 4080 | let normalized = raw.replace('\\', "/"); |
| 4081 | let mut uri = String::with_capacity(normalized.len() + 8); |
| 4082 | uri.push_str("file://"); |
| 4083 | if !normalized.starts_with('/') { |
| 4084 | uri.push('/'); |
| 4085 | } |
| 4086 | const HEX: &[u8; 16] = b"0123456789ABCDEF"; |
| 4087 | for &byte in normalized.as_bytes() { |
| 4088 | let keep = |
| 4089 | byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'-' | b'.' | b'_' | b'~' | b':'); |
| 4090 | if keep { |
| 4091 | uri.push(byte as char); |
| 4092 | } else { |
| 4093 | uri.push('%'); |
| 4094 | uri.push(HEX[usize::from(byte >> 4)] as char); |
| 4095 | uri.push(HEX[usize::from(byte & 0x0f)] as char); |
| 4096 | } |
| 4097 | } |
| 4098 | Some(uri) |
| 4099 | } |
| 4100 | |
| 4101 | pub(crate) fn workspace_target_from_file_uri( |
| 4102 | workspace: &Path, |
| 4103 | uri: &str, |
| 4104 | ) -> Option<WorkspaceTarget> { |
| 4105 | let path_str = uri.strip_prefix("file://")?; |
| 4106 | let path_str = path_str.strip_prefix("localhost").unwrap_or(path_str); |
| 4107 | let path_str = path_str.split('#').next().unwrap_or(path_str); |
| 4108 | let path_str = path_str.split('?').next().unwrap_or(path_str); |
| 4109 | let decoded = decode_percent_encoded_uri_path(path_str)?; |
| 4110 | let decoded = if cfg!(windows) { |
| 4111 | decoded |
| 4112 | .strip_prefix('/') |
| 4113 | .filter(|rest| rest.as_bytes().get(1) == Some(&b':')) |
| 4114 | .unwrap_or(&decoded) |
| 4115 | } else { |
| 4116 | &decoded |
| 4117 | }; |
| 4118 | workspace_target(workspace, decoded) |
| 4119 | } |
| 4120 | |
| 4121 | fn decode_percent_encoded_uri_path(input: &str) -> Option<String> { |
| 4122 | let bytes = input.as_bytes(); |
| 4123 | let mut out = Vec::with_capacity(bytes.len()); |
| 4124 | let mut i = 0; |
| 4125 | while i < bytes.len() { |
| 4126 | if bytes[i] == b'%' { |
| 4127 | if i + 2 >= bytes.len() { |
| 4128 | return None; |
| 4129 | } |
| 4130 | let hi = (bytes[i + 1] as char).to_digit(16)?; |
| 4131 | let lo = (bytes[i + 2] as char).to_digit(16)?; |
| 4132 | out.push(((hi << 4) | lo) as u8); |
| 4133 | i += 3; |
| 4134 | } else { |
| 4135 | out.push(bytes[i]); |
| 4136 | i += 1; |
| 4137 | } |
| 4138 | } |
| 4139 | String::from_utf8(out).ok() |
| 4140 | } |
| 4141 | |
| 4142 | /// Split `path:N`, `path:N:C` or `path:N:text` at the first all-digit |
| 4143 | /// segment after the path. Earlier colons stay in the path (`C:\x.rs:3`). |
| 4144 | fn split_path_line(token: &str) -> Option<(&str, u32)> { |
| 4145 | let mut offset = 0; |
| 4146 | for (index, part) in token.split(':').enumerate() { |
| 4147 | if index > 0 && !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()) { |
| 4148 | let path = token[..offset].strip_suffix(':')?; |
| 4149 | let line = part.parse().ok().filter(|line| *line > 0)?; |
| 4150 | return (!path.is_empty()).then_some((path, line)); |
| 4151 | } |
| 4152 | offset += part.len() + 1; |
| 4153 | } |
| 4154 | None |
| 4155 | } |
| 4156 | |
| 4157 | /// Heuristic check whether a string looks like a file path (contains a |
| 4158 | /// directory separator or a known source file extension). |
| 4159 | fn looks_like_file_path(s: &str) -> bool { |
| 4160 | if s.contains('/') || s.contains('\\') { |
| 4161 | return true; |
| 4162 | } |
| 4163 | // Check for a known file extension |
| 4164 | if let Some((_, ext)) = s.rsplit_once('.') { |
| 4165 | let ext = ext.trim(); |
| 4166 | matches!( |
| 4167 | ext, |
| 4168 | "rs" | "toml" |
| 4169 | | "md" |
| 4170 | | "sh" |
| 4171 | | "py" |
| 4172 | | "js" |
| 4173 | | "ts" |
| 4174 | | "json" |
| 4175 | | "yaml" |
| 4176 | | "yml" |
| 4177 | | "css" |
| 4178 | | "html" |
| 4179 | | "go" |
| 4180 | | "c" |
| 4181 | | "h" |
| 4182 | | "cpp" |
| 4183 | | "hpp" |
| 4184 | | "java" |
| 4185 | | "kt" |
| 4186 | | "swift" |
| 4187 | | "rb" |
| 4188 | | "php" |
| 4189 | | "lua" |
| 4190 | | "zig" |
| 4191 | | "mod" |
| 4192 | | "sum" |
| 4193 | | "lock" |
| 4194 | | "txt" |
| 4195 | | "ini" |
| 4196 | | "cfg" |
| 4197 | | "conf" |
| 4198 | | "env" |
| 4199 | | "gitignore" |
| 4200 | | "dockerfile" |
| 4201 | | "sql" |
| 4202 | | "r" |
| 4203 | | "ex" |
| 4204 | | "exs" |
| 4205 | | "vue" |
| 4206 | | "svelte" |
| 4207 | | "tsx" |
| 4208 | | "jsx" |
| 4209 | | "scss" |
| 4210 | | "sass" |
| 4211 | | "less" |
| 4212 | | "gradle" |
| 4213 | | "properties" |
| 4214 | | "xml" |
| 4215 | | "proto" |
| 4216 | | "nix" |
| 4217 | ) |
| 4218 | } else { |
| 4219 | false |
| 4220 | } |
| 4221 | } |
| 4222 | |
| 4223 | /// Aggregated file activity for compact Work panel display (#4636). |
| 4224 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 4225 | pub struct FileActivitySummary { |
| 4226 | pub files_read: u32, |
| 4227 | pub dirs_listed: u32, |
| 4228 | pub patterns_searched: u32, |
| 4229 | pub files_written: u32, |
| 4230 | } |
| 4231 | |
| 4232 | impl FileActivitySummary { |
| 4233 | pub fn is_empty(&self) -> bool { |
| 4234 | self.files_read == 0 |
| 4235 | && self.dirs_listed == 0 |
| 4236 | && self.patterns_searched == 0 |
| 4237 | && self.files_written == 0 |
| 4238 | } |
| 4239 | |
| 4240 | pub fn compact_display(&self, locale: Locale) -> Vec<String> { |
| 4241 | let mut parts = Vec::new(); |
| 4242 | for (count, clause, singular, plural) in [ |
| 4243 | ( |
| 4244 | self.files_read, |
| 4245 | MessageId::ActivityRead, |
| 4246 | MessageId::ActivityFileOne, |
| 4247 | MessageId::ActivityFileMany, |
| 4248 | ), |
| 4249 | ( |
| 4250 | self.dirs_listed, |
| 4251 | MessageId::ActivityListed, |
| 4252 | MessageId::ActivityDirectoryOne, |
| 4253 | MessageId::ActivityDirectoryMany, |
| 4254 | ), |
| 4255 | ( |
| 4256 | self.patterns_searched, |
| 4257 | MessageId::ActivitySearched, |
| 4258 | MessageId::ActivityPatternOne, |
| 4259 | MessageId::ActivityPatternMany, |
| 4260 | ), |
| 4261 | ( |
| 4262 | self.files_written, |
| 4263 | MessageId::ActivityWrote, |
| 4264 | MessageId::ActivityFileOne, |
| 4265 | MessageId::ActivityFileMany, |
| 4266 | ), |
| 4267 | ] { |
| 4268 | if count > 0 { |
| 4269 | let count = tool_run::counted(count as usize, locale, singular, plural); |
| 4270 | parts.push(tr(locale, clause).replace("{items}", &count)); |
| 4271 | } |
| 4272 | } |
| 4273 | parts |
| 4274 | } |
| 4275 | |
| 4276 | pub fn from_tool_name(name: &str) -> Option<FileActivityKind> { |
| 4277 | match name { |
| 4278 | "read_file" | "Read" | "read" => Some(FileActivityKind::Read), |
| 4279 | "list_dir" | "list_directory" | "Glob" | "glob" => Some(FileActivityKind::List), |
| 4280 | "search" | "grep" | "Grep" | "grep_files" | "file_search" | "codebase_search" => { |
| 4281 | Some(FileActivityKind::Search) |
| 4282 | } |
| 4283 | "write_file" | "Write" | "apply_patch" | "Edit" | "edit_file" | "fim_edit" => { |
| 4284 | Some(FileActivityKind::Write) |
| 4285 | } |
| 4286 | _ => None, |
| 4287 | } |
| 4288 | } |
| 4289 | } |
| 4290 | |
| 4291 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 4292 | pub enum FileActivityKind { |
| 4293 | Read, |
| 4294 | List, |
| 4295 | Search, |
| 4296 | Write, |
| 4297 | } |
| 4298 | |
| 4299 | impl FileActivitySummary { |
| 4300 | pub fn record(&mut self, kind: FileActivityKind) { |
| 4301 | match kind { |
| 4302 | FileActivityKind::Read => self.files_read += 1, |
| 4303 | FileActivityKind::List => self.dirs_listed += 1, |
| 4304 | FileActivityKind::Search => self.patterns_searched += 1, |
| 4305 | FileActivityKind::Write => self.files_written += 1, |
| 4306 | } |
| 4307 | } |
| 4308 | } |
| 4309 | |
| 4310 | /// Illuminate the newest graphemes of an actively streaming assistant line. |
| 4311 | fn apply_hot_tail_to_last_line(lines: &mut [Line<'static>], low_motion: bool) { |
| 4312 | if let Some(last) = lines.last_mut() { |
| 4313 | apply_hot_tail_to_line(last, low_motion); |
| 4314 | } |
| 4315 | } |
| 4316 | |
| 4317 | pub(crate) fn apply_hot_tail_to_line(line: &mut Line<'static>, low_motion: bool) { |
| 4318 | if line.spans.is_empty() { |
| 4319 | return; |
| 4320 | } |
| 4321 | // Reconstruct plain text from spans, split hot tail, re-style. |
| 4322 | let plain: String = line.spans.iter().map(|s| s.content.as_ref()).collect(); |
| 4323 | if plain.trim().is_empty() { |
| 4324 | return; |
| 4325 | } |
| 4326 | let (_settled, hot) = crate::tui::hot_tail::split_hot_tail( |
| 4327 | &plain, |
| 4328 | true, |
| 4329 | crate::tui::hot_tail::HOT_TAIL_GRAPHEMES, |
| 4330 | ); |
| 4331 | if hot.is_empty() { |
| 4332 | return; |
| 4333 | } |
| 4334 | let hot_start = plain.len().saturating_sub(hot.len()); |
| 4335 | let elapsed = std::time::SystemTime::now() |
| 4336 | .duration_since(std::time::UNIX_EPOCH) |
| 4337 | .map(|d| d.as_millis()) |
| 4338 | .unwrap_or(0); |
| 4339 | let base_fg = palette::TEXT_PRIMARY; |
| 4340 | let hot_style = crate::tui::hot_tail::hot_tail_style(base_fg, elapsed, low_motion); |
| 4341 | |
| 4342 | // Walk spans and re-style the trailing hot graphemes. |
| 4343 | let mut cursor = 0usize; |
| 4344 | let mut new_spans = Vec::with_capacity(line.spans.len() + 2); |
| 4345 | for span in line.spans.drain(..) { |
| 4346 | let content = span.content.to_string(); |
| 4347 | let len = content.len(); |
| 4348 | let span_end = cursor + len; |
| 4349 | if span_end <= hot_start { |
| 4350 | new_spans.push(span); |
| 4351 | } else if cursor >= hot_start { |
| 4352 | new_spans.push(Span::styled(content, hot_style)); |
| 4353 | } else { |
| 4354 | // Split this span across the boundary. |
| 4355 | let local = hot_start - cursor; |
| 4356 | let (left, right) = content.split_at(local.min(content.len())); |
| 4357 | if !left.is_empty() { |
| 4358 | new_spans.push(Span::styled(left.to_string(), span.style)); |
| 4359 | } |
| 4360 | if !right.is_empty() { |
| 4361 | new_spans.push(Span::styled(right.to_string(), hot_style)); |
| 4362 | } |
| 4363 | } |
| 4364 | cursor = span_end; |
| 4365 | } |
| 4366 | line.spans = new_spans; |
| 4367 | } |
| 4368 | |
| 4369 | #[cfg(test)] |
| 4370 | mod tests; |
| 4371 | |
| 4372 | #[cfg(test)] |
| 4373 | mod truncate_text_tests { |
| 4374 | use super::truncate_text; |
| 4375 | |
| 4376 | #[test] |
| 4377 | fn truncate_text_keeps_cjk_and_zwj_whole() { |
| 4378 | let cjk = truncate_text("日本語のテキストです", 9); |
| 4379 | assert_eq!(cjk, "日本語..."); |
| 4380 | let family = "a👨👩👧👦👨👩👧👦👨👩👧👦"; |
| 4381 | let out = truncate_text(family, 6); |
| 4382 | let body = out.strip_suffix("...").expect("ellipsis"); |
| 4383 | assert_eq!(body.chars().filter(|c| *c == '\u{200d}').count(), 3); |
| 4384 | assert!(family.starts_with(body)); |
| 4385 | } |
| 4386 | } |
| 4387 |