| 1 | //! Transcript history-cell tests. |
| 2 | //! |
| 3 | //! Rebuilt in v0.9.11 after declaring test bankruptcy on the previous suite |
| 4 | //! (123 tests / 3,964 lines). About a third of that file pinned glyph choices, |
| 5 | //! palette tokens, span indices and English label text — `spans[1] == "⣤"`, |
| 6 | //! `title_span.style.fg == theme.tool_title_color`, `visible[1] == "▏ done: |
| 7 | //! scan repo"`. Those assertions fail on every legitimate visual refactor and |
| 8 | //! catch nothing a user would notice, which is the liability `d64b9429b` |
| 9 | //! ("remove brittle visual test mass") named. |
| 10 | //! |
| 11 | //! What survives is named for the *property* it protects. Rules for additions: |
| 12 | //! |
| 13 | //! * Assert a property, not a token. `spans[1] == "⣤"` is a token; "the frame |
| 14 | //! does not change while motion is reduced" is the property, and it is |
| 15 | //! strictly stronger — it also catches an animation leak the constant missed. |
| 16 | //! * Where the value is a design choice (color, glyph, verb), assert the |
| 17 | //! *relationship* between cases instead: warning must not read as error. |
| 18 | //! * One test per property, with its cases in a table — not one test per case. |
| 19 | //! * Never assert `a || b` where `b` is trivially true of any English string. |
| 20 | |
| 21 | use super::constants::{TOOL_OUTPUT_HEAD_LINES, TOOL_OUTPUT_LINE_LIMIT, TOOL_OUTPUT_TAIL_LINES}; |
| 22 | use super::thinking::cached_color_depth; |
| 23 | use super::{ |
| 24 | ASSISTANT_GLYPH, ExecCell, ExecSource, GenericToolCell, HistoryCell, PlanUpdateCell, |
| 25 | REASONING_CURSOR, REASONING_OPENER, REASONING_RAIL, RenderMode, ToolCell, ToolStatus, |
| 26 | TranscriptFold, TranscriptRenderOptions, WebSearchCell, assistant_label_style_for, |
| 27 | extract_reasoning_summary, render_spillover_annotation, render_thinking, |
| 28 | render_thinking_with_analysis, render_tool_header_with_summary, |
| 29 | }; |
| 30 | use crate::tui::motion::MotionMode; |
| 31 | use codewhale_engine::session_manager::{SessionManager, create_saved_session}; |
| 32 | use codewhale_engine::tools::plan::{PlanSnapshot, StepStatus}; |
| 33 | use codewhale_models::{ContentBlock, Message, Role}; |
| 34 | use codewhale_tui_kit::ui_text::{ |
| 35 | line_to_plain, slice_visible_columns, text_display_width, text_visible_width, |
| 36 | }; |
| 37 | use std::path::PathBuf; |
| 38 | use std::time::{Duration, Instant}; |
| 39 | use tempfile::tempdir; |
| 40 | |
| 41 | #[test] |
| 42 | fn extension_prompt_snapshots_and_withdrawal_show_the_complete_model_input() { |
| 43 | let instructions = format!("{}\nLast instruction.", "x".repeat(12_000)); |
| 44 | for block in [Some(instructions.as_str()), None] { |
| 45 | let message = |
| 46 | codewhale_engine::runtime_handoff::extension_prompt_contributions_runtime_message( |
| 47 | block, |
| 48 | ); |
| 49 | let cells = super::history_cells_from_message(&message); |
| 50 | let [HistoryCell::System { content }] = cells.as_slice() else { |
| 51 | panic!("runtime instructions must be shown as a system receipt"); |
| 52 | }; |
| 53 | match block { |
| 54 | Some(text) => assert!( |
| 55 | content.contains(text), |
| 56 | "the full model-visible text stays auditable" |
| 57 | ), |
| 58 | None => assert!(content.contains("withdrawn")), |
| 59 | } |
| 60 | } |
| 61 | let message = codewhale_engine::runtime_handoff::mcp_server_instructions_runtime_message(&[( |
| 62 | "guided".into(), |
| 63 | "Search before fetching.".into(), |
| 64 | )]); |
| 65 | let cells = super::history_cells_from_message(&message); |
| 66 | assert!( |
| 67 | matches!(cells.as_slice(), [HistoryCell::System { content }] |
| 68 | if content.contains("Search before fetching.")), |
| 69 | "the transcript shows what the model saw" |
| 70 | ); |
| 71 | } |
| 72 | |
| 73 | // --------------------------------------------------------------------------- |
| 74 | // Helpers |
| 75 | // --------------------------------------------------------------------------- |
| 76 | |
| 77 | fn line_text(line: &ratatui::text::Line<'static>) -> String { |
| 78 | line.spans |
| 79 | .iter() |
| 80 | .map(|span| span.content.as_ref()) |
| 81 | .collect() |
| 82 | } |
| 83 | |
| 84 | fn lines_text(lines: &[ratatui::text::Line<'static>]) -> String { |
| 85 | lines.iter().map(line_text).collect::<Vec<_>>().join("\n") |
| 86 | } |
| 87 | |
| 88 | fn generic_tool(name: &str, status: ToolStatus) -> GenericToolCell { |
| 89 | GenericToolCell { |
| 90 | name: name.to_string(), |
| 91 | status, |
| 92 | input_summary: None, |
| 93 | output: None, |
| 94 | prompts: None, |
| 95 | spillover_path: None, |
| 96 | output_summary: None, |
| 97 | is_diff: false, |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | fn exec_tool(command: &str, status: ToolStatus) -> ExecCell { |
| 102 | ExecCell { |
| 103 | command: command.to_string(), |
| 104 | status, |
| 105 | output: None, |
| 106 | live_output: None, |
| 107 | shell_task_id: None, |
| 108 | owner_agent_id: None, |
| 109 | owner_agent_name: None, |
| 110 | started_at: None, |
| 111 | duration_ms: None, |
| 112 | stale_elapsed_since_output_ms: None, |
| 113 | waiting: None, |
| 114 | source: ExecSource::Assistant, |
| 115 | description: None, |
| 116 | interaction: None, |
| 117 | output_summary: None, |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | fn numbered_output(count: usize) -> String { |
| 122 | (0..count) |
| 123 | .map(|i| format!("row {i:02} plain content")) |
| 124 | .collect::<Vec<_>>() |
| 125 | .join("\n") |
| 126 | } |
| 127 | |
| 128 | fn calm_options() -> TranscriptRenderOptions { |
| 129 | TranscriptRenderOptions { |
| 130 | low_motion: true, |
| 131 | ..TranscriptRenderOptions::default() |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | #[test] |
| 136 | fn a_system_note_keeps_the_backslashes_in_a_windows_path() { |
| 137 | // A note names paths. The markdown renderer honours CommonMark §2.4, where |
| 138 | // a backslash before ASCII punctuation is an escape, so `\.` used to print |
| 139 | // as `.` and `C:\Users\asus\.codewhale` rendered as |
| 140 | // `C:\Users\asus.codewhale` — a directory that does not exist. |
| 141 | // A width wide enough for the whole line: the point of the case is the |
| 142 | // backslash, not the wrapper, and a narrower frame soft-wraps mid-path and |
| 143 | // splits the string this asserts on. |
| 144 | let cell = HistoryCell::System { |
| 145 | content: concat!( |
| 146 | "Setup provider/model state was not saved: failed to persist setup state to ", |
| 147 | r"C:\Users\asus\.codewhale\setup_state.json" |
| 148 | ) |
| 149 | .to_string(), |
| 150 | }; |
| 151 | let text: String = cell |
| 152 | .lines_with_copy_metadata(400, calm_options()) |
| 153 | .iter() |
| 154 | .flat_map(|line| line.line.spans.iter()) |
| 155 | .map(|span| span.content.as_ref()) |
| 156 | .collect(); |
| 157 | assert!( |
| 158 | text.contains(r"C:\Users\asus\.codewhale\setup_state.json"), |
| 159 | "{text}" |
| 160 | ); |
| 161 | assert!(!text.contains("asus.codewhale"), "{text}"); |
| 162 | } |
| 163 | |
| 164 | #[test] |
| 165 | fn a_system_note_leaves_a_fenced_block_verbatim() { |
| 166 | // A fence is already verbatim: doubling inside one would print the extra |
| 167 | // backslash instead of protecting it. |
| 168 | let cell = HistoryCell::System { |
| 169 | content: concat!("env:\n```\n", r"C:\Users\asus\.codewhale", "\n```").to_string(), |
| 170 | }; |
| 171 | let text: String = cell |
| 172 | .lines_with_copy_metadata(120, calm_options()) |
| 173 | .iter() |
| 174 | .flat_map(|line| line.line.spans.iter()) |
| 175 | .map(|span| span.content.as_ref()) |
| 176 | .collect(); |
| 177 | assert!(text.contains(r"C:\Users\asus\.codewhale"), "{text}"); |
| 178 | assert!(!text.contains(r"C:\\Users"), "{text}"); |
| 179 | } |
| 180 | |
| 181 | #[test] |
| 182 | fn a_system_note_leaves_inline_markup_and_table_rows_verbatim() { |
| 183 | // The renderer copies inline code and table cells verbatim, so doubling a |
| 184 | // backslash inside one prints it doubled; bold and strikethrough read a |
| 185 | // doubled backslash back as one. These are the shapes third-party guidance |
| 186 | // brings into a note (MCP servers, extension prompts), and each renders a |
| 187 | // Windows path correctly. |
| 188 | for content in [ |
| 189 | r"see `C:\Users\asus\.codewhale` for the file".to_string(), |
| 190 | r"**C:\Users\asus** is the home".to_string(), |
| 191 | r"| C:\Users\asus | ok |".to_string(), |
| 192 | r"~~C:\Users\asus~~".to_string(), |
| 193 | ] { |
| 194 | let cell = HistoryCell::System { |
| 195 | content: content.clone(), |
| 196 | }; |
| 197 | let text: String = cell |
| 198 | .lines_with_copy_metadata(120, calm_options()) |
| 199 | .iter() |
| 200 | .flat_map(|line| line.line.spans.iter()) |
| 201 | .map(|span| span.content.as_ref()) |
| 202 | .collect(); |
| 203 | assert!(text.contains(r"C:\Users\asus"), "{content} -> {text}"); |
| 204 | assert!(!text.contains(r"C:\\Users"), "{content} -> {text}"); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn a_fence_of_four_backticks_is_not_closed_by_three() { |
| 210 | // The renderer closes only on a run at least as long as the opener, so a |
| 211 | // three-backtick line inside a four-backtick fence is code content. The |
| 212 | // escaper has to agree, or it starts doubling inside a code sample. |
| 213 | let content = concat!( |
| 214 | "sample:\n````\n", |
| 215 | r"C:\Users\asus\.codewhale", |
| 216 | "\n```\n", |
| 217 | r"C:\Users\asus\.codewhale", |
| 218 | "\n````" |
| 219 | ); |
| 220 | let cell = HistoryCell::System { |
| 221 | content: content.to_string(), |
| 222 | }; |
| 223 | let text: String = cell |
| 224 | .lines_with_copy_metadata(120, calm_options()) |
| 225 | .iter() |
| 226 | .flat_map(|line| line.line.spans.iter()) |
| 227 | .map(|span| span.content.as_ref()) |
| 228 | .collect(); |
| 229 | assert!(text.contains(r"C:\Users\asus"), "{text}"); |
| 230 | assert!(!text.contains(r"C:\\Users"), "{text}"); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn ordinary_cell_fold_preserves_body_metadata_and_full_exports() { |
| 235 | let content = format!( |
| 236 | "[reference](https://example.com/reference)\n\n{}", |
| 237 | (1..=12) |
| 238 | .map(|line| format!("paragraph {line:02}")) |
| 239 | .collect::<Vec<_>>() |
| 240 | .join("\n\n") |
| 241 | ); |
| 242 | let mut tool = exec_tool("example", ToolStatus::Failed); |
| 243 | tool.output = Some(content.clone()); |
| 244 | let cells = [ |
| 245 | HistoryCell::User { |
| 246 | content: content.clone(), |
| 247 | }, |
| 248 | HistoryCell::Assistant { |
| 249 | content: content.clone(), |
| 250 | streaming: false, |
| 251 | }, |
| 252 | HistoryCell::Assistant { |
| 253 | content: content.clone(), |
| 254 | streaming: true, |
| 255 | }, |
| 256 | HistoryCell::System { |
| 257 | content: content.clone(), |
| 258 | }, |
| 259 | HistoryCell::Error { |
| 260 | message: content.clone(), |
| 261 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 262 | code: None, |
| 263 | }, |
| 264 | HistoryCell::Tool(ToolCell::Exec(tool)), |
| 265 | ]; |
| 266 | for cell in cells { |
| 267 | let options = calm_options(); |
| 268 | let full = cell.lines_with_copy_metadata(80, options); |
| 269 | let (preview, action) = |
| 270 | cell.lines_with_copy_metadata_folded(80, options, Some(TranscriptFold::Collapsed)); |
| 271 | assert!( |
| 272 | preview.len() < full.len(), |
| 273 | "a folded long body stays bounded" |
| 274 | ); |
| 275 | assert_eq!(action, Some(super::CellFoldAction::Expand)); |
| 276 | assert_eq!(preview[0].copy_prefix_width, preview[0].line.width()); |
| 277 | assert!(preview[0].links.is_empty()); |
| 278 | let body = &preview[1..]; |
| 279 | for (index, line) in body.iter().enumerate() { |
| 280 | assert_eq!(line.line, full[index].line); |
| 281 | assert_eq!(line.links, full[index].links); |
| 282 | assert_eq!(line.copy_prefix_width, full[index].copy_prefix_width); |
| 283 | if index + 1 < body.len() { |
| 284 | assert_eq!(line.copy_separator_after, full[index].copy_separator_after); |
| 285 | } |
| 286 | } |
| 287 | assert_eq!( |
| 288 | body.last().unwrap().copy_separator_after, |
| 289 | codewhale_tui_kit::ui_text::CopyLineSeparator::Newline |
| 290 | ); |
| 291 | let (plain, plain_action) = |
| 292 | cell.lines_with_options_folded(80, options, Some(TranscriptFold::Collapsed)); |
| 293 | assert_eq!(plain_action, action); |
| 294 | assert_eq!( |
| 295 | plain, |
| 296 | preview |
| 297 | .iter() |
| 298 | .map(|line| line.line.clone()) |
| 299 | .collect::<Vec<_>>() |
| 300 | ); |
| 301 | let (restored, action) = |
| 302 | cell.lines_with_copy_metadata_folded(80, options, Some(TranscriptFold::Expanded)); |
| 303 | assert!(action.is_none()); |
| 304 | assert_eq!(restored.len(), full.len()); |
| 305 | for (restored, original) in restored.iter().zip(&full) { |
| 306 | assert_eq!(restored.line, original.line); |
| 307 | assert_eq!(restored.links, original.links); |
| 308 | assert_eq!(restored.copy_prefix_width, original.copy_prefix_width); |
| 309 | assert_eq!(restored.copy_separator_after, original.copy_separator_after); |
| 310 | } |
| 311 | assert!(lines_text(&cell.transcript_lines(80)).contains("paragraph 12")); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | // --------------------------------------------------------------------------- |
| 316 | // Leaks — a rendered cell never exposes something the user was not shown |
| 317 | // --------------------------------------------------------------------------- |
| 318 | |
| 319 | /// Spilled tool output lives in a file under the session directory. The path is |
| 320 | /// an internal storage detail: it names the user's home, their session id, and |
| 321 | /// a content hash, and it is useless to them because the affordance opens the |
| 322 | /// pager, not the file. No width, no render mode, and no standalone annotation |
| 323 | /// may print it. |
| 324 | /// |
| 325 | /// Replaces five separate tests that each checked one width or one mode. |
| 326 | #[test] |
| 327 | fn no_width_or_render_mode_leaks_a_spillover_storage_path() { |
| 328 | let secret = "/Users/private/.codewhale/sessions/session-a/artifacts/hash.txt"; |
| 329 | |
| 330 | for width in [18_u16, 40, 80, 120] { |
| 331 | for mode in [RenderMode::Live, RenderMode::Transcript] { |
| 332 | let mut cell = generic_tool("read_file", ToolStatus::Success); |
| 333 | cell.input_summary = Some("cmd: cargo build --release".to_string()); |
| 334 | cell.output = Some(numbered_output(40)); |
| 335 | cell.spillover_path = Some(PathBuf::from(secret)); |
| 336 | |
| 337 | let rendered = lines_text(&cell.lines_with_mode(width, true, mode)); |
| 338 | for fragment in ["/Users", ".codewhale", "sessions/", "hash.txt"] { |
| 339 | assert!( |
| 340 | !rendered.contains(fragment), |
| 341 | "storage path fragment {fragment:?} leaked at width {width} in {mode:?}: \ |
| 342 | {rendered:?}" |
| 343 | ); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | // The standalone affordance carries no path either, and it fits the |
| 348 | // width it was given — an affordance that overflows is a wrap artifact |
| 349 | // in the transcript. |
| 350 | let annotation = line_to_plain(&render_spillover_annotation( |
| 351 | width, |
| 352 | codewhale_localization::Locale::En, |
| 353 | )); |
| 354 | assert!( |
| 355 | text_display_width(&annotation) <= usize::from(width), |
| 356 | "affordance exceeds width {width}: {annotation:?}" |
| 357 | ); |
| 358 | for fragment in ["/Users", ".codewhale", "hash.txt"] { |
| 359 | assert!( |
| 360 | !annotation.contains(fragment), |
| 361 | "affordance leaked {fragment:?}: {annotation:?}" |
| 362 | ); |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // The common case — a result that never spilled — spends no row on an |
| 367 | // affordance that would open an empty pager. |
| 368 | let mut plain = generic_tool("read_file", ToolStatus::Success); |
| 369 | plain.output = Some("contents".to_string()); |
| 370 | let hint = crate::tui::key_shortcuts::tool_details_shortcut_action_hint("output"); |
| 371 | let rendered = lines_text(&plain.lines_with_mode(80, true, RenderMode::Live)); |
| 372 | assert!( |
| 373 | !rendered.contains(&hint), |
| 374 | "a result that did not spill must not advertise the spillover pager: {rendered:?}" |
| 375 | ); |
| 376 | } |
| 377 | |
| 378 | /// With reasoning display off, the model's chain of thought must not reach the |
| 379 | /// screen in any lifecycle state — not while streaming, not once complete. |
| 380 | /// The live case still needs a progress signal, so it renders one compact row. |
| 381 | #[test] |
| 382 | fn hidden_reasoning_never_renders_its_content_in_any_state() { |
| 383 | let secret = "private chain of thought that must not be shown"; |
| 384 | let hidden = TranscriptRenderOptions { |
| 385 | show_thinking: false, |
| 386 | low_motion: true, |
| 387 | ..TranscriptRenderOptions::default() |
| 388 | }; |
| 389 | |
| 390 | let streaming = HistoryCell::Thinking { |
| 391 | content: secret.to_string(), |
| 392 | streaming: true, |
| 393 | duration_secs: None, |
| 394 | }; |
| 395 | let live = streaming.lines_with_options(80, hidden); |
| 396 | let live_text = lines_text(&live); |
| 397 | assert!( |
| 398 | !live_text.contains(secret), |
| 399 | "hidden live reasoning revealed its body: {live_text}" |
| 400 | ); |
| 401 | assert_eq!( |
| 402 | live.len(), |
| 403 | 1, |
| 404 | "hidden reasoning is one compact progress row, not a stack of state \ |
| 405 | copy: {live_text}" |
| 406 | ); |
| 407 | |
| 408 | let complete = HistoryCell::Thinking { |
| 409 | content: secret.to_string(), |
| 410 | streaming: false, |
| 411 | duration_secs: Some(1.0), |
| 412 | }; |
| 413 | assert!( |
| 414 | complete.lines_with_options(80, hidden).is_empty(), |
| 415 | "completed hidden reasoning must leave the live transcript entirely" |
| 416 | ); |
| 417 | } |
| 418 | |
| 419 | /// A live card is a summary. It must name the tool that ran (so the row is |
| 420 | /// attributable) and must not spend its one line echoing arguments the caller |
| 421 | /// never chose — `max_count: 15` is a schema default, not a user intent. |
| 422 | /// Transcript replay is the record, so it keeps the exact tool id. |
| 423 | /// |
| 424 | /// Replaces six tests, one of which (`unknown_generic_tool_keeps_raw_name_in_ |
| 425 | /// live_mode`) asserted only `!text.is_empty()` and so could never fail. |
| 426 | #[test] |
| 427 | fn live_cards_name_their_tool_without_echoing_control_only_arguments() { |
| 428 | assert_eq!( |
| 429 | codewhale_app_server::exec_agent::summarize_tool_args(&serde_json::json!({ |
| 430 | "max_count": 15, |
| 431 | "timeout_ms": 30_000 |
| 432 | })), |
| 433 | None, |
| 434 | "an argument set that is entirely control defaults summarizes to nothing" |
| 435 | ); |
| 436 | assert_eq!( |
| 437 | codewhale_app_server::exec_agent::summarize_tool_args(&serde_json::json!({ |
| 438 | "max_count": 15, |
| 439 | "branch": "main" |
| 440 | })) |
| 441 | .as_deref(), |
| 442 | Some("branch: main"), |
| 443 | "the meaningful key is what the summary is for" |
| 444 | ); |
| 445 | |
| 446 | for name in ["git_log", "future_private_tool"] { |
| 447 | let mut cell = generic_tool(name, ToolStatus::Success); |
| 448 | cell.input_summary = Some("max_count: 15".to_string()); |
| 449 | let lines = cell.lines_with_mode(120, true, RenderMode::Live); |
| 450 | let joined = lines_text(&lines); |
| 451 | |
| 452 | assert_eq!(lines.len(), 1, "compact live row for {name}: {joined:?}"); |
| 453 | assert!( |
| 454 | joined.contains(name), |
| 455 | "the row must be attributable to {name}: {joined:?}" |
| 456 | ); |
| 457 | assert!( |
| 458 | !joined.contains("max_count"), |
| 459 | "control defaults must not become the visible summary for {name}: {joined:?}" |
| 460 | ); |
| 461 | } |
| 462 | |
| 463 | // A tool the UI has a family for is identified by that family live; the |
| 464 | // raw id would be a second, redundant name. Replay keeps it. |
| 465 | let mut known = generic_tool("run_verifiers", ToolStatus::Running); |
| 466 | known.input_summary = Some("profile: auto, level: quick".to_string()); |
| 467 | let known = HistoryCell::Tool(ToolCell::Generic(known)); |
| 468 | let live = lines_text(&known.lines(80)); |
| 469 | let transcript = lines_text(&known.transcript_lines(80)); |
| 470 | assert!( |
| 471 | !live.contains("run_verifiers"), |
| 472 | "a known tool id must not take a slot in the compact live card: {live}" |
| 473 | ); |
| 474 | assert!( |
| 475 | transcript.contains("run_verifiers"), |
| 476 | "transcript replay preserves the exact tool id: {transcript}" |
| 477 | ); |
| 478 | } |
| 479 | |
| 480 | // --------------------------------------------------------------------------- |
| 481 | // Budget — the card never lies about how much it is showing |
| 482 | // --------------------------------------------------------------------------- |
| 483 | |
| 484 | /// `selected_output_indices` fills head + tail and then tops up from lines that |
| 485 | /// look important (error / warning / path). Plain output — a list of names, a |
| 486 | /// clean build log — matches none of those, so the top-up found nothing and the |
| 487 | /// card silently forfeited the rest of its budget while still reporting the |
| 488 | /// remainder as omitted. A card that advertises N rows shows N rows. |
| 489 | #[test] |
| 490 | fn a_live_card_spends_the_whole_output_budget_it_advertises() { |
| 491 | let total = 40usize; |
| 492 | let cell = { |
| 493 | let mut exec = exec_tool("list_things", ToolStatus::Failed); |
| 494 | exec.output = Some(numbered_output(total)); |
| 495 | exec.duration_ms = Some(120); |
| 496 | HistoryCell::Tool(ToolCell::Exec(exec)) |
| 497 | }; |
| 498 | |
| 499 | let live_text = lines_text(&cell.lines_with_options(80, calm_options())); |
| 500 | let shown = (0..total) |
| 501 | .filter(|i| live_text.contains(&format!("row {i:02} plain content"))) |
| 502 | .count(); |
| 503 | |
| 504 | assert_eq!( |
| 505 | shown, TOOL_OUTPUT_LINE_LIMIT, |
| 506 | "a card promising {TOOL_OUTPUT_LINE_LIMIT} rows must show \ |
| 507 | {TOOL_OUTPUT_LINE_LIMIT}, not stop at head+tail: {live_text}" |
| 508 | ); |
| 509 | for i in 0..TOOL_OUTPUT_HEAD_LINES { |
| 510 | assert!( |
| 511 | live_text.contains(&format!("row {i:02} plain content")), |
| 512 | "head row {i} missing: {live_text}" |
| 513 | ); |
| 514 | } |
| 515 | for i in (total - TOOL_OUTPUT_TAIL_LINES)..total { |
| 516 | assert!( |
| 517 | live_text.contains(&format!("row {i:02} plain content")), |
| 518 | "tail row {i} missing: {live_text}" |
| 519 | ); |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | /// Failure keeps the invocation plus head/tail evidence visible under every |
| 524 | /// density setting; the full record remains in the details view. |
| 525 | #[test] |
| 526 | fn calm1_failed_tool_keeps_context_and_result_under_every_density_setting() { |
| 527 | let total = 30usize; |
| 528 | let last = format!("row {:02} plain content", total - 1); |
| 529 | |
| 530 | for (label, options) in [ |
| 531 | ("default", TranscriptRenderOptions::default()), |
| 532 | ( |
| 533 | "tool details hidden", |
| 534 | TranscriptRenderOptions { |
| 535 | show_tool_details: false, |
| 536 | ..TranscriptRenderOptions::default() |
| 537 | }, |
| 538 | ), |
| 539 | ( |
| 540 | "calm mode", |
| 541 | TranscriptRenderOptions { |
| 542 | calm_mode: true, |
| 543 | ..TranscriptRenderOptions::default() |
| 544 | }, |
| 545 | ), |
| 546 | ] { |
| 547 | let cell = { |
| 548 | let mut cell = generic_tool("read_file", ToolStatus::Failed); |
| 549 | cell.input_summary = Some("command: noisy".to_string()); |
| 550 | cell.output = Some(numbered_output(total)); |
| 551 | HistoryCell::Tool(ToolCell::Generic(cell)) |
| 552 | }; |
| 553 | |
| 554 | let text = lines_text(&cell.lines_with_options(80, options)); |
| 555 | assert!( |
| 556 | text.contains(" lines) · "), |
| 557 | "[{label}] a bounded failure must advertise omitted output: {text}" |
| 558 | ); |
| 559 | assert!( |
| 560 | text.contains(&last), |
| 561 | "[{label}] failed output must stay expanded to its last row: {text}" |
| 562 | ); |
| 563 | assert!( |
| 564 | text.contains("command: noisy"), |
| 565 | "[{label}] the failing invocation must stay visible: {text}" |
| 566 | ); |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | /// The live surface is a summary and the transcript is the record. The contract |
| 571 | /// is directional: anything the live view drops must still be in the |
| 572 | /// transcript, and the live view must say so when it drops something. A success |
| 573 | /// gets a bounded preview; a failure gets the full budget; neither may leave |
| 574 | /// the transcript short. |
| 575 | /// |
| 576 | /// Replaces four near-identical live/transcript comparison tests. |
| 577 | #[test] |
| 578 | fn whatever_live_truncates_the_transcript_still_holds() { |
| 579 | let total = 30usize; |
| 580 | let first = "row 00 plain content"; |
| 581 | let last = format!("row {:02} plain content", total - 1); |
| 582 | |
| 583 | // Failed exec: capped live with an honest marker, uncapped in transcript. |
| 584 | let failed = { |
| 585 | let mut exec = exec_tool("noisy_script.sh", ToolStatus::Failed); |
| 586 | exec.output = Some(numbered_output(total)); |
| 587 | exec.duration_ms = Some(120); |
| 588 | HistoryCell::Tool(ToolCell::Exec(exec)) |
| 589 | }; |
| 590 | let live = failed.lines_with_options(80, calm_options()); |
| 591 | let transcript = failed.transcript_lines(80); |
| 592 | let live_text = lines_text(&live); |
| 593 | let transcript_text = lines_text(&transcript); |
| 594 | assert!( |
| 595 | live.len() < transcript.len(), |
| 596 | "live must compress (live={}, transcript={})", |
| 597 | live.len(), |
| 598 | transcript.len() |
| 599 | ); |
| 600 | assert!( |
| 601 | live_text.contains(" lines) · "), |
| 602 | "a live view that drops rows must say so: {live_text}" |
| 603 | ); |
| 604 | assert!( |
| 605 | !transcript_text.contains(" lines) · "), |
| 606 | "the transcript drops nothing, so it claims nothing: {transcript_text}" |
| 607 | ); |
| 608 | assert!(transcript_text.contains(first) && transcript_text.contains(&last)); |
| 609 | assert!( |
| 610 | transcript_text.contains("row 15 plain content"), |
| 611 | "the transcript keeps the middle the live view skipped: {transcript_text}" |
| 612 | ); |
| 613 | |
| 614 | // Successful exec: a bounded head preview, never the whole body. |
| 615 | let success = { |
| 616 | let mut exec = exec_tool("noisy_script.sh", ToolStatus::Success); |
| 617 | exec.output = Some(numbered_output(total)); |
| 618 | exec.duration_ms = Some(120); |
| 619 | HistoryCell::Tool(ToolCell::Exec(exec)) |
| 620 | }; |
| 621 | let live_text = lines_text(&success.lines_with_options(80, calm_options())); |
| 622 | let transcript_text = lines_text(&success.transcript_lines(80)); |
| 623 | let previewed = (0..total) |
| 624 | .filter(|i| live_text.contains(&format!("row {i:02} plain content"))) |
| 625 | .count(); |
| 626 | assert_eq!( |
| 627 | previewed, 3, |
| 628 | "a successful exec previews only the opening and final result rows: {live_text}" |
| 629 | ); |
| 630 | assert!( |
| 631 | live_text.contains(first) && live_text.contains(&last), |
| 632 | "the bounded preview retains context and the final result: {live_text}" |
| 633 | ); |
| 634 | let output_hint = crate::tui::key_shortcuts::tool_details_shortcut_action_hint("output"); |
| 635 | assert!( |
| 636 | live_text.contains(&output_hint), |
| 637 | "a shortened success must point to its full output: {live_text}" |
| 638 | ); |
| 639 | assert!( |
| 640 | !live_text.contains("row 15 plain content"), |
| 641 | "the live preview should leave routine middle output for details: {live_text}" |
| 642 | ); |
| 643 | assert!(transcript_text.contains(first) && transcript_text.contains(&last)); |
| 644 | assert!( |
| 645 | transcript_text.contains("row 15 plain content"), |
| 646 | "the full transcript must retain output omitted from the live card: {transcript_text}" |
| 647 | ); |
| 648 | |
| 649 | // Successful generic tool: output collapses entirely live, and does so |
| 650 | // without spending a row telling the user it collapsed. |
| 651 | let quiet = { |
| 652 | let mut cell = generic_tool("read_file", ToolStatus::Success); |
| 653 | cell.input_summary = Some("path: crates/tui/src/main.rs".to_string()); |
| 654 | cell.output = Some(numbered_output(24)); |
| 655 | HistoryCell::Tool(ToolCell::Generic(cell)) |
| 656 | }; |
| 657 | let live_text = lines_text(&quiet.lines_with_options(80, TranscriptRenderOptions::default())); |
| 658 | let transcript_text = lines_text(&quiet.transcript_lines(80)); |
| 659 | assert!( |
| 660 | !live_text.contains(first) && !live_text.contains(" lines) · "), |
| 661 | "a quiet success collapses silently: {live_text}" |
| 662 | ); |
| 663 | assert!(transcript_text.contains(first)); |
| 664 | assert!(transcript_text.contains("row 23 plain content")); |
| 665 | } |
| 666 | |
| 667 | /// A successful run shows three rows of output. They used to be the first two |
| 668 | /// and the very last, so `npm test` showed a blank row, the script banner and |
| 669 | /// a timing line, and hid whether the tests passed. The rows that say how the |
| 670 | /// run went must be among the three, blank rows must not take a slot, and |
| 671 | /// every hidden row must be announced, including rows after the last one shown. |
| 672 | #[test] |
| 673 | fn a_successful_run_preview_shows_how_the_run_ended() { |
| 674 | let node_test = "\n> trip-timer@1.0.0 test\n> node --test\n\n\ |
| 675 | ✔ formats minutes (0.5ms)\n\ |
| 676 | ✔ trips over an hour show remainder minutes (0.1ms)\n\ |
| 677 | ℹ tests 2\nℹ suites 0\nℹ pass 2\nℹ fail 0\nℹ cancelled 0\n\ |
| 678 | ℹ skipped 0\nℹ todo 0\nℹ duration_ms 57.924542"; |
| 679 | let cargo_test = " Compiling demo v0.1.0\n Running unittests src/lib.rs\n\n\ |
| 680 | running 2 tests\ntest a ... ok\ntest b ... ok\n\n\ |
| 681 | test result: ok. 2 passed; 0 failed; finished in 0.00s\n\n"; |
| 682 | let plain = numbered_output(30); |
| 683 | |
| 684 | // (case, output, rows that must be shown, omission markers in order) |
| 685 | let cases: [(&str, &str, &[&str], &[&str]); 3] = [ |
| 686 | ( |
| 687 | "totals followed by other lines", |
| 688 | node_test, |
| 689 | &["> trip-timer@1.0.0 test", "ℹ pass 2", "ℹ fail 0"], |
| 690 | &["(+5 lines)", "(+4 lines)"], |
| 691 | ), |
| 692 | ( |
| 693 | "result followed by blank lines", |
| 694 | cargo_test, |
| 695 | &[ |
| 696 | "Compiling demo v0.1.0", |
| 697 | "test b ... ok", |
| 698 | "test result: ok. 2 passed; 0 failed", |
| 699 | ], |
| 700 | &["(+3 lines)"], |
| 701 | ), |
| 702 | ( |
| 703 | "nothing states an outcome", |
| 704 | &plain, |
| 705 | &[ |
| 706 | "row 00 plain content", |
| 707 | "row 28 plain content", |
| 708 | "row 29 plain content", |
| 709 | ], |
| 710 | &["(+27 lines)"], |
| 711 | ), |
| 712 | ]; |
| 713 | |
| 714 | for (case, output, shown, markers) in cases { |
| 715 | let cell = { |
| 716 | let mut exec = exec_tool("npm test", ToolStatus::Success); |
| 717 | exec.output = Some(output.to_string()); |
| 718 | exec.duration_ms = Some(120); |
| 719 | HistoryCell::Tool(ToolCell::Exec(exec)) |
| 720 | }; |
| 721 | let live = cell.lines_with_options(80, calm_options()); |
| 722 | let live_text = lines_text(&live); |
| 723 | |
| 724 | for row in shown { |
| 725 | assert!( |
| 726 | live_text.contains(row), |
| 727 | "[{case}] `{row}` hidden: {live_text}" |
| 728 | ); |
| 729 | } |
| 730 | let source_rows_shown = output |
| 731 | .lines() |
| 732 | .filter(|line| !line.trim().is_empty() && live_text.contains(line.trim())) |
| 733 | .count(); |
| 734 | assert_eq!( |
| 735 | source_rows_shown, |
| 736 | shown.len(), |
| 737 | "[{case}] the preview keeps its three-row budget: {live_text}" |
| 738 | ); |
| 739 | let announced: Vec<String> = live |
| 740 | .iter() |
| 741 | .map(line_text) |
| 742 | .filter(|line| line.contains(" lines) · ")) |
| 743 | .collect(); |
| 744 | assert_eq!( |
| 745 | announced.len(), |
| 746 | markers.len(), |
| 747 | "[{case}] every gap is announced once: {live_text}" |
| 748 | ); |
| 749 | for (line, marker) in announced.iter().zip(markers) { |
| 750 | assert!(line.contains(marker), "[{case}] `{marker}`: {live_text}"); |
| 751 | } |
| 752 | |
| 753 | let transcript_text = lines_text(&cell.transcript_lines(80)); |
| 754 | for line in output.lines() { |
| 755 | assert!( |
| 756 | transcript_text.contains(line.trim()), |
| 757 | "[{case}] the transcript keeps `{line}`: {transcript_text}" |
| 758 | ); |
| 759 | } |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | /// Repro for #80: a `git diff --stat`-shaped result must keep its newlines on |
| 764 | /// the transcript surface — one file per row, not squashed into one line. |
| 765 | #[test] |
| 766 | fn multi_line_tool_output_keeps_one_row_per_source_line() { |
| 767 | let diff_stat = "Cargo.lock | 1 +\n\ |
| 768 | crates/cli/Cargo.toml | 1 +\n\ |
| 769 | crates/cli/src/main.rs | 47 ++++++\n\ |
| 770 | crates/config/src/lib.rs | 27 ++++\n\ |
| 771 | crates/engine/src/mcp.rs | 384 +++++"; |
| 772 | |
| 773 | let cell = { |
| 774 | let mut cell = generic_tool("read_file", ToolStatus::Success); |
| 775 | cell.input_summary = Some("command: git diff --stat".to_string()); |
| 776 | cell.output = Some(diff_stat.to_string()); |
| 777 | HistoryCell::Tool(ToolCell::Generic(cell)) |
| 778 | }; |
| 779 | |
| 780 | let transcript_text = lines_text(&cell.transcript_lines(80)); |
| 781 | for needle in [ |
| 782 | "Cargo.lock", |
| 783 | "crates/cli/Cargo.toml", |
| 784 | "crates/cli/src/main.rs", |
| 785 | "crates/config/src/lib.rs", |
| 786 | "crates/engine/src/mcp.rs", |
| 787 | ] { |
| 788 | assert!( |
| 789 | transcript_text.contains(needle), |
| 790 | "transcript missing {needle:?}: {transcript_text}" |
| 791 | ); |
| 792 | } |
| 793 | let cargo_lock_row = transcript_text |
| 794 | .lines() |
| 795 | .find(|line| line.contains("Cargo.lock")) |
| 796 | .expect("Cargo.lock row must exist"); |
| 797 | assert!( |
| 798 | !cargo_lock_row.contains("crates/cli/Cargo.toml"), |
| 799 | "two files were joined onto one row: {cargo_lock_row}" |
| 800 | ); |
| 801 | } |
| 802 | |
| 803 | /// Reasoning folds in the live view and the fold is reversible: the collapsed |
| 804 | /// state must truncate a long body, the expanded state must restore every line |
| 805 | /// it dropped, and both must show the model's own identifiers verbatim (the |
| 806 | /// #4146/#4148 scrub rendered `refresh_catalog_cache` as `…` and protected |
| 807 | /// nothing, since the body was always one keypress away). The configured |
| 808 | /// default only inverts which state the toggle starts in. |
| 809 | /// |
| 810 | /// Replaces four separate fold tests. |
| 811 | #[test] |
| 812 | fn reasoning_folds_in_live_and_the_fold_is_reversible() { |
| 813 | let body = (1..=20) |
| 814 | .map(|i| format!("step {i:02}: refresh_catalog_cache iteration")) |
| 815 | .collect::<Vec<_>>() |
| 816 | .join("\n"); |
| 817 | let cell = HistoryCell::Thinking { |
| 818 | content: body, |
| 819 | streaming: false, |
| 820 | duration_secs: Some(1.0), |
| 821 | }; |
| 822 | |
| 823 | for default_expanded in [false, true] { |
| 824 | let options = TranscriptRenderOptions { |
| 825 | thinking_default_expanded: default_expanded, |
| 826 | low_motion: true, |
| 827 | ..TranscriptRenderOptions::default() |
| 828 | }; |
| 829 | // An explicit intent says expanded or collapsed outright, so the same |
| 830 | // two calls answer for either configured default. Running both proves |
| 831 | // the intent is not re-read through the preference. |
| 832 | let expanded = lines_text( |
| 833 | &cell |
| 834 | .lines_with_options_folded(80, options, Some(TranscriptFold::Expanded)) |
| 835 | .0, |
| 836 | ); |
| 837 | let collapsed = lines_text( |
| 838 | &cell |
| 839 | .lines_with_options_folded(80, options, Some(TranscriptFold::Collapsed)) |
| 840 | .0, |
| 841 | ); |
| 842 | |
| 843 | for i in 1..=20 { |
| 844 | assert!( |
| 845 | expanded.contains(&format!("step {i:02}: refresh_catalog_cache iteration")), |
| 846 | "[default_expanded={default_expanded}] expanded reasoning dropped line {i}: \ |
| 847 | {expanded}" |
| 848 | ); |
| 849 | } |
| 850 | assert!( |
| 851 | !collapsed.contains("step 20:"), |
| 852 | "[default_expanded={default_expanded}] the collapsed fold must truncate: {collapsed}" |
| 853 | ); |
| 854 | assert!( |
| 855 | collapsed.contains("refresh_catalog_cache"), |
| 856 | "[default_expanded={default_expanded}] the shown head keeps identifiers \ |
| 857 | verbatim: {collapsed}" |
| 858 | ); |
| 859 | assert!( |
| 860 | !collapsed.contains("Space:") && !collapsed.contains("Ctrl+O"), |
| 861 | "[default_expanded={default_expanded}] the per-cell renderer stays \ |
| 862 | target-neutral; the chord belongs to whoever owns focus: {collapsed}" |
| 863 | ); |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | /// The preference baseline (verbose session or expanded default) decides only |
| 868 | /// the cells nobody has touched; an explicit intent decides its own cell in |
| 869 | /// both directions. Verbose plus an expanded default renders expanded — the |
| 870 | /// old triple-XOR collapsed exactly that cell — and an explicit expand stays |
| 871 | /// expanded under every preference combination, which the later relative bit |
| 872 | /// still got wrong (#5847). |
| 873 | #[test] |
| 874 | fn explicit_thinking_fold_outranks_every_preference_baseline() { |
| 875 | let body = (1..=20) |
| 876 | .map(|i| format!("step {i:02}: baseline check")) |
| 877 | .collect::<Vec<_>>() |
| 878 | .join("\n"); |
| 879 | let cell = HistoryCell::Thinking { |
| 880 | content: body, |
| 881 | streaming: false, |
| 882 | duration_secs: Some(1.0), |
| 883 | }; |
| 884 | // (fold, verbose, default_expanded, expect_expanded) |
| 885 | for (fold, verbose, default_expanded, expect_expanded) in [ |
| 886 | // No explicit intent: the preference baseline decides. |
| 887 | (None, false, false, false), |
| 888 | (None, false, true, true), |
| 889 | (None, true, false, true), |
| 890 | (None, true, true, true), |
| 891 | // An explicit expand renders expanded whatever the preferences say. |
| 892 | (Some(TranscriptFold::Expanded), false, false, true), |
| 893 | (Some(TranscriptFold::Expanded), false, true, true), |
| 894 | (Some(TranscriptFold::Expanded), true, false, true), |
| 895 | (Some(TranscriptFold::Expanded), true, true, true), |
| 896 | // And an explicit collapse renders collapsed whatever they say. |
| 897 | (Some(TranscriptFold::Collapsed), false, false, false), |
| 898 | (Some(TranscriptFold::Collapsed), false, true, false), |
| 899 | (Some(TranscriptFold::Collapsed), true, false, false), |
| 900 | (Some(TranscriptFold::Collapsed), true, true, false), |
| 901 | ] { |
| 902 | let options = TranscriptRenderOptions { |
| 903 | verbose, |
| 904 | thinking_default_expanded: default_expanded, |
| 905 | low_motion: true, |
| 906 | ..TranscriptRenderOptions::default() |
| 907 | }; |
| 908 | let text = lines_text(&cell.lines_with_options_folded(80, options, fold).0); |
| 909 | let expanded = text.contains("step 20: baseline check"); |
| 910 | assert_eq!( |
| 911 | expanded, expect_expanded, |
| 912 | "[fold={fold:?} verbose={verbose} default_expanded={default_expanded}]" |
| 913 | ); |
| 914 | } |
| 915 | } |
| 916 | |
| 917 | /// A completed reasoning cell short enough to fit needs no expand affordance, |
| 918 | /// and the live view must still show it — the alternative was a dead card that |
| 919 | /// said reasoning happened and nothing about what it was. |
| 920 | #[test] |
| 921 | fn short_completed_reasoning_is_shown_live_without_an_affordance() { |
| 922 | let cell = HistoryCell::Thinking { |
| 923 | content: "One brief reasoning step.".to_string(), |
| 924 | streaming: false, |
| 925 | duration_secs: Some(0.4), |
| 926 | }; |
| 927 | |
| 928 | let live_text = lines_text(&cell.lines_with_options(80, calm_options())); |
| 929 | let transcript_text = lines_text(&cell.transcript_lines(80)); |
| 930 | |
| 931 | assert!( |
| 932 | live_text.contains("One brief reasoning step."), |
| 933 | "short completed reasoning belongs inline: {live_text}" |
| 934 | ); |
| 935 | assert!(transcript_text.contains("One brief reasoning step.")); |
| 936 | assert!( |
| 937 | !live_text.contains("Ctrl+O") && !live_text.contains("Space:"), |
| 938 | "a body that fits needs no affordance: {live_text}" |
| 939 | ); |
| 940 | } |
| 941 | |
| 942 | /// A live reasoning block must show what the model is thinking right now — the |
| 943 | /// old behavior stalled on a `thinking...` placeholder until the block closed, |
| 944 | /// and a long body must keep the newest line rather than the oldest. |
| 945 | #[test] |
| 946 | fn streaming_reasoning_shows_its_newest_line_not_a_placeholder() { |
| 947 | let short = render_thinking( |
| 948 | "Step 1: read the code\nStep 2: trace the call\nStep 3: form a hypothesis", |
| 949 | 80, |
| 950 | true, |
| 951 | None, |
| 952 | true, |
| 953 | true, |
| 954 | ); |
| 955 | let short_text = lines_text(&short); |
| 956 | assert!( |
| 957 | short_text.contains("Step 3: form a hypothesis"), |
| 958 | "the newest reasoning line must be visible while streaming: {short_text}" |
| 959 | ); |
| 960 | assert!( |
| 961 | !short_text.contains("thinking..."), |
| 962 | "real content means the placeholder must not be drawn: {short_text}" |
| 963 | ); |
| 964 | |
| 965 | let long = (1..=16) |
| 966 | .map(|i| format!("Reasoning line {i}")) |
| 967 | .collect::<Vec<_>>() |
| 968 | .join("\n"); |
| 969 | let long_text = lines_text(&render_thinking(&long, 80, true, None, true, true)); |
| 970 | assert!( |
| 971 | long_text.contains("Reasoning line 16"), |
| 972 | "the tail is what is live: {long_text}" |
| 973 | ); |
| 974 | assert!( |
| 975 | !long_text.contains("Reasoning line 1\n"), |
| 976 | "the head is what gets clipped: {long_text}" |
| 977 | ); |
| 978 | } |
| 979 | |
| 980 | /// A foreground shell wait blocks the turn. The card names the command it is |
| 981 | /// running, without a key hint, and does not duplicate the sidebar's live tail |
| 982 | /// in the transcript. Once the command finishes, the final output supersedes |
| 983 | /// any stale live tail. |
| 984 | /// |
| 985 | /// Replaces three tests. |
| 986 | #[test] |
| 987 | fn a_foreground_shell_wait_names_its_command_without_a_key_hint() { |
| 988 | let command = "cargo test --workspace --all-features"; |
| 989 | let running = { |
| 990 | let mut exec = exec_tool(command, ToolStatus::Running); |
| 991 | exec.live_output = Some("running line 1\nrunning line 2".to_string()); |
| 992 | exec.shell_task_id = Some("shell_live".to_string()); |
| 993 | exec |
| 994 | }; |
| 995 | |
| 996 | for (label, text) in [ |
| 997 | ("live", lines_text(&running.lines_with_motion(80, true))), |
| 998 | ( |
| 999 | "transcript", |
| 1000 | lines_text(&HistoryCell::Tool(ToolCell::Exec(running.clone())).transcript_lines(80)), |
| 1001 | ), |
| 1002 | ] { |
| 1003 | assert!( |
| 1004 | text.contains(command), |
| 1005 | "[{label}] the card names what is running: {text}" |
| 1006 | ); |
| 1007 | assert!( |
| 1008 | !text.contains("Ctrl+B"), |
| 1009 | "[{label}] a long wait moves itself to the background: {text}" |
| 1010 | ); |
| 1011 | assert!( |
| 1012 | !text.contains("running line 1"), |
| 1013 | "[{label}] the live tail belongs to the sidebar and /jobs: {text}" |
| 1014 | ); |
| 1015 | assert!(!text.contains("command:"), "[{label}] {text}"); |
| 1016 | } |
| 1017 | |
| 1018 | let mut finished = exec_tool(command, ToolStatus::Success); |
| 1019 | finished.output = Some("final output".to_string()); |
| 1020 | finished.live_output = Some("stale live tail".to_string()); |
| 1021 | finished.shell_task_id = Some("shell_live".to_string()); |
| 1022 | let text = lines_text(&finished.lines_with_motion(80, true)); |
| 1023 | assert!( |
| 1024 | !text.contains("stale live tail"), |
| 1025 | "a finished command must not show the tail it already superseded: {text}" |
| 1026 | ); |
| 1027 | } |
| 1028 | |
| 1029 | // --------------------------------------------------------------------------- |
| 1030 | // Clipboard — what you copy is what was authored |
| 1031 | // --------------------------------------------------------------------------- |
| 1032 | |
| 1033 | /// Every rendered line carries a `copy_prefix_width`: the display columns of |
| 1034 | /// decoration the clipboard must skip. The property is that slicing a line at |
| 1035 | /// that width yields the payload and nothing decorative — for role markers, |
| 1036 | /// status chrome, and the two-column continuation prefix on wrapped fenced code |
| 1037 | /// (which must be counted in display columns, not bytes, or CJK shifts it). |
| 1038 | /// |
| 1039 | /// Replaces three tests that each covered one cell kind. |
| 1040 | #[test] |
| 1041 | fn the_copy_prefix_skips_every_decoration_and_keeps_the_payload() { |
| 1042 | let decorations = ['╎', '▎', '●', '│', '┃', '✓', '▏']; |
| 1043 | |
| 1044 | let copied_line = |cell: &HistoryCell, width: u16, needle: &str| -> (String, usize) { |
| 1045 | let rendered = cell.lines_with_copy_metadata(width, TranscriptRenderOptions::default()); |
| 1046 | let target = rendered |
| 1047 | .iter() |
| 1048 | .find(|entry| { |
| 1049 | entry |
| 1050 | .line |
| 1051 | .spans |
| 1052 | .iter() |
| 1053 | .any(|span| span.content.contains(needle)) |
| 1054 | }) |
| 1055 | .unwrap_or_else(|| panic!("no rendered line contains {needle:?}")); |
| 1056 | let text = line_to_plain(&target.line); |
| 1057 | ( |
| 1058 | slice_visible_columns(&text, target.copy_prefix_width, text_visible_width(&text)), |
| 1059 | target.copy_prefix_width, |
| 1060 | ) |
| 1061 | }; |
| 1062 | |
| 1063 | // Fenced code: indentation survives, decoration does not. |
| 1064 | let rust_fence = HistoryCell::Assistant { |
| 1065 | content: "```rust\n let answer = 42;\n```".to_string(), |
| 1066 | streaming: false, |
| 1067 | }; |
| 1068 | let (copied, _) = copied_line(&rust_fence, 40, "answer"); |
| 1069 | assert!( |
| 1070 | copied.contains(" let answer = 42;"), |
| 1071 | "code indentation was not preserved: {copied:?}" |
| 1072 | ); |
| 1073 | for glyph in decorations { |
| 1074 | assert!( |
| 1075 | !copied.contains(glyph), |
| 1076 | "decorative glyph {glyph:?} leaked into copied code: {copied:?}" |
| 1077 | ); |
| 1078 | } |
| 1079 | |
| 1080 | // Wrapped CJK code: the prefix is two *display* columns, not two bytes. |
| 1081 | let cjk_fence = HistoryCell::Assistant { |
| 1082 | content: "```text\n 中文 = 1\n```".to_string(), |
| 1083 | streaming: false, |
| 1084 | }; |
| 1085 | let (copied, prefix) = copied_line(&cjk_fence, 24, "中文"); |
| 1086 | assert_eq!( |
| 1087 | prefix, 2, |
| 1088 | "the continuation prefix is the role marker's two display columns" |
| 1089 | ); |
| 1090 | assert!( |
| 1091 | copied.starts_with(" 中文"), |
| 1092 | "wide-character indentation was mis-sliced: {copied:?}" |
| 1093 | ); |
| 1094 | |
| 1095 | // Tool receipt: status and family chrome are prefix, the receipt text is |
| 1096 | // payload. |
| 1097 | let receipt = { |
| 1098 | let mut exec = exec_tool("printf 'receipt'", ToolStatus::Success); |
| 1099 | exec.output = Some("receipt".to_string()); |
| 1100 | HistoryCell::Tool(ToolCell::Exec(exec)) |
| 1101 | }; |
| 1102 | let rendered = receipt.lines_with_copy_metadata(80, TranscriptRenderOptions::default()); |
| 1103 | let header = rendered.first().expect("tool receipt header"); |
| 1104 | assert!( |
| 1105 | header.copy_prefix_width >= 4, |
| 1106 | "status and family chrome should be measured as prefix, got {}", |
| 1107 | header.copy_prefix_width |
| 1108 | ); |
| 1109 | let body = line_to_plain(&ratatui::text::Line::from( |
| 1110 | header |
| 1111 | .line |
| 1112 | .spans |
| 1113 | .iter() |
| 1114 | .skip(1) |
| 1115 | .cloned() |
| 1116 | .collect::<Vec<_>>(), |
| 1117 | )); |
| 1118 | let copied = slice_visible_columns(&body, header.copy_prefix_width, text_visible_width(&body)); |
| 1119 | assert!( |
| 1120 | copied.contains("run done"), |
| 1121 | "receipt text was clipped away: {copied:?}" |
| 1122 | ); |
| 1123 | for glyph in decorations { |
| 1124 | assert!( |
| 1125 | !copied.contains(glyph), |
| 1126 | "decorative glyph {glyph:?} leaked into the copied receipt: {copied:?}" |
| 1127 | ); |
| 1128 | } |
| 1129 | } |
| 1130 | |
| 1131 | /// Issue #1212: the transcript rail (`▏`) marks prose continuation. Inside a |
| 1132 | /// fence it corrupts anything the user copies, so no line of a code block may |
| 1133 | /// carry it — not the first, not a blank line in the middle, not a wrapped |
| 1134 | /// continuation of an over-long source line. |
| 1135 | /// |
| 1136 | /// Replaces four tests that each covered one fence shape. |
| 1137 | #[test] |
| 1138 | fn no_line_inside_a_fence_carries_the_transcript_rail() { |
| 1139 | let long_source = "let x = ".to_string() + &"abcdef ".repeat(40); |
| 1140 | |
| 1141 | for (label, content, width) in [ |
| 1142 | ( |
| 1143 | "short fence", |
| 1144 | "SQL:\n```sql\nSELECT\nFROM customers\n```".to_string(), |
| 1145 | 80u16, |
| 1146 | ), |
| 1147 | ( |
| 1148 | "multi-line fence", |
| 1149 | "Here's the query:\n```sql\nSELECT\n c.customer_id,\n c.name,\n \ |
| 1150 | COUNT(o.order_id) AS order_count\nFROM customers c\nJOIN orders o ON \ |
| 1151 | c.customer_id = o.customer_id;\n```" |
| 1152 | .to_string(), |
| 1153 | 80, |
| 1154 | ), |
| 1155 | ( |
| 1156 | "fence with a blank line", |
| 1157 | "```\nfn one() {}\n\nfn two() {}\n```".to_string(), |
| 1158 | 80, |
| 1159 | ), |
| 1160 | ("wrapped fence", format!("```\n{long_source}\n```"), 40), |
| 1161 | ] { |
| 1162 | let cell = HistoryCell::Assistant { |
| 1163 | content, |
| 1164 | streaming: false, |
| 1165 | }; |
| 1166 | // Line 0 is the intro paragraph (or the fence opener); every line |
| 1167 | // after it belongs to the code block. |
| 1168 | for line in cell.lines(width).iter().skip(1) { |
| 1169 | let text = line_text(line); |
| 1170 | assert!( |
| 1171 | !text.contains('\u{258F}'), |
| 1172 | "[{label}] code line took the transcript rail: {text:?}" |
| 1173 | ); |
| 1174 | } |
| 1175 | } |
| 1176 | } |
| 1177 | |
| 1178 | /// Whose text gets interpreted is a trust boundary. The model's markdown is |
| 1179 | /// rendered; the user's prompt is shown exactly as typed, including leading |
| 1180 | /// hashes, dashes and runs of spaces. A cell holding only whitespace renders |
| 1181 | /// nothing at all rather than an orphaned role glyph. |
| 1182 | /// |
| 1183 | /// Replaces three tests. |
| 1184 | #[test] |
| 1185 | fn authored_text_keeps_its_shape_on_both_sides_of_the_turn() { |
| 1186 | let user = HistoryCell::User { |
| 1187 | content: " # heading\n- item\n \nhello world".to_string(), |
| 1188 | }; |
| 1189 | let visible: Vec<String> = user.lines(80).iter().map(line_text).collect(); |
| 1190 | assert!( |
| 1191 | visible[0].trim_end().ends_with("# heading"), |
| 1192 | "a user's literal `#` must not become a rendered heading: {visible:?}" |
| 1193 | ); |
| 1194 | assert!( |
| 1195 | visible[1].trim_end().ends_with("- item"), |
| 1196 | "dash-prefixed user text stays literal: {visible:?}" |
| 1197 | ); |
| 1198 | assert!( |
| 1199 | visible[2].ends_with(" "), |
| 1200 | "whitespace-only user lines survive: {visible:?}" |
| 1201 | ); |
| 1202 | assert!( |
| 1203 | visible[3].trim_end().ends_with("hello world"), |
| 1204 | "internal spacing stays literal: {visible:?}" |
| 1205 | ); |
| 1206 | assert!( |
| 1207 | !visible.iter().any(|line| line.contains('\u{2500}')), |
| 1208 | "user text must not gain a markdown heading rule: {visible:?}" |
| 1209 | ); |
| 1210 | |
| 1211 | let assistant = HistoryCell::Assistant { |
| 1212 | content: "# Heading\n\n- item".to_string(), |
| 1213 | streaming: false, |
| 1214 | }; |
| 1215 | let visible: Vec<String> = assistant.lines(80).iter().map(line_text).collect(); |
| 1216 | assert!( |
| 1217 | visible[0].contains("Heading") && !visible[0].contains("# Heading"), |
| 1218 | "the model's markdown is still parsed: {visible:?}" |
| 1219 | ); |
| 1220 | assert!( |
| 1221 | visible.iter().any(|line| line.contains('\u{2500}')), |
| 1222 | "an assistant h1 still draws its rule: {visible:?}" |
| 1223 | ); |
| 1224 | |
| 1225 | // A stray newline streamed between reasoning and a tool call used to render |
| 1226 | // as a bare role glyph with nothing after it. |
| 1227 | for content in ["", " ", "\n", "\n\n", " \t \n"] { |
| 1228 | for streaming in [false, true] { |
| 1229 | let cell = HistoryCell::Assistant { |
| 1230 | content: content.to_string(), |
| 1231 | streaming, |
| 1232 | }; |
| 1233 | assert!( |
| 1234 | cell.lines(80).is_empty(), |
| 1235 | "whitespace-only assistant content {content:?} (streaming={streaming}) \ |
| 1236 | must render nothing" |
| 1237 | ); |
| 1238 | } |
| 1239 | } |
| 1240 | let real = HistoryCell::Assistant { |
| 1241 | content: "hi".to_string(), |
| 1242 | streaming: false, |
| 1243 | }; |
| 1244 | assert_eq!( |
| 1245 | real.lines(80)[0].spans[0].content.as_ref(), |
| 1246 | ASSISTANT_GLYPH, |
| 1247 | "real content still gets its role marker" |
| 1248 | ); |
| 1249 | } |
| 1250 | |
| 1251 | /// Reasoning is neither the user's prompt nor the model's answer, and a reader |
| 1252 | /// scanning the transcript has to be able to skip it. The markers below are |
| 1253 | /// referenced as named constants rather than literal glyphs on purpose: this |
| 1254 | /// protects the *distinction*, so a redesign that restyles reasoning stays |
| 1255 | /// green while one that stops marking it at all fails. |
| 1256 | #[test] |
| 1257 | fn reasoning_is_marked_apart_from_both_the_prompt_and_the_answer() { |
| 1258 | let body_text = "concrete reasoning content"; |
| 1259 | let reasoning = render_thinking(body_text, 80, false, Some(1.0), false, true); |
| 1260 | assert!(reasoning.len() >= 2, "expected a header and a body line"); |
| 1261 | |
| 1262 | let header = line_text(&reasoning[0]); |
| 1263 | assert!( |
| 1264 | header.starts_with(REASONING_OPENER), |
| 1265 | "the reasoning header opens with its own marker: {header:?}" |
| 1266 | ); |
| 1267 | let body = line_text(&reasoning[1]); |
| 1268 | assert!( |
| 1269 | body.starts_with(REASONING_RAIL), |
| 1270 | "the reasoning body carries its own rail: {body:?}" |
| 1271 | ); |
| 1272 | |
| 1273 | let rail = REASONING_RAIL.trim(); |
| 1274 | for cell in [ |
| 1275 | HistoryCell::User { |
| 1276 | content: body_text.to_string(), |
| 1277 | }, |
| 1278 | HistoryCell::Assistant { |
| 1279 | content: body_text.to_string(), |
| 1280 | streaming: false, |
| 1281 | }, |
| 1282 | ] { |
| 1283 | let rendered = lines_text(&cell.lines(80)); |
| 1284 | assert!( |
| 1285 | rendered.contains(body_text), |
| 1286 | "sanity: the cell rendered its content: {rendered}" |
| 1287 | ); |
| 1288 | assert!( |
| 1289 | !rendered.contains(rail), |
| 1290 | "only reasoning may wear the reasoning rail: {rendered}" |
| 1291 | ); |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | /// A filled background behind reasoning is unreadable on a transparent or |
| 1296 | /// light terminal, so the highlight is configurable. With it off, not one span |
| 1297 | /// may carry a background — a single tinted span is the bug. The enabled case |
| 1298 | /// follows the terminal's actual color depth: capable terminals tint the body, |
| 1299 | /// while ANSI-16 intentionally stays untinted because it cannot render the |
| 1300 | /// subtle surface faithfully. |
| 1301 | #[test] |
| 1302 | fn disabling_the_reasoning_highlight_leaves_no_span_with_a_background() { |
| 1303 | let render = |highlight: bool| { |
| 1304 | render_thinking_with_analysis( |
| 1305 | "reasoning without a filled surface", |
| 1306 | 80, |
| 1307 | false, |
| 1308 | Some(1.0), |
| 1309 | false, |
| 1310 | true, |
| 1311 | highlight, |
| 1312 | ) |
| 1313 | .0 |
| 1314 | }; |
| 1315 | |
| 1316 | assert!( |
| 1317 | render(false) |
| 1318 | .iter() |
| 1319 | .flat_map(|line| line.spans.iter()) |
| 1320 | .all(|span| span.style.bg.is_none()), |
| 1321 | "a disabled highlight must not tint any span" |
| 1322 | ); |
| 1323 | let enabled_has_background = render(true) |
| 1324 | .iter() |
| 1325 | .flat_map(|line| line.spans.iter()) |
| 1326 | .any(|span| span.style.bg.is_some()); |
| 1327 | assert_eq!( |
| 1328 | enabled_has_background, |
| 1329 | codewhale_palette::reasoning_surface_tint(cached_color_depth()).is_some(), |
| 1330 | "the enabled highlight must follow the terminal color-depth contract" |
| 1331 | ); |
| 1332 | } |
| 1333 | |
| 1334 | // --------------------------------------------------------------------------- |
| 1335 | // Motion — reduced motion is actually still |
| 1336 | // --------------------------------------------------------------------------- |
| 1337 | |
| 1338 | /// The deleted tests pinned the frozen glyphs (`assert_eq!(spans[1], "⣤")`). |
| 1339 | /// That breaks on a skin change and passes on the bug that matters: a marker |
| 1340 | /// that keeps animating for a user who asked it to stop. The property is |
| 1341 | /// stillness — a running cell's rendered frame must not depend on how long it |
| 1342 | /// has been running once motion is reduced — and the full-motion case is |
| 1343 | /// asserted alongside it so a renderer that froze everything could not make |
| 1344 | /// this test vacuously true. |
| 1345 | /// |
| 1346 | /// Stillness is not enough on its own. Animation frame 0 is U+2800 BRAILLE |
| 1347 | /// PATTERN BLANK, an invisible cell. Freezing there (or on the Still path) |
| 1348 | /// looks like a missing marker, which is why reduced motion must freeze on a |
| 1349 | /// filled, legible bubble rather than the blank the spinner starts on. |
| 1350 | #[test] |
| 1351 | fn reduced_and_still_motion_render_a_frame_that_does_not_move() { |
| 1352 | let frame_at = |elapsed_ms: u64, low_motion: bool, motion: MotionMode| { |
| 1353 | let mut exec = exec_tool("echo hi", ToolStatus::Running); |
| 1354 | exec.started_at = Some(Instant::now() - Duration::from_millis(elapsed_ms)); |
| 1355 | let cell = HistoryCell::Tool(ToolCell::Exec(exec)); |
| 1356 | lines_text(&cell.lines_with_options( |
| 1357 | 80, |
| 1358 | TranscriptRenderOptions { |
| 1359 | low_motion, |
| 1360 | motion_mode: motion, |
| 1361 | ..TranscriptRenderOptions::default() |
| 1362 | }, |
| 1363 | )) |
| 1364 | }; |
| 1365 | |
| 1366 | let frame_symbols = super::TOOL_RUNNING_SYMBOLS.len() as u64; |
| 1367 | let early = 1_250; |
| 1368 | let late = early + super::TOOL_STATUS_SYMBOL_MS * (frame_symbols / 8); |
| 1369 | assert!( |
| 1370 | early >= 1_000 && late < 2_000, |
| 1371 | "both samples must stay in the same elapsed-second bucket" |
| 1372 | ); |
| 1373 | |
| 1374 | // Two independent mechanisms are supposed to produce stillness — the |
| 1375 | // `low_motion` flag and the resolved `motion_mode`. Each is asserted on its |
| 1376 | // own so losing either one fails here, rather than only losing both. |
| 1377 | for (low_motion, motion) in [ |
| 1378 | (true, MotionMode::Reduced), |
| 1379 | (true, MotionMode::Still), |
| 1380 | (false, MotionMode::Reduced), |
| 1381 | (false, MotionMode::Still), |
| 1382 | ] { |
| 1383 | let frozen = frame_at(early, low_motion, motion); |
| 1384 | assert_eq!( |
| 1385 | frozen, |
| 1386 | frame_at(late, low_motion, motion), |
| 1387 | "low_motion={low_motion} / {motion:?} must not animate the live marker" |
| 1388 | ); |
| 1389 | assert!( |
| 1390 | !frozen.contains('\u{2800}'), |
| 1391 | "a frozen marker must still be visible: low_motion={low_motion} / {motion:?}: {frozen:?}" |
| 1392 | ); |
| 1393 | } |
| 1394 | assert_ne!( |
| 1395 | frame_at(early, false, MotionMode::Full), |
| 1396 | frame_at(late, false, MotionMode::Full), |
| 1397 | "full motion must actually animate, or the stillness assertions above \ |
| 1398 | prove nothing" |
| 1399 | ); |
| 1400 | |
| 1401 | // The same contract for the two other animated surfaces: the streaming |
| 1402 | // reasoning cursor and the assistant role marker's pulse. |
| 1403 | let cursor_off = lines_text(&render_thinking( |
| 1404 | "ongoing reasoning...", |
| 1405 | 80, |
| 1406 | true, |
| 1407 | None, |
| 1408 | false, |
| 1409 | true, |
| 1410 | )); |
| 1411 | assert!( |
| 1412 | !cursor_off.contains(REASONING_CURSOR), |
| 1413 | "low motion must suppress the streaming reasoning cursor: {cursor_off}" |
| 1414 | ); |
| 1415 | assert_eq!( |
| 1416 | assistant_label_style_for(true, true).fg, |
| 1417 | assistant_label_style_for(false, false).fg, |
| 1418 | "a streaming assistant marker under low motion must look exactly like an \ |
| 1419 | idle one — no pulse" |
| 1420 | ); |
| 1421 | } |
| 1422 | |
| 1423 | /// Dual of the low-motion freeze above: when the cell is streaming and |
| 1424 | /// motion is allowed, the assistant marker must actually pulse. The deleted |
| 1425 | /// test slept up to 1s sampling `SystemTime` until the 2s sine dipped; the |
| 1426 | /// property is that the streaming+motion color is `pulse_brightness` of the |
| 1427 | /// idle source, which we can check without waiting on the wall clock. |
| 1428 | /// |
| 1429 | /// Around the sine crest, `pulse_brightness` rounds back to the source |
| 1430 | /// (~70ms of a 2s cycle). Matching the current instant would then also pass |
| 1431 | /// a renderer that never pulsed, so we only compare once the pure function |
| 1432 | /// itself is off the crest — a busy wait, not a sleep. |
| 1433 | #[test] |
| 1434 | fn assistant_marker_pulses_when_streaming_and_motion_is_allowed() { |
| 1435 | use codewhale_palette::{self as palette, pulse_brightness}; |
| 1436 | |
| 1437 | let idle = assistant_label_style_for(false, false).fg; |
| 1438 | assert_eq!( |
| 1439 | idle, |
| 1440 | Some(palette::WHALE_ACTION), |
| 1441 | "the idle marker is the unpulsed source; pulsing everything would make \ |
| 1442 | the streaming assertion vacuously true" |
| 1443 | ); |
| 1444 | assert_eq!( |
| 1445 | assistant_label_style_for(true, true).fg, |
| 1446 | idle, |
| 1447 | "low motion must keep the streaming marker at the unpulsed source" |
| 1448 | ); |
| 1449 | |
| 1450 | let epoch_ms = || { |
| 1451 | std::time::SystemTime::now() |
| 1452 | .duration_since(std::time::UNIX_EPOCH) |
| 1453 | .map(|d| d.as_millis() as u64) |
| 1454 | .unwrap_or(0) |
| 1455 | }; |
| 1456 | let deadline = Instant::now() + Duration::from_millis(250); |
| 1457 | let (t0, actual) = loop { |
| 1458 | assert!( |
| 1459 | Instant::now() < deadline, |
| 1460 | "pulse_brightness stayed at the source color through a 250ms spin; \ |
| 1461 | the 2s cycle leaves the crest in ~70ms" |
| 1462 | ); |
| 1463 | let t0 = epoch_ms(); |
| 1464 | // Skip the crest and a few ms of margin so the product read of |
| 1465 | // SystemTime cannot land back on identity between this sample and |
| 1466 | // the call under test. |
| 1467 | let near_crest = (t0.saturating_sub(8)..=t0.saturating_add(8)) |
| 1468 | .any(|ms| pulse_brightness(palette::WHALE_ACTION, ms) == palette::WHALE_ACTION); |
| 1469 | if near_crest { |
| 1470 | continue; |
| 1471 | } |
| 1472 | break (t0, assistant_label_style_for(true, false).fg); |
| 1473 | }; |
| 1474 | let t1 = epoch_ms(); |
| 1475 | let matches_pulse = |
| 1476 | (t0..=t1.max(t0)).any(|ms| actual == Some(pulse_brightness(palette::WHALE_ACTION, ms))); |
| 1477 | assert!( |
| 1478 | matches_pulse, |
| 1479 | "streaming + motion must apply pulse_brightness to the assistant \ |
| 1480 | marker, got {actual:?}" |
| 1481 | ); |
| 1482 | assert_ne!( |
| 1483 | actual, idle, |
| 1484 | "streaming + motion must not sit at the idle color once the pulse \ |
| 1485 | is off its crest" |
| 1486 | ); |
| 1487 | } |
| 1488 | |
| 1489 | /// The still-motion path rewrites the leading status marker in place. It once |
| 1490 | /// rewrote any braille cell it found, which silently ate braille that was part |
| 1491 | /// of the tool's own output. |
| 1492 | #[test] |
| 1493 | fn the_still_marker_rewrite_never_consumes_braille_tool_output() { |
| 1494 | let mut cell = generic_tool("read_file", ToolStatus::Running); |
| 1495 | cell.output = Some("⣿".to_string()); |
| 1496 | let cell = HistoryCell::Tool(ToolCell::Generic(cell)); |
| 1497 | |
| 1498 | let lines = cell.lines_with_options( |
| 1499 | 80, |
| 1500 | TranscriptRenderOptions { |
| 1501 | low_motion: true, |
| 1502 | motion_mode: MotionMode::Still, |
| 1503 | ..TranscriptRenderOptions::default() |
| 1504 | }, |
| 1505 | ); |
| 1506 | |
| 1507 | assert!( |
| 1508 | lines |
| 1509 | .iter() |
| 1510 | .flat_map(|line| line.spans.iter()) |
| 1511 | .any(|span| span.content.as_ref() == "⣿"), |
| 1512 | "tool output must survive the typed-header marker pass: {lines:?}" |
| 1513 | ); |
| 1514 | } |
| 1515 | |
| 1516 | // --------------------------------------------------------------------------- |
| 1517 | // Identity — a card never names a verb or a tool it did not run |
| 1518 | // --------------------------------------------------------------------------- |
| 1519 | |
| 1520 | /// #4145: a completed grep grouped under the exploration card rendered |
| 1521 | /// `read done · Searching …` — the header verb contradicted the label directly |
| 1522 | /// under it. The verb must agree with the work, in every locale, and a locale |
| 1523 | /// must not fall back to the English status word. |
| 1524 | /// |
| 1525 | /// Replaces two tests, each of which hard-coded one direction. |
| 1526 | #[test] |
| 1527 | fn a_card_verb_agrees_with_its_own_label_in_every_locale() { |
| 1528 | use codewhale_localization::Locale; |
| 1529 | |
| 1530 | for (label, expected_en, expected_zh, forbidden_en) in [ |
| 1531 | ( |
| 1532 | "Searching for `TranscriptScroll`", |
| 1533 | "find done", |
| 1534 | "搜索 完成", |
| 1535 | "read done", |
| 1536 | ), |
| 1537 | ("Reading src/foo.rs", "read done", "读取 完成", "find done"), |
| 1538 | ] { |
| 1539 | let cell = super::ExploringCell { |
| 1540 | entries: vec![super::ExploringEntry { |
| 1541 | label: label.to_string(), |
| 1542 | search: label.starts_with("Searching"), |
| 1543 | status: ToolStatus::Success, |
| 1544 | error: None, |
| 1545 | }], |
| 1546 | }; |
| 1547 | |
| 1548 | let header_en = line_text(&cell.lines_with_motion(80, true)[0]); |
| 1549 | assert!( |
| 1550 | header_en.contains(expected_en), |
| 1551 | "{label:?} should read {expected_en:?}: {header_en:?}" |
| 1552 | ); |
| 1553 | assert!( |
| 1554 | !header_en.contains(forbidden_en), |
| 1555 | "{label:?} must not be paired with {forbidden_en:?}: {header_en:?}" |
| 1556 | ); |
| 1557 | assert!( |
| 1558 | header_en.contains(label), |
| 1559 | "the label itself must survive: {header_en:?}" |
| 1560 | ); |
| 1561 | |
| 1562 | let header_zh = line_text(&cell.lines_with_motion_and_locale(80, true, Locale::ZhHans)[0]); |
| 1563 | assert!( |
| 1564 | header_zh.contains(expected_zh), |
| 1565 | "{label:?} should read {expected_zh:?} in zh-Hans: {header_zh:?}" |
| 1566 | ); |
| 1567 | assert!( |
| 1568 | !header_zh.to_lowercase().contains("done"), |
| 1569 | "zh-Hans must not leak the English status word: {header_zh:?}" |
| 1570 | ); |
| 1571 | assert!( |
| 1572 | header_zh.contains(label), |
| 1573 | "the label itself must survive localization: {header_zh:?}" |
| 1574 | ); |
| 1575 | } |
| 1576 | } |
| 1577 | |
| 1578 | /// A read/find receipt reports a line count, so the count has to be real — |
| 1579 | /// including the singular/plural and the localized unit. A run receipt reports |
| 1580 | /// no count at all: inferring "3 lines" from rendered text that happens to |
| 1581 | /// contain `stdout:` would be inventing a number the shell never reported. |
| 1582 | #[test] |
| 1583 | fn receipts_count_only_what_they_actually_counted() { |
| 1584 | use crate::tui::widgets::tool_card::ToolFamily; |
| 1585 | use codewhale_localization::Locale; |
| 1586 | |
| 1587 | for (locale, done, unit) in [(Locale::En, "done", "line"), (Locale::ZhHans, "完成", "行")] { |
| 1588 | let label = |family, status, output| { |
| 1589 | super::tool_receipt_label(family, status, Some(output), locale) |
| 1590 | }; |
| 1591 | |
| 1592 | assert_eq!(label(ToolFamily::Read, ToolStatus::Success, ""), done); |
| 1593 | assert_eq!( |
| 1594 | label(ToolFamily::Read, ToolStatus::Success, "hello\n"), |
| 1595 | if locale == Locale::En { |
| 1596 | "1 line".to_string() |
| 1597 | } else { |
| 1598 | format!("1 {unit}") |
| 1599 | } |
| 1600 | ); |
| 1601 | assert_eq!( |
| 1602 | label(ToolFamily::Read, ToolStatus::Success, "a\nb\nc\n"), |
| 1603 | if locale == Locale::En { |
| 1604 | "3 lines".to_string() |
| 1605 | } else { |
| 1606 | format!("3 {unit}") |
| 1607 | } |
| 1608 | ); |
| 1609 | assert_eq!( |
| 1610 | label(ToolFamily::Find, ToolStatus::Success, "match 1\nmatch 2\n"), |
| 1611 | if locale == Locale::En { |
| 1612 | "2 lines".to_string() |
| 1613 | } else { |
| 1614 | format!("2 {unit}") |
| 1615 | } |
| 1616 | ); |
| 1617 | |
| 1618 | // Run never counts, whatever the body looks like. |
| 1619 | for body in [ |
| 1620 | "stdout:\nok\nmore\nstderr:\nbad\n", |
| 1621 | "line 1\nline 2\nline 3\n", |
| 1622 | ] { |
| 1623 | assert_eq!( |
| 1624 | label(ToolFamily::Run, ToolStatus::Success, body), |
| 1625 | done, |
| 1626 | "a run receipt must not infer counts from {body:?}" |
| 1627 | ); |
| 1628 | } |
| 1629 | } |
| 1630 | |
| 1631 | assert_eq!( |
| 1632 | super::tool_receipt_label( |
| 1633 | ToolFamily::Read, |
| 1634 | ToolStatus::Running, |
| 1635 | Some("a\nb"), |
| 1636 | Locale::En |
| 1637 | ), |
| 1638 | "running", |
| 1639 | "an unfinished read has nothing to count yet" |
| 1640 | ); |
| 1641 | for (status, text) in [ |
| 1642 | (ToolStatus::Running, "运行中"), |
| 1643 | (ToolStatus::Failed, "失败"), |
| 1644 | (ToolStatus::Stopped, "已停止"), |
| 1645 | (ToolStatus::Hydrated, "已加载,未运行"), |
| 1646 | (ToolStatus::Warning, "存在问题"), |
| 1647 | ] { |
| 1648 | assert_eq!( |
| 1649 | super::tool_receipt_label(ToolFamily::Run, status, None, Locale::ZhHans), |
| 1650 | text |
| 1651 | ); |
| 1652 | } |
| 1653 | } |
| 1654 | |
| 1655 | /// The same truthfulness contract through the real shell render path, where a |
| 1656 | /// formatter has already rewritten the output: the header still reports a plain |
| 1657 | /// localized completion and never a fabricated line count or stream name. |
| 1658 | #[test] |
| 1659 | fn shell_headers_stay_truthful_through_the_output_formatters() { |
| 1660 | use codewhale_localization::Locale; |
| 1661 | |
| 1662 | let cases = [ |
| 1663 | ( |
| 1664 | "printf redirect", |
| 1665 | "printf '%s\\n' 'hello' 'world' > src/main.rs", |
| 1666 | "printf > src/main.rs\nhello\nworld\n", |
| 1667 | ), |
| 1668 | ( |
| 1669 | "logical-or fallback", |
| 1670 | "cargo build || echo fallback", |
| 1671 | " Compiling pkg v0.1.0\n Finished dev [unoptimized + debuginfo]\n", |
| 1672 | ), |
| 1673 | ]; |
| 1674 | |
| 1675 | for (label, command, output) in cases { |
| 1676 | let mut cell = exec_tool(command, ToolStatus::Success); |
| 1677 | cell.output = Some(output.to_string()); |
| 1678 | cell.duration_ms = Some(42); |
| 1679 | |
| 1680 | for (locale, done, unit) in [ |
| 1681 | (Locale::En, "done", "lines"), |
| 1682 | (Locale::ZhHans, "完成", " 行"), |
| 1683 | ] { |
| 1684 | let header = line_text(&cell.render_with_locale(80, true, RenderMode::Live, locale)[0]); |
| 1685 | assert!( |
| 1686 | header.contains(done), |
| 1687 | "[{label}] header must carry the localized completion: {header}" |
| 1688 | ); |
| 1689 | assert!( |
| 1690 | !header.contains(unit) && !header.contains("stdout") && !header.contains("stderr"), |
| 1691 | "[{label}] header must not invent counts or stream names: {header}" |
| 1692 | ); |
| 1693 | } |
| 1694 | } |
| 1695 | } |
| 1696 | |
| 1697 | /// #4133 / #4148: a spawn yields its card entirely to the DelegateCard, and an |
| 1698 | /// inspection (`peek` / `wait` / `status`) is a one-line check in every render |
| 1699 | /// mode. It must name the child it checked, must not read as a completed |
| 1700 | /// delegation, and must not leak the internal "unknown child" placeholder or |
| 1701 | /// echo the verb twice when the resolved identity collapses onto it. |
| 1702 | /// |
| 1703 | /// Replaces eight tests. |
| 1704 | #[test] |
| 1705 | fn agent_cards_stay_one_line_and_spawn_cards_yield_to_the_delegate_card() { |
| 1706 | let agent = |summary: &str, output: Option<&str>| { |
| 1707 | let mut cell = generic_tool("agent", ToolStatus::Success); |
| 1708 | cell.input_summary = Some(summary.to_string()); |
| 1709 | cell.output = output.map(str::to_string); |
| 1710 | cell |
| 1711 | }; |
| 1712 | |
| 1713 | for mode in [RenderMode::Live, RenderMode::Transcript] { |
| 1714 | let spawn = agent( |
| 1715 | "prompt: map the repo", |
| 1716 | Some(r#"{"agent_id":"agent_scout_1","status":"running"}"#), |
| 1717 | ); |
| 1718 | assert!( |
| 1719 | spawn.lines_with_mode(120, true, mode).is_empty(), |
| 1720 | "a spawn must not draw a generic card beside the DelegateCard in {mode:?}" |
| 1721 | ); |
| 1722 | |
| 1723 | for (summary, output, expected) in [ |
| 1724 | ( |
| 1725 | "action: peek agent_id: agent_scout_1", |
| 1726 | Some(r#"{"agent_id":"agent_scout_1","status":"running"}"#), |
| 1727 | "checked", |
| 1728 | ), |
| 1729 | ( |
| 1730 | "action: wait", |
| 1731 | Some(r#"{"action":"wait","settled":[{"agent_id":"agent_scout_1"}]}"#), |
| 1732 | "waited", |
| 1733 | ), |
| 1734 | ( |
| 1735 | "action: status agent_id: agent_scout_1", |
| 1736 | Some(r#"{"agent_id":"agent_scout_1","status":"running","terminal":false}"#), |
| 1737 | "checked", |
| 1738 | ), |
| 1739 | ] { |
| 1740 | let cell = agent(summary, output); |
| 1741 | let lines = cell.lines_with_mode(120, true, mode); |
| 1742 | let text = lines_text(&lines); |
| 1743 | assert_eq!( |
| 1744 | lines.len(), |
| 1745 | 1, |
| 1746 | "{summary:?} must stay one line in {mode:?}: {lines:?}" |
| 1747 | ); |
| 1748 | assert!( |
| 1749 | text.contains(expected), |
| 1750 | "{summary:?} should read as {expected:?}: {text:?}" |
| 1751 | ); |
| 1752 | assert!( |
| 1753 | !text.to_lowercase().contains("delegate done"), |
| 1754 | "an inspection must not read as a finished delegation: {text:?}" |
| 1755 | ); |
| 1756 | } |
| 1757 | } |
| 1758 | |
| 1759 | // Identity fallbacks: no raw placeholder, no doubled verb. |
| 1760 | let unresolved = agent("action: peek agent_type: delegate", None); |
| 1761 | let text = lines_text(&unresolved.lines_with_mode(80, true, RenderMode::Live)); |
| 1762 | assert!( |
| 1763 | !text.contains("unknown child"), |
| 1764 | "the internal fallback token must not reach the transcript: {text:?}" |
| 1765 | ); |
| 1766 | |
| 1767 | let collapsing = agent("action: peek role: delegate", None); |
| 1768 | let text = lines_text(&collapsing.lines_with_mode(80, true, RenderMode::Live)); |
| 1769 | assert!( |
| 1770 | text.contains(" agent "), |
| 1771 | "the agent family label should appear once in the summary: {text:?}" |
| 1772 | ); |
| 1773 | let mut failed = agent("action: peek agent_id: agent_scout_1", Some("failed")); |
| 1774 | failed.status = ToolStatus::Failed; |
| 1775 | let text = lines_text(&failed.lines_with_mode_and_locale( |
| 1776 | 120, |
| 1777 | true, |
| 1778 | RenderMode::Live, |
| 1779 | codewhale_localization::Locale::ZhHans, |
| 1780 | )); |
| 1781 | assert!(text.contains("失败"), "{text}"); |
| 1782 | assert!(!text.contains("已检查"), "{text}"); |
| 1783 | } |
| 1784 | |
| 1785 | /// A tool the catalog does not have produces one useful sentence — the catalog |
| 1786 | /// error — and nothing else. The old rendering spent a `name:` / `args:` / |
| 1787 | /// `result:` block restating a call that never happened. |
| 1788 | #[test] |
| 1789 | fn an_unknown_tool_failure_shows_only_the_catalog_error() { |
| 1790 | let mut cell = generic_tool("item", ToolStatus::Failed); |
| 1791 | cell.input_summary = Some("status: pending".to_string()); |
| 1792 | cell.output = Some( |
| 1793 | "Tool 'item' is not available in the current tool catalog. \ |
| 1794 | Checklist entries are not separate tool calls." |
| 1795 | .to_string(), |
| 1796 | ); |
| 1797 | |
| 1798 | for mode in [RenderMode::Live, RenderMode::Transcript] { |
| 1799 | let lines = cell.lines_with_mode(120, true, mode); |
| 1800 | let text = lines_text(&lines); |
| 1801 | assert_eq!(lines.len(), 1, "single header line in {mode:?}: {lines:?}"); |
| 1802 | assert!( |
| 1803 | text.contains("Tool 'item' is not available"), |
| 1804 | "the catalog error is the useful part: {text:?}" |
| 1805 | ); |
| 1806 | assert!( |
| 1807 | !text.contains("name: item"), |
| 1808 | "no name/args/result block for a call that did not happen: {text:?}" |
| 1809 | ); |
| 1810 | } |
| 1811 | } |
| 1812 | |
| 1813 | // --------------------------------------------------------------------------- |
| 1814 | // Severity — the ranks stay distinguishable |
| 1815 | // --------------------------------------------------------------------------- |
| 1816 | |
| 1817 | /// The deleted tests pinned each severity to a named palette constant, so a |
| 1818 | /// theme change broke four tests and a severity collapse broke none. What has |
| 1819 | /// to hold is the *relationship*: `Critical` reads exactly as loud as `Error`, |
| 1820 | /// `Warning` is visibly not an error, and `Info` is quieter than both — so a |
| 1821 | /// transient retry cannot be mistaken for a hard failure sitting next to it. |
| 1822 | #[test] |
| 1823 | fn error_severity_ranks_stay_visually_distinguishable() { |
| 1824 | use codewhale_error_taxonomy::ErrorSeverity; |
| 1825 | |
| 1826 | let rank = |severity| { |
| 1827 | let cell = HistoryCell::Error { |
| 1828 | message: "Authentication failed: invalid API key".to_string(), |
| 1829 | severity, |
| 1830 | code: None, |
| 1831 | }; |
| 1832 | let lines = cell.lines(80); |
| 1833 | assert!(!lines.is_empty(), "{severity:?} must render a line"); |
| 1834 | let label = &lines[0].spans[0]; |
| 1835 | (label.content.to_string(), label.style.fg) |
| 1836 | }; |
| 1837 | |
| 1838 | let (error_label, error_fg) = rank(ErrorSeverity::Error); |
| 1839 | let (critical_label, critical_fg) = rank(ErrorSeverity::Critical); |
| 1840 | let (warning_label, warning_fg) = rank(ErrorSeverity::Warning); |
| 1841 | let (info_label, info_fg) = rank(ErrorSeverity::Info); |
| 1842 | |
| 1843 | assert_eq!( |
| 1844 | (critical_label, critical_fg), |
| 1845 | (error_label.clone(), error_fg), |
| 1846 | "Critical and Error both flip offline mode; they must read identically" |
| 1847 | ); |
| 1848 | assert_ne!( |
| 1849 | warning_fg, error_fg, |
| 1850 | "a warning that reads as an error is the whole bug this guards" |
| 1851 | ); |
| 1852 | assert_ne!(warning_label, error_label, "and the labels must differ too"); |
| 1853 | assert_ne!(info_fg, error_fg, "info must not shout"); |
| 1854 | assert_ne!(info_fg, warning_fg, "info must not read as a warning"); |
| 1855 | assert_ne!(info_label, warning_label); |
| 1856 | |
| 1857 | // The body inherits the label's rank rather than staying neutral, or the |
| 1858 | // colour would carry no information past the first word. |
| 1859 | let cell = HistoryCell::Error { |
| 1860 | message: "Authentication failed: invalid API key".to_string(), |
| 1861 | severity: ErrorSeverity::Error, |
| 1862 | code: None, |
| 1863 | }; |
| 1864 | let body_fg = cell |
| 1865 | .lines(80) |
| 1866 | .iter() |
| 1867 | .flat_map(|line| line.spans.iter()) |
| 1868 | .find(|span| span.content.contains("Authentication")) |
| 1869 | .expect("error body span") |
| 1870 | .style |
| 1871 | .fg; |
| 1872 | assert_eq!(body_fg, error_fg); |
| 1873 | } |
| 1874 | |
| 1875 | #[test] |
| 1876 | fn error_guidance_keeps_recovery_commands_on_their_own_line() { |
| 1877 | let cell = HistoryCell::Error { |
| 1878 | message: "DeepSeek API key not found.\nSave it:\n codewhale auth set --provider deepseek" |
| 1879 | .to_string(), |
| 1880 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 1881 | code: None, |
| 1882 | }; |
| 1883 | for width in [80, 140] { |
| 1884 | let lines = cell.lines(width); |
| 1885 | let command_line = lines |
| 1886 | .iter() |
| 1887 | .map(|line| { |
| 1888 | line.spans |
| 1889 | .iter() |
| 1890 | .map(|span| span.content.as_ref()) |
| 1891 | .collect::<String>() |
| 1892 | }) |
| 1893 | .find(|line| line.contains("codewhale auth set --provider deepseek")) |
| 1894 | .expect("recovery command stays intact"); |
| 1895 | assert!(!command_line.contains('\n'), "{command_line:?}"); |
| 1896 | assert!(!command_line.contains("Save it:"), "{command_line:?}"); |
| 1897 | } |
| 1898 | } |
| 1899 | |
| 1900 | /// A multiline failure can run past the bottom of the terminal while its full |
| 1901 | /// text stays in history. The live cell advertises the pager; the pager and the |
| 1902 | /// transcript must carry the recovery instruction verbatim and must not |
| 1903 | /// recursively advertise themselves. |
| 1904 | #[test] |
| 1905 | fn an_error_cell_advertises_the_pager_live_and_never_inside_it() { |
| 1906 | let recovery = "Refusing insecure base URL 'http://192.168.1.25:8000/v1'.\n\ |
| 1907 | Loopback hosts (localhost, 127.0.0.1, [::1]) are auto-allowed.\n\ |
| 1908 | Set CODEWHALE_ALLOW_INSECURE_HTTP=1 only for a trusted LAN host."; |
| 1909 | let cell = HistoryCell::Error { |
| 1910 | message: recovery.to_string(), |
| 1911 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 1912 | code: None, |
| 1913 | }; |
| 1914 | |
| 1915 | let live_text = lines_text(&cell.lines(48)); |
| 1916 | let transcript_text = lines_text(&cell.transcript_lines(200)); |
| 1917 | let hint = crate::tui::key_shortcuts::tool_details_shortcut_action_hint("full error"); |
| 1918 | |
| 1919 | assert!(live_text.contains(&hint), "{live_text}"); |
| 1920 | assert!(!transcript_text.contains(&hint), "{transcript_text}"); |
| 1921 | assert!( |
| 1922 | transcript_text.contains("CODEWHALE_ALLOW_INSECURE_HTTP=1"), |
| 1923 | "the actionable instruction must survive verbatim: {transcript_text}" |
| 1924 | ); |
| 1925 | assert!( |
| 1926 | transcript_text.contains("192.168.1.25"), |
| 1927 | "the offending host must survive verbatim: {transcript_text}" |
| 1928 | ); |
| 1929 | } |
| 1930 | |
| 1931 | #[test] |
| 1932 | fn error_envelope_code_renders_muted_badge_without_duplication() { |
| 1933 | let cell = HistoryCell::Error { |
| 1934 | message: "SSE stream request did not receive response headers after 45s".to_string(), |
| 1935 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 1936 | code: Some("llm_network_error".to_string()), |
| 1937 | }; |
| 1938 | |
| 1939 | let lines = cell.lines(80); |
| 1940 | let rendered = lines_text(&lines); |
| 1941 | assert!(rendered.contains("Error [llm_network_error]"), "{rendered}"); |
| 1942 | assert!(rendered.contains("after 45s"), "{rendered}"); |
| 1943 | for line in &lines { |
| 1944 | assert!(line.width() <= 80, "line overflowed 80 cols: {line:?}"); |
| 1945 | } |
| 1946 | let badge_span = lines[0] |
| 1947 | .spans |
| 1948 | .iter() |
| 1949 | .find(|span| span.content == "[llm_network_error]") |
| 1950 | .expect("muted error code badge"); |
| 1951 | let label_span = &lines[0].spans[0]; |
| 1952 | assert_eq!(badge_span.style.fg, Some(codewhale_palette::TEXT_MUTED)); |
| 1953 | assert_ne!(badge_span.style.fg, label_span.style.fg); |
| 1954 | assert_eq!( |
| 1955 | crate::tui::history::text::history_cell_to_text(&cell, 80), |
| 1956 | "[llm_network_error] SSE stream request did not receive response headers after 45s" |
| 1957 | ); |
| 1958 | |
| 1959 | let narrow = cell.lines(28); |
| 1960 | let narrow_text = lines_text(&narrow); |
| 1961 | assert!(narrow_text.contains("[llm_network_error]"), "{narrow_text}"); |
| 1962 | assert!(narrow_text.contains("after 45s"), "{narrow_text}"); |
| 1963 | for line in &narrow { |
| 1964 | assert!( |
| 1965 | line.width() <= 28, |
| 1966 | "narrow line overflowed 28 cols: {line:?}" |
| 1967 | ); |
| 1968 | } |
| 1969 | |
| 1970 | let already_tagged = HistoryCell::Error { |
| 1971 | message: "Provider failed [llm_rate_limited]: retry in 10s".to_string(), |
| 1972 | severity: codewhale_error_taxonomy::ErrorSeverity::Warning, |
| 1973 | code: Some("llm_rate_limited".to_string()), |
| 1974 | }; |
| 1975 | let tagged_text = lines_text(&already_tagged.lines(100)); |
| 1976 | assert_eq!( |
| 1977 | tagged_text.matches("llm_rate_limited").count(), |
| 1978 | 1, |
| 1979 | "code already present in message must not duplicate: {tagged_text}" |
| 1980 | ); |
| 1981 | assert_eq!( |
| 1982 | crate::tui::history::text::history_cell_to_text(&already_tagged, 100), |
| 1983 | "Provider failed [llm_rate_limited]: retry in 10s" |
| 1984 | ); |
| 1985 | |
| 1986 | let substring_non_match = HistoryCell::Error { |
| 1987 | message: "Invalid statement from provider".to_string(), |
| 1988 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 1989 | code: Some("state".to_string()), |
| 1990 | }; |
| 1991 | assert!( |
| 1992 | lines_text(&substring_non_match.lines(80)).contains("[state]"), |
| 1993 | "partial word match must not suppress badge" |
| 1994 | ); |
| 1995 | } |
| 1996 | |
| 1997 | // --------------------------------------------------------------------------- |
| 1998 | // Cards with a content contract |
| 1999 | // --------------------------------------------------------------------------- |
| 2000 | |
| 2001 | /// A search receipt has to name where the answer came from and whether the |
| 2002 | /// provider it claimed was the provider it used. |
| 2003 | #[test] |
| 2004 | fn a_web_search_receipt_names_its_source_and_any_degradation() { |
| 2005 | let cell = WebSearchCell { |
| 2006 | query: "current release".to_string(), |
| 2007 | status: ToolStatus::Success, |
| 2008 | summary: Some("Found 2 results".to_string()), |
| 2009 | source: Some("provider-native/xai/grok-4.5".to_string()), |
| 2010 | degraded: Some("provider_native -> duckduckgo".to_string()), |
| 2011 | ref_count: 2, |
| 2012 | }; |
| 2013 | |
| 2014 | let rendered = lines_text(&cell.lines_with_motion(120, true)); |
| 2015 | |
| 2016 | for needle in [ |
| 2017 | "source", |
| 2018 | "provider-native/xai/grok-4.5", |
| 2019 | "degraded", |
| 2020 | "provider_native -> duckduckgo", |
| 2021 | "citations", |
| 2022 | ] { |
| 2023 | assert!(rendered.contains(needle), "missing {needle:?}: {rendered}"); |
| 2024 | } |
| 2025 | } |
| 2026 | |
| 2027 | /// A workflow's transcript is one row per run; live progress is the |
| 2028 | /// workbar's. A foreground `run` card that returned its settled record says |
| 2029 | /// only the finish — the final state replaces `started` — without repeating the header |
| 2030 | /// in a body; the expanded card adds the goal, the child labels, the final |
| 2031 | /// result and the error; the status card lists the runs it found. |
| 2032 | /// |
| 2033 | /// Replaces three tests, and drops assertions of the form |
| 2034 | /// `contains('s') || contains('m')` — true of essentially any English string. |
| 2035 | #[test] |
| 2036 | fn workflow_cards_report_lifecycle_children_phases_and_failures() { |
| 2037 | let run_output = serde_json::json!({ |
| 2038 | "run_id": "workflow_2400c600", |
| 2039 | "status": "completed", |
| 2040 | "workflow_goal": "audit the FLEET and WORKFLOW docs", |
| 2041 | "child_ids": ["a1", "a2", "a3"], |
| 2042 | "progress": ["phase: Scan", "log: 3 findings"], |
| 2043 | "events": [ |
| 2044 | {"type": "task_started", "task_id": "a1", "label": "scan-docs", |
| 2045 | "workflow_run_id": "workflow_2400c600", "workflow_phase_id": "Scan", |
| 2046 | "workflow_task_label": "scan-docs", "workflow_child_index": 0}, |
| 2047 | {"type": "task_started", "task_id": "a2", "workflow_task_label": "check-fleet", |
| 2048 | "workflow_run_id": "workflow_2400c600", "workflow_child_index": 1}, |
| 2049 | {"type": "task_started", "task_id": "a3", "label": "summarize", |
| 2050 | "workflow_run_id": "workflow_2400c600", "workflow_child_index": 2}, |
| 2051 | ], |
| 2052 | "schema_errors": [], |
| 2053 | }) |
| 2054 | .to_string(); |
| 2055 | let mut run = generic_tool("workflow", ToolStatus::Success); |
| 2056 | run.input_summary = Some("action: run".to_string()); |
| 2057 | run.output = Some(run_output); |
| 2058 | let text = lines_text(&run.lines_with_mode(120, true, RenderMode::Live)); |
| 2059 | assert!( |
| 2060 | !text.contains("started"), |
| 2061 | "the settled record replaces the start line: {text:?}" |
| 2062 | ); |
| 2063 | assert!( |
| 2064 | text.contains("finished") && text.contains("/3 done"), |
| 2065 | "the finish line with done/total agents: {text:?}" |
| 2066 | ); |
| 2067 | assert_eq!(text.lines().count(), 1, "one row for the run: {text:?}"); |
| 2068 | // #6503: a run with no failures does not announce `0 fail`. |
| 2069 | assert!(!text.contains("fail"), "no zero failure count: {text:?}"); |
| 2070 | assert!( |
| 2071 | !text.contains("status:"), |
| 2072 | "the body must not repeat the header lifecycle: {text:?}" |
| 2073 | ); |
| 2074 | |
| 2075 | let failed_output = serde_json::json!({ |
| 2076 | "run_id": "workflow_exp", |
| 2077 | "status": "failed", |
| 2078 | "workflow_goal": "ship v0.8.68", |
| 2079 | "started_at_ms": 1000, |
| 2080 | "completed_at_ms": 5000, |
| 2081 | "source_path": "workflows/demo.workflow.js", |
| 2082 | "error": "phase Verify failed", |
| 2083 | "result": {"summary": "2 of 3 children ok"}, |
| 2084 | "events": [ |
| 2085 | {"type": "run_started", "at_ms": 1000, "run_id": "workflow_exp", |
| 2086 | "workflow_goal": "ship v0.8.68"}, |
| 2087 | {"type": "phase_started", "at_ms": 1100, "title": "Verify"}, |
| 2088 | {"type": "task_started", "at_ms": 1200, "task_id": "t1", "label": "run tests", |
| 2089 | "workflow_task_label": "run tests", "profile": "implementer"}, |
| 2090 | {"type": "task_completed", "at_ms": 4000, "task_id": "t1", "status": "failed"}, |
| 2091 | {"type": "run_completed", "at_ms": 5000, "status": "failed", |
| 2092 | "error": "phase Verify failed"} |
| 2093 | ] |
| 2094 | }) |
| 2095 | .to_string(); |
| 2096 | let mut failed = generic_tool("workflow", ToolStatus::Failed); |
| 2097 | failed.input_summary = Some("action: run".to_string()); |
| 2098 | failed.output = Some(failed_output); |
| 2099 | failed.spillover_path = Some(PathBuf::from("/tmp/wf-artifact.json")); |
| 2100 | let text = lines_text(&failed.lines_with_mode(140, true, RenderMode::Transcript)); |
| 2101 | for needle in [ |
| 2102 | "ship v0.8.68", |
| 2103 | "Verify", |
| 2104 | "run tests", |
| 2105 | "2 of 3", |
| 2106 | "phase Verify failed", |
| 2107 | ] { |
| 2108 | assert!( |
| 2109 | text.contains(needle), |
| 2110 | "the expanded card must carry {needle:?}: {text}" |
| 2111 | ); |
| 2112 | } |
| 2113 | |
| 2114 | let status_output = serde_json::json!({ |
| 2115 | "action": "status", |
| 2116 | "count": 2, |
| 2117 | "runs": [ |
| 2118 | {"run_id": "workflow_aaa", "status": "running", "child_count": 4}, |
| 2119 | {"run_id": "workflow_bbb", "status": "completed", "child_count": 1}, |
| 2120 | ], |
| 2121 | }) |
| 2122 | .to_string(); |
| 2123 | let mut status = generic_tool("workflow", ToolStatus::Success); |
| 2124 | status.input_summary = Some("action: status".to_string()); |
| 2125 | status.output = Some(status_output); |
| 2126 | let text = lines_text(&status.lines_with_mode(120, true, RenderMode::Live)); |
| 2127 | for needle in ["2 run(s)", "workflow_aaa", "running", "workflow_bbb"] { |
| 2128 | assert!( |
| 2129 | text.contains(needle), |
| 2130 | "the status card must list {needle:?}: {text:?}" |
| 2131 | ); |
| 2132 | } |
| 2133 | } |
| 2134 | |
| 2135 | /// The founder's transcript (2026-09-28): a refused `start` echoed |
| 2136 | /// `action: start` and hid its reason; the settled run's reason was cut |
| 2137 | /// mid-word. Each is one row that says why. |
| 2138 | #[test] |
| 2139 | fn workflow_rows_say_why_without_raw_action_or_mid_word_cuts() { |
| 2140 | let mut refused = generic_tool("workflow", ToolStatus::Failed); |
| 2141 | refused.input_summary = Some("action: start".to_string()); |
| 2142 | refused.output = Some( |
| 2143 | "Error: Invalid input for tool 'workflow': Workflow leaf 'engine-readiness': \ |
| 2144 | task(): cwd entries must be bounded repo-relative paths\n\ |
| 2145 | Tool validation feedback: {\"category\":\"invalid_input\"}" |
| 2146 | .to_string(), |
| 2147 | ); |
| 2148 | let text = lines_text(&refused.lines_with_mode(100, true, RenderMode::Live)); |
| 2149 | assert!(!text.contains("action: start"), "{text}"); |
| 2150 | assert!( |
| 2151 | text.contains("cwd entries must be bounded repo-relative paths"), |
| 2152 | "{text}" |
| 2153 | ); |
| 2154 | assert!(!text.contains("Invalid input for tool"), "{text}"); |
| 2155 | |
| 2156 | let reason = "[auth] Authorization failed: You have run out of credits or need a Grok \ |
| 2157 | subscription. Add credits at https://grok.com/?_s=usage."; |
| 2158 | let failed = serde_json::json!({ |
| 2159 | "run_id": "workflow_6409ebe6", |
| 2160 | "status": "failed", |
| 2161 | "workflow_goal": "Read-only release-readiness audit for Codewhale v0.10.1. Determine blockers.", |
| 2162 | "started_at_ms": 1_000, |
| 2163 | "completed_at_ms": 1_355, |
| 2164 | "error": "no task produced a result: all 2 task(s) failed and 1 fan-out(s) lost every slot (no work survived them); the recorded result reflects no completed work", |
| 2165 | "transcript_line": "finished", |
| 2166 | "events": [ |
| 2167 | {"type": "run_started", "at_ms": 1_000, "workflow_goal": "Read-only release-readiness audit for Codewhale v0.10.1. Determine blockers."}, |
| 2168 | {"type": "task_started", "at_ms": 1_080, "task_id": "a", "workflow_task_label": "engine-readiness"}, |
| 2169 | {"type": "task_started", "at_ms": 1_117, "task_id": "b", "workflow_task_label": "desktop-readiness"}, |
| 2170 | {"type": "task_completed", "at_ms": 1_329, "task_id": "a", "status": "failed", "reason": reason}, |
| 2171 | {"type": "task_completed", "at_ms": 1_338, "task_id": "b", "status": "failed", "reason": reason}, |
| 2172 | {"type": "run_completed", "at_ms": 1_355, "status": "failed"}, |
| 2173 | ], |
| 2174 | }) |
| 2175 | .to_string(); |
| 2176 | let mut finish = generic_tool("workflow", ToolStatus::Failed); |
| 2177 | finish.output = Some(failed); |
| 2178 | let text = lines_text(&finish.lines_with_mode(60, true, RenderMode::Live)); |
| 2179 | assert!(!text.contains("started"), "{text}"); |
| 2180 | assert!(text.contains("0/2 done · 2 failed"), "{text}"); |
| 2181 | assert!(text.contains("355ms"), "{text}"); |
| 2182 | // The whole first sentence, wrapped, never cut. |
| 2183 | let flat = text |
| 2184 | .split_whitespace() |
| 2185 | .filter(|word| { |
| 2186 | !word |
| 2187 | .chars() |
| 2188 | .all(|ch| ('\u{2500}'..='\u{259F}').contains(&ch)) |
| 2189 | }) |
| 2190 | .collect::<Vec<_>>() |
| 2191 | .join(" "); |
| 2192 | assert!( |
| 2193 | flat.contains( |
| 2194 | "Authorization failed: You have run out of credits or need a Grok subscription" |
| 2195 | ), |
| 2196 | "{text}" |
| 2197 | ); |
| 2198 | assert!( |
| 2199 | !flat.contains("grok.com"), |
| 2200 | "only the first sentence: {text}" |
| 2201 | ); |
| 2202 | assert!(!text.contains("..."), "{text}"); |
| 2203 | } |
| 2204 | |
| 2205 | #[test] |
| 2206 | fn degraded_workflow_receipt_is_terminal_warning_not_running_or_success() { |
| 2207 | let output = serde_json::json!({ |
| 2208 | "run_id": "workflow_partial", |
| 2209 | "status": "degraded", |
| 2210 | "workflow_goal": "review the release", |
| 2211 | "started_at_ms": 1_000, |
| 2212 | "completed_at_ms": 2_000, |
| 2213 | "dispatch_failure_count": 1, |
| 2214 | "dispatch_failures": [{ |
| 2215 | "label": "review docs", |
| 2216 | "message": "profile unavailable", |
| 2217 | "at_ms": 1_500, |
| 2218 | }], |
| 2219 | }) |
| 2220 | .to_string(); |
| 2221 | let mut run = generic_tool("workflow", ToolStatus::Success); |
| 2222 | run.output = Some(output); |
| 2223 | |
| 2224 | let lines = run.lines_with_mode(120, false, RenderMode::Live); |
| 2225 | let text = lines_text(&lines); |
| 2226 | assert!( |
| 2227 | text.contains("finished with gaps"), |
| 2228 | "warning receipt missing: {text:?}" |
| 2229 | ); |
| 2230 | assert!( |
| 2231 | !text.to_lowercase().contains(" done"), |
| 2232 | "must not read as success: {text:?}" |
| 2233 | ); |
| 2234 | assert!( |
| 2235 | !text.contains(" running"), |
| 2236 | "must not read as live: {text:?}" |
| 2237 | ); |
| 2238 | |
| 2239 | let warning = lines |
| 2240 | .iter() |
| 2241 | .flat_map(|line| line.spans.iter()) |
| 2242 | .find(|span| span.content.as_ref() == "finished with gaps") |
| 2243 | .expect("terminal warning status span"); |
| 2244 | assert_eq!( |
| 2245 | warning.style.fg, |
| 2246 | Some(super::tool_rail_color(ToolStatus::Warning)), |
| 2247 | "degraded receipt must use the terminal warning accent" |
| 2248 | ); |
| 2249 | assert!( |
| 2250 | lines |
| 2251 | .iter() |
| 2252 | .flat_map(|line| line.spans.iter()) |
| 2253 | .all(|span| !span |
| 2254 | .content |
| 2255 | .chars() |
| 2256 | .any(|ch| ('\u{2800}'..='\u{28ff}').contains(&ch))), |
| 2257 | "terminal receipt must not retain a spinner: {text:?}" |
| 2258 | ); |
| 2259 | } |
| 2260 | |
| 2261 | /// A checklist update names one item. Showing the rest would make every |
| 2262 | /// single-item edit cost the height of the whole list; showing none would make |
| 2263 | /// the row unreadable. An id past the end of the list falls back to a |
| 2264 | /// placeholder instead of panicking. |
| 2265 | #[test] |
| 2266 | fn a_checklist_update_shows_only_the_item_that_changed() { |
| 2267 | let snapshot = super::ChecklistSnapshot { |
| 2268 | items: vec![ |
| 2269 | super::ChecklistItemSnapshot { |
| 2270 | content: "Read the spec".to_string(), |
| 2271 | status: "completed".to_string(), |
| 2272 | }, |
| 2273 | super::ChecklistItemSnapshot { |
| 2274 | content: "Write the test".to_string(), |
| 2275 | status: "in_progress".to_string(), |
| 2276 | }, |
| 2277 | super::ChecklistItemSnapshot { |
| 2278 | content: "Land the PR".to_string(), |
| 2279 | status: "pending".to_string(), |
| 2280 | }, |
| 2281 | ], |
| 2282 | completion_pct: 33, |
| 2283 | completed: 1, |
| 2284 | total: 3, |
| 2285 | }; |
| 2286 | let lines = super::render_checklist_change_card( |
| 2287 | "todo_update", |
| 2288 | ToolStatus::Success, |
| 2289 | &snapshot, |
| 2290 | &super::ChecklistChange { |
| 2291 | id: 2, |
| 2292 | status: "in_progress".to_string(), |
| 2293 | }, |
| 2294 | 80, |
| 2295 | true, |
| 2296 | codewhale_localization::Locale::En, |
| 2297 | ); |
| 2298 | assert!(lines.len() >= 3, "header, change, summary: {}", lines.len()); |
| 2299 | |
| 2300 | let change = line_text(&lines[1]); |
| 2301 | for needle in ["#2", "Write the test", "in progress"] { |
| 2302 | assert!(change.contains(needle), "missing {needle:?}: {change:?}"); |
| 2303 | } |
| 2304 | for other in ["Land the PR", "Read the spec"] { |
| 2305 | assert!( |
| 2306 | !change.contains(other), |
| 2307 | "an update must not redraw the whole list: {change:?}" |
| 2308 | ); |
| 2309 | } |
| 2310 | |
| 2311 | let summary = line_text(lines.last().expect("summary row")); |
| 2312 | assert!(summary.contains("3 items"), "{summary:?}"); |
| 2313 | assert!( |
| 2314 | summary.contains(&crate::tui::key_shortcuts::tool_details_shortcut_action_hint("list")), |
| 2315 | "the full list stays one keypress away: {summary:?}" |
| 2316 | ); |
| 2317 | |
| 2318 | let single = super::ChecklistSnapshot { |
| 2319 | items: vec![super::ChecklistItemSnapshot { |
| 2320 | content: "only item".to_string(), |
| 2321 | status: "pending".to_string(), |
| 2322 | }], |
| 2323 | completion_pct: 0, |
| 2324 | completed: 0, |
| 2325 | total: 1, |
| 2326 | }; |
| 2327 | let lines = super::render_checklist_change_card( |
| 2328 | "todo_update", |
| 2329 | ToolStatus::Success, |
| 2330 | &single, |
| 2331 | &super::ChecklistChange { |
| 2332 | id: 99, |
| 2333 | status: "completed".to_string(), |
| 2334 | }, |
| 2335 | 80, |
| 2336 | true, |
| 2337 | codewhale_localization::Locale::En, |
| 2338 | ); |
| 2339 | let change = line_text(&lines[1]); |
| 2340 | assert!(change.contains("#99") && change.contains("(missing title)")); |
| 2341 | } |
| 2342 | |
| 2343 | /// The plan card is the only place a plan's supporting artifact is visible. |
| 2344 | /// Every populated section has to reach the surface, or the model can record |
| 2345 | /// context the user never sees. |
| 2346 | #[test] |
| 2347 | fn a_plan_card_surfaces_every_populated_artifact_section() { |
| 2348 | let cell = PlanUpdateCell { |
| 2349 | snapshot: PlanSnapshot { |
| 2350 | objective: Some("Make Plan mode reviewable".to_string()), |
| 2351 | context_summary: Some("Grounded in issue #2691".to_string()), |
| 2352 | sources_used: vec!["gh issue view 2691".to_string()], |
| 2353 | critical_files: vec!["crates/engine/src/tools/plan.rs".to_string()], |
| 2354 | constraints: vec!["Keep To-do primary".to_string()], |
| 2355 | recommended_approach: Some( |
| 2356 | "Enrich update_plan without breaking legacy calls".to_string(), |
| 2357 | ), |
| 2358 | verification_plan: Some("Run focused renderer tests".to_string()), |
| 2359 | risks_and_unknowns: Some("Metadata-only plans can disappear".to_string()), |
| 2360 | handoff_packet: Some("Next agent should inspect relay output".to_string()), |
| 2361 | replan_if: vec!["Renderer omits plan card sections".to_string()], |
| 2362 | items: vec![codewhale_engine::tools::plan::PlanItemArg { |
| 2363 | step: "Render artifact sections".to_string(), |
| 2364 | status: StepStatus::InProgress, |
| 2365 | }], |
| 2366 | ..PlanSnapshot::default() |
| 2367 | }, |
| 2368 | status: ToolStatus::Success, |
| 2369 | }; |
| 2370 | |
| 2371 | let visible = lines_text(&cell.lines_with_motion(120, true)); |
| 2372 | |
| 2373 | for needle in [ |
| 2374 | "objective:", |
| 2375 | "Make Plan mode reviewable", |
| 2376 | "source:", |
| 2377 | "gh issue view 2691", |
| 2378 | "file:", |
| 2379 | "verify:", |
| 2380 | "handoff:", |
| 2381 | "replan if:", |
| 2382 | "Renderer omits plan card sections", |
| 2383 | "Render artifact sections", |
| 2384 | ] { |
| 2385 | assert!(visible.contains(needle), "missing {needle:?}: {visible}"); |
| 2386 | } |
| 2387 | } |
| 2388 | |
| 2389 | /// A fan-out tool's per-child prompts get one row each so the user can read |
| 2390 | /// what each child was asked; the inline `args:` summary that would otherwise |
| 2391 | /// say `prompts: <3 items>` is suppressed rather than printed alongside them. |
| 2392 | #[test] |
| 2393 | fn fan_out_prompts_replace_the_inline_argument_summary() { |
| 2394 | let mut cell = generic_tool("read_file", ToolStatus::Running); |
| 2395 | cell.input_summary = Some("prompts: <3 items>".to_string()); |
| 2396 | cell.prompts = Some(vec![ |
| 2397 | "Summarize the README".to_string(), |
| 2398 | "List the public types in client.rs".to_string(), |
| 2399 | "Diff this commit against main".to_string(), |
| 2400 | ]); |
| 2401 | let text = lines_text(&HistoryCell::Tool(ToolCell::Generic(cell)).lines(80)); |
| 2402 | |
| 2403 | assert!(text.contains("[0] Summarize the README")); |
| 2404 | assert!(text.contains("[1] List the public types in client.rs")); |
| 2405 | assert!(text.contains("[2] Diff this commit against main")); |
| 2406 | assert!( |
| 2407 | !text.contains("args: prompts:"), |
| 2408 | "the summary the rows replaced must not also render: {text}" |
| 2409 | ); |
| 2410 | |
| 2411 | let mut plain = generic_tool("file_search", ToolStatus::Running); |
| 2412 | plain.input_summary = Some("query: foo, path: src".to_string()); |
| 2413 | let text = lines_text(&HistoryCell::Tool(ToolCell::Generic(plain)).lines(80)); |
| 2414 | assert!( |
| 2415 | text.contains("query: foo"), |
| 2416 | "a non-fan-out tool keeps its argument summary: {text}" |
| 2417 | ); |
| 2418 | } |
| 2419 | |
| 2420 | /// A grouped activity row is metadata, not a tool card: exactly one line, and |
| 2421 | /// the synthetic tool name that carries it never reaches the screen. |
| 2422 | #[test] |
| 2423 | fn an_activity_group_renders_as_a_single_metadata_line() { |
| 2424 | let mut cell = generic_tool("activity_group", ToolStatus::Success); |
| 2425 | cell.input_summary = Some("Explored 2 files, 1 search".to_string()); |
| 2426 | |
| 2427 | let lines = cell.lines_with_mode(120, true, RenderMode::Live); |
| 2428 | |
| 2429 | assert_eq!(lines.len(), 1); |
| 2430 | assert_eq!(lines_text(&lines), "Explored 2 files, 1 search ›"); |
| 2431 | assert!(!lines_text(&lines).contains("activity_group")); |
| 2432 | cell.input_summary = None; |
| 2433 | let localized = cell.lines_with_mode_and_locale( |
| 2434 | 120, |
| 2435 | true, |
| 2436 | RenderMode::Live, |
| 2437 | codewhale_localization::Locale::ZhHans, |
| 2438 | ); |
| 2439 | assert!(lines_text(&localized).contains("更新了元数据")); |
| 2440 | assert!(!lines_text(&localized).contains("Updated metadata")); |
| 2441 | } |
| 2442 | |
| 2443 | // --------------------------------------------------------------------------- |
| 2444 | // Replay — wire messages project to the right typed cell |
| 2445 | // --------------------------------------------------------------------------- |
| 2446 | |
| 2447 | /// The wire carries a `(reasoning omitted)` placeholder for turns whose |
| 2448 | /// reasoning the provider did not return. Replaying it as a reasoning cell |
| 2449 | /// would put words in the model's mouth. |
| 2450 | #[test] |
| 2451 | fn restored_history_drops_the_wire_reasoning_placeholder() { |
| 2452 | let message = Message { |
| 2453 | role: Role::Assistant, |
| 2454 | content: vec![ |
| 2455 | ContentBlock::Thinking { |
| 2456 | thinking: "(reasoning omitted)".to_string(), |
| 2457 | signature: None, |
| 2458 | state: None, |
| 2459 | redacted_data: None, |
| 2460 | }, |
| 2461 | ContentBlock::Thinking { |
| 2462 | thinking: "Actual model reasoning".to_string(), |
| 2463 | signature: None, |
| 2464 | state: None, |
| 2465 | redacted_data: None, |
| 2466 | }, |
| 2467 | ], |
| 2468 | }; |
| 2469 | |
| 2470 | let cells = super::history_cells_from_message(&message); |
| 2471 | assert_eq!(cells.len(), 1); |
| 2472 | assert!(matches!( |
| 2473 | &cells[0], |
| 2474 | HistoryCell::Thinking { content, .. } if content == "Actual model reasoning" |
| 2475 | )); |
| 2476 | } |
| 2477 | |
| 2478 | #[test] |
| 2479 | fn archived_context_with_malformed_level_is_not_rendered_as_archive() { |
| 2480 | let msg = Message { |
| 2481 | role: Role::Assistant, |
| 2482 | content: vec![ContentBlock::Text { |
| 2483 | text: |
| 2484 | "<archived_context level=\"high\" range=\"msg 0-4\">\nSummary\n</archived_context>" |
| 2485 | .to_string(), |
| 2486 | cache_control: None, |
| 2487 | }], |
| 2488 | }; |
| 2489 | let cells = super::history_cells_from_message(&msg); |
| 2490 | assert!( |
| 2491 | !cells |
| 2492 | .iter() |
| 2493 | .any(|cell| matches!(cell, HistoryCell::ArchivedContext { .. })) |
| 2494 | ); |
| 2495 | } |
| 2496 | |
| 2497 | /// Compaction writes an `<archived_context>` envelope whose attributes are the |
| 2498 | /// only record of what was dropped. Attribute parsing must survive spaces and |
| 2499 | /// punctuation inside the values, or the summary reads with a mangled range. |
| 2500 | #[test] |
| 2501 | fn archived_context_metadata_survives_spaces_inside_attribute_values() { |
| 2502 | let msg = Message { |
| 2503 | role: Role::Assistant, |
| 2504 | content: vec![ContentBlock::Text { |
| 2505 | text: "<archived_context level=\"1\" range=\"msg 0-128\" tokens=\"2499\" \ |
| 2506 | density=\"~2,500 tokens\" model=\"deepseek-v4-flash\" \ |
| 2507 | timestamp=\"2026-04-28T00:00:00Z\">\nSummary body\n</archived_context>" |
| 2508 | .to_string(), |
| 2509 | cache_control: None, |
| 2510 | }], |
| 2511 | }; |
| 2512 | |
| 2513 | let cells = super::history_cells_from_message(&msg); |
| 2514 | assert_eq!(cells.len(), 1); |
| 2515 | let HistoryCell::ArchivedContext { |
| 2516 | level, |
| 2517 | range, |
| 2518 | tokens, |
| 2519 | density, |
| 2520 | model, |
| 2521 | timestamp, |
| 2522 | summary, |
| 2523 | } = &cells[0] |
| 2524 | else { |
| 2525 | panic!("expected archived context cell, got {:?}", cells[0]); |
| 2526 | }; |
| 2527 | |
| 2528 | assert_eq!(*level, 1); |
| 2529 | assert_eq!(range, "msg 0-128"); |
| 2530 | assert_eq!(tokens, "2499"); |
| 2531 | assert_eq!(density, "~2,500 tokens"); |
| 2532 | assert_eq!(model, "deepseek-v4-flash"); |
| 2533 | assert_eq!(timestamp, "2026-04-28T00:00:00Z"); |
| 2534 | assert_eq!(summary, "Summary body"); |
| 2535 | } |
| 2536 | |
| 2537 | /// Two projections that must not become generic assistant prose: a repair |
| 2538 | /// receipt is a system note, and a replayed `update_plan` call rebuilds the |
| 2539 | /// typed plan cell with its snapshot intact. |
| 2540 | #[test] |
| 2541 | fn replay_routes_repair_receipts_and_plan_calls_to_typed_cells() { |
| 2542 | let repair = Message { |
| 2543 | role: Role::Assistant, |
| 2544 | content: vec![ContentBlock::Text { |
| 2545 | text: "[tool_history_repair] Repaired 1 crashed tool call(s); quarantined 0 \ |
| 2546 | duplicate and 0 orphan terminal result(s)." |
| 2547 | .to_string(), |
| 2548 | cache_control: None, |
| 2549 | }], |
| 2550 | }; |
| 2551 | assert!(matches!( |
| 2552 | super::history_cells_from_message(&repair).as_slice(), |
| 2553 | [HistoryCell::System { content }] if content.starts_with("[tool_history_repair]") |
| 2554 | )); |
| 2555 | |
| 2556 | let plan = Message { |
| 2557 | role: Role::Assistant, |
| 2558 | content: vec![ContentBlock::ToolUse { |
| 2559 | execution_id: None, |
| 2560 | id: "plan-1".to_string(), |
| 2561 | name: "update_plan".to_string(), |
| 2562 | input: serde_json::json!({ |
| 2563 | "objective": "Make Plan mode reviewable", |
| 2564 | "sources_used": ["gh issue view 2691"], |
| 2565 | "critical_files": ["crates/engine/src/tools/plan.rs"], |
| 2566 | "plan": [ |
| 2567 | { "step": "render replay card", "status": "completed" } |
| 2568 | ] |
| 2569 | }), |
| 2570 | caller: None, |
| 2571 | thought_signature: None, |
| 2572 | }], |
| 2573 | }; |
| 2574 | let cells = super::history_cells_from_message(&plan); |
| 2575 | assert_eq!(cells.len(), 1); |
| 2576 | let HistoryCell::Tool(ToolCell::PlanUpdate(cell)) = &cells[0] else { |
| 2577 | panic!("expected update_plan replay cell"); |
| 2578 | }; |
| 2579 | assert_eq!(cell.status, ToolStatus::Success); |
| 2580 | assert_eq!( |
| 2581 | cell.snapshot.objective.as_deref(), |
| 2582 | Some("Make Plan mode reviewable") |
| 2583 | ); |
| 2584 | assert_eq!(cell.snapshot.sources_used, vec!["gh issue view 2691"]); |
| 2585 | assert_eq!(cell.snapshot.items[0].status, StepStatus::Completed); |
| 2586 | } |
| 2587 | |
| 2588 | #[test] |
| 2589 | fn replay_update_plan_uses_tool_result_status() { |
| 2590 | let plan_call = |id: &str| Message { |
| 2591 | role: Role::Assistant, |
| 2592 | content: vec![ContentBlock::ToolUse { |
| 2593 | execution_id: None, |
| 2594 | id: id.to_string(), |
| 2595 | name: "update_plan".to_string(), |
| 2596 | input: serde_json::json!({ |
| 2597 | "plan": [{ "step": "update", "status": "in_progress" }] |
| 2598 | }), |
| 2599 | caller: None, |
| 2600 | thought_signature: None, |
| 2601 | }], |
| 2602 | }; |
| 2603 | let tool_result = |id: &str, is_error: Option<bool>| Message { |
| 2604 | role: Role::User, |
| 2605 | content: vec![ContentBlock::ToolResult { |
| 2606 | execution_id: None, |
| 2607 | tool_use_id: id.to_string(), |
| 2608 | content: if is_error == Some(true) { |
| 2609 | "invalid plan".to_string() |
| 2610 | } else { |
| 2611 | "Plan updated".to_string() |
| 2612 | }, |
| 2613 | is_error, |
| 2614 | content_blocks: None, |
| 2615 | }], |
| 2616 | }; |
| 2617 | |
| 2618 | let failed_call = plan_call("plan-fail"); |
| 2619 | let failed_transcript = vec![failed_call.clone(), tool_result("plan-fail", Some(true))]; |
| 2620 | let failed_cells = |
| 2621 | super::history_cells_from_message_with_results(&failed_call, &failed_transcript); |
| 2622 | let [HistoryCell::Tool(ToolCell::PlanUpdate(failed_cell))] = failed_cells.as_slice() else { |
| 2623 | panic!("expected failed update_plan cell, got {failed_cells:?}"); |
| 2624 | }; |
| 2625 | assert_eq!(failed_cell.status, ToolStatus::Failed); |
| 2626 | |
| 2627 | let ok_call = plan_call("plan-ok"); |
| 2628 | let ok_transcript = vec![ok_call.clone(), tool_result("plan-ok", None)]; |
| 2629 | let ok_cells = super::history_cells_from_message_with_results(&ok_call, &ok_transcript); |
| 2630 | let [HistoryCell::Tool(ToolCell::PlanUpdate(ok_cell))] = ok_cells.as_slice() else { |
| 2631 | panic!("expected succeeded update_plan cell, got {ok_cells:?}"); |
| 2632 | }; |
| 2633 | assert_eq!(ok_cell.status, ToolStatus::Success); |
| 2634 | |
| 2635 | let missing_call = plan_call("plan-orphan"); |
| 2636 | let missing_transcript = vec![missing_call.clone()]; |
| 2637 | let missing_cells = |
| 2638 | super::history_cells_from_message_with_results(&missing_call, &missing_transcript); |
| 2639 | let [HistoryCell::Tool(ToolCell::PlanUpdate(missing_cell))] = missing_cells.as_slice() else { |
| 2640 | panic!("expected orphan update_plan cell, got {missing_cells:?}"); |
| 2641 | }; |
| 2642 | assert_eq!(missing_cell.status, ToolStatus::Failed); |
| 2643 | } |
| 2644 | |
| 2645 | #[test] |
| 2646 | fn exploring_cell_compact_status_prefix_uses_locale() { |
| 2647 | let locale = codewhale_localization::Locale::ZhHans; |
| 2648 | let long_label = "crates/tui/src/tui/history/very_long_exploring_entry_label_path.rs"; |
| 2649 | for (status, english) in [ |
| 2650 | (ToolStatus::Running, "live"), |
| 2651 | (ToolStatus::Success, "done"), |
| 2652 | (ToolStatus::Hydrated, "loaded"), |
| 2653 | (ToolStatus::Stopped, "stopped"), |
| 2654 | (ToolStatus::Warning, "issue"), |
| 2655 | (ToolStatus::Failed, "failed"), |
| 2656 | ] { |
| 2657 | let cell = super::ExploringCell { |
| 2658 | entries: vec![super::ExploringEntry { |
| 2659 | label: long_label.to_string(), |
| 2660 | search: false, |
| 2661 | status, |
| 2662 | error: None, |
| 2663 | }], |
| 2664 | }; |
| 2665 | let rendered = cell |
| 2666 | .lines_with_motion_and_locale(48, true, locale) |
| 2667 | .iter() |
| 2668 | .skip(1) |
| 2669 | .map(line_to_plain) |
| 2670 | .collect::<Vec<_>>() |
| 2671 | .join("\n"); |
| 2672 | let localized = super::tool_status_label(status, locale); |
| 2673 | assert!( |
| 2674 | rendered.contains(localized.as_ref()), |
| 2675 | "expected localized status `{localized}` for {status:?}, got: {rendered:?}" |
| 2676 | ); |
| 2677 | assert!( |
| 2678 | !rendered.contains(english), |
| 2679 | "unexpected English status `{english}` for {status:?}, got: {rendered:?}" |
| 2680 | ); |
| 2681 | } |
| 2682 | } |
| 2683 | |
| 2684 | /// The runtime appends a `<turn_meta>` block to the user's message. It is |
| 2685 | /// scaffolding and must be hidden — but only when it is the trailing block the |
| 2686 | /// runtime appended. A user who types the same tag is quoting, not injecting, |
| 2687 | /// and their text must survive verbatim. |
| 2688 | #[test] |
| 2689 | fn user_history_hides_only_the_trailing_turn_metadata_block() { |
| 2690 | let visible = "Explain this literal: <turn_meta>example</turn_meta>"; |
| 2691 | let turn_meta = concat!( |
| 2692 | "<turn_meta>\n", |
| 2693 | "Current local date: 2026-07-22\n", |
| 2694 | "Input provenance: external_user\n", |
| 2695 | "Input authority: external_current_turn\n", |
| 2696 | "</turn_meta>", |
| 2697 | ); |
| 2698 | let msg = Message { |
| 2699 | role: Role::User, |
| 2700 | content: vec![ |
| 2701 | ContentBlock::Text { |
| 2702 | text: visible.to_string(), |
| 2703 | cache_control: None, |
| 2704 | }, |
| 2705 | ContentBlock::Text { |
| 2706 | text: turn_meta.to_string(), |
| 2707 | cache_control: None, |
| 2708 | }, |
| 2709 | ], |
| 2710 | }; |
| 2711 | assert!(matches!( |
| 2712 | super::history_cells_from_message(&msg).as_slice(), |
| 2713 | [HistoryCell::User { content }] if content == visible |
| 2714 | )); |
| 2715 | |
| 2716 | let literal_only = Message { |
| 2717 | role: Role::User, |
| 2718 | content: vec![ContentBlock::Text { |
| 2719 | text: "<turn_meta>user-authored example</turn_meta>".to_string(), |
| 2720 | cache_control: None, |
| 2721 | }], |
| 2722 | }; |
| 2723 | assert!(matches!( |
| 2724 | super::history_cells_from_message(&literal_only).as_slice(), |
| 2725 | [HistoryCell::User { content }] |
| 2726 | if content == "<turn_meta>user-authored example</turn_meta>" |
| 2727 | )); |
| 2728 | } |
| 2729 | |
| 2730 | /// "Copy answer" must select the last completed assistant cell and serialize |
| 2731 | /// exactly its authored text — no reasoning, no tool bodies, no runtime status, |
| 2732 | /// no role marker, and never a half-streamed cell. |
| 2733 | #[test] |
| 2734 | fn the_answer_projection_copies_authored_text_and_nothing_else() { |
| 2735 | use crate::tui::history::text::history_cell_to_clipboard_text; |
| 2736 | |
| 2737 | let cells = [ |
| 2738 | HistoryCell::User { |
| 2739 | content: "please summarize".to_string(), |
| 2740 | }, |
| 2741 | HistoryCell::Thinking { |
| 2742 | content: "private reasoning trace".to_string(), |
| 2743 | streaming: false, |
| 2744 | duration_secs: Some(1.0), |
| 2745 | }, |
| 2746 | HistoryCell::Tool(ToolCell::Generic({ |
| 2747 | let mut cell = generic_tool("read_file", ToolStatus::Success); |
| 2748 | cell.input_summary = Some("src/lib.rs".to_string()); |
| 2749 | cell.output = Some("raw tool result body".to_string()); |
| 2750 | cell |
| 2751 | })), |
| 2752 | HistoryCell::System { |
| 2753 | content: "runtime status note".to_string(), |
| 2754 | }, |
| 2755 | HistoryCell::Assistant { |
| 2756 | content: "still streaming partial".to_string(), |
| 2757 | streaming: true, |
| 2758 | }, |
| 2759 | HistoryCell::Assistant { |
| 2760 | content: "## Final answer\nauthored markdown".to_string(), |
| 2761 | streaming: false, |
| 2762 | }, |
| 2763 | ]; |
| 2764 | |
| 2765 | let answer = cells |
| 2766 | .iter() |
| 2767 | .rev() |
| 2768 | .find(|cell| cell.is_completed_assistant_answer()) |
| 2769 | .expect("the completed assistant cell must qualify"); |
| 2770 | let copied = history_cell_to_clipboard_text(answer, 80); |
| 2771 | |
| 2772 | assert_eq!(copied, "## Final answer\nauthored markdown"); |
| 2773 | for excluded in [ |
| 2774 | "please summarize", |
| 2775 | "private reasoning trace", |
| 2776 | "raw tool result body", |
| 2777 | "runtime status note", |
| 2778 | "still streaming partial", |
| 2779 | ASSISTANT_GLYPH, |
| 2780 | ] { |
| 2781 | assert!( |
| 2782 | !copied.contains(excluded), |
| 2783 | "answer copy leaked {excluded:?}" |
| 2784 | ); |
| 2785 | } |
| 2786 | } |
| 2787 | |
| 2788 | // --------------------------------------------------------------------------- |
| 2789 | // Grouping and small parsers |
| 2790 | // --------------------------------------------------------------------------- |
| 2791 | |
| 2792 | fn tool_cell(name: &str, status: ToolStatus) -> HistoryCell { |
| 2793 | let mut cell = generic_tool(name, status); |
| 2794 | cell.input_summary = Some(format!("args for {name}")); |
| 2795 | cell.output = Some(format!("output for {name}")); |
| 2796 | HistoryCell::Tool(ToolCell::Generic(cell)) |
| 2797 | } |
| 2798 | |
| 2799 | /// Collapsing a run of tool cards is only safe when nothing in the run needs |
| 2800 | /// the user's eyes: a failure, an in-flight call, or a shell command must all |
| 2801 | /// break the group and stay individually visible, and a run shorter than the |
| 2802 | /// threshold is not a run at all. |
| 2803 | /// |
| 2804 | /// Replaces three tests. |
| 2805 | #[test] |
| 2806 | fn only_contiguous_finished_safe_tool_calls_collapse_into_a_run() { |
| 2807 | let history = vec![ |
| 2808 | HistoryCell::User { |
| 2809 | content: "go".to_string(), |
| 2810 | }, |
| 2811 | tool_cell("read_file", ToolStatus::Success), |
| 2812 | tool_cell("list_dir", ToolStatus::Success), |
| 2813 | tool_cell("web_search", ToolStatus::Success), |
| 2814 | HistoryCell::Assistant { |
| 2815 | content: "done".to_string(), |
| 2816 | streaming: false, |
| 2817 | }, |
| 2818 | ]; |
| 2819 | let runs = super::detect_tool_runs(&history, 3); |
| 2820 | assert_eq!(runs.len(), 1); |
| 2821 | assert_eq!((runs[0].start, runs[0].count), (1, 3)); |
| 2822 | assert_eq!( |
| 2823 | runs[0].tool_families, |
| 2824 | vec!["read_file", "list_dir", "web_search"] |
| 2825 | ); |
| 2826 | assert_eq!(runs[0].activity.files, 2); |
| 2827 | assert_eq!(runs[0].activity.searches, 1); |
| 2828 | |
| 2829 | assert!( |
| 2830 | super::detect_tool_runs( |
| 2831 | &[ |
| 2832 | tool_cell("read_file", ToolStatus::Success), |
| 2833 | tool_cell("list_dir", ToolStatus::Success), |
| 2834 | ], |
| 2835 | 3 |
| 2836 | ) |
| 2837 | .is_empty(), |
| 2838 | "a run below the threshold is not collapsed" |
| 2839 | ); |
| 2840 | |
| 2841 | assert!( |
| 2842 | super::detect_tool_runs( |
| 2843 | &[ |
| 2844 | tool_cell("read_file", ToolStatus::Success), |
| 2845 | HistoryCell::Assistant { |
| 2846 | content: "pause".to_string(), |
| 2847 | streaming: false, |
| 2848 | }, |
| 2849 | tool_cell("list_dir", ToolStatus::Success), |
| 2850 | tool_cell("web_search", ToolStatus::Success), |
| 2851 | ], |
| 2852 | 3 |
| 2853 | ) |
| 2854 | .is_empty(), |
| 2855 | "assistant prose breaks the run" |
| 2856 | ); |
| 2857 | |
| 2858 | // Each of failure, in-flight and shell breaks the group; only the clean |
| 2859 | // trailing triple survives. |
| 2860 | let mut mixed = Vec::new(); |
| 2861 | for breaker in [ |
| 2862 | tool_cell("web_search", ToolStatus::Failed), |
| 2863 | tool_cell("web_search", ToolStatus::Running), |
| 2864 | HistoryCell::Tool(ToolCell::Exec({ |
| 2865 | let mut exec = exec_tool("rm -rf target", ToolStatus::Success); |
| 2866 | exec.output = Some("ok".to_string()); |
| 2867 | exec |
| 2868 | })), |
| 2869 | ] { |
| 2870 | mixed.push(tool_cell("read_file", ToolStatus::Success)); |
| 2871 | mixed.push(tool_cell("list_dir", ToolStatus::Success)); |
| 2872 | mixed.push(breaker); |
| 2873 | } |
| 2874 | let tail_start = mixed.len(); |
| 2875 | mixed.push(tool_cell("read_file", ToolStatus::Success)); |
| 2876 | mixed.push(tool_cell("list_dir", ToolStatus::Success)); |
| 2877 | mixed.push(tool_cell("web_search", ToolStatus::Success)); |
| 2878 | |
| 2879 | let runs = super::detect_tool_runs(&mixed, 3); |
| 2880 | assert_eq!(runs.len(), 1, "only the clean tail collapses: {runs:?}"); |
| 2881 | assert_eq!((runs[0].start, runs[0].count), (tail_start, 3)); |
| 2882 | } |
| 2883 | |
| 2884 | /// The one-line summary that replaces a collapsed run is the user's only |
| 2885 | /// record of it, so it must name what actually happened — the right verb, the |
| 2886 | /// right counts, and only the tool families that belong to each clause. |
| 2887 | /// |
| 2888 | /// Replaces four tests. |
| 2889 | #[test] |
| 2890 | fn a_collapsed_run_summary_names_what_actually_happened() { |
| 2891 | let run = |families: &[&str], activity: super::ToolRunActivitySummary| super::ToolRun { |
| 2892 | start: 4, |
| 2893 | count: families.len(), |
| 2894 | tool_families: families.iter().map(|f| f.to_string()).collect(), |
| 2895 | activity, |
| 2896 | }; |
| 2897 | |
| 2898 | assert_eq!( |
| 2899 | super::tool_run_summary( |
| 2900 | &run( |
| 2901 | &["read_file", "list_dir"], |
| 2902 | super::ToolRunActivitySummary { |
| 2903 | files: 4, |
| 2904 | searches: 1, |
| 2905 | ..Default::default() |
| 2906 | } |
| 2907 | ), |
| 2908 | codewhale_localization::Locale::En |
| 2909 | ), |
| 2910 | "Explored 4 files, 1 search: read file, list dir" |
| 2911 | ); |
| 2912 | |
| 2913 | assert_eq!( |
| 2914 | super::tool_run_summary( |
| 2915 | &run( |
| 2916 | &["read_file", "run_tests", "validate_data"], |
| 2917 | super::ToolRunActivitySummary { |
| 2918 | files: 2, |
| 2919 | commands: 2, |
| 2920 | ..Default::default() |
| 2921 | } |
| 2922 | ), |
| 2923 | codewhale_localization::Locale::En |
| 2924 | ), |
| 2925 | "Explored 2 files: read file, ran 2 commands: run tests, validate data", |
| 2926 | "each clause lists only its own families" |
| 2927 | ); |
| 2928 | |
| 2929 | assert_eq!( |
| 2930 | super::tool_run_summary( |
| 2931 | &run( |
| 2932 | &["session_sync"], |
| 2933 | super::ToolRunActivitySummary { |
| 2934 | other: 2, |
| 2935 | ..Default::default() |
| 2936 | } |
| 2937 | ), |
| 2938 | codewhale_localization::Locale::En |
| 2939 | ), |
| 2940 | "Updated metadata", |
| 2941 | "a run of tools with no user-facing family falls back to a plain note" |
| 2942 | ); |
| 2943 | |
| 2944 | // Classification is derived from the real cells, not hand-set counters: |
| 2945 | // command tools count as commands, git history tools count as files. |
| 2946 | let commands = super::detect_tool_runs( |
| 2947 | &[ |
| 2948 | tool_cell("run_tests", ToolStatus::Success), |
| 2949 | tool_cell("run_verifiers", ToolStatus::Success), |
| 2950 | tool_cell("validate_data", ToolStatus::Success), |
| 2951 | ], |
| 2952 | 3, |
| 2953 | ); |
| 2954 | assert_eq!(commands[0].activity.commands, 3); |
| 2955 | assert_eq!( |
| 2956 | super::tool_run_summary(&commands[0], codewhale_localization::Locale::En), |
| 2957 | "Ran 3 commands: run tests, run verifiers, validate data" |
| 2958 | ); |
| 2959 | |
| 2960 | let git = super::detect_tool_runs( |
| 2961 | &[ |
| 2962 | tool_cell("git_log", ToolStatus::Success), |
| 2963 | tool_cell("git_show", ToolStatus::Success), |
| 2964 | tool_cell("git_blame", ToolStatus::Success), |
| 2965 | ], |
| 2966 | 3, |
| 2967 | ); |
| 2968 | assert_eq!(git[0].activity.files, 3); |
| 2969 | assert_eq!( |
| 2970 | super::tool_run_summary(&git[0], codewhale_localization::Locale::En), |
| 2971 | "Explored 3 files: git log, git show, git blame" |
| 2972 | ); |
| 2973 | let sample = run( |
| 2974 | &["read_file", "search"], |
| 2975 | super::ToolRunActivitySummary { |
| 2976 | files: 2, |
| 2977 | searches: 1, |
| 2978 | ..Default::default() |
| 2979 | }, |
| 2980 | ); |
| 2981 | for (locale, expected) in [ |
| 2982 | (codewhale_localization::Locale::ZhHans, "浏览了2个文件"), |
| 2983 | (codewhale_localization::Locale::ZhHant, "瀏覽了2個檔案"), |
| 2984 | (codewhale_localization::Locale::Ja, "2ファイル"), |
| 2985 | (codewhale_localization::Locale::Ru, "Просмотрено: файлы — 2"), |
| 2986 | (codewhale_localization::Locale::Uk, "Переглянуто: файли — 2"), |
| 2987 | ] { |
| 2988 | let text = super::tool_run_summary(&sample, locale); |
| 2989 | assert!(text.contains(expected), "{locale:?}: {text}"); |
| 2990 | assert!(!text.contains("Explored"), "{text}"); |
| 2991 | assert!(text.contains("read file"), "{text}"); |
| 2992 | } |
| 2993 | assert_eq!( |
| 2994 | super::tool_run_summary(&sample, codewhale_localization::Locale::ZhHans), |
| 2995 | "浏览了2个文件、1次搜索:read file、search" |
| 2996 | ); |
| 2997 | } |
| 2998 | |
| 2999 | /// The small pure helpers behind the cards, as one table each. Every row is a |
| 3000 | /// documented input shape or a documented rejection; a helper that guesses on |
| 3001 | /// malformed input is worse than one that declines. |
| 3002 | /// |
| 3003 | /// Replaces ten single-case tests. |
| 3004 | #[test] |
| 3005 | fn the_card_helpers_accept_their_documented_forms_and_decline_the_rest() { |
| 3006 | // Agent ids come out of a JSON body that the renderer must not fully parse. |
| 3007 | for (input, expected) in [ |
| 3008 | ( |
| 3009 | r#"{"agent_id": "agent-abc12", "nickname": "Beluga"}"#, |
| 3010 | Some("agent-abc12"), |
| 3011 | ), |
| 3012 | ( |
| 3013 | "{\n \"agent_id\" : \"agent-xyz\",\n \"model\": \"x\"\n}", |
| 3014 | Some("agent-xyz"), |
| 3015 | ), |
| 3016 | (r#"{"nickname": "Orca", "model": "x"}"#, None), |
| 3017 | (r#"{"agent_id": "", "model": "x"}"#, None), |
| 3018 | ("(not json)", None), |
| 3019 | ("", None), |
| 3020 | ] { |
| 3021 | assert_eq!( |
| 3022 | super::extract_agent_id(input), |
| 3023 | expected, |
| 3024 | "extract_agent_id({input:?})" |
| 3025 | ); |
| 3026 | } |
| 3027 | |
| 3028 | // Checklist update prefixes: both vocabularies, and no guessing. |
| 3029 | for (input, expected) in [ |
| 3030 | ( |
| 3031 | "Updated todo #3 to in_progress\n{ \"items\": [...] }", |
| 3032 | Some(super::ChecklistChange { |
| 3033 | id: 3, |
| 3034 | status: "in_progress".to_string(), |
| 3035 | }), |
| 3036 | ), |
| 3037 | ( |
| 3038 | "Updated checklist #7 to completed\n{ \"items\": [] }", |
| 3039 | Some(super::ChecklistChange { |
| 3040 | id: 7, |
| 3041 | status: "completed".to_string(), |
| 3042 | }), |
| 3043 | ), |
| 3044 | ("{ \"items\": [] }", None), |
| 3045 | ("Wrote 5 todos\n{}", None), |
| 3046 | ("Updated todo #3\n", None), |
| 3047 | ("Updated todo #foo to done\n", None), |
| 3048 | ] { |
| 3049 | assert_eq!( |
| 3050 | super::parse_update_prefix(input), |
| 3051 | expected, |
| 3052 | "parse_update_prefix({input:?})" |
| 3053 | ); |
| 3054 | } |
| 3055 | |
| 3056 | let summary_column = |secs: u64| { |
| 3057 | let started = Instant::now() |
| 3058 | .checked_sub(Duration::from_secs(secs)) |
| 3059 | .expect("monotonic clock covers the test offset"); |
| 3060 | let header = line_to_plain(&render_tool_header_with_summary( |
| 3061 | "read_file", |
| 3062 | Some("READINESS.md"), |
| 3063 | None, |
| 3064 | ToolStatus::Running, |
| 3065 | Some(started), |
| 3066 | true, |
| 3067 | codewhale_localization::Locale::En, |
| 3068 | )); |
| 3069 | let column = header |
| 3070 | .find("READINESS.md") |
| 3071 | .expect("summary is shown on a running header"); |
| 3072 | (column, header) |
| 3073 | }; |
| 3074 | let (still, quick) = summary_column(0); |
| 3075 | assert!(quick.trim_end().ends_with("READINESS.md"), "{quick:?}"); |
| 3076 | for secs in [5u64, 65] { |
| 3077 | let (column, header) = summary_column(secs); |
| 3078 | assert_eq!(column, still, "summary moved at {secs}s: {header:?}"); |
| 3079 | let elapsed = codewhale_command_contract::elapsed::format_elapsed_secs(secs); |
| 3080 | assert!(header.trim_end().ends_with(&elapsed), "{header:?}"); |
| 3081 | } |
| 3082 | |
| 3083 | // A reasoning summary prefers an explicit Summary block, and otherwise is |
| 3084 | // the reasoning itself rather than nothing. |
| 3085 | assert_eq!( |
| 3086 | extract_reasoning_summary("Thinking...\nSummary: First line\nSecond line\n\nTail") |
| 3087 | .expect("summary"), |
| 3088 | "First line\nSecond line" |
| 3089 | ); |
| 3090 | assert_eq!( |
| 3091 | extract_reasoning_summary("Line one\nLine two").expect("summary"), |
| 3092 | "Line one\nLine two" |
| 3093 | ); |
| 3094 | } |
| 3095 | |
| 3096 | /// The card rail is the block's border, so it carries the cell's own state. |
| 3097 | /// Property, not token: every status paints a distinct rail, the rail is never |
| 3098 | /// left unstyled — an unstyled rail is what shipped before, and it made a |
| 3099 | /// failed card look exactly like a finished one from the border in — and it |
| 3100 | /// agrees with the glyph beside it on everything that needs attention while |
| 3101 | /// receding on a settled card, which is the whole point of the split. |
| 3102 | #[test] |
| 3103 | fn card_rail_carries_the_cell_status() { |
| 3104 | let mut rails = Vec::new(); |
| 3105 | for status in [ |
| 3106 | ToolStatus::Running, |
| 3107 | ToolStatus::Success, |
| 3108 | ToolStatus::Hydrated, |
| 3109 | ToolStatus::Warning, |
| 3110 | ToolStatus::Failed, |
| 3111 | ] { |
| 3112 | let cell = exec_tool("cargo test", status); |
| 3113 | let lines = cell.render(80, /*low_motion*/ true, RenderMode::Live); |
| 3114 | let first = &lines[0]; |
| 3115 | |
| 3116 | let rail = first.spans.first().expect("card rail span"); |
| 3117 | assert!( |
| 3118 | matches!(rail.content.as_ref(), "─ " | "╭ "), |
| 3119 | "{status:?} lost its card rail: {:?}", |
| 3120 | rail.content |
| 3121 | ); |
| 3122 | let rail_color = rail.style.fg.unwrap_or_else(|| { |
| 3123 | panic!("{status:?} left the card rail unstyled — the border must follow the state") |
| 3124 | }); |
| 3125 | |
| 3126 | let glyph_color = first.spans[1] |
| 3127 | .style |
| 3128 | .fg |
| 3129 | .expect("header status glyph must be styled"); |
| 3130 | assert_eq!( |
| 3131 | rail_color, glyph_color, |
| 3132 | "{status:?} must read the same on the rail and the glyph" |
| 3133 | ); |
| 3134 | |
| 3135 | rails.push((status, rail_color)); |
| 3136 | } |
| 3137 | |
| 3138 | for (i, (status, color)) in rails.iter().enumerate() { |
| 3139 | for (other_status, other_color) in &rails[i + 1..] { |
| 3140 | assert_ne!( |
| 3141 | color, other_color, |
| 3142 | "{status:?} and {other_status:?} draw the same rail" |
| 3143 | ); |
| 3144 | } |
| 3145 | } |
| 3146 | } |
| 3147 | |
| 3148 | /// Finished work shares quiet ink while its glyph shape preserves identity: |
| 3149 | /// a passed verify and a completed read must still be distinguishable. |
| 3150 | #[test] |
| 3151 | fn a_settled_verify_glyph_does_not_read_as_a_settled_read() { |
| 3152 | let verify = generic_tool("run_tests", ToolStatus::Success); |
| 3153 | let read = generic_tool("read_file", ToolStatus::Success); |
| 3154 | |
| 3155 | let glyph = |cell: &GenericToolCell| { |
| 3156 | cell.lines_with_mode_and_locale( |
| 3157 | 80, |
| 3158 | /*low_motion*/ true, |
| 3159 | RenderMode::Live, |
| 3160 | codewhale_localization::Locale::En, |
| 3161 | )[0] |
| 3162 | // Rail, shared status mark, then the tool-family identity glyph. |
| 3163 | .spans[2] |
| 3164 | .clone() |
| 3165 | }; |
| 3166 | let verify = glyph(&verify); |
| 3167 | let read = glyph(&read); |
| 3168 | assert_ne!(verify.content, read.content, "tool identity stays visible"); |
| 3169 | assert_eq!( |
| 3170 | verify.style.fg, read.style.fg, |
| 3171 | "settled work shares quiet ink" |
| 3172 | ); |
| 3173 | } |
| 3174 | |
| 3175 | /// An exploring cell rolls its parallel entries up into one state, and a |
| 3176 | /// single failure is never averaged away by its successful siblings. This is |
| 3177 | /// the fold that used to exist in three places and could not produce `Failed` |
| 3178 | /// in the one that painted the header. |
| 3179 | #[test] |
| 3180 | fn exploring_cell_status_keeps_the_loudest_terminal_state() { |
| 3181 | use super::{ExploringCell, ExploringEntry}; |
| 3182 | |
| 3183 | let cell = |statuses: &[ToolStatus]| ExploringCell { |
| 3184 | entries: statuses |
| 3185 | .iter() |
| 3186 | .map(|status| ExploringEntry { |
| 3187 | label: "Reading src/foo.rs".to_string(), |
| 3188 | search: false, |
| 3189 | status: *status, |
| 3190 | error: None, |
| 3191 | }) |
| 3192 | .collect(), |
| 3193 | }; |
| 3194 | |
| 3195 | for (statuses, expected) in [ |
| 3196 | ( |
| 3197 | vec![ToolStatus::Success, ToolStatus::Success], |
| 3198 | ToolStatus::Success, |
| 3199 | ), |
| 3200 | ( |
| 3201 | vec![ToolStatus::Success, ToolStatus::Running], |
| 3202 | ToolStatus::Running, |
| 3203 | ), |
| 3204 | ( |
| 3205 | vec![ToolStatus::Failed, ToolStatus::Running], |
| 3206 | ToolStatus::Running, |
| 3207 | ), |
| 3208 | ( |
| 3209 | vec![ToolStatus::Success, ToolStatus::Failed], |
| 3210 | ToolStatus::Failed, |
| 3211 | ), |
| 3212 | ( |
| 3213 | vec![ToolStatus::Warning, ToolStatus::Failed], |
| 3214 | ToolStatus::Failed, |
| 3215 | ), |
| 3216 | ( |
| 3217 | vec![ToolStatus::Success, ToolStatus::Warning], |
| 3218 | ToolStatus::Warning, |
| 3219 | ), |
| 3220 | ( |
| 3221 | vec![ToolStatus::Success, ToolStatus::Hydrated], |
| 3222 | ToolStatus::Hydrated, |
| 3223 | ), |
| 3224 | ] { |
| 3225 | assert_eq!( |
| 3226 | cell(&statuses).status(), |
| 3227 | expected, |
| 3228 | "{statuses:?} should roll up to {expected:?}" |
| 3229 | ); |
| 3230 | } |
| 3231 | |
| 3232 | // And the cell reports that state through the ToolCell it lives in. |
| 3233 | assert_eq!( |
| 3234 | ToolCell::Exploring(cell(&[ToolStatus::Success, ToolStatus::Failed])).status(), |
| 3235 | Some(ToolStatus::Failed) |
| 3236 | ); |
| 3237 | } |
| 3238 | |
| 3239 | // --------------------------------------------------------------------------- |
| 3240 | // Tool-card ink: rail vs glyph |
| 3241 | // --------------------------------------------------------------------------- |
| 3242 | |
| 3243 | /// The rail is the card border and follows OMP's rule: every status draws a |
| 3244 | /// distinct border. Two statuses sharing a rail is the failure this mapping |
| 3245 | /// exists to prevent — it is how `Hydrated` once sat on the running accent and |
| 3246 | /// read as live work. |
| 3247 | #[test] |
| 3248 | fn tool_rail_is_distinct_for_every_status() { |
| 3249 | let statuses = [ |
| 3250 | ToolStatus::Running, |
| 3251 | ToolStatus::Success, |
| 3252 | ToolStatus::Hydrated, |
| 3253 | ToolStatus::Warning, |
| 3254 | ToolStatus::Failed, |
| 3255 | ]; |
| 3256 | for (i, status) in statuses.iter().enumerate() { |
| 3257 | for other in &statuses[i + 1..] { |
| 3258 | assert_ne!( |
| 3259 | super::tool_rail_color(*status), |
| 3260 | super::tool_rail_color(*other), |
| 3261 | "{status:?} and {other:?} draw the same rail" |
| 3262 | ); |
| 3263 | } |
| 3264 | } |
| 3265 | } |
| 3266 | |
| 3267 | /// Finished rows recede while failures and warnings retain attention ink. |
| 3268 | #[test] |
| 3269 | fn calm1_settled_headers_are_muted_without_hiding_failures() { |
| 3270 | use crate::tui::widgets::tool_card::ToolFamily; |
| 3271 | use ratatui::style::Modifier; |
| 3272 | for family in [ToolFamily::Read, ToolFamily::Verify] { |
| 3273 | for status in [ |
| 3274 | ToolStatus::Running, |
| 3275 | ToolStatus::Success, |
| 3276 | ToolStatus::Hydrated, |
| 3277 | ToolStatus::Warning, |
| 3278 | ToolStatus::Failed, |
| 3279 | ] { |
| 3280 | assert_eq!( |
| 3281 | super::tool_rail_color(status), |
| 3282 | super::tool_glyph_color(status, family) |
| 3283 | ); |
| 3284 | } |
| 3285 | assert_ne!( |
| 3286 | super::tool_glyph_color(ToolStatus::Success, family), |
| 3287 | super::tool_glyph_color(ToolStatus::Failed, family) |
| 3288 | ); |
| 3289 | } |
| 3290 | assert!( |
| 3291 | !super::tool_title_style(ToolStatus::Success) |
| 3292 | .add_modifier |
| 3293 | .contains(Modifier::BOLD) |
| 3294 | ); |
| 3295 | assert!( |
| 3296 | super::tool_title_style(ToolStatus::Failed) |
| 3297 | .add_modifier |
| 3298 | .contains(Modifier::BOLD) |
| 3299 | ); |
| 3300 | } |
| 3301 | |
| 3302 | /// Issue #5871: `todo_write` replaces the whole list on every call, so a long |
| 3303 | /// session stacked full checklist cards that could only be cleared by `/clear` |
| 3304 | /// or `/new` — and both of those also drop `api_messages` and the compaction |
| 3305 | /// summary. Only the newest snapshot keeps its card; the ones it replaced keep |
| 3306 | /// their header (the progress reading) and a details affordance. |
| 3307 | #[test] |
| 3308 | fn superseded_todo_snapshots_collapse_to_their_header() { |
| 3309 | let snapshot = |done: usize| { |
| 3310 | let items: Vec<String> = (0..3) |
| 3311 | .map(|i| { |
| 3312 | let status = if i < done { "completed" } else { "pending" }; |
| 3313 | format!(r#"{{"content":"step {i}","status":"{status}"}}"#) |
| 3314 | }) |
| 3315 | .collect(); |
| 3316 | let mut cell = generic_tool("todo_write", ToolStatus::Success); |
| 3317 | cell.output = Some(format!(r#"{{"items":[{}]}}"#, items.join(","))); |
| 3318 | HistoryCell::Tool(ToolCell::Generic(cell)) |
| 3319 | }; |
| 3320 | |
| 3321 | let mut options = TranscriptRenderOptions { |
| 3322 | show_tool_details: true, |
| 3323 | ..Default::default() |
| 3324 | }; |
| 3325 | let older = snapshot(1); |
| 3326 | |
| 3327 | let expanded = older.lines_with_options(120, options); |
| 3328 | assert!( |
| 3329 | expanded.len() > 2, |
| 3330 | "the newest snapshot renders its full card: {expanded:?}" |
| 3331 | ); |
| 3332 | |
| 3333 | options.superseded_work_receipt = true; |
| 3334 | let collapsed = older.lines_with_options(120, options); |
| 3335 | assert_eq!( |
| 3336 | collapsed.len(), |
| 3337 | 2, |
| 3338 | "a replaced snapshot keeps its header plus the details affordance" |
| 3339 | ); |
| 3340 | let header: String = collapsed[0] |
| 3341 | .spans |
| 3342 | .iter() |
| 3343 | .map(|span| span.content.as_ref()) |
| 3344 | .collect(); |
| 3345 | assert!( |
| 3346 | header.contains("1/3"), |
| 3347 | "the collapsed row keeps the progress reading: {header}" |
| 3348 | ); |
| 3349 | } |
| 3350 | |
| 3351 | /// One click is one request to open one file. |
| 3352 | /// |
| 3353 | /// The old `try_open_file_at_line` looped over every line of the cell and |
| 3354 | /// spawned a detached editor per match, so a stack trace or a grep result could |
| 3355 | /// launch several at once, all fighting the still-raw-mode TUI for the tty |
| 3356 | /// (#6235). The parser now returns the first resolvable reference and nothing |
| 3357 | /// else; spawning belongs to `external_editor`. |
| 3358 | #[test] |
| 3359 | fn first_file_line_reference_returns_one_match_and_resolves_it() { |
| 3360 | let dir = tempfile::tempdir().unwrap(); |
| 3361 | let workspace = dir.path(); |
| 3362 | std::fs::create_dir_all(workspace.join("src")).unwrap(); |
| 3363 | std::fs::write(workspace.join("src/first.rs"), "fn a() {}\n").unwrap(); |
| 3364 | std::fs::write(workspace.join("src/second.rs"), "fn b() {}\n").unwrap(); |
| 3365 | |
| 3366 | let text = "note: two frames below\n src/first.rs:12\n src/second.rs:34\n"; |
| 3367 | let (path, line) = super::first_file_line_reference(text, workspace) |
| 3368 | .expect("the first resolvable reference is returned"); |
| 3369 | assert_eq!(path, workspace.join("src/first.rs")); |
| 3370 | assert_eq!(line, 12); |
| 3371 | } |
| 3372 | |
| 3373 | /// The forms tools and models print: rustc's `-->` locator with a column, |
| 3374 | /// a backticked reference, and one inside a sentence with punctuation. |
| 3375 | #[test] |
| 3376 | fn file_line_reference_reads_common_forms_on_one_line() { |
| 3377 | let dir = tempfile::tempdir().unwrap(); |
| 3378 | let workspace = dir.path(); |
| 3379 | std::fs::create_dir_all(workspace.join("src")).unwrap(); |
| 3380 | std::fs::write(workspace.join("src/a.rs"), "fn a() {}\n").unwrap(); |
| 3381 | let expected = Some((workspace.join("src/a.rs"), 12)); |
| 3382 | |
| 3383 | for line in [ |
| 3384 | " --> src/a.rs:12:5", |
| 3385 | "see `src/a.rs:12` for the loop", |
| 3386 | "the bug is in (src/a.rs:12), again.", |
| 3387 | "src/a.rs:12: error: mismatched types", |
| 3388 | "./src/a.rs:12", |
| 3389 | ] { |
| 3390 | assert_eq!( |
| 3391 | super::file_line_reference(line, workspace), |
| 3392 | expected, |
| 3393 | "{line:?}" |
| 3394 | ); |
| 3395 | } |
| 3396 | assert_eq!(super::file_line_reference("src/a.rs:0", workspace), None); |
| 3397 | } |
| 3398 | |
| 3399 | /// Model output is not trusted to name a file: an absolute path outside the |
| 3400 | /// workspace and a `../` escape both used to open in `$EDITOR`. |
| 3401 | #[test] |
| 3402 | fn file_line_reference_refuses_paths_outside_the_workspace() { |
| 3403 | let root = tempfile::tempdir().unwrap(); |
| 3404 | let workspace = root.path().join("ws"); |
| 3405 | std::fs::create_dir_all(workspace.join("src")).unwrap(); |
| 3406 | std::fs::write(workspace.join("src/in.rs"), "fn a() {}\n").unwrap(); |
| 3407 | let outside = root.path().join("outside.rs"); |
| 3408 | std::fs::write(&outside, "secret\n").unwrap(); |
| 3409 | |
| 3410 | let absolute_outside = format!("{}:3", outside.display()); |
| 3411 | assert_eq!( |
| 3412 | super::file_line_reference(&absolute_outside, &workspace), |
| 3413 | None |
| 3414 | ); |
| 3415 | assert_eq!( |
| 3416 | super::file_line_reference("../outside.rs:3", &workspace), |
| 3417 | None |
| 3418 | ); |
| 3419 | assert_eq!( |
| 3420 | super::first_file_line_reference( |
| 3421 | &format!("{absolute_outside}\n../outside.rs:1\n"), |
| 3422 | &workspace |
| 3423 | ), |
| 3424 | None |
| 3425 | ); |
| 3426 | |
| 3427 | let absolute_inside = format!("{}:4", workspace.join("src/in.rs").display()); |
| 3428 | assert_eq!( |
| 3429 | super::file_line_reference(&absolute_inside, &workspace), |
| 3430 | Some((workspace.join("src/in.rs"), 4)), |
| 3431 | "an absolute path inside the workspace still opens" |
| 3432 | ); |
| 3433 | } |
| 3434 | |
| 3435 | /// A link inside the workspace passed the text-only check and `is_file()` |
| 3436 | /// followed it, so `vendor -> <outside>` or `notes.md -> <outside file>` in |
| 3437 | /// model output offered "Open in editor" on a file outside the workspace. |
| 3438 | #[cfg(unix)] |
| 3439 | #[test] |
| 3440 | fn file_line_reference_refuses_links_out_of_the_workspace() { |
| 3441 | let root = tempfile::tempdir().unwrap(); |
| 3442 | let workspace = root.path().join("ws"); |
| 3443 | let outside = root.path().join("outside"); |
| 3444 | std::fs::create_dir_all(workspace.join("src")).unwrap(); |
| 3445 | std::fs::create_dir_all(&outside).unwrap(); |
| 3446 | std::fs::write(outside.join("secret.rs"), "secret\n").unwrap(); |
| 3447 | std::fs::write(workspace.join("src/in.rs"), "fn a() {}\n").unwrap(); |
| 3448 | std::os::unix::fs::symlink(&outside, workspace.join("vendor")).unwrap(); |
| 3449 | std::os::unix::fs::symlink(outside.join("secret.rs"), workspace.join("notes.rs")).unwrap(); |
| 3450 | // A link that stays inside is still a link: refused, not followed. |
| 3451 | std::os::unix::fs::symlink(workspace.join("src"), workspace.join("alias")).unwrap(); |
| 3452 | |
| 3453 | for line in ["vendor/secret.rs:1", "notes.rs:1", "alias/in.rs:1"] { |
| 3454 | assert_eq!( |
| 3455 | super::file_line_reference(line, &workspace), |
| 3456 | None, |
| 3457 | "{line:?}" |
| 3458 | ); |
| 3459 | } |
| 3460 | assert_eq!( |
| 3461 | super::workspace_file(&workspace, "src"), |
| 3462 | None, |
| 3463 | "a directory" |
| 3464 | ); |
| 3465 | assert_eq!( |
| 3466 | super::file_line_reference("src/in.rs:2", &workspace), |
| 3467 | Some((workspace.join("src/in.rs"), 2)) |
| 3468 | ); |
| 3469 | } |
| 3470 | |
| 3471 | /// The two escapes the review named: a directory link to `/` and links into |
| 3472 | /// an `.ssh` directory. The `.ssh` here is one the test creates outside the |
| 3473 | /// workspace with real files in it, so a follow-the-link check would find |
| 3474 | /// them and resolve; the test does not depend on the host's own keys. |
| 3475 | #[cfg(unix)] |
| 3476 | #[test] |
| 3477 | fn file_line_reference_refuses_links_to_root_and_ssh() { |
| 3478 | let dir = tempfile::tempdir().unwrap(); |
| 3479 | let workspace = &dir.path().join("ws"); |
| 3480 | std::fs::create_dir_all(workspace).unwrap(); |
| 3481 | std::os::unix::fs::symlink("/", workspace.join("rootfs")).unwrap(); |
| 3482 | let ssh = dir.path().join("home/.ssh"); |
| 3483 | std::fs::create_dir_all(&ssh).unwrap(); |
| 3484 | std::fs::write(ssh.join("id_ed25519"), "PRIVATE KEY\n").unwrap(); |
| 3485 | std::fs::write(ssh.join("config"), "Host *\n").unwrap(); |
| 3486 | std::os::unix::fs::symlink(ssh.join("id_ed25519"), workspace.join("key.rs")).unwrap(); |
| 3487 | std::os::unix::fs::symlink(&ssh, workspace.join("ssh")).unwrap(); |
| 3488 | assert!(workspace.join("key.rs").is_file(), "the file link resolves"); |
| 3489 | assert!( |
| 3490 | workspace.join("ssh/config").is_file(), |
| 3491 | "the dir link resolves" |
| 3492 | ); |
| 3493 | |
| 3494 | for line in [ |
| 3495 | "rootfs/etc/hosts:1", |
| 3496 | "./rootfs/etc/hosts:1", |
| 3497 | "key.rs:1", |
| 3498 | "ssh/config:1", |
| 3499 | "ssh/id_ed25519:1", |
| 3500 | ] { |
| 3501 | assert_eq!( |
| 3502 | super::file_line_reference(line, workspace), |
| 3503 | None, |
| 3504 | "{line:?}" |
| 3505 | ); |
| 3506 | } |
| 3507 | let absolute = workspace.join("rootfs/etc/hosts"); |
| 3508 | assert_eq!( |
| 3509 | super::workspace_file(workspace, absolute.to_str().unwrap()), |
| 3510 | None, |
| 3511 | "an absolute path through the link" |
| 3512 | ); |
| 3513 | } |
| 3514 | |
| 3515 | #[test] |
| 3516 | fn first_file_line_reference_skips_unresolvable_and_malformed_rows() { |
| 3517 | let dir = tempfile::tempdir().unwrap(); |
| 3518 | let workspace = dir.path(); |
| 3519 | std::fs::create_dir_all(workspace.join("src")).unwrap(); |
| 3520 | std::fs::write(workspace.join("src/real.rs"), "fn a() {}\n").unwrap(); |
| 3521 | |
| 3522 | // A path that does not exist, a bare word, a non-numeric suffix and an |
| 3523 | // empty suffix all fall through to the one row that resolves. |
| 3524 | let text = concat!( |
| 3525 | " src/missing.rs:9\n", |
| 3526 | " notafile:12\n", |
| 3527 | " src/real.rs:abc\n", |
| 3528 | " src/real.rs:\n", |
| 3529 | " src/real.rs:7\n", |
| 3530 | ); |
| 3531 | let (path, line) = |
| 3532 | super::first_file_line_reference(text, workspace).expect("the only resolvable row wins"); |
| 3533 | assert_eq!(path, workspace.join("src/real.rs")); |
| 3534 | assert_eq!(line, 7); |
| 3535 | |
| 3536 | assert!( |
| 3537 | super::first_file_line_reference("no references here\n", workspace).is_none(), |
| 3538 | "a cell with nothing to open must report nothing, not a default" |
| 3539 | ); |
| 3540 | } |
| 3541 | |
| 3542 | #[test] |
| 3543 | fn workspace_target_accepts_files_and_directories_and_rejects_escapes() { |
| 3544 | let dir = tempfile::tempdir().unwrap(); |
| 3545 | let workspace = dir.path().join("ws"); |
| 3546 | std::fs::create_dir_all(workspace.join("dynamis/build/support-final")).unwrap(); |
| 3547 | std::fs::write( |
| 3548 | workspace.join("dynamis/build/support-final/app.rs"), |
| 3549 | "fn main() {}\n", |
| 3550 | ) |
| 3551 | .unwrap(); |
| 3552 | |
| 3553 | let dir_target = super::workspace_target(&workspace, "dynamis/build/support-final/") |
| 3554 | .expect("trailing slash directory resolves"); |
| 3555 | assert!(dir_target.is_dir); |
| 3556 | assert_eq!( |
| 3557 | dir_target.path, |
| 3558 | workspace.join("dynamis/build/support-final") |
| 3559 | ); |
| 3560 | |
| 3561 | let bare_dir = super::workspace_target(&workspace, "./dynamis/build/support-final") |
| 3562 | .expect("dot-slash directory resolves"); |
| 3563 | assert!(bare_dir.is_dir); |
| 3564 | assert_eq!(bare_dir.path, workspace.join("dynamis/build/support-final")); |
| 3565 | |
| 3566 | let file_target = super::workspace_target(&workspace, "dynamis/build/support-final/app.rs") |
| 3567 | .expect("regular file resolves"); |
| 3568 | assert!(!file_target.is_dir); |
| 3569 | assert_eq!( |
| 3570 | file_target.path, |
| 3571 | workspace.join("dynamis/build/support-final/app.rs") |
| 3572 | ); |
| 3573 | |
| 3574 | assert_eq!( |
| 3575 | super::workspace_target(&workspace, "dynamis/build/support-final/app.rs/"), |
| 3576 | None |
| 3577 | ); |
| 3578 | assert_eq!( |
| 3579 | super::workspace_file(&workspace, "dynamis/build/support-final/"), |
| 3580 | None |
| 3581 | ); |
| 3582 | assert_eq!( |
| 3583 | super::workspace_file(&workspace, "dynamis/build/support-final/app.rs"), |
| 3584 | Some(workspace.join("dynamis/build/support-final/app.rs")) |
| 3585 | ); |
| 3586 | assert_eq!(super::workspace_target(&workspace, "../ws"), None); |
| 3587 | assert_eq!(super::workspace_target(&workspace, "/etc/hosts"), None); |
| 3588 | } |
| 3589 | |
| 3590 | #[cfg(unix)] |
| 3591 | #[test] |
| 3592 | fn workspace_target_refuses_symlinks_for_both_files_and_directories() { |
| 3593 | let dir = tempfile::tempdir().unwrap(); |
| 3594 | let workspace = dir.path().join("ws"); |
| 3595 | let outside = dir.path().join("outside"); |
| 3596 | std::fs::create_dir_all(workspace.join("real")).unwrap(); |
| 3597 | std::fs::create_dir_all(&outside).unwrap(); |
| 3598 | std::fs::write(outside.join("secret.txt"), "secret\n").unwrap(); |
| 3599 | std::os::unix::fs::symlink(&outside, workspace.join("escape-dir")).unwrap(); |
| 3600 | std::os::unix::fs::symlink(workspace.join("real"), workspace.join("alias-dir")).unwrap(); |
| 3601 | |
| 3602 | assert_eq!(super::workspace_target(&workspace, "escape-dir/"), None); |
| 3603 | assert_eq!(super::workspace_target(&workspace, "escape-dir"), None); |
| 3604 | assert_eq!( |
| 3605 | super::workspace_target(&workspace, "escape-dir/secret.txt"), |
| 3606 | None |
| 3607 | ); |
| 3608 | assert_eq!(super::workspace_target(&workspace, "alias-dir/"), None); |
| 3609 | } |
| 3610 | |
| 3611 | #[test] |
| 3612 | fn parse_workspace_link_candidate_supports_lines_fragments_dirs_and_abs_paths() { |
| 3613 | let dir = tempfile::tempdir().unwrap(); |
| 3614 | let workspace = dir.path().join("ws"); |
| 3615 | std::fs::create_dir_all(workspace.join("src/nested")).unwrap(); |
| 3616 | std::fs::write(workspace.join("src/main.rs"), "fn main() {}\n").unwrap(); |
| 3617 | |
| 3618 | let (target, line) = |
| 3619 | super::parse_workspace_link_candidate("src/main.rs", &workspace).expect("plain file"); |
| 3620 | assert!(!target.is_dir); |
| 3621 | assert_eq!(line, None); |
| 3622 | |
| 3623 | let (target, line) = |
| 3624 | super::parse_workspace_link_candidate("./src/main.rs:42", &workspace).expect("file:line"); |
| 3625 | assert_eq!(target.path, workspace.join("src/main.rs")); |
| 3626 | assert_eq!(line, Some(42)); |
| 3627 | |
| 3628 | let (target, line) = super::parse_workspace_link_candidate("src/main.rs:42:7", &workspace) |
| 3629 | .expect("file:line:col"); |
| 3630 | assert_eq!(target.path, workspace.join("src/main.rs")); |
| 3631 | assert_eq!(line, Some(42)); |
| 3632 | |
| 3633 | let (target, line) = |
| 3634 | super::parse_workspace_link_candidate("src/main.rs#L10", &workspace).expect("file#L10"); |
| 3635 | assert_eq!(target.path, workspace.join("src/main.rs")); |
| 3636 | assert_eq!(line, Some(10)); |
| 3637 | |
| 3638 | let (target, line) = super::parse_workspace_link_candidate("src/main.rs#L10-L20", &workspace) |
| 3639 | .expect("file#L10-L20"); |
| 3640 | assert_eq!(target.path, workspace.join("src/main.rs")); |
| 3641 | assert_eq!(line, Some(10)); |
| 3642 | |
| 3643 | let (target, line) = |
| 3644 | super::parse_workspace_link_candidate("src/nested/", &workspace).expect("dir/"); |
| 3645 | assert!(target.is_dir); |
| 3646 | assert_eq!(target.path, workspace.join("src/nested")); |
| 3647 | assert_eq!(line, None); |
| 3648 | |
| 3649 | assert_eq!( |
| 3650 | super::parse_workspace_link_candidate("src/nested#L5", &workspace), |
| 3651 | None |
| 3652 | ); |
| 3653 | |
| 3654 | let abs = workspace.join("src/main.rs"); |
| 3655 | let abs_with_line = format!("{}:9", abs.display()); |
| 3656 | let (target, line) = |
| 3657 | super::parse_workspace_link_candidate(&abs_with_line, &workspace).expect("abs:line"); |
| 3658 | assert_eq!(target.path, abs); |
| 3659 | assert_eq!(line, Some(9)); |
| 3660 | } |
| 3661 | |
| 3662 | #[test] |
| 3663 | fn file_uri_round_trips_spaces_and_special_chars() { |
| 3664 | let dir = tempfile::tempdir().unwrap(); |
| 3665 | let workspace = dir.path().join("ws"); |
| 3666 | std::fs::create_dir_all(workspace.join("docs/my folder")).unwrap(); |
| 3667 | let file = workspace.join("docs/my folder/spec #1.md"); |
| 3668 | std::fs::write(&file, "# hi\n").unwrap(); |
| 3669 | |
| 3670 | let uri = super::file_uri_for_path(&file).expect("file uri"); |
| 3671 | assert!(uri.starts_with("file:///"), "{uri}"); |
| 3672 | assert!(uri.contains("my%20folder/spec%20%231.md"), "{uri}"); |
| 3673 | |
| 3674 | let resolved = |
| 3675 | super::workspace_target_from_file_uri(&workspace, &uri).expect("round-trip target"); |
| 3676 | assert!(!resolved.is_dir); |
| 3677 | assert_eq!(resolved.path, file); |
| 3678 | } |
| 3679 | |
| 3680 | /// #6601: the project-trust warning is a runtime-owned internal message; the |
| 3681 | /// model reads it, the transcript never shows it as the user's words. |
| 3682 | #[test] |
| 3683 | fn workspace_trust_warning_renders_no_transcript_cell() { |
| 3684 | for warning in [Some("untrusted project skills were skipped"), None] { |
| 3685 | let message = codewhale_engine::runtime_handoff::workspace_trust_runtime_message(warning); |
| 3686 | assert!(codewhale_engine::runtime_handoff::is_internal_runtime_handoff(&message)); |
| 3687 | assert!( |
| 3688 | super::history_cells_from_message(&message).is_empty(), |
| 3689 | "{warning:?}" |
| 3690 | ); |
| 3691 | } |
| 3692 | } |
| 3693 | |
| 3694 | #[test] |
| 3695 | fn calm1_failed_tool_preview_matrix_preserves_full_details_and_mcp_identity() { |
| 3696 | for width in [40, 60, 80, 140] { |
| 3697 | for status in [ToolStatus::Running, ToolStatus::Success, ToolStatus::Failed] { |
| 3698 | let output = (0..30) |
| 3699 | .map(|i| format!("row {i:02}")) |
| 3700 | .collect::<Vec<_>>() |
| 3701 | .join("\n"); |
| 3702 | let mcp = HistoryCell::Tool(ToolCell::Mcp(super::McpToolCell { |
| 3703 | tool: "linear_get_issue".into(), |
| 3704 | status, |
| 3705 | content: Some(output.clone()), |
| 3706 | is_image: false, |
| 3707 | })); |
| 3708 | let mut generic = generic_tool("read_file", status); |
| 3709 | generic.output = Some(output); |
| 3710 | for (cell, is_mcp) in [ |
| 3711 | (mcp, true), |
| 3712 | (HistoryCell::Tool(ToolCell::Generic(generic)), false), |
| 3713 | ] { |
| 3714 | let options = TranscriptRenderOptions { |
| 3715 | calm_mode: true, |
| 3716 | show_tool_details: false, |
| 3717 | low_motion: true, |
| 3718 | ..Default::default() |
| 3719 | }; |
| 3720 | let live = cell.lines_with_options(width, options); |
| 3721 | let text = lines_text(&live); |
| 3722 | let full = lines_text(&cell.transcript_lines(width)); |
| 3723 | assert!( |
| 3724 | full.contains("row 15"), |
| 3725 | "full details must preserve omitted content" |
| 3726 | ); |
| 3727 | if is_mcp { |
| 3728 | assert_eq!(text.matches("linear_get_issue").count(), 1, "{text}"); |
| 3729 | } |
| 3730 | if status == ToolStatus::Failed { |
| 3731 | assert!(text.contains("row 00") && text.contains("row 29"), "{text}"); |
| 3732 | assert!(!text.contains("row 15"), "{text}"); |
| 3733 | assert!(text.contains(" lines) · "), "{text}"); |
| 3734 | assert_eq!( |
| 3735 | (0..30) |
| 3736 | .filter(|i| text.contains(&format!("row {i:02}"))) |
| 3737 | .count(), |
| 3738 | 6 |
| 3739 | ); |
| 3740 | if is_mcp { |
| 3741 | assert!(live.len() <= 8, "{text}"); |
| 3742 | } |
| 3743 | } |
| 3744 | } |
| 3745 | } |
| 3746 | } |
| 3747 | } |
| 3748 | |
| 3749 | #[test] |
| 3750 | fn calm1_settled_reasoning_is_one_localized_row_and_stays_expandable() { |
| 3751 | for (locale, expected) in [ |
| 3752 | (codewhale_localization::Locale::En, "Thought for 12s"), |
| 3753 | (codewhale_localization::Locale::ZhHans, "思考用时 12s"), |
| 3754 | ] { |
| 3755 | let cell = HistoryCell::Thinking { |
| 3756 | content: "private reasoning body\nlast step".into(), |
| 3757 | streaming: false, |
| 3758 | duration_secs: Some(12.0), |
| 3759 | }; |
| 3760 | let options = TranscriptRenderOptions { |
| 3761 | calm_mode: true, |
| 3762 | locale, |
| 3763 | ..Default::default() |
| 3764 | }; |
| 3765 | let (lines, action) = cell.lines_with_options_folded(80, options, None); |
| 3766 | assert_eq!(lines.len(), 1); |
| 3767 | assert!( |
| 3768 | lines_text(&lines).contains(expected), |
| 3769 | "{}", |
| 3770 | lines_text(&lines) |
| 3771 | ); |
| 3772 | assert_eq!(action, Some(super::CellFoldAction::Expand)); |
| 3773 | let expanded = cell |
| 3774 | .lines_with_options_folded(80, options, Some(TranscriptFold::Expanded)) |
| 3775 | .0; |
| 3776 | assert!(lines_text(&expanded).contains("private reasoning body")); |
| 3777 | } |
| 3778 | } |
| 3779 | |
| 3780 | #[test] |
| 3781 | fn calm1_calm_and_hidden_details_share_one_card_budget() { |
| 3782 | let mut exec = exec_tool("command", ToolStatus::Success); |
| 3783 | exec.output = Some(numbered_output(40)); |
| 3784 | let cell = HistoryCell::Tool(ToolCell::Exec(exec)); |
| 3785 | let mut rendered = Vec::new(); |
| 3786 | for (calm_mode, show_tool_details) in [(true, false), (true, true), (false, false)] { |
| 3787 | let options = TranscriptRenderOptions { |
| 3788 | calm_mode, |
| 3789 | show_tool_details, |
| 3790 | low_motion: true, |
| 3791 | ..Default::default() |
| 3792 | }; |
| 3793 | let lines = cell.lines_with_options(80, options); |
| 3794 | assert!(lines.len() <= super::constants::TOOL_SUMMARY_CARD_LINES); |
| 3795 | rendered.push(lines_text(&lines)); |
| 3796 | } |
| 3797 | assert!(rendered.windows(2).all(|pair| pair[0] == pair[1])); |
| 3798 | } |
| 3799 | |
| 3800 | /// #4681: reopening a session must not surface `<turn_meta>` machine |
| 3801 | /// blocks in the transcript. Covers the current trailing shape and the |
| 3802 | /// legacy leading shape (sessions saved before the turn-meta tail move), |
| 3803 | /// while the loaded API history keeps both envelopes intact for replay. |
| 3804 | #[test] |
| 3805 | fn rehydrated_turn_meta_blocks_never_render_in_history_cells() { |
| 3806 | let tmp = tempdir().expect("tempdir"); |
| 3807 | let manager = SessionManager::new(tmp.path().join("sessions")).expect("new"); |
| 3808 | |
| 3809 | let turn_meta = "<turn_meta>\nCurrent local date: 2026-08-01\n</turn_meta>"; |
| 3810 | let trailing_shape = Message { |
| 3811 | role: Role::User, |
| 3812 | content: vec![ |
| 3813 | ContentBlock::Text { |
| 3814 | text: "Fix the flaky test".to_string(), |
| 3815 | cache_control: None, |
| 3816 | }, |
| 3817 | ContentBlock::Text { |
| 3818 | text: turn_meta.to_string(), |
| 3819 | cache_control: None, |
| 3820 | }, |
| 3821 | ], |
| 3822 | }; |
| 3823 | let legacy_leading_shape = Message { |
| 3824 | role: Role::User, |
| 3825 | content: vec![ |
| 3826 | ContentBlock::Text { |
| 3827 | text: turn_meta.to_string(), |
| 3828 | cache_control: None, |
| 3829 | }, |
| 3830 | ContentBlock::Text { |
| 3831 | text: "Now add the docs".to_string(), |
| 3832 | cache_control: None, |
| 3833 | }, |
| 3834 | ], |
| 3835 | }; |
| 3836 | let messages = vec![ |
| 3837 | trailing_shape, |
| 3838 | Message { |
| 3839 | role: Role::Assistant, |
| 3840 | content: vec![ContentBlock::Text { |
| 3841 | text: "Done.".to_string(), |
| 3842 | cache_control: None, |
| 3843 | }], |
| 3844 | }, |
| 3845 | legacy_leading_shape, |
| 3846 | ]; |
| 3847 | let session = create_saved_session(&messages, "test-model", tmp.path(), 100, None); |
| 3848 | let session_id = session.metadata.id.clone(); |
| 3849 | manager.save_session(&session).expect("save"); |
| 3850 | |
| 3851 | let loaded = manager.load_session(&session_id).expect("load"); |
| 3852 | |
| 3853 | // Display path: no rendered cell may carry turn_meta markup. |
| 3854 | let rendered: Vec<HistoryCell> = loaded |
| 3855 | .messages |
| 3856 | .iter() |
| 3857 | .flat_map(super::history_cells_from_message) |
| 3858 | .collect(); |
| 3859 | let user_texts: Vec<&str> = rendered |
| 3860 | .iter() |
| 3861 | .filter_map(|cell| match cell { |
| 3862 | HistoryCell::User { content } => Some(content.as_str()), |
| 3863 | _ => None, |
| 3864 | }) |
| 3865 | .collect(); |
| 3866 | assert_eq!(user_texts, vec!["Fix the flaky test", "Now add the docs"]); |
| 3867 | assert!( |
| 3868 | !user_texts.iter().any(|text| text.contains("<turn_meta")), |
| 3869 | "rendered cells must not contain turn_meta markup: {user_texts:?}" |
| 3870 | ); |
| 3871 | |
| 3872 | // Model-facing replay: the persisted envelopes survive the round trip. |
| 3873 | let replayed_envelopes = loaded |
| 3874 | .messages |
| 3875 | .iter() |
| 3876 | .flat_map(|message| &message.content) |
| 3877 | .filter(|block| { |
| 3878 | matches!(block, ContentBlock::Text { text, .. } if text.contains("<turn_meta>")) |
| 3879 | }) |
| 3880 | .count(); |
| 3881 | assert_eq!(replayed_envelopes, 2); |
| 3882 | } |
| 3883 | |
| 3884 | #[test] |
| 3885 | fn save_and_load_session_preserves_rich_update_plan_tool_payload() { |
| 3886 | let tmp = tempdir().expect("tempdir"); |
| 3887 | let manager = SessionManager::new(tmp.path().join("sessions")).expect("new"); |
| 3888 | let messages = vec![ |
| 3889 | Message { |
| 3890 | role: Role::User, |
| 3891 | content: vec![ContentBlock::Text { |
| 3892 | text: "plan this carefully".to_string(), |
| 3893 | cache_control: None, |
| 3894 | }], |
| 3895 | }, |
| 3896 | Message { |
| 3897 | role: Role::Assistant, |
| 3898 | content: vec![ContentBlock::ToolUse { |
| 3899 | execution_id: None, |
| 3900 | id: "plan-1".to_string(), |
| 3901 | name: "update_plan".to_string(), |
| 3902 | input: serde_json::json!({ |
| 3903 | "objective": "Make Plan mode reviewable", |
| 3904 | "sources_used": ["gh issue view 2691"], |
| 3905 | "critical_files": ["crates/engine/src/tools/plan.rs"], |
| 3906 | "constraints": ["Preserve legacy update_plan payloads"], |
| 3907 | "verification_plan": "Run focused plan tests", |
| 3908 | "handoff_packet": "Next agent should inspect replay", |
| 3909 | "plan": [ |
| 3910 | { "step": "render replay card", "status": "completed" } |
| 3911 | ] |
| 3912 | }), |
| 3913 | caller: None, |
| 3914 | thought_signature: None, |
| 3915 | }], |
| 3916 | }, |
| 3917 | Message { |
| 3918 | role: Role::User, |
| 3919 | content: vec![ContentBlock::ToolResult { |
| 3920 | execution_id: None, |
| 3921 | tool_use_id: "plan-1".to_string(), |
| 3922 | content: "Plan updated".to_string(), |
| 3923 | is_error: None, |
| 3924 | content_blocks: None, |
| 3925 | }], |
| 3926 | }, |
| 3927 | ]; |
| 3928 | let session = create_saved_session(&messages, "deepseek-v4-flash", tmp.path(), 42, None); |
| 3929 | let session_id = session.metadata.id.clone(); |
| 3930 | |
| 3931 | manager.save_session(&session).expect("save"); |
| 3932 | let loaded = manager.load_session(&session_id).expect("load"); |
| 3933 | |
| 3934 | assert_eq!(loaded.messages.len(), 3); |
| 3935 | let cells = super::history_cells_from_message(&loaded.messages[1]); |
| 3936 | let Some(HistoryCell::Tool(ToolCell::PlanUpdate(cell))) = cells.first() else { |
| 3937 | panic!("expected loaded update_plan to replay as a PlanUpdate cell"); |
| 3938 | }; |
| 3939 | assert_eq!( |
| 3940 | cell.snapshot.objective.as_deref(), |
| 3941 | Some("Make Plan mode reviewable") |
| 3942 | ); |
| 3943 | assert_eq!( |
| 3944 | cell.snapshot.critical_files, |
| 3945 | vec!["crates/engine/src/tools/plan.rs"] |
| 3946 | ); |
| 3947 | assert_eq!(cell.snapshot.items[0].status, StepStatus::Completed); |
| 3948 | } |
| 3949 | |
| 3950 | #[test] |
| 3951 | fn execute_tools_card_renders_call_summary_readable_failures_and_unparsable_fallback() { |
| 3952 | let mut ok_cell = generic_tool("execute_tools", ToolStatus::Success); |
| 3953 | ok_cell.input_summary = Some("code: await tools.call('grep_files', {})".to_string()); |
| 3954 | ok_cell.output = Some( |
| 3955 | serde_json::json!({ |
| 3956 | "success": true, |
| 3957 | "body": { "return": 42 }, |
| 3958 | "nested_calls": 3, |
| 3959 | "calls": [ |
| 3960 | { "seq": 1, "tool": "grep_files", "status": "ok", "ok": true, "elapsed_ms": 12 }, |
| 3961 | { "seq": 2, "tool": "grep_files", "status": "ok", "ok": true, "elapsed_ms": 8 }, |
| 3962 | { "seq": 3, "tool": "linear.list_issues", "status": "ok", "ok": true, "elapsed_ms": 40 } |
| 3963 | ] |
| 3964 | }) |
| 3965 | .to_string(), |
| 3966 | ); |
| 3967 | let ok_live = lines_text(&ok_cell.lines_with_mode(120, false, RenderMode::Live)); |
| 3968 | assert!( |
| 3969 | ok_live.contains("3 calls: grep_files x2, linear.list_issues"), |
| 3970 | "{ok_live}" |
| 3971 | ); |
| 3972 | assert!(!ok_live.contains("failed"), "{ok_live}"); |
| 3973 | |
| 3974 | let raw_failure = serde_json::json!({ |
| 3975 | "success": false, |
| 3976 | "body": { "error": "script threw TypeError" }, |
| 3977 | "nested_calls": 3, |
| 3978 | "calls": [ |
| 3979 | { "seq": 1, "tool": "grep_files", "status": "ok", "ok": true, "elapsed_ms": 5 }, |
| 3980 | { "seq": 2, "tool": "grep_files", "status": "failed", "ok": false, "elapsed_ms": 9, "note": "bad regex" }, |
| 3981 | { "seq": 3, "tool": "linear.list_issues", "status": "refused", "ok": false, "elapsed_ms": 1, "note": "policy denied" } |
| 3982 | ] |
| 3983 | }) |
| 3984 | .to_string(); |
| 3985 | let mut fail_cell = generic_tool("execute_tools", ToolStatus::Failed); |
| 3986 | fail_cell.output = Some(raw_failure); |
| 3987 | |
| 3988 | for mode in [RenderMode::Live, RenderMode::Transcript] { |
| 3989 | let rendered = lines_text(&fail_cell.lines_with_mode(120, false, mode)); |
| 3990 | assert!( |
| 3991 | rendered.contains("3 calls: grep_files x2, linear.list_issues · 2 failed"), |
| 3992 | "{mode:?}: {rendered}" |
| 3993 | ); |
| 3994 | assert!( |
| 3995 | rendered.contains("script threw TypeError"), |
| 3996 | "{mode:?}: {rendered}" |
| 3997 | ); |
| 3998 | assert!( |
| 3999 | rendered.contains("grep_files (failed): bad regex"), |
| 4000 | "{mode:?}: {rendered}" |
| 4001 | ); |
| 4002 | assert!( |
| 4003 | rendered.contains("linear.list_issues (refused): policy denied"), |
| 4004 | "{mode:?}: {rendered}" |
| 4005 | ); |
| 4006 | assert!( |
| 4007 | !rendered.contains("\"nested_calls\""), |
| 4008 | "{mode:?}: {rendered}" |
| 4009 | ); |
| 4010 | } |
| 4011 | |
| 4012 | let source_rendered = lines_text(&fail_cell.lines_with_mode(120, false, RenderMode::Source)); |
| 4013 | assert!( |
| 4014 | source_rendered.contains("\"nested_calls\""), |
| 4015 | "{source_rendered}" |
| 4016 | ); |
| 4017 | |
| 4018 | let mut fallback_cell = generic_tool("execute_tools", ToolStatus::Failed); |
| 4019 | fallback_cell.input_summary = Some("code: broken()".to_string()); |
| 4020 | fallback_cell.output = Some("not-json-receipt".to_string()); |
| 4021 | let fallback_live = lines_text(&fallback_cell.lines_with_mode(120, false, RenderMode::Live)); |
| 4022 | assert!(fallback_live.contains("code: broken()"), "{fallback_live}"); |
| 4023 | assert!( |
| 4024 | fallback_live.contains("not-json-receipt"), |
| 4025 | "{fallback_live}" |
| 4026 | ); |
| 4027 | } |
| 4028 | |
| 4029 | #[test] |
| 4030 | fn queued_tool_cells_use_neutral_dim_non_animated_state_and_support_approval_hold() { |
| 4031 | let queued_generic = HistoryCell::Tool(ToolCell::Generic(generic_tool( |
| 4032 | "read_file", |
| 4033 | ToolStatus::Queued, |
| 4034 | ))); |
| 4035 | assert!(!queued_generic.has_live_motion()); |
| 4036 | let HistoryCell::Tool(ref tool) = queued_generic else { |
| 4037 | panic!("expected tool cell"); |
| 4038 | }; |
| 4039 | assert!(tool.is_running()); |
| 4040 | let rendered = lines_text(&queued_generic.lines(80)); |
| 4041 | assert!(rendered.contains("queued"), "{rendered}"); |
| 4042 | assert!( |
| 4043 | rendered.contains(codewhale_tui_kit::glyphs::NEUTRAL), |
| 4044 | "{rendered}" |
| 4045 | ); |
| 4046 | assert_eq!( |
| 4047 | super::tool_rail_color(ToolStatus::Queued), |
| 4048 | codewhale_palette::TEXT_DIM |
| 4049 | ); |
| 4050 | |
| 4051 | let mut held_exec = ExecCell { |
| 4052 | command: "cargo test".to_string(), |
| 4053 | description: None, |
| 4054 | status: ToolStatus::Queued, |
| 4055 | output: None, |
| 4056 | live_output: None, |
| 4057 | shell_task_id: None, |
| 4058 | owner_agent_id: None, |
| 4059 | owner_agent_name: None, |
| 4060 | started_at: None, |
| 4061 | duration_ms: None, |
| 4062 | stale_elapsed_since_output_ms: None, |
| 4063 | waiting: Some(super::ExecWait::Approval), |
| 4064 | source: ExecSource::Assistant, |
| 4065 | interaction: None, |
| 4066 | output_summary: None, |
| 4067 | }; |
| 4068 | let held_rendered = lines_text(&held_exec.lines_with_motion(80, false)); |
| 4069 | assert!( |
| 4070 | held_rendered.contains("waiting for approval"), |
| 4071 | "{held_rendered}" |
| 4072 | ); |
| 4073 | assert!(!HistoryCell::Tool(ToolCell::Exec(held_exec.clone())).has_live_motion()); |
| 4074 | |
| 4075 | held_exec.waiting = None; |
| 4076 | let queued_exec_rendered = lines_text(&held_exec.lines_with_motion(80, false)); |
| 4077 | assert!( |
| 4078 | queued_exec_rendered.contains("queued"), |
| 4079 | "{queued_exec_rendered}" |
| 4080 | ); |
| 4081 | } |
| 4082 |