| 1 | pub mod agent_card; |
| 2 | pub mod attachment_preview; |
| 3 | pub mod key_hint; |
| 4 | pub mod pending_input_preview; |
| 5 | mod permission_changes; |
| 6 | mod renderable; |
| 7 | pub mod tool_card; |
| 8 | pub(crate) mod workbar; |
| 9 | pub mod workflow_panel; |
| 10 | |
| 11 | pub use renderable::Renderable; |
| 12 | |
| 13 | use std::borrow::Cow; |
| 14 | use std::collections::HashSet; |
| 15 | use std::time::Duration; |
| 16 | |
| 17 | use crate::commands; |
| 18 | use crate::tui::app::{App, ComposerDensity, ViewportState}; |
| 19 | use crate::tui::approval::{ |
| 20 | ApprovalOption, ApprovalRequest, ApprovalView, ElevationOption, ElevationRequest, |
| 21 | }; |
| 22 | use crate::tui::color_compat::ascii_safe_enabled; |
| 23 | use crate::tui::history::{GenericToolCell, HistoryCell, ToolCell, ToolRun, ToolStatus}; |
| 24 | use crate::tui::underwater::ShellPhase; |
| 25 | #[cfg(test)] |
| 26 | use codewhale_config::ProviderKind; |
| 27 | use codewhale_engine::core::authority::{RiskLevel, ToolCategory}; |
| 28 | #[cfg(test)] |
| 29 | use codewhale_engine::provider_lake::all_catalog_models_for_provider; |
| 30 | use codewhale_localization::{Locale, MessageId, tr}; |
| 31 | use codewhale_palette as palette; |
| 32 | use codewhale_ratatui::{decision_wrapped_rows as measure_wrapped_rows, visible_text}; |
| 33 | use codewhale_tui_kit::menu_style; |
| 34 | use codewhale_tui_kit::scrolling::TranscriptLineMeta; |
| 35 | use codewhale_tui_kit::ui_text::grapheme_display_width; |
| 36 | use codewhale_tui_kit::ui_text::truncate_line_to_width; |
| 37 | use ratatui::{ |
| 38 | buffer::Buffer, |
| 39 | layout::Rect, |
| 40 | style::{Color, Modifier, Style}, |
| 41 | text::{Line, Span}, |
| 42 | widgets::{Block, Borders, Clear, Padding, Paragraph, Widget, Wrap}, |
| 43 | }; |
| 44 | use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; |
| 45 | |
| 46 | const SEND_FLASH_DURATION: Duration = Duration::from_millis(500); |
| 47 | #[cfg(test)] |
| 48 | const COMPOSER_PANEL_HEIGHT: u16 = 2; |
| 49 | pub struct ChatWidget { |
| 50 | content_area: Rect, |
| 51 | /// Scrollable/selectable transcript geometry. When the last prompt is |
| 52 | /// pinned, this starts one row below `content_area`; the pinned header is |
| 53 | /// intentionally outside transcript hit-testing. |
| 54 | transcript_area: Rect, |
| 55 | lines: Vec<Line<'static>>, |
| 56 | line_links: Vec<Vec<codewhale_tui_kit::osc8::LineLink>>, |
| 57 | scrollbar: Option<codewhale_ratatui::TranscriptScrollFacts>, |
| 58 | jump_to_latest_button: Option<Rect>, |
| 59 | background: Color, |
| 60 | ocean_column: Option<crate::tui::ocean::OceanColumn>, |
| 61 | ocean_paint_theme: palette::UiTheme, |
| 62 | ocean_protected: Vec<Rect>, |
| 63 | /// Live-activity shape of the ambient scene (thinking/tools/subagents). |
| 64 | ocean_activity: crate::tui::ambient_life::AmbientActivity, |
| 65 | /// Ink for the selected underwater scene's idle fish/bubbles. |
| 66 | ambient_ink: Option<Color>, |
| 67 | ocean_elapsed_ms: u128, |
| 68 | life_elapsed_ms: u128, |
| 69 | #[cfg(test)] |
| 70 | ocean_animated: bool, |
| 71 | /// Fixed-point (0..=1000) life presence; see `ocean::life_presence`. |
| 72 | #[cfg(test)] |
| 73 | life_presence_fixed: u16, |
| 74 | ambient_presence: f32, |
| 75 | ambient_life: bool, |
| 76 | scroll_track: Color, |
| 77 | scroll_thumb: Color, |
| 78 | jump_border: Color, |
| 79 | jump_arrow: Color, |
| 80 | } |
| 81 | |
| 82 | fn resolve_transcript_viewport_after_layout( |
| 83 | viewport: &mut ViewportState, |
| 84 | visible_lines: usize, |
| 85 | ) -> (usize, usize, bool) { |
| 86 | let total_lines = viewport.transcript_cache.total_lines(); |
| 87 | let line_meta = viewport.transcript_cache.line_meta(); |
| 88 | if viewport.pending_scroll_delta != 0 { |
| 89 | viewport.transcript_scroll = viewport.transcript_scroll.scrolled_by( |
| 90 | viewport.pending_scroll_delta, |
| 91 | line_meta, |
| 92 | visible_lines, |
| 93 | ); |
| 94 | viewport.pending_scroll_delta = 0; |
| 95 | } |
| 96 | |
| 97 | let max_start = total_lines.saturating_sub(visible_lines); |
| 98 | // Snapshot tail intent before resolve: clamping an out-of-range fixed |
| 99 | // offset can return `to_bottom()`, which must not masquerade as the user's |
| 100 | // choice to resume following a streaming tail (v0.8.11). |
| 101 | let was_explicit_tail = viewport.transcript_scroll.is_at_tail(); |
| 102 | let (scroll_state, top) = viewport.transcript_scroll.resolve_top(line_meta, max_start); |
| 103 | viewport.transcript_scroll = scroll_state; |
| 104 | viewport.last_transcript_top = top; |
| 105 | viewport.last_transcript_visible = visible_lines; |
| 106 | viewport.last_transcript_total = total_lines; |
| 107 | (total_lines, top, was_explicit_tail) |
| 108 | } |
| 109 | |
| 110 | impl ChatWidget { |
| 111 | pub fn new(app: &mut App, area: Rect) -> Self { |
| 112 | // The clamped ambient clock, not raw wall time: sparse draw schedules |
| 113 | // advance the scene by at most one small step per frame, so creatures |
| 114 | // drift instead of teleporting between distant samples. |
| 115 | let ocean_elapsed_ms = app.sample_ambient_clock_ms(); |
| 116 | Self::new_with_ocean_elapsed(app, area, ocean_elapsed_ms) |
| 117 | } |
| 118 | |
| 119 | /// Build one render snapshot from an already sampled ocean clock. |
| 120 | /// |
| 121 | /// Production samples the monotonic clock in [`Self::new`]. Keeping the |
| 122 | /// sampled value as an explicit input here gives render tests a stable |
| 123 | /// frame without adding a second clock or freezing the runtime animation. |
| 124 | fn new_with_ocean_elapsed(app: &mut App, area: Rect, ocean_elapsed_ms: u128) -> Self { |
| 125 | let content_area = area; |
| 126 | let background = app.ui_theme.surface_bg; |
| 127 | // The ordinary shell inherits its host/theme surface. Underwater life |
| 128 | // is earned by the underwater theme, never painted over a user's |
| 129 | // terminal simply because the app happens to be active. |
| 130 | let underwater_atmosphere = app.theme_id == codewhale_palette::ThemeId::Underwater; |
| 131 | let ocean_ramp = underwater_atmosphere |
| 132 | .then(|| crate::tui::ocean::OceanRamp::for_theme(&app.ui_theme)) |
| 133 | .flatten(); |
| 134 | // Ink hue carries the live activity (reasoning deep-dim, tools bright, |
| 135 | // sub-agents seafoam) so the marks read the state at a glance. |
| 136 | let ocean_activity = crate::tui::ambient_life::AmbientActivity::from_kind( |
| 137 | crate::tui::underwater::LiveActivity::from_app(app).kind(), |
| 138 | ); |
| 139 | let render_empty_state = should_render_empty_state(app); |
| 140 | if !app.launch.visible |
| 141 | && app.launch.dissolve_started_ms.is_some() |
| 142 | && (!render_empty_state |
| 143 | || !app.launch.session_handoff_active( |
| 144 | app.ambient_clock_ms, |
| 145 | app.motion_policy().allows_decorative(), |
| 146 | )) |
| 147 | { |
| 148 | app.launch.dissolve_started_ms = None; |
| 149 | } |
| 150 | let launch_visible = render_empty_state |
| 151 | && app.launch.visible |
| 152 | && app.ui_theme == palette::UNDERWATER_UI_THEME; |
| 153 | let ambient_ink = underwater_atmosphere.then(|| { |
| 154 | let (quiet, lit) = |
| 155 | crate::tui::ocean::ambient_inks_for_activity(&app.ui_theme, ocean_activity); |
| 156 | if launch_visible { lit } else { quiet } |
| 157 | }); |
| 158 | // The completion breath is authored decorative motion, so it rides the |
| 159 | // same motion gate as everything else in the water. Both the column's |
| 160 | // settle flourish and ambient life's presence read this one clock: |
| 161 | // the pet needs the settle tail too; the column clips only its light pulse. |
| 162 | let browsing_history = !app.viewport.transcript_scroll.is_at_tail(); |
| 163 | let completion_life_clock = (underwater_atmosphere |
| 164 | && app.motion_policy().allows_decorative() |
| 165 | && !browsing_history |
| 166 | && crate::tui::underwater::ambient_motion_terminal_supported(app)) |
| 167 | .then_some(()) |
| 168 | .and(app.ocean_completion_started_at) |
| 169 | .map(|started| started.elapsed().as_millis()); |
| 170 | let completion_elapsed_ms = completion_life_clock |
| 171 | .filter(|elapsed| *elapsed < crate::tui::ocean::COMPLETION_SETTLE_MS); |
| 172 | let phase = ShellPhase::from_app(app); |
| 173 | let underwater_motion_enabled = underwater_atmosphere |
| 174 | && !browsing_history |
| 175 | && crate::tui::underwater::decorative_shell_motion_enabled(app) |
| 176 | && crate::tui::underwater::ambient_motion_terminal_supported(app); |
| 177 | let ocean_animated = underwater_motion_enabled |
| 178 | && (render_empty_state || matches!(phase, ShellPhase::Working | ShellPhase::Verifying)); |
| 179 | // Life presence eases the animated/static boundary as a pure function |
| 180 | // of the monotonic clocks (see ocean::life_presence): bursty fast |
| 181 | // streams ramp in, quiet waits settle out, never a hard snap. |
| 182 | // |
| 183 | // This deliberately takes the *gated* completion clock. Reading |
| 184 | // `app.ocean_completion_started_at` raw here let the completion branch |
| 185 | // of `life_presence` short-circuit the `!animated` check, so a |
| 186 | // reduced-motion session got ~1.4 s of full ambient life after every |
| 187 | // successful turn — precisely while the user was reading the result. |
| 188 | let life_presence = crate::tui::ocean::life_presence( |
| 189 | completion_life_clock, |
| 190 | app.turn_started_at |
| 191 | .map(|started| started.elapsed().as_millis()), |
| 192 | ocean_animated, |
| 193 | browsing_history, |
| 194 | render_empty_state, |
| 195 | ); |
| 196 | let life_presence_fixed = (life_presence * 1000.0).round().clamp(0.0, 1000.0) as u16; |
| 197 | let ambient_motion = crate::tui::underwater::ambient_life_motion_enabled(app) |
| 198 | && !matches!(phase, ShellPhase::Waiting | ShellPhase::Approval); |
| 199 | let ambient_presence = if ambient_motion { |
| 200 | life_presence.max(crate::tui::ocean::AMBIENT_IDLE_PRESENCE) |
| 201 | } else { |
| 202 | 0.0 |
| 203 | }; |
| 204 | let life_elapsed_ms = app.ambient_life_held_ms.unwrap_or(ocean_elapsed_ms); |
| 205 | let ocean_column = ocean_ramp.map(|ramp| { |
| 206 | let context_percent = crate::tui::phase_strip::context_percent_from_app(app); |
| 207 | let session_depth = if render_empty_state |
| 208 | && (app.launch.visible || app.launch.dissolve_started_ms.is_some()) |
| 209 | { |
| 210 | app.launch.card_dissolve_progress( |
| 211 | app.ambient_clock_ms, |
| 212 | app.motion_policy().allows_decorative(), |
| 213 | ) |
| 214 | } else { |
| 215 | 1.0 |
| 216 | }; |
| 217 | crate::tui::ocean::OceanColumn::new( |
| 218 | ramp, |
| 219 | content_area, |
| 220 | ocean_elapsed_ms, |
| 221 | completion_elapsed_ms, |
| 222 | phase, |
| 223 | ocean_animated, |
| 224 | life_presence_fixed, |
| 225 | context_percent, |
| 226 | ) |
| 227 | .with_paint_caps(app.viewport.ocean_caps) |
| 228 | .with_directional_light(app.ui_theme == palette::UNDERWATER_UI_THEME) |
| 229 | .with_session_depth(session_depth) |
| 230 | }); |
| 231 | let scroll_track = app.ui_theme.border; |
| 232 | let scroll_thumb = app.ui_theme.status_working; |
| 233 | let jump_border = app.ui_theme.border; |
| 234 | let jump_arrow = app.ui_theme.status_working; |
| 235 | let visible_lines = content_area.height as usize; |
| 236 | let render_options = app.transcript_render_options(); |
| 237 | |
| 238 | if render_empty_state { |
| 239 | let lines = build_empty_state_lines(app, content_area); |
| 240 | app.viewport.last_transcript_area = Some(content_area); |
| 241 | app.viewport.last_transcript_top = 0; |
| 242 | app.viewport.last_transcript_visible = visible_lines; |
| 243 | app.viewport.last_transcript_total = 0; |
| 244 | app.viewport.last_transcript_padding_top = 0; |
| 245 | app.viewport.jump_to_latest_button_area = None; |
| 246 | app.viewport.pinned_prompt_area = None; |
| 247 | app.viewport.pinned_prompt_message = None; |
| 248 | let ocean_protected = codewhale_ratatui::ocean::ocean_semantic_surfaces( |
| 249 | &lines, |
| 250 | content_area, |
| 251 | grapheme_display_width, |
| 252 | ); |
| 253 | app.viewport |
| 254 | .ocean_semantic_surfaces |
| 255 | .clone_from(&ocean_protected); |
| 256 | return Self { |
| 257 | ocean_paint_theme: app.ui_theme, |
| 258 | ocean_protected, |
| 259 | content_area, |
| 260 | transcript_area: content_area, |
| 261 | lines, |
| 262 | line_links: Vec::new(), |
| 263 | scrollbar: None, |
| 264 | jump_to_latest_button: None, |
| 265 | background, |
| 266 | ocean_column, |
| 267 | ocean_activity, |
| 268 | ambient_ink, |
| 269 | ocean_elapsed_ms, |
| 270 | life_elapsed_ms, |
| 271 | #[cfg(test)] |
| 272 | ocean_animated, |
| 273 | #[cfg(test)] |
| 274 | life_presence_fixed, |
| 275 | ambient_presence, |
| 276 | ambient_life: ambient_motion, |
| 277 | scroll_track, |
| 278 | scroll_thumb, |
| 279 | jump_border, |
| 280 | jump_arrow, |
| 281 | }; |
| 282 | } |
| 283 | |
| 284 | // Reserve the scrollbar's column before wrapping, so painting it cannot |
| 285 | // erase the final character of a line. Keep this width stable when the |
| 286 | // history starts/stops scrolling; cached lines and copy metadata must |
| 287 | // use the same layout on both sides of that transition. |
| 288 | let transcript_width = content_area.width.saturating_sub(1).max(1); |
| 289 | |
| 290 | // Per-cell revision caching (fix for issue #78): |
| 291 | // |
| 292 | // Every committed history cell carries its own revision counter in |
| 293 | // `app.history_revisions`. The transcript cache compares each cell's |
| 294 | // current revision against the previously rendered one, so unchanged |
| 295 | // cells reuse their cached wrapped lines instead of being re-wrapped |
| 296 | // every frame. This is the difference between O(history.len()) and |
| 297 | // O(changed_cells) per render — and was the root cause of scroll lag |
| 298 | // on long transcripts. |
| 299 | // |
| 300 | // The active in-flight cell (if any) is appended as the last cell so |
| 301 | // its mutations show up at the live tail. Each entry inside the |
| 302 | // active cell becomes a virtual cell at index `history.len() + i`, |
| 303 | // matching `App::cell_at_virtual_index`. Active-cell entries share |
| 304 | // the same `active_cell_revision` salt so any mutation in the active |
| 305 | // cell forces only those rows to re-render — committed history rows |
| 306 | // are unaffected. |
| 307 | app.resync_history_revisions(); |
| 308 | app.viewport.transcript_cache.set_streaming_source_receipt( |
| 309 | app.streaming_source_receipt.map(|receipt| { |
| 310 | crate::tui::transcript::StreamingSourceReceipt { |
| 311 | cell_index: receipt.cell_index, |
| 312 | from_revision: history_entry_revision(receipt.from_revision), |
| 313 | to_revision: history_entry_revision(receipt.to_revision), |
| 314 | content_len: receipt.content_len, |
| 315 | } |
| 316 | }), |
| 317 | ); |
| 318 | let provisional_action_owner = app.transcript_action_owner(); |
| 319 | let active_entries: &[HistoryCell] = app |
| 320 | .active_cell |
| 321 | .as_ref() |
| 322 | .map_or(&[], |active| active.entries()); |
| 323 | let history_len = app.history.len(); |
| 324 | // Cache the group projection, not the whole frame: filtered refs and |
| 325 | // transcript bookkeeping below still walk the retained history. |
| 326 | let open_tail = app.turn_fold_open_tail(); |
| 327 | let open_turn_user_index = app.active_turn_user_index; |
| 328 | let echoed_queued_users = app.echoed_queued_user_count(); |
| 329 | let cache_key_matches = app.tool_run_cache.history_version == app.history_version |
| 330 | && app.tool_run_cache.history_len == history_len |
| 331 | && app.tool_run_cache.active_cell_revision == app.active_cell_revision |
| 332 | && app.tool_run_cache.active_len == active_entries.len() |
| 333 | && app.tool_run_cache.threshold == app.tool_collapse_threshold |
| 334 | && app.tool_run_cache.mode == app.tool_collapse_mode |
| 335 | && app.tool_run_cache.calm_mode == app.calm_mode |
| 336 | && app.tool_run_cache.locale == app.ui_locale |
| 337 | && app.tool_run_cache.expanded_runs == app.expanded_tool_runs |
| 338 | && app.tool_run_cache.open_tail == open_tail |
| 339 | && app.tool_run_cache.open_turn_user_index == open_turn_user_index |
| 340 | && app.tool_run_cache.echoed_queued_users == echoed_queued_users |
| 341 | && app.tool_run_cache.turn_durations_revision == app.turn_durations_revision; |
| 342 | if !cache_key_matches { |
| 343 | let superseded_todos = |
| 344 | crate::tui::history::superseded_todo_write_indices(&app.history, active_entries); |
| 345 | let runs = if app.tool_collapse_active() { |
| 346 | crate::tui::history::detect_tool_runs_from_slices( |
| 347 | &app.history, |
| 348 | active_entries, |
| 349 | app.tool_collapse_threshold, |
| 350 | ) |
| 351 | } else { |
| 352 | Vec::new() |
| 353 | }; |
| 354 | let folds = if app.tool_collapse_active() { |
| 355 | crate::tui::history::detect_turn_folds( |
| 356 | &app.history, |
| 357 | active_entries, |
| 358 | open_tail, |
| 359 | open_turn_user_index, |
| 360 | echoed_queued_users, |
| 361 | &superseded_todos, |
| 362 | &app.turn_work_durations, |
| 363 | ) |
| 364 | } else { |
| 365 | crate::tui::history::TurnFoldProjection::default() |
| 366 | }; |
| 367 | let cell_at = |index: usize| { |
| 368 | app.history |
| 369 | .get(index) |
| 370 | .or_else(|| active_entries.get(index.checked_sub(history_len)?)) |
| 371 | }; |
| 372 | let mut fold_summaries: Vec<(usize, HistoryCell, u64)> = Vec::new(); |
| 373 | let mut fold_hidden: HashSet<usize> = HashSet::new(); |
| 374 | let mut folded_members: HashSet<usize> = HashSet::new(); |
| 375 | for turn in &folds.turns { |
| 376 | if app.expanded_tool_runs.contains(&turn.key) { |
| 377 | continue; |
| 378 | } |
| 379 | let Some(host) = turn.host() else { |
| 380 | continue; |
| 381 | }; |
| 382 | folded_members.extend(turn.members.iter().copied()); |
| 383 | fold_hidden.extend(turn.members.iter().copied().skip(1)); |
| 384 | fold_summaries.push(( |
| 385 | host, |
| 386 | turn_fold_summary_cell(turn, app.ui_locale), |
| 387 | members_summary_revision( |
| 388 | 0x7E12_F01D_0000_2231 ^ ((turn.key as u64) << 24), |
| 389 | turn.members.iter().copied(), |
| 390 | turn.duration.map_or(0, |duration| duration.as_secs()), |
| 391 | &app.history_revisions, |
| 392 | history_len, |
| 393 | app.active_cell_revision, |
| 394 | ), |
| 395 | )); |
| 396 | } |
| 397 | for &index in &folds.agents { |
| 398 | if app.expanded_tool_runs.contains(&index) { |
| 399 | continue; |
| 400 | } |
| 401 | if let Some(HistoryCell::SubAgent(agent)) = cell_at(index) { |
| 402 | fold_summaries.push(( |
| 403 | index, |
| 404 | agent_line_summary_cell(agent, app.ui_locale), |
| 405 | members_summary_revision( |
| 406 | 0xA6E7_11FE_0000_2233, |
| 407 | std::iter::once(index), |
| 408 | 0, |
| 409 | &app.history_revisions, |
| 410 | history_len, |
| 411 | app.active_cell_revision, |
| 412 | ), |
| 413 | )); |
| 414 | } |
| 415 | } |
| 416 | if app.calm_mode { |
| 417 | for (members, summary) in permission_changes::groups(&app.history, app.ui_locale) { |
| 418 | if members.clone().any(|index| folded_members.contains(&index)) { |
| 419 | continue; |
| 420 | } |
| 421 | let revision = members_summary_revision( |
| 422 | 0xD1A1_0001, |
| 423 | members.clone(), |
| 424 | 0, |
| 425 | &app.history_revisions, |
| 426 | history_len, |
| 427 | app.active_cell_revision, |
| 428 | ); |
| 429 | fold_summaries.push((members.start, summary, revision)); |
| 430 | fold_hidden.extend(members.skip(1)); |
| 431 | } |
| 432 | } |
| 433 | let cache = &mut app.tool_run_cache; |
| 434 | #[cfg(test)] |
| 435 | { |
| 436 | cache.projection_builds += 1; |
| 437 | } |
| 438 | cache.generation = cache.generation.wrapping_add(1); |
| 439 | cache.summaries.clear(); |
| 440 | cache.hidden_indices.clear(); |
| 441 | for (host, cell, revision) in fold_summaries { |
| 442 | cache.summaries.insert(host, (cell, revision)); |
| 443 | } |
| 444 | cache.hidden_indices.extend(fold_hidden); |
| 445 | for run in &runs { |
| 446 | // A hidden replacement snapshot cannot own a group summary. |
| 447 | if app.expanded_tool_runs.contains(&run.start) |
| 448 | || folded_members.contains(&run.start) |
| 449 | || (run.start..run.start.saturating_add(run.count)) |
| 450 | .any(|index| superseded_todos.contains(&index)) |
| 451 | { |
| 452 | continue; |
| 453 | } |
| 454 | cache.summaries.insert( |
| 455 | run.start, |
| 456 | ( |
| 457 | tool_run_summary_cell(run, app.ui_locale), |
| 458 | tool_run_summary_revision( |
| 459 | run, |
| 460 | &app.history_revisions, |
| 461 | history_len, |
| 462 | app.active_cell_revision, |
| 463 | ), |
| 464 | ), |
| 465 | ); |
| 466 | cache |
| 467 | .hidden_indices |
| 468 | .extend(run.start + 1..run.start + run.count); |
| 469 | } |
| 470 | cache.superseded_todos = superseded_todos; |
| 471 | cache.history_version = app.history_version; |
| 472 | cache.history_len = history_len; |
| 473 | cache.active_cell_revision = app.active_cell_revision; |
| 474 | cache.active_len = active_entries.len(); |
| 475 | cache.threshold = app.tool_collapse_threshold; |
| 476 | cache.mode = app.tool_collapse_mode; |
| 477 | cache.calm_mode = app.calm_mode; |
| 478 | cache.locale = app.ui_locale; |
| 479 | cache.expanded_runs.clone_from(&app.expanded_tool_runs); |
| 480 | cache.open_tail = open_tail; |
| 481 | cache.open_turn_user_index = open_turn_user_index; |
| 482 | cache.echoed_queued_users = echoed_queued_users; |
| 483 | cache.turn_durations_revision = app.turn_durations_revision; |
| 484 | } |
| 485 | // v0.9.1: do not collapse concurrent sub-agent cards into an Enter- |
| 486 | // expand shelf. Count lives in header chrome; full cards stay visible; |
| 487 | // sidebar / SubAgents modal are the drill-in surface. |
| 488 | let has_collapsed = !app.collapsed_cells.is_empty() |
| 489 | || !app.tool_run_cache.summaries.is_empty() |
| 490 | || !app.tool_run_cache.superseded_todos.is_empty(); |
| 491 | if has_collapsed { |
| 492 | app.tool_run_cache |
| 493 | .refresh_filtered(history_len + active_entries.len(), &app.collapsed_cells); |
| 494 | } |
| 495 | let summary_cells = &app.tool_run_cache.summaries; |
| 496 | |
| 497 | // Fast path: no collapsed cells — use original slices directly. |
| 498 | if !has_collapsed { |
| 499 | let mut cell_revisions: Vec<u64> = |
| 500 | Vec::with_capacity(app.history.len() + active_entries.len()); |
| 501 | cell_revisions.extend( |
| 502 | app.history_revisions |
| 503 | .iter() |
| 504 | .copied() |
| 505 | .map(history_entry_revision), |
| 506 | ); |
| 507 | if !active_entries.is_empty() { |
| 508 | let active_rev = app.active_cell_revision; |
| 509 | for i in 0..active_entries.len() { |
| 510 | let salt = (i as u64).wrapping_add(1); |
| 511 | cell_revisions.push(active_entry_revision(active_rev, salt)); |
| 512 | } |
| 513 | } |
| 514 | // Build identity mapping: filtered index == original index. |
| 515 | // Reused across frames; identity maps are rebuilt only when the |
| 516 | // row count changes. |
| 517 | let row_count = app.history.len() + active_entries.len(); |
| 518 | if app.collapsed_cell_map.len() != row_count { |
| 519 | app.collapsed_cell_map = (0..row_count).collect(); |
| 520 | } |
| 521 | |
| 522 | app.viewport |
| 523 | .transcript_cache |
| 524 | .set_workspace(Some(&app.workspace)); |
| 525 | let shards: [&[HistoryCell]; 2] = [&app.history, active_entries]; |
| 526 | app.viewport.transcript_cache.ensure_split( |
| 527 | &shards, |
| 528 | &cell_revisions, |
| 529 | transcript_width, |
| 530 | render_options, |
| 531 | &app.cell_folds, |
| 532 | None, |
| 533 | provisional_action_owner, |
| 534 | ); |
| 535 | } else { |
| 536 | // Slow path: borrow non-collapsed cells into a filtered ref list |
| 537 | // so collapsed cells are excluded from rendering, and build the |
| 538 | // filtered→original index mapping. Collapsed run starts render a |
| 539 | // synthetic summary cell borrowed from the generation cache. |
| 540 | // No history cells or summary bodies are cloned on scroll frames. |
| 541 | // Which rows survive is cached per projection generation; only |
| 542 | // the revisions are gathered fresh (#6652). |
| 543 | let filtered = &app.tool_run_cache.filtered; |
| 544 | let active_rev = app.active_cell_revision; |
| 545 | let mut filtered_cells: Vec<&HistoryCell> = Vec::with_capacity(filtered.original.len()); |
| 546 | let mut filtered_revs: Vec<u64> = Vec::with_capacity(filtered.original.len()); |
| 547 | for &original in &filtered.original { |
| 548 | if original < history_len { |
| 549 | filtered_cells.push(&app.history[original]); |
| 550 | filtered_revs.push(history_entry_revision(app.history_revisions[original])); |
| 551 | } else { |
| 552 | let active_index = original - history_len; |
| 553 | filtered_cells.push(&active_entries[active_index]); |
| 554 | filtered_revs.push(active_entry_revision( |
| 555 | active_rev, |
| 556 | (active_index as u64).wrapping_add(1), |
| 557 | )); |
| 558 | } |
| 559 | } |
| 560 | for &slot in &filtered.summary_slots { |
| 561 | if let Some((summary, revision)) = summary_cells.get(&filtered.original[slot]) { |
| 562 | filtered_cells[slot] = summary; |
| 563 | filtered_revs[slot] = *revision; |
| 564 | } |
| 565 | } |
| 566 | app.collapsed_cell_map.clone_from(&filtered.original); |
| 567 | |
| 568 | app.viewport |
| 569 | .transcript_cache |
| 570 | .set_workspace(Some(&app.workspace)); |
| 571 | app.viewport.transcript_cache.ensure_filtered( |
| 572 | &filtered_cells, |
| 573 | &filtered_revs, |
| 574 | transcript_width, |
| 575 | render_options, |
| 576 | &app.cell_folds, |
| 577 | Some(&app.collapsed_cell_map), |
| 578 | provisional_action_owner, |
| 579 | ); |
| 580 | } |
| 581 | |
| 582 | let (mut total_lines, mut top, mut was_explicit_tail) = |
| 583 | resolve_transcript_viewport_after_layout(&mut app.viewport, visible_lines); |
| 584 | |
| 585 | // A sticky prompt is layout chrome, not a synthetic transcript row. |
| 586 | // First resolve against the full viewport, then reserve one real row |
| 587 | // only when the prompt has actually scrolled above it. Resolving once |
| 588 | // more with the smaller body keeps the newest tail line visible. |
| 589 | let mut transcript_area = content_area; |
| 590 | let mut pinned_prompt = (app.pin_last_prompt && content_area.height > 1) |
| 591 | .then(|| { |
| 592 | scrolled_user_prompt_pin( |
| 593 | &app.history, |
| 594 | app.viewport.transcript_cache.line_meta(), |
| 595 | &app.collapsed_cell_map, |
| 596 | top, |
| 597 | content_area.width, |
| 598 | ) |
| 599 | }) |
| 600 | .flatten(); |
| 601 | let visible_lines = if pinned_prompt.is_some() { |
| 602 | transcript_area.y = transcript_area.y.saturating_add(1); |
| 603 | transcript_area.height = transcript_area.height.saturating_sub(1); |
| 604 | let visible = usize::from(transcript_area.height); |
| 605 | (total_lines, top, was_explicit_tail) = |
| 606 | resolve_transcript_viewport_after_layout(&mut app.viewport, visible); |
| 607 | // Reserving the row moved `top` down by one on the tail, so |
| 608 | // re-resolve the header against the final viewport: a prompt |
| 609 | // whose first line was exactly the old top row must now head the |
| 610 | // header instead of being hidden behind it. The previous |
| 611 | // candidate's first line is still above the new `top`, so this |
| 612 | // always re-selects a message. |
| 613 | pinned_prompt = scrolled_user_prompt_pin( |
| 614 | &app.history, |
| 615 | app.viewport.transcript_cache.line_meta(), |
| 616 | &app.collapsed_cell_map, |
| 617 | top, |
| 618 | content_area.width, |
| 619 | ); |
| 620 | visible |
| 621 | } else { |
| 622 | visible_lines |
| 623 | }; |
| 624 | let owner = app.transcript_action_owner(); |
| 625 | let index_map = has_collapsed.then_some(app.collapsed_cell_map.as_slice()); |
| 626 | app.viewport.transcript_cache.retarget(owner, index_map); |
| 627 | |
| 628 | // The cache has now observed this revision (or the cell was filtered, |
| 629 | // in which case a later reveal must cold-render). Start the next append |
| 630 | // receipt from the current revision instead of chaining across an |
| 631 | // already-consumed proof. |
| 632 | if let Some(receipt) = app.streaming_source_receipt.as_mut() { |
| 633 | receipt.from_revision = receipt.to_revision; |
| 634 | } |
| 635 | |
| 636 | let line_meta = app.viewport.transcript_cache.line_meta(); |
| 637 | |
| 638 | // If the user scrolled back to the live tail, the per-stream |
| 639 | // "leave me alone" lock is over — new chunks should pin to bottom |
| 640 | // again until they explicitly scroll up. Without this clear, content |
| 641 | // piles up off-screen below the visible area and the view appears |
| 642 | // frozen at the moment they returned to bottom. |
| 643 | // |
| 644 | // Only clear the lock when the user's INTENT was tail (their |
| 645 | // stored state was already `to_bottom()` before resolve), AND |
| 646 | // when the transcript actually has scrolling room to talk about |
| 647 | // — if everything fits in one screen, "tail" is trivially true |
| 648 | // and clearing here would yank the user back to bottom on the |
| 649 | // next chunk even though they explicitly scrolled up. |
| 650 | if was_explicit_tail && total_lines > visible_lines { |
| 651 | app.user_scrolled_during_stream = false; |
| 652 | } |
| 653 | |
| 654 | app.viewport.last_transcript_area = Some(transcript_area); |
| 655 | app.viewport.last_transcript_padding_top = 0; |
| 656 | |
| 657 | let end = (top + visible_lines).min(total_lines); |
| 658 | let mut lines = if total_lines == 0 { |
| 659 | vec![Line::from("")] |
| 660 | } else { |
| 661 | app.viewport.transcript_cache.lines()[top..end].to_vec() |
| 662 | }; |
| 663 | let mut line_links = if total_lines == 0 { |
| 664 | vec![Vec::new()] |
| 665 | } else { |
| 666 | app.viewport.transcript_cache.line_links()[top..end].to_vec() |
| 667 | }; |
| 668 | |
| 669 | if !app.low_motion |
| 670 | && app.fancy_animations |
| 671 | && let (Some(start), Some(started)) = ( |
| 672 | app.ocean_receipt_settle_start, |
| 673 | app.ocean_completion_started_at, |
| 674 | ) |
| 675 | { |
| 676 | apply_receipt_settle_cascade( |
| 677 | &mut lines, |
| 678 | top, |
| 679 | line_meta, |
| 680 | &app.collapsed_cell_map, |
| 681 | &app.history, |
| 682 | start, |
| 683 | started.elapsed().as_millis(), |
| 684 | ); |
| 685 | } |
| 686 | |
| 687 | // Brief flash highlight on the most recently sent user message. It is |
| 688 | // a one-shot transition, so Reduced/Still clear the timestamp instead |
| 689 | // of leaving a stale flash waiting for a later state-change redraw. |
| 690 | if app.motion_policy().allows_decorative() { |
| 691 | if let Some(send_at) = app.last_send_at { |
| 692 | if send_at.elapsed() < SEND_FLASH_DURATION { |
| 693 | apply_send_flash( |
| 694 | &mut lines, |
| 695 | top, |
| 696 | &app.history, |
| 697 | line_meta, |
| 698 | &app.collapsed_cell_map, |
| 699 | ); |
| 700 | } else { |
| 701 | app.last_send_at = None; |
| 702 | } |
| 703 | } |
| 704 | } else { |
| 705 | app.last_send_at = None; |
| 706 | } |
| 707 | |
| 708 | let sweep_entries: &[HistoryCell] = app |
| 709 | .active_cell |
| 710 | .as_ref() |
| 711 | .map_or(&[], |active| active.entries()); |
| 712 | let activity_sweep_visible = crate::tui::ui::motion::activity_sweep_allowed(app) |
| 713 | && app.turn_started_at.is_some_and(|started| { |
| 714 | apply_activity_sweep( |
| 715 | &mut lines, |
| 716 | top, |
| 717 | line_meta, |
| 718 | &app.collapsed_cell_map, |
| 719 | &app.history, |
| 720 | sweep_entries, |
| 721 | started.elapsed(), |
| 722 | app.theme_id, |
| 723 | &app.ui_theme, |
| 724 | app.viewport.detected_background, |
| 725 | ) |
| 726 | }); |
| 727 | let settle_flash_visible = crate::tui::ui::motion::activity_sweep_allowed(app) |
| 728 | && apply_settle_flash( |
| 729 | &mut lines, |
| 730 | top, |
| 731 | line_meta, |
| 732 | &app.collapsed_cell_map, |
| 733 | app.history.len(), |
| 734 | sweep_entries, |
| 735 | &app.active_tool_entry_completed_at, |
| 736 | std::time::Instant::now(), |
| 737 | app.theme_id, |
| 738 | &app.ui_theme, |
| 739 | app.viewport.detected_background, |
| 740 | ); |
| 741 | app.viewport.activity_sweep_visible = activity_sweep_visible; |
| 742 | app.viewport.settle_flash_visible = settle_flash_visible; |
| 743 | |
| 744 | // No background "highlight" for the Alt+V detail target: it used to |
| 745 | // paint the target cell's spans `Color::Reset`, which is invisible on |
| 746 | // terminal-owned themes and a black hole on painted surfaces |
| 747 | // (Underwater, Shoreline): the cell's text sat on the terminal's own |
| 748 | // background, and CJK trailing columns left black remnants when the |
| 749 | // cell scrolled (#6704). The footer's `Alt+V details` hint names it. |
| 750 | // |
| 751 | // The pinned header is clickable: a click jumps the viewport to the |
| 752 | // user message it describes. Record the hit box and target line in |
| 753 | // the same frame that paints the header, so the coordinates the |
| 754 | // mouse handler tests are the coordinates the user saw. |
| 755 | app.viewport.pinned_prompt_area = (pinned_prompt.is_some() && app.use_mouse_capture) |
| 756 | .then_some(Rect { |
| 757 | x: content_area.x, |
| 758 | y: content_area.y, |
| 759 | width: content_area.width, |
| 760 | height: 1, |
| 761 | }); |
| 762 | // Record the message, not a line offset: offsets are frame-bound, and |
| 763 | // a rewrite between paint and click would land the jump on whatever |
| 764 | // now sits on the stale offset. |
| 765 | app.viewport.pinned_prompt_message = pinned_prompt.as_ref().map(|(_, message)| *message); |
| 766 | |
| 767 | apply_selection(&mut lines, top, app); |
| 768 | |
| 769 | if let Some((pin, _)) = pinned_prompt { |
| 770 | lines.insert(0, pin); |
| 771 | line_links.insert(0, Vec::new()); |
| 772 | } |
| 773 | |
| 774 | // The HTML contract is a top-first ledger. Bottom-padding the short |
| 775 | // transcript made every newly wrapped stream line shift all prior |
| 776 | // rows upward, producing repeated thousand-cell repaints and the |
| 777 | // visible "slab" motion recorded in live QA. Empty-state centering is |
| 778 | // handled separately; active work starts at the top and appends in |
| 779 | // place until scrolling is genuinely necessary. |
| 780 | app.viewport.last_transcript_padding_top = 0; |
| 781 | |
| 782 | let scrollbar = (total_lines > visible_lines && transcript_area.width > 1).then_some( |
| 783 | codewhale_ratatui::TranscriptScrollFacts { |
| 784 | top, |
| 785 | visible: visible_lines, |
| 786 | total: total_lines, |
| 787 | }, |
| 788 | ); |
| 789 | let jump_to_latest_button = |
| 790 | if app.use_mouse_capture && !app.viewport.transcript_scroll.is_at_tail() { |
| 791 | codewhale_ratatui::transcript_jump_rect(transcript_area, scrollbar.is_some()) |
| 792 | } else { |
| 793 | None |
| 794 | }; |
| 795 | app.viewport.jump_to_latest_button_area = jump_to_latest_button; |
| 796 | |
| 797 | let ocean_protected = codewhale_ratatui::ocean::ocean_semantic_surfaces( |
| 798 | &lines, |
| 799 | content_area, |
| 800 | grapheme_display_width, |
| 801 | ); |
| 802 | app.viewport |
| 803 | .ocean_semantic_surfaces |
| 804 | .clone_from(&ocean_protected); |
| 805 | Self { |
| 806 | ocean_paint_theme: app.ui_theme, |
| 807 | ocean_protected, |
| 808 | content_area, |
| 809 | transcript_area, |
| 810 | lines, |
| 811 | line_links, |
| 812 | scrollbar, |
| 813 | jump_to_latest_button, |
| 814 | background, |
| 815 | ocean_column, |
| 816 | ocean_activity, |
| 817 | ambient_ink, |
| 818 | ocean_elapsed_ms, |
| 819 | life_elapsed_ms, |
| 820 | #[cfg(test)] |
| 821 | ocean_animated, |
| 822 | #[cfg(test)] |
| 823 | life_presence_fixed, |
| 824 | ambient_presence, |
| 825 | ambient_life: ambient_motion, |
| 826 | scroll_track, |
| 827 | scroll_thumb, |
| 828 | jump_border, |
| 829 | jump_arrow, |
| 830 | } |
| 831 | } |
| 832 | |
| 833 | /// Sample the water field against the full terminal instead of restarting |
| 834 | /// it at the transcript's first row. Standalone widget callers keep the |
| 835 | /// local column, which is useful for previews and focused tests. |
| 836 | #[must_use] |
| 837 | pub(crate) fn with_ocean_viewport(mut self, viewport: Rect) -> Self { |
| 838 | self.ocean_column = self |
| 839 | .ocean_column |
| 840 | .map(|column| column.with_viewport(viewport)); |
| 841 | self |
| 842 | } |
| 843 | |
| 844 | #[must_use] |
| 845 | pub(crate) fn ocean_column(&self) -> Option<crate::tui::ocean::OceanColumn> { |
| 846 | self.ocean_column |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | fn apply_receipt_settle_cascade( |
| 851 | lines: &mut [Line<'static>], |
| 852 | top: usize, |
| 853 | line_meta: &[TranscriptLineMeta], |
| 854 | filtered_to_original: &[usize], |
| 855 | history: &[HistoryCell], |
| 856 | start: usize, |
| 857 | elapsed_ms: u128, |
| 858 | ) { |
| 859 | for (visible_index, line) in lines.iter_mut().enumerate() { |
| 860 | let Some((filtered_cell, _)) = line_meta |
| 861 | .get(top + visible_index) |
| 862 | .and_then(TranscriptLineMeta::cell_line) |
| 863 | else { |
| 864 | continue; |
| 865 | }; |
| 866 | let original_cell = filtered_to_original |
| 867 | .get(filtered_cell) |
| 868 | .copied() |
| 869 | .unwrap_or(filtered_cell); |
| 870 | if original_cell < start |
| 871 | || !matches!( |
| 872 | history.get(original_cell), |
| 873 | Some(HistoryCell::Tool(_) | HistoryCell::SubAgent(_)) |
| 874 | ) |
| 875 | || !receipt_is_settling(original_cell - start, elapsed_ms) |
| 876 | { |
| 877 | continue; |
| 878 | } |
| 879 | for span in &mut line.spans { |
| 880 | span.style = span.style.add_modifier(Modifier::DIM); |
| 881 | } |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | #[must_use] |
| 886 | fn receipt_is_settling(receipt_order: usize, elapsed_ms: u128) -> bool { |
| 887 | let delay = u128::try_from(receipt_order.min(6)).unwrap_or(6) * 70; |
| 888 | elapsed_ms < delay + 140 |
| 889 | } |
| 890 | |
| 891 | fn tool_run_summary_cell(run: &ToolRun, locale: codewhale_localization::Locale) -> HistoryCell { |
| 892 | HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 893 | name: "activity_group".to_string(), |
| 894 | status: ToolStatus::Success, |
| 895 | input_summary: Some(crate::tui::history::tool_run_summary(run, locale)), |
| 896 | output: None, |
| 897 | prompts: None, |
| 898 | spillover_path: None, |
| 899 | output_summary: Some(format!("+{}", run.count)), |
| 900 | is_diff: false, |
| 901 | })) |
| 902 | } |
| 903 | |
| 904 | fn turn_fold_summary_cell( |
| 905 | turn: &crate::tui::history::TurnFold, |
| 906 | locale: codewhale_localization::Locale, |
| 907 | ) -> HistoryCell { |
| 908 | let changes = crate::tui::history::turn_fold_changes_in(turn, locale, ascii_safe_enabled()) |
| 909 | .map(|changes| { |
| 910 | format!( |
| 911 | "{changes} \u{00B7} {}", |
| 912 | codewhale_localization::tr( |
| 913 | locale, |
| 914 | codewhale_localization::MessageId::TurnReviewChanges |
| 915 | ) |
| 916 | ) |
| 917 | }); |
| 918 | HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 919 | name: "turn_work".to_string(), |
| 920 | status: ToolStatus::Success, |
| 921 | input_summary: Some(crate::tui::history::turn_fold_headline(turn, locale)), |
| 922 | output: None, |
| 923 | prompts: None, |
| 924 | spillover_path: None, |
| 925 | output_summary: changes, |
| 926 | is_diff: false, |
| 927 | })) |
| 928 | } |
| 929 | |
| 930 | fn agent_line_summary_cell( |
| 931 | agent: &crate::tui::history::SubAgentCell, |
| 932 | locale: codewhale_localization::Locale, |
| 933 | ) -> HistoryCell { |
| 934 | use crate::tui::history::SubAgentCell; |
| 935 | let (tag, rest) = match agent { |
| 936 | SubAgentCell::Delegate(card) => { |
| 937 | let mut rest = format!(" \u{00B7} {}", card.status.label_in(locale)); |
| 938 | if let (Some(started), Some(finished)) = (card.started_at, card.finished_at) { |
| 939 | rest.push_str(" \u{00B7} "); |
| 940 | rest.push_str(&codewhale_command_contract::elapsed::format_elapsed_ms( |
| 941 | finished.duration_since(started).as_millis() as u64, |
| 942 | )); |
| 943 | } |
| 944 | if let Some(summary) = card |
| 945 | .summary |
| 946 | .as_deref() |
| 947 | .map(str::trim) |
| 948 | .filter(|s| !s.is_empty()) |
| 949 | { |
| 950 | rest.push_str(" \u{00B7} "); |
| 951 | rest.push_str(summary.lines().next().unwrap_or(summary)); |
| 952 | } |
| 953 | ( |
| 954 | codewhale_agent_contract::role::public_role_label(&card.agent_type), |
| 955 | rest, |
| 956 | ) |
| 957 | } |
| 958 | SubAgentCell::Fanout(card) => ( |
| 959 | card.kind.clone(), |
| 960 | format!( |
| 961 | " \u{00B7} {} \u{00B7} {}", |
| 962 | card.workers.len(), |
| 963 | card.aggregate_status_public().label_in(locale) |
| 964 | ), |
| 965 | ), |
| 966 | }; |
| 967 | HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 968 | name: "agent_line".to_string(), |
| 969 | status: ToolStatus::Success, |
| 970 | input_summary: Some(rest), |
| 971 | output: None, |
| 972 | prompts: None, |
| 973 | spillover_path: None, |
| 974 | output_summary: Some(tag), |
| 975 | is_diff: false, |
| 976 | })) |
| 977 | } |
| 978 | |
| 979 | fn tool_run_summary_revision( |
| 980 | run: &ToolRun, |
| 981 | revisions: &[u64], |
| 982 | history_len: usize, |
| 983 | active_rev: u64, |
| 984 | ) -> u64 { |
| 985 | members_summary_revision( |
| 986 | 0xA11C_EA5E_D00D_2692u64 ^ ((run.start as u64) << 32) ^ (run.count as u64), |
| 987 | run.start..run.start.saturating_add(run.count), |
| 988 | 0, |
| 989 | revisions, |
| 990 | history_len, |
| 991 | active_rev, |
| 992 | ) |
| 993 | } |
| 994 | |
| 995 | fn members_summary_revision( |
| 996 | seed: u64, |
| 997 | members: impl Iterator<Item = usize>, |
| 998 | salt: u64, |
| 999 | revisions: &[u64], |
| 1000 | history_len: usize, |
| 1001 | active_rev: u64, |
| 1002 | ) -> u64 { |
| 1003 | let mut revision = seed ^ salt.rotate_left(17); |
| 1004 | let mut extends_into_active = false; |
| 1005 | for idx in members { |
| 1006 | extends_into_active |= idx >= history_len; |
| 1007 | let cell_revision = revisions |
| 1008 | .get(idx) |
| 1009 | .copied() |
| 1010 | .map(history_entry_revision) |
| 1011 | .unwrap_or_else(|| { |
| 1012 | let active_idx = idx.saturating_sub(history_len); |
| 1013 | active_entry_revision(active_rev, (active_idx as u64).wrapping_add(1)) |
| 1014 | }); |
| 1015 | revision = revision.rotate_left(7) ^ cell_revision; |
| 1016 | } |
| 1017 | revision_in_domain(revision, extends_into_active) |
| 1018 | } |
| 1019 | |
| 1020 | const ACTIVE_REVISION_DOMAIN: u64 = 1 << 63; |
| 1021 | |
| 1022 | fn revision_in_domain(revision: u64, active: bool) -> u64 { |
| 1023 | // The top bit is exclusively a cache-domain tag. Clearing it means raw |
| 1024 | // counters that differ only by bit 63 can theoretically alias within one |
| 1025 | // domain after 2^63 updates; that lifetime is acceptable, while active and |
| 1026 | // committed-history keys must never alias each other. |
| 1027 | let payload = revision & !ACTIVE_REVISION_DOMAIN; |
| 1028 | if active { |
| 1029 | ACTIVE_REVISION_DOMAIN | payload |
| 1030 | } else { |
| 1031 | payload |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | fn history_entry_revision(revision: u64) -> u64 { |
| 1036 | revision_in_domain(revision, false) |
| 1037 | } |
| 1038 | |
| 1039 | pub(crate) fn active_entry_revision(active_rev: u64, salt: u64) -> u64 { |
| 1040 | // Active entries and committed history cells can occupy the same |
| 1041 | // positional cache slot across `flush_active_cell`. Keep their revision |
| 1042 | // domains distinct so the first active entry (`active_rev = 0`, |
| 1043 | // `salt = 1`) cannot collide with the first history revision (`1`) and |
| 1044 | // reuse a stale `running` render after cancellation. |
| 1045 | let mixed = active_rev |
| 1046 | .wrapping_mul(0x9E37_79B9_7F4A_7C15) |
| 1047 | .wrapping_add(salt); |
| 1048 | revision_in_domain(mixed, true) |
| 1049 | } |
| 1050 | |
| 1051 | /// Build the pinned user-prompt header for the content at the top of the |
| 1052 | /// resolved transcript viewport. |
| 1053 | /// |
| 1054 | /// The header belongs to whichever user message owns the content the |
| 1055 | /// viewport starts on: the newest user message whose first rendered line |
| 1056 | /// sits above `top`. The instant a newer prompt's first line reaches the top |
| 1057 | /// viewport row — scrolling up, or the tail sitting short — the header hands |
| 1058 | /// over to the previous turn's prompt, so it never blinks out while the user |
| 1059 | /// scrolls across a turn boundary. The returned message index lets a click |
| 1060 | /// on the header jump the viewport back to that message (resolved against |
| 1061 | /// the click frame's layout, so a rewrite between paint and click cannot |
| 1062 | /// land the jump on a stale offset), and the caller owns the one-row layout |
| 1063 | /// reservation so the header never masquerades as `top` or displaces the |
| 1064 | /// newest tail line. |
| 1065 | fn scrolled_user_prompt_pin( |
| 1066 | history: &[HistoryCell], |
| 1067 | line_meta: &[TranscriptLineMeta], |
| 1068 | collapsed_cell_map: &[usize], |
| 1069 | top: usize, |
| 1070 | width: u16, |
| 1071 | ) -> Option<(Line<'static>, usize)> { |
| 1072 | if width == 0 || top == 0 { |
| 1073 | return None; |
| 1074 | } |
| 1075 | // First rendered line of a non-blank user cell, as an original history |
| 1076 | // index. Only `line_in_cell == 0` matches: later lines of a long prompt |
| 1077 | // are its body, not the message start. |
| 1078 | let user_first_line = |meta: &TranscriptLineMeta| -> Option<usize> { |
| 1079 | let TranscriptLineMeta::CellLine { |
| 1080 | cell_index, |
| 1081 | line_in_cell: 0, |
| 1082 | .. |
| 1083 | } = meta |
| 1084 | else { |
| 1085 | return None; |
| 1086 | }; |
| 1087 | let original = collapsed_cell_map |
| 1088 | .get(*cell_index) |
| 1089 | .copied() |
| 1090 | .unwrap_or(*cell_index); |
| 1091 | // Only a prompt with renderable first-line text can head the pin. A |
| 1092 | // message that opens on a blank line is skipped here, not rejected |
| 1093 | // later, so the scan keeps walking to an older message that can head |
| 1094 | // the header instead of dropping out (review follow-up). |
| 1095 | let content = match history.get(original) { |
| 1096 | Some(HistoryCell::User { content }) => content, |
| 1097 | _ => return None, |
| 1098 | }; |
| 1099 | if content.lines().next().unwrap_or("").trim().is_empty() { |
| 1100 | return None; |
| 1101 | } |
| 1102 | Some(original) |
| 1103 | }; |
| 1104 | // Newest user message whose start sits above the viewport's top row, |
| 1105 | // scanned newest-first so a long prompt that began several screens up |
| 1106 | // still resolves to its own first line. A prompt whose first line is |
| 1107 | // exactly the top row belongs to the screen, not the header, so the |
| 1108 | // hand-over happens the instant it enters. |
| 1109 | let orig_idx = line_meta.iter().take(top).rev().find_map(user_first_line)?; |
| 1110 | let content = match history.get(orig_idx) { |
| 1111 | Some(HistoryCell::User { content }) => content, |
| 1112 | _ => return None, |
| 1113 | }; |
| 1114 | |
| 1115 | let first = content.lines().next().unwrap_or("").trim(); |
| 1116 | if first.is_empty() { |
| 1117 | return None; |
| 1118 | } |
| 1119 | let budget = usize::from(width.saturating_sub(4)).max(1); |
| 1120 | let mut shown = String::new(); |
| 1121 | let mut used = 0usize; |
| 1122 | for ch in first.chars() { |
| 1123 | let w = UnicodeWidthChar::width(ch).unwrap_or(0); |
| 1124 | if used + w > budget { |
| 1125 | break; |
| 1126 | } |
| 1127 | shown.push(ch); |
| 1128 | used += w; |
| 1129 | } |
| 1130 | if used < UnicodeWidthStr::width(first) && !shown.is_empty() { |
| 1131 | shown.push('…'); |
| 1132 | } |
| 1133 | |
| 1134 | Some(( |
| 1135 | Line::from(vec![ |
| 1136 | Span::styled( |
| 1137 | format!("{} ", codewhale_tui_kit::glyphs::USER), |
| 1138 | Style::default() |
| 1139 | .fg(palette::WHALE_HUMAN) |
| 1140 | .add_modifier(Modifier::BOLD), |
| 1141 | ), |
| 1142 | Span::styled(shown, Style::default().fg(palette::TEXT_PRIMARY)), |
| 1143 | ]), |
| 1144 | orig_idx, |
| 1145 | )) |
| 1146 | } |
| 1147 | |
| 1148 | impl ChatWidget { |
| 1149 | fn viewport(&self) -> codewhale_ratatui::TranscriptViewport<'_> { |
| 1150 | use codewhale_ratatui::{TranscriptViewport, TranscriptViewportStyles}; |
| 1151 | let background = Style::default().bg(self.background); |
| 1152 | TranscriptViewport { |
| 1153 | rows: &self.lines, |
| 1154 | pinned_rows: self.transcript_area.y.saturating_sub(self.content_area.y), |
| 1155 | style: background, |
| 1156 | fill: true, |
| 1157 | ascii: crate::tui::color_compat::ascii_safe_enabled(), |
| 1158 | scrollbar: self.scrollbar, |
| 1159 | jump_to_latest: self.jump_to_latest_button.is_some(), |
| 1160 | styles: TranscriptViewportStyles { |
| 1161 | background, |
| 1162 | track: Style::default().fg(self.scroll_track), |
| 1163 | thumb: Style::default().fg(self.scroll_thumb), |
| 1164 | jump_border: Style::default().fg(self.jump_border), |
| 1165 | jump_arrow: Style::default().fg(self.jump_arrow), |
| 1166 | }, |
| 1167 | ..TranscriptViewport::new(&self.lines) |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | |
| 1172 | impl Renderable for ChatWidget { |
| 1173 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 1174 | debug_assert_eq!( |
| 1175 | area, self.content_area, |
| 1176 | "ChatWidget content_area drifted from render area" |
| 1177 | ); |
| 1178 | let plan = self.viewport().render_content(area, buf); |
| 1179 | // The kit guarded background pass stays between content and chrome. |
| 1180 | self.render_underwater_field(plan.area, buf); |
| 1181 | plan.paint_chrome(buf); |
| 1182 | let regions = codewhale_tui_kit::osc8::link_regions_for_plan(&plan, &self.line_links); |
| 1183 | for region in ®ions { |
| 1184 | let hit = Rect::new( |
| 1185 | region.col_start, |
| 1186 | region.row, |
| 1187 | region |
| 1188 | .col_end |
| 1189 | .saturating_sub(region.col_start) |
| 1190 | .saturating_add(1), |
| 1191 | 1, |
| 1192 | ); |
| 1193 | crate::tui::hover_layer::register_rect( |
| 1194 | crate::tui::hover_hit::HoverTargetKind::Link, |
| 1195 | hit, |
| 1196 | region.target.clone(), |
| 1197 | true, |
| 1198 | ); |
| 1199 | } |
| 1200 | codewhale_tui_kit::osc8::set_frame_links(regions); |
| 1201 | } |
| 1202 | fn desired_height(&self, _width: u16) -> u16 { |
| 1203 | 1 |
| 1204 | } |
| 1205 | } |
| 1206 | |
| 1207 | impl ChatWidget { |
| 1208 | /// Paint the explicitly selected underwater field. Flat keeps the theme |
| 1209 | /// surface, Solarized Light keeps canonical Base3, and Terminal keeps its |
| 1210 | /// inherited background without inherited aquarium decoration. |
| 1211 | fn render_underwater_field(&self, area: Rect, buf: &mut Buffer) { |
| 1212 | if let Some(column) = self.ocean_column { |
| 1213 | // Cache per-row ocean colors; invalidate only on phase/size/breath. |
| 1214 | let phase_tag = column.phase_tag(); |
| 1215 | let fingerprint = column.ramp_fingerprint(); |
| 1216 | let ramp = crate::tui::ambient_life::frame_ocean_ramp( |
| 1217 | &column, |
| 1218 | area.height, |
| 1219 | area.y, |
| 1220 | self.ocean_elapsed_ms, |
| 1221 | phase_tag, |
| 1222 | fingerprint, |
| 1223 | ); |
| 1224 | let facts = codewhale_ratatui::ocean::OceanPaintFacts { |
| 1225 | ground: self.background, |
| 1226 | sample_top: area.y, |
| 1227 | samples: &ramp, |
| 1228 | protected: &self.ocean_protected, |
| 1229 | }; |
| 1230 | column.paint_native(area, buf, &self.ocean_paint_theme, &facts); |
| 1231 | } |
| 1232 | |
| 1233 | if self.ambient_life |
| 1234 | && let (Some(ink), Some(column)) = (self.ambient_ink, self.ocean_column) |
| 1235 | && let Some(theme) = column.paint_theme(self.background) |
| 1236 | { |
| 1237 | let whale = crate::tui::ambient_life::WhaleCameo { |
| 1238 | elapsed_ms: column.completion_elapsed_ms(), |
| 1239 | anchor_x: area.x.saturating_add(area.width / 2), |
| 1240 | anchor_y: area.y.saturating_add(area.height.saturating_mul(2) / 3), |
| 1241 | }; |
| 1242 | let _ambient_stats = crate::tui::ambient_life::render_ambient_life( |
| 1243 | area, |
| 1244 | buf, |
| 1245 | &theme, |
| 1246 | ink, |
| 1247 | &self.lines, |
| 1248 | self.life_elapsed_ms, |
| 1249 | self.ocean_presence_f32(), |
| 1250 | whale, |
| 1251 | self.ocean_activity, |
| 1252 | &self.ocean_protected, |
| 1253 | ); |
| 1254 | } |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | impl ChatWidget { |
| 1259 | /// Life presence as a 0..=1 fraction; drives ambient-life ink fading. |
| 1260 | fn ocean_presence_f32(&self) -> f32 { |
| 1261 | self.ambient_presence.clamp(0.0, 1.0) |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | #[cfg(test)] |
| 1266 | fn fish_mark(facing_right: bool) -> &'static str { |
| 1267 | if facing_right { "><>" } else { "<><" } |
| 1268 | } |
| 1269 | |
| 1270 | #[cfg(test)] |
| 1271 | fn fish_heading(previous_x: u16, current_x: u16, next_x: u16, fallback_right: bool) -> bool { |
| 1272 | if next_x != current_x { |
| 1273 | next_x > current_x |
| 1274 | } else if current_x != previous_x { |
| 1275 | current_x > previous_x |
| 1276 | } else { |
| 1277 | fallback_right |
| 1278 | } |
| 1279 | } |
| 1280 | |
| 1281 | #[cfg(test)] |
| 1282 | const COMPOSER_PANEL_MIN_WIDTH: u16 = codewhale_ratatui::NATIVE_COMPOSER_PANEL_MIN_WIDTH; |
| 1283 | |
| 1284 | /// Existing configuration remains host authority; all geometry is kit-owned. |
| 1285 | pub(crate) fn composer_enclosure_enabled(app: &App) -> bool { |
| 1286 | app.composer_border |
| 1287 | } |
| 1288 | pub(crate) fn active_composer_submit_rect(app: &App, area: Rect) -> Option<Rect> { |
| 1289 | if !app.composer_shows_send() { |
| 1290 | return None; |
| 1291 | } |
| 1292 | codewhale_ratatui::native_composer_geometry(area, composer_enclosure_enabled(app), false).submit |
| 1293 | } |
| 1294 | #[cfg(test)] |
| 1295 | fn enclosed_composer_panel_fits(enclosed: bool, width: u16, height: u16) -> bool { |
| 1296 | codewhale_ratatui::native_composer_geometry(Rect::new(0, 0, width, height), enclosed, false) |
| 1297 | .submit |
| 1298 | .is_some() |
| 1299 | } |
| 1300 | #[cfg(test)] |
| 1301 | fn composer_inner_area(area: Rect, panel: bool) -> Rect { |
| 1302 | codewhale_ratatui::native_composer_geometry(area, panel, false).inner |
| 1303 | } |
| 1304 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1305 | pub(crate) struct ComposerContentGeometry { |
| 1306 | pub(crate) text_area: Rect, |
| 1307 | #[cfg(test)] |
| 1308 | pub(crate) prompt_inset: u16, |
| 1309 | } |
| 1310 | impl ComposerContentGeometry { |
| 1311 | pub(crate) fn text_width(self) -> usize { |
| 1312 | usize::from(self.text_area.width.max(1)) |
| 1313 | } |
| 1314 | } |
| 1315 | pub(crate) fn composer_content_geometry(inner: Rect, history: bool) -> ComposerContentGeometry { |
| 1316 | let (text_area, _prompt_inset) = |
| 1317 | codewhale_ratatui::native_composer_content_geometry(inner, history); |
| 1318 | ComposerContentGeometry { |
| 1319 | text_area, |
| 1320 | #[cfg(test)] |
| 1321 | prompt_inset: _prompt_inset, |
| 1322 | } |
| 1323 | } |
| 1324 | fn composer_native_density(density: ComposerDensity) -> codewhale_ratatui::NativeComposerDensity { |
| 1325 | match density { |
| 1326 | ComposerDensity::Compact => codewhale_ratatui::NativeComposerDensity::Compact, |
| 1327 | ComposerDensity::Comfortable => codewhale_ratatui::NativeComposerDensity::Comfortable, |
| 1328 | ComposerDensity::Spacious => codewhale_ratatui::NativeComposerDensity::Spacious, |
| 1329 | } |
| 1330 | } |
| 1331 | |
| 1332 | pub struct ComposerWidget<'a> { |
| 1333 | app: &'a App, |
| 1334 | max_height: u16, |
| 1335 | slash_menu_entries: &'a [SlashMenuEntry], |
| 1336 | mention_menu_entries: &'a [String], |
| 1337 | } |
| 1338 | |
| 1339 | impl<'a> ComposerWidget<'a> { |
| 1340 | pub fn new( |
| 1341 | app: &'a App, |
| 1342 | max_height: u16, |
| 1343 | slash_menu_entries: &'a [SlashMenuEntry], |
| 1344 | mention_menu_entries: &'a [String], |
| 1345 | ) -> Self { |
| 1346 | Self { |
| 1347 | app, |
| 1348 | max_height, |
| 1349 | slash_menu_entries, |
| 1350 | mention_menu_entries, |
| 1351 | } |
| 1352 | } |
| 1353 | |
| 1354 | /// Number of popup rows below the input. Mention and slash menus are |
| 1355 | /// mutually exclusive — the cursor can only sit inside an `@token` OR |
| 1356 | /// a `/cmd` token, not both at once. Mention takes precedence because |
| 1357 | /// the partial-mention check is positional and stricter than slash's |
| 1358 | /// "starts-with-/" check. |
| 1359 | fn active_menu_row_count(&self) -> usize { |
| 1360 | if self.app.is_history_search_active() { |
| 1361 | self.app.history_search_matches().len().max(1) |
| 1362 | } else if !self.mention_menu_entries.is_empty() { |
| 1363 | self.mention_menu_entries.len() |
| 1364 | } else { |
| 1365 | self.slash_menu_entries.len() |
| 1366 | } |
| 1367 | } |
| 1368 | |
| 1369 | /// Row reservation passed to `composer_height`. When the slash- or |
| 1370 | /// mention-menu is active we lock the composer to its worst-case |
| 1371 | /// envelope so the chat area above doesn't repaint every keystroke |
| 1372 | /// as the matched-entry count shrinks. Pure cosmetic: the menu |
| 1373 | /// itself still renders its actual entries — the extra rows are |
| 1374 | /// just panel padding inside the same Rect. |
| 1375 | /// |
| 1376 | /// Reported on Windows 10 PowerShell + WSL where the console |
| 1377 | /// backend's per-cell write cost makes the layout jitter visible |
| 1378 | /// even though the work is tiny on Unix terminals. See user |
| 1379 | /// feedback in v0.8.8 polish thread. |
| 1380 | pub fn active_menu_reserved_rows(&self) -> usize { |
| 1381 | let actual = self.active_menu_row_count(); |
| 1382 | if actual == 0 { |
| 1383 | return 0; |
| 1384 | } |
| 1385 | if self.app.is_history_search_active() { |
| 1386 | return actual; |
| 1387 | } |
| 1388 | // Slash- and mention-menu are the cases that grow/shrink mid-typing. |
| 1389 | // Reserve the composer's panel-max so the layout stays stable |
| 1390 | // for the lifetime of the menu session. |
| 1391 | actual.max(usize::from(self.max_height_cap())) |
| 1392 | } |
| 1393 | |
| 1394 | fn wants_enclosed_panel(&self) -> bool { |
| 1395 | composer_enclosure_enabled(self.app) |
| 1396 | } |
| 1397 | |
| 1398 | #[cfg(test)] |
| 1399 | pub(crate) fn has_panel(&self, area: Rect) -> bool { |
| 1400 | enclosed_composer_panel_fits(self.wants_enclosed_panel(), area.width, area.height) |
| 1401 | } |
| 1402 | |
| 1403 | /// The border- and submit-aware input rectangle shared by rendering, |
| 1404 | /// cursor mapping, and the frame's persistent mouse geometry. |
| 1405 | #[cfg(test)] |
| 1406 | pub(crate) fn inner_area(&self, area: Rect) -> Rect { |
| 1407 | composer_inner_area(area, self.has_panel(area)) |
| 1408 | } |
| 1409 | |
| 1410 | fn owns_focus(&self) -> bool { |
| 1411 | use crate::tui::shell_key_routing::Focus; |
| 1412 | match self.app.focus() { |
| 1413 | Focus::Composer => true, |
| 1414 | Focus::Launch => self.app.launch.menu_selected.is_none(), |
| 1415 | _ => false, |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | fn max_height_cap(&self) -> u16 { |
| 1420 | composer_max_height(self.app.composer_density) |
| 1421 | } |
| 1422 | /// Project host semantics, menu filtering and styles; the kit owns every |
| 1423 | /// row, source index, caret, viewport and pointer rectangle below them. |
| 1424 | fn frame(&self, clipped: bool) -> codewhale_ratatui::NativeComposerFrame<'_> { |
| 1425 | use codewhale_ratatui::{ |
| 1426 | NativeComposerFrame, NativeComposerMenu, NativeComposerMenuItem, NativeComposerStyles, |
| 1427 | }; |
| 1428 | let history = self.app.is_history_search_active(); |
| 1429 | let input = self.app.composer_display_input(); |
| 1430 | let placeholder = if let Some(suggestion) = &self.app.prompt_suggestion |
| 1431 | && !history |
| 1432 | { |
| 1433 | Line::styled( |
| 1434 | suggestion.clone(), |
| 1435 | Style::default().fg(self.app.ui_theme.text_soft), |
| 1436 | ) |
| 1437 | } else { |
| 1438 | Line::styled( |
| 1439 | composer_empty_hint_text(self.app), |
| 1440 | Style::default().fg(self.app.ui_theme.text_body), |
| 1441 | ) |
| 1442 | }; |
| 1443 | let hint = if history { |
| 1444 | Some(Line::from(vec![ |
| 1445 | Span::styled( |
| 1446 | format!(" {} ", self.app.tr(MessageId::HistoryHintMove)), |
| 1447 | Style::default().fg(palette::TEXT_MUTED), |
| 1448 | ), |
| 1449 | Span::styled( |
| 1450 | format!("{} ", self.app.tr(MessageId::HistoryHintAccept)), |
| 1451 | Style::default().fg(palette::TEXT_MUTED), |
| 1452 | ), |
| 1453 | Span::styled( |
| 1454 | self.app.tr(MessageId::HistoryHintRestore), |
| 1455 | Style::default().fg(palette::TEXT_MUTED), |
| 1456 | ), |
| 1457 | ])) |
| 1458 | } else if !self.slash_menu_entries.is_empty() { |
| 1459 | Some(Line::styled( |
| 1460 | self.app.tr(MessageId::ComposerSlashMenuHint), |
| 1461 | Style::default().fg(self.app.ui_theme.text_hint), |
| 1462 | )) |
| 1463 | } else if !input.trim().is_empty() { |
| 1464 | composer_submit_hint(self.app, clipped).map(|hint| { |
| 1465 | Line::styled(format!(" {} ", hint.text), Style::default().fg(hint.color)) |
| 1466 | }) |
| 1467 | } else { |
| 1468 | None |
| 1469 | }; |
| 1470 | let top_title = history.then(|| { |
| 1471 | Line::styled( |
| 1472 | format!(" {} ", self.app.tr(MessageId::HistorySearchTitle)), |
| 1473 | Style::default().fg(palette::TEXT_MUTED), |
| 1474 | ) |
| 1475 | }); |
| 1476 | let top_right = crate::tui::agent_focus::composer_chip_text(self.app).map(|chip| { |
| 1477 | Line::styled( |
| 1478 | format!(" {chip} "), |
| 1479 | Style::default() |
| 1480 | .fg(self.app.ui_theme.accent_action) |
| 1481 | .add_modifier(Modifier::BOLD), |
| 1482 | ) |
| 1483 | }); |
| 1484 | let mut menu = NativeComposerMenu { |
| 1485 | reserved_rows: self.active_menu_reserved_rows(), |
| 1486 | ..Default::default() |
| 1487 | }; |
| 1488 | let menu_line = |label: String, selected: bool| { |
| 1489 | let style = if selected { |
| 1490 | menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 1491 | } else { |
| 1492 | Style::default().fg(palette::TEXT_MUTED) |
| 1493 | }; |
| 1494 | NativeComposerMenuItem::Line(Line::from(vec![ |
| 1495 | Span::raw(" "), |
| 1496 | Span::styled(codewhale_tui_kit::glyphs::selection_marker(selected), style), |
| 1497 | Span::styled(" ", style), |
| 1498 | Span::styled(label, style), |
| 1499 | ])) |
| 1500 | }; |
| 1501 | if history { |
| 1502 | let entries = self.app.history_search_matches(); |
| 1503 | menu.selected = self |
| 1504 | .app |
| 1505 | .history_search_selected_index() |
| 1506 | .min(entries.len().saturating_sub(1)); |
| 1507 | if entries.is_empty() { |
| 1508 | menu.items.push(NativeComposerMenuItem::Line(Line::styled( |
| 1509 | self.app.tr(MessageId::HistoryNoMatches), |
| 1510 | Style::default().fg(palette::TEXT_MUTED), |
| 1511 | ))) |
| 1512 | } else { |
| 1513 | menu.items = entries |
| 1514 | .iter() |
| 1515 | .enumerate() |
| 1516 | .map(|(index, label)| menu_line(label.clone(), index == menu.selected)) |
| 1517 | .collect(); |
| 1518 | } |
| 1519 | } else if !self.mention_menu_entries.is_empty() { |
| 1520 | menu.selected = self |
| 1521 | .app |
| 1522 | .mention_menu_selected |
| 1523 | .min(self.mention_menu_entries.len().saturating_sub(1)); |
| 1524 | menu.items = self |
| 1525 | .mention_menu_entries |
| 1526 | .iter() |
| 1527 | .enumerate() |
| 1528 | .map(|(index, label)| menu_line(format!("@{label}"), index == menu.selected)) |
| 1529 | .collect(); |
| 1530 | } else { |
| 1531 | menu.pointer_rows = true; |
| 1532 | menu.selected = self |
| 1533 | .app |
| 1534 | .slash_menu_selected |
| 1535 | .min(self.slash_menu_entries.len().saturating_sub(1)); |
| 1536 | menu.items = self |
| 1537 | .slash_menu_entries |
| 1538 | .iter() |
| 1539 | .enumerate() |
| 1540 | .map(|(index, entry)| { |
| 1541 | let selected = index == menu.selected; |
| 1542 | let style = if selected { |
| 1543 | menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 1544 | } else { |
| 1545 | Style::default().fg(palette::TEXT_MUTED) |
| 1546 | }; |
| 1547 | let name_style = if entry.is_skill && !selected { |
| 1548 | Style::default().fg(palette::WHALE_ACTION) |
| 1549 | } else { |
| 1550 | style |
| 1551 | }; |
| 1552 | let description_style = if selected { |
| 1553 | menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 1554 | } else { |
| 1555 | Style::default().fg(palette::TEXT_DIM) |
| 1556 | }; |
| 1557 | NativeComposerMenuItem::Columns { |
| 1558 | name: entry |
| 1559 | .alias_hint |
| 1560 | .as_ref() |
| 1561 | .map(|hint| format!("{} or /{hint}", entry.name)) |
| 1562 | .unwrap_or_else(|| entry.name.clone()), |
| 1563 | description: entry.description.clone(), |
| 1564 | prefix: Span::styled(if entry.is_skill { "✦" } else { " " }, name_style), |
| 1565 | marker: Span::styled( |
| 1566 | codewhale_tui_kit::glyphs::selection_marker(selected), |
| 1567 | style, |
| 1568 | ), |
| 1569 | name_style, |
| 1570 | description_style, |
| 1571 | } |
| 1572 | }) |
| 1573 | .collect(); |
| 1574 | } |
| 1575 | let background = Style::default().bg(self.app.ui_theme.composer_bg); |
| 1576 | let can_submit = self.app.composer_shows_send(); |
| 1577 | let theme = &self.app.ui_theme; |
| 1578 | let focused = self.owns_focus(); |
| 1579 | let chat_color = if focused { |
| 1580 | composer_chat_color(self.app) |
| 1581 | } else { |
| 1582 | None |
| 1583 | }; |
| 1584 | let border = crate::tui::ui::motion::composer_live_border(self.app) |
| 1585 | .or(chat_color) |
| 1586 | .unwrap_or(theme.border); |
| 1587 | let prompt = if focused { |
| 1588 | Style::default() |
| 1589 | .fg(chat_color.unwrap_or(theme.accent_primary)) |
| 1590 | .bold() |
| 1591 | } else { |
| 1592 | Style::default().fg(theme.text_muted) |
| 1593 | }; |
| 1594 | let submit = if can_submit { |
| 1595 | palette::chrome_style(theme, palette::ChromeInk::Info).bold() |
| 1596 | } else { |
| 1597 | Style::default() |
| 1598 | }; |
| 1599 | NativeComposerFrame { |
| 1600 | text: Cow::Borrowed(input), |
| 1601 | cursor: self.app.composer_display_cursor(), |
| 1602 | selection: self.app.selection_range(), |
| 1603 | placeholder, |
| 1604 | enclosed: self.wants_enclosed_panel(), |
| 1605 | density: composer_native_density(self.app.composer_density), |
| 1606 | history_search: history, |
| 1607 | focused: true, |
| 1608 | can_submit, |
| 1609 | ascii: crate::tui::color_compat::ascii_safe_enabled(), |
| 1610 | top_title, |
| 1611 | top_right, |
| 1612 | hint, |
| 1613 | quiet_hint: if input.trim().is_empty() { |
| 1614 | None |
| 1615 | } else { |
| 1616 | composer_submit_hint(self.app, clipped).map(|hint| { |
| 1617 | Line::styled(format!(" {} ", hint.text), Style::default().fg(hint.color)) |
| 1618 | }) |
| 1619 | }, |
| 1620 | menu, |
| 1621 | styles: NativeComposerStyles { |
| 1622 | background, |
| 1623 | border: Style::default().fg(border), |
| 1624 | quiet_border: Style::default().fg(self.app.ui_theme.border), |
| 1625 | text: Style::default().fg(theme.text_body), |
| 1626 | selection: Style::default() |
| 1627 | .fg(theme.text_body) |
| 1628 | .bg(self.app.ui_theme.selection_bg), |
| 1629 | prompt, |
| 1630 | submit, |
| 1631 | }, |
| 1632 | } |
| 1633 | } |
| 1634 | |
| 1635 | pub(crate) fn plan(&self, area: Rect) -> codewhale_ratatui::NativeComposerPlan { |
| 1636 | let frame = self.frame(false); |
| 1637 | let source = frame.source_plan(area); |
| 1638 | if source.rows.len() > frame.input_rows_budget(area) |
| 1639 | && frame.hint.is_none() |
| 1640 | && frame.quiet_hint.is_none() |
| 1641 | && composer_submit_hint(self.app, true).is_some() |
| 1642 | { |
| 1643 | self.frame(true).plan_with_source(area, source) |
| 1644 | } else { |
| 1645 | frame.plan_with_source(area, source) |
| 1646 | } |
| 1647 | } |
| 1648 | |
| 1649 | fn paint_ocean_composer_surface( |
| 1650 | &self, |
| 1651 | plan: &codewhale_ratatui::NativeComposerPlan, |
| 1652 | buf: &mut Buffer, |
| 1653 | ) { |
| 1654 | let area = plan.area; |
| 1655 | use codewhale_ratatui::color::{ColorDepth, blend, mix_oklab}; |
| 1656 | let Some(caps) = self.app.viewport.ocean_caps else { |
| 1657 | return; |
| 1658 | }; |
| 1659 | if self.app.theme_id != palette::ThemeId::Underwater |
| 1660 | || area.width < 4 |
| 1661 | || area.height < 2 |
| 1662 | || caps.ascii |
| 1663 | || !matches!(caps.depth, ColorDepth::TrueColor | ColorDepth::Ansi256) |
| 1664 | { |
| 1665 | return; |
| 1666 | } |
| 1667 | let theme = &self.app.ui_theme; |
| 1668 | let body = theme.composer_bg; |
| 1669 | let home = self.app.launch.visible |
| 1670 | && !self.app.is_loading |
| 1671 | && self.app.launch.dissolve_started_ms.is_none() |
| 1672 | && self.app.composer_display_input().is_empty() |
| 1673 | && !self.app.is_history_search_active() |
| 1674 | && self.app.agent_focus.is_none() |
| 1675 | && plan.geometry.submit.is_some() |
| 1676 | && caps.depth == ColorDepth::TrueColor; |
| 1677 | if !home { |
| 1678 | crate::tui::composer_chrome::paint_waterline(area, buf, theme); |
| 1679 | return; |
| 1680 | } |
| 1681 | let lip = mix_oklab( |
| 1682 | body, |
| 1683 | theme.accent_secondary, |
| 1684 | if self.owns_focus() { 0.23 } else { 0.11 }, |
| 1685 | ); |
| 1686 | let shadow = mix_oklab(body, theme.footer_bg, 0.75); |
| 1687 | let left = area.left(); |
| 1688 | let right = area.right() - 1; |
| 1689 | let top = area.top(); |
| 1690 | let bottom = area.bottom() - 1; |
| 1691 | for x in left..=right { |
| 1692 | let (upper, lower) = if x == left { |
| 1693 | ("▗", "▝") |
| 1694 | } else if x == right { |
| 1695 | ("▖", "▘") |
| 1696 | } else { |
| 1697 | ("▄", "▀") |
| 1698 | }; |
| 1699 | let weight = f32::from(right - x) / f32::from(area.width - 1); |
| 1700 | buf[(x, top)] |
| 1701 | .set_symbol(upper) |
| 1702 | .set_fg(blend(lip, body, weight)) |
| 1703 | .set_bg(theme.surface_bg); |
| 1704 | buf[(x, bottom)] |
| 1705 | .set_symbol(lower) |
| 1706 | .set_fg(body) |
| 1707 | .set_bg(shadow); |
| 1708 | } |
| 1709 | for y in top + 1..bottom { |
| 1710 | for x in [left, right] { |
| 1711 | buf[(x, y)].set_symbol(" ").set_bg(body); |
| 1712 | } |
| 1713 | } |
| 1714 | } |
| 1715 | |
| 1716 | /// Publish pointer targets from the same plan that actually painted. |
| 1717 | pub(crate) fn render_plan( |
| 1718 | &self, |
| 1719 | area: Rect, |
| 1720 | buf: &mut Buffer, |
| 1721 | ) -> codewhale_ratatui::NativeComposerPlan { |
| 1722 | let plan = self.plan(area.intersection(buf.area)); |
| 1723 | plan.paint(buf); |
| 1724 | self.paint_ocean_composer_surface(&plan, buf); |
| 1725 | if let Some(submit) = plan.geometry.submit |
| 1726 | && !self.app.composer_shows_send() |
| 1727 | { |
| 1728 | for x in submit.left()..submit.right() { |
| 1729 | buf[(x, submit.y)].set_symbol(" "); |
| 1730 | } |
| 1731 | } |
| 1732 | *self.app.viewport.last_slash_menu_hitboxes.borrow_mut() = plan.menu_rects.clone(); |
| 1733 | for (rect, label) in &plan.truncated { |
| 1734 | crate::tui::hover_layer::register_rect( |
| 1735 | crate::tui::hover_hit::HoverTargetKind::TruncatedText, |
| 1736 | *rect, |
| 1737 | label.clone(), |
| 1738 | false, |
| 1739 | ); |
| 1740 | } |
| 1741 | plan |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | impl Renderable for ComposerWidget<'_> { |
| 1746 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 1747 | self.render_plan(area, buf); |
| 1748 | } |
| 1749 | fn desired_height(&self, width: u16) -> u16 { |
| 1750 | self.frame(false).desired_height(width, self.max_height) |
| 1751 | } |
| 1752 | #[cfg(test)] |
| 1753 | fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> { |
| 1754 | self.plan(area).cursor.map(|pos| (pos.x, pos.y)) |
| 1755 | } |
| 1756 | } |
| 1757 | |
| 1758 | /// Compact, bottom-anchored approval card. |
| 1759 | /// |
| 1760 | /// The widget reads its selected option and locale directly from the |
| 1761 | /// [`ApprovalView`]. Rendering preserves transcript context while reserving |
| 1762 | /// the complete action set and at least one load-bearing command/preview row |
| 1763 | /// on ordinary terminal sizes. |
| 1764 | pub struct ApprovalWidget<'a> { |
| 1765 | request: &'a ApprovalRequest, |
| 1766 | view: &'a ApprovalView, |
| 1767 | } |
| 1768 | |
| 1769 | struct ScopeMenuRow { |
| 1770 | option: Option<ApprovalOption>, |
| 1771 | is_save_preview: bool, |
| 1772 | line: Line<'static>, |
| 1773 | } |
| 1774 | |
| 1775 | impl<'a> ApprovalWidget<'a> { |
| 1776 | pub fn new(request: &'a ApprovalRequest, view: &'a ApprovalView) -> Self { |
| 1777 | Self { request, view } |
| 1778 | } |
| 1779 | |
| 1780 | pub(crate) fn docked_height(&self, _width: u16) -> u16 { |
| 1781 | 1 |
| 1782 | } |
| 1783 | |
| 1784 | fn edge_style(&self) -> (Color, Color, Color) { |
| 1785 | let stakes = self.request.stakes(); |
| 1786 | let colors = if self.request.is_repo_law_prompt() { |
| 1787 | repo_law_approval_palette() |
| 1788 | } else { |
| 1789 | approval_palette(stakes) |
| 1790 | }; |
| 1791 | (colors.border, colors.accent, colors.shortcut) |
| 1792 | } |
| 1793 | |
| 1794 | fn edge_glyph(&self, ascii: bool) -> &'static str { |
| 1795 | if self.request.is_repo_law_prompt() |
| 1796 | || self.request.stakes() == crate::tui::approval::ApprovalStakes::Critical |
| 1797 | { |
| 1798 | if ascii { "| ! " } else { "┃ ! " } |
| 1799 | } else if ascii { |
| 1800 | "| * " |
| 1801 | } else { |
| 1802 | "┃ ⛯ " |
| 1803 | } |
| 1804 | } |
| 1805 | |
| 1806 | fn drawer_edge_glyph(&self, ascii: bool) -> &'static str { |
| 1807 | if ascii { "| " } else { "┃ " } |
| 1808 | } |
| 1809 | |
| 1810 | fn scope_menu_rows(&self, width: u16) -> Vec<ScopeMenuRow> { |
| 1811 | if !self.view.scopes_open || self.view.is_workflow_plan_approval() { |
| 1812 | return Vec::new(); |
| 1813 | } |
| 1814 | let locale = self.view.locale(); |
| 1815 | let ascii = ascii_safe_enabled(); |
| 1816 | let (border_color, edge_color, shortcut_color) = self.edge_style(); |
| 1817 | let drawer_edge = self.drawer_edge_glyph(ascii); |
| 1818 | let mut rows = Vec::with_capacity(6); |
| 1819 | rows.push(ScopeMenuRow { |
| 1820 | option: None, |
| 1821 | is_save_preview: false, |
| 1822 | line: Line::from(vec![ |
| 1823 | Span::styled( |
| 1824 | drawer_edge, |
| 1825 | Style::default().fg(edge_color).add_modifier(Modifier::BOLD), |
| 1826 | ), |
| 1827 | Span::styled("─ Scope ─", Style::default().fg(border_color)), |
| 1828 | ]), |
| 1829 | }); |
| 1830 | |
| 1831 | let mut items: Vec<(ApprovalOption, &str, String)> = vec![ |
| 1832 | (ApprovalOption::ApproveOnce, "[1]", "Allow once".to_string()), |
| 1833 | ( |
| 1834 | ApprovalOption::ApproveAlways, |
| 1835 | "[2]", |
| 1836 | "Allow in this conversation".to_string(), |
| 1837 | ), |
| 1838 | ]; |
| 1839 | if self.request.owner.is_none() && self.request.can_save_allow_rule() { |
| 1840 | items.push(( |
| 1841 | ApprovalOption::AllowExactRepo, |
| 1842 | "[3]", |
| 1843 | "Always allow in this repo".to_string(), |
| 1844 | )); |
| 1845 | } |
| 1846 | |
| 1847 | if self.view.offers_permission_settings() { |
| 1848 | let chord = crate::tui::shell_key_routing::binding( |
| 1849 | crate::tui::shell_key_routing::ShellBindingId::PermissionCycle, |
| 1850 | ) |
| 1851 | .footer_chord; |
| 1852 | items.push(( |
| 1853 | ApprovalOption::OpenPermissions, |
| 1854 | chord, |
| 1855 | format!("{}…", tr(locale, MessageId::ChipPermissionFullAccess)), |
| 1856 | )); |
| 1857 | } |
| 1858 | |
| 1859 | for (option, key_hint, label) in items { |
| 1860 | let is_selected = self.view.scope_selected == option; |
| 1861 | let row_style = if is_selected { |
| 1862 | menu_style::selected_row_style() |
| 1863 | } else { |
| 1864 | Style::default().fg(palette::TEXT_PRIMARY) |
| 1865 | }; |
| 1866 | let hint_style = if is_selected { |
| 1867 | menu_style::selected_row_style() |
| 1868 | } else { |
| 1869 | Style::default().fg(shortcut_color) |
| 1870 | }; |
| 1871 | let marker = codewhale_tui_kit::glyphs::selection_marker(is_selected); |
| 1872 | rows.push(ScopeMenuRow { |
| 1873 | option: Some(option), |
| 1874 | is_save_preview: false, |
| 1875 | line: Line::from(vec![ |
| 1876 | Span::styled( |
| 1877 | drawer_edge, |
| 1878 | Style::default().fg(edge_color).add_modifier(Modifier::BOLD), |
| 1879 | ), |
| 1880 | Span::styled(format!(" {marker} "), row_style), |
| 1881 | Span::styled( |
| 1882 | format!("{key_hint} "), |
| 1883 | hint_style.add_modifier(Modifier::BOLD), |
| 1884 | ), |
| 1885 | Span::styled(label, row_style), |
| 1886 | ]), |
| 1887 | }); |
| 1888 | |
| 1889 | if option == ApprovalOption::AllowExactRepo |
| 1890 | && let Some(preview) = self.request.allow_rule_save_preview() |
| 1891 | { |
| 1892 | let arrow = if ascii { "-> " } else { "↳ " }; |
| 1893 | let indent = " "; |
| 1894 | let prefix_width = drawer_edge.width() + indent.width() + arrow.width(); |
| 1895 | let avail = usize::from(width).saturating_sub(prefix_width); |
| 1896 | if avail > 0 { |
| 1897 | let pattern = preview.pattern_text(); |
| 1898 | let full_preview = if preview.rule_count > 1 && preview.entries.len() > 1 { |
| 1899 | format!( |
| 1900 | "{pattern} (.codewhale/permissions.toml · {})", |
| 1901 | preview.summary(locale) |
| 1902 | ) |
| 1903 | } else { |
| 1904 | format!("{pattern} (.codewhale/permissions.toml)") |
| 1905 | }; |
| 1906 | let wrapped = wrap_text(&full_preview, avail); |
| 1907 | let continuation_pad = " ".repeat(indent.width() + arrow.width()); |
| 1908 | for (line_idx, chunk) in wrapped.into_iter().enumerate() { |
| 1909 | let mut detail_spans = vec![Span::styled( |
| 1910 | drawer_edge, |
| 1911 | Style::default().fg(edge_color).add_modifier(Modifier::BOLD), |
| 1912 | )]; |
| 1913 | if line_idx == 0 { |
| 1914 | detail_spans.push(Span::raw(indent)); |
| 1915 | detail_spans.push(Span::styled( |
| 1916 | arrow, |
| 1917 | Style::default().fg(palette::TEXT_MUTED), |
| 1918 | )); |
| 1919 | } else { |
| 1920 | detail_spans.push(Span::raw(continuation_pad.clone())); |
| 1921 | } |
| 1922 | detail_spans.push(Span::styled( |
| 1923 | chunk, |
| 1924 | Style::default().fg(palette::WHALE_HUMAN), |
| 1925 | )); |
| 1926 | rows.push(ScopeMenuRow { |
| 1927 | option: None, |
| 1928 | is_save_preview: true, |
| 1929 | line: Line::from(detail_spans), |
| 1930 | }); |
| 1931 | } |
| 1932 | } |
| 1933 | } |
| 1934 | } |
| 1935 | rows |
| 1936 | } |
| 1937 | |
| 1938 | fn details_lines(&self, area: Rect) -> Vec<Line<'static>> { |
| 1939 | let stakes = self.request.stakes(); |
| 1940 | let locale = self.view.locale(); |
| 1941 | let ascii = ascii_safe_enabled(); |
| 1942 | let (border_color, edge_color, shortcut_color) = self.edge_style(); |
| 1943 | let drawer_edge = self.drawer_edge_glyph(ascii); |
| 1944 | let critical = matches!(stakes, crate::tui::approval::ApprovalStakes::Critical); |
| 1945 | let repo_law = self.request.is_repo_law_prompt(); |
| 1946 | let mut body: Vec<Line<'static>> = Vec::with_capacity(16); |
| 1947 | |
| 1948 | let chord = crate::tui::shell_key_routing::tool_details_chord(); |
| 1949 | body.push(Line::from(vec![ |
| 1950 | Span::styled( |
| 1951 | drawer_edge, |
| 1952 | Style::default().fg(edge_color).add_modifier(Modifier::BOLD), |
| 1953 | ), |
| 1954 | Span::styled( |
| 1955 | format!("─ Details (Tab/d close · {chord} pager) ─"), |
| 1956 | Style::default().fg(border_color), |
| 1957 | ), |
| 1958 | ])); |
| 1959 | let summary_text = self.request.summary_for_locale(locale); |
| 1960 | if !summary_text.trim().is_empty() { |
| 1961 | body.push(Line::from(vec![ |
| 1962 | Span::raw(" "), |
| 1963 | Span::styled( |
| 1964 | summary_text, |
| 1965 | Style::default() |
| 1966 | .fg(palette::WHALE_ACTION) |
| 1967 | .add_modifier(Modifier::BOLD), |
| 1968 | ), |
| 1969 | ])); |
| 1970 | } |
| 1971 | |
| 1972 | if let Some(owner) = self.request.owner.as_ref() { |
| 1973 | body.push(Line::from(vec![ |
| 1974 | Span::raw(" "), |
| 1975 | Span::styled( |
| 1976 | approval_owner_header(owner, locale), |
| 1977 | Style::default() |
| 1978 | .fg(palette::TEXT_SECONDARY) |
| 1979 | .add_modifier(Modifier::BOLD), |
| 1980 | ), |
| 1981 | ])); |
| 1982 | } |
| 1983 | |
| 1984 | if repo_law { |
| 1985 | body.push(Line::from(vec![ |
| 1986 | Span::raw(" "), |
| 1987 | Span::styled( |
| 1988 | "◆ ", |
| 1989 | Style::default() |
| 1990 | .fg(palette::STATUS_WARNING) |
| 1991 | .add_modifier(Modifier::BOLD), |
| 1992 | ), |
| 1993 | Span::styled( |
| 1994 | tr(locale, MessageId::ApprovalRepoLawWarning), |
| 1995 | Style::default() |
| 1996 | .fg(palette::WHALE_ERROR) |
| 1997 | .add_modifier(Modifier::BOLD), |
| 1998 | ), |
| 1999 | ])); |
| 2000 | body.push(Line::from(vec![ |
| 2001 | Span::raw(" "), |
| 2002 | Span::styled( |
| 2003 | tr(locale, MessageId::ApprovalRepoLawRuleLabel), |
| 2004 | Style::default().fg(palette::TEXT_HINT), |
| 2005 | ), |
| 2006 | Span::styled( |
| 2007 | self.request.description.clone(), |
| 2008 | Style::default().fg(palette::TEXT_SECONDARY), |
| 2009 | ), |
| 2010 | ])); |
| 2011 | } |
| 2012 | |
| 2013 | if self.request.asks_without_git { |
| 2014 | body.push(Line::from(vec![ |
| 2015 | Span::raw(" "), |
| 2016 | Span::styled( |
| 2017 | tr(locale, MessageId::ApprovalAsksWithoutGit), |
| 2018 | Style::default().fg(palette::TEXT_HINT), |
| 2019 | ), |
| 2020 | ])); |
| 2021 | } |
| 2022 | |
| 2023 | let details = self.request.prominent_detail_items(locale); |
| 2024 | if details.is_empty() { |
| 2025 | push_params_detail_line(&mut body, self.request, locale, area.width); |
| 2026 | } else { |
| 2027 | let mut rendered_detail = false; |
| 2028 | for detail in details.iter().take(4) { |
| 2029 | let is_change_preview = detail.is_preview; |
| 2030 | if let Some(shell_lines) = detail.shell_lines.as_deref() { |
| 2031 | let command_width = area.width.saturating_sub(12) as usize; |
| 2032 | let inline_shell_lines = prioritize_inline_shell_lines( |
| 2033 | shell_lines, |
| 2034 | is_change_preview, |
| 2035 | area.height <= 24, |
| 2036 | ); |
| 2037 | let max_rows = if is_change_preview { |
| 2038 | if self.request.intent_summary.is_some() { |
| 2039 | Some(3) |
| 2040 | } else { |
| 2041 | Some(5) |
| 2042 | } |
| 2043 | } else { |
| 2044 | Some(8) |
| 2045 | }; |
| 2046 | push_shell_command_lines( |
| 2047 | &mut body, |
| 2048 | &detail.label, |
| 2049 | &inline_shell_lines, |
| 2050 | command_width.max(20), |
| 2051 | max_rows, |
| 2052 | ); |
| 2053 | } else { |
| 2054 | push_detail_line(&mut body, &detail.label, &detail.value); |
| 2055 | } |
| 2056 | rendered_detail = true; |
| 2057 | } |
| 2058 | if !rendered_detail { |
| 2059 | push_params_detail_line(&mut body, self.request, locale, area.width); |
| 2060 | } |
| 2061 | } |
| 2062 | |
| 2063 | if let Some(ref summary) = self.request.intent_summary { |
| 2064 | let max_width = area.width.saturating_sub(16) as usize; |
| 2065 | if max_width > 0 { |
| 2066 | let intent_label = tr(locale, MessageId::ApprovalIntentLabel); |
| 2067 | let summary_lines: Vec<&str> = summary.lines().collect(); |
| 2068 | let intent_lines = 3usize; |
| 2069 | for (i, sline) in summary_lines.iter().take(intent_lines).enumerate() { |
| 2070 | let prefix = if i == 0 { |
| 2071 | intent_label.clone() |
| 2072 | } else { |
| 2073 | Cow::Borrowed(" ") |
| 2074 | }; |
| 2075 | let truncated = truncate_line_to_width(sline, max_width); |
| 2076 | body.push(Line::from(vec![ |
| 2077 | Span::raw(" "), |
| 2078 | Span::styled( |
| 2079 | prefix, |
| 2080 | if i == 0 { |
| 2081 | Style::default().fg(palette::TEXT_HINT) |
| 2082 | } else { |
| 2083 | Style::default() |
| 2084 | }, |
| 2085 | ), |
| 2086 | Span::styled(truncated, Style::default().fg(palette::TEXT_SECONDARY)), |
| 2087 | ])); |
| 2088 | } |
| 2089 | if summary_lines.len() > intent_lines { |
| 2090 | let more = tr(locale, MessageId::ApprovalMoreLines) |
| 2091 | .replace("{count}", &(summary_lines.len() - intent_lines).to_string()); |
| 2092 | body.push(Line::from(vec![ |
| 2093 | Span::raw(" "), |
| 2094 | Span::styled(more, Style::default().fg(palette::TEXT_HINT)), |
| 2095 | ])); |
| 2096 | } |
| 2097 | } |
| 2098 | } |
| 2099 | |
| 2100 | if critical && self.request.owner.is_none() { |
| 2101 | push_destructive_approval_semantics(&mut body, locale, false); |
| 2102 | } |
| 2103 | |
| 2104 | if critical || details.is_empty() || self.request.review_failure().is_some() { |
| 2105 | body.push(Line::from(vec![ |
| 2106 | Span::raw(" "), |
| 2107 | Span::styled(label_about(locale), Style::default().fg(palette::TEXT_HINT)), |
| 2108 | Span::styled( |
| 2109 | self.request.description_for_locale(locale), |
| 2110 | Style::default().fg(palette::TEXT_BODY), |
| 2111 | ), |
| 2112 | ])); |
| 2113 | } |
| 2114 | if critical { |
| 2115 | for impact in self.request.impacts_for_locale(locale).into_iter().take(4) { |
| 2116 | body.push(Line::from(vec![ |
| 2117 | Span::raw(" "), |
| 2118 | Span::styled( |
| 2119 | label_impact(locale), |
| 2120 | Style::default().fg(palette::TEXT_HINT), |
| 2121 | ), |
| 2122 | Span::styled(impact, Style::default().fg(palette::TEXT_BODY)), |
| 2123 | ])); |
| 2124 | } |
| 2125 | let (cat_label, cat_color) = category_label_for(self.request, locale); |
| 2126 | body.push(Line::from(vec![ |
| 2127 | Span::raw(" "), |
| 2128 | Span::styled(label_type(locale), Style::default().fg(palette::TEXT_HINT)), |
| 2129 | Span::styled( |
| 2130 | cat_label, |
| 2131 | Style::default().fg(cat_color).add_modifier(Modifier::BOLD), |
| 2132 | ), |
| 2133 | ])); |
| 2134 | } |
| 2135 | |
| 2136 | if self.request.can_save_ask_rule() { |
| 2137 | body.push(Line::from(vec![ |
| 2138 | Span::raw(" "), |
| 2139 | Span::styled( |
| 2140 | "[s] ", |
| 2141 | Style::default() |
| 2142 | .fg(shortcut_color) |
| 2143 | .add_modifier(Modifier::BOLD), |
| 2144 | ), |
| 2145 | Span::styled( |
| 2146 | "Ask again next time (.codewhale/permissions.toml)", |
| 2147 | Style::default().fg(palette::TEXT_HINT), |
| 2148 | ), |
| 2149 | ])); |
| 2150 | } |
| 2151 | |
| 2152 | for line in body.iter_mut().skip(1) { |
| 2153 | line.spans.insert( |
| 2154 | 0, |
| 2155 | Span::styled( |
| 2156 | drawer_edge, |
| 2157 | Style::default().fg(edge_color).add_modifier(Modifier::BOLD), |
| 2158 | ), |
| 2159 | ); |
| 2160 | } |
| 2161 | body |
| 2162 | } |
| 2163 | |
| 2164 | fn drawer_height(&self, area: Rect) -> u16 { |
| 2165 | let max_drawer = area.height.saturating_sub(1); |
| 2166 | if max_drawer == 0 { |
| 2167 | return 0; |
| 2168 | } |
| 2169 | if self.view.scopes_open && !self.view.is_workflow_plan_approval() { |
| 2170 | return u16::try_from(self.scope_menu_rows(area.width).len()) |
| 2171 | .unwrap_or(u16::MAX) |
| 2172 | .min(max_drawer); |
| 2173 | } |
| 2174 | if self.view.details_expanded { |
| 2175 | let lines = self.details_lines(area); |
| 2176 | let max_expanded = max_drawer.min(18); |
| 2177 | return u16::try_from(lines.len()) |
| 2178 | .unwrap_or(u16::MAX) |
| 2179 | .min(max_expanded); |
| 2180 | } |
| 2181 | 0 |
| 2182 | } |
| 2183 | |
| 2184 | pub(crate) fn inline_region(&self, area: Rect) -> Rect { |
| 2185 | if area.width == 0 || area.height == 0 { |
| 2186 | return Rect::new(area.x, area.y, area.width, 0); |
| 2187 | } |
| 2188 | let total_height = 1u16 |
| 2189 | .saturating_add(self.drawer_height(area)) |
| 2190 | .min(area.height); |
| 2191 | let y = area.bottom().saturating_sub(total_height); |
| 2192 | Rect::new(area.x, y, area.width, total_height) |
| 2193 | } |
| 2194 | |
| 2195 | fn render_bar( |
| 2196 | &self, |
| 2197 | bar_area: Rect, |
| 2198 | buf: &mut Buffer, |
| 2199 | ) -> (Vec<Rect>, Option<Rect>, Option<Rect>) { |
| 2200 | let ascii = ascii_safe_enabled(); |
| 2201 | let locale = self.view.locale(); |
| 2202 | let (_, edge_color, _) = self.edge_style(); |
| 2203 | let workflow_plan = self.view.is_workflow_plan_approval(); |
| 2204 | let selected_option = if self.view.scopes_open { |
| 2205 | None |
| 2206 | } else { |
| 2207 | Some(ApprovalOption::from_index_for( |
| 2208 | self.request, |
| 2209 | self.view.selected(), |
| 2210 | )) |
| 2211 | }; |
| 2212 | |
| 2213 | let selected_pill = menu_style::selected_row_style().add_modifier(Modifier::REVERSED); |
| 2214 | let wide = bar_area.width >= 100; |
| 2215 | let padded = wide; |
| 2216 | let allow_text = if workflow_plan { |
| 2217 | "Approve" |
| 2218 | } else if wide { |
| 2219 | if ascii { "v Allow" } else { "✓ Allow" } |
| 2220 | } else { |
| 2221 | "Allow" |
| 2222 | }; |
| 2223 | let deny_text = if workflow_plan { |
| 2224 | "Edit" |
| 2225 | } else if wide { |
| 2226 | if ascii { "x Deny" } else { "✕ Deny" } |
| 2227 | } else { |
| 2228 | "Deny" |
| 2229 | }; |
| 2230 | let keyed = |text: &str, option: ApprovalOption, key: &str| { |
| 2231 | let key = if selected_option == Some(option) { |
| 2232 | "Enter" |
| 2233 | } else { |
| 2234 | key |
| 2235 | }; |
| 2236 | if padded { |
| 2237 | format!(" {text} [{key}] ") |
| 2238 | } else { |
| 2239 | format!("{text} [{key}]") |
| 2240 | } |
| 2241 | }; |
| 2242 | |
| 2243 | let allow_label = keyed(allow_text, ApprovalOption::ApproveOnce, "y"); |
| 2244 | let deny_label = keyed( |
| 2245 | deny_text, |
| 2246 | ApprovalOption::Deny, |
| 2247 | if workflow_plan { "e" } else { "n" }, |
| 2248 | ); |
| 2249 | let m_label = if workflow_plan { |
| 2250 | String::new() |
| 2251 | } else if !wide { |
| 2252 | "[m]".to_string() |
| 2253 | } else if self.view.scopes_open { |
| 2254 | if ascii { "[^ m]" } else { "[▴ m]" }.to_string() |
| 2255 | } else { |
| 2256 | if ascii { "[v m]" } else { "[▾ m]" }.to_string() |
| 2257 | }; |
| 2258 | let d_key = if self.view.details_expanded { |
| 2259 | if ascii { "[^ d]" } else { "[▴ d]" } |
| 2260 | } else { |
| 2261 | "[d]" |
| 2262 | }; |
| 2263 | let d_label = if wide { |
| 2264 | format!("Details {d_key}") |
| 2265 | } else { |
| 2266 | d_key.to_string() |
| 2267 | }; |
| 2268 | let cancel_label = if workflow_plan { |
| 2269 | keyed("Cancel", ApprovalOption::Abort, "n") |
| 2270 | } else { |
| 2271 | String::new() |
| 2272 | }; |
| 2273 | |
| 2274 | struct ControlSpec { |
| 2275 | text: String, |
| 2276 | style: Style, |
| 2277 | kind: ControlKind, |
| 2278 | } |
| 2279 | #[derive(Clone, Copy)] |
| 2280 | enum ControlKind { |
| 2281 | OptionIndex(usize), |
| 2282 | Scopes, |
| 2283 | Details, |
| 2284 | } |
| 2285 | |
| 2286 | let mut controls: Vec<ControlSpec> = Vec::with_capacity(5); |
| 2287 | let allow_color = if self.request.risk == RiskLevel::Destructive { |
| 2288 | palette::WHALE_HUMAN |
| 2289 | } else { |
| 2290 | palette::WHALE_ACTION |
| 2291 | }; |
| 2292 | controls.push(ControlSpec { |
| 2293 | text: d_label, |
| 2294 | style: if self.view.details_expanded { |
| 2295 | Style::default() |
| 2296 | .fg(palette::WHALE_HUMAN) |
| 2297 | .add_modifier(Modifier::BOLD) |
| 2298 | } else { |
| 2299 | Style::default().fg(palette::TEXT_MUTED) |
| 2300 | }, |
| 2301 | kind: ControlKind::Details, |
| 2302 | }); |
| 2303 | controls.push(ControlSpec { |
| 2304 | text: allow_label, |
| 2305 | style: if selected_option == Some(ApprovalOption::ApproveOnce) { |
| 2306 | selected_pill |
| 2307 | } else { |
| 2308 | Style::default() |
| 2309 | .fg(allow_color) |
| 2310 | .add_modifier(Modifier::BOLD) |
| 2311 | }, |
| 2312 | kind: ControlKind::OptionIndex(0), |
| 2313 | }); |
| 2314 | if !workflow_plan { |
| 2315 | controls.push(ControlSpec { |
| 2316 | text: m_label, |
| 2317 | style: if self.view.scopes_open { |
| 2318 | Style::default() |
| 2319 | .fg(palette::WHALE_HUMAN) |
| 2320 | .add_modifier(Modifier::BOLD) |
| 2321 | } else { |
| 2322 | Style::default().fg(palette::TEXT_MUTED) |
| 2323 | }, |
| 2324 | kind: ControlKind::Scopes, |
| 2325 | }); |
| 2326 | } |
| 2327 | let deny_index = if workflow_plan { 1 } else { 2 }; |
| 2328 | controls.push(ControlSpec { |
| 2329 | text: deny_label, |
| 2330 | style: if selected_option == Some(ApprovalOption::Deny) { |
| 2331 | selected_pill |
| 2332 | } else { |
| 2333 | Style::default().fg(palette::TEXT_SECONDARY) |
| 2334 | }, |
| 2335 | kind: ControlKind::OptionIndex(deny_index), |
| 2336 | }); |
| 2337 | if workflow_plan { |
| 2338 | controls.push(ControlSpec { |
| 2339 | text: cancel_label, |
| 2340 | style: if selected_option == Some(ApprovalOption::Abort) { |
| 2341 | selected_pill |
| 2342 | } else { |
| 2343 | Style::default().fg(palette::TEXT_MUTED) |
| 2344 | }, |
| 2345 | kind: ControlKind::OptionIndex(2), |
| 2346 | }); |
| 2347 | } |
| 2348 | |
| 2349 | let controls_width: usize = controls |
| 2350 | .iter() |
| 2351 | .map(|c| c.text.width()) |
| 2352 | .sum::<usize>() |
| 2353 | .saturating_add(controls.len().saturating_sub(1)); |
| 2354 | |
| 2355 | let mut left_spans: Vec<Span<'static>> = Vec::with_capacity(6); |
| 2356 | let mut left_used: usize = 0; |
| 2357 | |
| 2358 | let edge = self.edge_glyph(ascii); |
| 2359 | left_used = left_used.saturating_add(edge.width()); |
| 2360 | left_spans.push(Span::styled( |
| 2361 | edge, |
| 2362 | Style::default().fg(edge_color).add_modifier(Modifier::BOLD), |
| 2363 | )); |
| 2364 | |
| 2365 | if let Some(owner) = self.request.owner.as_ref() { |
| 2366 | let tag = format!("[{}] ", visible_text(&owner.label, ascii)); |
| 2367 | left_used = left_used.saturating_add(tag.width()); |
| 2368 | left_spans.push(Span::styled( |
| 2369 | tag, |
| 2370 | Style::default() |
| 2371 | .fg(palette::TEXT_SECONDARY) |
| 2372 | .add_modifier(Modifier::BOLD), |
| 2373 | )); |
| 2374 | } |
| 2375 | |
| 2376 | let risk_label = if self.request.is_repo_law_prompt() { |
| 2377 | Some((Cow::Borrowed("Repo rule"), palette::STATUS_WARNING)) |
| 2378 | } else if self.request.stakes() == crate::tui::approval::ApprovalStakes::Critical { |
| 2379 | Some(( |
| 2380 | tr(locale, MessageId::ApprovalRiskDestructive), |
| 2381 | palette::WHALE_ERROR, |
| 2382 | )) |
| 2383 | } else { |
| 2384 | None |
| 2385 | }; |
| 2386 | if let Some((label, ink)) = risk_label { |
| 2387 | let sep = if ascii { " - " } else { " · " }; |
| 2388 | left_used = left_used.saturating_add(label.width() + sep.width()); |
| 2389 | left_spans.push(Span::styled( |
| 2390 | label, |
| 2391 | Style::default() |
| 2392 | .fg(ink) |
| 2393 | .bg(palette::WHALE_BG) |
| 2394 | .add_modifier(Modifier::BOLD | Modifier::REVERSED), |
| 2395 | )); |
| 2396 | left_spans.push(Span::styled(sep, Style::default().fg(ink))); |
| 2397 | } |
| 2398 | |
| 2399 | let (raw_verb, raw_subject, outside_workspace) = self.request.docked_parts(locale); |
| 2400 | let verb = visible_text(&raw_verb, ascii); |
| 2401 | let subject = visible_text(&raw_subject, ascii); |
| 2402 | |
| 2403 | let total_width = usize::from(bar_area.width); |
| 2404 | let reserved_right = if total_width > controls_width + 2 { |
| 2405 | controls_width + 2 |
| 2406 | } else { |
| 2407 | controls_width.min(total_width) |
| 2408 | }; |
| 2409 | let left_budget = total_width.saturating_sub(reserved_right); |
| 2410 | let permission_hint = format!( |
| 2411 | " {} {}", |
| 2412 | crate::tui::shell_key_routing::binding( |
| 2413 | crate::tui::shell_key_routing::ShellBindingId::PermissionCycle, |
| 2414 | ) |
| 2415 | .footer_chord, |
| 2416 | tr(locale, MessageId::ConfigSectionPermissions), |
| 2417 | ); |
| 2418 | let show_permission_hint = self.view.offers_permission_settings() |
| 2419 | && left_budget |
| 2420 | >= left_used + verb.width() + 1 + subject.width().min(48) + permission_hint.width(); |
| 2421 | let left_budget = if show_permission_hint { |
| 2422 | left_budget - permission_hint.width() |
| 2423 | } else { |
| 2424 | left_budget |
| 2425 | }; |
| 2426 | |
| 2427 | if left_used < left_budget && !verb.is_empty() { |
| 2428 | let verb_with_space = format!("{verb} "); |
| 2429 | let verb_trunc = |
| 2430 | truncate_line_to_width(&verb_with_space, left_budget.saturating_sub(left_used)); |
| 2431 | left_used = left_used.saturating_add(verb_trunc.width()); |
| 2432 | let verb_color = if outside_workspace { |
| 2433 | edge_color |
| 2434 | } else { |
| 2435 | palette::TEXT_SECONDARY |
| 2436 | }; |
| 2437 | left_spans.push(Span::styled( |
| 2438 | verb_trunc, |
| 2439 | Style::default().fg(verb_color).add_modifier(Modifier::BOLD), |
| 2440 | )); |
| 2441 | } |
| 2442 | if left_used < left_budget && !subject.is_empty() { |
| 2443 | let subj_budget = left_budget.saturating_sub(left_used); |
| 2444 | let subj_trunc = truncate_line_to_width(&subject, subj_budget); |
| 2445 | left_spans.push(Span::styled( |
| 2446 | subj_trunc, |
| 2447 | Style::default().fg(palette::TEXT_PRIMARY), |
| 2448 | )); |
| 2449 | } |
| 2450 | |
| 2451 | if show_permission_hint { |
| 2452 | left_spans.push(Span::styled( |
| 2453 | permission_hint, |
| 2454 | Style::default().fg(palette::TEXT_HINT), |
| 2455 | )); |
| 2456 | } |
| 2457 | |
| 2458 | Paragraph::new(Line::from(left_spans)).render( |
| 2459 | Rect { |
| 2460 | width: (total_width - reserved_right) as u16, |
| 2461 | ..bar_area |
| 2462 | }, |
| 2463 | buf, |
| 2464 | ); |
| 2465 | |
| 2466 | let mut action_rects = vec![Rect::default(); 3]; |
| 2467 | let mut scopes_hitbox = None; |
| 2468 | let mut details_hitbox = None; |
| 2469 | |
| 2470 | let controls_x = bar_area |
| 2471 | .right() |
| 2472 | .saturating_sub(u16::try_from(controls_width).unwrap_or(bar_area.width)) |
| 2473 | .max(bar_area.x); |
| 2474 | let mut cursor_x = controls_x; |
| 2475 | for (i, control) in controls.into_iter().enumerate() { |
| 2476 | if i > 0 { |
| 2477 | cursor_x = cursor_x.saturating_add(1); |
| 2478 | } |
| 2479 | let w = u16::try_from(control.text.width()).unwrap_or(0); |
| 2480 | if cursor_x >= bar_area.right() || w == 0 { |
| 2481 | continue; |
| 2482 | } |
| 2483 | let avail = bar_area.right().saturating_sub(cursor_x); |
| 2484 | let render_w = w.min(avail); |
| 2485 | let rect = Rect::new(cursor_x, bar_area.y, render_w, 1); |
| 2486 | Span::styled(control.text, control.style).render(rect, buf); |
| 2487 | match control.kind { |
| 2488 | ControlKind::OptionIndex(idx) => { |
| 2489 | if idx < action_rects.len() { |
| 2490 | action_rects[idx] = rect; |
| 2491 | } |
| 2492 | } |
| 2493 | ControlKind::Scopes => scopes_hitbox = Some(rect), |
| 2494 | ControlKind::Details => details_hitbox = Some(rect), |
| 2495 | } |
| 2496 | cursor_x = cursor_x.saturating_add(render_w); |
| 2497 | } |
| 2498 | |
| 2499 | (action_rects, scopes_hitbox, details_hitbox) |
| 2500 | } |
| 2501 | } |
| 2502 | |
| 2503 | impl Renderable for ApprovalWidget<'_> { |
| 2504 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 2505 | let region = self.inline_region(area); |
| 2506 | if region.width == 0 || region.height == 0 { |
| 2507 | self.view.set_save_preview_shown(false); |
| 2508 | self.view.set_mouse_hitboxes(Vec::new()); |
| 2509 | self.view.set_scopes_toggle_hitbox(None); |
| 2510 | self.view.set_details_toggle_hitbox(None); |
| 2511 | self.view.set_scope_menu_hitboxes(Vec::new()); |
| 2512 | return; |
| 2513 | } |
| 2514 | |
| 2515 | for y in region.top()..region.bottom() { |
| 2516 | for x in region.left()..region.right() { |
| 2517 | buf[(x, y)] |
| 2518 | .set_symbol(" ") |
| 2519 | .set_style(Style::default().bg(palette::WHALE_BG)); |
| 2520 | } |
| 2521 | } |
| 2522 | |
| 2523 | let bar_area = Rect::new(region.x, region.bottom().saturating_sub(1), region.width, 1); |
| 2524 | let (action_rects, scopes_hitbox, details_hitbox) = self.render_bar(bar_area, buf); |
| 2525 | |
| 2526 | let mut save_shown = false; |
| 2527 | let mut scope_hitboxes = Vec::new(); |
| 2528 | if region.height > 1 { |
| 2529 | let drawer_area = Rect::new(region.x, region.y, region.width, region.height - 1); |
| 2530 | if self.view.scopes_open && !self.view.is_workflow_plan_approval() { |
| 2531 | let rows = self.scope_menu_rows(drawer_area.width); |
| 2532 | let total_preview_rows = rows.iter().filter(|row| row.is_save_preview).count(); |
| 2533 | let mut drawn_preview_rows = 0usize; |
| 2534 | for (row_idx, row) in rows |
| 2535 | .into_iter() |
| 2536 | .take(usize::from(drawer_area.height)) |
| 2537 | .enumerate() |
| 2538 | { |
| 2539 | let y = drawer_area |
| 2540 | .y |
| 2541 | .saturating_add(u16::try_from(row_idx).unwrap_or(0)); |
| 2542 | let row_rect = Rect::new(drawer_area.x, y, drawer_area.width, 1); |
| 2543 | if let Some(option) = row.option { |
| 2544 | if self.view.scope_selected == option { |
| 2545 | let bg = menu_style::selected_row_bg_style(); |
| 2546 | for x in row_rect.left()..row_rect.right() { |
| 2547 | buf[(x, y)].set_style(bg); |
| 2548 | } |
| 2549 | } |
| 2550 | scope_hitboxes.push((option, row_rect)); |
| 2551 | } else if row.is_save_preview |
| 2552 | && row.line.width() <= usize::from(drawer_area.width) |
| 2553 | { |
| 2554 | drawn_preview_rows += 1; |
| 2555 | } |
| 2556 | Paragraph::new(row.line).render(row_rect, buf); |
| 2557 | } |
| 2558 | save_shown = total_preview_rows > 0 && drawn_preview_rows == total_preview_rows; |
| 2559 | } else if self.view.details_expanded { |
| 2560 | let lines = self.details_lines(area); |
| 2561 | let cap = usize::from(drawer_area.height); |
| 2562 | let total = lines.len(); |
| 2563 | if total > cap && cap > 1 { |
| 2564 | for (idx, line) in lines.into_iter().take(cap - 1).enumerate() { |
| 2565 | let y = drawer_area |
| 2566 | .y |
| 2567 | .saturating_add(u16::try_from(idx).unwrap_or(0)); |
| 2568 | Paragraph::new(line) |
| 2569 | .render(Rect::new(drawer_area.x, y, drawer_area.width, 1), buf); |
| 2570 | } |
| 2571 | let y = drawer_area.y.saturating_add(drawer_area.height - 1); |
| 2572 | let ascii = ascii_safe_enabled(); |
| 2573 | let (_, edge_color, _) = self.edge_style(); |
| 2574 | let hint = Line::from(vec![ |
| 2575 | Span::styled( |
| 2576 | self.drawer_edge_glyph(ascii), |
| 2577 | Style::default().fg(edge_color).add_modifier(Modifier::BOLD), |
| 2578 | ), |
| 2579 | Span::raw(" "), |
| 2580 | Span::styled( |
| 2581 | approval_truncation_hint(self.view.locale()), |
| 2582 | Style::default().fg(palette::TEXT_HINT), |
| 2583 | ), |
| 2584 | ]); |
| 2585 | Paragraph::new(hint) |
| 2586 | .render(Rect::new(drawer_area.x, y, drawer_area.width, 1), buf); |
| 2587 | } else { |
| 2588 | for (idx, line) in lines.into_iter().take(cap).enumerate() { |
| 2589 | let y = drawer_area |
| 2590 | .y |
| 2591 | .saturating_add(u16::try_from(idx).unwrap_or(0)); |
| 2592 | Paragraph::new(line) |
| 2593 | .render(Rect::new(drawer_area.x, y, drawer_area.width, 1), buf); |
| 2594 | } |
| 2595 | } |
| 2596 | } |
| 2597 | } |
| 2598 | |
| 2599 | self.view.set_save_preview_shown(save_shown); |
| 2600 | self.view.set_mouse_hitboxes(action_rects); |
| 2601 | self.view.set_scopes_toggle_hitbox(scopes_hitbox); |
| 2602 | self.view.set_details_toggle_hitbox(details_hitbox); |
| 2603 | self.view.set_scope_menu_hitboxes(scope_hitboxes); |
| 2604 | } |
| 2605 | |
| 2606 | fn desired_height(&self, width: u16) -> u16 { |
| 2607 | self.docked_height(width) |
| 2608 | } |
| 2609 | } |
| 2610 | |
| 2611 | fn approval_truncation_hint(locale: Locale) -> Cow<'static, str> { |
| 2612 | let details = crate::tui::shell_key_routing::tool_details_chord(); |
| 2613 | Cow::Owned(tr(locale, MessageId::ApprovalTruncationHint).replace("{details}", details.as_ref())) |
| 2614 | } |
| 2615 | |
| 2616 | /// Approval palette per risk variant. |
| 2617 | struct ApprovalColors { |
| 2618 | border: Color, |
| 2619 | accent: Color, |
| 2620 | shortcut: Color, |
| 2621 | } |
| 2622 | |
| 2623 | fn approval_palette(stakes: crate::tui::approval::ApprovalStakes) -> ApprovalColors { |
| 2624 | use crate::tui::approval::ApprovalStakes; |
| 2625 | match stakes { |
| 2626 | ApprovalStakes::Routine => ApprovalColors { |
| 2627 | border: palette::BORDER_COLOR, |
| 2628 | accent: palette::WHALE_HUMAN, |
| 2629 | shortcut: palette::WHALE_ACTION, |
| 2630 | }, |
| 2631 | // Ordinary state-touching work: a calm ask, not an alarm. |
| 2632 | ApprovalStakes::Elevated => ApprovalColors { |
| 2633 | border: palette::WHALE_HUMAN, |
| 2634 | accent: palette::WHALE_HUMAN, |
| 2635 | shortcut: palette::WHALE_ACTION, |
| 2636 | }, |
| 2637 | ApprovalStakes::Critical => ApprovalColors { |
| 2638 | border: palette::WHALE_ERROR, |
| 2639 | accent: palette::WHALE_ERROR, |
| 2640 | shortcut: palette::STATUS_WARNING, |
| 2641 | }, |
| 2642 | } |
| 2643 | } |
| 2644 | |
| 2645 | fn repo_law_approval_palette() -> ApprovalColors { |
| 2646 | ApprovalColors { |
| 2647 | border: palette::STATUS_WARNING, |
| 2648 | accent: palette::WHALE_ERROR, |
| 2649 | shortcut: palette::STATUS_WARNING, |
| 2650 | } |
| 2651 | } |
| 2652 | |
| 2653 | fn category_label_for(request: &ApprovalRequest, locale: Locale) -> (Cow<'static, str>, Color) { |
| 2654 | let category = request.category; |
| 2655 | let label = match category { |
| 2656 | ToolCategory::Safe => tr(locale, MessageId::ApprovalCategorySafe), |
| 2657 | ToolCategory::FileWrite => tr(locale, MessageId::ApprovalCategoryFileWrite), |
| 2658 | ToolCategory::Shell => tr(locale, MessageId::ApprovalCategoryShell), |
| 2659 | ToolCategory::Network => tr(locale, MessageId::ApprovalCategoryNetwork), |
| 2660 | ToolCategory::McpRead => tr(locale, MessageId::ApprovalCategoryMcpRead), |
| 2661 | ToolCategory::McpAction => tr(locale, MessageId::ApprovalCategoryMcpAction), |
| 2662 | ToolCategory::Agent => tr(locale, MessageId::ApprovalCategoryAgent), |
| 2663 | ToolCategory::Unknown => tr(locale, MessageId::ApprovalCategoryUnknown), |
| 2664 | }; |
| 2665 | // "Connected app (github)": name the server the tool comes from. |
| 2666 | let label = match ( |
| 2667 | category, |
| 2668 | crate::tui::approval::connected_app_server(&request.tool_name), |
| 2669 | ) { |
| 2670 | (ToolCategory::McpRead | ToolCategory::McpAction, Some(server)) => { |
| 2671 | Cow::Owned(format!("{label} ({server})")) |
| 2672 | } |
| 2673 | _ => label, |
| 2674 | }; |
| 2675 | let color = match category { |
| 2676 | ToolCategory::Safe => palette::STATUS_SUCCESS, |
| 2677 | ToolCategory::FileWrite => palette::STATUS_WARNING, |
| 2678 | ToolCategory::Shell => palette::STATUS_ERROR, |
| 2679 | ToolCategory::Network => palette::STATUS_WARNING, |
| 2680 | ToolCategory::McpRead => palette::WHALE_ACTION, |
| 2681 | ToolCategory::McpAction => palette::STATUS_WARNING, |
| 2682 | ToolCategory::Agent => palette::WHALE_ACTION, |
| 2683 | ToolCategory::Unknown => palette::STATUS_ERROR, |
| 2684 | }; |
| 2685 | (label, color) |
| 2686 | } |
| 2687 | |
| 2688 | fn label_type(locale: Locale) -> Cow<'static, str> { |
| 2689 | tr(locale, MessageId::ApprovalFieldType) |
| 2690 | } |
| 2691 | |
| 2692 | fn label_about(locale: Locale) -> Cow<'static, str> { |
| 2693 | tr(locale, MessageId::ApprovalFieldAbout) |
| 2694 | } |
| 2695 | |
| 2696 | fn label_impact(locale: Locale) -> Cow<'static, str> { |
| 2697 | tr(locale, MessageId::ApprovalFieldImpact) |
| 2698 | } |
| 2699 | |
| 2700 | fn label_params(locale: Locale) -> Cow<'static, str> { |
| 2701 | tr(locale, MessageId::ApprovalFieldParams) |
| 2702 | } |
| 2703 | |
| 2704 | fn push_detail_line(lines: &mut Vec<Line<'static>>, label: &str, value: &str) { |
| 2705 | lines.push(Line::from(vec![ |
| 2706 | Span::raw(" "), |
| 2707 | Span::styled( |
| 2708 | format!("{label:<7} "), |
| 2709 | Style::default() |
| 2710 | .fg(palette::WHALE_ACTION) |
| 2711 | .add_modifier(Modifier::BOLD), |
| 2712 | ), |
| 2713 | Span::styled(value.to_string(), Style::default().fg(palette::TEXT_BODY)), |
| 2714 | ])); |
| 2715 | } |
| 2716 | |
| 2717 | fn push_params_detail_line( |
| 2718 | lines: &mut Vec<Line<'static>>, |
| 2719 | request: &ApprovalRequest, |
| 2720 | locale: Locale, |
| 2721 | card_width: u16, |
| 2722 | ) { |
| 2723 | let params_str = request.params_display(); |
| 2724 | let params_width = card_width.saturating_sub(14) as usize; |
| 2725 | let params_truncated = truncate_line_to_width(¶ms_str, params_width.max(20)); |
| 2726 | lines.push(Line::from(vec![ |
| 2727 | Span::raw(" "), |
| 2728 | Span::styled( |
| 2729 | label_params(locale), |
| 2730 | Style::default().fg(palette::TEXT_HINT), |
| 2731 | ), |
| 2732 | Span::styled( |
| 2733 | params_truncated, |
| 2734 | Style::default().fg(palette::TEXT_SECONDARY), |
| 2735 | ), |
| 2736 | ])); |
| 2737 | } |
| 2738 | |
| 2739 | fn push_shell_command_lines( |
| 2740 | lines: &mut Vec<Line<'static>>, |
| 2741 | label: &str, |
| 2742 | command_lines: &[String], |
| 2743 | command_width: usize, |
| 2744 | max_rows: Option<usize>, |
| 2745 | ) { |
| 2746 | lines.push(Line::from(vec![ |
| 2747 | Span::raw(" "), |
| 2748 | Span::styled( |
| 2749 | format!("{label}:"), |
| 2750 | Style::default() |
| 2751 | .fg(palette::WHALE_ACTION) |
| 2752 | .add_modifier(Modifier::BOLD), |
| 2753 | ), |
| 2754 | ])); |
| 2755 | |
| 2756 | let mut rendered = 0usize; |
| 2757 | for line in command_lines { |
| 2758 | for wrapped in wrap_text(line, command_width) { |
| 2759 | if max_rows.is_some_and(|limit| rendered >= limit) { |
| 2760 | lines.push(Line::from(vec![ |
| 2761 | Span::raw(" "), |
| 2762 | Span::styled( |
| 2763 | "...", |
| 2764 | Style::default() |
| 2765 | .fg(palette::TEXT_HINT) |
| 2766 | .add_modifier(Modifier::BOLD), |
| 2767 | ), |
| 2768 | ])); |
| 2769 | return; |
| 2770 | } |
| 2771 | lines.push(Line::from(vec![ |
| 2772 | Span::raw(" "), |
| 2773 | Span::styled( |
| 2774 | wrapped, |
| 2775 | Style::default() |
| 2776 | .fg(palette::TEXT_BODY) |
| 2777 | .add_modifier(Modifier::BOLD), |
| 2778 | ), |
| 2779 | ])); |
| 2780 | rendered += 1; |
| 2781 | } |
| 2782 | } |
| 2783 | } |
| 2784 | |
| 2785 | /// Put one representative command/change first for compact inline rendering. |
| 2786 | /// This is a display-only projection: approval parameters and the details |
| 2787 | /// pager retain the exact original order. |
| 2788 | fn prioritize_inline_shell_lines( |
| 2789 | command_lines: &[String], |
| 2790 | is_change_preview: bool, |
| 2791 | compact: bool, |
| 2792 | ) -> Vec<String> { |
| 2793 | if !compact || command_lines.len() < 2 { |
| 2794 | return command_lines.to_vec(); |
| 2795 | } |
| 2796 | |
| 2797 | let representative = if is_change_preview { |
| 2798 | command_lines |
| 2799 | .iter() |
| 2800 | .enumerate() |
| 2801 | .max_by_key(|(index, line)| (preview_line_priority(line), std::cmp::Reverse(*index))) |
| 2802 | .map(|(index, _)| index) |
| 2803 | } else { |
| 2804 | command_lines |
| 2805 | .iter() |
| 2806 | .enumerate() |
| 2807 | .max_by_key(|(index, line)| (command_line_priority(line), std::cmp::Reverse(*index))) |
| 2808 | .map(|(index, _)| index) |
| 2809 | }; |
| 2810 | let Some(representative) = representative.filter(|index| *index > 0) else { |
| 2811 | return command_lines.to_vec(); |
| 2812 | }; |
| 2813 | |
| 2814 | let mut projected = Vec::with_capacity(command_lines.len()); |
| 2815 | projected.push(command_lines[representative].clone()); |
| 2816 | projected.extend( |
| 2817 | command_lines |
| 2818 | .iter() |
| 2819 | .enumerate() |
| 2820 | .filter(|(index, _)| *index != representative) |
| 2821 | .map(|(_, line)| line.clone()), |
| 2822 | ); |
| 2823 | projected |
| 2824 | } |
| 2825 | |
| 2826 | fn preview_line_priority(line: &str) -> u8 { |
| 2827 | let trimmed = line.trim_start(); |
| 2828 | if trimmed.starts_with('+') && !trimmed.starts_with("+++") { |
| 2829 | 4 |
| 2830 | } else if trimmed.starts_with('-') && !trimmed.starts_with("---") { |
| 2831 | 3 |
| 2832 | } else if trimmed.starts_with("@@") { |
| 2833 | 2 |
| 2834 | } else if trimmed.starts_with("diff ") |
| 2835 | || trimmed.starts_with("---") |
| 2836 | || trimmed.starts_with("+++") |
| 2837 | { |
| 2838 | 0 |
| 2839 | } else { |
| 2840 | 1 |
| 2841 | } |
| 2842 | } |
| 2843 | |
| 2844 | fn command_line_priority(line: &str) -> u8 { |
| 2845 | let trimmed = line.trim(); |
| 2846 | if trimmed.is_empty() || trimmed.starts_with('#') { |
| 2847 | return 0; |
| 2848 | } |
| 2849 | |
| 2850 | let tokens = trimmed |
| 2851 | .split(|ch: char| ch.is_whitespace() || matches!(ch, ';' | '|' | '&' | '(' | ')')) |
| 2852 | .filter(|token| !token.is_empty()) |
| 2853 | .map(|token| token.rsplit('/').next().unwrap_or(token)) |
| 2854 | .collect::<Vec<_>>(); |
| 2855 | if tokens.iter().any(|token| { |
| 2856 | matches!( |
| 2857 | *token, |
| 2858 | "rm" | "rmdir" |
| 2859 | | "unlink" |
| 2860 | | "mv" |
| 2861 | | "dd" |
| 2862 | | "chmod" |
| 2863 | | "chown" |
| 2864 | | "kill" |
| 2865 | | "pkill" |
| 2866 | | "shutdown" |
| 2867 | | "reboot" |
| 2868 | | "mkfs" |
| 2869 | ) |
| 2870 | }) || tokens.windows(2).any(|pair| { |
| 2871 | matches!( |
| 2872 | pair, |
| 2873 | ["git", "push"] | ["cargo", "publish"] | ["npm", "publish"] |
| 2874 | ) |
| 2875 | }) || trimmed.contains('>') |
| 2876 | { |
| 2877 | return 4; |
| 2878 | } |
| 2879 | |
| 2880 | let first = tokens.first().copied().unwrap_or_default(); |
| 2881 | if matches!( |
| 2882 | first, |
| 2883 | "cd" | "pushd" | "popd" | "set" | "export" | "unset" | "pwd" | ":" | "true" |
| 2884 | ) { |
| 2885 | 1 |
| 2886 | } else if matches!(first, "echo" | "printf") { |
| 2887 | 2 |
| 2888 | } else { |
| 2889 | 3 |
| 2890 | } |
| 2891 | } |
| 2892 | |
| 2893 | fn push_destructive_approval_semantics( |
| 2894 | lines: &mut Vec<Line<'static>>, |
| 2895 | locale: Locale, |
| 2896 | compact: bool, |
| 2897 | ) { |
| 2898 | if compact { |
| 2899 | let (label, value) = destructive_approval_compact_semantics(locale); |
| 2900 | lines.push(Line::from(vec![ |
| 2901 | Span::raw(" "), |
| 2902 | Span::styled(label, Style::default().fg(palette::TEXT_HINT)), |
| 2903 | Span::styled(value, Style::default().fg(palette::TEXT_SECONDARY)), |
| 2904 | ])); |
| 2905 | return; |
| 2906 | } |
| 2907 | |
| 2908 | for (label, value) in destructive_approval_semantics(locale) { |
| 2909 | lines.push(Line::from(vec![ |
| 2910 | Span::raw(" "), |
| 2911 | Span::styled(label, Style::default().fg(palette::TEXT_HINT)), |
| 2912 | Span::styled(value, Style::default().fg(palette::TEXT_SECONDARY)), |
| 2913 | ])); |
| 2914 | } |
| 2915 | } |
| 2916 | |
| 2917 | fn destructive_approval_compact_semantics( |
| 2918 | locale: Locale, |
| 2919 | ) -> (Cow<'static, str>, Cow<'static, str>) { |
| 2920 | ( |
| 2921 | tr(locale, MessageId::ApprovalFieldWhy), |
| 2922 | tr(locale, MessageId::ApprovalWhyCompactBody), |
| 2923 | ) |
| 2924 | } |
| 2925 | |
| 2926 | fn destructive_approval_semantics(locale: Locale) -> [(Cow<'static, str>, Cow<'static, str>); 2] { |
| 2927 | [ |
| 2928 | ( |
| 2929 | tr(locale, MessageId::ApprovalFieldWhy), |
| 2930 | tr(locale, MessageId::ApprovalWhyBody), |
| 2931 | ), |
| 2932 | ( |
| 2933 | tr(locale, MessageId::ApprovalFieldStop), |
| 2934 | tr(locale, MessageId::ApprovalStopBody), |
| 2935 | ), |
| 2936 | ] |
| 2937 | } |
| 2938 | |
| 2939 | fn approval_owner_header(owner: &crate::tui::approval::ApprovalOwner, locale: Locale) -> String { |
| 2940 | let template = tr(locale, MessageId::ApprovalOwnerHeader); |
| 2941 | let with_agent = template.replace("{agent}", &owner.label); |
| 2942 | match owner.role.as_deref() { |
| 2943 | Some(role) => with_agent.replace("{role}", role), |
| 2944 | None => with_agent |
| 2945 | .replace(" · {role}", "") |
| 2946 | .replace("{role}", "") |
| 2947 | .trim_end() |
| 2948 | .to_string(), |
| 2949 | } |
| 2950 | } |
| 2951 | |
| 2952 | pub struct ElevationWidget<'a> { |
| 2953 | request: &'a ElevationRequest, |
| 2954 | selected: usize, |
| 2955 | locale: Locale, |
| 2956 | hitboxes: Option<&'a std::cell::RefCell<Vec<Rect>>>, |
| 2957 | } |
| 2958 | |
| 2959 | impl<'a> ElevationWidget<'a> { |
| 2960 | pub fn new_with_hitboxes( |
| 2961 | request: &'a ElevationRequest, |
| 2962 | selected: usize, |
| 2963 | locale: Locale, |
| 2964 | hitboxes: &'a std::cell::RefCell<Vec<Rect>>, |
| 2965 | ) -> Self { |
| 2966 | Self { |
| 2967 | request, |
| 2968 | selected, |
| 2969 | locale, |
| 2970 | hitboxes: Some(hitboxes), |
| 2971 | } |
| 2972 | } |
| 2973 | } |
| 2974 | |
| 2975 | impl Renderable for ElevationWidget<'_> { |
| 2976 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 2977 | use codewhale_localization::MessageId; |
| 2978 | use codewhale_localization::tr; |
| 2979 | |
| 2980 | let popup_width = 70.min(area.width.saturating_sub(4)); |
| 2981 | |
| 2982 | let mut lines = vec![match self.request.command.as_deref() { |
| 2983 | Some(command) => Line::from(vec![ |
| 2984 | Span::raw(tr(self.locale, MessageId::ElevationFieldCmd)), |
| 2985 | Span::styled( |
| 2986 | truncate_line_to_width(command, 45), |
| 2987 | Style::default().fg(palette::TEXT_MUTED), |
| 2988 | ), |
| 2989 | ]), |
| 2990 | None => Line::from(vec![ |
| 2991 | Span::raw(tr(self.locale, MessageId::ElevationFieldTool)), |
| 2992 | Span::styled( |
| 2993 | &self.request.tool_name, |
| 2994 | Style::default() |
| 2995 | .fg(palette::WHALE_ACTION) |
| 2996 | .add_modifier(Modifier::BOLD), |
| 2997 | ), |
| 2998 | ]), |
| 2999 | }]; |
| 3000 | |
| 3001 | lines.push(Line::from("")); |
| 3002 | lines.push(Line::from(vec![ |
| 3003 | Span::raw(tr(self.locale, MessageId::ElevationFieldReason)), |
| 3004 | Span::styled( |
| 3005 | &self.request.denial_reason, |
| 3006 | Style::default().fg(palette::STATUS_WARNING), |
| 3007 | ), |
| 3008 | ])); |
| 3009 | |
| 3010 | lines.push(Line::from("")); |
| 3011 | lines.push(Line::from(Span::styled( |
| 3012 | tr(self.locale, MessageId::ElevationImpactHeader), |
| 3013 | Style::default().fg(palette::TEXT_MUTED), |
| 3014 | ))); |
| 3015 | if self |
| 3016 | .request |
| 3017 | .options |
| 3018 | .iter() |
| 3019 | .any(|option| matches!(option, ElevationOption::WithNetwork)) |
| 3020 | { |
| 3021 | lines.push(Line::from(Span::styled( |
| 3022 | tr(self.locale, MessageId::ElevationImpactNetwork), |
| 3023 | Style::default().fg(palette::TEXT_PRIMARY), |
| 3024 | ))); |
| 3025 | } |
| 3026 | if self |
| 3027 | .request |
| 3028 | .options |
| 3029 | .iter() |
| 3030 | .any(|option| matches!(option, ElevationOption::WithWriteAccess(_))) |
| 3031 | { |
| 3032 | lines.push(Line::from(Span::styled( |
| 3033 | tr(self.locale, MessageId::ElevationImpactWrite), |
| 3034 | Style::default().fg(palette::TEXT_PRIMARY), |
| 3035 | ))); |
| 3036 | } |
| 3037 | lines.push(Line::from(Span::styled( |
| 3038 | tr(self.locale, MessageId::ElevationImpactFullAccess), |
| 3039 | Style::default().fg(palette::TEXT_PRIMARY), |
| 3040 | ))); |
| 3041 | lines.push(Line::from("")); |
| 3042 | lines.push(Line::from(Span::styled( |
| 3043 | tr(self.locale, MessageId::ElevationPromptProceed), |
| 3044 | Style::default().fg(palette::TEXT_MUTED), |
| 3045 | ))); |
| 3046 | lines.push(Line::from("")); |
| 3047 | |
| 3048 | let option_start = lines.len(); |
| 3049 | for (i, option) in self.request.options.iter().enumerate() { |
| 3050 | let is_selected = i == self.selected; |
| 3051 | let style = if is_selected { |
| 3052 | menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 3053 | } else { |
| 3054 | Style::default() |
| 3055 | }; |
| 3056 | |
| 3057 | let (label_id, desc_id) = match option { |
| 3058 | ElevationOption::WithNetwork => ( |
| 3059 | MessageId::ElevationOptionNetwork, |
| 3060 | MessageId::ElevationOptionNetworkDesc, |
| 3061 | ), |
| 3062 | ElevationOption::WithWriteAccess(_) => ( |
| 3063 | MessageId::ElevationOptionWrite, |
| 3064 | MessageId::ElevationOptionWriteDesc, |
| 3065 | ), |
| 3066 | ElevationOption::FullAccess => ( |
| 3067 | MessageId::ElevationOptionFullAccess, |
| 3068 | MessageId::ElevationOptionFullAccessDesc, |
| 3069 | ), |
| 3070 | ElevationOption::Abort => ( |
| 3071 | MessageId::ElevationOptionAbort, |
| 3072 | MessageId::ElevationOptionAbortDesc, |
| 3073 | ), |
| 3074 | }; |
| 3075 | |
| 3076 | let label_color = match option { |
| 3077 | ElevationOption::Abort => palette::TEXT_MUTED, |
| 3078 | ElevationOption::FullAccess => palette::STATUS_ERROR, |
| 3079 | _ => palette::TEXT_PRIMARY, |
| 3080 | }; |
| 3081 | |
| 3082 | lines.push(Line::from(vec![ |
| 3083 | Span::raw(" "), |
| 3084 | Span::styled( |
| 3085 | format!( |
| 3086 | "{} ", |
| 3087 | codewhale_tui_kit::glyphs::selection_marker(is_selected) |
| 3088 | ), |
| 3089 | style, |
| 3090 | ), |
| 3091 | Span::styled(tr(self.locale, label_id), style.fg(label_color)), |
| 3092 | ])); |
| 3093 | lines.push(Line::from(vec![ |
| 3094 | Span::raw(" "), |
| 3095 | Span::styled( |
| 3096 | tr(self.locale, desc_id), |
| 3097 | Style::default().fg(palette::TEXT_MUTED), |
| 3098 | ), |
| 3099 | ])); |
| 3100 | } |
| 3101 | |
| 3102 | // Reserve the options before the explanation. `Abort` is the last row of |
| 3103 | // that list, so a card sized to its preamble hides the safe exit with no |
| 3104 | // scroll rail and no hint that anything is missing. The denial detail is |
| 3105 | // what gets shortened; the choices never do. |
| 3106 | // |
| 3107 | // `Padding::uniform(1)` inside `Borders::ALL` costs two rows and two |
| 3108 | // columns on each axis. |
| 3109 | const CHROME: u16 = 4; |
| 3110 | let inner_width = popup_width.saturating_sub(CHROME); |
| 3111 | let max_inner_height = area.height.saturating_sub(2).saturating_sub(CHROME); |
| 3112 | |
| 3113 | // The same binding table routes these keys. Reserve its hint alongside |
| 3114 | // the choices so truncating the denial never hides keyboard access. |
| 3115 | use crate::tui::shell_key_routing::{ShellBindingId, binding}; |
| 3116 | let controls = Line::from(Span::styled( |
| 3117 | format!( |
| 3118 | " {}/{} · {} · {}", |
| 3119 | binding(ShellBindingId::ElevationUp).footer_chord, |
| 3120 | binding(ShellBindingId::ElevationDown).footer_chord, |
| 3121 | binding(ShellBindingId::ElevationConfirm).footer_chord, |
| 3122 | binding(ShellBindingId::ElevationAbort).footer_chord, |
| 3123 | ), |
| 3124 | Style::default().fg(palette::TEXT_MUTED), |
| 3125 | )); |
| 3126 | let controls_rows = measure_wrapped_rows(std::slice::from_ref(&controls), inner_width); |
| 3127 | // Elevation has no details pager. Do not reuse the initial-approval |
| 3128 | // hint that advertises a details shortcut this card cannot handle. |
| 3129 | let truncation_hint = Line::from(Span::styled( |
| 3130 | " …", |
| 3131 | Style::default().fg(palette::TEXT_MUTED), |
| 3132 | )); |
| 3133 | let truncation_rows = |
| 3134 | measure_wrapped_rows(std::slice::from_ref(&truncation_hint), inner_width); |
| 3135 | |
| 3136 | let mut option_lines = lines.split_off(option_start); |
| 3137 | // Each option is a label row followed by a description row. On a terminal |
| 3138 | // too small for both, the description is chrome and the choice is |
| 3139 | // content, so the descriptions go first and every option keeps its row. |
| 3140 | let mut rows_per_option = 2usize; |
| 3141 | if measure_wrapped_rows(&option_lines, inner_width) |
| 3142 | .saturating_add(controls_rows) |
| 3143 | .saturating_add(2 + truncation_rows) |
| 3144 | > max_inner_height |
| 3145 | { |
| 3146 | option_lines = option_lines |
| 3147 | .into_iter() |
| 3148 | .enumerate() |
| 3149 | .filter_map(|(idx, line)| (idx % 2 == 0).then_some(line)) |
| 3150 | .collect(); |
| 3151 | rows_per_option = 1; |
| 3152 | } |
| 3153 | let option_rows = |
| 3154 | measure_wrapped_rows(&option_lines, inner_width).saturating_add(controls_rows); |
| 3155 | // Empty separators are chrome. Remove them before truncating useful |
| 3156 | // detail; on the smallest frame even the preamble can go, since the |
| 3157 | // border still names the card and the choices must remain reachable. |
| 3158 | if measure_wrapped_rows(&lines, inner_width) |
| 3159 | .saturating_add(option_rows) |
| 3160 | .saturating_add(truncation_rows) |
| 3161 | > max_inner_height |
| 3162 | { |
| 3163 | lines.retain(|line| line.width() != 0); |
| 3164 | } |
| 3165 | let mut truncated = false; |
| 3166 | while !lines.is_empty() |
| 3167 | && measure_wrapped_rows(&lines, inner_width) |
| 3168 | .saturating_add(option_rows) |
| 3169 | .saturating_add(truncation_rows) |
| 3170 | > max_inner_height |
| 3171 | { |
| 3172 | lines.pop(); |
| 3173 | truncated = true; |
| 3174 | } |
| 3175 | if truncated |
| 3176 | && measure_wrapped_rows(&lines, inner_width) |
| 3177 | .saturating_add(option_rows) |
| 3178 | .saturating_add(truncation_rows) |
| 3179 | <= max_inner_height |
| 3180 | { |
| 3181 | lines.push(truncation_hint); |
| 3182 | } |
| 3183 | |
| 3184 | // Row offsets are measured after wrapping, not counted in source lines: |
| 3185 | // a description that wraps used to push every hitbox below it out of |
| 3186 | // step with the row the pointer was actually over. |
| 3187 | let option_row_offsets = { |
| 3188 | let mut offsets = Vec::with_capacity(self.request.options.len()); |
| 3189 | let mut row = measure_wrapped_rows(&lines, inner_width); |
| 3190 | for pair in option_lines.chunks(rows_per_option) { |
| 3191 | let height = measure_wrapped_rows(pair, inner_width); |
| 3192 | offsets.push((row, height)); |
| 3193 | row = row.saturating_add(height); |
| 3194 | } |
| 3195 | offsets |
| 3196 | }; |
| 3197 | lines.extend(option_lines); |
| 3198 | lines.push(controls); |
| 3199 | |
| 3200 | let popup_height = measure_wrapped_rows(&lines, inner_width) |
| 3201 | .saturating_add(CHROME) |
| 3202 | .min(area.height.saturating_sub(2)); |
| 3203 | let popup_area = Rect { |
| 3204 | x: (area.width.saturating_sub(popup_width)) / 2, |
| 3205 | y: (area.height.saturating_sub(popup_height)) / 2, |
| 3206 | width: popup_width, |
| 3207 | height: popup_height, |
| 3208 | }; |
| 3209 | |
| 3210 | Clear.render(popup_area, buf); |
| 3211 | |
| 3212 | let title = tr(self.locale, MessageId::ElevationTitleRequired); |
| 3213 | let block = Block::default() |
| 3214 | .title(title) |
| 3215 | .borders(Borders::ALL) |
| 3216 | .border_style(Style::default().fg(palette::BORDER_COLOR)) |
| 3217 | .style( |
| 3218 | Style::default() |
| 3219 | .fg(palette::TEXT_PRIMARY) |
| 3220 | .bg(palette::WHALE_BG), |
| 3221 | ) |
| 3222 | .padding(Padding::uniform(1)); |
| 3223 | |
| 3224 | if let Some(hitboxes) = self.hitboxes { |
| 3225 | hitboxes.borrow_mut().clear(); |
| 3226 | let content = block.inner(popup_area); |
| 3227 | let content_bottom = content.y.saturating_add(content.height); |
| 3228 | for (offset, rows) in option_row_offsets { |
| 3229 | let y = content.y.saturating_add(offset); |
| 3230 | let height = rows.min(content_bottom.saturating_sub(y)); |
| 3231 | if height > 0 { |
| 3232 | hitboxes |
| 3233 | .borrow_mut() |
| 3234 | .push(Rect::new(content.x, y, content.width, height)); |
| 3235 | } |
| 3236 | } |
| 3237 | } |
| 3238 | |
| 3239 | let paragraph = Paragraph::new(lines) |
| 3240 | .block(block) |
| 3241 | .wrap(Wrap { trim: false }); |
| 3242 | |
| 3243 | paragraph.render(popup_area, buf); |
| 3244 | } |
| 3245 | |
| 3246 | fn desired_height(&self, _width: u16) -> u16 { |
| 3247 | 1 |
| 3248 | } |
| 3249 | } |
| 3250 | |
| 3251 | fn apply_selection(lines: &mut [Line<'static>], top: usize, app: &App) { |
| 3252 | let Some((start, end)) = app.viewport.transcript_selection.ordered_endpoints() else { |
| 3253 | return; |
| 3254 | }; |
| 3255 | |
| 3256 | let selection_style = Style::default() |
| 3257 | .bg(app.ui_theme.selection_bg) |
| 3258 | .fg(palette::SELECTION_TEXT); |
| 3259 | |
| 3260 | for (idx, line) in lines.iter_mut().enumerate() { |
| 3261 | let line_index = top + idx; |
| 3262 | if line_index < start.line_index || line_index > end.line_index { |
| 3263 | continue; |
| 3264 | } |
| 3265 | |
| 3266 | let (col_start, col_end) = if start.line_index == end.line_index { |
| 3267 | (start.column, end.column) |
| 3268 | } else if line_index == start.line_index { |
| 3269 | (start.column, usize::MAX) |
| 3270 | } else if line_index == end.line_index { |
| 3271 | (0, end.column) |
| 3272 | } else { |
| 3273 | (0, usize::MAX) |
| 3274 | }; |
| 3275 | |
| 3276 | if col_start == 0 && col_end == usize::MAX { |
| 3277 | for span in &mut line.spans { |
| 3278 | span.style = span.style.patch(selection_style); |
| 3279 | } |
| 3280 | continue; |
| 3281 | } |
| 3282 | |
| 3283 | line.spans = codewhale_ratatui::transcript_selected_spans_measured( |
| 3284 | line, |
| 3285 | col_start, |
| 3286 | col_end, |
| 3287 | selection_style, |
| 3288 | grapheme_display_width, |
| 3289 | ); |
| 3290 | } |
| 3291 | } |
| 3292 | |
| 3293 | /// Apply a brief background tint to the last user message's visible lines. |
| 3294 | fn apply_send_flash( |
| 3295 | lines: &mut [Line<'static>], |
| 3296 | top: usize, |
| 3297 | history: &[HistoryCell], |
| 3298 | line_meta: &[TranscriptLineMeta], |
| 3299 | original_index_map: &[usize], |
| 3300 | ) { |
| 3301 | // Find the last User cell index. |
| 3302 | let last_user_cell = history |
| 3303 | .iter() |
| 3304 | .rposition(|cell| matches!(cell, HistoryCell::User { .. })); |
| 3305 | let Some(target_cell) = last_user_cell else { |
| 3306 | return; |
| 3307 | }; |
| 3308 | |
| 3309 | let flash_bg = palette::SURFACE_TOOL_ACTIVE; // subtle dark-blue tint |
| 3310 | |
| 3311 | for (idx, line) in lines.iter_mut().enumerate() { |
| 3312 | let line_index = top + idx; |
| 3313 | if let Some(TranscriptLineMeta::CellLine { cell_index, .. }) = line_meta.get(line_index) |
| 3314 | && original_index_map |
| 3315 | .get(*cell_index) |
| 3316 | .copied() |
| 3317 | .unwrap_or(*cell_index) |
| 3318 | == target_cell |
| 3319 | { |
| 3320 | for span in &mut line.spans { |
| 3321 | span.style = span.style.bg(flash_bg); |
| 3322 | } |
| 3323 | } |
| 3324 | } |
| 3325 | } |
| 3326 | |
| 3327 | #[allow(clippy::too_many_arguments)] |
| 3328 | pub(crate) fn apply_activity_sweep( |
| 3329 | lines: &mut [Line<'static>], |
| 3330 | top: usize, |
| 3331 | line_meta: &[TranscriptLineMeta], |
| 3332 | original_index_map: &[usize], |
| 3333 | history: &[HistoryCell], |
| 3334 | active_entries: &[HistoryCell], |
| 3335 | elapsed: Duration, |
| 3336 | theme_id: palette::ThemeId, |
| 3337 | ui_theme: &palette::UiTheme, |
| 3338 | detected_background: Option<Color>, |
| 3339 | ) -> bool { |
| 3340 | let highlight = ui_theme.text_body; |
| 3341 | if !matches!(highlight, Color::Rgb(..)) { |
| 3342 | return false; |
| 3343 | } |
| 3344 | let effective_ground = palette::effective_surface(ui_theme.surface_bg, detected_background); |
| 3345 | let mut visible = false; |
| 3346 | for (idx, line) in lines.iter_mut().enumerate() { |
| 3347 | let Some(TranscriptLineMeta::CellLine { |
| 3348 | cell_index, |
| 3349 | line_in_cell, |
| 3350 | .. |
| 3351 | }) = line_meta.get(top + idx) |
| 3352 | else { |
| 3353 | continue; |
| 3354 | }; |
| 3355 | if *line_in_cell > 1 { |
| 3356 | continue; |
| 3357 | } |
| 3358 | let original = original_index_map |
| 3359 | .get(*cell_index) |
| 3360 | .copied() |
| 3361 | .unwrap_or(*cell_index); |
| 3362 | let cell = history.get(original).or_else(|| { |
| 3363 | original |
| 3364 | .checked_sub(history.len()) |
| 3365 | .and_then(|active| active_entries.get(active)) |
| 3366 | }); |
| 3367 | let Some(shape) = cell.and_then(HistoryCell::activity_sweep) else { |
| 3368 | continue; |
| 3369 | }; |
| 3370 | if let Some(extent) = |
| 3371 | crate::tui::history::tool_header_sweep_extent(shape, line, *line_in_cell) |
| 3372 | && sweep_span_extent( |
| 3373 | line, |
| 3374 | extent, |
| 3375 | elapsed, |
| 3376 | theme_id, |
| 3377 | ui_theme, |
| 3378 | highlight, |
| 3379 | effective_ground, |
| 3380 | ) |
| 3381 | { |
| 3382 | visible = true; |
| 3383 | } |
| 3384 | } |
| 3385 | visible |
| 3386 | } |
| 3387 | |
| 3388 | const SETTLE_FLASH_DURATION: Duration = |
| 3389 | Duration::from_millis((codewhale_ratatui::tokens::MOTION_DURATION_PANEL_MS * 2.0) as u64); |
| 3390 | |
| 3391 | #[allow(clippy::too_many_arguments)] |
| 3392 | pub(crate) fn apply_settle_flash( |
| 3393 | lines: &mut [Line<'static>], |
| 3394 | top: usize, |
| 3395 | line_meta: &[TranscriptLineMeta], |
| 3396 | original_index_map: &[usize], |
| 3397 | history_len: usize, |
| 3398 | active_entries: &[HistoryCell], |
| 3399 | completed_at: &std::collections::HashMap<usize, std::time::Instant>, |
| 3400 | now: std::time::Instant, |
| 3401 | theme_id: palette::ThemeId, |
| 3402 | ui_theme: &palette::UiTheme, |
| 3403 | detected_background: Option<Color>, |
| 3404 | ) -> bool { |
| 3405 | if completed_at.is_empty() { |
| 3406 | return false; |
| 3407 | } |
| 3408 | let effective_ground = palette::effective_surface(ui_theme.surface_bg, detected_background); |
| 3409 | let mut visible = false; |
| 3410 | for (idx, line) in lines.iter_mut().enumerate() { |
| 3411 | let Some(TranscriptLineMeta::CellLine { |
| 3412 | cell_index, |
| 3413 | line_in_cell: 0, |
| 3414 | .. |
| 3415 | }) = line_meta.get(top + idx) |
| 3416 | else { |
| 3417 | continue; |
| 3418 | }; |
| 3419 | let original = original_index_map |
| 3420 | .get(*cell_index) |
| 3421 | .copied() |
| 3422 | .unwrap_or(*cell_index); |
| 3423 | let Some(entry) = original.checked_sub(history_len) else { |
| 3424 | continue; |
| 3425 | }; |
| 3426 | let Some(since) = completed_at |
| 3427 | .get(&entry) |
| 3428 | .map(|at| now.saturating_duration_since(*at)) |
| 3429 | .filter(|since| *since < SETTLE_FLASH_DURATION) |
| 3430 | else { |
| 3431 | continue; |
| 3432 | }; |
| 3433 | let Some(HistoryCell::Tool(tool)) = active_entries.get(entry) else { |
| 3434 | continue; |
| 3435 | }; |
| 3436 | let ink = match tool.status() { |
| 3437 | Some(ToolStatus::Success) => ui_theme.tool_success, |
| 3438 | Some(ToolStatus::Failed) => ui_theme.tool_failed, |
| 3439 | _ => continue, |
| 3440 | }; |
| 3441 | if !matches!(ink, Color::Rgb(..)) { |
| 3442 | continue; |
| 3443 | } |
| 3444 | let settle_spans = crate::tui::history::tool_header_settle_spans(tool, line); |
| 3445 | let progress = since.as_secs_f32() / SETTLE_FLASH_DURATION.as_secs_f32(); |
| 3446 | let strength = codewhale_ratatui::ACTIVITY_SWEEP_PEAK |
| 3447 | * (1.0 - codewhale_ratatui::MotionEasing::EaseOut.apply(progress)); |
| 3448 | for index in settle_spans { |
| 3449 | let Some(span) = line.spans.get_mut(index) else { |
| 3450 | continue; |
| 3451 | }; |
| 3452 | let Some(fg) = span.style.fg else { |
| 3453 | continue; |
| 3454 | }; |
| 3455 | let Some(ground) = span |
| 3456 | .style |
| 3457 | .bg |
| 3458 | .map(|bg| { |
| 3459 | palette::adapt_bg_for_palette_mode( |
| 3460 | palette::adapt_bg_for_theme(bg, theme_id, ui_theme), |
| 3461 | ui_theme.mode, |
| 3462 | ) |
| 3463 | }) |
| 3464 | .filter(|bg| palette::resolvable_rgb(*bg).is_some()) |
| 3465 | .or(effective_ground) |
| 3466 | else { |
| 3467 | continue; |
| 3468 | }; |
| 3469 | let mapped = palette::adapt_fg_for_palette_mode( |
| 3470 | palette::adapt_fg_for_theme(fg, theme_id, ui_theme), |
| 3471 | ground, |
| 3472 | ui_theme.mode, |
| 3473 | ); |
| 3474 | let target = if mapped == ink { |
| 3475 | ui_theme.text_body |
| 3476 | } else { |
| 3477 | ink |
| 3478 | }; |
| 3479 | let next = codewhale_ratatui::activity_sweep_ink(mapped, ground, target, strength); |
| 3480 | if next != mapped { |
| 3481 | span.style = span.style.fg(next); |
| 3482 | visible = true; |
| 3483 | } |
| 3484 | } |
| 3485 | } |
| 3486 | visible |
| 3487 | } |
| 3488 | |
| 3489 | fn sweep_span_extent( |
| 3490 | line: &mut Line<'static>, |
| 3491 | extent: std::ops::Range<usize>, |
| 3492 | elapsed: Duration, |
| 3493 | theme_id: palette::ThemeId, |
| 3494 | ui_theme: &palette::UiTheme, |
| 3495 | highlight: Color, |
| 3496 | effective_ground: Option<Color>, |
| 3497 | ) -> bool { |
| 3498 | use unicode_segmentation::UnicodeSegmentation as _; |
| 3499 | let width: usize = line.spans[extent.clone()].iter().map(Span::width).sum(); |
| 3500 | let mut sweepable = false; |
| 3501 | let mut swept: Vec<Span<'static>> = Vec::new(); |
| 3502 | let mut offset = 0usize; |
| 3503 | for span in &line.spans[extent.clone()] { |
| 3504 | let span_ground = span |
| 3505 | .style |
| 3506 | .bg |
| 3507 | .map(|bg| { |
| 3508 | palette::adapt_bg_for_palette_mode( |
| 3509 | palette::adapt_bg_for_theme(bg, theme_id, ui_theme), |
| 3510 | ui_theme.mode, |
| 3511 | ) |
| 3512 | }) |
| 3513 | .filter(|bg| palette::resolvable_rgb(*bg).is_some()) |
| 3514 | .or(effective_ground); |
| 3515 | for grapheme in span.content.graphemes(true) { |
| 3516 | let cells = grapheme_display_width(grapheme); |
| 3517 | let mut style = span.style; |
| 3518 | if cells > 0 |
| 3519 | && !grapheme.chars().all(char::is_whitespace) |
| 3520 | && let Some(fg) = span.style.fg |
| 3521 | && let Some(ground) = span_ground |
| 3522 | { |
| 3523 | let mapped_fg = palette::adapt_fg_for_palette_mode( |
| 3524 | palette::adapt_fg_for_theme(fg, theme_id, ui_theme), |
| 3525 | ground, |
| 3526 | ui_theme.mode, |
| 3527 | ); |
| 3528 | if codewhale_ratatui::activity_sweep_ink( |
| 3529 | mapped_fg, |
| 3530 | ground, |
| 3531 | highlight, |
| 3532 | codewhale_ratatui::ACTIVITY_SWEEP_PEAK, |
| 3533 | ) != mapped_fg |
| 3534 | { |
| 3535 | sweepable = true; |
| 3536 | } |
| 3537 | let strength = codewhale_ratatui::activity_sweep_strength( |
| 3538 | elapsed, |
| 3539 | width, |
| 3540 | offset as f32 + (cells.saturating_sub(1)) as f32 / 2.0, |
| 3541 | ); |
| 3542 | if strength > 0.0 { |
| 3543 | let next = codewhale_ratatui::activity_sweep_ink( |
| 3544 | mapped_fg, ground, highlight, strength, |
| 3545 | ); |
| 3546 | if next != mapped_fg { |
| 3547 | style = style.fg(next); |
| 3548 | } |
| 3549 | } |
| 3550 | } |
| 3551 | offset += cells; |
| 3552 | match swept.last_mut() { |
| 3553 | Some(last) if last.style == style => last.content.to_mut().push_str(grapheme), |
| 3554 | _ => swept.push(Span::styled(grapheme.to_string(), style)), |
| 3555 | } |
| 3556 | } |
| 3557 | } |
| 3558 | if sweepable { |
| 3559 | line.spans.splice(extent, swept); |
| 3560 | } |
| 3561 | sweepable |
| 3562 | } |
| 3563 | |
| 3564 | #[cfg(test)] |
| 3565 | fn apply_selection_to_line( |
| 3566 | line: &Line<'static>, |
| 3567 | start: usize, |
| 3568 | end: usize, |
| 3569 | style: Style, |
| 3570 | ) -> Vec<Span<'static>> { |
| 3571 | codewhale_ratatui::transcript_selected_spans_measured( |
| 3572 | line, |
| 3573 | start, |
| 3574 | end, |
| 3575 | style, |
| 3576 | grapheme_display_width, |
| 3577 | ) |
| 3578 | } |
| 3579 | |
| 3580 | /// The "fully idle" predicate: nothing in the transcript, nothing running, |
| 3581 | /// nothing pending. It gates the idle ocean, and — because the idle ocean has |
| 3582 | /// a row floor the layout has to respect — it also gates how many rows the |
| 3583 | /// work rail is allowed to take. Evaluate it *once* per frame in |
| 3584 | /// [`crate::tui::ui::render`] and thread the result, so the reservation and |
| 3585 | /// the render can never disagree inside a single frame. |
| 3586 | pub(crate) fn should_render_empty_state(app: &App) -> bool { |
| 3587 | if app.launch.visible && app.launch.return_to_session { |
| 3588 | return true; |
| 3589 | } |
| 3590 | let active_is_empty = app |
| 3591 | .active_cell |
| 3592 | .as_ref() |
| 3593 | .is_none_or(crate::tui::active_cell::ActiveCell::is_empty); |
| 3594 | app.history.is_empty() |
| 3595 | && active_is_empty |
| 3596 | && !app.is_loading |
| 3597 | && !app.is_compacting |
| 3598 | && !app.is_purging |
| 3599 | && !app.attention_hold_active() |
| 3600 | && app.task_panel.is_empty() |
| 3601 | // Live work suppresses the empty state. On lock contention, treat |
| 3602 | // the todo store as non-empty rather than flash the empty ocean. |
| 3603 | && !app |
| 3604 | .todos |
| 3605 | .try_lock() |
| 3606 | .map(|todos| !todos.snapshot().is_empty()) |
| 3607 | .unwrap_or(true) |
| 3608 | && app.goal.objective.is_none() |
| 3609 | && app.paused_goal_objective.is_none() |
| 3610 | } |
| 3611 | |
| 3612 | fn build_empty_state_lines(app: &App, area: Rect) -> Vec<Line<'static>> { |
| 3613 | crate::tui::underwater::empty_state_lines(app, area) |
| 3614 | } |
| 3615 | |
| 3616 | #[cfg(test)] |
| 3617 | fn composer_top_padding(content_lines: usize, rows_budget: usize) -> usize { |
| 3618 | codewhale_ratatui::native_composer_top_padding(content_lines, rows_budget) |
| 3619 | } |
| 3620 | |
| 3621 | /// Placeholder text shown when the composer input is empty. |
| 3622 | #[cfg(test)] |
| 3623 | const COMPOSER_PLACEHOLDER: &str = "Write a task or use /."; |
| 3624 | |
| 3625 | /// How many visual rows the empty-input placeholder occupies after wrapping. |
| 3626 | #[cfg(test)] |
| 3627 | fn placeholder_visual_lines(content_width: usize) -> usize { |
| 3628 | placeholder_visual_lines_for(COMPOSER_PLACEHOLDER, content_width) |
| 3629 | } |
| 3630 | |
| 3631 | #[cfg(test)] |
| 3632 | fn placeholder_visual_lines_for(placeholder: &str, content_width: usize) -> usize { |
| 3633 | wrap_text(placeholder, content_width).len().max(1) |
| 3634 | } |
| 3635 | |
| 3636 | pub(crate) fn composer_empty_hint_text(app: &App) -> Cow<'static, str> { |
| 3637 | if let Some(placeholder) = crate::tui::agent_focus::composer_placeholder(app) { |
| 3638 | Cow::Owned(placeholder) |
| 3639 | } else if app.is_history_search_active() { |
| 3640 | app.tr(MessageId::HistorySearchPlaceholder) |
| 3641 | } else if !app.offline_mode && app.queued_draft.is_none() && !app.queued_messages.is_empty() { |
| 3642 | app.tr(MessageId::ComposerPlaceholderSendNow) |
| 3643 | } else if app.is_loading { |
| 3644 | app.tr(MessageId::ComposerPlaceholderFollowUp) |
| 3645 | } else { |
| 3646 | app.tr(MessageId::ComposerPlaceholder) |
| 3647 | } |
| 3648 | } |
| 3649 | |
| 3650 | /// Live label for what portable bare Enter will do with the current draft. |
| 3651 | /// |
| 3652 | /// The quiet composer and the enclosed panel share this so the action is |
| 3653 | /// visible before submit (#4703) without teaching internal "steer" vocabulary. |
| 3654 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 3655 | pub(crate) struct ComposerSubmitHint { |
| 3656 | pub text: String, |
| 3657 | pub color: Color, |
| 3658 | } |
| 3659 | |
| 3660 | pub(crate) fn composer_submit_hint(app: &App, clipped: bool) -> Option<ComposerSubmitHint> { |
| 3661 | use crate::tui::app::{ComposerSubmitAction, ComposerSubmitChord, SubmitDisposition}; |
| 3662 | |
| 3663 | let queue_count = app.queued_message_count(); |
| 3664 | let (text, color) = match app.decide_composer_submit(ComposerSubmitChord::Enter) { |
| 3665 | ComposerSubmitAction::Submit(SubmitDisposition::Immediate) => { |
| 3666 | if queue_count == 0 { |
| 3667 | return (clipped && app.oversized_paste_full_text.is_none()).then(|| { |
| 3668 | let binding = crate::tui::shell_key_routing::binding( |
| 3669 | crate::tui::shell_key_routing::ShellBindingId::ExternalEditor, |
| 3670 | ); |
| 3671 | ComposerSubmitHint { |
| 3672 | text: app.tr(MessageId::ComposerHintLongDraft).replace( |
| 3673 | "{shortcut}", |
| 3674 | &crate::tui::shell_key_routing::display_chord(binding.footer_chord), |
| 3675 | ), |
| 3676 | color: app.ui_theme.text_hint, |
| 3677 | } |
| 3678 | }); |
| 3679 | } |
| 3680 | ( |
| 3681 | app.tr(MessageId::ComposerHintSendWithQueue) |
| 3682 | .replace("{count}", &queue_count.to_string()), |
| 3683 | palette::WHALE_ACTION, |
| 3684 | ) |
| 3685 | } |
| 3686 | ComposerSubmitAction::Submit(SubmitDisposition::Queue) => { |
| 3687 | if app.offline_mode { |
| 3688 | let id = if app.onboarding_explore_offline { |
| 3689 | MessageId::ComposerHintOfflineConnect |
| 3690 | } else { |
| 3691 | MessageId::ComposerHintOfflineQueue |
| 3692 | }; |
| 3693 | (app.tr(id).into_owned(), palette::STATUS_WARNING) |
| 3694 | } else if queue_count > 0 { |
| 3695 | ( |
| 3696 | app.tr(MessageId::ComposerHintQueueWithCount) |
| 3697 | .replace("{count}", &queue_count.saturating_add(1).to_string()), |
| 3698 | palette::WHALE_ACTION, |
| 3699 | ) |
| 3700 | } else { |
| 3701 | ( |
| 3702 | app.tr(MessageId::ComposerHintQueue).into_owned(), |
| 3703 | palette::WHALE_ACTION, |
| 3704 | ) |
| 3705 | } |
| 3706 | } |
| 3707 | ComposerSubmitAction::Submit(SubmitDisposition::Steer) => ( |
| 3708 | app.tr(MessageId::ComposerHintSendIntoTurn).into_owned(), |
| 3709 | palette::WHALE_ACTION, |
| 3710 | ), |
| 3711 | ComposerSubmitAction::SendQueuedNow => ( |
| 3712 | app.tr(MessageId::ComposerHintSendNow).into_owned(), |
| 3713 | palette::WHALE_ACTION, |
| 3714 | ), |
| 3715 | ComposerSubmitAction::Noop => return None, |
| 3716 | }; |
| 3717 | let text = if app.composer_multiline_mode && !app.input.is_empty() { |
| 3718 | format!( |
| 3719 | "{}{text}", |
| 3720 | crate::tui::shell_key_routing::display_chord("Alt+") |
| 3721 | ) |
| 3722 | } else { |
| 3723 | text |
| 3724 | }; |
| 3725 | Some(ComposerSubmitHint { text, color }) |
| 3726 | } |
| 3727 | |
| 3728 | #[cfg(test)] |
| 3729 | pub(crate) fn empty_composer_visual_rows( |
| 3730 | _hint: Option<&str>, |
| 3731 | _content_width: usize, |
| 3732 | _rows_budget: usize, |
| 3733 | ) -> usize { |
| 3734 | 1 |
| 3735 | } |
| 3736 | |
| 3737 | pub(crate) fn composer_chat_color(app: &App) -> Option<Color> { |
| 3738 | let name = app.composer_color.as_deref()?; |
| 3739 | let (dark, light, ansi) = match name { |
| 3740 | "red" => ((0xF2, 0x5F, 0x5C), (0xC6, 0x28, 0x28), Color::Red), |
| 3741 | "orange" => ((0xF0, 0x82, 0x32), (0xB8, 0x5A, 0x0D), Color::LightRed), |
| 3742 | "amber" => ((0xE8, 0xC5, 0x47), (0x8A, 0x6A, 0x00), Color::Yellow), |
| 3743 | "green" => ((0x7B, 0xCB, 0x6B), (0x2E, 0x7D, 0x32), Color::Green), |
| 3744 | "cyan" => ((0x4C, 0xC9, 0xD9), (0x00, 0x79, 0x8A), Color::Cyan), |
| 3745 | "blue" => ((0x5B, 0x8D, 0xEF), (0x1F, 0x5F, 0xCC), Color::Blue), |
| 3746 | "purple" => ((0xBE, 0x78, 0xEC), (0x8C, 0x3C, 0xB9), Color::Magenta), |
| 3747 | "pink" => ((0xF0, 0x7C, 0xC0), (0xB8, 0x32, 0x7F), Color::LightMagenta), |
| 3748 | _ => return None, |
| 3749 | }; |
| 3750 | if app.theme_id == palette::ThemeId::Terminal { |
| 3751 | return Some(ansi); |
| 3752 | } |
| 3753 | let (r, g, b) = match app.ui_theme.mode { |
| 3754 | palette::PaletteMode::Light | palette::PaletteMode::SolarizedLight => light, |
| 3755 | _ => dark, |
| 3756 | }; |
| 3757 | Some(palette::enforce_contrast( |
| 3758 | Color::Rgb(r, g, b), |
| 3759 | app.ui_theme.composer_bg, |
| 3760 | palette::SECONDARY_CHROME_CONTRAST, |
| 3761 | )) |
| 3762 | } |
| 3763 | |
| 3764 | pub(crate) fn composer_max_height(density: ComposerDensity) -> u16 { |
| 3765 | composer_native_density(density).max_rows() |
| 3766 | } |
| 3767 | |
| 3768 | #[cfg(test)] |
| 3769 | fn composer_height( |
| 3770 | input: &str, |
| 3771 | area_width: u16, |
| 3772 | available_height: u16, |
| 3773 | extra_lines: usize, |
| 3774 | density: ComposerDensity, |
| 3775 | show_panel: bool, |
| 3776 | ) -> u16 { |
| 3777 | let has_panel = enclosed_composer_panel_fits(show_panel, area_width, available_height); |
| 3778 | // Measure through the same border- and submit-aware plane that rendering, |
| 3779 | // cursor placement, the frame viewport, and mouse mapping use. A draft |
| 3780 | // that wraps here therefore cannot consume the painted `[↵]` cells later. |
| 3781 | let measurement_area = Rect::new(0, 0, area_width, if has_panel { 3 } else { 1 }); |
| 3782 | let content_width = |
| 3783 | composer_content_geometry(composer_inner_area(measurement_area, has_panel), false) |
| 3784 | .text_width(); |
| 3785 | let mut line_count = wrap_input_lines(input, content_width).len(); |
| 3786 | if line_count == 0 { |
| 3787 | line_count = 1; |
| 3788 | } |
| 3789 | crate::tui::composer_chrome::desired_height( |
| 3790 | line_count, |
| 3791 | extra_lines, |
| 3792 | available_height, |
| 3793 | density, |
| 3794 | has_panel, |
| 3795 | ) |
| 3796 | } |
| 3797 | |
| 3798 | /// A single entry in the slash-command autocomplete popup. |
| 3799 | pub(crate) struct SlashMenuEntry { |
| 3800 | pub name: String, |
| 3801 | pub description: String, |
| 3802 | pub is_skill: bool, |
| 3803 | /// Matching pinyin/alias prefix hint, e.g. when user types `/bang` and |
| 3804 | /// the command `/help` matches via alias `bangzhu`. |
| 3805 | pub alias_hint: Option<String>, |
| 3806 | } |
| 3807 | |
| 3808 | /// Check if all characters in `needle` appear in `haystack` in order |
| 3809 | /// (subsequence matching — fuzzy filtering). |
| 3810 | fn fuzzy_chars_in_order(needle: &str, haystack: &str) -> bool { |
| 3811 | let mut chars = needle.chars(); |
| 3812 | let mut current = match chars.next() { |
| 3813 | Some(c) => c, |
| 3814 | None => return true, |
| 3815 | }; |
| 3816 | for ch in haystack.chars() { |
| 3817 | if ch == current { |
| 3818 | if let Some(next) = chars.next() { |
| 3819 | current = next; |
| 3820 | } else { |
| 3821 | return true; |
| 3822 | } |
| 3823 | } |
| 3824 | } |
| 3825 | false |
| 3826 | } |
| 3827 | |
| 3828 | #[cfg(test)] |
| 3829 | pub(crate) fn slash_completion_hints( |
| 3830 | input: &str, |
| 3831 | limit: usize, |
| 3832 | cached_skills: &[(String, String)], |
| 3833 | locale: codewhale_localization::Locale, |
| 3834 | workspace: Option<&std::path::Path>, |
| 3835 | api_provider: ProviderKind, |
| 3836 | ) -> Vec<SlashMenuEntry> { |
| 3837 | let model_candidates = all_catalog_models_for_provider(api_provider); |
| 3838 | slash_completion_hints_with_model_candidates( |
| 3839 | input, |
| 3840 | limit, |
| 3841 | cached_skills, |
| 3842 | locale, |
| 3843 | workspace, |
| 3844 | &model_candidates, |
| 3845 | ) |
| 3846 | } |
| 3847 | |
| 3848 | /// Slash-menu rows for `/<command> ` and `/<command> <partial>`. |
| 3849 | /// |
| 3850 | /// Once the name is typed the menu used to go blank, so `/workspace |
| 3851 | /// worktrees` — the only route to the git worktree manager — was unfindable |
| 3852 | /// without already knowing it (#5952). The rows come from the registry's own |
| 3853 | /// `usage` string: the usage line itself as the head row, then the literal |
| 3854 | /// subcommands that line declares, filtered by what has been typed. There is |
| 3855 | /// no second place argument documentation is written down. |
| 3856 | fn command_argument_hints(trimmed_input: &str, limit: usize) -> Vec<SlashMenuEntry> { |
| 3857 | if limit == 0 { |
| 3858 | return Vec::new(); |
| 3859 | } |
| 3860 | let Some((command_token, rest)) = trimmed_input |
| 3861 | .trim_start_matches('/') |
| 3862 | .split_once(char::is_whitespace) |
| 3863 | else { |
| 3864 | return Vec::new(); |
| 3865 | }; |
| 3866 | let Some(info) = commands::get_command_info(command_token) else { |
| 3867 | return Vec::new(); |
| 3868 | }; |
| 3869 | if !info.show_in_slash_completion(command_token) { |
| 3870 | return Vec::new(); |
| 3871 | } |
| 3872 | // Only the first argument word is a subcommand. Once a second word is |
| 3873 | // being typed the usage line has nothing left to offer, so the menu gets |
| 3874 | // out of the way exactly as it does today. |
| 3875 | let arg_prefix = rest.trim_start(); |
| 3876 | if arg_prefix.contains(char::is_whitespace) { |
| 3877 | return Vec::new(); |
| 3878 | } |
| 3879 | let arg_prefix_lower = arg_prefix.to_ascii_lowercase(); |
| 3880 | |
| 3881 | let canonical = format!("/{}", info.name); |
| 3882 | let mut entries: Vec<SlashMenuEntry> = Vec::new(); |
| 3883 | // The head row states what the command accepts. Its name is the command |
| 3884 | // itself, so selecting it re-inserts what is already typed — the row can |
| 3885 | // be arrowed through without losing the argument being written. It is |
| 3886 | // dropped once filtering starts so Tab still completes a single match. |
| 3887 | if arg_prefix.is_empty() && info.usage != canonical { |
| 3888 | entries.push(SlashMenuEntry { |
| 3889 | name: canonical.clone(), |
| 3890 | description: info.usage.to_string(), |
| 3891 | is_skill: false, |
| 3892 | alias_hint: None, |
| 3893 | }); |
| 3894 | } |
| 3895 | for subcommand in info.subcommands() { |
| 3896 | if !subcommand.starts_with(&arg_prefix_lower) { |
| 3897 | continue; |
| 3898 | } |
| 3899 | entries.push(SlashMenuEntry { |
| 3900 | name: format!("{canonical} {subcommand}"), |
| 3901 | // The subcommand is the whole row: the command's own description |
| 3902 | // is already one row up on the head row, and repeating it beside |
| 3903 | // every verb would say the same sentence a dozen times. |
| 3904 | description: String::new(), |
| 3905 | is_skill: false, |
| 3906 | alias_hint: None, |
| 3907 | }); |
| 3908 | } |
| 3909 | entries.truncate(limit); |
| 3910 | entries |
| 3911 | } |
| 3912 | |
| 3913 | #[cfg(test)] |
| 3914 | pub(crate) fn slash_completion_hints_with_model_candidates( |
| 3915 | input: &str, |
| 3916 | limit: usize, |
| 3917 | cached_skills: &[(String, String)], |
| 3918 | locale: codewhale_localization::Locale, |
| 3919 | workspace: Option<&std::path::Path>, |
| 3920 | model_candidates: &[String], |
| 3921 | ) -> Vec<SlashMenuEntry> { |
| 3922 | slash_completion_hints_for_plugins( |
| 3923 | input, |
| 3924 | limit, |
| 3925 | cached_skills, |
| 3926 | locale, |
| 3927 | workspace, |
| 3928 | model_candidates, |
| 3929 | None, |
| 3930 | ) |
| 3931 | } |
| 3932 | pub(crate) fn slash_completion_hints_for_plugins( |
| 3933 | input: &str, |
| 3934 | limit: usize, |
| 3935 | cached_skills: &[(String, String)], |
| 3936 | locale: codewhale_localization::Locale, |
| 3937 | workspace: Option<&std::path::Path>, |
| 3938 | model_candidates: &[String], |
| 3939 | plugins: Option<&codewhale_plugins::PluginRegistry>, |
| 3940 | ) -> Vec<SlashMenuEntry> { |
| 3941 | if !super::app::looks_like_slash_command_input(input) { |
| 3942 | return Vec::new(); |
| 3943 | } |
| 3944 | |
| 3945 | let trimmed = input.trim_start(); |
| 3946 | // `$skillname` mode: only skill completions, prefixed with `$`. |
| 3947 | if trimmed.starts_with('$') { |
| 3948 | let prefix = trimmed.trim_start_matches('$').to_ascii_lowercase(); |
| 3949 | let mut entries: Vec<SlashMenuEntry> = Vec::new(); |
| 3950 | for (skill_name, skill_desc) in cached_skills { |
| 3951 | let skill_name_lower = skill_name.to_ascii_lowercase(); |
| 3952 | if skill_name_lower.starts_with(&prefix) |
| 3953 | || skill_name_lower.contains(&prefix) |
| 3954 | || fuzzy_chars_in_order(&prefix, &skill_name_lower) |
| 3955 | { |
| 3956 | entries.push(SlashMenuEntry { |
| 3957 | name: format!("${skill_name}"), |
| 3958 | description: skill_desc.clone(), |
| 3959 | is_skill: true, |
| 3960 | alias_hint: None, |
| 3961 | }); |
| 3962 | } |
| 3963 | } |
| 3964 | entries.sort_by(|a, b| a.name.cmp(&b.name)); |
| 3965 | entries.dedup_by(|a, b| a.name == b.name); |
| 3966 | return entries.into_iter().take(limit).collect(); |
| 3967 | } |
| 3968 | |
| 3969 | let prefix = input.trim_start_matches('/'); |
| 3970 | let completing_skill_arg = prefix.strip_prefix("skill ").map(str::trim_start); |
| 3971 | let completing_model_arg = prefix.strip_prefix("model ").map(str::trim_start); |
| 3972 | if input.contains(char::is_whitespace) |
| 3973 | && completing_skill_arg.is_none() |
| 3974 | && completing_model_arg.is_none() |
| 3975 | { |
| 3976 | return command_argument_hints(trimmed, limit); |
| 3977 | } |
| 3978 | let mut entries: Vec<SlashMenuEntry> = Vec::new(); |
| 3979 | let prefix_lower = prefix.to_ascii_lowercase(); |
| 3980 | |
| 3981 | // ── Phase 1: prefix (starts_with) matches ───────────────────────── |
| 3982 | // Highest priority — preserves existing exact-prefix completion. |
| 3983 | if completing_skill_arg.is_none() && completing_model_arg.is_none() { |
| 3984 | let load = |registry: &commands::user_registry::UserCommandRegistry| { |
| 3985 | let all_user_commands = registry.iter().collect::<Vec<_>>(); |
| 3986 | let user_commands = all_user_commands |
| 3987 | .iter() |
| 3988 | .copied() |
| 3989 | .filter(|cmd| !cmd.hidden) |
| 3990 | .collect::<Vec<_>>(); |
| 3991 | let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new(); |
| 3992 | |
| 3993 | for name in |
| 3994 | all_command_names_matching_loaded(prefix, &user_commands, &all_user_commands) |
| 3995 | { |
| 3996 | seen.insert(name.clone()); |
| 3997 | let command_key = name.trim_start_matches('/'); |
| 3998 | push_command_entry( |
| 3999 | &mut entries, |
| 4000 | &name, |
| 4001 | command_key, |
| 4002 | &prefix_lower, |
| 4003 | locale, |
| 4004 | &all_user_commands, |
| 4005 | ); |
| 4006 | } |
| 4007 | |
| 4008 | // ── Phase 2: contains (substring) matches ───────────────────────── |
| 4009 | // Medium priority — broader catching. |
| 4010 | for cmd in commands::command_infos() { |
| 4011 | let name = format!("/{}", cmd.name); |
| 4012 | if seen.contains(&name) { |
| 4013 | continue; |
| 4014 | } |
| 4015 | let cmd_lower = cmd.name.to_ascii_lowercase(); |
| 4016 | let name_match = cmd_lower.contains(&prefix_lower); |
| 4017 | let alias_matches = |
| 4018 | |alias: &str| alias.to_ascii_lowercase().contains(&prefix_lower); |
| 4019 | if builtin_visible_for_completion_match( |
| 4020 | cmd, |
| 4021 | &all_user_commands, |
| 4022 | &prefix_lower, |
| 4023 | name_match, |
| 4024 | alias_matches, |
| 4025 | ) { |
| 4026 | seen.insert(name.clone()); |
| 4027 | push_command_entry( |
| 4028 | &mut entries, |
| 4029 | &name, |
| 4030 | cmd.name, |
| 4031 | &prefix_lower, |
| 4032 | locale, |
| 4033 | &all_user_commands, |
| 4034 | ); |
| 4035 | } |
| 4036 | } |
| 4037 | for cmd in &user_commands { |
| 4038 | let name = format!("/{}", cmd.name); |
| 4039 | if seen.contains(&name) { |
| 4040 | continue; |
| 4041 | } |
| 4042 | let alias_match = cmd.aliases.iter().any(|a| a.contains(&prefix_lower)); |
| 4043 | if cmd.name.contains(&prefix_lower) || alias_match { |
| 4044 | seen.insert(name.clone()); |
| 4045 | push_command_entry( |
| 4046 | &mut entries, |
| 4047 | &name, |
| 4048 | &cmd.name, |
| 4049 | &prefix_lower, |
| 4050 | locale, |
| 4051 | &all_user_commands, |
| 4052 | ); |
| 4053 | } |
| 4054 | } |
| 4055 | |
| 4056 | // ── Phase 3: fuzzy subsequence matches ──────────────────────────── |
| 4057 | // Lowest priority — characters in order, not necessarily consecutive. |
| 4058 | for cmd in commands::command_infos() { |
| 4059 | let name = format!("/{}", cmd.name); |
| 4060 | if seen.contains(&name) { |
| 4061 | continue; |
| 4062 | } |
| 4063 | let cmd_lower = cmd.name.to_ascii_lowercase(); |
| 4064 | let name_match = fuzzy_chars_in_order(&prefix_lower, &cmd_lower); |
| 4065 | let alias_matches = |alias: &str| fuzzy_chars_in_order(&prefix_lower, alias); |
| 4066 | if builtin_visible_for_completion_match( |
| 4067 | cmd, |
| 4068 | &all_user_commands, |
| 4069 | &prefix_lower, |
| 4070 | name_match, |
| 4071 | alias_matches, |
| 4072 | ) { |
| 4073 | seen.insert(name.clone()); |
| 4074 | push_command_entry( |
| 4075 | &mut entries, |
| 4076 | &name, |
| 4077 | cmd.name, |
| 4078 | &prefix_lower, |
| 4079 | locale, |
| 4080 | &all_user_commands, |
| 4081 | ); |
| 4082 | } |
| 4083 | } |
| 4084 | for cmd in &user_commands { |
| 4085 | let name = format!("/{}", cmd.name); |
| 4086 | if seen.contains(&name) { |
| 4087 | continue; |
| 4088 | } |
| 4089 | let alias_match = cmd |
| 4090 | .aliases |
| 4091 | .iter() |
| 4092 | .any(|a| fuzzy_chars_in_order(&prefix_lower, a)); |
| 4093 | if fuzzy_chars_in_order(&prefix_lower, &cmd.name) || alias_match { |
| 4094 | seen.insert(name.clone()); |
| 4095 | push_command_entry( |
| 4096 | &mut entries, |
| 4097 | &name, |
| 4098 | &cmd.name, |
| 4099 | &prefix_lower, |
| 4100 | locale, |
| 4101 | &all_user_commands, |
| 4102 | ); |
| 4103 | } |
| 4104 | } |
| 4105 | }; |
| 4106 | if let Some(plugins) = plugins { |
| 4107 | commands::user_registry::with_registry_for_plugins(plugins, load); |
| 4108 | } else { |
| 4109 | commands::user_registry::with_registry_for_workspace(workspace, load); |
| 4110 | } |
| 4111 | } |
| 4112 | |
| 4113 | // ── Skills (only after user has typed `/skill `) ────────────────── |
| 4114 | // `/model <prefix>` is the only slash-argument path that needs the |
| 4115 | // provider inventory. Filter it here instead of rebuilding that inventory |
| 4116 | // for every generic slash-menu keystroke. |
| 4117 | if let Some(model_prefix) = completing_model_arg { |
| 4118 | let model_prefix = model_prefix.to_ascii_lowercase(); |
| 4119 | for model_name in model_candidates { |
| 4120 | let lower = model_name.to_ascii_lowercase(); |
| 4121 | if lower.starts_with(&model_prefix) |
| 4122 | || lower.contains(&model_prefix) |
| 4123 | || fuzzy_chars_in_order(&model_prefix, &lower) |
| 4124 | { |
| 4125 | entries.push(SlashMenuEntry { |
| 4126 | name: format!("/model {model_name}"), |
| 4127 | description: String::from("Switch to this model"), |
| 4128 | is_skill: false, |
| 4129 | alias_hint: None, |
| 4130 | }); |
| 4131 | } |
| 4132 | } |
| 4133 | } |
| 4134 | |
| 4135 | let skill_prefix = completing_skill_arg.unwrap_or(prefix).to_ascii_lowercase(); |
| 4136 | if completing_skill_arg.is_some() { |
| 4137 | for (skill_name, skill_desc) in cached_skills { |
| 4138 | let skill_name_lower = skill_name.to_ascii_lowercase(); |
| 4139 | if skill_name_lower.starts_with(&skill_prefix) { |
| 4140 | entries.push(SlashMenuEntry { |
| 4141 | name: format!("/skill {skill_name}"), |
| 4142 | description: skill_desc.clone(), |
| 4143 | is_skill: true, |
| 4144 | alias_hint: None, |
| 4145 | }); |
| 4146 | } |
| 4147 | } |
| 4148 | // Skills: contains fuzzy fallback |
| 4149 | for (skill_name, skill_desc) in cached_skills { |
| 4150 | let skill_name_lower = skill_name.to_ascii_lowercase(); |
| 4151 | if skill_name_lower.contains(&skill_prefix) |
| 4152 | && !entries |
| 4153 | .iter() |
| 4154 | .any(|e| e.name == format!("/skill {skill_name}")) |
| 4155 | { |
| 4156 | entries.push(SlashMenuEntry { |
| 4157 | name: format!("/skill {skill_name}"), |
| 4158 | description: skill_desc.clone(), |
| 4159 | is_skill: true, |
| 4160 | alias_hint: None, |
| 4161 | }); |
| 4162 | } |
| 4163 | } |
| 4164 | for (skill_name, skill_desc) in cached_skills { |
| 4165 | let skill_name_lower = skill_name.to_ascii_lowercase(); |
| 4166 | if !skill_name_lower.starts_with(&skill_prefix) |
| 4167 | && !skill_name_lower.contains(&skill_prefix) |
| 4168 | && fuzzy_chars_in_order(&skill_prefix, &skill_name_lower) |
| 4169 | { |
| 4170 | entries.push(SlashMenuEntry { |
| 4171 | name: format!("/skill {skill_name}"), |
| 4172 | description: skill_desc.clone(), |
| 4173 | is_skill: true, |
| 4174 | alias_hint: None, |
| 4175 | }); |
| 4176 | } |
| 4177 | } |
| 4178 | } |
| 4179 | |
| 4180 | // Special: /model <name> completions when only /model matches |
| 4181 | if entries.iter().any(|e| e.name == "/model") && prefix_lower.eq_ignore_ascii_case("model") { |
| 4182 | for model_name in model_candidates { |
| 4183 | entries.push(SlashMenuEntry { |
| 4184 | name: format!("/model {model_name}"), |
| 4185 | description: String::from("Switch to this model"), |
| 4186 | is_skill: false, |
| 4187 | alias_hint: None, |
| 4188 | }); |
| 4189 | } |
| 4190 | } |
| 4191 | |
| 4192 | // A bare slash is an invitation, not a manual — but an invitation you |
| 4193 | // cannot walk past is a dead end. The small task-oriented set is sorted |
| 4194 | // to the head below (`root_rank`) instead of being the only thing kept, |
| 4195 | // so the first six rows are unchanged and arrowing down reaches every |
| 4196 | // other command. Founder live-test: "I like how we prioritize the slash |
| 4197 | // thing but it should still be able to find all of them." |
| 4198 | if prefix_lower.is_empty() { |
| 4199 | // Skills are the exception, and for a different reason: they are user |
| 4200 | // content with their own triggers (`$name`, `/skill`), and there can |
| 4201 | // be hundreds. Commands are what this menu is for. |
| 4202 | entries.retain(|entry| !entry.is_skill); |
| 4203 | } |
| 4204 | |
| 4205 | // Rank exact-alias matches above prefix/alias matches so e.g. typing |
| 4206 | // `/q` ranks `/exit` (alias `q` is an exact hit) above `/clear` (alias |
| 4207 | // `qingping` only matches by prefix). Inside each tier, fall back to |
| 4208 | // alphabetical name order for deterministic display (#1811). |
| 4209 | let rank = |entry: &SlashMenuEntry| -> u8 { |
| 4210 | if entry.is_skill { |
| 4211 | return 3; |
| 4212 | } |
| 4213 | let command_key = entry.name.trim_start_matches('/'); |
| 4214 | if command_key.eq_ignore_ascii_case(&prefix_lower) { |
| 4215 | return 0; |
| 4216 | } |
| 4217 | if let Some(info) = commands::get_command_info(command_key) |
| 4218 | && info |
| 4219 | .aliases |
| 4220 | .iter() |
| 4221 | .any(|a| a.eq_ignore_ascii_case(&prefix_lower)) |
| 4222 | { |
| 4223 | return 0; |
| 4224 | } |
| 4225 | if command_key.to_ascii_lowercase().starts_with(&prefix_lower) { |
| 4226 | return 1; |
| 4227 | } |
| 4228 | 2 |
| 4229 | }; |
| 4230 | // Bare `/` follows the deliberately short task sequence. Typed prefixes |
| 4231 | // keep the existing rank/alpha order. |
| 4232 | let root_rank = |entry: &SlashMenuEntry| -> usize { |
| 4233 | if !prefix_lower.is_empty() { |
| 4234 | return 0; |
| 4235 | } |
| 4236 | let command_key = entry.name.trim_start_matches('/'); |
| 4237 | commands::traits::bare_slash_discovery_rank(command_key).unwrap_or(usize::MAX) |
| 4238 | }; |
| 4239 | entries.sort_by(|a, b| { |
| 4240 | root_rank(a) |
| 4241 | .cmp(&root_rank(b)) |
| 4242 | .then_with(|| rank(a).cmp(&rank(b))) |
| 4243 | .then_with(|| a.name.cmp(&b.name)) |
| 4244 | }); |
| 4245 | entries.dedup_by(|a, b| a.name == b.name); |
| 4246 | entries.into_iter().take(limit).collect() |
| 4247 | } |
| 4248 | |
| 4249 | fn all_command_names_matching_loaded( |
| 4250 | prefix: &str, |
| 4251 | user_commands: &[&commands::user_registry::UserCommandMetadata], |
| 4252 | all_user_commands: &[&commands::user_registry::UserCommandMetadata], |
| 4253 | ) -> Vec<String> { |
| 4254 | let prefix = prefix.strip_prefix('/').unwrap_or(prefix).to_lowercase(); |
| 4255 | let mut result: Vec<String> = commands::command_infos() |
| 4256 | .iter() |
| 4257 | .filter(|cmd| { |
| 4258 | builtin_visible_for_completion_match( |
| 4259 | cmd, |
| 4260 | all_user_commands, |
| 4261 | &prefix, |
| 4262 | cmd.name.starts_with(&prefix), |
| 4263 | |alias| alias.starts_with(&prefix), |
| 4264 | ) |
| 4265 | }) |
| 4266 | .map(|cmd| format!("/{}", cmd.name)) |
| 4267 | .collect(); |
| 4268 | |
| 4269 | result.extend(user_commands.iter().filter_map(|command| { |
| 4270 | let name_matches = command.name.starts_with(&prefix); |
| 4271 | let alias_matches = command |
| 4272 | .aliases |
| 4273 | .iter() |
| 4274 | .any(|alias| alias.starts_with(&prefix)); |
| 4275 | (name_matches || alias_matches).then(|| format!("/{}", command.name)) |
| 4276 | })); |
| 4277 | |
| 4278 | result.sort(); |
| 4279 | result.dedup(); |
| 4280 | result |
| 4281 | } |
| 4282 | |
| 4283 | fn builtin_visible_for_completion_match( |
| 4284 | builtin: &commands::CommandInfo, |
| 4285 | user_commands: &[&commands::user_registry::UserCommandMetadata], |
| 4286 | prefix: &str, |
| 4287 | canonical_name_matches: bool, |
| 4288 | alias_matches: impl Fn(&str) -> bool, |
| 4289 | ) -> bool { |
| 4290 | if !builtin.show_in_slash_completion(prefix) { |
| 4291 | return false; |
| 4292 | } |
| 4293 | |
| 4294 | if commands::discovery::user_command_shadows_builtin_canonical(builtin, user_commands) { |
| 4295 | return false; |
| 4296 | } |
| 4297 | |
| 4298 | // Keep the canonical built-in visible when the typed text matches the |
| 4299 | // canonical name, even if a user command shadows one of the built-in's |
| 4300 | // aliases. Example: a user command with alias `/image` must not hide |
| 4301 | // canonical `/attach` for `/att`. |
| 4302 | if canonical_name_matches { |
| 4303 | return true; |
| 4304 | } |
| 4305 | |
| 4306 | // If the built-in is visible only through an alias, hide it when that |
| 4307 | // specific alias is shadowed by a user command. Example: `/image` should |
| 4308 | // complete to the user command, not built-in `/attach` via its `/image` |
| 4309 | // alias. |
| 4310 | builtin.aliases.iter().any(|alias| { |
| 4311 | alias_matches(alias) |
| 4312 | && !commands::discovery::user_command_shadows_builtin_alias(alias, user_commands) |
| 4313 | }) |
| 4314 | } |
| 4315 | |
| 4316 | /// Push a built-in command entry to the slash menu, resolving description |
| 4317 | /// and alias hints. |
| 4318 | fn push_command_entry( |
| 4319 | entries: &mut Vec<SlashMenuEntry>, |
| 4320 | name: &str, |
| 4321 | command_key: &str, |
| 4322 | prefix_lower: &str, |
| 4323 | locale: codewhale_localization::Locale, |
| 4324 | user_commands: &[&commands::user_registry::UserCommandMetadata], |
| 4325 | ) { |
| 4326 | let user_command = user_commands |
| 4327 | .iter() |
| 4328 | .find(|command| command.name == command_key); |
| 4329 | |
| 4330 | let (description, alias_hint) = if let Some(command) = user_command { |
| 4331 | // User command shadows any built-in — use user metadata. |
| 4332 | let mut description = command |
| 4333 | .description |
| 4334 | .clone() |
| 4335 | .unwrap_or_else(|| String::from("User-defined command")); |
| 4336 | if let Some(hint) = command.display_usage() { |
| 4337 | description.push_str(" "); |
| 4338 | description.push_str(hint); |
| 4339 | } |
| 4340 | let alias_hint = if !command_key.to_ascii_lowercase().starts_with(prefix_lower) { |
| 4341 | command |
| 4342 | .aliases |
| 4343 | .iter() |
| 4344 | .find(|alias| { |
| 4345 | alias.starts_with(prefix_lower) |
| 4346 | || alias.contains(prefix_lower) |
| 4347 | || fuzzy_chars_in_order(prefix_lower, alias) |
| 4348 | }) |
| 4349 | .cloned() |
| 4350 | } else { |
| 4351 | None |
| 4352 | }; |
| 4353 | (description, alias_hint) |
| 4354 | } else if let Some(info) = commands::get_command_info(command_key) { |
| 4355 | let unshadowed_aliases = info |
| 4356 | .aliases |
| 4357 | .iter() |
| 4358 | .copied() |
| 4359 | .filter(|alias| { |
| 4360 | !commands::discovery::user_command_shadows_builtin_alias(alias, user_commands) |
| 4361 | }) |
| 4362 | .collect::<Vec<_>>(); |
| 4363 | let hint = if !command_key.to_ascii_lowercase().starts_with(prefix_lower) { |
| 4364 | unshadowed_aliases |
| 4365 | .iter() |
| 4366 | .copied() |
| 4367 | .find(|a| { |
| 4368 | a.to_ascii_lowercase().starts_with(prefix_lower) |
| 4369 | || a.to_ascii_lowercase().contains(prefix_lower) |
| 4370 | || fuzzy_chars_in_order(prefix_lower, &a.to_ascii_lowercase()) |
| 4371 | }) |
| 4372 | .map(str::to_string) |
| 4373 | } else { |
| 4374 | None |
| 4375 | }; |
| 4376 | // Omit aliases already shown in the label (`/clear or /qingping`) so |
| 4377 | // the description does not repeat them (#3990). |
| 4378 | let remaining_aliases: Vec<&str> = unshadowed_aliases |
| 4379 | .into_iter() |
| 4380 | .filter(|alias| hint.as_deref() != Some(*alias)) |
| 4381 | .collect(); |
| 4382 | let desc = if prefix_lower.is_empty() || remaining_aliases.is_empty() { |
| 4383 | info.description_for(locale).to_string() |
| 4384 | } else { |
| 4385 | format!( |
| 4386 | "{} {}", |
| 4387 | info.description_for(locale), |
| 4388 | tr(locale, MessageId::HelpAliasesSuffix).replace( |
| 4389 | "{aliases}", |
| 4390 | &remaining_aliases |
| 4391 | .iter() |
| 4392 | .map(|a| format!("/{a}")) |
| 4393 | .collect::<Vec<_>>() |
| 4394 | .join(&tr(locale, MessageId::ListSeparator)) |
| 4395 | ) |
| 4396 | ) |
| 4397 | }; |
| 4398 | (desc, hint) |
| 4399 | } else { |
| 4400 | (String::from("User-defined command"), None) |
| 4401 | }; |
| 4402 | entries.push(SlashMenuEntry { |
| 4403 | name: name.to_string(), |
| 4404 | description, |
| 4405 | is_skill: false, |
| 4406 | alias_hint, |
| 4407 | }); |
| 4408 | } |
| 4409 | |
| 4410 | #[cfg(test)] |
| 4411 | fn layout_input( |
| 4412 | input: &str, |
| 4413 | cursor: usize, |
| 4414 | width: usize, |
| 4415 | height: usize, |
| 4416 | ) -> (Vec<String>, usize, usize) { |
| 4417 | let (lines, row, col, _) = layout_input_with_scroll(input, cursor, width, height); |
| 4418 | (lines, row, col) |
| 4419 | } |
| 4420 | #[cfg(test)] |
| 4421 | pub fn layout_input_with_scroll( |
| 4422 | input: &str, |
| 4423 | cursor: usize, |
| 4424 | width: usize, |
| 4425 | height: usize, |
| 4426 | ) -> (Vec<String>, usize, usize, usize) { |
| 4427 | let plan = codewhale_ratatui::native_composer_source_plan(input, cursor, width, height); |
| 4428 | ( |
| 4429 | plan.visible.into_iter().map(|(_, text)| text).collect(), |
| 4430 | plan.cursor_row, |
| 4431 | plan.cursor_col, |
| 4432 | plan.scroll_offset, |
| 4433 | ) |
| 4434 | } |
| 4435 | #[cfg(test)] |
| 4436 | fn cursor_row_col(input: &str, cursor: usize, width: usize) -> (usize, usize) { |
| 4437 | codewhale_ratatui::native_composer_source_cursor( |
| 4438 | &codewhale_ratatui::native_composer_source_rows(input, width.max(1)), |
| 4439 | cursor, |
| 4440 | ) |
| 4441 | } |
| 4442 | #[cfg(test)] |
| 4443 | fn wrap_input_lines(input: &str, width: usize) -> Vec<String> { |
| 4444 | if input.is_empty() { |
| 4445 | Vec::new() |
| 4446 | } else { |
| 4447 | codewhale_ratatui::native_composer_source_rows(input, width.max(1)) |
| 4448 | .into_iter() |
| 4449 | .map(|(_, text)| text) |
| 4450 | .collect() |
| 4451 | } |
| 4452 | } |
| 4453 | #[cfg(test)] |
| 4454 | pub use codewhale_ratatui::native_composer_source_rows as wrap_input_lines_for_mouse; |
| 4455 | use codewhale_ratatui::native_composer_wrap_text as wrap_text; |
| 4456 | |
| 4457 | #[cfg(test)] |
| 4458 | mod tests { |
| 4459 | use super::{ |
| 4460 | ACTIVE_REVISION_DOMAIN, ApprovalWidget, COMPOSER_PANEL_HEIGHT, COMPOSER_PLACEHOLDER, |
| 4461 | ChatWidget, ComposerWidget, Renderable, SETTLE_FLASH_DURATION, SlashMenuEntry, |
| 4462 | active_composer_submit_rect, active_entry_revision, apply_activity_sweep, |
| 4463 | apply_selection_to_line, apply_send_flash, apply_settle_flash, approval_palette, |
| 4464 | approval_truncation_hint, build_empty_state_lines, composer_content_geometry, |
| 4465 | composer_empty_hint_text, composer_height, composer_inner_area, composer_max_height, |
| 4466 | composer_submit_hint, composer_top_padding, cursor_row_col, empty_composer_visual_rows, |
| 4467 | enclosed_composer_panel_fits, fish_heading, fish_mark, history_entry_revision, |
| 4468 | layout_input, layout_input_with_scroll, placeholder_visual_lines, push_command_entry, |
| 4469 | receipt_is_settling, revision_in_domain, should_render_empty_state, slash_completion_hints, |
| 4470 | test_native_ocean_caps, tool_run_summary_revision, wrap_input_lines, |
| 4471 | wrap_input_lines_for_mouse, wrap_text, |
| 4472 | }; |
| 4473 | use crate::tui::active_cell::ActiveCell; |
| 4474 | use crate::tui::app::{ |
| 4475 | App, ComposerDensity, QueuedMessage, TaskPanelEntry, TaskPanelEntryKind, ToolCollapseMode, |
| 4476 | TranscriptSpacing, TuiOptions, |
| 4477 | }; |
| 4478 | use crate::tui::history::{ |
| 4479 | ExecCell, ExecSource, GenericToolCell, HistoryCell, ToolCell, ToolRun, ToolStatus, |
| 4480 | }; |
| 4481 | use crate::tui::views::ModalView; |
| 4482 | use codewhale_config::ProviderKind; |
| 4483 | use codewhale_localization::Locale; |
| 4484 | use codewhale_palette as palette; |
| 4485 | use codewhale_runtime::config::Config; |
| 4486 | use codewhale_tui_kit::scrolling::{TranscriptLineMeta, TranscriptScroll}; |
| 4487 | use crossterm::event::{ |
| 4488 | KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, |
| 4489 | }; |
| 4490 | use ratatui::{ |
| 4491 | buffer::Buffer, |
| 4492 | layout::Rect, |
| 4493 | style::{Color, Modifier, Style}, |
| 4494 | text::{Line, Span}, |
| 4495 | }; |
| 4496 | use std::time::Duration; |
| 4497 | use std::{path::PathBuf, time::Instant}; |
| 4498 | use unicode_width::UnicodeWidthStr; |
| 4499 | |
| 4500 | fn create_test_app() -> App { |
| 4501 | let options = TuiOptions { |
| 4502 | model: "deepseek-v4-flash".to_string(), |
| 4503 | start_in_agent_mode: true, |
| 4504 | ..crate::tui::test_support::test_tui_options(PathBuf::from(".")) |
| 4505 | }; |
| 4506 | let mut app = App::new(options, &Config::default()); |
| 4507 | // Widget contracts below exercise the post-Startup conversation |
| 4508 | // surface. Startup rendering has its own explicit fixture/tests. |
| 4509 | app.launch.visible = false; |
| 4510 | app.ui_locale = Locale::En; |
| 4511 | app.composer.vim_enabled = false; |
| 4512 | // Most widget fixtures exercise the underwater theme's field. Other |
| 4513 | // themes keep the terminal-owned shell; keep tests that inspect fish |
| 4514 | // and caustics intentional rather than coupled to that choice. |
| 4515 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 4516 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 4517 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 4518 | app |
| 4519 | } |
| 4520 | |
| 4521 | fn buffer_text(buf: &Buffer, area: Rect) -> String { |
| 4522 | let mut text = String::new(); |
| 4523 | for y in area.y..area.y.saturating_add(area.height) { |
| 4524 | for x in area.x..area.x.saturating_add(area.width) { |
| 4525 | text.push_str(buf[(x, y)].symbol()); |
| 4526 | } |
| 4527 | text.push('\n'); |
| 4528 | } |
| 4529 | text |
| 4530 | } |
| 4531 | |
| 4532 | #[test] |
| 4533 | fn approval_palette_reserves_signal_gold_for_human_decisions() { |
| 4534 | use crate::tui::approval::ApprovalStakes; |
| 4535 | |
| 4536 | let routine = approval_palette(ApprovalStakes::Routine); |
| 4537 | let elevated = approval_palette(ApprovalStakes::Elevated); |
| 4538 | let critical = approval_palette(ApprovalStakes::Critical); |
| 4539 | |
| 4540 | assert_eq!(routine.accent, palette::WHALE_HUMAN); |
| 4541 | assert_eq!(routine.shortcut, palette::WHALE_ACTION); |
| 4542 | assert_eq!(elevated.border, palette::WHALE_HUMAN); |
| 4543 | assert_eq!(elevated.accent, palette::WHALE_HUMAN); |
| 4544 | assert_eq!(critical.accent, palette::WHALE_ERROR); |
| 4545 | } |
| 4546 | |
| 4547 | #[test] |
| 4548 | fn first_active_tool_settles_when_flushed_to_history() { |
| 4549 | let mut app = create_test_app(); |
| 4550 | app.clear_history(); |
| 4551 | app.next_history_revision = 1; |
| 4552 | app.active_cell_revision = 0; |
| 4553 | |
| 4554 | let mut active = ActiveCell::new(); |
| 4555 | active.push_tool("user_shell_1", running_user_shell_cell()); |
| 4556 | app.active_cell = Some(active); |
| 4557 | |
| 4558 | let area = Rect::new(0, 0, 100, 20); |
| 4559 | let mut running_buf = Buffer::empty(area); |
| 4560 | ChatWidget::new(&mut app, area).render(area, &mut running_buf); |
| 4561 | let running = buffer_text(&running_buf, area); |
| 4562 | assert!(running.contains("$ sleep 30 · running"), "{running}"); |
| 4563 | |
| 4564 | app.finalize_active_cell_as_interrupted(); |
| 4565 | let HistoryCell::Tool(ToolCell::Exec(exec)) = &app.history[0] else { |
| 4566 | panic!("expected settled exec history cell") |
| 4567 | }; |
| 4568 | assert_eq!(exec.status, ToolStatus::Stopped); |
| 4569 | |
| 4570 | let mut settled_buf = Buffer::empty(area); |
| 4571 | ChatWidget::new(&mut app, area).render(area, &mut settled_buf); |
| 4572 | let settled = buffer_text(&settled_buf, area); |
| 4573 | assert!( |
| 4574 | !settled.contains("· running"), |
| 4575 | "flushed terminal state reused the active cache entry:\n{settled}" |
| 4576 | ); |
| 4577 | assert!(settled.contains("$ sleep 30 · stopped"), "{settled}"); |
| 4578 | } |
| 4579 | |
| 4580 | fn render_approval_request( |
| 4581 | request: &crate::tui::approval::ApprovalRequest, |
| 4582 | area: Rect, |
| 4583 | ) -> String { |
| 4584 | let view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 4585 | let widget = ApprovalWidget::new(request, &view); |
| 4586 | let mut buf = Buffer::empty(area); |
| 4587 | widget.render(area, &mut buf); |
| 4588 | buffer_text(&buf, area) |
| 4589 | } |
| 4590 | |
| 4591 | fn row_text(buf: &Buffer, area: Rect, row: u16) -> String { |
| 4592 | let mut text = String::new(); |
| 4593 | for x in area.x..area.x.saturating_add(area.width) { |
| 4594 | text.push_str(buf[(x, row)].symbol()); |
| 4595 | } |
| 4596 | text |
| 4597 | } |
| 4598 | |
| 4599 | fn success_tool_cell(name: &str) -> HistoryCell { |
| 4600 | HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 4601 | name: name.to_string(), |
| 4602 | status: ToolStatus::Success, |
| 4603 | input_summary: Some(format!("path: {name}.txt")), |
| 4604 | output: Some(format!("full output from {name}")), |
| 4605 | prompts: None, |
| 4606 | spillover_path: None, |
| 4607 | output_summary: None, |
| 4608 | is_diff: false, |
| 4609 | })) |
| 4610 | } |
| 4611 | |
| 4612 | fn running_user_shell_cell() -> HistoryCell { |
| 4613 | HistoryCell::Tool(ToolCell::Exec(ExecCell { |
| 4614 | command: "sleep 30".to_string(), |
| 4615 | status: ToolStatus::Running, |
| 4616 | output: None, |
| 4617 | live_output: None, |
| 4618 | shell_task_id: None, |
| 4619 | owner_agent_id: None, |
| 4620 | owner_agent_name: None, |
| 4621 | started_at: None, |
| 4622 | duration_ms: None, |
| 4623 | stale_elapsed_since_output_ms: None, |
| 4624 | waiting: None, |
| 4625 | source: ExecSource::User, |
| 4626 | description: None, |
| 4627 | interaction: None, |
| 4628 | output_summary: None, |
| 4629 | })) |
| 4630 | } |
| 4631 | |
| 4632 | fn add_dense_tool_run(app: &mut App) { |
| 4633 | app.add_message(success_tool_cell("read_file")); |
| 4634 | app.add_message(success_tool_cell("list_dir")); |
| 4635 | app.add_message(success_tool_cell("web_search")); |
| 4636 | } |
| 4637 | |
| 4638 | fn spacer_rows_after_transcript_cell(app: &App, target_cell: usize) -> usize { |
| 4639 | let mut saw_target = false; |
| 4640 | let mut spacer_rows = 0; |
| 4641 | for meta in app.viewport.transcript_cache.line_meta() { |
| 4642 | match meta { |
| 4643 | TranscriptLineMeta::CellLine { cell_index, .. } if *cell_index == target_cell => { |
| 4644 | saw_target = true; |
| 4645 | spacer_rows = 0; |
| 4646 | } |
| 4647 | TranscriptLineMeta::Spacer { .. } if saw_target => spacer_rows += 1, |
| 4648 | TranscriptLineMeta::CellLine { .. } if saw_target => break, |
| 4649 | TranscriptLineMeta::Spacer { .. } | TranscriptLineMeta::CellLine { .. } => {} |
| 4650 | } |
| 4651 | } |
| 4652 | spacer_rows |
| 4653 | } |
| 4654 | |
| 4655 | #[test] |
| 4656 | fn chat_widget_breathes_between_groups_without_padding_tool_rows_at_any_width() { |
| 4657 | for (width, height) in [(40, 8), (120, 12)] { |
| 4658 | let mut app = create_test_app(); |
| 4659 | app.low_motion = true; |
| 4660 | app.fancy_animations = false; |
| 4661 | app.transcript_spacing = TranscriptSpacing::Spacious; |
| 4662 | app.tool_collapse_mode = ToolCollapseMode::Expanded; |
| 4663 | |
| 4664 | for turn in 0..4 { |
| 4665 | app.add_message(HistoryCell::User { |
| 4666 | content: format!("turn {turn}: inspect the release receipts"), |
| 4667 | }); |
| 4668 | app.add_message(HistoryCell::Assistant { |
| 4669 | content: format!("I will inspect receipt group {turn}."), |
| 4670 | streaming: false, |
| 4671 | }); |
| 4672 | app.add_message(success_tool_cell(&format!("read_{turn}"))); |
| 4673 | app.add_message(success_tool_cell(&format!("verify_{turn}"))); |
| 4674 | app.add_message(HistoryCell::Assistant { |
| 4675 | content: format!("receipt group {turn} is complete"), |
| 4676 | streaming: false, |
| 4677 | }); |
| 4678 | } |
| 4679 | |
| 4680 | let area = Rect::new(0, 0, width, height); |
| 4681 | app.viewport.transcript_scroll = TranscriptScroll::at_line(0); |
| 4682 | let mut top_buf = Buffer::empty(area); |
| 4683 | ChatWidget::new(&mut app, area).render(area, &mut top_buf); |
| 4684 | |
| 4685 | assert_eq!(app.viewport.last_transcript_top, 0, "width={width}"); |
| 4686 | assert!( |
| 4687 | app.viewport.last_transcript_total > usize::from(height), |
| 4688 | "fixture must scroll at width={width}" |
| 4689 | ); |
| 4690 | assert_eq!( |
| 4691 | spacer_rows_after_transcript_cell(&app, 0), |
| 4692 | 3, |
| 4693 | "the top-level user turn needs a breathing row at width={width}" |
| 4694 | ); |
| 4695 | assert_eq!( |
| 4696 | spacer_rows_after_transcript_cell(&app, 1), |
| 4697 | 2, |
| 4698 | "answer to tool-group transition needs a breathing row at width={width}" |
| 4699 | ); |
| 4700 | assert_eq!( |
| 4701 | spacer_rows_after_transcript_cell(&app, 2), |
| 4702 | 0, |
| 4703 | "calls inside one tool group must stay compact at width={width}" |
| 4704 | ); |
| 4705 | assert_eq!( |
| 4706 | spacer_rows_after_transcript_cell(&app, 3), |
| 4707 | 2, |
| 4708 | "the completed tool group needs a breathing row at width={width}" |
| 4709 | ); |
| 4710 | assert!( |
| 4711 | buffer_text(&top_buf, area).contains("turn 0"), |
| 4712 | "top scroll source drifted at width={width}" |
| 4713 | ); |
| 4714 | |
| 4715 | let total = app.viewport.last_transcript_total; |
| 4716 | app.viewport.transcript_scroll = TranscriptScroll::to_bottom(); |
| 4717 | let mut tail_buf = Buffer::empty(area); |
| 4718 | ChatWidget::new(&mut app, area).render(area, &mut tail_buf); |
| 4719 | |
| 4720 | assert_eq!(app.viewport.last_transcript_total, total, "width={width}"); |
| 4721 | assert!(app.viewport.last_transcript_top > 0, "width={width}"); |
| 4722 | assert!( |
| 4723 | buffer_text(&tail_buf, area).contains("receipt group 3 is complete"), |
| 4724 | "tail scroll lost the final source-backed cell at width={width}" |
| 4725 | ); |
| 4726 | assert!( |
| 4727 | app.viewport |
| 4728 | .transcript_cache |
| 4729 | .line_meta() |
| 4730 | .iter() |
| 4731 | .all(|meta| match meta { |
| 4732 | TranscriptLineMeta::CellLine { cell_index, .. } => { |
| 4733 | *cell_index < app.history.len() |
| 4734 | } |
| 4735 | TranscriptLineMeta::Spacer { .. } => true, |
| 4736 | }), |
| 4737 | "spacing rows must not invent source-cell ownership at width={width}" |
| 4738 | ); |
| 4739 | } |
| 4740 | } |
| 4741 | |
| 4742 | #[test] |
| 4743 | fn send_flash_uses_original_index_map_for_collapsed_rows() { |
| 4744 | let history = vec![ |
| 4745 | success_tool_cell("read_file"), |
| 4746 | success_tool_cell("list_dir"), |
| 4747 | HistoryCell::User { |
| 4748 | content: "sent".to_string(), |
| 4749 | }, |
| 4750 | ]; |
| 4751 | let mut lines = vec![Line::from("sent")]; |
| 4752 | let line_meta = vec![TranscriptLineMeta::CellLine { |
| 4753 | cell_index: 0, |
| 4754 | line_in_cell: 0, |
| 4755 | copy_prefix_width: 0, |
| 4756 | copy_separator_after: codewhale_tui_kit::ui_text::CopyLineSeparator::Newline, |
| 4757 | }]; |
| 4758 | let original_index_map = vec![2]; |
| 4759 | |
| 4760 | apply_send_flash(&mut lines, 0, &history, &line_meta, &original_index_map); |
| 4761 | |
| 4762 | assert_eq!( |
| 4763 | lines[0].spans[0].style.bg, |
| 4764 | Some(palette::SURFACE_TOOL_ACTIVE) |
| 4765 | ); |
| 4766 | } |
| 4767 | |
| 4768 | #[test] |
| 4769 | fn activity_sweep_lights_verb_and_status_but_never_the_summary() { |
| 4770 | let header = || { |
| 4771 | Line::from(vec![ |
| 4772 | Span::styled("\u{28E4} ", Style::default().fg(palette::WHALE_ACTION)), |
| 4773 | Span::styled("\u{2315} ", Style::default().fg(palette::WHALE_ACTION)), |
| 4774 | Span::styled( |
| 4775 | "find", |
| 4776 | Style::default() |
| 4777 | .fg(palette::TEXT_SOFT) |
| 4778 | .add_modifier(Modifier::BOLD), |
| 4779 | ), |
| 4780 | Span::raw(" "), |
| 4781 | Span::styled("running", Style::default().fg(palette::WHALE_ACTION)), |
| 4782 | Span::styled(" \u{00B7} ", Style::default().fg(palette::TEXT_DIM)), |
| 4783 | Span::styled("READINESS.md", Style::default().fg(palette::TEXT_MUTED)), |
| 4784 | Span::styled(" 12s", Style::default().fg(palette::TEXT_DIM)), |
| 4785 | ]) |
| 4786 | }; |
| 4787 | let history = vec![HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 4788 | name: "grep_files".to_string(), |
| 4789 | status: ToolStatus::Running, |
| 4790 | input_summary: None, |
| 4791 | output: None, |
| 4792 | prompts: None, |
| 4793 | spillover_path: None, |
| 4794 | output_summary: None, |
| 4795 | is_diff: false, |
| 4796 | }))]; |
| 4797 | let line_meta = vec![TranscriptLineMeta::CellLine { |
| 4798 | cell_index: 0, |
| 4799 | line_in_cell: 0, |
| 4800 | copy_prefix_width: 0, |
| 4801 | copy_separator_after: codewhale_tui_kit::ui_text::CopyLineSeparator::Newline, |
| 4802 | }]; |
| 4803 | let theme = palette::UNDERWATER_UI_THEME; |
| 4804 | let earn = Duration::from_millis(codewhale_tui_kit::spinner::LIVE_MARKER_DELAY_MS); |
| 4805 | let sweep = |elapsed: Duration| { |
| 4806 | let mut lines = vec![header()]; |
| 4807 | let visible = apply_activity_sweep( |
| 4808 | &mut lines, |
| 4809 | 0, |
| 4810 | &line_meta, |
| 4811 | &[0], |
| 4812 | &history, |
| 4813 | &[], |
| 4814 | elapsed, |
| 4815 | palette::ThemeId::Underwater, |
| 4816 | &theme, |
| 4817 | None, |
| 4818 | ); |
| 4819 | assert!(visible); |
| 4820 | lines.remove(0) |
| 4821 | }; |
| 4822 | let cells = |line: &Line<'static>| -> Vec<(String, Option<Color>)> { |
| 4823 | line.spans |
| 4824 | .iter() |
| 4825 | .flat_map(|span| { |
| 4826 | span.content |
| 4827 | .chars() |
| 4828 | .map(move |ch| (ch.to_string(), span.style.fg)) |
| 4829 | }) |
| 4830 | .collect() |
| 4831 | }; |
| 4832 | let plain = cells(&header()); |
| 4833 | let resting = cells(&sweep(earn + Duration::from_millis(2_000))); |
| 4834 | assert_eq!(resting, plain, "the rest phase paints nothing"); |
| 4835 | let midway = cells(&sweep(earn + Duration::from_millis(900))); |
| 4836 | assert_eq!(midway.len(), plain.len()); |
| 4837 | let summary = plain |
| 4838 | .iter() |
| 4839 | .position(|(ch, _)| ch == "R") |
| 4840 | .expect("summary present"); |
| 4841 | assert_eq!( |
| 4842 | midway[summary..], |
| 4843 | plain[summary..], |
| 4844 | "summary and elapsed stay still" |
| 4845 | ); |
| 4846 | assert!( |
| 4847 | midway[..summary] != plain[..summary], |
| 4848 | "the verb and status brighten mid-sweep" |
| 4849 | ); |
| 4850 | assert_eq!( |
| 4851 | midway[..4], |
| 4852 | plain[..4], |
| 4853 | "the spinner and glyph keep their ink" |
| 4854 | ); |
| 4855 | } |
| 4856 | |
| 4857 | #[test] |
| 4858 | fn settled_tool_rows_flash_their_outcome_ink_once() { |
| 4859 | let generic = |status| { |
| 4860 | HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 4861 | name: "grep_files".to_string(), |
| 4862 | status, |
| 4863 | input_summary: Some("pattern: TODO, path: crates".to_string()), |
| 4864 | output: None, |
| 4865 | prompts: None, |
| 4866 | spillover_path: None, |
| 4867 | output_summary: None, |
| 4868 | is_diff: false, |
| 4869 | })) |
| 4870 | }; |
| 4871 | let exec = |status| { |
| 4872 | HistoryCell::Tool(ToolCell::Exec(ExecCell { |
| 4873 | command: "cargo test -p codewhale-tui".to_string(), |
| 4874 | description: None, |
| 4875 | status, |
| 4876 | output: None, |
| 4877 | live_output: None, |
| 4878 | shell_task_id: None, |
| 4879 | owner_agent_id: None, |
| 4880 | owner_agent_name: None, |
| 4881 | started_at: Instant::now().checked_sub(Duration::from_secs(5)), |
| 4882 | duration_ms: Some(5_000), |
| 4883 | stale_elapsed_since_output_ms: None, |
| 4884 | waiting: None, |
| 4885 | source: ExecSource::Assistant, |
| 4886 | interaction: None, |
| 4887 | output_summary: None, |
| 4888 | })) |
| 4889 | }; |
| 4890 | let theme = palette::UNDERWATER_UI_THEME; |
| 4891 | let options = crate::tui::history::TranscriptRenderOptions::default(); |
| 4892 | let completed = Instant::now(); |
| 4893 | let flash = |cell: &HistoryCell, after: Duration| { |
| 4894 | let mut rendered = cell.lines_with_options(100, options); |
| 4895 | let meta: Vec<TranscriptLineMeta> = (0..rendered.len()) |
| 4896 | .map(|line_in_cell| TranscriptLineMeta::CellLine { |
| 4897 | cell_index: 0, |
| 4898 | line_in_cell, |
| 4899 | copy_prefix_width: 0, |
| 4900 | copy_separator_after: codewhale_tui_kit::ui_text::CopyLineSeparator::Newline, |
| 4901 | }) |
| 4902 | .collect(); |
| 4903 | let mut flashed = rendered.clone(); |
| 4904 | let visible = apply_settle_flash( |
| 4905 | &mut flashed, |
| 4906 | 0, |
| 4907 | &meta, |
| 4908 | &[0], |
| 4909 | 0, |
| 4910 | std::slice::from_ref(cell), |
| 4911 | &std::collections::HashMap::from([(0, completed)]), |
| 4912 | completed + after, |
| 4913 | palette::ThemeId::Underwater, |
| 4914 | &theme, |
| 4915 | None, |
| 4916 | ); |
| 4917 | (rendered.remove(0), flashed.remove(0), visible) |
| 4918 | }; |
| 4919 | let fg_of = |line: &Line<'static>| -> Vec<Option<Color>> { |
| 4920 | line.spans.iter().map(|span| span.style.fg).collect() |
| 4921 | }; |
| 4922 | |
| 4923 | for cell in [ |
| 4924 | generic(ToolStatus::Success), |
| 4925 | generic(ToolStatus::Failed), |
| 4926 | exec(ToolStatus::Success), |
| 4927 | exec(ToolStatus::Failed), |
| 4928 | ] { |
| 4929 | let (before, early, visible) = flash(&cell, Duration::from_millis(60)); |
| 4930 | assert!(visible, "a fresh outcome flashes: {before:?}"); |
| 4931 | assert_eq!(early.spans.len(), before.spans.len()); |
| 4932 | let summary = before |
| 4933 | .spans |
| 4934 | .iter() |
| 4935 | .position(|span| span.content.contains("TODO") || span.content.contains("cargo")) |
| 4936 | .expect("summary or command present"); |
| 4937 | let (before_fg, early_fg) = (fg_of(&before), fg_of(&early)); |
| 4938 | assert_ne!( |
| 4939 | early_fg[..summary], |
| 4940 | before_fg[..summary], |
| 4941 | "the outcome mark lights" |
| 4942 | ); |
| 4943 | assert_eq!( |
| 4944 | early_fg[summary], before_fg[summary], |
| 4945 | "the summary and command never flash" |
| 4946 | ); |
| 4947 | let (_, settled, visible) = flash(&cell, SETTLE_FLASH_DURATION); |
| 4948 | assert!(!visible); |
| 4949 | assert_eq!( |
| 4950 | fg_of(&settled), |
| 4951 | fg_of(&before), |
| 4952 | "the flash leaves no residue" |
| 4953 | ); |
| 4954 | } |
| 4955 | let (before, running, visible) = flash(&generic(ToolStatus::Running), Duration::ZERO); |
| 4956 | assert!(!visible); |
| 4957 | assert_eq!(fg_of(&running), fg_of(&before)); |
| 4958 | } |
| 4959 | |
| 4960 | #[test] |
| 4961 | fn history_inserts_mid_turn_keep_settle_timestamps_on_their_entry() { |
| 4962 | let mut app = create_test_app(); |
| 4963 | app.active_cell = Some(crate::tui::active_cell::ActiveCell::new()); |
| 4964 | let at = Instant::now(); |
| 4965 | app.active_tool_entry_completed_at.insert(0, at); |
| 4966 | app.add_message(HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 4967 | name: "grep_files".to_string(), |
| 4968 | status: ToolStatus::Success, |
| 4969 | input_summary: None, |
| 4970 | output: None, |
| 4971 | prompts: None, |
| 4972 | spillover_path: None, |
| 4973 | output_summary: None, |
| 4974 | is_diff: false, |
| 4975 | }))); |
| 4976 | assert_eq!(app.active_tool_entry_completed_at.get(&0), Some(&at)); |
| 4977 | assert_eq!(app.active_tool_entry_completed_at.len(), 1); |
| 4978 | } |
| 4979 | |
| 4980 | #[test] |
| 4981 | fn activity_sweep_and_breath_stop_under_reduced_motion() { |
| 4982 | let mut app = create_test_app(); |
| 4983 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 4984 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 4985 | app.low_motion = false; |
| 4986 | app.fancy_animations = true; |
| 4987 | app.turn_started_at = Some(std::time::Instant::now()); |
| 4988 | assert!(crate::tui::ui::motion::activity_sweep_allowed(&app)); |
| 4989 | for (low_motion, fancy) in [(true, true), (false, false)] { |
| 4990 | app.low_motion = low_motion; |
| 4991 | app.fancy_animations = fancy; |
| 4992 | assert!(!crate::tui::ui::motion::activity_sweep_allowed(&app)); |
| 4993 | assert!(!crate::tui::ui::motion::composer_border_breathes(&app)); |
| 4994 | let first = crate::tui::ui::motion::composer_live_border(&app); |
| 4995 | std::thread::sleep(Duration::from_millis(30)); |
| 4996 | assert_eq!(crate::tui::ui::motion::composer_live_border(&app), first); |
| 4997 | } |
| 4998 | } |
| 4999 | |
| 5000 | #[test] |
| 5001 | fn composer_border_holds_still_while_the_transcript_is_scrolled_away() { |
| 5002 | let mut app = create_test_app(); |
| 5003 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 5004 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 5005 | app.low_motion = false; |
| 5006 | app.fancy_animations = true; |
| 5007 | app.turn_started_at = Some(std::time::Instant::now()); |
| 5008 | assert!(crate::tui::ui::motion::composer_border_breathes(&app)); |
| 5009 | |
| 5010 | app.viewport.transcript_scroll = codewhale_tui_kit::scrolling::TranscriptScroll::at_line(0); |
| 5011 | assert!(!crate::tui::ui::motion::composer_border_breathes(&app)); |
| 5012 | |
| 5013 | app.viewport.transcript_scroll = |
| 5014 | codewhale_tui_kit::scrolling::TranscriptScroll::to_bottom(); |
| 5015 | assert!(crate::tui::ui::motion::composer_border_breathes(&app)); |
| 5016 | } |
| 5017 | |
| 5018 | #[test] |
| 5019 | fn activity_sweep_real_renders_whale_and_remapped_themes() { |
| 5020 | let exec = HistoryCell::Tool(ToolCell::Exec(ExecCell { |
| 5021 | command: "cargo test -p codewhale-tui".to_string(), |
| 5022 | description: None, |
| 5023 | status: ToolStatus::Running, |
| 5024 | output: None, |
| 5025 | live_output: None, |
| 5026 | shell_task_id: None, |
| 5027 | owner_agent_id: None, |
| 5028 | owner_agent_name: None, |
| 5029 | started_at: Instant::now().checked_sub(Duration::from_secs(5)), |
| 5030 | duration_ms: None, |
| 5031 | stale_elapsed_since_output_ms: None, |
| 5032 | waiting: None, |
| 5033 | source: ExecSource::Assistant, |
| 5034 | interaction: None, |
| 5035 | output_summary: None, |
| 5036 | })); |
| 5037 | let generic = HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 5038 | name: "grep_files".to_string(), |
| 5039 | status: ToolStatus::Running, |
| 5040 | input_summary: Some("pattern: TODO, path: crates".to_string()), |
| 5041 | output: None, |
| 5042 | prompts: None, |
| 5043 | spillover_path: None, |
| 5044 | output_summary: None, |
| 5045 | is_diff: false, |
| 5046 | })); |
| 5047 | let earn = Duration::from_millis(codewhale_tui_kit::spinner::LIVE_MARKER_DELAY_MS); |
| 5048 | let mid_sweep = earn + Duration::from_millis(900); |
| 5049 | |
| 5050 | let adapt_fg = |fg: Option<Color>, |
| 5051 | theme_id: palette::ThemeId, |
| 5052 | theme: &palette::UiTheme, |
| 5053 | detected_bg: Option<Color>| { |
| 5054 | let mut cell = ratatui::buffer::Cell::default(); |
| 5055 | cell.set_symbol("a"); |
| 5056 | cell.fg = fg.unwrap_or(Color::Reset); |
| 5057 | cell.bg = theme.surface_bg; |
| 5058 | crate::tui::color_compat::adapt_cell_colors( |
| 5059 | &mut cell, |
| 5060 | palette::ColorDepth::TrueColor, |
| 5061 | theme.mode, |
| 5062 | theme_id, |
| 5063 | theme, |
| 5064 | detected_bg, |
| 5065 | ); |
| 5066 | cell.fg |
| 5067 | }; |
| 5068 | let cells_of = |line: &Line<'static>| -> Vec<(char, Option<Color>)> { |
| 5069 | line.spans |
| 5070 | .iter() |
| 5071 | .flat_map(|span| span.content.chars().map(move |ch| (ch, span.style.fg))) |
| 5072 | .collect() |
| 5073 | }; |
| 5074 | let sweep_cell = |cell: &HistoryCell, |
| 5075 | width: u16, |
| 5076 | options: crate::tui::history::TranscriptRenderOptions, |
| 5077 | theme_id: palette::ThemeId, |
| 5078 | theme: palette::UiTheme, |
| 5079 | detected_bg: Option<Color>| { |
| 5080 | let rendered = cell.lines_with_options(width, options); |
| 5081 | let meta: Vec<TranscriptLineMeta> = (0..rendered.len()) |
| 5082 | .map(|line_in_cell| TranscriptLineMeta::CellLine { |
| 5083 | cell_index: 0, |
| 5084 | line_in_cell, |
| 5085 | copy_prefix_width: 0, |
| 5086 | copy_separator_after: codewhale_tui_kit::ui_text::CopyLineSeparator::Newline, |
| 5087 | }) |
| 5088 | .collect(); |
| 5089 | let mut swept = rendered.clone(); |
| 5090 | let visible = apply_activity_sweep( |
| 5091 | &mut swept, |
| 5092 | 0, |
| 5093 | &meta, |
| 5094 | &[0], |
| 5095 | std::slice::from_ref(cell), |
| 5096 | &[], |
| 5097 | mid_sweep, |
| 5098 | theme_id, |
| 5099 | &theme, |
| 5100 | detected_bg, |
| 5101 | ); |
| 5102 | (rendered, swept, visible) |
| 5103 | }; |
| 5104 | let assert_brighter_changes = |
| 5105 | |before_line: &Line<'static>, |
| 5106 | after_line: &Line<'static>, |
| 5107 | theme_id: palette::ThemeId, |
| 5108 | theme: &palette::UiTheme, |
| 5109 | detected_bg: Option<Color>| { |
| 5110 | let before = cells_of(before_line); |
| 5111 | let after = cells_of(after_line); |
| 5112 | assert_eq!(before.len(), after.len()); |
| 5113 | let mut changed_indices = Vec::new(); |
| 5114 | for (idx, ((ch, b_fg), (_, a_fg))) in before.iter().zip(after.iter()).enumerate() { |
| 5115 | if b_fg != a_fg { |
| 5116 | let drawn_before = adapt_fg(*b_fg, theme_id, theme, detected_bg); |
| 5117 | let drawn_after = adapt_fg(*a_fg, theme_id, theme, detected_bg); |
| 5118 | let l_before = |
| 5119 | palette::relative_luminance(drawn_before).expect("luma before"); |
| 5120 | let l_after = palette::relative_luminance(drawn_after).expect("luma after"); |
| 5121 | assert!( |
| 5122 | l_after > l_before, |
| 5123 | "{theme_id:?} cell {idx} ({ch}) dimmed: {drawn_before:?} ({l_before}) -> {drawn_after:?} ({l_after})" |
| 5124 | ); |
| 5125 | changed_indices.push(idx); |
| 5126 | } |
| 5127 | } |
| 5128 | assert!( |
| 5129 | !changed_indices.is_empty(), |
| 5130 | "{theme_id:?} had no swept cells" |
| 5131 | ); |
| 5132 | (before, changed_indices) |
| 5133 | }; |
| 5134 | |
| 5135 | assert_eq!(palette::UI_THEME.surface_bg, Color::Reset); |
| 5136 | for cell in [&generic, &exec] { |
| 5137 | let opts = crate::tui::history::TranscriptRenderOptions { |
| 5138 | show_tool_details: false, |
| 5139 | calm_mode: false, |
| 5140 | palette_mode: palette::UI_THEME.mode, |
| 5141 | ..Default::default() |
| 5142 | }; |
| 5143 | let (rendered, swept, visible) = sweep_cell( |
| 5144 | cell, |
| 5145 | 120, |
| 5146 | opts, |
| 5147 | palette::ThemeId::Whale, |
| 5148 | palette::UI_THEME, |
| 5149 | None, |
| 5150 | ); |
| 5151 | assert!( |
| 5152 | !visible, |
| 5153 | "Whale without detected background must not claim visible sweep" |
| 5154 | ); |
| 5155 | assert_eq!(swept, rendered); |
| 5156 | |
| 5157 | let detected = Some(Color::Rgb(16, 20, 28)); |
| 5158 | let (rendered, swept, visible) = sweep_cell( |
| 5159 | cell, |
| 5160 | 120, |
| 5161 | opts, |
| 5162 | palette::ThemeId::Whale, |
| 5163 | palette::UI_THEME, |
| 5164 | detected, |
| 5165 | ); |
| 5166 | assert!(visible, "Whale with detected dark background should sweep"); |
| 5167 | assert_brighter_changes( |
| 5168 | &rendered[0], |
| 5169 | &swept[0], |
| 5170 | palette::ThemeId::Whale, |
| 5171 | &palette::UI_THEME, |
| 5172 | detected, |
| 5173 | ); |
| 5174 | } |
| 5175 | |
| 5176 | let shoreline = palette::SHORELINE_UI_THEME; |
| 5177 | let calm_shoreline = crate::tui::history::TranscriptRenderOptions { |
| 5178 | show_tool_details: false, |
| 5179 | calm_mode: false, |
| 5180 | palette_mode: shoreline.mode, |
| 5181 | ..Default::default() |
| 5182 | }; |
| 5183 | let (rendered, swept, visible) = sweep_cell( |
| 5184 | &generic, |
| 5185 | 120, |
| 5186 | calm_shoreline, |
| 5187 | palette::ThemeId::Shoreline, |
| 5188 | shoreline, |
| 5189 | None, |
| 5190 | ); |
| 5191 | assert!(visible); |
| 5192 | let (before, changed) = assert_brighter_changes( |
| 5193 | &rendered[0], |
| 5194 | &swept[0], |
| 5195 | palette::ThemeId::Shoreline, |
| 5196 | &shoreline, |
| 5197 | None, |
| 5198 | ); |
| 5199 | let plain: String = before.iter().map(|(ch, _)| *ch).collect(); |
| 5200 | let dot = plain |
| 5201 | .find('\u{00B7}') |
| 5202 | .map(|idx| plain[..idx].chars().count()) |
| 5203 | .expect("separator present"); |
| 5204 | assert!( |
| 5205 | changed.iter().all(|&idx| idx < dot), |
| 5206 | "summary after separator must stay untouched in {plain:?}" |
| 5207 | ); |
| 5208 | |
| 5209 | for (theme_id, theme) in [ |
| 5210 | (palette::ThemeId::Shoreline, shoreline), |
| 5211 | (palette::ThemeId::Underwater, palette::UNDERWATER_UI_THEME), |
| 5212 | ] { |
| 5213 | let details_opts = crate::tui::history::TranscriptRenderOptions { |
| 5214 | show_tool_details: true, |
| 5215 | calm_mode: false, |
| 5216 | palette_mode: theme.mode, |
| 5217 | ..Default::default() |
| 5218 | }; |
| 5219 | let (rendered, swept, visible) = |
| 5220 | sweep_cell(&exec, 120, details_opts, theme_id, theme, None); |
| 5221 | assert!(visible); |
| 5222 | let (before, changed) = |
| 5223 | assert_brighter_changes(&rendered[0], &swept[0], theme_id, &theme, None); |
| 5224 | let plain: String = before.iter().map(|(ch, _)| *ch).collect(); |
| 5225 | let status_start = plain |
| 5226 | .find("running") |
| 5227 | .map(|idx| plain[..idx].chars().count()) |
| 5228 | .expect("status word present"); |
| 5229 | let status_end = status_start + "running".chars().count(); |
| 5230 | assert!( |
| 5231 | changed |
| 5232 | .iter() |
| 5233 | .all(|&idx| idx >= status_start && idx < status_end), |
| 5234 | "{theme_id:?} legacy header swept outside status in {plain:?}: {changed:?}" |
| 5235 | ); |
| 5236 | } |
| 5237 | |
| 5238 | let (rendered, swept, visible) = sweep_cell( |
| 5239 | &exec, |
| 5240 | 24, |
| 5241 | calm_shoreline, |
| 5242 | palette::ThemeId::Shoreline, |
| 5243 | shoreline, |
| 5244 | None, |
| 5245 | ); |
| 5246 | assert!( |
| 5247 | rendered.len() >= 2, |
| 5248 | "narrow shell header should wrap status to line 1" |
| 5249 | ); |
| 5250 | assert!(visible); |
| 5251 | assert_eq!(swept[0], rendered[0]); |
| 5252 | let (before, changed) = assert_brighter_changes( |
| 5253 | &rendered[1], |
| 5254 | &swept[1], |
| 5255 | palette::ThemeId::Shoreline, |
| 5256 | &shoreline, |
| 5257 | None, |
| 5258 | ); |
| 5259 | let line1_plain: String = before.iter().map(|(ch, _)| *ch).collect(); |
| 5260 | let status_end = "running".len(); |
| 5261 | assert!(line1_plain.starts_with("running"), "{line1_plain:?}"); |
| 5262 | assert!( |
| 5263 | changed.iter().all(|&idx| idx < status_end), |
| 5264 | "narrow wrapped shell swept outside status in {line1_plain:?}: {changed:?}" |
| 5265 | ); |
| 5266 | } |
| 5267 | |
| 5268 | /// #6704: the Alt+V detail target (here a visible error cell) must not |
| 5269 | /// punch the terminal's own background through a painted surface. Its |
| 5270 | /// text used to be forced to `Color::Reset`, which Windows Terminal shows |
| 5271 | /// as black under the Underwater theme's navy water. |
| 5272 | #[test] |
| 5273 | fn detail_target_text_keeps_the_painted_surface() { |
| 5274 | let mut app = create_test_app(); |
| 5275 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 5276 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 5277 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 5278 | app.add_message(HistoryCell::User { |
| 5279 | content: "run the check".to_string(), |
| 5280 | }); |
| 5281 | app.add_message(HistoryCell::Error { |
| 5282 | message: "验证失败 detail target".to_string(), |
| 5283 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 5284 | code: None, |
| 5285 | }); |
| 5286 | |
| 5287 | let area = Rect::new(0, 0, 80, 12); |
| 5288 | let mut buf = Buffer::empty(area); |
| 5289 | ChatWidget::new_with_ocean_elapsed(&mut app, area, 0).render(area, &mut buf); |
| 5290 | |
| 5291 | let rendered = buffer_text(&buf, area); |
| 5292 | assert!(rendered.contains("detail target"), "{rendered}"); |
| 5293 | let holes = (area.y..area.bottom()) |
| 5294 | .flat_map(|y| (area.x..area.right()).map(move |x| (x, y))) |
| 5295 | .filter(|&pos| buf[pos].bg == Color::Reset) |
| 5296 | .collect::<Vec<_>>(); |
| 5297 | assert!( |
| 5298 | holes.is_empty(), |
| 5299 | "cells fell through to the terminal background at {holes:?}:\n{rendered}" |
| 5300 | ); |
| 5301 | } |
| 5302 | |
| 5303 | #[test] |
| 5304 | fn tool_run_summary_revision_separates_128_entry_history_and_active_alias() { |
| 5305 | let active_rev = 17; |
| 5306 | let run = ToolRun { |
| 5307 | start: 0, |
| 5308 | count: 128, |
| 5309 | tool_families: Vec::new(), |
| 5310 | activity: Default::default(), |
| 5311 | }; |
| 5312 | let history_revisions = (1..=run.count) |
| 5313 | .map(|salt| active_entry_revision(active_rev, salt as u64)) |
| 5314 | .collect::<Vec<_>>(); |
| 5315 | |
| 5316 | let history_key = |
| 5317 | tool_run_summary_revision(&run, &history_revisions, run.count, active_rev); |
| 5318 | let active_key = tool_run_summary_revision(&run, &[], 0, active_rev); |
| 5319 | |
| 5320 | // Rotating by seven over 128 entries cancels the 128 identical domain |
| 5321 | // bits, reproducing the old untagged hash alias. The final domain tag |
| 5322 | // must still keep the cache keys distinct. |
| 5323 | assert_eq!( |
| 5324 | history_key & !ACTIVE_REVISION_DOMAIN, |
| 5325 | active_key & !ACTIVE_REVISION_DOMAIN, |
| 5326 | "fixture must exercise the 128-entry payload alias" |
| 5327 | ); |
| 5328 | assert_eq!(history_key & ACTIVE_REVISION_DOMAIN, 0); |
| 5329 | assert_eq!(active_key & ACTIVE_REVISION_DOMAIN, ACTIVE_REVISION_DOMAIN); |
| 5330 | assert_ne!(history_key, active_key); |
| 5331 | } |
| 5332 | |
| 5333 | #[test] |
| 5334 | fn high_bit_raw_revision_remains_distinct_across_history_and_active_domains() { |
| 5335 | let raw = ACTIVE_REVISION_DOMAIN | 0x2692; |
| 5336 | let history_key = history_entry_revision(raw); |
| 5337 | let active_key = revision_in_domain(raw, true); |
| 5338 | |
| 5339 | assert_eq!(history_key, 0x2692); |
| 5340 | assert_eq!(active_key, ACTIVE_REVISION_DOMAIN | 0x2692); |
| 5341 | assert_ne!(history_key, active_key); |
| 5342 | } |
| 5343 | |
| 5344 | fn patch_cell(path: &str, added: usize, deleted: usize) -> HistoryCell { |
| 5345 | use crate::tui::history::{FileMutationFile, FileMutationOutcome, PatchSummaryCell}; |
| 5346 | HistoryCell::Tool(ToolCell::PatchSummary(PatchSummaryCell { |
| 5347 | path: path.to_string(), |
| 5348 | summary: format!("Updated {path}"), |
| 5349 | status: ToolStatus::Success, |
| 5350 | error: None, |
| 5351 | receipt: Some(crate::tui::history::FileMutationReceipt { |
| 5352 | exact_diff: format!("--- a/{path}\n+++ b/{path}\n+new\n"), |
| 5353 | display_diff: format!("--- a/{path}\n+++ b/{path}\n+new\n"), |
| 5354 | files: vec![FileMutationFile { |
| 5355 | path: path.to_string(), |
| 5356 | previous_path: None, |
| 5357 | outcome: FileMutationOutcome::Updated, |
| 5358 | }], |
| 5359 | added, |
| 5360 | deleted, |
| 5361 | }), |
| 5362 | })) |
| 5363 | } |
| 5364 | |
| 5365 | #[test] |
| 5366 | fn a_finished_turn_folds_its_steps_into_one_worked_for_line() { |
| 5367 | let mut app = create_test_app(); |
| 5368 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5369 | app.tool_collapse_threshold = 3; |
| 5370 | app.add_message(HistoryCell::User { |
| 5371 | content: "fix the counter".to_string(), |
| 5372 | }); |
| 5373 | app.add_message(success_tool_cell("read_file")); |
| 5374 | app.add_message(success_tool_cell("grep_files")); |
| 5375 | app.add_message(patch_cell("src/count.rs", 3, 1)); |
| 5376 | app.add_message(HistoryCell::Assistant { |
| 5377 | content: "Fixed the counter.".to_string(), |
| 5378 | streaming: false, |
| 5379 | }); |
| 5380 | app.turn_work_durations |
| 5381 | .insert(0, std::time::Duration::from_secs(72)); |
| 5382 | let area = Rect::new(0, 0, 80, 12); |
| 5383 | |
| 5384 | app.is_loading = true; |
| 5385 | let mut live = Buffer::empty(area); |
| 5386 | ChatWidget::new(&mut app, area).render(area, &mut live); |
| 5387 | assert!(!buffer_text(&live, area).contains("Worked for")); |
| 5388 | |
| 5389 | app.is_loading = false; |
| 5390 | let mut buf = Buffer::empty(area); |
| 5391 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5392 | let rendered = buffer_text(&buf, area); |
| 5393 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 4]); |
| 5394 | assert!( |
| 5395 | rendered.contains("Worked for 1m 12s \u{00B7} 3 steps \u{203A}"), |
| 5396 | "{rendered}" |
| 5397 | ); |
| 5398 | assert!( |
| 5399 | rendered.contains("1 file changed +3 \u{2212}1 \u{00B7} Enter to review"), |
| 5400 | "{rendered}" |
| 5401 | ); |
| 5402 | assert!(!rendered.contains("full output from"), "{rendered}"); |
| 5403 | assert!(rendered.contains("Fixed the counter."), "{rendered}"); |
| 5404 | let turn = app.folded_turn_at(1).expect("summary row hosts the fold"); |
| 5405 | assert!( |
| 5406 | crate::tui::history::turn_fold_diff(&turn, |index| app |
| 5407 | .cell_at_virtual_index(index) |
| 5408 | .cloned()) |
| 5409 | .contains("+++ b/src/count.rs") |
| 5410 | ); |
| 5411 | |
| 5412 | assert!(app.transcript_fold_header_at(1)); |
| 5413 | assert!(app.toggle_tool_run_expansion_at(1)); |
| 5414 | let _ = ChatWidget::new(&mut app, area); |
| 5415 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 2, 3, 4]); |
| 5416 | assert!(app.folded_turn_at(1).is_none()); |
| 5417 | assert!(app.toggle_tool_run_expansion_at(3)); |
| 5418 | let _ = ChatWidget::new(&mut app, area); |
| 5419 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 4]); |
| 5420 | } |
| 5421 | |
| 5422 | #[test] |
| 5423 | fn a_failed_step_stays_visible_beside_the_fold() { |
| 5424 | let mut app = create_test_app(); |
| 5425 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5426 | app.add_message(HistoryCell::User { |
| 5427 | content: "run it".to_string(), |
| 5428 | }); |
| 5429 | app.add_message(success_tool_cell("read_file")); |
| 5430 | let HistoryCell::Tool(ToolCell::Generic(mut failed)) = success_tool_cell("run_tests") |
| 5431 | else { |
| 5432 | unreachable!() |
| 5433 | }; |
| 5434 | failed.status = ToolStatus::Failed; |
| 5435 | app.add_message(HistoryCell::Tool(ToolCell::Generic(failed))); |
| 5436 | let area = Rect::new(0, 0, 80, 12); |
| 5437 | let mut buf = Buffer::empty(area); |
| 5438 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5439 | let rendered = buffer_text(&buf, area); |
| 5440 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 2]); |
| 5441 | assert!( |
| 5442 | rendered.contains("1 step \u{00B7} 1 failed \u{203A}"), |
| 5443 | "{rendered}" |
| 5444 | ); |
| 5445 | } |
| 5446 | |
| 5447 | #[test] |
| 5448 | fn adv_superseded_todo_first_member_breaks_click_and_enter() { |
| 5449 | let mut app = create_test_app(); |
| 5450 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5451 | app.add_message(HistoryCell::User { |
| 5452 | content: "a".to_string(), |
| 5453 | }); |
| 5454 | app.add_message(success_tool_cell("todo_write")); |
| 5455 | app.add_message(success_tool_cell("read_file")); |
| 5456 | app.add_message(patch_cell("src/a.rs", 1, 0)); |
| 5457 | app.add_message(HistoryCell::User { |
| 5458 | content: "b".to_string(), |
| 5459 | }); |
| 5460 | app.add_message(success_tool_cell("todo_write")); |
| 5461 | let area = Rect::new(0, 0, 80, 14); |
| 5462 | let mut buf = Buffer::empty(area); |
| 5463 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5464 | let rendered = buffer_text(&buf, area); |
| 5465 | assert!(rendered.contains("2 steps"), "{rendered}"); |
| 5466 | let host = app.collapsed_cell_map[1]; |
| 5467 | assert!( |
| 5468 | app.transcript_fold_header_at(host), |
| 5469 | "click on the fold summary row must toggle it" |
| 5470 | ); |
| 5471 | assert!( |
| 5472 | app.folded_turn_at(host).is_some(), |
| 5473 | "Enter on the fold summary row must find its turn" |
| 5474 | ); |
| 5475 | } |
| 5476 | |
| 5477 | #[test] |
| 5478 | fn adv_queued_follow_up_folds_the_running_turn() { |
| 5479 | let mut app = create_test_app(); |
| 5480 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5481 | app.add_message(HistoryCell::User { |
| 5482 | content: "a".to_string(), |
| 5483 | }); |
| 5484 | app.add_message(success_tool_cell("read_file")); |
| 5485 | app.add_message(success_tool_cell("grep_files")); |
| 5486 | app.add_message(HistoryCell::User { |
| 5487 | content: "queued follow-up".to_string(), |
| 5488 | }); |
| 5489 | app.is_loading = true; |
| 5490 | let area = Rect::new(0, 0, 80, 12); |
| 5491 | let mut buf = Buffer::empty(area); |
| 5492 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5493 | let rendered = buffer_text(&buf, area); |
| 5494 | assert!( |
| 5495 | !rendered.contains("2 steps"), |
| 5496 | "running turn folded: {rendered}" |
| 5497 | ); |
| 5498 | |
| 5499 | app.active_turn_user_index = Some(0); |
| 5500 | app.add_message(HistoryCell::Assistant { |
| 5501 | content: "working on it".to_string(), |
| 5502 | streaming: false, |
| 5503 | }); |
| 5504 | app.history_version = app.history_version.wrapping_add(1); |
| 5505 | let mut buf2 = Buffer::empty(area); |
| 5506 | ChatWidget::new(&mut app, area).render(area, &mut buf2); |
| 5507 | let rendered2 = buffer_text(&buf2, area); |
| 5508 | assert!( |
| 5509 | !rendered2.contains("2 steps"), |
| 5510 | "active_turn_user_index must keep running turn open even after queued echo: {rendered2}" |
| 5511 | ); |
| 5512 | } |
| 5513 | |
| 5514 | #[test] |
| 5515 | fn adv_warning_and_stopped_steps_hide_inside_fold() { |
| 5516 | let mut app = create_test_app(); |
| 5517 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5518 | app.add_message(HistoryCell::User { |
| 5519 | content: "a".to_string(), |
| 5520 | }); |
| 5521 | app.add_message(success_tool_cell("read_file")); |
| 5522 | let HistoryCell::Tool(ToolCell::Generic(mut warn)) = success_tool_cell("run_tests") else { |
| 5523 | unreachable!() |
| 5524 | }; |
| 5525 | warn.status = ToolStatus::Warning; |
| 5526 | app.add_message(HistoryCell::Tool(ToolCell::Generic(warn))); |
| 5527 | let HistoryCell::Tool(ToolCell::Generic(mut stopped)) = success_tool_cell("long_task") |
| 5528 | else { |
| 5529 | unreachable!() |
| 5530 | }; |
| 5531 | stopped.status = ToolStatus::Stopped; |
| 5532 | app.add_message(HistoryCell::Tool(ToolCell::Generic(stopped))); |
| 5533 | let area = Rect::new(0, 0, 80, 12); |
| 5534 | let mut buf = Buffer::empty(area); |
| 5535 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5536 | let rendered = buffer_text(&buf, area); |
| 5537 | assert!( |
| 5538 | app.collapsed_cell_map.contains(&2), |
| 5539 | "warning step hidden: {rendered}" |
| 5540 | ); |
| 5541 | assert!( |
| 5542 | app.collapsed_cell_map.contains(&3), |
| 5543 | "stopped step hidden: {rendered}" |
| 5544 | ); |
| 5545 | } |
| 5546 | |
| 5547 | #[test] |
| 5548 | fn adv_exec_command_hidden_inside_fold() { |
| 5549 | let mut app = create_test_app(); |
| 5550 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5551 | app.add_message(HistoryCell::User { |
| 5552 | content: "a".to_string(), |
| 5553 | }); |
| 5554 | app.add_message(success_tool_cell("read_file")); |
| 5555 | let HistoryCell::Tool(ToolCell::Exec(mut exec)) = running_user_shell_cell() else { |
| 5556 | unreachable!() |
| 5557 | }; |
| 5558 | exec.command = "git push --force origin main".to_string(); |
| 5559 | exec.status = ToolStatus::Success; |
| 5560 | app.add_message(HistoryCell::Tool(ToolCell::Exec(exec))); |
| 5561 | let area = Rect::new(0, 0, 80, 12); |
| 5562 | let mut buf = Buffer::empty(area); |
| 5563 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5564 | let rendered = buffer_text(&buf, area); |
| 5565 | assert!(rendered.contains("git push"), "exec hidden: {rendered}"); |
| 5566 | } |
| 5567 | |
| 5568 | #[test] |
| 5569 | fn adv_failed_sub_agent_is_dimmed() { |
| 5570 | use crate::tui::widgets::agent_card::{AgentLifecycle, DelegateCard}; |
| 5571 | let mut app = create_test_app(); |
| 5572 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5573 | app.add_message(HistoryCell::User { |
| 5574 | content: "a".to_string(), |
| 5575 | }); |
| 5576 | let mut card = DelegateCard::new("agent_1", "reviewer"); |
| 5577 | card.status = AgentLifecycle::Failed; |
| 5578 | card.summary = Some("crashed".to_string()); |
| 5579 | app.add_message(HistoryCell::SubAgent( |
| 5580 | crate::tui::history::SubAgentCell::Delegate(card), |
| 5581 | )); |
| 5582 | let area = Rect::new(0, 0, 80, 8); |
| 5583 | let mut buf = Buffer::empty(area); |
| 5584 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5585 | let rendered = buffer_text(&buf, area); |
| 5586 | assert!( |
| 5587 | rendered.contains('\u{2570}'), |
| 5588 | "failed sub-agent folded to dim line: {rendered}" |
| 5589 | ); |
| 5590 | } |
| 5591 | |
| 5592 | #[test] |
| 5593 | fn main_agent_prose_has_no_author_label_and_sub_agents_carry_a_name_tag() { |
| 5594 | use crate::tui::widgets::agent_card::{AgentLifecycle, DelegateCard}; |
| 5595 | let mut app = create_test_app(); |
| 5596 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5597 | app.add_message(HistoryCell::User { |
| 5598 | content: "review the change".to_string(), |
| 5599 | }); |
| 5600 | let mut card = DelegateCard::new("agent_1", "reviewer"); |
| 5601 | card.status = AgentLifecycle::Completed; |
| 5602 | card.summary = Some("two findings".to_string()); |
| 5603 | app.add_message(HistoryCell::SubAgent( |
| 5604 | crate::tui::history::SubAgentCell::Delegate(card), |
| 5605 | )); |
| 5606 | app.add_message(HistoryCell::Assistant { |
| 5607 | content: "The review found two issues.".to_string(), |
| 5608 | streaming: false, |
| 5609 | }); |
| 5610 | let area = Rect::new(0, 0, 80, 10); |
| 5611 | let mut buf = Buffer::empty(area); |
| 5612 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5613 | let rendered = buffer_text(&buf, area); |
| 5614 | let role = codewhale_agent_contract::role::public_role_label("reviewer"); |
| 5615 | let agent_row = rendered |
| 5616 | .lines() |
| 5617 | .find(|line| line.contains(&role)) |
| 5618 | .unwrap_or_else(|| panic!("{rendered}")); |
| 5619 | assert!( |
| 5620 | agent_row.contains("\u{00B7} done \u{00B7} two findings \u{203A}"), |
| 5621 | "{rendered}" |
| 5622 | ); |
| 5623 | assert!(!rendered.contains('\u{2570}'), "{rendered}"); |
| 5624 | let prose = rendered |
| 5625 | .lines() |
| 5626 | .find(|line| line.contains("The review found two issues.")) |
| 5627 | .unwrap(); |
| 5628 | assert!(!prose.to_lowercase().contains("whale"), "{prose}"); |
| 5629 | assert!(app.toggle_tool_run_expansion_at(1)); |
| 5630 | let mut opened = Buffer::empty(area); |
| 5631 | ChatWidget::new(&mut app, area).render(area, &mut opened); |
| 5632 | assert!(buffer_text(&opened, area).contains('\u{2570}')); |
| 5633 | } |
| 5634 | |
| 5635 | #[test] |
| 5636 | fn chat_widget_collapses_dense_tool_runs_by_default() { |
| 5637 | let mut app = create_test_app(); |
| 5638 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5639 | app.tool_collapse_threshold = 3; |
| 5640 | add_dense_tool_run(&mut app); |
| 5641 | |
| 5642 | let area = Rect { |
| 5643 | x: 0, |
| 5644 | y: 0, |
| 5645 | width: 80, |
| 5646 | height: 8, |
| 5647 | }; |
| 5648 | let mut buf = Buffer::empty(area); |
| 5649 | let widget = ChatWidget::new(&mut app, area); |
| 5650 | widget.render(area, &mut buf); |
| 5651 | let rendered = buffer_text(&buf, area); |
| 5652 | |
| 5653 | assert_eq!(app.collapsed_cell_map, vec![0]); |
| 5654 | assert!( |
| 5655 | rendered.contains("Explored 2 files, 1 search"), |
| 5656 | "{rendered}" |
| 5657 | ); |
| 5658 | assert!(!rendered.contains("activity_group"), "{rendered}"); |
| 5659 | assert!( |
| 5660 | !rendered.contains("full output from list_dir"), |
| 5661 | "{rendered}" |
| 5662 | ); |
| 5663 | } |
| 5664 | |
| 5665 | #[test] |
| 5666 | fn g3_collapsed_projection_reuses_summaries_until_content_or_expansion_changes() { |
| 5667 | let mut app = create_test_app(); |
| 5668 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5669 | app.tool_collapse_threshold = 3; |
| 5670 | add_dense_tool_run(&mut app); |
| 5671 | let area = Rect::new(0, 0, 80, 20); |
| 5672 | let _ = ChatWidget::new(&mut app, area); |
| 5673 | assert_eq!(app.tool_run_cache.projection_builds, 1); |
| 5674 | app.scroll_up(3); |
| 5675 | let _ = ChatWidget::new(&mut app, area); |
| 5676 | assert_eq!(app.tool_run_cache.projection_builds, 1); |
| 5677 | app.ui_locale = codewhale_localization::Locale::ZhHans; |
| 5678 | let mut localized = Buffer::empty(area); |
| 5679 | ChatWidget::new(&mut app, area).render(area, &mut localized); |
| 5680 | assert_eq!(app.tool_run_cache.projection_builds, 2); |
| 5681 | let cell = &app.tool_run_cache.summaries.get(&0).unwrap().0; |
| 5682 | let HistoryCell::Tool(ToolCell::Generic(cell)) = cell else { |
| 5683 | panic!("activity cell"); |
| 5684 | }; |
| 5685 | assert!( |
| 5686 | cell.input_summary |
| 5687 | .as_deref() |
| 5688 | .unwrap() |
| 5689 | .contains("浏览了2个文件") |
| 5690 | ); |
| 5691 | assert!(!buffer_text(&localized, area).contains("Explored")); |
| 5692 | let _ = ChatWidget::new(&mut app, area); |
| 5693 | assert_eq!(app.tool_run_cache.projection_builds, 2); |
| 5694 | app.ui_locale = codewhale_localization::Locale::En; |
| 5695 | let mut english = Buffer::empty(area); |
| 5696 | ChatWidget::new(&mut app, area).render(area, &mut english); |
| 5697 | assert_eq!(app.tool_run_cache.projection_builds, 3); |
| 5698 | assert!(buffer_text(&english, area).contains("Explored 2 files")); |
| 5699 | app.expanded_tool_runs.insert(0); |
| 5700 | let _ = ChatWidget::new(&mut app, area); |
| 5701 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 2]); |
| 5702 | app.expanded_tool_runs.clear(); |
| 5703 | if let HistoryCell::Tool(ToolCell::Generic(tool)) = &mut app.history[1] { |
| 5704 | tool.status = ToolStatus::Failed; |
| 5705 | } |
| 5706 | app.bump_history_cell(1); |
| 5707 | let _ = ChatWidget::new(&mut app, area); |
| 5708 | assert!(app.tool_run_cache.summaries.is_empty()); |
| 5709 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 2]); |
| 5710 | } |
| 5711 | |
| 5712 | /// Isolates the former per-cell linear run lookup from rendering and I/O. |
| 5713 | #[test] |
| 5714 | #[ignore = "timing benchmark, not a correctness gate"] |
| 5715 | #[allow(clippy::print_stderr)] |
| 5716 | fn bench_g3_collapsed_projection_lookup() { |
| 5717 | for groups in [100usize, 1_000] { |
| 5718 | let mut app = create_test_app(); |
| 5719 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5720 | app.tool_collapse_threshold = 3; |
| 5721 | for _ in 0..groups { |
| 5722 | add_dense_tool_run(&mut app); |
| 5723 | app.push_history_cell(HistoryCell::Assistant { |
| 5724 | content: "done".into(), |
| 5725 | streaming: false, |
| 5726 | }); |
| 5727 | } |
| 5728 | let area = Rect::new(0, 0, 140, 40); |
| 5729 | let _ = ChatWidget::new(&mut app, area); |
| 5730 | let runs = crate::tui::history::detect_tool_runs_from_slices(&app.history, &[], 3); |
| 5731 | let frames = 200u32; |
| 5732 | let started = std::time::Instant::now(); |
| 5733 | for _ in 0..frames { |
| 5734 | for index in 0..app.history.len() { |
| 5735 | std::hint::black_box( |
| 5736 | runs.iter() |
| 5737 | .find(|run| run.start == std::hint::black_box(index)), |
| 5738 | ); |
| 5739 | } |
| 5740 | } |
| 5741 | let before = started.elapsed() / frames; |
| 5742 | let started = std::time::Instant::now(); |
| 5743 | for _ in 0..frames { |
| 5744 | for index in 0..app.history.len() { |
| 5745 | std::hint::black_box( |
| 5746 | app.tool_run_cache |
| 5747 | .summaries |
| 5748 | .get(&std::hint::black_box(index)), |
| 5749 | ); |
| 5750 | } |
| 5751 | } |
| 5752 | let after = started.elapsed() / frames; |
| 5753 | eprintln!( |
| 5754 | "#6652 lookup: {} cells, {} groups, linear {:?}, cached direct {:?} per frame", |
| 5755 | app.history.len(), |
| 5756 | runs.len(), |
| 5757 | before, |
| 5758 | after |
| 5759 | ); |
| 5760 | } |
| 5761 | } |
| 5762 | |
| 5763 | #[test] |
| 5764 | fn calm1_collapsed_group_keeps_count_and_reveal_affordance() { |
| 5765 | let mut app = create_test_app(); |
| 5766 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5767 | app.tool_collapse_threshold = 3; |
| 5768 | add_dense_tool_run(&mut app); |
| 5769 | for width in [40, 60, 80, 140] { |
| 5770 | let area = Rect::new(0, 0, width, 8); |
| 5771 | let mut buf = Buffer::empty(area); |
| 5772 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5773 | let text = buffer_text(&buf, area); |
| 5774 | assert!(text.contains("+3 ›"), "{text}"); |
| 5775 | assert_eq!(app.collapsed_cell_map, vec![0]); |
| 5776 | } |
| 5777 | } |
| 5778 | |
| 5779 | #[test] |
| 5780 | fn chat_widget_collapses_dense_active_tool_runs_by_default() { |
| 5781 | let mut app = create_test_app(); |
| 5782 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5783 | app.tool_collapse_threshold = 3; |
| 5784 | let active = app.active_cell.get_or_insert_with(ActiveCell::new); |
| 5785 | active.push_untracked(success_tool_cell("read_file")); |
| 5786 | active.push_untracked(success_tool_cell("list_dir")); |
| 5787 | active.push_untracked(success_tool_cell("web_search")); |
| 5788 | app.bump_active_cell_revision(); |
| 5789 | |
| 5790 | let area = Rect { |
| 5791 | x: 0, |
| 5792 | y: 0, |
| 5793 | width: 80, |
| 5794 | height: 8, |
| 5795 | }; |
| 5796 | let mut buf = Buffer::empty(area); |
| 5797 | let widget = ChatWidget::new(&mut app, area); |
| 5798 | widget.render(area, &mut buf); |
| 5799 | let rendered = buffer_text(&buf, area); |
| 5800 | |
| 5801 | assert_eq!(app.collapsed_cell_map, vec![0]); |
| 5802 | assert!( |
| 5803 | rendered.contains("Explored 2 files, 1 search"), |
| 5804 | "{rendered}" |
| 5805 | ); |
| 5806 | assert!(!rendered.contains("activity_group"), "{rendered}"); |
| 5807 | assert!( |
| 5808 | !rendered.contains("full output from list_dir"), |
| 5809 | "{rendered}" |
| 5810 | ); |
| 5811 | } |
| 5812 | |
| 5813 | #[test] |
| 5814 | fn collapsed_slow_path_does_not_reuse_running_active_cache_after_flush() { |
| 5815 | let mut app = create_test_app(); |
| 5816 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5817 | app.tool_collapse_threshold = 3; |
| 5818 | add_dense_tool_run(&mut app); |
| 5819 | |
| 5820 | // Force the next committed history revision to have the same raw key |
| 5821 | // as active revision 0, salt 1. The prior collapsed run keeps both |
| 5822 | // renders on the filtered slow path. |
| 5823 | app.next_history_revision = ACTIVE_REVISION_DOMAIN | 1; |
| 5824 | app.active_cell_revision = 0; |
| 5825 | let mut active = ActiveCell::new(); |
| 5826 | active.push_tool("user_shell_slow_path", running_user_shell_cell()); |
| 5827 | app.active_cell = Some(active); |
| 5828 | |
| 5829 | let area = Rect::new(0, 0, 100, 20); |
| 5830 | let mut running_buf = Buffer::empty(area); |
| 5831 | ChatWidget::new(&mut app, area).render(area, &mut running_buf); |
| 5832 | let running = buffer_text(&running_buf, area); |
| 5833 | assert!(running.contains("$ sleep 30 · running"), "{running}"); |
| 5834 | assert_eq!(app.collapsed_cell_map, vec![0, 3]); |
| 5835 | |
| 5836 | app.finalize_active_cell_as_interrupted(); |
| 5837 | assert_eq!( |
| 5838 | app.history_revisions[3], |
| 5839 | ACTIVE_REVISION_DOMAIN | 1, |
| 5840 | "fixture must force the old raw-revision collision" |
| 5841 | ); |
| 5842 | |
| 5843 | let mut settled_buf = Buffer::empty(area); |
| 5844 | ChatWidget::new(&mut app, area).render(area, &mut settled_buf); |
| 5845 | let settled = buffer_text(&settled_buf, area); |
| 5846 | assert!( |
| 5847 | !settled.contains("· running"), |
| 5848 | "history cell reused the active slow-path cache entry:\n{settled}" |
| 5849 | ); |
| 5850 | assert!(settled.contains("$ sleep 30 · stopped"), "{settled}"); |
| 5851 | } |
| 5852 | |
| 5853 | #[test] |
| 5854 | fn chat_widget_expands_dense_tool_runs_on_demand() { |
| 5855 | let mut app = create_test_app(); |
| 5856 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5857 | app.tool_collapse_threshold = 3; |
| 5858 | add_dense_tool_run(&mut app); |
| 5859 | app.expanded_tool_runs.insert(0); |
| 5860 | |
| 5861 | let area = Rect { |
| 5862 | x: 0, |
| 5863 | y: 0, |
| 5864 | width: 80, |
| 5865 | height: 12, |
| 5866 | }; |
| 5867 | let mut buf = Buffer::empty(area); |
| 5868 | let widget = ChatWidget::new(&mut app, area); |
| 5869 | widget.render(area, &mut buf); |
| 5870 | let rendered = buffer_text(&buf, area); |
| 5871 | |
| 5872 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 2]); |
| 5873 | assert!(rendered.contains("read_file.txt"), "{rendered}"); |
| 5874 | assert!(rendered.contains("list_dir.txt"), "{rendered}"); |
| 5875 | assert!(rendered.contains("web_search.txt"), "{rendered}"); |
| 5876 | assert!( |
| 5877 | !rendered.contains("full output from list_dir"), |
| 5878 | "{rendered}" |
| 5879 | ); |
| 5880 | } |
| 5881 | |
| 5882 | #[test] |
| 5883 | fn chat_widget_expanded_mode_leaves_dense_tool_runs_visible() { |
| 5884 | let mut app = create_test_app(); |
| 5885 | app.tool_collapse_mode = ToolCollapseMode::Expanded; |
| 5886 | app.tool_collapse_threshold = 3; |
| 5887 | add_dense_tool_run(&mut app); |
| 5888 | |
| 5889 | let area = Rect { |
| 5890 | x: 0, |
| 5891 | y: 0, |
| 5892 | width: 80, |
| 5893 | height: 12, |
| 5894 | }; |
| 5895 | let _widget = ChatWidget::new(&mut app, area); |
| 5896 | |
| 5897 | assert_eq!(app.collapsed_cell_map, vec![0, 1, 2]); |
| 5898 | } |
| 5899 | |
| 5900 | #[test] |
| 5901 | fn chat_widget_collapse_path_stable_across_frames() { |
| 5902 | let mut app = create_test_app(); |
| 5903 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5904 | app.tool_collapse_threshold = 3; |
| 5905 | add_dense_tool_run(&mut app); |
| 5906 | app.add_message(HistoryCell::User { |
| 5907 | content: "trailing prompt".to_string(), |
| 5908 | }); |
| 5909 | |
| 5910 | let area = Rect { |
| 5911 | x: 0, |
| 5912 | y: 0, |
| 5913 | width: 80, |
| 5914 | height: 10, |
| 5915 | }; |
| 5916 | |
| 5917 | let mut first_buf = Buffer::empty(area); |
| 5918 | ChatWidget::new(&mut app, area).render(area, &mut first_buf); |
| 5919 | let first = buffer_text(&first_buf, area); |
| 5920 | let first_map = app.collapsed_cell_map.clone(); |
| 5921 | let first_total = app.viewport.last_transcript_total; |
| 5922 | |
| 5923 | // Second frame without any app mutation: the borrowed filtered path |
| 5924 | // must reproduce the identical output and index map. |
| 5925 | let mut second_buf = Buffer::empty(area); |
| 5926 | ChatWidget::new(&mut app, area).render(area, &mut second_buf); |
| 5927 | let second = buffer_text(&second_buf, area); |
| 5928 | |
| 5929 | assert_eq!(first, second, "collapse path is frame-stable"); |
| 5930 | assert_eq!(first_map, app.collapsed_cell_map); |
| 5931 | assert_eq!(first_total, app.viewport.last_transcript_total); |
| 5932 | assert!(first.contains("Explored 2 files, 1 search"), "{first}"); |
| 5933 | assert!(first.contains("trailing prompt"), "{first}"); |
| 5934 | } |
| 5935 | |
| 5936 | #[test] |
| 5937 | fn chat_widget_collapses_run_spanning_history_and_active_entries() { |
| 5938 | let mut app = create_test_app(); |
| 5939 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 5940 | app.tool_collapse_threshold = 3; |
| 5941 | app.add_message(success_tool_cell("read_file")); |
| 5942 | app.add_message(success_tool_cell("list_dir")); |
| 5943 | let active = app.active_cell.get_or_insert_with(ActiveCell::new); |
| 5944 | active.push_untracked(success_tool_cell("web_search")); |
| 5945 | app.bump_active_cell_revision(); |
| 5946 | |
| 5947 | let area = Rect { |
| 5948 | x: 0, |
| 5949 | y: 0, |
| 5950 | width: 80, |
| 5951 | height: 8, |
| 5952 | }; |
| 5953 | let mut buf = Buffer::empty(area); |
| 5954 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 5955 | let rendered = buffer_text(&buf, area); |
| 5956 | |
| 5957 | assert_eq!(app.collapsed_cell_map, vec![0]); |
| 5958 | assert!( |
| 5959 | rendered.contains("Explored 2 files, 1 search"), |
| 5960 | "run spanning the history/active boundary renders one summary: {rendered}" |
| 5961 | ); |
| 5962 | |
| 5963 | // Mutating the active tail must re-render the summary (its revision |
| 5964 | // folds in the covered active entries). |
| 5965 | let rev_before = app.active_cell_revision; |
| 5966 | app.bump_active_cell_revision(); |
| 5967 | assert_ne!(rev_before, app.active_cell_revision); |
| 5968 | let mut second_buf = Buffer::empty(area); |
| 5969 | ChatWidget::new(&mut app, area).render(area, &mut second_buf); |
| 5970 | let second = buffer_text(&second_buf, area); |
| 5971 | assert!(second.contains("Explored 2 files, 1 search"), "{second}"); |
| 5972 | } |
| 5973 | |
| 5974 | // Cursor alignment tests |
| 5975 | |
| 5976 | #[test] |
| 5977 | fn cursor_basic_ascii() { |
| 5978 | // "hello" with cursor at various positions, width=10 |
| 5979 | assert_eq!(cursor_row_col("hello", 0, 10), (0, 0)); |
| 5980 | assert_eq!(cursor_row_col("hello", 3, 10), (0, 3)); |
| 5981 | assert_eq!(cursor_row_col("hello", 5, 10), (0, 5)); |
| 5982 | } |
| 5983 | |
| 5984 | #[test] |
| 5985 | fn cursor_at_wrap_boundary() { |
| 5986 | // "abcde" exactly fills width=5 |
| 5987 | // Cursor at position 5 (after last char) should wrap to next line |
| 5988 | let (row, col) = cursor_row_col("abcde", 5, 5); |
| 5989 | assert_eq!(row, 1, "cursor at end of full line should wrap"); |
| 5990 | assert_eq!(col, 0, "cursor should be at start of next line"); |
| 5991 | } |
| 5992 | |
| 5993 | #[test] |
| 5994 | fn cursor_with_cjk_characters() { |
| 5995 | // "中" is a CJK character with width 2 |
| 5996 | // "a中b" = 1 + 2 + 1 = 4 display width |
| 5997 | assert_eq!(cursor_row_col("a中b", 0, 10), (0, 0)); // before 'a' |
| 5998 | assert_eq!(cursor_row_col("a中b", 1, 10), (0, 1)); // after 'a', before '中' |
| 5999 | assert_eq!(cursor_row_col("a中b", 2, 10), (0, 3)); // after '中', before 'b' |
| 6000 | assert_eq!(cursor_row_col("a中b", 3, 10), (0, 4)); // after 'b' |
| 6001 | } |
| 6002 | |
| 6003 | #[test] |
| 6004 | fn cursor_cjk_at_wrap_boundary() { |
| 6005 | // width=5, input "abcd中" (4 + 2 = 6, CJK doesn't fit on line 1) |
| 6006 | // CJK should wrap to next line |
| 6007 | let lines = wrap_text("abcd中", 5); |
| 6008 | assert_eq!(lines, vec!["abcd", "中"]); |
| 6009 | |
| 6010 | // Cursor after CJK should be on row 1, col 2 |
| 6011 | let (row, col) = cursor_row_col("abcd中", 5, 5); |
| 6012 | assert_eq!(row, 1); |
| 6013 | assert_eq!(col, 2); |
| 6014 | } |
| 6015 | |
| 6016 | /// Composer wrapping breaks between words, not through them. A line |
| 6017 | /// ending in a severed word (`…Write the file onl`) reads exactly like |
| 6018 | /// content that was cut off, which is how it was reported. |
| 6019 | #[test] |
| 6020 | fn composer_wraps_on_word_boundaries_without_losing_a_character() { |
| 6021 | let text = "Mark inferences as inferences. A short PRD where each \ |
| 6022 | section decides something beats a long one."; |
| 6023 | for width in [20usize, 33, 47, 60, 79] { |
| 6024 | let lines = wrap_text(text, width); |
| 6025 | assert_eq!( |
| 6026 | lines.concat(), |
| 6027 | text, |
| 6028 | "wrapping must be lossless at width={width}: {lines:?}" |
| 6029 | ); |
| 6030 | for line in &lines { |
| 6031 | assert!( |
| 6032 | line.width() <= width, |
| 6033 | "line exceeds width={width}: {line:?}" |
| 6034 | ); |
| 6035 | } |
| 6036 | // No line may end in the middle of a word: either it ends the |
| 6037 | // text, or it ends on whitespace. |
| 6038 | for line in lines.iter().take(lines.len().saturating_sub(1)) { |
| 6039 | assert!( |
| 6040 | line.is_empty() || line.ends_with(' '), |
| 6041 | "wrapped line broke mid-word at width={width}: {line:?}" |
| 6042 | ); |
| 6043 | } |
| 6044 | } |
| 6045 | } |
| 6046 | |
| 6047 | /// A token with no break point in it still has to fit the terminal, so it |
| 6048 | /// breaks hard. Losslessness holds there too. |
| 6049 | #[test] |
| 6050 | fn composer_hard_breaks_words_longer_than_the_line() { |
| 6051 | let text = "see https://example.com/a/very/long/path/that/never/breaks?x=1 now"; |
| 6052 | let lines = wrap_text(text, 24); |
| 6053 | assert_eq!(lines.concat(), text, "{lines:?}"); |
| 6054 | for line in &lines { |
| 6055 | assert!(line.width() <= 24, "line exceeds width: {line:?}"); |
| 6056 | } |
| 6057 | assert!( |
| 6058 | lines.len() > 2, |
| 6059 | "an unbreakable token must still be split across lines: {lines:?}" |
| 6060 | ); |
| 6061 | } |
| 6062 | |
| 6063 | /// Wide characters have no spaces to break on; the width accounting must |
| 6064 | /// still hold. This repo patches `unicode-width` for CJK, so measure the |
| 6065 | /// wrapped output rather than trusting char counts. |
| 6066 | #[test] |
| 6067 | fn composer_wrapping_respects_wide_character_width() { |
| 6068 | let text = "中文字符串没有空格可以换行"; |
| 6069 | let lines = wrap_text(text, 7); |
| 6070 | assert_eq!(lines.concat(), text, "{lines:?}"); |
| 6071 | for line in &lines { |
| 6072 | assert!(line.width() <= 7, "line exceeds width: {line:?}"); |
| 6073 | } |
| 6074 | } |
| 6075 | |
| 6076 | #[test] |
| 6077 | fn cursor_with_combining_marks() { |
| 6078 | // "e\u0301" is 'e' with combining acute accent (é) |
| 6079 | // Display width is 1 (combining mark has width 0) |
| 6080 | let input = "e\u{0301}"; // é as e + combining acute |
| 6081 | assert_eq!(input.chars().count(), 2); |
| 6082 | |
| 6083 | // Cursor positions: |
| 6084 | // 0 = before 'e' |
| 6085 | // 1 = after 'e', before combining mark |
| 6086 | // 2 = after combining mark |
| 6087 | assert_eq!(cursor_row_col(input, 0, 10), (0, 0)); |
| 6088 | assert_eq!(cursor_row_col(input, 1, 10), (0, 1)); |
| 6089 | assert_eq!(cursor_row_col(input, 2, 10), (0, 1)); // combining mark has width 0 |
| 6090 | } |
| 6091 | |
| 6092 | #[test] |
| 6093 | fn cursor_with_emoji() { |
| 6094 | // Many emojis are double-width |
| 6095 | let input = "a😀b"; |
| 6096 | // Cursor at 2 (after emoji) should account for emoji width |
| 6097 | let (_row, col) = cursor_row_col(input, 2, 10); |
| 6098 | // Emoji width varies by system, but should be either 1 or 2 |
| 6099 | assert!((2..=3).contains(&col), "col = {col}, expected 2 or 3"); |
| 6100 | } |
| 6101 | |
| 6102 | #[test] |
| 6103 | fn cursor_with_emoji_zwj_sequence() { |
| 6104 | let input = "👨👩👧👦"; |
| 6105 | let cursor = input.chars().count(); |
| 6106 | let (row, col) = cursor_row_col(input, cursor, 10); |
| 6107 | assert_eq!(row, 0); |
| 6108 | assert_eq!(col, input.width()); |
| 6109 | } |
| 6110 | |
| 6111 | #[test] |
| 6112 | fn cursor_with_newlines() { |
| 6113 | // "ab\ncd" with cursor moving through |
| 6114 | assert_eq!(cursor_row_col("ab\ncd", 0, 10), (0, 0)); // before 'a' |
| 6115 | assert_eq!(cursor_row_col("ab\ncd", 2, 10), (0, 2)); // after 'b', before '\n' |
| 6116 | assert_eq!(cursor_row_col("ab\ncd", 3, 10), (1, 0)); // after '\n', before 'c' |
| 6117 | assert_eq!(cursor_row_col("ab\ncd", 5, 10), (1, 2)); // after 'd' |
| 6118 | } |
| 6119 | |
| 6120 | #[test] |
| 6121 | fn wrap_input_lines_preserves_empty_lines() { |
| 6122 | let lines = wrap_input_lines("a\n\nb", 10); |
| 6123 | assert_eq!(lines, vec!["a", "", "b"]); |
| 6124 | } |
| 6125 | |
| 6126 | #[test] |
| 6127 | fn wrap_and_caret_measure_tabs_as_painted() { |
| 6128 | // Ratatui strips control characters, so a tab paints no cells. Wrap |
| 6129 | // budgets, caret columns, and click mapping must all agree on zero; |
| 6130 | // counting the tab would break the line early and drift the caret |
| 6131 | // and clicks one cell per tab. |
| 6132 | assert_eq!(wrap_text("\t0123456789", 11), vec!["\t0123456789"]); |
| 6133 | assert_eq!(cursor_row_col("a\tb", 3, 80), (0, 2)); |
| 6134 | assert_eq!(cursor_row_col("\ta", 2, 80), (0, 1)); |
| 6135 | } |
| 6136 | |
| 6137 | #[test] |
| 6138 | fn wrap_input_lines_trailing_newline() { |
| 6139 | let lines = wrap_input_lines("a\n", 10); |
| 6140 | assert_eq!(lines, vec!["a", ""]); |
| 6141 | } |
| 6142 | |
| 6143 | #[test] |
| 6144 | fn wrap_input_lines_for_mouse_empty_input() { |
| 6145 | // Empty input should return a single empty line at position 0. |
| 6146 | // This ensures empty composer mouse selection works correctly (issue #3909). |
| 6147 | let result = wrap_input_lines_for_mouse("", 10); |
| 6148 | assert_eq!(result, vec![(0, String::new())]); |
| 6149 | |
| 6150 | // Also verify with width=0 edge case |
| 6151 | let result_zero = wrap_input_lines_for_mouse("", 0); |
| 6152 | assert_eq!(result_zero, vec![(0, String::new())]); |
| 6153 | } |
| 6154 | |
| 6155 | #[test] |
| 6156 | fn cursor_and_wrap_consistency() { |
| 6157 | // Ensure cursor_row_col is consistent with wrap_text |
| 6158 | // for various inputs |
| 6159 | let test_cases = vec![ |
| 6160 | ("hello world", 5), |
| 6161 | ("abcdefghij", 3), |
| 6162 | ("中文测试", 6), |
| 6163 | ("a\nb\nc", 10), |
| 6164 | ]; |
| 6165 | |
| 6166 | for (input, width) in test_cases { |
| 6167 | let lines = wrap_input_lines(input, width); |
| 6168 | let (cursor_row, _) = cursor_row_col(input, input.chars().count(), width); |
| 6169 | |
| 6170 | // Cursor at end should be on the last line (or wrapped past it) |
| 6171 | assert!( |
| 6172 | cursor_row <= lines.len(), |
| 6173 | "cursor_row={cursor_row} should be <= lines.len()={} for input={input:?}", |
| 6174 | lines.len() |
| 6175 | ); |
| 6176 | } |
| 6177 | } |
| 6178 | |
| 6179 | #[test] |
| 6180 | fn bare_slash_menu_leads_with_the_small_set_and_reaches_the_long_tail() { |
| 6181 | let hints = slash_completion_hints("/", 512, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6182 | let names: Vec<&str> = hints.iter().map(|hint| hint.name.as_str()).collect(); |
| 6183 | assert_eq!( |
| 6184 | names.iter().take(6).copied().collect::<Vec<_>>(), |
| 6185 | ["/help", "/setup", "/model", "/settings", "/resume", "/rc"], |
| 6186 | "the small starting set still leads: {names:?}" |
| 6187 | ); |
| 6188 | // Founder ruling: the ranking is welcome, the truncation is not — a |
| 6189 | // command you cannot reach from the menu is a command you cannot find. |
| 6190 | assert!( |
| 6191 | names.len() > 6, |
| 6192 | "the long tail follows the starting set: {names:?}" |
| 6193 | ); |
| 6194 | assert!( |
| 6195 | slash_completion_hints("/wor", 128, &[], Locale::En, None, ProviderKind::Deepseek) |
| 6196 | .iter() |
| 6197 | .any(|hint| hint.name == "/workflow") |
| 6198 | ); |
| 6199 | assert!( |
| 6200 | slash_completion_hints("/conf", 128, &[], Locale::En, None, ProviderKind::Deepseek) |
| 6201 | .iter() |
| 6202 | .any(|hint| hint.name == "/config") |
| 6203 | ); |
| 6204 | assert!( |
| 6205 | slash_completion_hints("/age", 128, &[], Locale::En, None, ProviderKind::Deepseek) |
| 6206 | .iter() |
| 6207 | .any(|hint| hint.name == "/subagents") |
| 6208 | ); |
| 6209 | assert!( |
| 6210 | slash_completion_hints("/comp", 128, &[], Locale::En, None, ProviderKind::Deepseek) |
| 6211 | .iter() |
| 6212 | .any(|hint| hint.name == "/compact") |
| 6213 | ); |
| 6214 | } |
| 6215 | |
| 6216 | #[test] |
| 6217 | fn slash_completion_hints_rank_exact_alias_above_prefix_alias() { |
| 6218 | // `/q` should rank `/exit` (exact alias `q`) above `/clear` (alias |
| 6219 | // `qingping` only matches by prefix). Before #1811 the entries were |
| 6220 | // sorted alphabetically, so `/clear` shadowed `/exit` even though |
| 6221 | // the user typed the exact alias for `/exit`. |
| 6222 | let hints = |
| 6223 | slash_completion_hints("/q", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6224 | let names: Vec<&str> = hints.iter().map(|h| h.name.as_str()).collect(); |
| 6225 | let exit_pos = names |
| 6226 | .iter() |
| 6227 | .position(|n| *n == "/exit") |
| 6228 | .expect("/exit should appear when typing /q (alias `q`)"); |
| 6229 | let clear_pos = names |
| 6230 | .iter() |
| 6231 | .position(|n| *n == "/clear") |
| 6232 | .expect("/clear should still appear when typing /q (alias `qingping`)"); |
| 6233 | assert!( |
| 6234 | exit_pos < clear_pos, |
| 6235 | "expected /exit to rank above /clear for prefix /q, got {names:?}" |
| 6236 | ); |
| 6237 | } |
| 6238 | |
| 6239 | #[test] |
| 6240 | fn slash_completion_does_not_repeat_alias_already_in_label() { |
| 6241 | // Typing `/p` matches `/clear` via alias `qingping`, so the label |
| 6242 | // shows `/clear or /qingping`. The description must not also append |
| 6243 | // `(aliases: /qingping)` (#3990). |
| 6244 | let hints = |
| 6245 | slash_completion_hints("/p", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6246 | let clear = hints |
| 6247 | .iter() |
| 6248 | .find(|h| h.name == "/clear") |
| 6249 | .expect("/clear should appear for /p via qingping"); |
| 6250 | assert_eq!( |
| 6251 | clear.alias_hint.as_deref(), |
| 6252 | Some("qingping"), |
| 6253 | "label should surface the matching alias" |
| 6254 | ); |
| 6255 | assert!( |
| 6256 | !clear.description.contains("(aliases:"), |
| 6257 | "description should omit alias list when the only alias is already in the label: {}", |
| 6258 | clear.description |
| 6259 | ); |
| 6260 | assert!( |
| 6261 | !clear.description.contains("/qingping"), |
| 6262 | "description must not repeat /qingping: {}", |
| 6263 | clear.description |
| 6264 | ); |
| 6265 | } |
| 6266 | |
| 6267 | #[test] |
| 6268 | fn a_bare_slash_leads_with_the_short_list_and_still_reaches_every_command() { |
| 6269 | // Founder live-test: "I like how we prioritize the slash thing but it |
| 6270 | // should still be able to find all of them." The curated six stay at |
| 6271 | // the head; the rest follow instead of being filtered away, and the |
| 6272 | // popup scrolls around the selection to reach them. |
| 6273 | let hints = slash_completion_hints("/", 512, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6274 | let names: Vec<String> = hints.iter().map(|h| h.name.clone()).collect(); |
| 6275 | |
| 6276 | let head: Vec<String> = crate::commands::traits::BARE_SLASH_DISCOVERY_COMMANDS |
| 6277 | .iter() |
| 6278 | .map(|name| format!("/{name}")) |
| 6279 | .collect(); |
| 6280 | assert_eq!( |
| 6281 | names.iter().take(head.len()).cloned().collect::<Vec<_>>(), |
| 6282 | head, |
| 6283 | "the short task sequence still leads" |
| 6284 | ); |
| 6285 | assert!( |
| 6286 | names.len() > head.len(), |
| 6287 | "a bare slash must reach past the short list: {} entries", |
| 6288 | names.len() |
| 6289 | ); |
| 6290 | // A command deliberately outside the short list must be reachable. |
| 6291 | assert!( |
| 6292 | names.iter().any(|name| name == "/mcp"), |
| 6293 | "every command is findable from a bare slash" |
| 6294 | ); |
| 6295 | } |
| 6296 | |
| 6297 | #[test] |
| 6298 | fn slash_completion_hints_keep_prefix_match_alphabetical_within_tier() { |
| 6299 | // Within the same rank tier (no exact-alias match), entries fall |
| 6300 | // back to alphabetical name order, same as the prior behavior. |
| 6301 | let hints = |
| 6302 | slash_completion_hints("/co", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6303 | let names: Vec<&str> = hints |
| 6304 | .iter() |
| 6305 | .map(|h| h.name.as_str()) |
| 6306 | .filter(|n| n.starts_with("/co")) |
| 6307 | .collect(); |
| 6308 | let sorted = { |
| 6309 | let mut copy = names.clone(); |
| 6310 | copy.sort(); |
| 6311 | copy |
| 6312 | }; |
| 6313 | assert_eq!( |
| 6314 | names, sorted, |
| 6315 | "tied entries (no exact-alias match) should stay alphabetical" |
| 6316 | ); |
| 6317 | } |
| 6318 | |
| 6319 | #[test] |
| 6320 | fn slash_completion_hints_exclude_set_and_deepseek_commands() { |
| 6321 | let hints = slash_completion_hints("/", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6322 | assert!(!hints.iter().any(|hint| hint.name == "/set")); |
| 6323 | assert!(!hints.iter().any(|hint| hint.name == "/codewhale")); |
| 6324 | } |
| 6325 | |
| 6326 | #[test] |
| 6327 | fn slash_completion_hints_rank_toolbox_commands_below_the_starting_set() { |
| 6328 | let root = slash_completion_hints("/", 512, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6329 | let position = |name: &str| root.iter().position(|hint| hint.name == name); |
| 6330 | // The task-oriented set leads; the toolbox is reachable behind it |
| 6331 | // rather than hidden until guessed at. |
| 6332 | assert_eq!(position("/model"), Some(2)); |
| 6333 | for toolbox in [ |
| 6334 | "/provider", |
| 6335 | "/fleet", |
| 6336 | "/config", |
| 6337 | "/statusline", |
| 6338 | "/rlm", |
| 6339 | "/modeldb", |
| 6340 | "/models", |
| 6341 | "/plugin", |
| 6342 | ] { |
| 6343 | let rank = position(toolbox) |
| 6344 | .unwrap_or_else(|| panic!("{toolbox} must be reachable from a bare slash")); |
| 6345 | assert!(rank >= 6, "{toolbox} must rank below the starting set"); |
| 6346 | } |
| 6347 | assert!(position("/subagents").is_some()); |
| 6348 | assert!(position("/agents").is_some()); |
| 6349 | |
| 6350 | let rlm = slash_completion_hints("/rl", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6351 | assert!(rlm.iter().any(|hint| hint.name == "/rlm")); |
| 6352 | |
| 6353 | let modeldb = slash_completion_hints( |
| 6354 | "/modeld", |
| 6355 | 128, |
| 6356 | &[], |
| 6357 | Locale::En, |
| 6358 | None, |
| 6359 | ProviderKind::Deepseek, |
| 6360 | ); |
| 6361 | assert!(modeldb.iter().any(|hint| hint.name == "/modeldb")); |
| 6362 | |
| 6363 | let plugin = |
| 6364 | slash_completion_hints("/pl", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6365 | assert!(plugin.iter().any(|hint| hint.name == "/plugin")); |
| 6366 | |
| 6367 | let subagents = |
| 6368 | slash_completion_hints("/sub", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6369 | assert!(subagents.iter().any(|hint| hint.name == "/subagents")); |
| 6370 | } |
| 6371 | |
| 6372 | #[test] |
| 6373 | fn slash_completion_hints_use_user_command_frontmatter_description() { |
| 6374 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6375 | let commands_dir = tmp.path().join(".deepseek").join("commands"); |
| 6376 | crate::test_support::trust_workspace(tmp.path()); |
| 6377 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6378 | std::fs::write( |
| 6379 | commands_dir.join("git-scan.md"), |
| 6380 | "---\ndescription: Scan nested git repositories\n---\nscan", |
| 6381 | ) |
| 6382 | .unwrap(); |
| 6383 | |
| 6384 | let hints = slash_completion_hints( |
| 6385 | "/git", |
| 6386 | 128, |
| 6387 | &[], |
| 6388 | Locale::En, |
| 6389 | Some(tmp.path()), |
| 6390 | ProviderKind::Deepseek, |
| 6391 | ); |
| 6392 | let entry = hints |
| 6393 | .iter() |
| 6394 | .find(|hint| hint.name == "/git-scan") |
| 6395 | .expect("custom command should be present"); |
| 6396 | assert_eq!(entry.description, "Scan nested git repositories"); |
| 6397 | } |
| 6398 | |
| 6399 | #[test] |
| 6400 | fn slash_completion_hints_use_user_command_argument_hint() { |
| 6401 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6402 | crate::test_support::trust_workspace(tmp.path()); |
| 6403 | let commands_dir = tmp.path().join(".deepseek").join("commands"); |
| 6404 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6405 | std::fs::write( |
| 6406 | commands_dir.join("deploy.md"), |
| 6407 | "---\ndescription: Deploy target\nargument-hint: <env>\n---\ndeploy", |
| 6408 | ) |
| 6409 | .unwrap(); |
| 6410 | |
| 6411 | let hints = slash_completion_hints( |
| 6412 | "/deploy", |
| 6413 | 128, |
| 6414 | &[], |
| 6415 | Locale::En, |
| 6416 | Some(tmp.path()), |
| 6417 | ProviderKind::Deepseek, |
| 6418 | ); |
| 6419 | let entry = hints |
| 6420 | .iter() |
| 6421 | .find(|hint| hint.name == "/deploy") |
| 6422 | .expect("custom command should be present"); |
| 6423 | assert_eq!(entry.description, "Deploy target <env>"); |
| 6424 | } |
| 6425 | |
| 6426 | #[test] |
| 6427 | fn slash_completion_uses_frontmatter_name_and_usage() { |
| 6428 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6429 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6430 | crate::test_support::trust_workspace(tmp.path()); |
| 6431 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6432 | std::fs::write( |
| 6433 | commands_dir.join("workflow-file.md"), |
| 6434 | "---\nname: inspect\ndescription: Inspect target\nusage: /inspect <path>\narguments: <path>\n---\ninspect", |
| 6435 | ) |
| 6436 | .unwrap(); |
| 6437 | |
| 6438 | let hints = slash_completion_hints( |
| 6439 | "/ins", |
| 6440 | 128, |
| 6441 | &[], |
| 6442 | Locale::En, |
| 6443 | Some(tmp.path()), |
| 6444 | ProviderKind::Deepseek, |
| 6445 | ); |
| 6446 | let entry = hints |
| 6447 | .iter() |
| 6448 | .find(|hint| hint.name == "/inspect") |
| 6449 | .expect("frontmatter name should complete"); |
| 6450 | |
| 6451 | assert_eq!(entry.description, "Inspect target /inspect <path>"); |
| 6452 | assert!(!hints.iter().any(|hint| hint.name == "/workflow-file")); |
| 6453 | } |
| 6454 | |
| 6455 | #[test] |
| 6456 | fn slash_completion_uses_arguments_when_usage_and_legacy_hint_are_absent() { |
| 6457 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6458 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6459 | crate::test_support::trust_workspace(tmp.path()); |
| 6460 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6461 | std::fs::write( |
| 6462 | commands_dir.join("deploy.md"), |
| 6463 | "---\ndescription: Deploy target\narguments: <environment>\n---\ndeploy", |
| 6464 | ) |
| 6465 | .unwrap(); |
| 6466 | |
| 6467 | let hints = slash_completion_hints( |
| 6468 | "/deploy", |
| 6469 | 128, |
| 6470 | &[], |
| 6471 | Locale::En, |
| 6472 | Some(tmp.path()), |
| 6473 | ProviderKind::Deepseek, |
| 6474 | ); |
| 6475 | let entry = hints |
| 6476 | .iter() |
| 6477 | .find(|hint| hint.name == "/deploy") |
| 6478 | .expect("custom command should be present"); |
| 6479 | |
| 6480 | assert_eq!(entry.description, "Deploy target <environment>"); |
| 6481 | } |
| 6482 | |
| 6483 | #[test] |
| 6484 | fn typing_a_command_and_a_space_states_its_usage_and_lists_its_subcommands() { |
| 6485 | let hints = slash_completion_hints( |
| 6486 | "/workspace ", |
| 6487 | 128, |
| 6488 | &[], |
| 6489 | Locale::En, |
| 6490 | None, |
| 6491 | ProviderKind::Deepseek, |
| 6492 | ); |
| 6493 | |
| 6494 | let head = hints.first().expect("usage row"); |
| 6495 | assert_eq!(head.name, "/workspace"); |
| 6496 | assert_eq!(head.description, "/workspace [path|worktrees]"); |
| 6497 | assert!( |
| 6498 | hints.iter().any(|hint| hint.name == "/workspace worktrees"), |
| 6499 | "worktrees must be offered as a subcommand candidate: {:?}", |
| 6500 | hints.iter().map(|h| h.name.as_str()).collect::<Vec<_>>() |
| 6501 | ); |
| 6502 | } |
| 6503 | |
| 6504 | /// An alias reaches the same usage line as the canonical name, and the |
| 6505 | /// rows it offers are still spelled with the canonical name. |
| 6506 | #[test] |
| 6507 | fn a_command_alias_states_the_canonical_usage() { |
| 6508 | let hints = |
| 6509 | slash_completion_hints("/cwd ", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6510 | assert_eq!(hints[0].name, "/workspace"); |
| 6511 | assert_eq!(hints[0].description, "/workspace [path|worktrees]"); |
| 6512 | } |
| 6513 | |
| 6514 | /// Once filtering starts the usage row steps aside so a single remaining |
| 6515 | /// verb is unambiguous — that is what lets Tab complete it. |
| 6516 | #[test] |
| 6517 | fn a_partial_subcommand_filters_to_the_verbs_that_match() { |
| 6518 | let hints = slash_completion_hints( |
| 6519 | "/workspace wor", |
| 6520 | 128, |
| 6521 | &[], |
| 6522 | Locale::En, |
| 6523 | None, |
| 6524 | ProviderKind::Deepseek, |
| 6525 | ); |
| 6526 | assert_eq!( |
| 6527 | hints |
| 6528 | .iter() |
| 6529 | .map(|hint| hint.name.as_str()) |
| 6530 | .collect::<Vec<_>>(), |
| 6531 | vec!["/workspace worktrees"] |
| 6532 | ); |
| 6533 | |
| 6534 | let none = slash_completion_hints( |
| 6535 | "/workspace zzz", |
| 6536 | 128, |
| 6537 | &[], |
| 6538 | Locale::En, |
| 6539 | None, |
| 6540 | ProviderKind::Deepseek, |
| 6541 | ); |
| 6542 | assert!( |
| 6543 | none.is_empty(), |
| 6544 | "{:?}", |
| 6545 | none.iter() |
| 6546 | .map(|hint| hint.name.as_str()) |
| 6547 | .collect::<Vec<_>>() |
| 6548 | ); |
| 6549 | } |
| 6550 | |
| 6551 | #[test] |
| 6552 | fn a_command_that_takes_no_arguments_still_closes_the_menu() { |
| 6553 | let hints = |
| 6554 | slash_completion_hints("/copy ", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6555 | assert!(hints.is_empty()); |
| 6556 | } |
| 6557 | |
| 6558 | #[test] |
| 6559 | fn a_second_argument_word_and_an_unknown_command_offer_nothing() { |
| 6560 | assert!( |
| 6561 | slash_completion_hints( |
| 6562 | "/workspace worktrees ", |
| 6563 | 128, |
| 6564 | &[], |
| 6565 | Locale::En, |
| 6566 | None, |
| 6567 | ProviderKind::Deepseek, |
| 6568 | ) |
| 6569 | .is_empty() |
| 6570 | ); |
| 6571 | assert!( |
| 6572 | slash_completion_hints( |
| 6573 | "/nosuchcommand ", |
| 6574 | 128, |
| 6575 | &[], |
| 6576 | Locale::En, |
| 6577 | None, |
| 6578 | ProviderKind::Deepseek, |
| 6579 | ) |
| 6580 | .is_empty() |
| 6581 | ); |
| 6582 | } |
| 6583 | |
| 6584 | /// `/skill ` and `/model ` own their argument menus; the usage rows must |
| 6585 | /// not displace them. |
| 6586 | #[test] |
| 6587 | fn argument_menus_that_already_exist_keep_their_rows() { |
| 6588 | let skills = vec![("codereview".to_string(), "Review a diff".to_string())]; |
| 6589 | let hints = slash_completion_hints( |
| 6590 | "/skill ", |
| 6591 | 128, |
| 6592 | &skills, |
| 6593 | Locale::En, |
| 6594 | None, |
| 6595 | ProviderKind::Deepseek, |
| 6596 | ); |
| 6597 | assert!(hints.iter().any(|hint| hint.name == "/skill codereview")); |
| 6598 | assert!(hints.iter().all(|hint| hint.name != "/skill")); |
| 6599 | } |
| 6600 | |
| 6601 | #[test] |
| 6602 | fn slash_completion_hints_exclude_hidden_user_commands() { |
| 6603 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6604 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6605 | crate::test_support::trust_workspace(tmp.path()); |
| 6606 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6607 | std::fs::write( |
| 6608 | commands_dir.join("secret.md"), |
| 6609 | "---\ndescription: Internal command\nhidden: true\n---\nsecret", |
| 6610 | ) |
| 6611 | .unwrap(); |
| 6612 | |
| 6613 | let hints = slash_completion_hints( |
| 6614 | "/secret", |
| 6615 | 128, |
| 6616 | &[], |
| 6617 | Locale::En, |
| 6618 | Some(tmp.path()), |
| 6619 | ProviderKind::Deepseek, |
| 6620 | ); |
| 6621 | |
| 6622 | assert!(!hints.iter().any(|hint| hint.name == "/secret")); |
| 6623 | } |
| 6624 | |
| 6625 | #[test] |
| 6626 | fn hidden_name_override_filters_shadowed_builtin_from_slash_completion() { |
| 6627 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6628 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6629 | crate::test_support::trust_workspace(tmp.path()); |
| 6630 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6631 | std::fs::write( |
| 6632 | commands_dir.join("private-help.md"), |
| 6633 | "---\nname: help\nhidden: true\n---\nprivate help", |
| 6634 | ) |
| 6635 | .unwrap(); |
| 6636 | |
| 6637 | let hints = slash_completion_hints( |
| 6638 | "/help", |
| 6639 | 128, |
| 6640 | &[], |
| 6641 | Locale::En, |
| 6642 | Some(tmp.path()), |
| 6643 | ProviderKind::Deepseek, |
| 6644 | ); |
| 6645 | |
| 6646 | assert!(!hints.iter().any(|hint| hint.name == "/help")); |
| 6647 | } |
| 6648 | |
| 6649 | #[test] |
| 6650 | fn slash_completion_hints_match_user_command_aliases() { |
| 6651 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6652 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6653 | crate::test_support::trust_workspace(tmp.path()); |
| 6654 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6655 | std::fs::write( |
| 6656 | commands_dir.join("deploy-target.md"), |
| 6657 | "---\ndescription: Deploy target\nalias: ship\n---\ndeploy", |
| 6658 | ) |
| 6659 | .unwrap(); |
| 6660 | |
| 6661 | let hints = slash_completion_hints( |
| 6662 | "/ship", |
| 6663 | 128, |
| 6664 | &[], |
| 6665 | Locale::En, |
| 6666 | Some(tmp.path()), |
| 6667 | ProviderKind::Deepseek, |
| 6668 | ); |
| 6669 | let entry = hints |
| 6670 | .iter() |
| 6671 | .find(|hint| hint.name == "/deploy-target") |
| 6672 | .expect("user command should be matched by alias"); |
| 6673 | |
| 6674 | assert_eq!(entry.alias_hint.as_deref(), Some("ship")); |
| 6675 | assert_eq!(entry.description, "Deploy target"); |
| 6676 | } |
| 6677 | |
| 6678 | #[test] |
| 6679 | fn slash_completion_offers_no_retired_pod_entry() { |
| 6680 | let hints = |
| 6681 | slash_completion_hints("/pod", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6682 | assert!( |
| 6683 | !hints.iter().any(|hint| hint.name == "/pod"), |
| 6684 | "the retired /pod spelling must not complete" |
| 6685 | ); |
| 6686 | for entry in hints.iter().filter(|hint| hint.name == "/fleet") { |
| 6687 | assert_eq!( |
| 6688 | entry.alias_hint, None, |
| 6689 | "no alias may point at the retired spelling" |
| 6690 | ); |
| 6691 | } |
| 6692 | } |
| 6693 | |
| 6694 | #[test] |
| 6695 | fn slash_completion_omits_rejected_user_alias_collisions() { |
| 6696 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6697 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6698 | crate::test_support::trust_workspace(tmp.path()); |
| 6699 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6700 | std::fs::write( |
| 6701 | commands_dir.join("alpha.md"), |
| 6702 | "---\ndescription: Alpha command\nalias: beta\n---\nalpha", |
| 6703 | ) |
| 6704 | .unwrap(); |
| 6705 | std::fs::write( |
| 6706 | commands_dir.join("beta.md"), |
| 6707 | "---\ndescription: Beta command\n---\nbeta", |
| 6708 | ) |
| 6709 | .unwrap(); |
| 6710 | |
| 6711 | let hints = slash_completion_hints( |
| 6712 | "/bet", |
| 6713 | 128, |
| 6714 | &[], |
| 6715 | Locale::En, |
| 6716 | Some(tmp.path()), |
| 6717 | ProviderKind::Deepseek, |
| 6718 | ); |
| 6719 | |
| 6720 | assert!(hints.iter().any(|hint| hint.name == "/beta")); |
| 6721 | assert!( |
| 6722 | !hints.iter().any(|hint| hint.name == "/alpha"), |
| 6723 | "a command must not match through an alias rejected by the registry" |
| 6724 | ); |
| 6725 | } |
| 6726 | |
| 6727 | #[test] |
| 6728 | fn slash_completion_hints_keep_builtin_canonical_when_only_builtin_alias_is_shadowed() { |
| 6729 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6730 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6731 | crate::test_support::trust_workspace(tmp.path()); |
| 6732 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6733 | std::fs::write( |
| 6734 | commands_dir.join("attach-review.md"), |
| 6735 | "---\ndescription: Review image\nalias: image\n---\nreview image", |
| 6736 | ) |
| 6737 | .unwrap(); |
| 6738 | |
| 6739 | let canonical_hints = slash_completion_hints( |
| 6740 | "/att", |
| 6741 | 128, |
| 6742 | &[], |
| 6743 | Locale::En, |
| 6744 | Some(tmp.path()), |
| 6745 | ProviderKind::Deepseek, |
| 6746 | ); |
| 6747 | |
| 6748 | let attach = canonical_hints |
| 6749 | .iter() |
| 6750 | .find(|hint| hint.name == "/attach") |
| 6751 | .expect( |
| 6752 | "canonical /attach should remain visible when only its /image alias is shadowed", |
| 6753 | ); |
| 6754 | assert!( |
| 6755 | !attach.description.contains("/image"), |
| 6756 | "canonical completion must not advertise a user-shadowed alias" |
| 6757 | ); |
| 6758 | |
| 6759 | let alias_hints = slash_completion_hints( |
| 6760 | "/image", |
| 6761 | 128, |
| 6762 | &[], |
| 6763 | Locale::En, |
| 6764 | Some(tmp.path()), |
| 6765 | ProviderKind::Deepseek, |
| 6766 | ); |
| 6767 | |
| 6768 | assert!( |
| 6769 | alias_hints.iter().any(|hint| hint.name == "/attach-review"), |
| 6770 | "user command should complete through its /image alias" |
| 6771 | ); |
| 6772 | assert!( |
| 6773 | !alias_hints.iter().any(|hint| hint.name == "/attach"), |
| 6774 | "built-in /attach should not complete through shadowed /image alias" |
| 6775 | ); |
| 6776 | } |
| 6777 | |
| 6778 | #[test] |
| 6779 | fn slash_completion_accepted_user_alias_claims_builtin_canonical_token() { |
| 6780 | // A visible user command whose accepted alias equals a built-in |
| 6781 | // canonical token must own that token in completion: the built-in |
| 6782 | // suggestion is absent and the user command appears for the alias. |
| 6783 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6784 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6785 | crate::test_support::trust_workspace(tmp.path()); |
| 6786 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6787 | std::fs::write( |
| 6788 | commands_dir.join("assistant.md"), |
| 6789 | "---\ndescription: My assistant\nalias: help\n---\nassistant", |
| 6790 | ) |
| 6791 | .unwrap(); |
| 6792 | |
| 6793 | let hints = slash_completion_hints( |
| 6794 | "/help", |
| 6795 | 128, |
| 6796 | &[], |
| 6797 | Locale::En, |
| 6798 | Some(tmp.path()), |
| 6799 | ProviderKind::Deepseek, |
| 6800 | ); |
| 6801 | |
| 6802 | assert!( |
| 6803 | !hints.iter().any(|hint| hint.name == "/help"), |
| 6804 | "built-in /help must be absent when a user alias claims the token" |
| 6805 | ); |
| 6806 | assert!( |
| 6807 | hints.iter().any(|hint| hint.name == "/assistant"), |
| 6808 | "the user command must appear for the claimed token" |
| 6809 | ); |
| 6810 | } |
| 6811 | |
| 6812 | #[test] |
| 6813 | fn slash_completion_hints_prefer_user_metadata_for_shadowed_builtin() { |
| 6814 | let tmp = tempfile::TempDir::new().unwrap(); |
| 6815 | let commands_dir = tmp.path().join(".codewhale").join("commands"); |
| 6816 | crate::test_support::trust_workspace(tmp.path()); |
| 6817 | std::fs::create_dir_all(&commands_dir).unwrap(); |
| 6818 | std::fs::write( |
| 6819 | commands_dir.join("help.md"), |
| 6820 | "---\ndescription: Custom help workflow\nargument-hint: <topic>\n---\nhelp", |
| 6821 | ) |
| 6822 | .unwrap(); |
| 6823 | |
| 6824 | let hints = slash_completion_hints( |
| 6825 | "/help", |
| 6826 | 128, |
| 6827 | &[], |
| 6828 | Locale::En, |
| 6829 | Some(tmp.path()), |
| 6830 | ProviderKind::Deepseek, |
| 6831 | ); |
| 6832 | let help_entries: Vec<_> = hints.iter().filter(|hint| hint.name == "/help").collect(); |
| 6833 | |
| 6834 | assert_eq!(help_entries.len(), 1); |
| 6835 | assert_eq!(help_entries[0].description, "Custom help workflow <topic>"); |
| 6836 | } |
| 6837 | |
| 6838 | #[test] |
| 6839 | fn review_regression_push_command_entry_uses_preloaded_user_command_frontmatter() { |
| 6840 | let registry = crate::commands::user_registry::UserCommandRegistry::from_loaded(vec![( |
| 6841 | "deploy".to_string(), |
| 6842 | "---\ndescription: Deploy target\nargument-hint: <env>\n---\ndeploy".to_string(), |
| 6843 | )]); |
| 6844 | let user_commands: Vec<_> = registry.iter().collect(); |
| 6845 | let mut entries = Vec::new(); |
| 6846 | |
| 6847 | push_command_entry( |
| 6848 | &mut entries, |
| 6849 | "/deploy", |
| 6850 | "deploy", |
| 6851 | "deploy", |
| 6852 | Locale::En, |
| 6853 | &user_commands, |
| 6854 | ); |
| 6855 | |
| 6856 | assert_eq!(entries.len(), 1); |
| 6857 | assert_eq!(entries[0].name, "/deploy"); |
| 6858 | assert_eq!(entries[0].description, "Deploy target <env>"); |
| 6859 | } |
| 6860 | |
| 6861 | #[test] |
| 6862 | fn slash_completion_hints_hide_skills_from_top_level_menu() { |
| 6863 | let cached_skills = vec![ |
| 6864 | ("search-files".to_string(), "Search files".to_string()), |
| 6865 | ("my-review".to_string(), "Review code".to_string()), |
| 6866 | ]; |
| 6867 | let hints = slash_completion_hints( |
| 6868 | "/", |
| 6869 | 128, |
| 6870 | &cached_skills, |
| 6871 | Locale::En, |
| 6872 | None, |
| 6873 | ProviderKind::Deepseek, |
| 6874 | ); |
| 6875 | // Individual skills stay out of the root: they are user content with |
| 6876 | // their own triggers (`$name`, `/skill`) and there can be hundreds. |
| 6877 | assert!(!hints.iter().any(|hint| hint.is_skill)); |
| 6878 | // The commands that reach them are commands like any other, and a |
| 6879 | // bare slash must be able to find every command. |
| 6880 | assert!(hints.iter().any(|hint| hint.name == "/skill")); |
| 6881 | } |
| 6882 | |
| 6883 | #[test] |
| 6884 | fn slash_completion_hints_hide_skills_from_top_level_prefix() { |
| 6885 | let cached_skills = vec![ |
| 6886 | ("search-files".to_string(), "Search files".to_string()), |
| 6887 | ("my-review".to_string(), "Review code".to_string()), |
| 6888 | ]; |
| 6889 | let hints = slash_completion_hints( |
| 6890 | "/se", |
| 6891 | 128, |
| 6892 | &cached_skills, |
| 6893 | Locale::En, |
| 6894 | None, |
| 6895 | ProviderKind::Deepseek, |
| 6896 | ); |
| 6897 | assert!(!hints.iter().any(|hint| hint.name == "/skill search-files")); |
| 6898 | assert!(!hints.iter().any(|hint| hint.name == "/skill my-review")); |
| 6899 | } |
| 6900 | |
| 6901 | #[test] |
| 6902 | fn slash_completion_hints_complete_skill_argument_all() { |
| 6903 | let cached_skills = vec![ |
| 6904 | ("search-files".to_string(), "Search files".to_string()), |
| 6905 | ("my-review".to_string(), "Review code".to_string()), |
| 6906 | ]; |
| 6907 | let hints = slash_completion_hints( |
| 6908 | "/skill ", |
| 6909 | 128, |
| 6910 | &cached_skills, |
| 6911 | Locale::En, |
| 6912 | None, |
| 6913 | ProviderKind::Deepseek, |
| 6914 | ); |
| 6915 | assert_eq!(hints.len(), 2); |
| 6916 | assert!(hints.iter().any(|hint| hint.name == "/skill search-files")); |
| 6917 | assert!(hints.iter().any(|hint| hint.name == "/skill my-review")); |
| 6918 | assert!(hints.iter().all(|hint| hint.is_skill)); |
| 6919 | } |
| 6920 | |
| 6921 | #[test] |
| 6922 | fn slash_completion_hints_complete_skill_argument_prefix() { |
| 6923 | let cached_skills = vec![ |
| 6924 | ("search-files".to_string(), "Search files".to_string()), |
| 6925 | ("my-review".to_string(), "Review code".to_string()), |
| 6926 | ]; |
| 6927 | let hints = slash_completion_hints( |
| 6928 | "/skill my", |
| 6929 | 128, |
| 6930 | &cached_skills, |
| 6931 | Locale::En, |
| 6932 | None, |
| 6933 | ProviderKind::Deepseek, |
| 6934 | ); |
| 6935 | assert_eq!(hints.len(), 1); |
| 6936 | assert_eq!(hints[0].name, "/skill my-review"); |
| 6937 | assert!(hints[0].is_skill); |
| 6938 | } |
| 6939 | |
| 6940 | #[test] |
| 6941 | fn slash_completion_hints_model_deepseek_provider_uses_bare_ids() { |
| 6942 | let hints = |
| 6943 | slash_completion_hints("/model", 128, &[], Locale::En, None, ProviderKind::Deepseek); |
| 6944 | let names = hints |
| 6945 | .iter() |
| 6946 | .map(|hint| hint.name.as_str()) |
| 6947 | .collect::<Vec<_>>(); |
| 6948 | |
| 6949 | assert!(names.contains(&"/model deepseek-v4-pro")); |
| 6950 | assert!(names.contains(&"/model deepseek-v4-flash")); |
| 6951 | assert!(!names.contains(&"/model deepseek-ai/deepseek-v4-pro")); |
| 6952 | assert!(!names.contains(&"/model deepseek/deepseek-v4-pro")); |
| 6953 | } |
| 6954 | |
| 6955 | #[test] |
| 6956 | fn slash_completion_hints_model_provider_uses_provider_specific_ids() { |
| 6957 | let hints = slash_completion_hints( |
| 6958 | "/model", |
| 6959 | 128, |
| 6960 | &[], |
| 6961 | Locale::En, |
| 6962 | None, |
| 6963 | ProviderKind::NvidiaNim, |
| 6964 | ); |
| 6965 | let names = hints |
| 6966 | .iter() |
| 6967 | .map(|hint| hint.name.as_str()) |
| 6968 | .collect::<Vec<_>>(); |
| 6969 | |
| 6970 | assert!(names.contains(&"/model deepseek-ai/deepseek-v4-pro")); |
| 6971 | assert!(!names.contains(&"/model deepseek/deepseek-v4-pro")); |
| 6972 | } |
| 6973 | |
| 6974 | #[test] |
| 6975 | fn slash_completion_hints_model_ollama_has_no_static_remote_models() { |
| 6976 | let hints = |
| 6977 | slash_completion_hints("/model", 128, &[], Locale::En, None, ProviderKind::Ollama); |
| 6978 | let names = hints |
| 6979 | .iter() |
| 6980 | .map(|hint| hint.name.as_str()) |
| 6981 | .collect::<Vec<_>>(); |
| 6982 | |
| 6983 | assert!(names.contains(&"/model")); |
| 6984 | assert!(!names.contains(&"/model deepseek-v4-pro")); |
| 6985 | assert!(!names.contains(&"/model deepseek-v4-flash")); |
| 6986 | assert!(!names.contains(&"/model deepseek-coder:1.3b")); |
| 6987 | } |
| 6988 | |
| 6989 | #[test] |
| 6990 | fn truncated_slash_row_registers_its_full_localized_copy_for_hover() { |
| 6991 | let mut app = create_test_app(); |
| 6992 | app.input = "/model".to_string(); |
| 6993 | app.cursor_position = app.input.len(); |
| 6994 | let full_name = "/model provider/very-long-model-identifier"; |
| 6995 | let full_description = "切换到这个模型并保留完整的本地化说明"; |
| 6996 | let entries = vec![SlashMenuEntry { |
| 6997 | name: full_name.to_string(), |
| 6998 | description: full_description.to_string(), |
| 6999 | is_skill: false, |
| 7000 | alias_hint: None, |
| 7001 | }]; |
| 7002 | let area = Rect::new(0, 0, 36, 7); |
| 7003 | let mut buf = Buffer::empty(area); |
| 7004 | |
| 7005 | crate::tui::hover_layer::begin_frame(); |
| 7006 | ComposerWidget::new(&app, area.height, &entries, &[]).render(area, &mut buf); |
| 7007 | |
| 7008 | let targets = crate::tui::hover_layer::registered_targets(); |
| 7009 | assert_eq!(targets.len(), 1, "targets: {targets:?}"); |
| 7010 | assert_eq!( |
| 7011 | targets[0].kind, |
| 7012 | crate::tui::hover_hit::HoverTargetKind::TruncatedText |
| 7013 | ); |
| 7014 | assert!(targets[0].label.contains(full_name)); |
| 7015 | assert!(targets[0].label.contains(full_description)); |
| 7016 | } |
| 7017 | |
| 7018 | #[test] |
| 7019 | fn complete_slash_row_does_not_register_a_hover_popover() { |
| 7020 | let mut app = create_test_app(); |
| 7021 | app.input = "/help".to_string(); |
| 7022 | app.cursor_position = app.input.len(); |
| 7023 | let entries = vec![SlashMenuEntry { |
| 7024 | name: "/help".to_string(), |
| 7025 | description: "Show help".to_string(), |
| 7026 | is_skill: false, |
| 7027 | alias_hint: None, |
| 7028 | }]; |
| 7029 | let area = Rect::new(0, 0, 80, 7); |
| 7030 | let mut buf = Buffer::empty(area); |
| 7031 | |
| 7032 | crate::tui::hover_layer::begin_frame(); |
| 7033 | ComposerWidget::new(&app, area.height, &entries, &[]).render(area, &mut buf); |
| 7034 | |
| 7035 | assert!(crate::tui::hover_layer::registered_targets().is_empty()); |
| 7036 | } |
| 7037 | |
| 7038 | #[test] |
| 7039 | fn selection_style_uses_explicit_selection_text_role() { |
| 7040 | let line = Line::from(Span::styled( |
| 7041 | "hello world", |
| 7042 | Style::default().fg(palette::TEXT_PRIMARY), |
| 7043 | )); |
| 7044 | let selection_style = Style::default() |
| 7045 | .bg(palette::SELECTION_BG) |
| 7046 | .fg(palette::SELECTION_TEXT); |
| 7047 | |
| 7048 | let styled = apply_selection_to_line(&line, 0, 5, selection_style); |
| 7049 | assert_eq!(styled.len(), 2); |
| 7050 | assert_eq!(styled[0].content.as_ref(), "hello"); |
| 7051 | assert_eq!(styled[0].style.fg, Some(palette::SELECTION_TEXT)); |
| 7052 | assert_eq!(styled[0].style.bg, Some(palette::SELECTION_BG)); |
| 7053 | assert_eq!(styled[1].content.as_ref(), " world"); |
| 7054 | } |
| 7055 | |
| 7056 | #[test] |
| 7057 | fn selection_keeps_keycap_grapheme_intact() { |
| 7058 | let line = Line::from(Span::raw("A1\u{fe0f}\u{20e3}B")); |
| 7059 | let selection_style = Style::default().bg(palette::SELECTION_BG); |
| 7060 | |
| 7061 | // Selecting the second display column of the two-column keycap must |
| 7062 | // style the complete grapheme, never only FE0F/U+20E3. |
| 7063 | let styled = apply_selection_to_line(&line, 2, 3, selection_style); |
| 7064 | assert_eq!(styled.len(), 3); |
| 7065 | assert_eq!(styled[0].content.as_ref(), "A"); |
| 7066 | assert_eq!(styled[1].content.as_ref(), "1\u{fe0f}\u{20e3}"); |
| 7067 | assert_eq!(styled[1].style.bg, Some(palette::SELECTION_BG)); |
| 7068 | assert_eq!(styled[2].content.as_ref(), "B"); |
| 7069 | } |
| 7070 | |
| 7071 | #[test] |
| 7072 | fn composer_layout_helpers_stay_consistent() { |
| 7073 | let input = "line one wraps nicely\nline two wraps as well"; |
| 7074 | let width = 16; |
| 7075 | let available_height = 6; |
| 7076 | let menu_lines = 2; |
| 7077 | |
| 7078 | let height = composer_height( |
| 7079 | input, |
| 7080 | width, |
| 7081 | available_height, |
| 7082 | menu_lines, |
| 7083 | ComposerDensity::Comfortable, |
| 7084 | true, |
| 7085 | ); |
| 7086 | let has_panel = enclosed_composer_panel_fits(true, width, available_height); |
| 7087 | let chrome_height = if has_panel { |
| 7088 | usize::from(COMPOSER_PANEL_HEIGHT) |
| 7089 | } else { |
| 7090 | 1 |
| 7091 | }; |
| 7092 | let measurement_area = Rect::new(0, 0, width, if has_panel { 3 } else { 1 }); |
| 7093 | let content_width = |
| 7094 | composer_content_geometry(composer_inner_area(measurement_area, has_panel), false) |
| 7095 | .text_width(); |
| 7096 | let input_height_budget = usize::from(height) |
| 7097 | .saturating_sub(menu_lines) |
| 7098 | .saturating_sub(chrome_height) |
| 7099 | .max(1); |
| 7100 | let (visible, cursor_row, cursor_col) = layout_input( |
| 7101 | input, |
| 7102 | input.chars().count(), |
| 7103 | content_width, |
| 7104 | input_height_budget, |
| 7105 | ); |
| 7106 | |
| 7107 | assert!(visible.len().saturating_add(menu_lines) <= usize::from(height)); |
| 7108 | assert!(!visible.is_empty()); |
| 7109 | assert!(cursor_row < visible.len()); |
| 7110 | assert!(cursor_col < content_width.max(1)); |
| 7111 | assert!(height >= 5); |
| 7112 | } |
| 7113 | |
| 7114 | #[test] |
| 7115 | fn composer_height_prefers_panel_shape_when_space_allows() { |
| 7116 | let height = composer_height("", 40, 8, 0, ComposerDensity::Comfortable, true); |
| 7117 | assert_eq!(height, 4); |
| 7118 | } |
| 7119 | |
| 7120 | #[test] |
| 7121 | fn composer_panel_height_and_render_policy_agree_at_width_boundary() { |
| 7122 | let mut app = create_test_app(); |
| 7123 | app.composer_border = true; |
| 7124 | app.composer_density = ComposerDensity::Comfortable; |
| 7125 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7126 | let mention_menu_entries = Vec::<String>::new(); |
| 7127 | let widget = ComposerWidget::new(&app, 8, &slash_menu_entries, &mention_menu_entries); |
| 7128 | |
| 7129 | for (width, expected_panel, expected_height) in |
| 7130 | [(11, false, 3), (12, true, 4), (13, true, 4), (14, true, 4)] |
| 7131 | { |
| 7132 | let height = widget.desired_height(width); |
| 7133 | let area = Rect::new(0, 0, width, height); |
| 7134 | |
| 7135 | assert_eq!(height, expected_height, "width={width}"); |
| 7136 | assert_eq!(widget.has_panel(area), expected_panel, "width={width}"); |
| 7137 | assert_eq!( |
| 7138 | widget.inner_area(area).height, |
| 7139 | 2, |
| 7140 | "width={width} comfortable composer reserves two input rows plus \ |
| 7141 | every rendered border row" |
| 7142 | ); |
| 7143 | |
| 7144 | let mut buf = Buffer::empty(area); |
| 7145 | widget.render(area, &mut buf); |
| 7146 | assert_eq!( |
| 7147 | buf[(1, area.bottom().saturating_sub(1))].symbol() == "\u{2500}", |
| 7148 | expected_panel, |
| 7149 | "width={width} bottom border disagrees with height policy" |
| 7150 | ); |
| 7151 | if expected_panel { |
| 7152 | assert_eq!( |
| 7153 | widget.inner_area(area), |
| 7154 | Rect::new(1, 1, area.width.saturating_sub(7), 2), |
| 7155 | "width={width} panel input area must reserve the send control and breathing cell" |
| 7156 | ); |
| 7157 | assert_eq!(buf[(area.left(), area.top())].symbol(), "\u{256d}"); |
| 7158 | assert_eq!( |
| 7159 | buf[(area.right().saturating_sub(1), area.top())].symbol(), |
| 7160 | "\u{256e}" |
| 7161 | ); |
| 7162 | assert_eq!( |
| 7163 | buf[(area.left(), area.bottom().saturating_sub(1))].symbol(), |
| 7164 | "\u{2570}" |
| 7165 | ); |
| 7166 | assert_eq!( |
| 7167 | buf[( |
| 7168 | area.right().saturating_sub(1), |
| 7169 | area.bottom().saturating_sub(1) |
| 7170 | )] |
| 7171 | .symbol(), |
| 7172 | "\u{256f}" |
| 7173 | ); |
| 7174 | assert_eq!( |
| 7175 | buf[(area.left(), area.y.saturating_add(1))].symbol(), |
| 7176 | "\u{2502}" |
| 7177 | ); |
| 7178 | assert_eq!( |
| 7179 | buf[(area.right().saturating_sub(1), area.y.saturating_add(1))].symbol(), |
| 7180 | "\u{2502}" |
| 7181 | ); |
| 7182 | } else { |
| 7183 | assert_eq!( |
| 7184 | widget.inner_area(area), |
| 7185 | Rect::new(area.x, area.y.saturating_add(1), area.width, 2), |
| 7186 | "width={width} compact fallback must keep its full input width" |
| 7187 | ); |
| 7188 | assert_ne!(buf[(area.left(), area.top())].symbol(), "\u{256d}"); |
| 7189 | } |
| 7190 | } |
| 7191 | } |
| 7192 | |
| 7193 | #[test] |
| 7194 | fn composer_height_wraps_to_the_rounded_panel_content_width() { |
| 7195 | // At the minimum viable panel width, the side rails, prompt gutter, |
| 7196 | // shared `[↵]` control, and its breathing cell leave three text |
| 7197 | // columns. Measuring against the old width would render extra lines |
| 7198 | // without allocating their rows. |
| 7199 | let height = composer_height( |
| 7200 | "123456789", |
| 7201 | super::COMPOSER_PANEL_MIN_WIDTH, |
| 7202 | 8, |
| 7203 | 0, |
| 7204 | ComposerDensity::Comfortable, |
| 7205 | true, |
| 7206 | ); |
| 7207 | assert_eq!(height, 6); |
| 7208 | } |
| 7209 | |
| 7210 | #[test] |
| 7211 | fn composer_expands_for_multiline_input_and_collapses_again() { |
| 7212 | let height_for = |
| 7213 | |input| composer_height(input, 40, 12, 0, ComposerDensity::Comfortable, true); |
| 7214 | |
| 7215 | let collapsed = height_for("short"); |
| 7216 | let expanded = height_for("one\ntwo\nthree\nfour\nfive\nsix"); |
| 7217 | let collapsed_again = height_for("short"); |
| 7218 | |
| 7219 | // Comfortable: two input rows + top/bottom panel borders. |
| 7220 | assert_eq!(collapsed, 4); |
| 7221 | // Six content rows + two borders, still under the Comfortable cap of 9. |
| 7222 | assert_eq!(expanded, 8); |
| 7223 | assert!(expanded > collapsed); |
| 7224 | assert_eq!(collapsed_again, collapsed); |
| 7225 | } |
| 7226 | |
| 7227 | /// Issue #4809 acceptance: the composer auto-fits its content through the |
| 7228 | /// real widget path — typed input, `submit_input`, `clear_input` — not just |
| 7229 | /// through the pure height helper. |
| 7230 | #[test] |
| 7231 | fn composer_auto_fits_typed_lines_and_returns_to_density_floor_on_submit_or_clear() { |
| 7232 | const WIDTH: u16 = 40; |
| 7233 | const AVAILABLE: u16 = 24; |
| 7234 | |
| 7235 | fn measure(app: &App) -> (u16, u16) { |
| 7236 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7237 | let mention_menu_entries = Vec::<String>::new(); |
| 7238 | let widget = |
| 7239 | ComposerWidget::new(app, AVAILABLE, &slash_menu_entries, &mention_menu_entries); |
| 7240 | let total = widget.desired_height(WIDTH); |
| 7241 | let inner = widget.inner_area(Rect::new(0, 0, WIDTH, total)).height; |
| 7242 | (total, inner) |
| 7243 | } |
| 7244 | |
| 7245 | let mut app = create_test_app(); |
| 7246 | app.composer_border = true; |
| 7247 | app.composer_density = ComposerDensity::Comfortable; |
| 7248 | |
| 7249 | // Empty composer: one input row and one quiet row inside the borders. |
| 7250 | assert_eq!(measure(&app), (4, 2), "empty composer"); |
| 7251 | |
| 7252 | app.insert_str("one line"); |
| 7253 | assert_eq!(measure(&app), (4, 2), "single-line composer"); |
| 7254 | |
| 7255 | // Typing N lines grows the composer to N input rows while N is under |
| 7256 | // the Comfortable cap of 9 total rows (7 input rows + 2 borders). |
| 7257 | for n in 2..=7u16 { |
| 7258 | app.clear_input(); |
| 7259 | let text = (1..=n) |
| 7260 | .map(|i| format!("line {i}")) |
| 7261 | .collect::<Vec<_>>() |
| 7262 | .join("\n"); |
| 7263 | app.insert_str(&text); |
| 7264 | assert_eq!(measure(&app), (n + 2, n), "{n} typed lines"); |
| 7265 | } |
| 7266 | |
| 7267 | app.clear_input(); |
| 7268 | app.insert_str(&vec!["over"; 40].join("\n")); |
| 7269 | assert_eq!( |
| 7270 | measure(&app), |
| 7271 | (AVAILABLE, AVAILABLE - 2), |
| 7272 | "content beyond the cap" |
| 7273 | ); |
| 7274 | |
| 7275 | // Submitting returns the composer to its stable density floor. |
| 7276 | assert!(app.submit_input().is_some()); |
| 7277 | assert_eq!(measure(&app), (4, 2), "after submit"); |
| 7278 | |
| 7279 | // So does clearing a fresh multi-line draft. |
| 7280 | app.insert_str("a\nb\nc\nd"); |
| 7281 | assert_eq!(measure(&app), (6, 4), "four-line draft"); |
| 7282 | app.clear_input(); |
| 7283 | assert_eq!(measure(&app), (4, 2), "after clear"); |
| 7284 | } |
| 7285 | |
| 7286 | #[test] |
| 7287 | fn composer_height_uses_quiet_rule_when_panel_is_not_needed() { |
| 7288 | let with_border = composer_height("", 40, 8, 0, ComposerDensity::Comfortable, true); |
| 7289 | let without_border = composer_height("", 40, 8, 0, ComposerDensity::Comfortable, false); |
| 7290 | |
| 7291 | // Quiet composer keeps a single top rule over the comfortable |
| 7292 | // input floor; the panel shape adds its bottom border. |
| 7293 | assert_eq!(with_border, 4); |
| 7294 | assert_eq!(without_border, 3); |
| 7295 | assert!(without_border < with_border); |
| 7296 | } |
| 7297 | |
| 7298 | #[test] |
| 7299 | fn composer_density_changes_height_cap() { |
| 7300 | assert!( |
| 7301 | composer_max_height(ComposerDensity::Spacious) |
| 7302 | > composer_max_height(ComposerDensity::Compact) |
| 7303 | ); |
| 7304 | } |
| 7305 | |
| 7306 | #[test] |
| 7307 | fn composer_content_geometry_is_the_single_prompt_adjusted_text_rect() { |
| 7308 | let inner = Rect::new(10, 4, 7, 3); |
| 7309 | let normal = composer_content_geometry(inner, false); |
| 7310 | assert_eq!(normal.prompt_inset, 2); |
| 7311 | assert_eq!(normal.text_area, Rect::new(12, 4, 5, 3)); |
| 7312 | assert_eq!(normal.text_width(), 5); |
| 7313 | |
| 7314 | let history = composer_content_geometry(inner, true); |
| 7315 | assert_eq!(history.prompt_inset, 0); |
| 7316 | assert_eq!(history.text_area, inner); |
| 7317 | |
| 7318 | let narrow = composer_content_geometry(Rect::new(3, 2, 2, 1), false); |
| 7319 | assert_eq!(narrow.prompt_inset, 0); |
| 7320 | assert_eq!(narrow.text_area, Rect::new(3, 2, 2, 1)); |
| 7321 | } |
| 7322 | |
| 7323 | #[test] |
| 7324 | fn composer_wrap_boundary_cursor_scroll_and_mouse_lines_share_text_width() { |
| 7325 | let geometry = composer_content_geometry(Rect::new(0, 0, 7, 2), false); |
| 7326 | let input = "abcde"; |
| 7327 | let cursor = input.chars().count(); |
| 7328 | let width = geometry.text_width(); |
| 7329 | |
| 7330 | let (absolute_row, absolute_col) = cursor_row_col(input, cursor, width); |
| 7331 | let (visible, visible_row, visible_col, scroll_offset) = |
| 7332 | layout_input_with_scroll(input, cursor, width, 1); |
| 7333 | let mouse_lines = wrap_input_lines_for_mouse(input, width); |
| 7334 | |
| 7335 | assert_eq!((absolute_row, absolute_col), (1, 0)); |
| 7336 | assert_eq!(scroll_offset, 1); |
| 7337 | assert_eq!((visible_row, visible_col), (0, 0)); |
| 7338 | assert_eq!(visible, vec![String::new()]); |
| 7339 | assert_eq!(mouse_lines[scroll_offset], (cursor, String::new())); |
| 7340 | } |
| 7341 | |
| 7342 | #[test] |
| 7343 | fn empty_composer_keeps_prompt_and_hint_on_one_row() { |
| 7344 | let mut app = create_test_app(); |
| 7345 | // Pin density so the test is independent of any loaded user settings. |
| 7346 | app.composer_density = ComposerDensity::Comfortable; |
| 7347 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7348 | let mention_menu_entries = Vec::<String>::new(); |
| 7349 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7350 | |
| 7351 | // Use a wide area so the placeholder fits on one line (no wrapping). |
| 7352 | let area = Rect { |
| 7353 | x: 0, |
| 7354 | y: 0, |
| 7355 | width: 40, |
| 7356 | height: 5, |
| 7357 | }; |
| 7358 | |
| 7359 | // The two border rows carry independent permission/mode signals. |
| 7360 | // inner_area: {x:1, y:1, w:38, h:3} |
| 7361 | // input_rows_budget = 3 |
| 7362 | // The prompt and hint share one quiet row. |
| 7363 | assert_eq!( |
| 7364 | empty_composer_visual_rows(Some(COMPOSER_PLACEHOLDER), 40, 3), |
| 7365 | 1 |
| 7366 | ); |
| 7367 | assert_eq!(widget.cursor_pos(area), Some((3, 2))); |
| 7368 | } |
| 7369 | |
| 7370 | #[test] |
| 7371 | fn empty_composer_cursor_accounts_for_wrapped_placeholder_hint() { |
| 7372 | let mut app = create_test_app(); |
| 7373 | app.composer_density = ComposerDensity::Comfortable; |
| 7374 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7375 | let mention_menu_entries = Vec::<String>::new(); |
| 7376 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7377 | |
| 7378 | // Narrow area forces the placeholder to wrap. |
| 7379 | let area = Rect { |
| 7380 | x: 0, |
| 7381 | y: 0, |
| 7382 | width: 14, |
| 7383 | height: 5, |
| 7384 | }; |
| 7385 | |
| 7386 | // inner_area: {x:1, y:1, w:12, h:3} |
| 7387 | // input_rows_budget = 3 |
| 7388 | // placeholder_visual_lines(12) = 3 |
| 7389 | // The narrow fallback still reserves one composer row; Paragraph |
| 7390 | // clipping keeps it from growing the shell. |
| 7391 | assert_eq!(placeholder_visual_lines(12), 3); |
| 7392 | assert_eq!( |
| 7393 | empty_composer_visual_rows(Some(COMPOSER_PLACEHOLDER), 14, 3), |
| 7394 | 1 |
| 7395 | ); |
| 7396 | assert_eq!(widget.cursor_pos(area), Some((3, 2))); |
| 7397 | } |
| 7398 | |
| 7399 | #[test] |
| 7400 | fn empty_composer_renders_prompt_and_hint_on_cursor_row() { |
| 7401 | let mut app = create_test_app(); |
| 7402 | app.composer_density = ComposerDensity::Comfortable; |
| 7403 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7404 | let mention_menu_entries = Vec::<String>::new(); |
| 7405 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7406 | let area = Rect { |
| 7407 | x: 0, |
| 7408 | y: 0, |
| 7409 | width: 40, |
| 7410 | height: 5, |
| 7411 | }; |
| 7412 | let mut buf = Buffer::empty(area); |
| 7413 | |
| 7414 | widget.render(area, &mut buf); |
| 7415 | let Some((cursor_x, cursor_y)) = widget.cursor_pos(area) else { |
| 7416 | panic!("empty composer should expose cursor position"); |
| 7417 | }; |
| 7418 | let rendered = buffer_text(&buf, area); |
| 7419 | let placeholder = composer_empty_hint_text(&app).into_owned(); |
| 7420 | let first_placeholder_cell = placeholder |
| 7421 | .chars() |
| 7422 | .next() |
| 7423 | .expect("composer placeholder should not be empty") |
| 7424 | .to_string(); |
| 7425 | |
| 7426 | assert_eq!(buf[(cursor_x, cursor_y)].symbol(), first_placeholder_cell); |
| 7427 | assert_eq!( |
| 7428 | buf[(cursor_x, cursor_y)].fg, |
| 7429 | app.ui_theme.text_body, |
| 7430 | "the idle prompt should use the body-text role" |
| 7431 | ); |
| 7432 | assert!( |
| 7433 | !buf[(cursor_x, cursor_y)] |
| 7434 | .modifier |
| 7435 | .contains(Modifier::ITALIC), |
| 7436 | "the idle prompt should remain upright at distance" |
| 7437 | ); |
| 7438 | assert!( |
| 7439 | rendered.contains(&placeholder), |
| 7440 | "placeholder hint should render on the prompt row: {rendered}" |
| 7441 | ); |
| 7442 | assert!( |
| 7443 | row_text(&buf, area, cursor_y).contains(&placeholder), |
| 7444 | "prompt and hint should share one row: {rendered}" |
| 7445 | ); |
| 7446 | let inner = widget.inner_area(area); |
| 7447 | let quiet_row = cursor_y.saturating_add(1); |
| 7448 | assert!(active_composer_submit_rect(&app, area).is_none()); |
| 7449 | assert!( |
| 7450 | quiet_row < inner.bottom() |
| 7451 | && (inner.left()..area.right() - 1).all(|x| buf[(x, quiet_row)].symbol() == " "), |
| 7452 | "unavailable Send leaves the row blank: {rendered}" |
| 7453 | ); |
| 7454 | } |
| 7455 | |
| 7456 | #[test] |
| 7457 | fn composer_keeps_prompt_anchored_after_first_keystroke() { |
| 7458 | let mut app = create_test_app(); |
| 7459 | app.composer_density = ComposerDensity::Comfortable; |
| 7460 | app.input = "hello".to_string(); |
| 7461 | app.cursor_position = app.input.len(); |
| 7462 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7463 | let mention_menu_entries = Vec::<String>::new(); |
| 7464 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7465 | let area = Rect::new(0, 0, 40, 5); |
| 7466 | let mut buf = Buffer::empty(area); |
| 7467 | |
| 7468 | widget.render(area, &mut buf); |
| 7469 | let (cursor_x, cursor_y) = widget |
| 7470 | .cursor_pos(area) |
| 7471 | .expect("composer with input should expose a cursor"); |
| 7472 | |
| 7473 | assert_eq!(buf[(1, cursor_y)].symbol(), "❯"); |
| 7474 | assert_eq!(buf[(3, cursor_y)].symbol(), "h"); |
| 7475 | assert_eq!(cursor_x, 8, "cursor keeps the prompt gutter reserved"); |
| 7476 | } |
| 7477 | |
| 7478 | fn render_composer(app: &App, width: u16, height: u16) -> String { |
| 7479 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7480 | let mention_menu_entries = Vec::<String>::new(); |
| 7481 | let widget = ComposerWidget::new(app, height, &slash_menu_entries, &mention_menu_entries); |
| 7482 | let area = Rect::new(0, 0, width, height); |
| 7483 | let mut buf = Buffer::empty(area); |
| 7484 | widget.render(area, &mut buf); |
| 7485 | buffer_text(&buf, area) |
| 7486 | } |
| 7487 | |
| 7488 | #[test] |
| 7489 | fn composer_empty_hint_names_a_follow_up_while_a_turn_is_running() { |
| 7490 | let mut app = create_test_app(); |
| 7491 | assert_eq!( |
| 7492 | composer_empty_hint_text(&app).as_ref(), |
| 7493 | "Describe a task or type /" |
| 7494 | ); |
| 7495 | |
| 7496 | app.is_loading = true; |
| 7497 | assert_eq!(composer_empty_hint_text(&app).as_ref(), "Type a follow-up…"); |
| 7498 | |
| 7499 | app.queue_message(QueuedMessage::new("later".to_string(), None)); |
| 7500 | assert_eq!( |
| 7501 | composer_empty_hint_text(&app).as_ref(), |
| 7502 | "Enter send now · type another" |
| 7503 | ); |
| 7504 | |
| 7505 | app.is_loading = false; |
| 7506 | assert_eq!( |
| 7507 | composer_empty_hint_text(&app).as_ref(), |
| 7508 | "Enter send now · type another" |
| 7509 | ); |
| 7510 | } |
| 7511 | |
| 7512 | #[test] |
| 7513 | fn composer_submit_hint_names_send_after_this_turn_without_steer() { |
| 7514 | let mut app = create_test_app(); |
| 7515 | app.input = "keep going".to_string(); |
| 7516 | app.cursor_position = app.input.chars().count(); |
| 7517 | assert!(composer_submit_hint(&app, false).is_none()); |
| 7518 | |
| 7519 | app.is_loading = true; |
| 7520 | let hint = composer_submit_hint(&app, false).expect("busy draft should name Enter"); |
| 7521 | assert_eq!(hint.text, "↵ send after this turn"); |
| 7522 | assert!( |
| 7523 | !hint.text.to_ascii_lowercase().contains("steer"), |
| 7524 | "composer hint leaked internal vocabulary: {}", |
| 7525 | hint.text |
| 7526 | ); |
| 7527 | |
| 7528 | app.queue_message(QueuedMessage::new("first".to_string(), None)); |
| 7529 | let hint = composer_submit_hint(&app, false).expect("queued count should stay visible"); |
| 7530 | assert_eq!(hint.text, "↵ send after this turn (2 waiting)"); |
| 7531 | } |
| 7532 | |
| 7533 | #[test] |
| 7534 | fn composer_submit_hint_renders_at_release_floor_widths() { |
| 7535 | let mut app = create_test_app(); |
| 7536 | app.composer_border = true; |
| 7537 | app.is_loading = true; |
| 7538 | app.input = "keep going".to_string(); |
| 7539 | app.cursor_position = app.input.chars().count(); |
| 7540 | |
| 7541 | for (width, height) in [(40_u16, 12), (60, 16), (80, 24), (100, 32), (140, 40)] { |
| 7542 | let rendered = render_composer(&app, width, height); |
| 7543 | assert!( |
| 7544 | rendered.contains("send after this turn"), |
| 7545 | "missing queue hint at {width}x{height}:\n{rendered}" |
| 7546 | ); |
| 7547 | assert!( |
| 7548 | !rendered.to_ascii_lowercase().contains("steer"), |
| 7549 | "steer vocabulary at {width}x{height}:\n{rendered}" |
| 7550 | ); |
| 7551 | } |
| 7552 | } |
| 7553 | |
| 7554 | #[test] |
| 7555 | fn quiet_composer_still_shows_the_submit_hint() { |
| 7556 | let mut app = create_test_app(); |
| 7557 | app.composer_border = false; |
| 7558 | app.is_loading = true; |
| 7559 | app.input = "keep going".to_string(); |
| 7560 | app.cursor_position = app.input.chars().count(); |
| 7561 | let rendered = render_composer(&app, 80, 4); |
| 7562 | assert!( |
| 7563 | rendered.contains("send after this turn"), |
| 7564 | "quiet composer hid the Enter action:\n{rendered}" |
| 7565 | ); |
| 7566 | } |
| 7567 | |
| 7568 | #[test] |
| 7569 | fn composer_border_omits_session_title_chrome() { |
| 7570 | // The top-right composer chrome (session title / receipts / vim mode) |
| 7571 | // was classic-shell-only; with the classic shell removed the composer |
| 7572 | // border never carries it. Session identity lives in the header. |
| 7573 | let mut app = create_test_app(); |
| 7574 | app.composer_density = ComposerDensity::Comfortable; |
| 7575 | app.session_title = Some("my-session".to_string()); |
| 7576 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7577 | let mention_menu_entries = Vec::<String>::new(); |
| 7578 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7579 | let area = Rect { |
| 7580 | x: 0, |
| 7581 | y: 0, |
| 7582 | width: 96, |
| 7583 | height: 5, |
| 7584 | }; |
| 7585 | let mut buf = Buffer::empty(area); |
| 7586 | |
| 7587 | widget.render(area, &mut buf); |
| 7588 | let rendered = buffer_text(&buf, area); |
| 7589 | |
| 7590 | assert!(!rendered.contains("Composer")); |
| 7591 | assert!(!rendered.contains("my-session")); |
| 7592 | } |
| 7593 | |
| 7594 | #[test] |
| 7595 | fn composer_border_omits_active_turn_receipt_chrome() { |
| 7596 | let mut app = create_test_app(); |
| 7597 | app.composer_density = ComposerDensity::Comfortable; |
| 7598 | app.set_receipt_text("✓ turn completed · 2 tool(s) used"); |
| 7599 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7600 | let mention_menu_entries = Vec::<String>::new(); |
| 7601 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7602 | let area = Rect { |
| 7603 | x: 0, |
| 7604 | y: 0, |
| 7605 | width: 96, |
| 7606 | height: 5, |
| 7607 | }; |
| 7608 | let mut buf = Buffer::empty(area); |
| 7609 | |
| 7610 | widget.render(area, &mut buf); |
| 7611 | let rendered = buffer_text(&buf, area); |
| 7612 | |
| 7613 | assert!(!rendered.contains("Composer")); |
| 7614 | assert!(!rendered.contains("turn completed")); |
| 7615 | assert!(!rendered.contains("tool(s) used")); |
| 7616 | } |
| 7617 | |
| 7618 | #[test] |
| 7619 | fn composer_prompt_tracks_focus_on_each_theme_surface() { |
| 7620 | let slash = Vec::<SlashMenuEntry>::new(); |
| 7621 | let mentions = Vec::<String>::new(); |
| 7622 | let area = Rect::new(0, 0, 40, 5); |
| 7623 | for theme_id in palette::SELECTABLE_THEMES { |
| 7624 | let mut app = create_test_app(); |
| 7625 | app.theme_id = *theme_id; |
| 7626 | app.ui_theme = theme_id.ui_theme(); |
| 7627 | app.launch.visible = true; |
| 7628 | for selected in [None, Some(0)] { |
| 7629 | app.launch.menu_selected = selected; |
| 7630 | let widget = ComposerWidget::new(&app, 5, &slash, &mentions); |
| 7631 | let mut buf = Buffer::empty(area); |
| 7632 | widget.render(area, &mut buf); |
| 7633 | let prompt = widget.plan(area).cursor.unwrap(); |
| 7634 | let expected = if selected.is_none() { |
| 7635 | app.ui_theme.accent_primary |
| 7636 | } else { |
| 7637 | app.ui_theme.text_muted |
| 7638 | }; |
| 7639 | assert_eq!( |
| 7640 | buf[(1, prompt.y)].fg, |
| 7641 | expected, |
| 7642 | "{} {selected:?}", |
| 7643 | theme_id.name() |
| 7644 | ); |
| 7645 | assert_eq!( |
| 7646 | buf[(1, prompt.y)].modifier.contains(Modifier::BOLD), |
| 7647 | selected.is_none() |
| 7648 | ); |
| 7649 | if app.theme_id == palette::ThemeId::Underwater { |
| 7650 | assert_eq!(buf[(1, 0)].symbol(), "▄"); |
| 7651 | assert_eq!(buf[(1, 4)].symbol(), "▀"); |
| 7652 | assert_eq!(buf[(1, 0)].bg, app.ui_theme.surface_bg); |
| 7653 | assert_eq!(buf[(1, 4)].fg, app.ui_theme.composer_bg); |
| 7654 | for x in [0, 39] { |
| 7655 | assert_eq!(buf[(x, 1)].symbol(), " "); |
| 7656 | assert_eq!(buf[(x, 1)].bg, app.ui_theme.composer_bg); |
| 7657 | } |
| 7658 | } else { |
| 7659 | for cell in [(1, 0), (1, 4), (0, 1), (39, 1)] { |
| 7660 | assert_eq!( |
| 7661 | buf[cell].fg, |
| 7662 | app.ui_theme.border, |
| 7663 | "{} {selected:?}", |
| 7664 | theme_id.name() |
| 7665 | ); |
| 7666 | } |
| 7667 | } |
| 7668 | } |
| 7669 | } |
| 7670 | } |
| 7671 | |
| 7672 | #[test] |
| 7673 | fn composer_border_keeps_mode_titles_contextual() { |
| 7674 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7675 | let mention_menu_entries = Vec::<String>::new(); |
| 7676 | let area = Rect { |
| 7677 | x: 0, |
| 7678 | y: 0, |
| 7679 | width: 96, |
| 7680 | height: 5, |
| 7681 | }; |
| 7682 | |
| 7683 | let mut normal_app = create_test_app(); |
| 7684 | normal_app.composer_density = ComposerDensity::Comfortable; |
| 7685 | let normal_widget = |
| 7686 | ComposerWidget::new(&normal_app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7687 | let mut normal_buf = Buffer::empty(area); |
| 7688 | normal_widget.render(area, &mut normal_buf); |
| 7689 | let normal_rendered = buffer_text(&normal_buf, area); |
| 7690 | assert!(!normal_rendered.contains("Composer")); |
| 7691 | assert!(!normal_rendered.contains("Draft")); |
| 7692 | assert!( |
| 7693 | !normal_rendered |
| 7694 | .contains(&*normal_app.tr(codewhale_localization::MessageId::HistorySearchTitle)) |
| 7695 | ); |
| 7696 | |
| 7697 | let mut draft_app = create_test_app(); |
| 7698 | draft_app.composer_density = ComposerDensity::Comfortable; |
| 7699 | draft_app.insert_str("first line\nsecond line"); |
| 7700 | let draft_widget = |
| 7701 | ComposerWidget::new(&draft_app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7702 | let mut draft_buf = Buffer::empty(area); |
| 7703 | draft_widget.render(area, &mut draft_buf); |
| 7704 | // Multi-line drafts no longer announce themselves with a block title; |
| 7705 | // the user can see the draft. Only history search keeps its title. |
| 7706 | assert!(!buffer_text(&draft_buf, area).contains("Draft")); |
| 7707 | |
| 7708 | let mut search_app = create_test_app(); |
| 7709 | search_app.composer_density = ComposerDensity::Comfortable; |
| 7710 | search_app.start_history_search(); |
| 7711 | let search_widget = |
| 7712 | ComposerWidget::new(&search_app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7713 | let mut search_buf = Buffer::empty(area); |
| 7714 | search_widget.render(area, &mut search_buf); |
| 7715 | assert!( |
| 7716 | buffer_text(&search_buf, area) |
| 7717 | .contains(&*search_app.tr(codewhale_localization::MessageId::HistorySearchTitle)) |
| 7718 | ); |
| 7719 | } |
| 7720 | |
| 7721 | #[test] |
| 7722 | fn enclosed_composer_paints_the_shared_send_hitbox() { |
| 7723 | let mut app = create_test_app(); |
| 7724 | app.composer_border = true; |
| 7725 | app.input = "ship it".to_string(); |
| 7726 | app.cursor_position = app.input.chars().count(); |
| 7727 | for (width, height) in [(40_u16, 12), (60, 16), (80, 24), (100, 32), (120, 32)] { |
| 7728 | let rendered = render_composer(&app, width, height); |
| 7729 | assert!( |
| 7730 | rendered.contains("[↵]"), |
| 7731 | "missing send affordance at {width}x{height}:\n{rendered}" |
| 7732 | ); |
| 7733 | assert!( |
| 7734 | !rendered.contains("▚△▞"), |
| 7735 | "retired crown must stay gone at {width}x{height}:\n{rendered}" |
| 7736 | ); |
| 7737 | } |
| 7738 | } |
| 7739 | |
| 7740 | #[test] |
| 7741 | fn composer_submit_ink_matches_real_submit_readiness() { |
| 7742 | let mut app = create_test_app(); |
| 7743 | app.composer_border = true; |
| 7744 | let slash = Vec::<SlashMenuEntry>::new(); |
| 7745 | let mentions = Vec::<String>::new(); |
| 7746 | let area = Rect::new(0, 0, 80, 8); |
| 7747 | for draft in ["", " ", "ship it"] { |
| 7748 | app.input = draft.to_string(); |
| 7749 | app.cursor_position = app.input.chars().count(); |
| 7750 | let widget = ComposerWidget::new(&app, 8, &slash, &mentions); |
| 7751 | let mut buf = Buffer::empty(area); |
| 7752 | widget.render(area, &mut buf); |
| 7753 | let ready = app.composer_draft_is_submittable(); |
| 7754 | let submit = widget.plan(area).geometry.submit.unwrap(); |
| 7755 | assert_eq!( |
| 7756 | active_composer_submit_rect(&app, area), |
| 7757 | ready.then_some(submit) |
| 7758 | ); |
| 7759 | let painted: String = (submit.x..submit.right()) |
| 7760 | .map(|x| buf[(x, submit.y)].symbol()) |
| 7761 | .collect(); |
| 7762 | assert_eq!(painted, if ready { "[↵]" } else { " " }); |
| 7763 | assert_eq!( |
| 7764 | buf[(submit.x, submit.y)].modifier.contains(Modifier::BOLD), |
| 7765 | ready |
| 7766 | ); |
| 7767 | if ready { |
| 7768 | assert_eq!( |
| 7769 | buf[(submit.x, submit.y)].fg, |
| 7770 | codewhale_palette::chrome_style( |
| 7771 | &app.ui_theme, |
| 7772 | codewhale_palette::ChromeInk::Info |
| 7773 | ) |
| 7774 | .fg |
| 7775 | .unwrap() |
| 7776 | ); |
| 7777 | } |
| 7778 | } |
| 7779 | app.input.clear(); |
| 7780 | app.queue_message(QueuedMessage::new("next".to_string(), None)); |
| 7781 | assert!(active_composer_submit_rect(&app, area).is_some()); |
| 7782 | assert!(render_composer(&app, area.width, area.height).contains("[↵]")); |
| 7783 | } |
| 7784 | |
| 7785 | #[test] |
| 7786 | fn enclosed_composer_send_hitbox_matches_painted_cells() { |
| 7787 | let mut app = create_test_app(); |
| 7788 | app.composer_border = true; |
| 7789 | app.input = "x".repeat(240); |
| 7790 | app.cursor_position = app.input.chars().count(); |
| 7791 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7792 | let mention_menu_entries = Vec::<String>::new(); |
| 7793 | let widget = ComposerWidget::new(&app, 8, &slash_menu_entries, &mention_menu_entries); |
| 7794 | let area = Rect::new(0, 0, 80, 8); |
| 7795 | let mut buf = Buffer::empty(area); |
| 7796 | widget.render(area, &mut buf); |
| 7797 | let submit = active_composer_submit_rect(&app, area).expect("enclosed composer submit"); |
| 7798 | let painted: String = (submit.x..submit.x + submit.width) |
| 7799 | .map(|x| buf[(x, submit.y)].symbol().to_string()) |
| 7800 | .collect(); |
| 7801 | assert_eq!(painted, "[↵]", "geometry must cover the painted send cells"); |
| 7802 | } |
| 7803 | |
| 7804 | #[test] |
| 7805 | fn enclosed_composer_reserves_submit_cells_for_a_74_character_draft() { |
| 7806 | let mut app = create_test_app(); |
| 7807 | app.composer_border = true; |
| 7808 | let draft = "x".repeat(74); |
| 7809 | app.input = draft.clone(); |
| 7810 | app.cursor_position = app.input.chars().count(); |
| 7811 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7812 | let mention_menu_entries = Vec::<String>::new(); |
| 7813 | let widget = ComposerWidget::new(&app, 8, &slash_menu_entries, &mention_menu_entries); |
| 7814 | let area = Rect::new(0, 0, 80, 8); |
| 7815 | let mut buf = Buffer::empty(area); |
| 7816 | widget.render(area, &mut buf); |
| 7817 | |
| 7818 | let submit = active_composer_submit_rect(&app, area).expect("enclosed composer submit"); |
| 7819 | let input_plane = widget.inner_area(area); |
| 7820 | let text_area = composer_content_geometry(input_plane, false).text_area; |
| 7821 | assert_eq!( |
| 7822 | text_area.right(), |
| 7823 | submit.x.saturating_sub(1), |
| 7824 | "one blank cell must remain between draft text and submit" |
| 7825 | ); |
| 7826 | |
| 7827 | let (cursor_x, cursor_y) = widget.cursor_pos(area).expect("draft cursor"); |
| 7828 | assert!( |
| 7829 | cursor_x < submit.x || cursor_x >= submit.right() || cursor_y != submit.y, |
| 7830 | "cursor {cursor_x},{cursor_y} must not land in submit {submit:?}" |
| 7831 | ); |
| 7832 | assert_eq!(app.input, draft, "rendering must retain the full draft"); |
| 7833 | |
| 7834 | let first_line: String = (text_area.x..text_area.right()) |
| 7835 | .map(|x| buf[(x, cursor_y.saturating_sub(1))].symbol().to_string()) |
| 7836 | .collect(); |
| 7837 | let continuation: String = (text_area.x..text_area.x.saturating_add(3)) |
| 7838 | .map(|x| buf[(x, cursor_y)].symbol().to_string()) |
| 7839 | .collect(); |
| 7840 | assert_eq!(first_line, "x".repeat(71), "first wrapped draft row"); |
| 7841 | assert_eq!( |
| 7842 | continuation, "xxx", |
| 7843 | "draft continuation must remain visible" |
| 7844 | ); |
| 7845 | let painted: String = (submit.x..submit.right()) |
| 7846 | .map(|x| buf[(x, submit.y)].symbol().to_string()) |
| 7847 | .collect(); |
| 7848 | assert_eq!(painted, "[↵]", "submit stays intact beside the draft"); |
| 7849 | } |
| 7850 | |
| 7851 | #[test] |
| 7852 | fn composer_send_hitbox_only_exists_where_the_panel_paints() { |
| 7853 | let mut app = create_test_app(); |
| 7854 | app.composer_border = true; |
| 7855 | app.input = "draft".into(); |
| 7856 | // Widths 6–11 fail COMPOSER_PANEL_MIN_WIDTH: the painter sheds the |
| 7857 | // enclosure there, so no invisible hit target may remain. |
| 7858 | for width in 6..12_u16 { |
| 7859 | let area = Rect::new(0, 0, width, 4); |
| 7860 | assert!( |
| 7861 | active_composer_submit_rect(&app, area).is_none(), |
| 7862 | "no hitbox without the painted panel at width {width}" |
| 7863 | ); |
| 7864 | } |
| 7865 | let area = Rect::new(0, 0, 12, 4); |
| 7866 | assert!( |
| 7867 | active_composer_submit_rect(&app, area).is_some(), |
| 7868 | "the minimum panel width hosts the hitbox" |
| 7869 | ); |
| 7870 | // Short composer rows and the quiet opt-out shed the hitbox too. |
| 7871 | assert!(active_composer_submit_rect(&app, Rect::new(0, 0, 80, 2)).is_none()); |
| 7872 | app.composer_border = false; |
| 7873 | assert!(active_composer_submit_rect(&app, Rect::new(0, 0, 80, 4)).is_none()); |
| 7874 | } |
| 7875 | |
| 7876 | #[test] |
| 7877 | fn quiet_composer_does_not_paint_a_fake_send_control() { |
| 7878 | let mut app = create_test_app(); |
| 7879 | app.composer_border = false; |
| 7880 | app.input = "ship it".to_string(); |
| 7881 | app.cursor_position = app.input.chars().count(); |
| 7882 | let rendered = render_composer(&app, 80, 4); |
| 7883 | assert!( |
| 7884 | !rendered.contains("[↵]"), |
| 7885 | "compact composer must shed the send chrome:\n{rendered}" |
| 7886 | ); |
| 7887 | } |
| 7888 | |
| 7889 | #[test] |
| 7890 | fn slash_menu_open_locks_composer_height_against_match_count_changes() { |
| 7891 | // Repro for the Windows 10 PowerShell + WSL feedback: typing |
| 7892 | // through a slash command shrinks the matched-entry list, which |
| 7893 | // used to shrink the composer height — and shrinking the |
| 7894 | // composer forces the chat area above to repaint every |
| 7895 | // keystroke. With the height lock, the desired height returned |
| 7896 | // for a 5-match menu and a 1-match menu must be identical so |
| 7897 | // the layout stays stable for the lifetime of the slash session. |
| 7898 | let mut app = create_test_app(); |
| 7899 | app.composer_density = ComposerDensity::Comfortable; |
| 7900 | app.input = "/skill".to_string(); |
| 7901 | |
| 7902 | let many_matches: Vec<SlashMenuEntry> = (0..5) |
| 7903 | .map(|i| SlashMenuEntry { |
| 7904 | name: format!("/skill{i}"), |
| 7905 | description: String::new(), |
| 7906 | is_skill: false, |
| 7907 | alias_hint: None, |
| 7908 | }) |
| 7909 | .collect(); |
| 7910 | let one_match = vec![SlashMenuEntry { |
| 7911 | name: "/skill".to_string(), |
| 7912 | description: String::new(), |
| 7913 | is_skill: false, |
| 7914 | alias_hint: None, |
| 7915 | }]; |
| 7916 | let no_matches = Vec::<SlashMenuEntry>::new(); |
| 7917 | |
| 7918 | let widget_many = ComposerWidget::new(&app, 9, &many_matches, &[]); |
| 7919 | let widget_one = ComposerWidget::new(&app, 9, &one_match, &[]); |
| 7920 | let widget_none = ComposerWidget::new(&app, 9, &no_matches, &[]); |
| 7921 | |
| 7922 | // Fixed worst-case envelope while the slash menu is open. |
| 7923 | let height_many = widget_many.desired_height(40); |
| 7924 | let height_one = widget_one.desired_height(40); |
| 7925 | assert_eq!( |
| 7926 | height_many, height_one, |
| 7927 | "slash menu height must not jitter as the matched-entry count changes" |
| 7928 | ); |
| 7929 | |
| 7930 | // Sanity: closing the slash menu (no matches) lets the panel |
| 7931 | // collapse back to a tight composer — we only want to lock |
| 7932 | // height *while* the menu is open. |
| 7933 | let height_none = widget_none.desired_height(40); |
| 7934 | assert!( |
| 7935 | height_none < height_many, |
| 7936 | "with the menu closed the composer should release the reserved rows; got {height_none} vs locked {height_many}" |
| 7937 | ); |
| 7938 | } |
| 7939 | |
| 7940 | #[test] |
| 7941 | fn empty_composer_cursor_follows_idle_prompt_when_border_disabled() { |
| 7942 | let mut app = create_test_app(); |
| 7943 | app.composer_density = ComposerDensity::Comfortable; |
| 7944 | app.composer_border = false; |
| 7945 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7946 | let mention_menu_entries = Vec::<String>::new(); |
| 7947 | let widget = ComposerWidget::new(&app, 3, &slash_menu_entries, &mention_menu_entries); |
| 7948 | |
| 7949 | let area = Rect { |
| 7950 | x: 0, |
| 7951 | y: 0, |
| 7952 | width: 40, |
| 7953 | height: 3, |
| 7954 | }; |
| 7955 | |
| 7956 | assert_eq!(widget.cursor_pos(area), Some((2, 1))); |
| 7957 | } |
| 7958 | |
| 7959 | #[test] |
| 7960 | fn localized_composer_placeholders_render_at_narrow_widths() { |
| 7961 | for locale in [Locale::Ja, Locale::ZhHans, Locale::PtBr] { |
| 7962 | let mut app = create_test_app(); |
| 7963 | app.ui_locale = locale; |
| 7964 | app.composer_density = ComposerDensity::Comfortable; |
| 7965 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 7966 | let mention_menu_entries = Vec::<String>::new(); |
| 7967 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 7968 | let area = Rect { |
| 7969 | x: 0, |
| 7970 | y: 0, |
| 7971 | width: 18, |
| 7972 | height: 5, |
| 7973 | }; |
| 7974 | let mut buf = Buffer::empty(area); |
| 7975 | |
| 7976 | widget.render(area, &mut buf); |
| 7977 | let Some((cursor_x, cursor_y)) = widget.cursor_pos(area) else { |
| 7978 | panic!("localized composer should expose cursor position"); |
| 7979 | }; |
| 7980 | |
| 7981 | assert!(cursor_x < area.width, "{locale:?} cursor x overflow"); |
| 7982 | assert!(cursor_y < area.height, "{locale:?} cursor y overflow"); |
| 7983 | } |
| 7984 | } |
| 7985 | |
| 7986 | #[test] |
| 7987 | fn composer_top_padding_uses_clamp() { |
| 7988 | // content_lines=0 is clamped to 1 |
| 7989 | assert_eq!(composer_top_padding(0, 3), 1); |
| 7990 | // content_lines=1 |
| 7991 | assert_eq!(composer_top_padding(1, 3), 1); |
| 7992 | // content_lines=3 fills the budget |
| 7993 | assert_eq!(composer_top_padding(3, 3), 0); |
| 7994 | // content_lines > budget is clamped |
| 7995 | assert_eq!(composer_top_padding(5, 3), 0); |
| 7996 | } |
| 7997 | |
| 7998 | #[test] |
| 7999 | fn empty_state_renders_only_without_transcript_activity() { |
| 8000 | let mut app = create_test_app(); |
| 8001 | assert!(should_render_empty_state(&app)); |
| 8002 | app.add_message(crate::tui::history::HistoryCell::User { |
| 8003 | content: "hello".to_string(), |
| 8004 | }); |
| 8005 | assert!(!should_render_empty_state(&app)); |
| 8006 | } |
| 8007 | |
| 8008 | #[test] |
| 8009 | fn durable_tasks_suppress_the_launch_tableau() { |
| 8010 | let mut app = create_test_app(); |
| 8011 | app.task_panel.push(TaskPanelEntry { |
| 8012 | exit_code: None, |
| 8013 | id: "shell_1".to_string(), |
| 8014 | status: "running".to_string(), |
| 8015 | prompt_summary: "cargo test".to_string(), |
| 8016 | duration_ms: Some(100), |
| 8017 | kind: TaskPanelEntryKind::Background, |
| 8018 | stale: false, |
| 8019 | elapsed_since_output_ms: None, |
| 8020 | owner_agent_id: None, |
| 8021 | owner_agent_name: None, |
| 8022 | current_tool: None, |
| 8023 | role: None, |
| 8024 | files_touched: 0, |
| 8025 | }); |
| 8026 | |
| 8027 | assert!(!should_render_empty_state(&app)); |
| 8028 | } |
| 8029 | |
| 8030 | #[test] |
| 8031 | fn chat_widget_publishes_wrapped_url_regions_without_touching_cells() { |
| 8032 | let mut app = create_test_app(); |
| 8033 | app.low_motion = true; |
| 8034 | let target = "https://example.test/a/very/long/path/that/wraps/across/chat/rows"; |
| 8035 | app.add_message(HistoryCell::Assistant { |
| 8036 | content: target.to_string(), |
| 8037 | streaming: false, |
| 8038 | }); |
| 8039 | |
| 8040 | let area = Rect::new(4, 2, 20, 10); |
| 8041 | let mut buf = Buffer::empty(area); |
| 8042 | let _ = codewhale_tui_kit::osc8::take_frame_links(); |
| 8043 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 8044 | let regions = codewhale_tui_kit::osc8::take_frame_links(); |
| 8045 | |
| 8046 | assert!(regions.len() > 1, "narrow chat should wrap: {regions:?}"); |
| 8047 | assert!(regions.iter().all(|region| region.target == target)); |
| 8048 | assert!(regions.iter().all(|region| { |
| 8049 | area.contains(ratatui::layout::Position { |
| 8050 | x: region.col_start, |
| 8051 | y: region.row, |
| 8052 | }) && area.contains(ratatui::layout::Position { |
| 8053 | x: region.col_end, |
| 8054 | y: region.row, |
| 8055 | }) |
| 8056 | })); |
| 8057 | assert!((area.y..area.bottom()).all(|y| { |
| 8058 | (area.x..area.right()).all(|x| { |
| 8059 | let symbol = buf[(x, y)].symbol(); |
| 8060 | !symbol.contains('\x1b') && !symbol.contains("]8;;") |
| 8061 | }) |
| 8062 | })); |
| 8063 | } |
| 8064 | |
| 8065 | #[test] |
| 8066 | fn waiting_state_freezes_the_whole_ocean_field() { |
| 8067 | let mut app = create_test_app(); |
| 8068 | app.low_motion = false; |
| 8069 | app.fancy_animations = true; |
| 8070 | app.view_stack |
| 8071 | .push(crate::tui::views::HelpView::new_for_locale(app.ui_locale)); |
| 8072 | |
| 8073 | let widget = ChatWidget::new(&mut app, Rect::new(0, 0, 100, 20)); |
| 8074 | |
| 8075 | assert!(!widget.ocean_animated); |
| 8076 | assert!(!widget.ambient_life); |
| 8077 | assert!(!should_render_empty_state(&app)); |
| 8078 | } |
| 8079 | |
| 8080 | #[test] |
| 8081 | fn reduced_motion_gets_no_ambient_life_through_the_completion_breath() { |
| 8082 | // The completion branch of `life_presence` runs before its `!animated` |
| 8083 | // check, so feeding it an ungated clock flashed a full field of fish |
| 8084 | // and jellyfish for ~1.4 s after every successful turn even with |
| 8085 | // `low_motion = true`. Reduced motion means reduced motion. |
| 8086 | for (low_motion, fancy_animations) in [(true, true), (false, false)] { |
| 8087 | let mut app = create_test_app(); |
| 8088 | app.low_motion = low_motion; |
| 8089 | app.fancy_animations = fancy_animations; |
| 8090 | app.ocean_completion_started_at = Some(Instant::now()); |
| 8091 | |
| 8092 | let widget = ChatWidget::new(&mut app, Rect::new(0, 0, 100, 20)); |
| 8093 | |
| 8094 | assert_eq!( |
| 8095 | widget.life_presence_fixed, 0, |
| 8096 | "low_motion={low_motion} fancy={fancy_animations} leaked ambient life" |
| 8097 | ); |
| 8098 | } |
| 8099 | |
| 8100 | let mut full = create_test_app(); |
| 8101 | full.low_motion = false; |
| 8102 | full.fancy_animations = true; |
| 8103 | full.ocean_completion_started_at = Some(Instant::now()); |
| 8104 | let widget = ChatWidget::new(&mut full, Rect::new(0, 0, 100, 20)); |
| 8105 | assert!( |
| 8106 | widget.life_presence_fixed > 0, |
| 8107 | "full motion should still get the completion breath" |
| 8108 | ); |
| 8109 | } |
| 8110 | |
| 8111 | #[test] |
| 8112 | fn dot_whale_gets_the_motion_gated_completion_settle_clock() { |
| 8113 | let mut app = create_test_app(); |
| 8114 | app.low_motion = false; |
| 8115 | app.fancy_animations = true; |
| 8116 | app.ocean_completion_started_at = |
| 8117 | Some(Instant::now() - std::time::Duration::from_millis(900)); |
| 8118 | let widget = ChatWidget::new(&mut app, Rect::new(0, 0, 100, 24)); |
| 8119 | let age = widget |
| 8120 | .ocean_column |
| 8121 | .and_then(|column| column.completion_elapsed_ms()); |
| 8122 | assert!( |
| 8123 | age.is_some_and(|age| (800..1_400).contains(&age)), |
| 8124 | "{age:?}" |
| 8125 | ); |
| 8126 | assert!(widget.life_presence_fixed > 0 && widget.life_presence_fixed < 1_000); |
| 8127 | |
| 8128 | app.low_motion = true; |
| 8129 | let still = ChatWidget::new(&mut app, Rect::new(0, 0, 100, 24)); |
| 8130 | assert_eq!( |
| 8131 | still |
| 8132 | .ocean_column |
| 8133 | .and_then(|column| column.completion_elapsed_ms()), |
| 8134 | None |
| 8135 | ); |
| 8136 | assert_eq!(still.life_presence_fixed, 0); |
| 8137 | } |
| 8138 | |
| 8139 | #[test] |
| 8140 | fn reduced_and_still_modes_clear_the_one_shot_send_flash() { |
| 8141 | for (low_motion, fancy_animations) in [(true, true), (false, false)] { |
| 8142 | let mut app = create_test_app(); |
| 8143 | app.low_motion = low_motion; |
| 8144 | app.fancy_animations = fancy_animations; |
| 8145 | app.last_send_at = Some(Instant::now()); |
| 8146 | app.add_message(HistoryCell::User { |
| 8147 | content: "semantic receipt".to_string(), |
| 8148 | }); |
| 8149 | |
| 8150 | let _widget = ChatWidget::new(&mut app, Rect::new(0, 0, 100, 20)); |
| 8151 | assert!( |
| 8152 | app.last_send_at.is_none(), |
| 8153 | "non-full motion must not retain a time-based flash" |
| 8154 | ); |
| 8155 | } |
| 8156 | |
| 8157 | let mut full = create_test_app(); |
| 8158 | full.low_motion = false; |
| 8159 | full.fancy_animations = true; |
| 8160 | full.last_send_at = Some(Instant::now()); |
| 8161 | full.add_message(HistoryCell::User { |
| 8162 | content: "animated receipt".to_string(), |
| 8163 | }); |
| 8164 | let _widget = ChatWidget::new(&mut full, Rect::new(0, 0, 100, 20)); |
| 8165 | assert!( |
| 8166 | full.last_send_at.is_some(), |
| 8167 | "full motion should retain the active send-flash window" |
| 8168 | ); |
| 8169 | } |
| 8170 | |
| 8171 | #[test] |
| 8172 | fn empty_state_shows_startup_context() { |
| 8173 | let mut app = create_test_app(); |
| 8174 | app.onboarding_needs_api_key = false; |
| 8175 | app.workspace = PathBuf::from("/tmp/codewhale-test-workspace"); |
| 8176 | app.mcp_configured_count = 2; |
| 8177 | |
| 8178 | let lines = build_empty_state_lines(&app, Rect::new(0, 0, 100, 20)); |
| 8179 | let rendered = lines |
| 8180 | .iter() |
| 8181 | .map(|line| { |
| 8182 | line.spans |
| 8183 | .iter() |
| 8184 | .map(|span| span.content.as_ref()) |
| 8185 | .collect::<String>() |
| 8186 | }) |
| 8187 | .collect::<Vec<_>>() |
| 8188 | .join("\n"); |
| 8189 | |
| 8190 | assert!(rendered.contains("codewhale")); |
| 8191 | assert!(rendered.contains("/tmp/codewhale-test-workspace · no git · mcp 2")); |
| 8192 | assert!(rendered.contains("What do you want to accomplish?")); |
| 8193 | assert!(!rendered.contains("/workflow /goal /auto")); |
| 8194 | } |
| 8195 | |
| 8196 | #[test] |
| 8197 | fn empty_state_centers_startup_block_by_actual_text_width() { |
| 8198 | let mut app = create_test_app(); |
| 8199 | app.workspace = PathBuf::from("/tmp/codewhale-test-workspace"); |
| 8200 | |
| 8201 | let lines = build_empty_state_lines(&app, Rect::new(0, 0, 100, 20)); |
| 8202 | let text_lines = lines |
| 8203 | .iter() |
| 8204 | .map(|line| { |
| 8205 | line.spans |
| 8206 | .iter() |
| 8207 | .map(|span| span.content.as_ref()) |
| 8208 | .collect::<String>() |
| 8209 | }) |
| 8210 | .collect::<Vec<_>>(); |
| 8211 | let context = "/tmp/codewhale-test-workspace · no git · mcp 0"; |
| 8212 | let context_line = text_lines |
| 8213 | .iter() |
| 8214 | .find(|line| line.trim_start() == context) |
| 8215 | .expect("context line"); |
| 8216 | let expected_padding = (100usize - UnicodeWidthStr::width(context)) / 2; |
| 8217 | let actual_padding = context_line.chars().take_while(|ch| *ch == ' ').count(); |
| 8218 | |
| 8219 | assert_eq!(actual_padding, expected_padding); |
| 8220 | } |
| 8221 | |
| 8222 | #[test] |
| 8223 | fn underwater_launch_is_visibly_deep_and_preserves_text_cells() { |
| 8224 | let mut app = create_test_app(); |
| 8225 | // App::new reads persisted presentation settings. Other tests swap the |
| 8226 | // isolated settings home in parallel, so this visual contract must pin |
| 8227 | // the theme it is actually asserting instead of inheriting a transient |
| 8228 | // non-underwater choice from the process. |
| 8229 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 8230 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 8231 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 8232 | app.low_motion = false; |
| 8233 | app.fancy_animations = true; |
| 8234 | app.workspace = PathBuf::from("codewhale-test-workspace"); |
| 8235 | app.model = "deepseek-v4-pro".to_string(); |
| 8236 | |
| 8237 | let area = Rect::new(0, 0, 100, 20); |
| 8238 | let base = app.ui_theme.surface_bg; |
| 8239 | let context = format!("{} · no git · mcp 0", app.workspace.display()); |
| 8240 | let mut buf = Buffer::empty(area); |
| 8241 | // Sample one known point in the live motion path. The old test raced |
| 8242 | // the scheduler between App construction and rendering, which could |
| 8243 | // move the school off-screen on slower Windows runners. |
| 8244 | ChatWidget::new_with_ocean_elapsed(&mut app, area, 0).render(area, &mut buf); |
| 8245 | |
| 8246 | assert_ne!(buf[(0, 0)].bg, buf[(0, 19)].bg); |
| 8247 | let rendered = buffer_text(&buf, area); |
| 8248 | assert!( |
| 8249 | ambient_life_cells(&mut app, area, 0) > 0, |
| 8250 | "wide idle water shows ocean life:\n{rendered}" |
| 8251 | ); |
| 8252 | |
| 8253 | let context_x = ((100usize - UnicodeWidthStr::width(context.as_str())) / 2) as u16; |
| 8254 | let context_cell = (0..area.height) |
| 8255 | .find_map(|y| (buf[(context_x, y)].symbol() == "c").then_some((context_x, y))) |
| 8256 | .expect("context line"); |
| 8257 | let mut water = Buffer::empty(area); |
| 8258 | water.set_style(area, Style::default().bg(base)); |
| 8259 | water[context_cell] = buf[context_cell].clone(); |
| 8260 | water[context_cell].set_bg(base); |
| 8261 | ChatWidget::new_with_ocean_elapsed(&mut app, area, 0) |
| 8262 | .ocean_column() |
| 8263 | .unwrap() |
| 8264 | .paint_matching_native(area, &mut water, base, &app.ui_theme, &[]); |
| 8265 | assert_eq!(buf[context_cell].bg, water[context_cell].bg); |
| 8266 | assert_ne!( |
| 8267 | buf[context_cell].bg, base, |
| 8268 | "the water column should continue behind ordinary text" |
| 8269 | ); |
| 8270 | } |
| 8271 | |
| 8272 | #[test] |
| 8273 | fn home_water_continues_through_typing_history_and_return() { |
| 8274 | let viewport = Rect::new(0, 0, 106, 39); |
| 8275 | let chat = Rect::new(0, 2, 106, 30); |
| 8276 | let field = |app: &mut App, elapsed| { |
| 8277 | let mut buffer = Buffer::empty(viewport); |
| 8278 | buffer.set_style(viewport, Style::default().bg(app.ui_theme.surface_bg)); |
| 8279 | ChatWidget::new_with_ocean_elapsed(app, chat, elapsed) |
| 8280 | .with_ocean_viewport(viewport) |
| 8281 | .ocean_column() |
| 8282 | .unwrap() |
| 8283 | .paint_matching_native( |
| 8284 | viewport, |
| 8285 | &mut buffer, |
| 8286 | app.ui_theme.surface_bg, |
| 8287 | &app.ui_theme, |
| 8288 | &[], |
| 8289 | ); |
| 8290 | buffer |
| 8291 | }; |
| 8292 | for low_motion in [false, true] { |
| 8293 | let mut app = create_test_app(); |
| 8294 | app.low_motion = low_motion; |
| 8295 | app.fancy_animations = true; |
| 8296 | app.launch.visible = true; |
| 8297 | let home = field(&mut app, 0); |
| 8298 | assert_ne!(home[(4, 1)].bg, home[(84, 1)].bg); |
| 8299 | assert_ne!(home[(84, 1)].bg, home[(84, 38)].bg); |
| 8300 | |
| 8301 | app.insert_str("read the notes"); |
| 8302 | assert_eq!(field(&mut app, 500), home); |
| 8303 | app.launch.visible = false; |
| 8304 | app.add_message(HistoryCell::User { |
| 8305 | content: "read the notes".into(), |
| 8306 | }); |
| 8307 | app.add_message(HistoryCell::Assistant { |
| 8308 | content: "Here they are.".into(), |
| 8309 | streaming: false, |
| 8310 | }); |
| 8311 | let session = field(&mut app, 1_000); |
| 8312 | assert_ne!(session, home); |
| 8313 | let peak_luma = |buffer: &Buffer| { |
| 8314 | buffer |
| 8315 | .content() |
| 8316 | .iter() |
| 8317 | .filter_map(|cell| match cell.bg { |
| 8318 | Color::Rgb(r, g, b) => { |
| 8319 | Some(u32::from(r) * 299 + u32::from(g) * 587 + u32::from(b) * 114) |
| 8320 | } |
| 8321 | _ => None, |
| 8322 | }) |
| 8323 | .max() |
| 8324 | .unwrap_or(0) |
| 8325 | }; |
| 8326 | assert!(peak_luma(&session) < peak_luma(&home)); |
| 8327 | app.viewport.transcript_scroll = TranscriptScroll::at_line(0); |
| 8328 | assert_eq!(field(&mut app, 5_000), session); |
| 8329 | app.launch.visible = true; |
| 8330 | app.launch.return_to_session = true; |
| 8331 | assert_eq!(field(&mut app, 6_000), home); |
| 8332 | app.launch.visible = false; |
| 8333 | assert_eq!(field(&mut app, 7_000), session); |
| 8334 | |
| 8335 | app.clear_input(); |
| 8336 | app.viewport.transcript_scroll = TranscriptScroll::to_bottom(); |
| 8337 | app.is_loading = true; |
| 8338 | app.turn_started_at = Instant::now().checked_sub(Duration::from_secs(2)); |
| 8339 | let working = field(&mut app, 8_000); |
| 8340 | assert!(working != home && working != session); |
| 8341 | |
| 8342 | use crate::tui::approval::{ApprovalRequest, ApprovalView}; |
| 8343 | app.view_stack.push(ApprovalView::new(ApprovalRequest::new( |
| 8344 | "approval", |
| 8345 | "read_file", |
| 8346 | "Read file", |
| 8347 | &serde_json::json!({"path": "README.md"}), |
| 8348 | "request", |
| 8349 | ))); |
| 8350 | let approval = field(&mut app, 9_000); |
| 8351 | assert!(approval != home && approval != session && approval != working); |
| 8352 | app.view_stack.pop(); |
| 8353 | app.is_loading = false; |
| 8354 | app.runtime_turn_status = Some("failed".into()); |
| 8355 | let failed = field(&mut app, 10_000); |
| 8356 | assert!(failed != home && failed != session && failed != approval); |
| 8357 | } |
| 8358 | } |
| 8359 | |
| 8360 | #[test] |
| 8361 | fn terminal_owned_theme_keeps_theme_surface_without_ambient_life() { |
| 8362 | let mut app = create_test_app(); |
| 8363 | app.theme_id = codewhale_palette::ThemeId::Whale; |
| 8364 | app.ui_theme = palette::UI_THEME; |
| 8365 | app.low_motion = false; |
| 8366 | app.fancy_animations = true; |
| 8367 | let area = Rect::new(0, 0, 100, 20); |
| 8368 | let base = app.ui_theme.surface_bg; |
| 8369 | let mut buf = Buffer::empty(area); |
| 8370 | let widget = ChatWidget::new(&mut app, area); |
| 8371 | assert!(!widget.ambient_life); |
| 8372 | widget.render(area, &mut buf); |
| 8373 | |
| 8374 | assert_eq!(buf[(0, 0)].bg, base); |
| 8375 | assert_eq!(buf[(0, 19)].bg, base, "flat keeps the plain theme surface"); |
| 8376 | assert_eq!( |
| 8377 | ambient_life_cells(&mut app, area, 0), |
| 8378 | 0, |
| 8379 | "terminal-owned themes must keep a normal shell without decorative fish" |
| 8380 | ); |
| 8381 | } |
| 8382 | |
| 8383 | #[test] |
| 8384 | fn solarized_light_keeps_canonical_surface_without_a_field() { |
| 8385 | let mut app = create_test_app(); |
| 8386 | app.theme_id = codewhale_palette::ThemeId::SolarizedLight; |
| 8387 | app.ui_theme = codewhale_palette::SOLARIZED_LIGHT_UI_THEME; |
| 8388 | app.low_motion = false; |
| 8389 | app.fancy_animations = true; |
| 8390 | // The old cyan-tinted ramp produced the reported #e1e9da at row 16 |
| 8391 | // of a common 30-row viewport. |
| 8392 | let area = Rect::new(0, 0, 100, 30); |
| 8393 | let canonical_base3 = Color::Rgb(0xfd, 0xf6, 0xe3); |
| 8394 | let mut buf = Buffer::empty(area); |
| 8395 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 8396 | |
| 8397 | assert_eq!(buf[(0, 0)].bg, canonical_base3); |
| 8398 | assert_eq!( |
| 8399 | buf[(0, 16)].bg, |
| 8400 | canonical_base3, |
| 8401 | "Solarized Light must not regress to the reported #e1e9da tint" |
| 8402 | ); |
| 8403 | assert_eq!( |
| 8404 | buf[(0, 29)].bg, |
| 8405 | canonical_base3, |
| 8406 | "Solarized Light must keep canonical Base3 through the viewport" |
| 8407 | ); |
| 8408 | assert_eq!( |
| 8409 | ambient_life_cells(&mut app, area, 0), |
| 8410 | 0, |
| 8411 | "a theme with no painted field earns no ambient life" |
| 8412 | ); |
| 8413 | } |
| 8414 | |
| 8415 | #[test] |
| 8416 | fn underwater_custom_background_keeps_field_depth() { |
| 8417 | let mut app = create_test_app(); |
| 8418 | let custom = Color::Rgb(0x1a, 0x1b, 0x26); |
| 8419 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 8420 | app.ui_theme = palette::UNDERWATER_UI_THEME.with_background_color(custom); |
| 8421 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 8422 | |
| 8423 | let area = Rect::new(0, 0, 100, 30); |
| 8424 | let mut buf = Buffer::empty(area); |
| 8425 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 8426 | |
| 8427 | assert_ne!(buf[(0, 0)].bg, custom); |
| 8428 | assert_ne!( |
| 8429 | buf[(0, 0)].bg, |
| 8430 | buf[(0, 29)].bg, |
| 8431 | "custom backgrounds must not flatten the underwater field" |
| 8432 | ); |
| 8433 | } |
| 8434 | |
| 8435 | #[test] |
| 8436 | fn terminal_owned_background_stays_visually_quiet_without_deepsea() { |
| 8437 | let mut app = create_test_app(); |
| 8438 | app.theme_id = codewhale_palette::ThemeId::Terminal; |
| 8439 | app.ui_theme = codewhale_palette::TERMINAL_UI_THEME; |
| 8440 | app.low_motion = false; |
| 8441 | app.fancy_animations = true; |
| 8442 | let area = Rect::new(0, 0, 100, 20); |
| 8443 | let mut buf = Buffer::empty(area); |
| 8444 | let widget = ChatWidget::new(&mut app, area); |
| 8445 | assert!(!widget.ambient_life); |
| 8446 | widget.render(area, &mut buf); |
| 8447 | |
| 8448 | assert!( |
| 8449 | (0..area.height).all(|y| (0..area.width).all(|x| buf[(x, y)].bg == Color::Reset)), |
| 8450 | "the Terminal treatment must never paint a background" |
| 8451 | ); |
| 8452 | assert_eq!( |
| 8453 | ambient_life_cells(&mut app, area, 0), |
| 8454 | 0, |
| 8455 | "Terminal must remain a quiet host-owned shell without the selected Deepsea scene" |
| 8456 | ); |
| 8457 | } |
| 8458 | |
| 8459 | /// #4208: `CODEWHALE_ASCII_SAFE=1` must narrow every CodeWhale-authored |
| 8460 | /// decorative glyph — whale mark, fish, bubble, context meter, borders, |
| 8461 | /// braille state markers — across real rendered surfaces, not a |
| 8462 | /// hand-picked symbol list. |
| 8463 | #[test] |
| 8464 | fn ascii_safe_tier_covers_whole_rendered_surfaces() { |
| 8465 | let mut app = create_test_app(); |
| 8466 | app.low_motion = false; |
| 8467 | app.fancy_animations = true; |
| 8468 | |
| 8469 | // Idle empty water at a size that earns the whale, fish, and bubble. |
| 8470 | let transcript_area = Rect::new(0, 0, 100, 32); |
| 8471 | let mut transcript = Buffer::empty(transcript_area); |
| 8472 | ChatWidget::new(&mut app, transcript_area).render(transcript_area, &mut transcript); |
| 8473 | |
| 8474 | // The opening screen is the ordinary idle transcript now, so its |
| 8475 | // content comes from the same empty-state builder every other screen |
| 8476 | // uses rather than a second surface. |
| 8477 | app.launch.visible = true; |
| 8478 | let launch_area = Rect::new(0, 0, 100, 32); |
| 8479 | let launch_lines = crate::tui::underwater::empty_state_lines(&app, launch_area); |
| 8480 | let mut launch = Buffer::empty(launch_area); |
| 8481 | for (row, line) in launch_lines.iter().enumerate() { |
| 8482 | if let Ok(y) = u16::try_from(row) |
| 8483 | && y < launch_area.height |
| 8484 | { |
| 8485 | ratatui::widgets::Widget::render( |
| 8486 | ratatui::widgets::Paragraph::new(line.clone()), |
| 8487 | Rect::new(0, y, launch_area.width, 1), |
| 8488 | &mut launch, |
| 8489 | ); |
| 8490 | } |
| 8491 | } |
| 8492 | app.launch.visible = false; |
| 8493 | |
| 8494 | // The info line (the shell's bottom row since the placement move) |
| 8495 | // owns the route facts and the block context meter. |
| 8496 | let info_area = Rect::new(0, 0, 100, 1); |
| 8497 | let mut info_buf = Buffer::empty(info_area); |
| 8498 | { |
| 8499 | let segments = crate::tui::ui::frame::info_segments(&app, info_area.width); |
| 8500 | let help_hint = crate::tui::shell_key_routing::info_help_hint(app.ui_locale); |
| 8501 | let info = crate::tui::infoline::InfoLine::new(&app.ui_theme, &help_hint, &segments) |
| 8502 | .ascii_safe(true); |
| 8503 | use ratatui::widgets::Widget; |
| 8504 | Widget::render(info, info_area, &mut info_buf); |
| 8505 | } |
| 8506 | |
| 8507 | for (surface, buf, rect) in [ |
| 8508 | ("idle transcript", &transcript, transcript_area), |
| 8509 | ("launch", &launch, launch_area), |
| 8510 | ("info line", &info_buf, info_area), |
| 8511 | ] { |
| 8512 | for y in rect.y..rect.bottom() { |
| 8513 | for x in rect.x..rect.right() { |
| 8514 | let mut cell = buf[(x, y)].clone(); |
| 8515 | crate::tui::color_compat::adapt_cell_symbol_for_ascii(&mut cell); |
| 8516 | assert!( |
| 8517 | cell.symbol().is_ascii(), |
| 8518 | "{surface} cell ({x},{y}) {:?} lacks an ASCII-safe alternative", |
| 8519 | buf[(x, y)].symbol() |
| 8520 | ); |
| 8521 | } |
| 8522 | } |
| 8523 | } |
| 8524 | } |
| 8525 | |
| 8526 | #[test] |
| 8527 | fn reduced_motion_freezes_the_ocean_without_removing_depth() { |
| 8528 | let mut app = create_test_app(); |
| 8529 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 8530 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 8531 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 8532 | app.low_motion = true; |
| 8533 | app.fancy_animations = true; |
| 8534 | let area = Rect::new(0, 0, 100, 20); |
| 8535 | // Drive the sampled clock directly: the freeze must hold even across |
| 8536 | // a 9-second animation-clock jump. |
| 8537 | let mut first = Buffer::empty(area); |
| 8538 | ChatWidget::new_with_ocean_elapsed(&mut app, area, 2_000).render(area, &mut first); |
| 8539 | |
| 8540 | let mut second = Buffer::empty(area); |
| 8541 | ChatWidget::new_with_ocean_elapsed(&mut app, area, 11_000).render(area, &mut second); |
| 8542 | |
| 8543 | assert_ne!(first[(0, 0)].bg, first[(0, 19)].bg); |
| 8544 | assert_eq!(first[(0, 0)].bg, second[(0, 0)].bg); |
| 8545 | assert_eq!(first[(11, 14)].symbol(), second[(11, 14)].symbol()); |
| 8546 | } |
| 8547 | |
| 8548 | /// Rendered line metadata for pin tests: `(cell_index, line_in_cell)`. |
| 8549 | fn pin_meta(entries: &[(usize, usize)]) -> Vec<TranscriptLineMeta> { |
| 8550 | entries |
| 8551 | .iter() |
| 8552 | .map(|(cell_index, line_in_cell)| TranscriptLineMeta::CellLine { |
| 8553 | cell_index: *cell_index, |
| 8554 | line_in_cell: *line_in_cell, |
| 8555 | copy_prefix_width: 0, |
| 8556 | copy_separator_after: codewhale_tui_kit::ui_text::CopyLineSeparator::None, |
| 8557 | }) |
| 8558 | .collect() |
| 8559 | } |
| 8560 | |
| 8561 | fn pin_text(line: &Line<'static>) -> String { |
| 8562 | line.spans |
| 8563 | .iter() |
| 8564 | .map(|span| span.content.as_ref()) |
| 8565 | .collect() |
| 8566 | } |
| 8567 | |
| 8568 | #[test] |
| 8569 | fn pin_helper_returns_header_when_user_line_is_above_viewport() { |
| 8570 | let history = vec![ |
| 8571 | HistoryCell::User { |
| 8572 | content: "remember this prompt".into(), |
| 8573 | }, |
| 8574 | HistoryCell::Assistant { |
| 8575 | content: "ok".into(), |
| 8576 | streaming: false, |
| 8577 | }, |
| 8578 | ]; |
| 8579 | let meta = pin_meta(&[(0, 0), (1, 0)]); |
| 8580 | let map = vec![0, 1]; |
| 8581 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 1, 40) |
| 8582 | .expect("scrolled user prompt should yield a pinned header"); |
| 8583 | let text = pin_text(&pin); |
| 8584 | assert!( |
| 8585 | text.contains("remember this prompt"), |
| 8586 | "expected pinned user text, got {text:?}" |
| 8587 | ); |
| 8588 | assert_eq!(message, 0, "the pin must name the user message it heads"); |
| 8589 | } |
| 8590 | |
| 8591 | #[test] |
| 8592 | fn pin_helper_is_idle_when_user_line_is_visible() { |
| 8593 | let history = vec![HistoryCell::User { |
| 8594 | content: "still on screen".into(), |
| 8595 | }]; |
| 8596 | let meta = pin_meta(&[(0, 0)]); |
| 8597 | let map = vec![0]; |
| 8598 | assert!(super::scrolled_user_prompt_pin(&history, &meta, &map, 0, 40).is_none()); |
| 8599 | } |
| 8600 | |
| 8601 | /// Scrolling up a turn keeps the header alive: it re-pins to the previous |
| 8602 | /// turn's prompt instead of dropping out once the newest prompt leaves the |
| 8603 | /// viewport. |
| 8604 | #[test] |
| 8605 | fn pin_helper_follows_the_viewport_up_to_the_previous_turn() { |
| 8606 | let history = vec![ |
| 8607 | HistoryCell::User { |
| 8608 | content: "first prompt".into(), |
| 8609 | }, |
| 8610 | HistoryCell::Assistant { |
| 8611 | content: "a1".into(), |
| 8612 | streaming: false, |
| 8613 | }, |
| 8614 | HistoryCell::Assistant { |
| 8615 | content: "a2".into(), |
| 8616 | streaming: false, |
| 8617 | }, |
| 8618 | HistoryCell::Assistant { |
| 8619 | content: "a3".into(), |
| 8620 | streaming: false, |
| 8621 | }, |
| 8622 | HistoryCell::User { |
| 8623 | content: "second prompt".into(), |
| 8624 | }, |
| 8625 | HistoryCell::Assistant { |
| 8626 | content: "b1".into(), |
| 8627 | streaming: false, |
| 8628 | }, |
| 8629 | HistoryCell::Assistant { |
| 8630 | content: "b2".into(), |
| 8631 | streaming: false, |
| 8632 | }, |
| 8633 | HistoryCell::Assistant { |
| 8634 | content: "b3".into(), |
| 8635 | streaming: false, |
| 8636 | }, |
| 8637 | ]; |
| 8638 | let meta = pin_meta(&[ |
| 8639 | (0, 0), |
| 8640 | (1, 0), |
| 8641 | (2, 0), |
| 8642 | (3, 0), |
| 8643 | (4, 0), |
| 8644 | (5, 0), |
| 8645 | (6, 0), |
| 8646 | (7, 0), |
| 8647 | ]); |
| 8648 | let map: Vec<usize> = (0..8).collect(); |
| 8649 | |
| 8650 | // Viewport over the newest replies: the newest prompt owns the top. |
| 8651 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 5, 40) |
| 8652 | .expect("newest prompt pins while its line is above the viewport"); |
| 8653 | assert!(pin_text(&pin).contains("second prompt")); |
| 8654 | assert_eq!(message, 4, "the second prompt is history cell 4"); |
| 8655 | |
| 8656 | // Viewport scrolled up past the newest prompt: the header re-pins to |
| 8657 | // the previous turn instead of disappearing. |
| 8658 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 1, 40) |
| 8659 | .expect("a turn above the viewport must keep a pinned header"); |
| 8660 | assert!(pin_text(&pin).contains("first prompt")); |
| 8661 | assert_eq!(message, 0); |
| 8662 | } |
| 8663 | |
| 8664 | /// The scan keys off a message's *first* rendered line and the filtered→ |
| 8665 | /// original cell mapping: a later line of a multi-line prompt must not |
| 8666 | /// stand in for the message start, and filtered indices must resolve to |
| 8667 | /// the original cell. |
| 8668 | #[test] |
| 8669 | fn pin_helper_uses_first_rendered_line_and_resolves_filtered_cells() { |
| 8670 | let history = vec![ |
| 8671 | HistoryCell::Assistant { |
| 8672 | content: "collapsed away".into(), |
| 8673 | streaming: false, |
| 8674 | }, |
| 8675 | HistoryCell::User { |
| 8676 | content: "wrapped prompt line one\nline two".into(), |
| 8677 | }, |
| 8678 | HistoryCell::Assistant { |
| 8679 | content: "c1".into(), |
| 8680 | streaming: false, |
| 8681 | }, |
| 8682 | HistoryCell::Assistant { |
| 8683 | content: "c2".into(), |
| 8684 | streaming: false, |
| 8685 | }, |
| 8686 | ]; |
| 8687 | // Original cell 0 is collapsed away, so the rendered (filtered) index |
| 8688 | // 0 maps back to original 1 — the user message — across its two |
| 8689 | // lines. |
| 8690 | let meta = pin_meta(&[(0, 0), (0, 1), (1, 0), (2, 0)]); |
| 8691 | let map = vec![1, 2, 3]; |
| 8692 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 3, 40) |
| 8693 | .expect("multi-line prompt pins at its first rendered line"); |
| 8694 | assert!(pin_text(&pin).contains("wrapped prompt line one")); |
| 8695 | assert!( |
| 8696 | !pin_text(&pin).contains("line two"), |
| 8697 | "the pin must show the first line, not a body line" |
| 8698 | ); |
| 8699 | assert_eq!( |
| 8700 | message, 1, |
| 8701 | "the pin names the user message, resolved through the filtered map" |
| 8702 | ); |
| 8703 | } |
| 8704 | |
| 8705 | /// A prompt whose first line is blank cannot head the header, and it must |
| 8706 | /// not suppress an older message that can: the header keeps handing over |
| 8707 | /// instead of dropping out (SpikeBot 003 review follow-up). |
| 8708 | #[test] |
| 8709 | fn pin_helper_skips_blank_first_line_prompts_and_keeps_handing_over() { |
| 8710 | let history = vec![ |
| 8711 | HistoryCell::User { |
| 8712 | content: "older prompt".into(), |
| 8713 | }, |
| 8714 | HistoryCell::Assistant { |
| 8715 | content: "a1".into(), |
| 8716 | streaming: false, |
| 8717 | }, |
| 8718 | HistoryCell::User { |
| 8719 | content: "\nblank first line".into(), |
| 8720 | }, |
| 8721 | HistoryCell::Assistant { |
| 8722 | content: "b1".into(), |
| 8723 | streaming: false, |
| 8724 | }, |
| 8725 | ]; |
| 8726 | let meta = pin_meta(&[(0, 0), (1, 0), (2, 0), (3, 0)]); |
| 8727 | let map: Vec<usize> = (0..4).collect(); |
| 8728 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 4, 40) |
| 8729 | .expect("a blank-led prompt must not blank out the header"); |
| 8730 | assert!(pin_text(&pin).contains("older prompt")); |
| 8731 | assert_eq!(message, 0); |
| 8732 | } |
| 8733 | |
| 8734 | /// The header hands over the instant a newer prompt's first line reaches |
| 8735 | /// the viewport's top row: no window where it blinks out while the user |
| 8736 | /// scrolls across a turn boundary. |
| 8737 | #[test] |
| 8738 | fn pin_helper_hands_over_the_instant_the_newer_prompt_enters() { |
| 8739 | let history = vec![ |
| 8740 | HistoryCell::User { |
| 8741 | content: "first prompt".into(), |
| 8742 | }, |
| 8743 | HistoryCell::Assistant { |
| 8744 | content: "a1".into(), |
| 8745 | streaming: false, |
| 8746 | }, |
| 8747 | HistoryCell::Assistant { |
| 8748 | content: "a2".into(), |
| 8749 | streaming: false, |
| 8750 | }, |
| 8751 | HistoryCell::User { |
| 8752 | content: "second prompt".into(), |
| 8753 | }, |
| 8754 | HistoryCell::Assistant { |
| 8755 | content: "b1".into(), |
| 8756 | streaming: false, |
| 8757 | }, |
| 8758 | ]; |
| 8759 | let meta = pin_meta(&[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]); |
| 8760 | let map: Vec<usize> = (0..5).collect(); |
| 8761 | |
| 8762 | // One row before the newest prompt reaches the screen: still pinned |
| 8763 | // to the newest prompt (its first line sits above a viewport starting |
| 8764 | // at 4). |
| 8765 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 4, 40) |
| 8766 | .expect("the newest prompt is still pinned one row above the viewport"); |
| 8767 | assert!(pin_text(&pin).contains("second prompt")); |
| 8768 | assert_eq!(message, 3); |
| 8769 | |
| 8770 | // The newest prompt's first line is now the top row itself: hand over |
| 8771 | // to the previous turn immediately, with no gap in between. |
| 8772 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 3, 40) |
| 8773 | .expect("the header must hand over instead of blinking out"); |
| 8774 | assert!(pin_text(&pin).contains("first prompt")); |
| 8775 | assert_eq!(message, 0); |
| 8776 | |
| 8777 | // Scrolling further keeps the previous turn pinned while its content |
| 8778 | // fills the top of the screen. |
| 8779 | let (pin, message) = super::scrolled_user_prompt_pin(&history, &meta, &map, 2, 40) |
| 8780 | .expect("the previous turn stays pinned"); |
| 8781 | assert!(pin_text(&pin).contains("first prompt")); |
| 8782 | assert_eq!(message, 0); |
| 8783 | } |
| 8784 | |
| 8785 | #[test] |
| 8786 | fn pinned_prompt_reserves_header_without_hiding_tail_or_shifting_mouse_mapping() { |
| 8787 | let mut app = create_test_app(); |
| 8788 | app.pin_last_prompt = true; |
| 8789 | app.add_message(HistoryCell::User { |
| 8790 | content: "keep this goal visible".into(), |
| 8791 | }); |
| 8792 | for index in 0..8 { |
| 8793 | app.add_message(HistoryCell::Assistant { |
| 8794 | content: format!("answer {index}"), |
| 8795 | streaming: false, |
| 8796 | }); |
| 8797 | } |
| 8798 | |
| 8799 | let area = Rect::new(2, 5, 48, 5); |
| 8800 | let widget = ChatWidget::new_with_ocean_elapsed(&mut app, area, 0); |
| 8801 | let transcript_area = app |
| 8802 | .viewport |
| 8803 | .last_transcript_area |
| 8804 | .expect("transcript geometry recorded"); |
| 8805 | assert_eq!(transcript_area, Rect::new(2, 6, 48, 4)); |
| 8806 | assert_eq!(widget.transcript_area, transcript_area); |
| 8807 | assert_eq!(app.viewport.last_transcript_visible, 4); |
| 8808 | assert_eq!( |
| 8809 | app.viewport.last_transcript_top + app.viewport.last_transcript_visible, |
| 8810 | app.viewport.last_transcript_total, |
| 8811 | "reserving the header must still resolve the real transcript to its newest tail" |
| 8812 | ); |
| 8813 | let last_rendered: String = widget |
| 8814 | .lines |
| 8815 | .last() |
| 8816 | .expect("tail line rendered") |
| 8817 | .spans |
| 8818 | .iter() |
| 8819 | .map(|span| span.content.as_ref()) |
| 8820 | .collect(); |
| 8821 | let last_cached: String = app |
| 8822 | .viewport |
| 8823 | .transcript_cache |
| 8824 | .lines() |
| 8825 | .last() |
| 8826 | .expect("tail line cached") |
| 8827 | .spans |
| 8828 | .iter() |
| 8829 | .map(|span| span.content.as_ref()) |
| 8830 | .collect(); |
| 8831 | assert_eq!(last_rendered, last_cached); |
| 8832 | |
| 8833 | let pinned_row = MouseEvent { |
| 8834 | kind: MouseEventKind::Down(MouseButton::Right), |
| 8835 | column: area.x, |
| 8836 | row: area.y, |
| 8837 | modifiers: KeyModifiers::NONE, |
| 8838 | }; |
| 8839 | assert!( |
| 8840 | crate::tui::mouse_ui::selection_point_from_mouse(&app, pinned_row).is_none(), |
| 8841 | "the sticky header must not impersonate transcript line `top`" |
| 8842 | ); |
| 8843 | |
| 8844 | let meta = app.viewport.transcript_cache.line_meta(); |
| 8845 | let (line_offset, expected_cell) = meta[app.viewport.last_transcript_top..] |
| 8846 | .iter() |
| 8847 | .take(app.viewport.last_transcript_visible) |
| 8848 | .enumerate() |
| 8849 | .find_map(|(offset, meta)| meta.cell_line().map(|(cell, _)| (offset, cell))) |
| 8850 | .expect("visible transcript contains a cell row"); |
| 8851 | let body_row = MouseEvent { |
| 8852 | kind: MouseEventKind::Down(MouseButton::Right), |
| 8853 | column: transcript_area.x, |
| 8854 | row: transcript_area.y + u16::try_from(line_offset).unwrap(), |
| 8855 | modifiers: KeyModifiers::NONE, |
| 8856 | }; |
| 8857 | assert_eq!( |
| 8858 | crate::tui::mouse_ui::transcript_cell_index_from_mouse(&app, body_row), |
| 8859 | Some(expected_cell), |
| 8860 | "click, drag, selection, and right-click must share the actual body geometry" |
| 8861 | ); |
| 8862 | } |
| 8863 | |
| 8864 | /// The pinned header records its own hit box and jump target on the frame |
| 8865 | /// that paints it, so a click can return to the message it names. |
| 8866 | #[test] |
| 8867 | fn pinned_prompt_records_its_click_target_on_the_header_row() { |
| 8868 | let mut app = create_test_app(); |
| 8869 | app.pin_last_prompt = true; |
| 8870 | app.use_mouse_capture = true; |
| 8871 | app.add_message(HistoryCell::User { |
| 8872 | content: "keep this goal visible".into(), |
| 8873 | }); |
| 8874 | for index in 0..8 { |
| 8875 | app.add_message(HistoryCell::Assistant { |
| 8876 | content: format!("answer {index}"), |
| 8877 | streaming: false, |
| 8878 | }); |
| 8879 | } |
| 8880 | |
| 8881 | let area = Rect::new(2, 5, 48, 5); |
| 8882 | let widget = ChatWidget::new_with_ocean_elapsed(&mut app, area, 0); |
| 8883 | |
| 8884 | assert_eq!( |
| 8885 | widget.transcript_area, |
| 8886 | Rect::new(2, 6, 48, 4), |
| 8887 | "the header takes the first content row" |
| 8888 | ); |
| 8889 | assert_eq!( |
| 8890 | app.viewport.pinned_prompt_area, |
| 8891 | Some(Rect { |
| 8892 | x: 2, |
| 8893 | y: 5, |
| 8894 | width: 48, |
| 8895 | height: 1, |
| 8896 | }), |
| 8897 | "the hit box must cover the painted header row" |
| 8898 | ); |
| 8899 | assert_eq!( |
| 8900 | app.viewport.pinned_prompt_message, |
| 8901 | Some(0), |
| 8902 | "the header must record the user message it names" |
| 8903 | ); |
| 8904 | |
| 8905 | // Without mouse capture the header stays decorative: no hit box. |
| 8906 | app.use_mouse_capture = false; |
| 8907 | let _ = ChatWidget::new_with_ocean_elapsed(&mut app, area, 0); |
| 8908 | assert!(app.viewport.pinned_prompt_area.is_none()); |
| 8909 | } |
| 8910 | |
| 8911 | /// Reserving the header row must re-resolve against the final viewport: |
| 8912 | /// when the newest prompt's first line is exactly the full-height top row |
| 8913 | /// (a turn that fills the screen), the reserved viewport moves that line |
| 8914 | /// above the body, and the header must name the newest prompt instead of |
| 8915 | /// hiding it behind an older prompt's header. |
| 8916 | #[test] |
| 8917 | fn pin_helper_repins_against_the_reserved_viewport() { |
| 8918 | let mut app = create_test_app(); |
| 8919 | app.pin_last_prompt = true; |
| 8920 | app.use_mouse_capture = true; |
| 8921 | app.add_message(HistoryCell::User { |
| 8922 | content: "older prompt".into(), |
| 8923 | }); |
| 8924 | app.add_message(HistoryCell::Assistant { |
| 8925 | content: "older reply".into(), |
| 8926 | streaming: false, |
| 8927 | }); |
| 8928 | app.add_message(HistoryCell::User { |
| 8929 | content: "newest prompt".into(), |
| 8930 | }); |
| 8931 | app.add_message(HistoryCell::Assistant { |
| 8932 | content: "newest reply".into(), |
| 8933 | streaming: false, |
| 8934 | }); |
| 8935 | |
| 8936 | // Learn the layout at a roomy height: total rendered lines and the |
| 8937 | // newest prompt's first line. |
| 8938 | let roomy = Rect::new(0, 0, 80, 40); |
| 8939 | let _ = ChatWidget::new_with_ocean_elapsed(&mut app, roomy, 0); |
| 8940 | let meta = app.viewport.transcript_cache.line_meta(); |
| 8941 | let newest_message = app.history.len() - 2; |
| 8942 | let newest_first = meta |
| 8943 | .iter() |
| 8944 | .position(|meta| { |
| 8945 | matches!( |
| 8946 | meta, |
| 8947 | TranscriptLineMeta::CellLine { |
| 8948 | cell_index, |
| 8949 | line_in_cell: 0, |
| 8950 | .. |
| 8951 | } if *cell_index == newest_message |
| 8952 | ) |
| 8953 | }) |
| 8954 | .expect("newest prompt rendered"); |
| 8955 | let total = meta.len(); |
| 8956 | assert!(total > newest_first, "the newest turn has body lines"); |
| 8957 | let height = u16::try_from(total - newest_first).expect("fits"); |
| 8958 | assert!(height > 1, "need at least one body row under the header"); |
| 8959 | |
| 8960 | // Re-render at exactly that height so the tail viewport starts on the |
| 8961 | // newest prompt's first line. |
| 8962 | let tight = Rect::new(0, 0, 80, height); |
| 8963 | let widget = ChatWidget::new_with_ocean_elapsed(&mut app, tight, 0); |
| 8964 | let pinned_text: String = widget.lines[0] |
| 8965 | .spans |
| 8966 | .iter() |
| 8967 | .map(|span| span.content.as_ref()) |
| 8968 | .collect(); |
| 8969 | assert!( |
| 8970 | pinned_text.contains("newest prompt"), |
| 8971 | "the header must re-resolve for the reserved viewport, got {pinned_text:?}" |
| 8972 | ); |
| 8973 | } |
| 8974 | |
| 8975 | /// Render → click the header → the viewport lands on the named message: |
| 8976 | /// the recorder and the mouse handler are exercised together, not each |
| 8977 | /// half against a hand-written fixture. |
| 8978 | #[test] |
| 8979 | fn pinned_prompt_click_lands_on_the_named_message_end_to_end() { |
| 8980 | let mut app = create_test_app(); |
| 8981 | app.pin_last_prompt = true; |
| 8982 | app.use_mouse_capture = true; |
| 8983 | app.add_message(HistoryCell::User { |
| 8984 | content: "target prompt".into(), |
| 8985 | }); |
| 8986 | for index in 0..8 { |
| 8987 | app.add_message(HistoryCell::Assistant { |
| 8988 | content: format!("answer {index}"), |
| 8989 | streaming: false, |
| 8990 | }); |
| 8991 | } |
| 8992 | app.add_message(HistoryCell::User { |
| 8993 | content: "newest prompt".into(), |
| 8994 | }); |
| 8995 | for index in 0..8 { |
| 8996 | app.add_message(HistoryCell::Assistant { |
| 8997 | content: format!("latest {index}"), |
| 8998 | streaming: false, |
| 8999 | }); |
| 9000 | } |
| 9001 | |
| 9002 | let area = Rect::new(0, 0, 60, 8); |
| 9003 | let _ = ChatWidget::new_with_ocean_elapsed(&mut app, area, 0); |
| 9004 | let header = app |
| 9005 | .viewport |
| 9006 | .pinned_prompt_area |
| 9007 | .expect("header painted above the scrolled viewport"); |
| 9008 | let expected = app |
| 9009 | .pinned_prompt_target_line() |
| 9010 | .expect("the named message is rendered"); |
| 9011 | |
| 9012 | let events = crate::tui::mouse_ui::handle_mouse_event( |
| 9013 | &mut app, |
| 9014 | MouseEvent { |
| 9015 | kind: MouseEventKind::Down(MouseButton::Left), |
| 9016 | column: header.x + 1, |
| 9017 | row: header.y, |
| 9018 | modifiers: KeyModifiers::NONE, |
| 9019 | }, |
| 9020 | Instant::now(), |
| 9021 | ); |
| 9022 | |
| 9023 | assert!(events.is_empty()); |
| 9024 | assert_eq!( |
| 9025 | app.viewport.transcript_scroll, |
| 9026 | TranscriptScroll::at_line(expected) |
| 9027 | ); |
| 9028 | assert_eq!(app.viewport.pending_scroll_delta, 0); |
| 9029 | } |
| 9030 | |
| 9031 | #[test] |
| 9032 | fn fish_glyph_always_matches_screen_direction() { |
| 9033 | assert_eq!(fish_mark(true), "><>"); |
| 9034 | assert_eq!(fish_mark(false), "<><"); |
| 9035 | assert!(fish_heading(8, 9, 10, false)); |
| 9036 | assert!(!fish_heading(10, 9, 8, true)); |
| 9037 | assert!(fish_heading(8, 9, 9, false)); |
| 9038 | assert!(!fish_heading(10, 9, 9, true)); |
| 9039 | |
| 9040 | // Mirrored tracks are the regression case: a forward path flag can |
| 9041 | // correspond to decreasing screen x. Heading follows x, not the flag. |
| 9042 | assert!(!fish_heading(74, 73, 72, true)); |
| 9043 | } |
| 9044 | |
| 9045 | /// Render a chat field carrying `rows` of history and return its rows. |
| 9046 | fn history_field_rows(rows: usize) -> Vec<String> { |
| 9047 | let mut app = create_test_app(); |
| 9048 | app.low_motion = false; |
| 9049 | app.fancy_animations = true; |
| 9050 | for index in 0..rows { |
| 9051 | app.add_message(HistoryCell::Assistant { |
| 9052 | content: format!("history row {index}"), |
| 9053 | streaming: false, |
| 9054 | }); |
| 9055 | } |
| 9056 | app.viewport.transcript_scroll = TranscriptScroll::at_line(0); |
| 9057 | let area = Rect::new(0, 0, 100, 20); |
| 9058 | let widget = ChatWidget::new(&mut app, area); |
| 9059 | assert!(!widget.ambient_life); |
| 9060 | assert!(!widget.ocean_animated); |
| 9061 | let mut buf = Buffer::empty(area); |
| 9062 | widget.render(area, &mut buf); |
| 9063 | buffer_text(&buf, area) |
| 9064 | .lines() |
| 9065 | .map(str::to_string) |
| 9066 | .collect() |
| 9067 | } |
| 9068 | |
| 9069 | #[test] |
| 9070 | fn browsing_history_holds_no_fish() { |
| 9071 | let rows = history_field_rows(4); |
| 9072 | let rendered = rows.join("\n"); |
| 9073 | for index in 0..4 { |
| 9074 | assert!( |
| 9075 | rendered.contains(&format!("history row {index}")), |
| 9076 | "ambient life damaged history row {index}:\n{rendered}" |
| 9077 | ); |
| 9078 | } |
| 9079 | } |
| 9080 | |
| 9081 | fn ambient_life_cells(app: &mut App, area: Rect, elapsed: u128) -> usize { |
| 9082 | let alive = ChatWidget::new_with_ocean_elapsed(app, area, elapsed); |
| 9083 | let mut still = ChatWidget::new_with_ocean_elapsed(app, area, elapsed); |
| 9084 | still.ocean_column = alive.ocean_column; |
| 9085 | still.ambient_life = false; |
| 9086 | let mut alive_buf = Buffer::empty(area); |
| 9087 | alive.render(area, &mut alive_buf); |
| 9088 | let mut still_buf = Buffer::empty(area); |
| 9089 | still.render(area, &mut still_buf); |
| 9090 | alive_buf |
| 9091 | .content |
| 9092 | .iter() |
| 9093 | .zip(&still_buf.content) |
| 9094 | .filter(|(a, b)| a != b) |
| 9095 | .count() |
| 9096 | } |
| 9097 | |
| 9098 | fn assert_life_keeps_clear_of_text(app: &mut App, area: Rect) -> String { |
| 9099 | let mut painted_any = false; |
| 9100 | let mut last = String::new(); |
| 9101 | for elapsed in [0, 4_000, 9_000, 15_000, 26_000] { |
| 9102 | let alive = ChatWidget::new_with_ocean_elapsed(app, area, elapsed); |
| 9103 | assert!(alive.ambient_life); |
| 9104 | let mut still = ChatWidget::new_with_ocean_elapsed(app, area, elapsed); |
| 9105 | still.ocean_column = alive.ocean_column; |
| 9106 | still.ambient_life = false; |
| 9107 | let mut alive_buf = Buffer::empty(area); |
| 9108 | alive.render(area, &mut alive_buf); |
| 9109 | let mut still_buf = Buffer::empty(area); |
| 9110 | still.render(area, &mut still_buf); |
| 9111 | let text_columns = area.right().saturating_sub(1); |
| 9112 | let is_text = |x: i32, y: i32| { |
| 9113 | x >= i32::from(area.left()) |
| 9114 | && x < i32::from(text_columns) |
| 9115 | && y >= i32::from(area.top()) |
| 9116 | && y < i32::from(area.bottom()) |
| 9117 | && still_buf[(x as u16, y as u16)].symbol() != " " |
| 9118 | }; |
| 9119 | last = buffer_text(&alive_buf, area); |
| 9120 | for y in area.top()..area.bottom() { |
| 9121 | for x in area.left()..text_columns { |
| 9122 | if alive_buf[(x, y)] == still_buf[(x, y)] { |
| 9123 | continue; |
| 9124 | } |
| 9125 | painted_any = true; |
| 9126 | for dy in -1..=1 { |
| 9127 | for dx in -2..=2 { |
| 9128 | assert!( |
| 9129 | !is_text(i32::from(x) + dx, i32::from(y) + dy), |
| 9130 | "life at ({x}, {y}) touches text at t={elapsed}:\n{last}" |
| 9131 | ); |
| 9132 | } |
| 9133 | } |
| 9134 | } |
| 9135 | } |
| 9136 | } |
| 9137 | assert!(painted_any, "the ocean painted no life at all:\n{last}"); |
| 9138 | last |
| 9139 | } |
| 9140 | |
| 9141 | #[test] |
| 9142 | fn browsing_history_holds_ocean_life_and_completion_still() { |
| 9143 | let mut app = create_test_app(); |
| 9144 | app.low_motion = false; |
| 9145 | app.fancy_animations = true; |
| 9146 | for index in 0..18 { |
| 9147 | app.add_message(HistoryCell::Assistant { |
| 9148 | content: format!("history turn {index:02}"), |
| 9149 | streaming: false, |
| 9150 | }); |
| 9151 | } |
| 9152 | app.is_loading = true; |
| 9153 | app.runtime_turn_status = Some("in_progress".to_string()); |
| 9154 | app.turn_started_at = Some( |
| 9155 | Instant::now() |
| 9156 | .checked_sub(std::time::Duration::from_millis(900)) |
| 9157 | .expect("recent turn start"), |
| 9158 | ); |
| 9159 | app.ocean_completion_started_at = Some(Instant::now()); |
| 9160 | app.viewport.transcript_scroll = TranscriptScroll::at_line(0); |
| 9161 | |
| 9162 | let widget = ChatWidget::new(&mut app, Rect::new(0, 0, 80, 24)); |
| 9163 | assert_eq!(widget.life_presence_fixed, 0); |
| 9164 | } |
| 9165 | |
| 9166 | #[test] |
| 9167 | fn active_tail_life_keeps_clear_of_text() { |
| 9168 | let mut app = create_test_app(); |
| 9169 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 9170 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 9171 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 9172 | app.low_motion = false; |
| 9173 | app.fancy_animations = true; |
| 9174 | for index in 0..18 { |
| 9175 | app.add_message(HistoryCell::Assistant { |
| 9176 | content: format!("release check {index:02}"), |
| 9177 | streaming: false, |
| 9178 | }); |
| 9179 | } |
| 9180 | app.is_loading = true; |
| 9181 | app.runtime_turn_status = Some("in_progress".to_string()); |
| 9182 | app.turn_started_at = Some( |
| 9183 | Instant::now() |
| 9184 | .checked_sub(std::time::Duration::from_millis(900)) |
| 9185 | .expect("recent turn start"), |
| 9186 | ); |
| 9187 | let area = Rect::new(0, 0, 80, 24); |
| 9188 | assert!(ChatWidget::new_with_ocean_elapsed(&mut app, area, 0).ocean_animated); |
| 9189 | let rendered = assert_life_keeps_clear_of_text(&mut app, area); |
| 9190 | assert!(rendered.contains("release check 17"), "{rendered}"); |
| 9191 | } |
| 9192 | |
| 9193 | #[test] |
| 9194 | fn ocean_life_moves_while_a_turn_runs_and_holds_still_when_idle() { |
| 9195 | fn life_cells(app: &mut App, area: Rect, elapsed: u128) -> Vec<(u16, u16, String)> { |
| 9196 | let alive = ChatWidget::new_with_ocean_elapsed(app, area, elapsed); |
| 9197 | let mut still = ChatWidget::new_with_ocean_elapsed(app, area, elapsed); |
| 9198 | still.ocean_column = alive.ocean_column; |
| 9199 | still.ambient_life = false; |
| 9200 | let mut alive_buf = Buffer::empty(area); |
| 9201 | alive.render(area, &mut alive_buf); |
| 9202 | let mut still_buf = Buffer::empty(area); |
| 9203 | still.render(area, &mut still_buf); |
| 9204 | let mut cells = Vec::new(); |
| 9205 | for y in area.top()..area.bottom() { |
| 9206 | for x in area.left()..area.right() { |
| 9207 | if alive_buf[(x, y)] != still_buf[(x, y)] { |
| 9208 | cells.push((x, y, alive_buf[(x, y)].symbol().to_string())); |
| 9209 | } |
| 9210 | } |
| 9211 | } |
| 9212 | cells |
| 9213 | } |
| 9214 | |
| 9215 | let mut app = create_test_app(); |
| 9216 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 9217 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 9218 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 9219 | app.low_motion = false; |
| 9220 | app.fancy_animations = true; |
| 9221 | app.add_message(HistoryCell::Assistant { |
| 9222 | content: "release receipt".to_string(), |
| 9223 | streaming: false, |
| 9224 | }); |
| 9225 | let area = Rect::new(0, 0, 80, 24); |
| 9226 | let start = Instant::now(); |
| 9227 | |
| 9228 | app.is_loading = true; |
| 9229 | app.runtime_turn_status = Some("in_progress".to_string()); |
| 9230 | app.turn_started_at = Some(start); |
| 9231 | app.ambient_clock_ms = 9_000; |
| 9232 | assert!(!app.ambient_idle_settled(true, start)); |
| 9233 | let early = life_cells(&mut app, area, 4_000); |
| 9234 | let late = life_cells(&mut app, area, 9_000); |
| 9235 | assert!(!early.is_empty() && !late.is_empty()); |
| 9236 | assert_ne!(early, late, "a running turn must move the ocean"); |
| 9237 | assert!(crate::tui::ui::underwater_life_motion_requested( |
| 9238 | &app, false, false |
| 9239 | )); |
| 9240 | |
| 9241 | app.is_loading = false; |
| 9242 | app.runtime_turn_status = Some("completed".to_string()); |
| 9243 | app.turn_started_at = None; |
| 9244 | assert!(!app.ambient_idle_settled(false, start)); |
| 9245 | let settle = std::time::Duration::from_millis(App::AMBIENT_IDLE_SETTLE_MS + 1); |
| 9246 | assert!(app.ambient_idle_settled(false, start + settle)); |
| 9247 | assert!(!crate::tui::ui::underwater_life_motion_requested( |
| 9248 | &app, false, true |
| 9249 | )); |
| 9250 | let held = life_cells(&mut app, area, 9_000); |
| 9251 | let after_keystrokes = life_cells(&mut app, area, 13_000); |
| 9252 | assert!(!held.is_empty(), "a settled ocean keeps its creatures"); |
| 9253 | assert_eq!( |
| 9254 | held, after_keystrokes, |
| 9255 | "an idle redraw must not step the ocean" |
| 9256 | ); |
| 9257 | |
| 9258 | app.low_motion = true; |
| 9259 | assert!(!app.ambient_idle_settled(true, start + settle)); |
| 9260 | assert!(!crate::tui::ui::underwater_life_motion_requested( |
| 9261 | &app, false, false |
| 9262 | )); |
| 9263 | assert!(life_cells(&mut app, area, 4_000).is_empty()); |
| 9264 | } |
| 9265 | |
| 9266 | #[test] |
| 9267 | fn completed_turn_life_keeps_clear_of_text() { |
| 9268 | let mut app = create_test_app(); |
| 9269 | app.theme_id = codewhale_palette::ThemeId::Underwater; |
| 9270 | app.ui_theme = palette::UNDERWATER_UI_THEME; |
| 9271 | app.viewport.ocean_caps = Some(test_native_ocean_caps()); |
| 9272 | app.low_motion = false; |
| 9273 | app.fancy_animations = true; |
| 9274 | app.add_message(HistoryCell::Assistant { |
| 9275 | content: "release receipt".to_string(), |
| 9276 | streaming: false, |
| 9277 | }); |
| 9278 | app.runtime_turn_status = Some("completed".to_string()); |
| 9279 | app.ocean_completion_started_at = Some(Instant::now()); |
| 9280 | let area = Rect::new(0, 0, 80, 24); |
| 9281 | let rendered = assert_life_keeps_clear_of_text(&mut app, area); |
| 9282 | assert!(rendered.contains("release receipt"), "{rendered}"); |
| 9283 | } |
| 9284 | |
| 9285 | #[test] |
| 9286 | fn a_field_full_of_transcript_holds_no_fish() { |
| 9287 | // Full-width prose really does claim the whole field; short status |
| 9288 | // lines no longer impersonate this fixture. |
| 9289 | let mut app = create_test_app(); |
| 9290 | app.low_motion = false; |
| 9291 | app.fancy_animations = true; |
| 9292 | for _ in 0..30 { |
| 9293 | app.add_message(HistoryCell::Assistant { |
| 9294 | content: "X".repeat(100), |
| 9295 | streaming: false, |
| 9296 | }); |
| 9297 | } |
| 9298 | app.viewport.transcript_scroll = TranscriptScroll::at_line(0); |
| 9299 | let area = Rect::new(0, 0, 100, 20); |
| 9300 | let widget = ChatWidget::new_with_ocean_elapsed(&mut app, area, 0); |
| 9301 | let mut buf = Buffer::empty(area); |
| 9302 | widget.render(area, &mut buf); |
| 9303 | let rendered = buffer_text(&buf, area); |
| 9304 | assert_eq!( |
| 9305 | ambient_life_cells(&mut app, area, 0), |
| 9306 | 0, |
| 9307 | "a full transcript is not an aquarium:\n{rendered}" |
| 9308 | ); |
| 9309 | } |
| 9310 | |
| 9311 | fn todo_write_cell(item: Option<&str>) -> HistoryCell { |
| 9312 | let items = item.map_or_else( |
| 9313 | || "[]".to_string(), |
| 9314 | |content| format!(r#"[{{"id":1,"content":"{content}","status":"pending"}}]"#), |
| 9315 | ); |
| 9316 | let count = usize::from(item.is_some()); |
| 9317 | HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 9318 | name: "todo_write".to_string(), |
| 9319 | status: ToolStatus::Success, |
| 9320 | input_summary: Some(format!("todos: <{count} items>")), |
| 9321 | output: Some(format!( |
| 9322 | "Todo list updated ({count} items, 0% settled)\n{{\"items\":{items},\"completion_pct\":0}}" |
| 9323 | )), |
| 9324 | prompts: None, |
| 9325 | spillover_path: None, |
| 9326 | output_summary: None, |
| 9327 | is_diff: false, |
| 9328 | })) |
| 9329 | } |
| 9330 | |
| 9331 | #[test] |
| 9332 | fn todo_write_renders_only_the_latest_successful_snapshot() { |
| 9333 | let mut app = create_test_app(); |
| 9334 | app.add_message(todo_write_cell(Some("stale task"))); |
| 9335 | app.add_message(HistoryCell::Assistant { |
| 9336 | content: "working".to_string(), |
| 9337 | streaming: false, |
| 9338 | }); |
| 9339 | app.add_message(todo_write_cell(Some("current task"))); |
| 9340 | |
| 9341 | let area = Rect::new(0, 0, 80, 20); |
| 9342 | let mut buf = Buffer::empty(area); |
| 9343 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 9344 | let rendered = buffer_text(&buf, area); |
| 9345 | |
| 9346 | assert!(!rendered.contains("stale task"), "{rendered}"); |
| 9347 | assert!(rendered.contains("current task"), "{rendered}"); |
| 9348 | assert_eq!(app.collapsed_cell_map, vec![1, 2]); |
| 9349 | } |
| 9350 | |
| 9351 | #[test] |
| 9352 | fn empty_todo_write_hides_the_previous_snapshot() { |
| 9353 | let mut app = create_test_app(); |
| 9354 | app.add_message(todo_write_cell(Some("finished task"))); |
| 9355 | let active = app.active_cell.get_or_insert_with(ActiveCell::new); |
| 9356 | active.push_untracked(todo_write_cell(None)); |
| 9357 | app.bump_active_cell_revision(); |
| 9358 | |
| 9359 | let area = Rect::new(0, 0, 80, 20); |
| 9360 | let mut buf = Buffer::empty(area); |
| 9361 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 9362 | let rendered = buffer_text(&buf, area); |
| 9363 | |
| 9364 | assert!(!rendered.contains("finished task"), "{rendered}"); |
| 9365 | assert!(!rendered.contains("todo_write"), "{rendered}"); |
| 9366 | assert!(app.collapsed_cell_map.is_empty()); |
| 9367 | } |
| 9368 | |
| 9369 | #[test] |
| 9370 | fn todo_replacement_preserves_tool_runs_and_full_transcript_history() { |
| 9371 | use crate::tui::{live_transcript::LiveTranscriptOverlay, views::ModalView}; |
| 9372 | |
| 9373 | let mut app = create_test_app(); |
| 9374 | app.low_motion = true; |
| 9375 | app.show_tool_details = true; |
| 9376 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 9377 | app.tool_collapse_threshold = 3; |
| 9378 | add_dense_tool_run(&mut app); |
| 9379 | app.add_message(HistoryCell::Assistant { |
| 9380 | content: "checkpoint".to_string(), |
| 9381 | streaming: false, |
| 9382 | }); |
| 9383 | app.add_message(todo_write_cell(Some("stale task"))); |
| 9384 | let active = app.active_cell.get_or_insert_with(ActiveCell::new); |
| 9385 | active.push_untracked(success_tool_cell("read_file")); |
| 9386 | active.push_untracked(success_tool_cell("web_search")); |
| 9387 | app.bump_active_cell_revision(); |
| 9388 | |
| 9389 | let area = Rect::new(0, 0, 100, 40); |
| 9390 | let mut buf = Buffer::empty(area); |
| 9391 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 9392 | assert_eq!(app.collapsed_cell_map, vec![0, 3, 4]); |
| 9393 | |
| 9394 | app.active_cell |
| 9395 | .as_mut() |
| 9396 | .unwrap() |
| 9397 | .push_untracked(todo_write_cell(Some("current task"))); |
| 9398 | app.bump_active_cell_revision(); |
| 9399 | let mut buf = Buffer::empty(area); |
| 9400 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 9401 | let rendered = buffer_text(&buf, area); |
| 9402 | assert_eq!(app.collapsed_cell_map, vec![0, 3, 5, 6, 7]); |
| 9403 | assert!( |
| 9404 | rendered.contains("Explored 2 files, 1 search"), |
| 9405 | "{rendered}" |
| 9406 | ); |
| 9407 | assert!(rendered.contains("read_file.txt"), "{rendered}"); |
| 9408 | assert!(rendered.contains("web_search.txt"), "{rendered}"); |
| 9409 | assert!(rendered.contains("current task"), "{rendered}"); |
| 9410 | assert!(!rendered.contains("stale task"), "{rendered}"); |
| 9411 | |
| 9412 | let mut repeated = Buffer::empty(area); |
| 9413 | ChatWidget::new(&mut app, area).render(area, &mut repeated); |
| 9414 | assert_eq!(buffer_text(&repeated, area), rendered); |
| 9415 | assert_eq!(app.history.len(), 5); |
| 9416 | assert_eq!(app.active_cell.as_ref().unwrap().entries().len(), 3); |
| 9417 | |
| 9418 | let mut overlay = LiveTranscriptOverlay::new(); |
| 9419 | overlay.refresh_from_app(&mut app); |
| 9420 | let area = Rect::new(0, 0, 100, 60); |
| 9421 | let mut buf = Buffer::empty(area); |
| 9422 | ModalView::render(&overlay, area, &mut buf); |
| 9423 | let full_history = buffer_text(&buf, area); |
| 9424 | assert!(full_history.contains("stale task"), "{full_history}"); |
| 9425 | assert!(full_history.contains("current task"), "{full_history}"); |
| 9426 | } |
| 9427 | |
| 9428 | /// Probe: confirm `cell.lines_with_motion` returns no Line whose total |
| 9429 | /// visual width exceeds the requested area width, even for pathological |
| 9430 | /// long single-line tool results. |
| 9431 | #[test] |
| 9432 | fn long_tool_result_lines_fit_requested_width() { |
| 9433 | let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 9434 | name: "todo_write".to_string(), |
| 9435 | status: ToolStatus::Success, |
| 9436 | input_summary: Some("items: <2 items>".to_string()), |
| 9437 | output: Some("hello world ".repeat(420)), |
| 9438 | prompts: None, |
| 9439 | spillover_path: None, |
| 9440 | output_summary: None, |
| 9441 | is_diff: false, |
| 9442 | })); |
| 9443 | for width in [40u16, 80, 111, 165] { |
| 9444 | let lines = cell.lines(width); |
| 9445 | for (idx, line) in lines.iter().enumerate() { |
| 9446 | let visual: usize = line |
| 9447 | .spans |
| 9448 | .iter() |
| 9449 | .map(|s| UnicodeWidthStr::width(s.content.as_ref())) |
| 9450 | .sum(); |
| 9451 | // Card-rail prefix (╭/│/╰ + space) adds 2 chars. |
| 9452 | let rail_adjust = if line.spans.first().is_some_and(|s| { |
| 9453 | let c = s.content.as_ref(); |
| 9454 | c == "\u{256D} " || c == "\u{2502} " || c == "\u{2570} " |
| 9455 | }) { |
| 9456 | 2usize |
| 9457 | } else { |
| 9458 | 0 |
| 9459 | }; |
| 9460 | assert!( |
| 9461 | visual.saturating_sub(rail_adjust) <= usize::from(width), |
| 9462 | "line {idx} at width {width} has visual width {visual} > {width}" |
| 9463 | ); |
| 9464 | } |
| 9465 | } |
| 9466 | } |
| 9467 | |
| 9468 | /// Regression: a long single-line tool result must not write any cells |
| 9469 | /// outside the chat content area (issue #36 — sidebar gutter bleed). |
| 9470 | /// |
| 9471 | /// We render `ChatWidget` into a buffer that is wider than the chat area |
| 9472 | /// (simulating the sidebar split) and assert every cell to the right of |
| 9473 | /// `chat_area` is still the default empty cell. |
| 9474 | #[test] |
| 9475 | fn chat_widget_does_not_bleed_into_sidebar_for_long_tool_result() { |
| 9476 | // Reproduces the actual `todo_write` output shape: a status line, |
| 9477 | // a newline, then a pretty-printed JSON payload with long string |
| 9478 | // values. Run at several widths since the leak in the issue was |
| 9479 | // observed at ~165 cols. |
| 9480 | let cases: Vec<(u16, u16)> = vec![(80, 50), (120, 80), (165, 111), (200, 140)]; |
| 9481 | for (total_width, chat_width) in cases { |
| 9482 | let mut app = create_test_app(); |
| 9483 | let long_value: String = "hello world ".repeat(420); |
| 9484 | let json_payload = format!( |
| 9485 | "{{\n \"items\": [\n {{ \"id\": 1, \"content\": \"{long_value}\", \"status\": \"pending\" }}\n ]\n}}" |
| 9486 | ); |
| 9487 | let output = format!("Todo list updated (1 items, 0% complete)\n{json_payload}"); |
| 9488 | app.add_message(HistoryCell::Tool(ToolCell::Generic(GenericToolCell { |
| 9489 | name: "todo_write".to_string(), |
| 9490 | status: ToolStatus::Success, |
| 9491 | input_summary: Some("todos: <1 items>".to_string()), |
| 9492 | output: Some(output), |
| 9493 | prompts: None, |
| 9494 | spillover_path: None, |
| 9495 | output_summary: None, |
| 9496 | is_diff: false, |
| 9497 | }))); |
| 9498 | |
| 9499 | let height: u16 = 30; |
| 9500 | let chat_area = Rect { |
| 9501 | x: 0, |
| 9502 | y: 0, |
| 9503 | width: chat_width, |
| 9504 | height, |
| 9505 | }; |
| 9506 | let full_area = Rect { |
| 9507 | x: 0, |
| 9508 | y: 0, |
| 9509 | width: total_width, |
| 9510 | height, |
| 9511 | }; |
| 9512 | let mut buf = Buffer::empty(full_area); |
| 9513 | |
| 9514 | let widget = ChatWidget::new(&mut app, chat_area); |
| 9515 | widget.render(chat_area, &mut buf); |
| 9516 | |
| 9517 | // Every cell outside chat_area should remain at default. If the |
| 9518 | // widget bled, we'll see leftover symbols. |
| 9519 | let default_symbol = " "; |
| 9520 | for y in 0..height { |
| 9521 | for x in chat_width..total_width { |
| 9522 | let cell = &buf[(x, y)]; |
| 9523 | let sym = cell.symbol(); |
| 9524 | assert!( |
| 9525 | sym == default_symbol || sym.is_empty(), |
| 9526 | "[{total_width}x{height}, chat={chat_width}] cell ({x},{y}) leaked content {sym:?} outside chat_area" |
| 9527 | ); |
| 9528 | } |
| 9529 | } |
| 9530 | } |
| 9531 | } |
| 9532 | |
| 9533 | #[test] |
| 9534 | fn chat_widget_uses_configured_surface_background() { |
| 9535 | let mut app = create_test_app(); |
| 9536 | let custom = ratatui::style::Color::Rgb(26, 27, 38); |
| 9537 | app.theme_id = codewhale_palette::ThemeId::Whale; |
| 9538 | app.ui_theme = palette::UI_THEME.with_background_color(custom); |
| 9539 | app.add_message(HistoryCell::Assistant { |
| 9540 | content: "ready".to_string(), |
| 9541 | streaming: false, |
| 9542 | }); |
| 9543 | |
| 9544 | let area = Rect { |
| 9545 | x: 0, |
| 9546 | y: 0, |
| 9547 | width: 30, |
| 9548 | height: 5, |
| 9549 | }; |
| 9550 | let mut buf = Buffer::empty(area); |
| 9551 | let widget = ChatWidget::new(&mut app, area); |
| 9552 | widget.render(area, &mut buf); |
| 9553 | |
| 9554 | assert_eq!(buf[(area.x, area.y)].bg, custom); |
| 9555 | assert_eq!( |
| 9556 | buf[(area.x + area.width - 1, area.y + area.height - 1)].bg, |
| 9557 | custom |
| 9558 | ); |
| 9559 | } |
| 9560 | |
| 9561 | #[test] |
| 9562 | fn chat_widget_does_not_render_turn_receipt_as_transcript_content() { |
| 9563 | let mut app = create_test_app(); |
| 9564 | for i in 0..8 { |
| 9565 | app.add_message(HistoryCell::Assistant { |
| 9566 | content: format!("assistant line {i}"), |
| 9567 | streaming: false, |
| 9568 | }); |
| 9569 | } |
| 9570 | app.set_receipt_text("✓ turn completed · 2 tool(s) used"); |
| 9571 | |
| 9572 | let area = Rect { |
| 9573 | x: 0, |
| 9574 | y: 0, |
| 9575 | width: 48, |
| 9576 | height: 6, |
| 9577 | }; |
| 9578 | let mut buf = Buffer::empty(area); |
| 9579 | let widget = ChatWidget::new(&mut app, area); |
| 9580 | widget.render(area, &mut buf); |
| 9581 | let rendered = buffer_text(&buf, area); |
| 9582 | |
| 9583 | assert!(!rendered.contains("turn completed")); |
| 9584 | assert!( |
| 9585 | rendered.contains("assistant line 7"), |
| 9586 | "receipt should not displace the latest transcript line: {rendered:?}" |
| 9587 | ); |
| 9588 | } |
| 9589 | |
| 9590 | /// Regression: when the transcript scrollbar is visible, the rightmost |
| 9591 | /// content column must remain readable (the scrollbar gets its own |
| 9592 | /// 1-column gutter rather than overdrawing chat content). |
| 9593 | #[test] |
| 9594 | fn chat_widget_reserves_scrollbar_gutter_when_scrollbar_visible() { |
| 9595 | let content_hash = "0123456789abcdef".repeat(4); |
| 9596 | let capability_hash = "fedcba9876543210".repeat(4); |
| 9597 | // System continuations paint a left rail as well as the right scrollbar. |
| 9598 | // Neither decoration is part of a wrapped trust token. |
| 9599 | let token_text = |text: &str| -> String { |
| 9600 | text.chars() |
| 9601 | .filter(|ch| !ch.is_whitespace() && !matches!(ch, '│' | '┃' | '\u{258f}')) |
| 9602 | .collect() |
| 9603 | }; |
| 9604 | for filtered in [false, true] { |
| 9605 | let mut app = create_test_app(); |
| 9606 | app.low_motion = true; |
| 9607 | app.fancy_animations = false; |
| 9608 | app.use_mouse_capture = false; |
| 9609 | for i in 0..20 { |
| 9610 | app.add_message(HistoryCell::User { |
| 9611 | content: format!("user message {i}"), |
| 9612 | }); |
| 9613 | } |
| 9614 | app.add_message(HistoryCell::System { |
| 9615 | content: format!( |
| 9616 | "Content hash:\n{content_hash}\nCapability hash:\n{capability_hash}" |
| 9617 | ), |
| 9618 | }); |
| 9619 | if filtered { |
| 9620 | app.collapsed_cells.insert(0); |
| 9621 | } |
| 9622 | |
| 9623 | // Reuse the cache across scrollbar appearance, narrow-pane resizes, |
| 9624 | // and disappearance. Both ordinary and filtered histories must keep |
| 9625 | // every trust-token character in the painted terminal cells. |
| 9626 | for (width, height) in [ |
| 9627 | (40, 100), |
| 9628 | (40, 16), |
| 9629 | (58, 16), |
| 9630 | (60, 16), |
| 9631 | (80, 16), |
| 9632 | (40, 16), |
| 9633 | (40, 100), |
| 9634 | ] { |
| 9635 | let area = Rect::new(2, 1, width, height); |
| 9636 | let mut buf = Buffer::empty(area); |
| 9637 | let widget = ChatWidget::new(&mut app, area); |
| 9638 | assert_eq!(widget.scrollbar.is_some(), height == 16); |
| 9639 | widget.render(area, &mut buf); |
| 9640 | |
| 9641 | let rendered = buffer_text(&buf, area); |
| 9642 | let joined = token_text(&rendered); |
| 9643 | for hash in [&content_hash, &capability_hash] { |
| 9644 | assert!( |
| 9645 | joined.contains(hash.as_str()), |
| 9646 | "lost trust-token characters at {width}x{height}, filtered={filtered}: {rendered:?}" |
| 9647 | ); |
| 9648 | // The decoration filter must still reject actual overpaint: |
| 9649 | // replace the last hex cell on this token's first row with |
| 9650 | // a scrollbar, as in the reported narrow-pane failure. |
| 9651 | let y = (area.y..area.bottom()) |
| 9652 | .find(|&y| { |
| 9653 | buffer_text(&buf, Rect::new(area.x, y, width, 1)).contains(&hash[..16]) |
| 9654 | }) |
| 9655 | .expect("the first token segment is visible"); |
| 9656 | let x = (area.x..area.right()) |
| 9657 | .rev() |
| 9658 | .find(|&x| { |
| 9659 | let symbol = buf[(x, y)].symbol(); |
| 9660 | symbol.len() == 1 && symbol.as_bytes()[0].is_ascii_hexdigit() |
| 9661 | }) |
| 9662 | .expect("the token row contains hex cells"); |
| 9663 | let mut overpainted = buf.clone(); |
| 9664 | overpainted[(x, y)].set_symbol("│"); |
| 9665 | assert!( |
| 9666 | !token_text(&buffer_text(&overpainted, area)).contains(hash.as_str()), |
| 9667 | "the token check must reject a scrollbar-erased hex cell" |
| 9668 | ); |
| 9669 | } |
| 9670 | if widget.scrollbar.is_some() { |
| 9671 | for y in widget.transcript_area.y..widget.transcript_area.bottom() { |
| 9672 | assert!(matches!(buf[(area.right() - 1, y)].symbol(), "│" | "┃")); |
| 9673 | assert!(!matches!(buf[(area.right() - 2, y)].symbol(), "│" | "┃")); |
| 9674 | } |
| 9675 | } |
| 9676 | } |
| 9677 | } |
| 9678 | } |
| 9679 | |
| 9680 | #[test] |
| 9681 | fn chat_widget_shows_jump_to_latest_button_when_scrolled_up() { |
| 9682 | let mut app = create_test_app(); |
| 9683 | app.use_mouse_capture = true; |
| 9684 | for i in 0..80 { |
| 9685 | app.add_message(HistoryCell::User { |
| 9686 | content: format!("user message {i}"), |
| 9687 | }); |
| 9688 | } |
| 9689 | app.viewport.transcript_scroll = TranscriptScroll::at_line(0); |
| 9690 | |
| 9691 | let area = Rect { |
| 9692 | x: 0, |
| 9693 | y: 0, |
| 9694 | width: 80, |
| 9695 | height: 8, |
| 9696 | }; |
| 9697 | let mut buf = Buffer::empty(area); |
| 9698 | let widget = ChatWidget::new(&mut app, area); |
| 9699 | widget.render(area, &mut buf); |
| 9700 | |
| 9701 | let button = app |
| 9702 | .viewport |
| 9703 | .jump_to_latest_button_area |
| 9704 | .expect("button appears when transcript is not at tail"); |
| 9705 | assert_eq!(button.width, 3); |
| 9706 | assert_eq!(button.height, 3); |
| 9707 | assert_eq!(buf[(button.x + 1, button.y + 1)].symbol(), "↓"); |
| 9708 | } |
| 9709 | |
| 9710 | #[test] |
| 9711 | fn chat_widget_uses_light_theme_scroll_chrome() { |
| 9712 | let mut app = create_test_app(); |
| 9713 | app.ui_theme = palette::LIGHT_UI_THEME; |
| 9714 | app.use_mouse_capture = true; |
| 9715 | for i in 0..120 { |
| 9716 | app.add_message(HistoryCell::User { |
| 9717 | content: format!("user message {i}"), |
| 9718 | }); |
| 9719 | } |
| 9720 | app.viewport.transcript_scroll = TranscriptScroll::at_line(0); |
| 9721 | |
| 9722 | let area = Rect { |
| 9723 | x: 0, |
| 9724 | y: 0, |
| 9725 | width: 80, |
| 9726 | height: 8, |
| 9727 | }; |
| 9728 | let mut buf = Buffer::empty(area); |
| 9729 | let widget = ChatWidget::new(&mut app, area); |
| 9730 | widget.render(area, &mut buf); |
| 9731 | |
| 9732 | let mut saw_track = false; |
| 9733 | let mut saw_thumb = false; |
| 9734 | for y in 0..area.height { |
| 9735 | let cell = &buf[(area.width - 1, y)]; |
| 9736 | match cell.symbol() { |
| 9737 | "│" => { |
| 9738 | saw_track = true; |
| 9739 | assert_eq!(cell.fg, palette::LIGHT_UI_THEME.border); |
| 9740 | } |
| 9741 | "┃" => { |
| 9742 | saw_thumb = true; |
| 9743 | assert_eq!(cell.fg, palette::LIGHT_UI_THEME.status_working); |
| 9744 | } |
| 9745 | _ => {} |
| 9746 | } |
| 9747 | } |
| 9748 | assert!(saw_track, "scrollbar track should render"); |
| 9749 | assert!(saw_thumb, "scrollbar thumb should render"); |
| 9750 | |
| 9751 | let button = app |
| 9752 | .viewport |
| 9753 | .jump_to_latest_button_area |
| 9754 | .expect("button appears when transcript is not at tail"); |
| 9755 | assert_eq!( |
| 9756 | buf[(button.x + 1, button.y + 1)].fg, |
| 9757 | palette::LIGHT_UI_THEME.status_working |
| 9758 | ); |
| 9759 | } |
| 9760 | |
| 9761 | #[test] |
| 9762 | fn chat_widget_hides_jump_to_latest_button_at_tail() { |
| 9763 | let mut app = create_test_app(); |
| 9764 | app.use_mouse_capture = true; |
| 9765 | for i in 0..80 { |
| 9766 | app.add_message(HistoryCell::User { |
| 9767 | content: format!("user message {i}"), |
| 9768 | }); |
| 9769 | } |
| 9770 | app.viewport.transcript_scroll = TranscriptScroll::to_bottom(); |
| 9771 | |
| 9772 | let area = Rect { |
| 9773 | x: 0, |
| 9774 | y: 0, |
| 9775 | width: 80, |
| 9776 | height: 8, |
| 9777 | }; |
| 9778 | let _widget = ChatWidget::new(&mut app, area); |
| 9779 | assert!( |
| 9780 | app.viewport.jump_to_latest_button_area.is_none(), |
| 9781 | "button should hide while following the live tail" |
| 9782 | ); |
| 9783 | assert!(app.viewport.transcript_scroll.is_at_tail()); |
| 9784 | } |
| 9785 | |
| 9786 | /// Regression for issue #582: a resize event during a long task must not |
| 9787 | /// leave the chat widget with an empty viewport. The actual ConHost |
| 9788 | /// size-stale fix lives in `tui::ui::run_tui`. |
| 9789 | #[test] |
| 9790 | fn chat_widget_renders_cleanly_after_resize_during_long_task() { |
| 9791 | let mut app = create_test_app(); |
| 9792 | for i in 0..30 { |
| 9793 | app.add_message(HistoryCell::User { |
| 9794 | content: format!("user message {i} during a long-running task"), |
| 9795 | }); |
| 9796 | } |
| 9797 | |
| 9798 | // Drive the same shrink-then-grow cycle that maximize→windowed |
| 9799 | // transitions produce on Windows. |
| 9800 | for (width, height) in [(140u16, 40u16), (90, 28), (60, 20), (140, 40)] { |
| 9801 | app.handle_resize(width, height); |
| 9802 | let area = Rect { |
| 9803 | x: 0, |
| 9804 | y: 0, |
| 9805 | width, |
| 9806 | height, |
| 9807 | }; |
| 9808 | let mut buf = Buffer::empty(area); |
| 9809 | let widget = ChatWidget::new(&mut app, area); |
| 9810 | widget.render(area, &mut buf); |
| 9811 | |
| 9812 | let mut non_empty = 0usize; |
| 9813 | for y in 0..height { |
| 9814 | for x in 0..width { |
| 9815 | let sym = buf[(x, y)].symbol(); |
| 9816 | if sym != " " && !sym.is_empty() { |
| 9817 | non_empty += 1; |
| 9818 | } |
| 9819 | } |
| 9820 | } |
| 9821 | assert!( |
| 9822 | non_empty > 0, |
| 9823 | "resize at {width}x{height} produced an empty buffer (#582)" |
| 9824 | ); |
| 9825 | } |
| 9826 | } |
| 9827 | |
| 9828 | #[test] |
| 9829 | fn approval_inline_band_stays_within_short_terminal() { |
| 9830 | let request = crate::tui::approval::ApprovalRequest::new( |
| 9831 | "approval-1", |
| 9832 | "exec_shell", |
| 9833 | "Run git commit", |
| 9834 | &serde_json::json!({ "command": "git commit -m fix" }), |
| 9835 | "exec_shell:git commit", |
| 9836 | ); |
| 9837 | let view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 9838 | let widget = ApprovalWidget::new(&request, &view); |
| 9839 | |
| 9840 | for area in [Rect::new(0, 0, 162, 17), Rect::new(0, 0, 39, 17)] { |
| 9841 | let region = widget.inline_region(area); |
| 9842 | // Band never addresses cells outside the frame. |
| 9843 | assert!(region.x >= area.x); |
| 9844 | assert!(region.right() <= area.right()); |
| 9845 | assert!(region.bottom() <= area.bottom()); |
| 9846 | // Inline prompt is anchored to the bottom of the frame. |
| 9847 | assert_eq!( |
| 9848 | region.bottom(), |
| 9849 | area.bottom(), |
| 9850 | "approval band must be bottom-anchored at {area:?}" |
| 9851 | ); |
| 9852 | |
| 9853 | let mut buf = Buffer::empty(area); |
| 9854 | widget.render(area, &mut buf); |
| 9855 | } |
| 9856 | } |
| 9857 | |
| 9858 | #[test] |
| 9859 | fn approval_inline_band_caps_at_half_the_viewport_and_keeps_actions_visible() { |
| 9860 | let command = (0..24) |
| 9861 | .map(|index| format!("printf command-{index}")) |
| 9862 | .collect::<Vec<_>>() |
| 9863 | .join("\n"); |
| 9864 | let request = crate::tui::approval::ApprovalRequest::new( |
| 9865 | "approval-long", |
| 9866 | "exec_shell", |
| 9867 | "Run a long shell command", |
| 9868 | &serde_json::json!({ "command": command }), |
| 9869 | "exec_shell:long", |
| 9870 | ); |
| 9871 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 9872 | let widget = ApprovalWidget::new(&request, &view); |
| 9873 | let area = Rect::new(0, 0, 100, 30); |
| 9874 | let region = widget.inline_region(area); |
| 9875 | |
| 9876 | assert_eq!(region.bottom(), area.bottom()); |
| 9877 | assert_eq!(region.height, 1, "{region:?}"); |
| 9878 | |
| 9879 | let mut buf = Buffer::empty(area); |
| 9880 | widget.render(area, &mut buf); |
| 9881 | let rendered = buffer_text(&buf, area); |
| 9882 | assert!(rendered.contains("Allow"), "{rendered}"); |
| 9883 | assert!(rendered.contains("Deny"), "{rendered}"); |
| 9884 | |
| 9885 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 9886 | let expanded_widget = ApprovalWidget::new(&request, &view); |
| 9887 | let expanded_region = expanded_widget.inline_region(area); |
| 9888 | assert!(expanded_region.height > 1 && expanded_region.height < area.height); |
| 9889 | let mut expanded_buf = Buffer::empty(area); |
| 9890 | expanded_widget.render(area, &mut expanded_buf); |
| 9891 | let expanded_rendered = buffer_text(&expanded_buf, area); |
| 9892 | assert!(expanded_rendered.contains("..."), "{expanded_rendered}"); |
| 9893 | } |
| 9894 | |
| 9895 | #[test] |
| 9896 | fn approval_compact_tiers_preserve_command_before_falling_back_to_details() { |
| 9897 | let request = crate::tui::approval::ApprovalRequest::new( |
| 9898 | "approval-tiers", |
| 9899 | "exec_shell", |
| 9900 | "Print a localized verification marker", |
| 9901 | &serde_json::json!({ "command": "printf '安全確認'" }), |
| 9902 | "exec_shell:printf", |
| 9903 | ); |
| 9904 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 9905 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 9906 | let widget = ApprovalWidget::new(&request, &view); |
| 9907 | |
| 9908 | for area in [Rect::new(0, 0, 80, 24), Rect::new(0, 0, 60, 16)] { |
| 9909 | let region = widget.inline_region(area); |
| 9910 | assert_eq!(region.bottom(), area.bottom()); |
| 9911 | assert!(region.height < area.height, "{area:?}: {region:?}"); |
| 9912 | |
| 9913 | let mut buf = Buffer::empty(area); |
| 9914 | widget.render(area, &mut buf); |
| 9915 | let rendered = buffer_text(&buf, area); |
| 9916 | assert!(rendered.contains("Command:"), "{area:?}: {rendered}"); |
| 9917 | for marker in ['安', '全', '確', '認'] { |
| 9918 | assert!(rendered.contains(marker), "{area:?}: {rendered}"); |
| 9919 | } |
| 9920 | assert!(rendered.contains("Allow"), "{area:?}: {rendered}"); |
| 9921 | assert!(rendered.contains("Deny"), "{area:?}: {rendered}"); |
| 9922 | } |
| 9923 | |
| 9924 | let tiny = Rect::new(0, 0, 40, 12); |
| 9925 | let mut buf = Buffer::empty(tiny); |
| 9926 | widget.render(tiny, &mut buf); |
| 9927 | let rendered = buffer_text(&buf, tiny); |
| 9928 | assert!(rendered.contains("Allow"), "{rendered}"); |
| 9929 | assert!(rendered.contains("Deny"), "{rendered}"); |
| 9930 | assert!( |
| 9931 | rendered.contains(crate::tui::shell_key_routing::tool_details_chord().as_ref()), |
| 9932 | "{rendered}" |
| 9933 | ); |
| 9934 | } |
| 9935 | |
| 9936 | #[test] |
| 9937 | fn approval_truncation_hint_uses_platform_details_chord_in_every_locale() { |
| 9938 | let details = crate::tui::shell_key_routing::tool_details_chord(); |
| 9939 | for locale in Locale::shipped() { |
| 9940 | let hint = approval_truncation_hint(*locale); |
| 9941 | assert!(hint.contains(details.as_ref()), "{locale:?}: {hint}"); |
| 9942 | assert!(!hint.contains("[v]"), "{locale:?}: {hint}"); |
| 9943 | } |
| 9944 | } |
| 9945 | |
| 9946 | #[test] |
| 9947 | fn repo_law_approval_has_distinct_authority_grammar() { |
| 9948 | let request = crate::tui::approval::ApprovalRequest::new( |
| 9949 | "approval-law", |
| 9950 | "edit_file", |
| 9951 | "Repo law holds this write: \"manifest review\" protects Cargo.toml (matched Cargo.toml, .codewhale/constitution.json)", |
| 9952 | &serde_json::json!({ "path": "Cargo.toml", "old": "a", "new": "b" }), |
| 9953 | "edit_file:Cargo.toml", |
| 9954 | ); |
| 9955 | assert!(request.is_repo_law_prompt()); |
| 9956 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 9957 | let area = Rect::new(0, 0, 120, 30); |
| 9958 | let mut bar_buf = Buffer::empty(area); |
| 9959 | ApprovalWidget::new(&request, &view).render(area, &mut bar_buf); |
| 9960 | let bar_rendered = buffer_text(&bar_buf, area); |
| 9961 | assert!(bar_rendered.contains("Repo rule"), "{bar_rendered}"); |
| 9962 | assert!(bar_rendered.contains("┃ !"), "{bar_rendered}"); |
| 9963 | let bar_y = area.bottom() - 1; |
| 9964 | let emphasized = (area.left()..area.right()) |
| 9965 | .map(|x| &bar_buf[(x, bar_y)]) |
| 9966 | .filter(|cell| { |
| 9967 | cell.fg == palette::STATUS_WARNING && cell.modifier.contains(Modifier::REVERSED) |
| 9968 | }) |
| 9969 | .map(|cell| cell.symbol()) |
| 9970 | .collect::<String>(); |
| 9971 | assert_eq!(emphasized, "Repo rule"); |
| 9972 | assert!(bar_rendered.contains("Cargo.toml"), "{bar_rendered}"); |
| 9973 | |
| 9974 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 9975 | let mut buf = Buffer::empty(area); |
| 9976 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 9977 | let rendered = buffer_text(&buf, area); |
| 9978 | assert!( |
| 9979 | rendered.contains("This repo's constitution asks you to confirm this change."), |
| 9980 | "{rendered}" |
| 9981 | ); |
| 9982 | for retired in ["REPO LAW", "Repository law", "posture"] { |
| 9983 | assert!(!rendered.contains(retired), "{retired}: {rendered}"); |
| 9984 | } |
| 9985 | } |
| 9986 | |
| 9987 | #[test] |
| 9988 | fn approval_selected_destructive_option_uses_contrasting_highlight() { |
| 9989 | let request = crate::tui::approval::ApprovalRequest::new( |
| 9990 | "approval-1", |
| 9991 | "exec_shell", |
| 9992 | "Run git commit", |
| 9993 | &serde_json::json!({ "command": "git commit -m fix" }), |
| 9994 | "exec_shell:git commit", |
| 9995 | ); |
| 9996 | let view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 9997 | let widget = ApprovalWidget::new(&request, &view); |
| 9998 | let area = Rect::new(0, 0, 100, 30); |
| 9999 | let mut buf = Buffer::empty(area); |
| 10000 | |
| 10001 | widget.render(area, &mut buf); |
| 10002 | |
| 10003 | let selected_row = (area.y..area.y.saturating_add(area.height)) |
| 10004 | .find(|&y| { |
| 10005 | (area.x..area.x.saturating_add(area.width)) |
| 10006 | .any(|x| buf[(x, y)].bg == palette::SELECTION_BG) |
| 10007 | }) |
| 10008 | .expect("selected approval row should use selection background"); |
| 10009 | let highlighted_cells = (area.x..area.x.saturating_add(area.width)) |
| 10010 | .filter(|&x| { |
| 10011 | let cell = &buf[(x, selected_row)]; |
| 10012 | !cell.symbol().trim().is_empty() |
| 10013 | && cell.bg == palette::SELECTION_BG |
| 10014 | && cell.fg == palette::SELECTION_TEXT |
| 10015 | }) |
| 10016 | .count(); |
| 10017 | |
| 10018 | assert!( |
| 10019 | highlighted_cells >= 4, |
| 10020 | "selected destructive option should render visible selection text" |
| 10021 | ); |
| 10022 | } |
| 10023 | |
| 10024 | #[test] |
| 10025 | fn approval_inline_marks_selected_row_and_separator_rule() { |
| 10026 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10027 | "approval-1", |
| 10028 | "exec_shell", |
| 10029 | "Run git commit", |
| 10030 | &serde_json::json!({ "command": "git commit -m fix" }), |
| 10031 | "exec_shell:git commit", |
| 10032 | ); |
| 10033 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10034 | let area = Rect::new(0, 0, 100, 30); |
| 10035 | let mut buf = Buffer::empty(area); |
| 10036 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10037 | let bar = buffer_text(&buf, area); |
| 10038 | assert!(bar.contains("┃ ⛯"), "{bar}"); |
| 10039 | |
| 10040 | view.handle_key(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)); |
| 10041 | let mut menu_buf = Buffer::empty(area); |
| 10042 | ApprovalWidget::new(&request, &view).render(area, &mut menu_buf); |
| 10043 | let rendered = buffer_text(&menu_buf, area); |
| 10044 | assert!(rendered.contains('\u{25b8}'), "{rendered}"); |
| 10045 | assert!(rendered.contains('\u{2500}'), "{rendered}"); |
| 10046 | } |
| 10047 | |
| 10048 | #[test] |
| 10049 | fn approval_inline_explains_auto_review_timeout_and_keeps_the_command() { |
| 10050 | let description = "Auto-Review could not finish (timed out); please decide."; |
| 10051 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10052 | "review-fallback", |
| 10053 | "bash", |
| 10054 | description, |
| 10055 | &serde_json::json!({"command": "printf value"}), |
| 10056 | "bash:printf", |
| 10057 | ); |
| 10058 | let area = Rect::new(0, 0, 120, 40); |
| 10059 | let bar = render_approval_request(&request, area); |
| 10060 | assert!( |
| 10061 | bar.contains("Auto-Review (timed out)") && bar.contains("printf value"), |
| 10062 | "{bar}" |
| 10063 | ); |
| 10064 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10065 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10066 | let mut buf = Buffer::empty(area); |
| 10067 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10068 | let drawer = buffer_text(&buf, area); |
| 10069 | assert!(drawer.contains(description), "{drawer}"); |
| 10070 | |
| 10071 | let mut localized = |
| 10072 | crate::tui::approval::ApprovalView::new_for_locale(request.clone(), Locale::Fr); |
| 10073 | let mut localized_buf = Buffer::empty(area); |
| 10074 | ApprovalWidget::new(&request, &localized).render(area, &mut localized_buf); |
| 10075 | let localized_bar = buffer_text(&localized_buf, area); |
| 10076 | assert!(localized_bar.contains("délai dépassé"), "{localized_bar}"); |
| 10077 | assert!(localized_bar.contains("printf value"), "{localized_bar}"); |
| 10078 | |
| 10079 | localized.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10080 | let mut localized_buf = Buffer::empty(area); |
| 10081 | ApprovalWidget::new(&request, &localized).render(area, &mut localized_buf); |
| 10082 | let localized_drawer = buffer_text(&localized_buf, area); |
| 10083 | assert!( |
| 10084 | localized_drawer.contains("À vous de décider."), |
| 10085 | "{localized_drawer}" |
| 10086 | ); |
| 10087 | } |
| 10088 | |
| 10089 | #[test] |
| 10090 | fn approval_inline_keeps_action_row_and_leaves_transcript_visible() { |
| 10091 | let request = crate::tui::approval::ApprovalRequest::new_with_intent( |
| 10092 | "approval-1", |
| 10093 | "exec_shell", |
| 10094 | "Run shell command", |
| 10095 | &serde_json::json!({ |
| 10096 | "command": "rm -rf ./build && find . -name '*.tmp' -delete && cargo clean && echo done", |
| 10097 | }), |
| 10098 | "exec_shell:cleanup", |
| 10099 | Some( |
| 10100 | "Clearing stale build artifacts and temp files before a fresh run so the next build is reproducible.", |
| 10101 | ), |
| 10102 | std::path::Path::new("/tmp/project"), |
| 10103 | ); |
| 10104 | let view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10105 | let widget = ApprovalWidget::new(&request, &view); |
| 10106 | |
| 10107 | for (w, h) in [(40u16, 14u16), (80, 24), (100, 50), (60, 10)] { |
| 10108 | let area = Rect::new(0, 0, w, h); |
| 10109 | let mut buf = Buffer::empty(area); |
| 10110 | widget.render(area, &mut buf); |
| 10111 | let rendered = buffer_text(&buf, area); |
| 10112 | |
| 10113 | assert!( |
| 10114 | rendered.contains("Allow") && rendered.contains("Deny"), |
| 10115 | "action row must stay visible at {w}x{h}:\n{rendered}" |
| 10116 | ); |
| 10117 | |
| 10118 | let region = widget.inline_region(area); |
| 10119 | assert!(region.right() <= area.right() && region.bottom() <= area.bottom()); |
| 10120 | assert_eq!(region.bottom(), area.bottom()); |
| 10121 | assert_eq!(region.height, 1); |
| 10122 | if h >= 40 { |
| 10123 | assert!(region.y > area.y); |
| 10124 | } |
| 10125 | } |
| 10126 | } |
| 10127 | |
| 10128 | #[test] |
| 10129 | fn approval_option_two_reads_as_session_scoped_not_always() { |
| 10130 | let mut request = crate::tui::approval::ApprovalRequest::new( |
| 10131 | "approval-1", |
| 10132 | "exec_shell", |
| 10133 | "Run git commit", |
| 10134 | &serde_json::json!({ "command": "git commit -m fix" }), |
| 10135 | "exec_shell:git commit", |
| 10136 | ); |
| 10137 | request.persistent_allow_rules.clear(); |
| 10138 | |
| 10139 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10140 | view.handle_key(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)); |
| 10141 | |
| 10142 | let mut full_buf = Buffer::empty(Rect::new(0, 0, 100, 30)); |
| 10143 | ApprovalWidget::new(&request, &view).render(Rect::new(0, 0, 100, 30), &mut full_buf); |
| 10144 | let full = buffer_text(&full_buf, Rect::new(0, 0, 100, 30)); |
| 10145 | let full_session_option = full |
| 10146 | .lines() |
| 10147 | .find(|line| line.contains("[2]")) |
| 10148 | .expect("scope menu should render option 2"); |
| 10149 | assert!( |
| 10150 | full_session_option |
| 10151 | .to_lowercase() |
| 10152 | .contains("this conversation") |
| 10153 | && !full_session_option.to_lowercase().contains("always"), |
| 10154 | "{full}" |
| 10155 | ); |
| 10156 | |
| 10157 | let mut compact_buf = Buffer::empty(Rect::new(0, 0, 60, 17)); |
| 10158 | ApprovalWidget::new(&request, &view).render(Rect::new(0, 0, 60, 17), &mut compact_buf); |
| 10159 | let compact = buffer_text(&compact_buf, Rect::new(0, 0, 60, 17)); |
| 10160 | let compact_session_option = compact |
| 10161 | .lines() |
| 10162 | .find(|line| line.contains("[2]")) |
| 10163 | .expect("compact scope menu should render option 2"); |
| 10164 | assert!( |
| 10165 | compact_session_option |
| 10166 | .to_lowercase() |
| 10167 | .contains("conversation") |
| 10168 | && !compact_session_option.to_lowercase().contains("always"), |
| 10169 | "{compact}" |
| 10170 | ); |
| 10171 | } |
| 10172 | |
| 10173 | #[test] |
| 10174 | fn approval_shell_command_detects_printf_write_file_preview() { |
| 10175 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10176 | "approval-1", |
| 10177 | "exec_shell", |
| 10178 | "Run shell command", |
| 10179 | &serde_json::json!({ |
| 10180 | "command": "printf '%s\\n' 'alpha' 'beta' > src/generated.txt", |
| 10181 | "cwd": "/tmp/project", |
| 10182 | }), |
| 10183 | "exec_shell:printf", |
| 10184 | ); |
| 10185 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10186 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10187 | let area = Rect::new(0, 0, 110, 32); |
| 10188 | let mut buf = Buffer::empty(area); |
| 10189 | |
| 10190 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10191 | let rendered = buffer_text(&buf, area); |
| 10192 | |
| 10193 | assert!(rendered.contains("Command:"), "{rendered}"); |
| 10194 | assert!( |
| 10195 | rendered.contains("printf > src/generated.txt"), |
| 10196 | "{rendered}" |
| 10197 | ); |
| 10198 | assert!(rendered.contains("alpha"), "{rendered}"); |
| 10199 | assert!(rendered.contains("beta"), "{rendered}"); |
| 10200 | assert!(rendered.contains("Dir"), "{rendered}"); |
| 10201 | assert!(rendered.contains("/tmp/project"), "{rendered}"); |
| 10202 | } |
| 10203 | |
| 10204 | #[test] |
| 10205 | fn approval_card_renders_shell_ask_rule_save_preview() { |
| 10206 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10207 | "approval-1", |
| 10208 | "exec_shell", |
| 10209 | "Run shell command", |
| 10210 | &serde_json::json!({ "command": "cargo test --workspace" }), |
| 10211 | "exec_shell:cargo-test", |
| 10212 | ); |
| 10213 | |
| 10214 | let default_rendered = render_approval_request(&request, Rect::new(0, 0, 120, 40)); |
| 10215 | assert!( |
| 10216 | !default_rendered.contains(".codewhale/permissions.toml"), |
| 10217 | "{default_rendered}" |
| 10218 | ); |
| 10219 | |
| 10220 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10221 | view.handle_key(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)); |
| 10222 | let mut buf = Buffer::empty(Rect::new(0, 0, 120, 40)); |
| 10223 | ApprovalWidget::new(&request, &view).render(Rect::new(0, 0, 120, 40), &mut buf); |
| 10224 | let menu_rendered = buffer_text(&buf, Rect::new(0, 0, 120, 40)); |
| 10225 | assert!( |
| 10226 | menu_rendered.contains("Always allow in this repo"), |
| 10227 | "{menu_rendered}" |
| 10228 | ); |
| 10229 | assert!( |
| 10230 | menu_rendered.contains("cargo test --workspace"), |
| 10231 | "{menu_rendered}" |
| 10232 | ); |
| 10233 | assert!( |
| 10234 | menu_rendered.contains(".codewhale/permissions.toml"), |
| 10235 | "{menu_rendered}" |
| 10236 | ); |
| 10237 | |
| 10238 | let mut view = crate::tui::approval::ApprovalView::new(request); |
| 10239 | let crate::tui::views::ViewAction::Emit(crate::tui::views::ViewEvent::OpenTextPager { |
| 10240 | content, |
| 10241 | .. |
| 10242 | }) = crate::tui::views::ModalView::handle_key( |
| 10243 | &mut view, |
| 10244 | crossterm::event::KeyEvent::new( |
| 10245 | crossterm::event::KeyCode::Char('v'), |
| 10246 | crossterm::event::KeyModifiers::ALT, |
| 10247 | ), |
| 10248 | ) |
| 10249 | else { |
| 10250 | panic!("the details chord opens the pager"); |
| 10251 | }; |
| 10252 | assert!( |
| 10253 | content.contains("[s] allow now, and always ask before this again"), |
| 10254 | "{content}" |
| 10255 | ); |
| 10256 | assert!( |
| 10257 | content.contains("always ask first · run cargo test --workspace"), |
| 10258 | "{content}" |
| 10259 | ); |
| 10260 | } |
| 10261 | |
| 10262 | #[test] |
| 10263 | fn approval_card_renders_file_ask_rule_save_previews() { |
| 10264 | let cases = [ |
| 10265 | ( |
| 10266 | "write_file", |
| 10267 | serde_json::json!({ |
| 10268 | "path": "src/main.rs", |
| 10269 | "content": "fn main() {}\n", |
| 10270 | }), |
| 10271 | "src/main.rs", |
| 10272 | ), |
| 10273 | ( |
| 10274 | "edit_file", |
| 10275 | serde_json::json!({ |
| 10276 | "path": "/workspace/src/lib.rs", |
| 10277 | "old_string": "old", |
| 10278 | "new_string": "new", |
| 10279 | }), |
| 10280 | "src/lib.rs", |
| 10281 | ), |
| 10282 | ]; |
| 10283 | |
| 10284 | for (tool_name, params, expected_rule) in cases { |
| 10285 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10286 | "approval-1", |
| 10287 | tool_name, |
| 10288 | "Modify a file", |
| 10289 | ¶ms, |
| 10290 | &format!("{tool_name}:src"), |
| 10291 | ); |
| 10292 | |
| 10293 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10294 | view.handle_key(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)); |
| 10295 | let area = Rect::new(0, 0, 120, 40); |
| 10296 | let mut buf = Buffer::empty(area); |
| 10297 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10298 | let rendered = buffer_text(&buf, area); |
| 10299 | |
| 10300 | assert!( |
| 10301 | rendered.contains("Always allow in this repo"), |
| 10302 | "{tool_name}:\n{rendered}" |
| 10303 | ); |
| 10304 | assert!( |
| 10305 | rendered.contains(expected_rule), |
| 10306 | "{tool_name} should preview {expected_rule}:\n{rendered}" |
| 10307 | ); |
| 10308 | assert!( |
| 10309 | rendered.contains(".codewhale/permissions.toml"), |
| 10310 | "{tool_name}:\n{rendered}" |
| 10311 | ); |
| 10312 | } |
| 10313 | } |
| 10314 | |
| 10315 | #[test] |
| 10316 | fn approval_card_renders_apply_patch_multi_rule_save_preview() { |
| 10317 | let patch = "diff --git a/src/a.rs b/src/a.rs\n\ |
| 10318 | --- a/src/a.rs\n\ |
| 10319 | +++ b/src/a.rs\n\ |
| 10320 | @@ -1,1 +1,1 @@\n\ |
| 10321 | -old\n\ |
| 10322 | +new\n\ |
| 10323 | diff --git a/src/b.rs b/src/b.rs\n\ |
| 10324 | --- a/src/b.rs\n\ |
| 10325 | +++ b/src/b.rs\n\ |
| 10326 | @@ -1,1 +1,1 @@\n\ |
| 10327 | -old\n\ |
| 10328 | +new\n"; |
| 10329 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10330 | "approval-1", |
| 10331 | "apply_patch", |
| 10332 | "Apply a patch", |
| 10333 | &serde_json::json!({ "patch": patch }), |
| 10334 | "apply_patch:multi", |
| 10335 | ); |
| 10336 | |
| 10337 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10338 | view.handle_key(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)); |
| 10339 | let area = Rect::new(0, 0, 120, 40); |
| 10340 | let mut buf = Buffer::empty(area); |
| 10341 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10342 | let rendered = buffer_text(&buf, area); |
| 10343 | |
| 10344 | assert!(rendered.contains("Always allow in this repo"), "{rendered}"); |
| 10345 | assert!(rendered.contains("src/a.rs, src/b.rs"), "{rendered}"); |
| 10346 | } |
| 10347 | |
| 10348 | #[test] |
| 10349 | fn approval_card_shows_a_one_line_edit_and_why_a_plain_folder_asks() { |
| 10350 | let old = "export function formatDuration(totalMinutes) {\n const hours = Math.floor(totalMinutes / 60);\n return `${hours}h ${totalMinutes}m`;\n}"; |
| 10351 | let new = "export function formatDuration(totalMinutes) {\n const hours = Math.floor(totalMinutes / 60);\n return `${hours}h ${totalMinutes % 60}m`;\n}"; |
| 10352 | let mut request = crate::tui::approval::ApprovalRequest::new( |
| 10353 | "approval-1", |
| 10354 | "edit_file", |
| 10355 | "Edit a file on disk", |
| 10356 | &serde_json::json!({ |
| 10357 | "path": "duration.mjs", |
| 10358 | "edits": [{ "oldText": old, "newText": new }] |
| 10359 | }), |
| 10360 | "tool:edit_file", |
| 10361 | ); |
| 10362 | |
| 10363 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10364 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10365 | let area = Rect::new(0, 0, 110, 32); |
| 10366 | let mut buf = Buffer::empty(area); |
| 10367 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10368 | let in_repo = buffer_text(&buf, area); |
| 10369 | assert!( |
| 10370 | in_repo.contains("- return `${hours}h ${totalMinutes}m`;"), |
| 10371 | "{in_repo}" |
| 10372 | ); |
| 10373 | assert!( |
| 10374 | in_repo.contains("+ return `${hours}h ${totalMinutes % 60}m`;"), |
| 10375 | "{in_repo}" |
| 10376 | ); |
| 10377 | assert!(!in_repo.contains("No Git repository"), "{in_repo}"); |
| 10378 | |
| 10379 | request.asks_without_git = true; |
| 10380 | let mut plain_view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10381 | plain_view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10382 | let mut plain_buf = Buffer::empty(area); |
| 10383 | ApprovalWidget::new(&request, &plain_view).render(area, &mut plain_buf); |
| 10384 | let plain = buffer_text(&plain_buf, area); |
| 10385 | assert!( |
| 10386 | plain.contains("No Git repository here, so edits ask first."), |
| 10387 | "{plain}" |
| 10388 | ); |
| 10389 | assert!( |
| 10390 | plain.contains("+ return `${hours}h ${totalMinutes % 60}m`;"), |
| 10391 | "{plain}" |
| 10392 | ); |
| 10393 | } |
| 10394 | |
| 10395 | #[test] |
| 10396 | fn approval_card_truncates_apply_patch_ask_rule_save_preview() { |
| 10397 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10398 | "approval-1", |
| 10399 | "apply_patch", |
| 10400 | "Apply a patch", |
| 10401 | &serde_json::json!({ |
| 10402 | "replace": [ |
| 10403 | { "path": "src/a.rs", "content": "a" }, |
| 10404 | { "path": "src/b.rs", "content": "b" }, |
| 10405 | { "path": "src/c.rs", "content": "c" }, |
| 10406 | { "path": "src/d.rs", "content": "d" }, |
| 10407 | { "path": "src/e.rs", "content": "e" } |
| 10408 | ] |
| 10409 | }), |
| 10410 | "apply_patch:many", |
| 10411 | ); |
| 10412 | |
| 10413 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10414 | view.handle_key(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)); |
| 10415 | let area = Rect::new(0, 0, 120, 80); |
| 10416 | let mut buf = Buffer::empty(area); |
| 10417 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10418 | let rendered = buffer_text(&buf, area); |
| 10419 | |
| 10420 | assert!(rendered.contains("Always allow in this repo"), "{rendered}"); |
| 10421 | let rule_line = rendered |
| 10422 | .lines() |
| 10423 | .find(|line| line.contains(".codewhale/permissions.toml")) |
| 10424 | .expect("rule preview line"); |
| 10425 | assert!(rule_line.contains("src/a.rs"), "{rule_line}"); |
| 10426 | assert!(rule_line.contains("+1 more"), "{rule_line}"); |
| 10427 | assert!(!rule_line.contains("src/e.rs"), "{rule_line}"); |
| 10428 | } |
| 10429 | |
| 10430 | #[test] |
| 10431 | fn approval_card_keeps_a_one_line_save_preview_when_the_full_one_does_not_fit() { |
| 10432 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10433 | "approval-1", |
| 10434 | "apply_patch", |
| 10435 | "Apply a patch", |
| 10436 | &serde_json::json!({ |
| 10437 | "replace": [ |
| 10438 | { "path": "src/a.rs", "content": "a" }, |
| 10439 | { "path": "src/b.rs", "content": "b" }, |
| 10440 | { "path": "src/c.rs", "content": "c" }, |
| 10441 | { "path": "src/d.rs", "content": "d" }, |
| 10442 | { "path": "src/e.rs", "content": "e" } |
| 10443 | ] |
| 10444 | }), |
| 10445 | "apply_patch:many", |
| 10446 | ); |
| 10447 | |
| 10448 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10449 | view.handle_key(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)); |
| 10450 | |
| 10451 | for height in [10, 12, 16, 20] { |
| 10452 | let area = Rect::new(0, 0, 120, height); |
| 10453 | let mut buf = Buffer::empty(area); |
| 10454 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10455 | let rendered = buffer_text(&buf, area); |
| 10456 | assert!(rendered.contains("src/a.rs"), "height {height}: {rendered}"); |
| 10457 | assert!( |
| 10458 | rendered.contains(".codewhale/permissions.toml"), |
| 10459 | "height {height}: {rendered}" |
| 10460 | ); |
| 10461 | } |
| 10462 | |
| 10463 | let bar_only = Rect::new(0, 0, 80, 1); |
| 10464 | let mut buf = Buffer::empty(bar_only); |
| 10465 | ApprovalWidget::new(&request, &view).render(bar_only, &mut buf); |
| 10466 | let rendered = buffer_text(&buf, bar_only); |
| 10467 | assert!( |
| 10468 | !rendered.contains(".codewhale/permissions.toml"), |
| 10469 | "{rendered}" |
| 10470 | ); |
| 10471 | assert!( |
| 10472 | rendered.contains("Allow") && rendered.contains("Deny"), |
| 10473 | "{rendered}" |
| 10474 | ); |
| 10475 | } |
| 10476 | |
| 10477 | #[test] |
| 10478 | fn approval_card_omits_ask_rule_save_preview_when_rule_is_unavailable() { |
| 10479 | let unsafe_path = crate::tui::approval::ApprovalRequest::new( |
| 10480 | "approval-1", |
| 10481 | "write_file", |
| 10482 | "Write a file", |
| 10483 | &serde_json::json!({ |
| 10484 | "path": "../escape.rs", |
| 10485 | "content": "unsafe\n", |
| 10486 | }), |
| 10487 | "write_file:escape", |
| 10488 | ); |
| 10489 | let preflight_failed = crate::tui::approval::ApprovalRequest::new( |
| 10490 | "approval-2", |
| 10491 | "apply_patch", |
| 10492 | "Apply a patch", |
| 10493 | &serde_json::json!({ "patch": "@@ -1 +1 @@\n-old\n+new\n" }), |
| 10494 | "apply_patch:invalid", |
| 10495 | ); |
| 10496 | |
| 10497 | for request in [unsafe_path, preflight_failed] { |
| 10498 | let rendered = render_approval_request(&request, Rect::new(0, 0, 120, 40)); |
| 10499 | |
| 10500 | assert!( |
| 10501 | !rendered.contains("s allow now, and always ask before this again"), |
| 10502 | "S shortcut should stay hidden:\n{rendered}" |
| 10503 | ); |
| 10504 | assert!( |
| 10505 | !rendered.contains("Save:"), |
| 10506 | "save preview should stay hidden:\n{rendered}" |
| 10507 | ); |
| 10508 | assert!( |
| 10509 | !rendered.contains("always ask first"), |
| 10510 | "ask-rule details should stay hidden:\n{rendered}" |
| 10511 | ); |
| 10512 | } |
| 10513 | } |
| 10514 | |
| 10515 | #[test] |
| 10516 | fn approval_file_write_modal_renders_proposed_change_preview() { |
| 10517 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10518 | "approval-1", |
| 10519 | "write_file", |
| 10520 | "Write a file", |
| 10521 | &serde_json::json!({ |
| 10522 | "path": "src/main.rs", |
| 10523 | "content": "fn main() {\n println!(\"visible before approval\");\n}\n", |
| 10524 | }), |
| 10525 | "write_file:src/main.rs", |
| 10526 | ); |
| 10527 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10528 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10529 | let area = Rect::new(0, 0, 120, 34); |
| 10530 | let mut buf = Buffer::empty(area); |
| 10531 | |
| 10532 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10533 | let rendered = buffer_text(&buf, area); |
| 10534 | |
| 10535 | assert!(rendered.contains("Preview:"), "{rendered}"); |
| 10536 | assert!(rendered.contains("+ fn main() {"), "{rendered}"); |
| 10537 | assert!(rendered.contains("visible before approval"), "{rendered}"); |
| 10538 | } |
| 10539 | |
| 10540 | #[test] |
| 10541 | fn apply_patch_approval_shows_preview_and_reserved_controls_on_short_terminal() { |
| 10542 | let request = crate::tui::approval::ApprovalRequest::new( |
| 10543 | "approval-1", |
| 10544 | "apply_patch", |
| 10545 | "Apply a patch", |
| 10546 | &serde_json::json!({ |
| 10547 | "patch": "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1 +1 @@\n-old\n+new\n", |
| 10548 | }), |
| 10549 | "apply_patch:src/lib.rs", |
| 10550 | ); |
| 10551 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10552 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10553 | let area = Rect::new(0, 0, 80, 20); |
| 10554 | let mut buf = Buffer::empty(area); |
| 10555 | |
| 10556 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10557 | let rendered = buffer_text(&buf, area); |
| 10558 | |
| 10559 | assert!(rendered.contains("Preview:"), "{rendered}"); |
| 10560 | assert!(rendered.contains("+new"), "{rendered}"); |
| 10561 | assert!(rendered.contains("Allow"), "{rendered}"); |
| 10562 | assert!(rendered.contains("Deny"), "{rendered}"); |
| 10563 | } |
| 10564 | |
| 10565 | #[test] |
| 10566 | fn approval_intent_summary_still_renders_with_shell_details() { |
| 10567 | let request = crate::tui::approval::ApprovalRequest::new_with_intent( |
| 10568 | "approval-1", |
| 10569 | "exec_shell", |
| 10570 | "Run shell command", |
| 10571 | &serde_json::json!({ |
| 10572 | "command": "cargo build || echo fallback", |
| 10573 | "cwd": "/tmp/project", |
| 10574 | }), |
| 10575 | "exec_shell:cargo", |
| 10576 | Some("Need to verify the fallback build path before editing files."), |
| 10577 | std::path::Path::new("/tmp/project"), |
| 10578 | ); |
| 10579 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10580 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10581 | let area = Rect::new(0, 0, 120, 34); |
| 10582 | let mut buf = Buffer::empty(area); |
| 10583 | |
| 10584 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10585 | let rendered = buffer_text(&buf, area); |
| 10586 | |
| 10587 | assert!(rendered.contains("Intent:"), "{rendered}"); |
| 10588 | assert!(rendered.contains("fallback build path"), "{rendered}"); |
| 10589 | assert!(rendered.contains("Command:"), "{rendered}"); |
| 10590 | assert!(rendered.contains("cargo build ||"), "{rendered}"); |
| 10591 | assert!(rendered.contains("echo fallback"), "{rendered}"); |
| 10592 | } |
| 10593 | |
| 10594 | #[test] |
| 10595 | fn approval_card_truncates_cjk_text_by_display_width() { |
| 10596 | let note = "检查宽字符参数".repeat(4); |
| 10597 | let intent = "需要确认回退构建路径".repeat(4); |
| 10598 | let request = crate::tui::approval::ApprovalRequest::new_with_intent( |
| 10599 | "approval-1", |
| 10600 | "custom_note", |
| 10601 | "Record a note", |
| 10602 | &serde_json::json!({ "note": note }), |
| 10603 | "custom_note", |
| 10604 | Some(&intent), |
| 10605 | std::path::Path::new("/tmp/project"), |
| 10606 | ); |
| 10607 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10608 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10609 | let mut buf = Buffer::empty(Rect::new(0, 0, 100, 34)); |
| 10610 | ApprovalWidget::new(&request, &view).render(Rect::new(0, 0, 100, 34), &mut buf); |
| 10611 | let rendered = buffer_text(&buf, Rect::new(0, 0, 100, 34)).replace(' ', ""); |
| 10612 | |
| 10613 | assert!(rendered.contains(&intent), "{rendered}"); |
| 10614 | assert!(rendered.contains(¬e), "{rendered}"); |
| 10615 | } |
| 10616 | |
| 10617 | #[test] |
| 10618 | fn approval_shell_modal_stays_useful_on_short_terminals() { |
| 10619 | let request = crate::tui::approval::ApprovalRequest::new_with_intent( |
| 10620 | "approval-1", |
| 10621 | "exec_shell", |
| 10622 | "Built-in safety gate requires approval: destructive background/headless actions cannot auto-approve", |
| 10623 | &serde_json::json!({ |
| 10624 | "command": "cd /workspace/codewhale; cargo clippy -p codewhale-tui --all-targets --locked -- -D warnings 2>&1 | tee /tmp/codewhale-clippy.log", |
| 10625 | "cwd": "/workspace/codewhale", |
| 10626 | }), |
| 10627 | "exec_shell:cargo-clippy", |
| 10628 | Some("Confirmed - passes in isolation, so this is the documentation gate."), |
| 10629 | std::path::Path::new("/workspace/codewhale"), |
| 10630 | ); |
| 10631 | let mut view = crate::tui::approval::ApprovalView::new(request.clone()); |
| 10632 | let area = Rect::new(0, 0, 80, 20); |
| 10633 | let mut bar_buf = Buffer::empty(area); |
| 10634 | ApprovalWidget::new(&request, &view).render(area, &mut bar_buf); |
| 10635 | let bar_rendered = buffer_text(&bar_buf, area); |
| 10636 | assert!(bar_rendered.contains("cargo"), "{bar_rendered}"); |
| 10637 | assert!(bar_rendered.contains("Allow"), "{bar_rendered}"); |
| 10638 | assert!(bar_rendered.contains("Deny"), "{bar_rendered}"); |
| 10639 | |
| 10640 | view.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); |
| 10641 | let mut buf = Buffer::empty(area); |
| 10642 | ApprovalWidget::new(&request, &view).render(area, &mut buf); |
| 10643 | let rendered = buffer_text(&buf, area); |
| 10644 | |
| 10645 | assert!( |
| 10646 | !rendered.contains("Built-in safety gate requires approval"), |
| 10647 | "{rendered}" |
| 10648 | ); |
| 10649 | assert!(!rendered.contains("Impact: Command"), "{rendered}"); |
| 10650 | assert!(rendered.contains("Command:"), "{rendered}"); |
| 10651 | assert!(rendered.contains("cargo clippy"), "{rendered}"); |
| 10652 | assert!(rendered.contains("Allow"), "{rendered}"); |
| 10653 | assert!(rendered.contains("Deny"), "{rendered}"); |
| 10654 | } |
| 10655 | |
| 10656 | /// Regression for issue #65: after `App::handle_resize`, the chat widget |
| 10657 | /// must produce a clean render at the new width — no stale wrapping, |
| 10658 | /// no panic, no content exceeding the requested width. Cycling through |
| 10659 | /// several widths (shrinks and grows) flushes any cached layout that |
| 10660 | /// fails to invalidate on resize. |
| 10661 | #[test] |
| 10662 | fn chat_widget_renders_cleanly_after_resize_cycle() { |
| 10663 | let mut app = create_test_app(); |
| 10664 | // Add some long content that wraps differently at different widths. |
| 10665 | for i in 0..40 { |
| 10666 | app.add_message(HistoryCell::User { |
| 10667 | content: format!("user message {i} with enough text to wrap at 30 columns easily"), |
| 10668 | }); |
| 10669 | } |
| 10670 | |
| 10671 | let widths_to_cycle = [120u16, 80, 40, 60, 100, 30]; |
| 10672 | let height: u16 = 20; |
| 10673 | for width in widths_to_cycle { |
| 10674 | // Caller-side: simulate the resize handler invalidating caches. |
| 10675 | app.handle_resize(width, height); |
| 10676 | let area = Rect { |
| 10677 | x: 0, |
| 10678 | y: 0, |
| 10679 | width, |
| 10680 | height, |
| 10681 | }; |
| 10682 | let mut buf = Buffer::empty(area); |
| 10683 | let widget = ChatWidget::new(&mut app, area); |
| 10684 | widget.render(area, &mut buf); |
| 10685 | |
| 10686 | // The render must produce at least some non-empty content for a |
| 10687 | // populated history at any reasonable width. This catches a class |
| 10688 | // of resize regressions where stale layout state leaves a blank |
| 10689 | // viewport after a width change. |
| 10690 | let mut non_empty = 0usize; |
| 10691 | for y in 0..height { |
| 10692 | for x in 0..width { |
| 10693 | let sym = buf[(x, y)].symbol(); |
| 10694 | if sym != " " && !sym.is_empty() { |
| 10695 | non_empty += 1; |
| 10696 | } |
| 10697 | } |
| 10698 | } |
| 10699 | assert!( |
| 10700 | non_empty > 0, |
| 10701 | "render at {width}x{height} produced an empty buffer after resize" |
| 10702 | ); |
| 10703 | } |
| 10704 | } |
| 10705 | |
| 10706 | /// Regression for issue #65: the transcript view cache must invalidate |
| 10707 | /// when width changes, so the same `App.history` re-wraps to the new |
| 10708 | /// width on the very next `ChatWidget::new` call. |
| 10709 | #[test] |
| 10710 | fn transcript_cache_invalidates_on_width_change() { |
| 10711 | let mut app = create_test_app(); |
| 10712 | for i in 0..10 { |
| 10713 | app.add_message(HistoryCell::User { |
| 10714 | content: format!("a fairly long user message number {i} that needs to wrap"), |
| 10715 | }); |
| 10716 | } |
| 10717 | |
| 10718 | let area_wide = Rect { |
| 10719 | x: 0, |
| 10720 | y: 0, |
| 10721 | width: 120, |
| 10722 | height: 20, |
| 10723 | }; |
| 10724 | let area_narrow = Rect { |
| 10725 | x: 0, |
| 10726 | y: 0, |
| 10727 | width: 30, |
| 10728 | height: 20, |
| 10729 | }; |
| 10730 | let mut buf_wide = Buffer::empty(area_wide); |
| 10731 | let widget_wide = ChatWidget::new(&mut app, area_wide); |
| 10732 | widget_wide.render(area_wide, &mut buf_wide); |
| 10733 | let wide_total_lines = app.viewport.transcript_cache.total_lines(); |
| 10734 | |
| 10735 | // Without an explicit resize call, just shrinking the render area |
| 10736 | // should still trigger a cache rebuild because the cache keys on width. |
| 10737 | let mut buf_narrow = Buffer::empty(area_narrow); |
| 10738 | let widget_narrow = ChatWidget::new(&mut app, area_narrow); |
| 10739 | widget_narrow.render(area_narrow, &mut buf_narrow); |
| 10740 | let narrow_total_lines = app.viewport.transcript_cache.total_lines(); |
| 10741 | |
| 10742 | assert!( |
| 10743 | narrow_total_lines > wide_total_lines, |
| 10744 | "narrow render should produce more wrapped lines (got {narrow_total_lines}, wide={wide_total_lines})" |
| 10745 | ); |
| 10746 | } |
| 10747 | |
| 10748 | // ── Ghost-text prompt suggestion rendering ──────────────────────── |
| 10749 | |
| 10750 | #[test] |
| 10751 | fn ghost_text_renders_when_suggestion_set_and_input_empty() { |
| 10752 | let mut app = create_test_app(); |
| 10753 | app.prompt_suggestion = Some("What about error handling?".to_string()); |
| 10754 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 10755 | let mention_menu_entries = Vec::<String>::new(); |
| 10756 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 10757 | let area = Rect { |
| 10758 | x: 0, |
| 10759 | y: 0, |
| 10760 | width: 80, |
| 10761 | height: 5, |
| 10762 | }; |
| 10763 | let mut buf = Buffer::empty(area); |
| 10764 | widget.render(area, &mut buf); |
| 10765 | |
| 10766 | let rendered: String = buf |
| 10767 | .content |
| 10768 | .iter() |
| 10769 | .map(|c| c.symbol()) |
| 10770 | .collect::<Vec<_>>() |
| 10771 | .join(""); |
| 10772 | assert!( |
| 10773 | rendered.contains("What about error handling?"), |
| 10774 | "ghost text should render the suggestion. Got: {rendered}" |
| 10775 | ); |
| 10776 | let (x, y) = widget.cursor_pos(area).expect("empty composer caret"); |
| 10777 | assert_eq!(buf[(x, y)].fg, app.ui_theme.text_soft); |
| 10778 | } |
| 10779 | |
| 10780 | #[test] |
| 10781 | fn ghost_text_hidden_when_input_not_empty() { |
| 10782 | let mut app = create_test_app(); |
| 10783 | app.prompt_suggestion = Some("A suggestion".to_string()); |
| 10784 | app.input = "hello".to_string(); |
| 10785 | app.cursor_position = 5; |
| 10786 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 10787 | let mention_menu_entries = Vec::<String>::new(); |
| 10788 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 10789 | let area = Rect { |
| 10790 | x: 0, |
| 10791 | y: 0, |
| 10792 | width: 80, |
| 10793 | height: 5, |
| 10794 | }; |
| 10795 | let mut buf = Buffer::empty(area); |
| 10796 | widget.render(area, &mut buf); |
| 10797 | |
| 10798 | let has_suggestion = buf |
| 10799 | .content |
| 10800 | .iter() |
| 10801 | .any(|c| c.symbol().contains("A suggestion")); |
| 10802 | assert!( |
| 10803 | !has_suggestion, |
| 10804 | "suggestion should not render when input is non-empty" |
| 10805 | ); |
| 10806 | } |
| 10807 | |
| 10808 | #[test] |
| 10809 | fn ghost_text_hidden_when_no_suggestion() { |
| 10810 | let mut app = create_test_app(); |
| 10811 | app.prompt_suggestion = None; |
| 10812 | let slash_menu_entries = Vec::<SlashMenuEntry>::new(); |
| 10813 | let mention_menu_entries = Vec::<String>::new(); |
| 10814 | let widget = ComposerWidget::new(&app, 5, &slash_menu_entries, &mention_menu_entries); |
| 10815 | let area = Rect { |
| 10816 | x: 0, |
| 10817 | y: 0, |
| 10818 | width: 80, |
| 10819 | height: 5, |
| 10820 | }; |
| 10821 | let mut buf = Buffer::empty(area); |
| 10822 | widget.render(area, &mut buf); |
| 10823 | |
| 10824 | // When no suggestion and input is empty, placeholder text should appear |
| 10825 | // instead. The exact placeholder text is locale-dependent, so we check |
| 10826 | // that the suggestion text is NOT present. |
| 10827 | let has_placeholder_like_text = buf.content.iter().any(|c| !c.symbol().trim().is_empty()); |
| 10828 | assert!( |
| 10829 | has_placeholder_like_text, |
| 10830 | "some non-empty text should render as placeholder" |
| 10831 | ); |
| 10832 | } |
| 10833 | |
| 10834 | #[test] |
| 10835 | fn receipt_settle_cascade_is_bounded_and_ordered() { |
| 10836 | assert!(receipt_is_settling(0, 0)); |
| 10837 | assert!(!receipt_is_settling(0, 140)); |
| 10838 | assert!(receipt_is_settling(1, 140)); |
| 10839 | assert!(!receipt_is_settling(6, 560)); |
| 10840 | assert!(!receipt_is_settling(60, 560)); |
| 10841 | } |
| 10842 | |
| 10843 | /// Cold-versus-warm proof for the whole chat frame (#6652): the cached |
| 10844 | /// tool-run projection, the cached collapsed-row mapping, and the |
| 10845 | /// transcript cache's in-place update must show exactly what a frame built |
| 10846 | /// from empty caches shows, after every kind of transcript mutation. |
| 10847 | #[test] |
| 10848 | fn warm_chat_frame_matches_a_cold_frame_after_every_mutation() { |
| 10849 | fn next(state: &mut u64) -> u64 { |
| 10850 | *state ^= *state >> 12; |
| 10851 | *state ^= *state << 25; |
| 10852 | *state ^= *state >> 27; |
| 10853 | state.wrapping_mul(0x2545_F491_4F6C_DD1D) |
| 10854 | } |
| 10855 | fn below(state: &mut u64, bound: usize) -> usize { |
| 10856 | (next(state) % bound as u64) as usize |
| 10857 | } |
| 10858 | fn random_cell(state: &mut u64, serial: u64) -> HistoryCell { |
| 10859 | match below(state, 8) { |
| 10860 | 0 => HistoryCell::User { |
| 10861 | content: format!("prompt {serial} with enough words to wrap in a narrow pane"), |
| 10862 | }, |
| 10863 | 1 => HistoryCell::Assistant { |
| 10864 | content: format!("answer {serial}\n\n- one\n- two"), |
| 10865 | streaming: false, |
| 10866 | }, |
| 10867 | 2 => HistoryCell::Thinking { |
| 10868 | content: format!("reasoning {serial}\nmore reasoning\nand more"), |
| 10869 | streaming: false, |
| 10870 | duration_secs: Some(1.0), |
| 10871 | }, |
| 10872 | 3 => todo_write_cell(Some(&format!("task {serial}"))), |
| 10873 | _ => success_tool_cell( |
| 10874 | ["read_file", "list_dir", "web_search", "grep"][below(state, 4)], |
| 10875 | ), |
| 10876 | } |
| 10877 | } |
| 10878 | // Everything a frame leaves behind that a reader can observe: visible |
| 10879 | // rows, transcript rows, row -> cell map, row total. |
| 10880 | type Observed = (Vec<Line<'static>>, Vec<Line<'static>>, Vec<usize>, usize); |
| 10881 | fn frame(app: &mut App, area: Rect) -> Observed { |
| 10882 | let mut buf = Buffer::empty(area); |
| 10883 | // An empty transcript paints the empty state and never consults |
| 10884 | // the cache, so whatever it still holds is not on screen. |
| 10885 | let empty_state = should_render_empty_state(app); |
| 10886 | let widget = ChatWidget::new(app, area); |
| 10887 | widget.render(area, &mut buf); |
| 10888 | ( |
| 10889 | widget.lines.clone(), |
| 10890 | if empty_state { |
| 10891 | Vec::new() |
| 10892 | } else { |
| 10893 | app.viewport.transcript_cache.lines().to_vec() |
| 10894 | }, |
| 10895 | app.collapsed_cell_map.clone(), |
| 10896 | app.viewport.last_transcript_total, |
| 10897 | ) |
| 10898 | } |
| 10899 | |
| 10900 | // The same app, drawn with every cache empty. |
| 10901 | fn cold_frame(app: &mut App, area: Rect) -> Observed { |
| 10902 | let transcript = std::mem::replace( |
| 10903 | &mut app.viewport.transcript_cache, |
| 10904 | crate::tui::transcript::TranscriptViewCache::new(), |
| 10905 | ); |
| 10906 | let projection = std::mem::take(&mut app.tool_run_cache); |
| 10907 | let cold = frame(app, area); |
| 10908 | app.viewport.transcript_cache = transcript; |
| 10909 | app.tool_run_cache = projection; |
| 10910 | cold |
| 10911 | } |
| 10912 | |
| 10913 | for seed in 1..=6u64 { |
| 10914 | let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; |
| 10915 | let mut app = create_test_app(); |
| 10916 | app.low_motion = true; |
| 10917 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 10918 | app.tool_collapse_threshold = 3; |
| 10919 | let mut width = 90u16; |
| 10920 | let mut log: Vec<&'static str> = Vec::new(); |
| 10921 | let mut serial = 0u64; |
| 10922 | for step in 0..120 { |
| 10923 | serial += 1; |
| 10924 | let total = app.history.len(); |
| 10925 | let op = match below(&mut state, 18) { |
| 10926 | 0..=5 => { |
| 10927 | let cell = random_cell(&mut state, serial); |
| 10928 | app.add_message(cell); |
| 10929 | "add" |
| 10930 | } |
| 10931 | 6 if total > 0 => { |
| 10932 | let index = below(&mut state, total); |
| 10933 | app.history[index] = random_cell(&mut state, serial); |
| 10934 | app.bump_history_cell(index); |
| 10935 | "replace" |
| 10936 | } |
| 10937 | 7 => { |
| 10938 | let streaming = matches!( |
| 10939 | app.history.last(), |
| 10940 | Some(HistoryCell::Assistant { |
| 10941 | streaming: true, |
| 10942 | .. |
| 10943 | }) |
| 10944 | ); |
| 10945 | if streaming { |
| 10946 | let index = app.history.len() - 1; |
| 10947 | if let Some(HistoryCell::Assistant { content, .. }) = |
| 10948 | app.history.get_mut(index) |
| 10949 | { |
| 10950 | content.push_str(" streamed words\n"); |
| 10951 | } |
| 10952 | app.bump_history_cell(index); |
| 10953 | } else { |
| 10954 | app.add_message(HistoryCell::Assistant { |
| 10955 | content: "opening ".to_string(), |
| 10956 | streaming: true, |
| 10957 | }); |
| 10958 | } |
| 10959 | "stream" |
| 10960 | } |
| 10961 | 8 if total > 0 => { |
| 10962 | let index = total - 1; |
| 10963 | if let Some(HistoryCell::Assistant { streaming, .. }) = |
| 10964 | app.history.get_mut(index) |
| 10965 | { |
| 10966 | *streaming = false; |
| 10967 | } |
| 10968 | app.bump_history_cell(index); |
| 10969 | "finish stream" |
| 10970 | } |
| 10971 | 9 => { |
| 10972 | let cell = random_cell(&mut state, serial); |
| 10973 | app.active_cell |
| 10974 | .get_or_insert_with(ActiveCell::new) |
| 10975 | .push_untracked(cell); |
| 10976 | app.bump_active_cell_revision(); |
| 10977 | "active push" |
| 10978 | } |
| 10979 | 10 => { |
| 10980 | app.flush_active_cell(); |
| 10981 | "flush active" |
| 10982 | } |
| 10983 | 11 if total > 0 => { |
| 10984 | let index = below(&mut state, total + 2); |
| 10985 | if !app.collapsed_cells.remove(&index) { |
| 10986 | app.collapsed_cells.insert(index); |
| 10987 | } |
| 10988 | "hide cell" |
| 10989 | } |
| 10990 | 12 if total > 0 => { |
| 10991 | let index = below(&mut state, total); |
| 10992 | if !app.expanded_tool_runs.remove(&index) { |
| 10993 | app.expanded_tool_runs.insert(index); |
| 10994 | } |
| 10995 | "expand run" |
| 10996 | } |
| 10997 | 13 if total > 0 => { |
| 10998 | let index = below(&mut state, total); |
| 10999 | app.cell_folds.insert( |
| 11000 | index, |
| 11001 | if below(&mut state, 2) == 0 { |
| 11002 | crate::tui::history::TranscriptFold::Expanded |
| 11003 | } else { |
| 11004 | crate::tui::history::TranscriptFold::Collapsed |
| 11005 | }, |
| 11006 | ); |
| 11007 | "fold" |
| 11008 | } |
| 11009 | 14 => { |
| 11010 | app.tool_collapse_threshold = [0, 2, 3, 5][below(&mut state, 4)]; |
| 11011 | "threshold" |
| 11012 | } |
| 11013 | 15 => { |
| 11014 | width = [50, 90, 130][below(&mut state, 3)]; |
| 11015 | "width" |
| 11016 | } |
| 11017 | 16 if total > 0 && below(&mut state, 3) == 0 => { |
| 11018 | app.truncate_history_to(below(&mut state, total)); |
| 11019 | "truncate" |
| 11020 | } |
| 11021 | 17 if below(&mut state, 8) == 0 => { |
| 11022 | app.clear_history(); |
| 11023 | "clear" |
| 11024 | } |
| 11025 | _ => "no-op", |
| 11026 | }; |
| 11027 | log.push(op); |
| 11028 | let context = || format!("seed {seed} step {step}: {}", log.join(", ")); |
| 11029 | let area = Rect::new(0, 0, width, 18); |
| 11030 | |
| 11031 | let warm = frame(&mut app, area); |
| 11032 | // Nothing changed: the next frame is the same frame. |
| 11033 | assert_eq!(frame(&mut app, area), warm, "settled; {}", context()); |
| 11034 | |
| 11035 | let cold = cold_frame(&mut app, area); |
| 11036 | if warm.0 != cold.0 { |
| 11037 | let row = warm |
| 11038 | .0 |
| 11039 | .iter() |
| 11040 | .zip(&cold.0) |
| 11041 | .position(|(warm, cold)| warm != cold) |
| 11042 | .unwrap_or(warm.0.len().min(cold.0.len())); |
| 11043 | let plain = |lines: &[Line<'static>]| { |
| 11044 | lines |
| 11045 | .iter() |
| 11046 | .map(|line| line.to_string()) |
| 11047 | .collect::<Vec<_>>() |
| 11048 | .join(" / ") |
| 11049 | }; |
| 11050 | let kinds = app |
| 11051 | .history |
| 11052 | .iter() |
| 11053 | .map(|cell| format!("{cell:?}").chars().take(48).collect::<String>()) |
| 11054 | .collect::<Vec<_>>(); |
| 11055 | panic!( |
| 11056 | "visible rows differ at row {row} of {}/{}; cold frame repeatable: {}; {}\n warm: {:?}\n cold: {:?}\n map: {:?}\n cold map: {:?}\n warm rows: {}\n cold rows: {}\n history: {kinds:#?}\n collapsed {:?} expanded {:?} threshold {} active {}", |
| 11057 | warm.0.len(), |
| 11058 | cold.0.len(), |
| 11059 | cold_frame(&mut app, area) == cold, |
| 11060 | context(), |
| 11061 | warm.0.get(row), |
| 11062 | cold.0.get(row), |
| 11063 | warm.2, |
| 11064 | cold.2, |
| 11065 | plain(&warm.0), |
| 11066 | plain(&cold.0), |
| 11067 | app.collapsed_cells, |
| 11068 | app.expanded_tool_runs, |
| 11069 | app.tool_collapse_threshold, |
| 11070 | app.active_cell.as_ref().map_or(0, |a| a.entries().len()), |
| 11071 | ); |
| 11072 | } |
| 11073 | assert_eq!(warm.1, cold.1, "transcript rows; {}", context()); |
| 11074 | assert_eq!(warm.2, cold.2, "row -> cell map; {}", context()); |
| 11075 | assert_eq!(warm.3, cold.3, "row total; {}", context()); |
| 11076 | } |
| 11077 | } |
| 11078 | } |
| 11079 | |
| 11080 | /// Per-frame cost of preparing the collapsed transcript inputs, before |
| 11081 | /// (a filter pass with three hash lookups per cell) and after (a key check |
| 11082 | /// plus a gather over the cached mapping). Same binary, same history; |
| 11083 | /// `--ignored --nocapture`. |
| 11084 | #[test] |
| 11085 | #[ignore = "timing benchmark, not a correctness gate"] |
| 11086 | #[allow(clippy::print_stderr)] |
| 11087 | fn bench_collapsed_row_mapping_per_frame() { |
| 11088 | for turns in [1_000usize, 5_000] { |
| 11089 | let mut app = create_test_app(); |
| 11090 | app.tool_collapse_mode = ToolCollapseMode::Compact; |
| 11091 | app.tool_collapse_threshold = 3; |
| 11092 | for turn in 0..turns { |
| 11093 | app.add_message(HistoryCell::User { |
| 11094 | content: format!("question {turn}"), |
| 11095 | }); |
| 11096 | for name in ["read_file", "list_dir", "web_search"] { |
| 11097 | app.add_message(success_tool_cell(name)); |
| 11098 | } |
| 11099 | app.add_message(HistoryCell::Assistant { |
| 11100 | content: format!("answer {turn}"), |
| 11101 | streaming: false, |
| 11102 | }); |
| 11103 | } |
| 11104 | let area = Rect::new(0, 0, 120, 30); |
| 11105 | let mut buf = Buffer::empty(area); |
| 11106 | ChatWidget::new(&mut app, area).render(area, &mut buf); |
| 11107 | let history_len = app.history.len(); |
| 11108 | let frames = 200u32; |
| 11109 | |
| 11110 | let started = Instant::now(); |
| 11111 | let mut sink = 0usize; |
| 11112 | for _ in 0..frames { |
| 11113 | let cache = &app.tool_run_cache; |
| 11114 | let mut cells: Vec<&HistoryCell> = Vec::with_capacity(history_len); |
| 11115 | let mut revs: Vec<u64> = Vec::with_capacity(history_len); |
| 11116 | let mut map: Vec<usize> = Vec::with_capacity(history_len); |
| 11117 | for (idx, cell) in app.history.iter().enumerate() { |
| 11118 | if cache.superseded_todos.contains(&idx) |
| 11119 | || app.collapsed_cells.contains(&idx) |
| 11120 | || cache.hidden_indices.contains(&idx) |
| 11121 | { |
| 11122 | continue; |
| 11123 | } |
| 11124 | if let Some((summary, revision)) = cache.summaries.get(&idx) { |
| 11125 | cells.push(summary); |
| 11126 | revs.push(*revision); |
| 11127 | } else { |
| 11128 | cells.push(cell); |
| 11129 | revs.push(history_entry_revision(app.history_revisions[idx])); |
| 11130 | } |
| 11131 | map.push(idx); |
| 11132 | } |
| 11133 | sink += std::hint::black_box(cells.len() + revs.len() + map.len()); |
| 11134 | } |
| 11135 | let before = started.elapsed() / frames; |
| 11136 | |
| 11137 | let started = Instant::now(); |
| 11138 | for _ in 0..frames { |
| 11139 | app.tool_run_cache |
| 11140 | .refresh_filtered(history_len, &app.collapsed_cells); |
| 11141 | let filtered = &app.tool_run_cache.filtered; |
| 11142 | let mut cells: Vec<&HistoryCell> = Vec::with_capacity(filtered.original.len()); |
| 11143 | let mut revs: Vec<u64> = Vec::with_capacity(filtered.original.len()); |
| 11144 | for &original in &filtered.original { |
| 11145 | cells.push(&app.history[original]); |
| 11146 | revs.push(history_entry_revision(app.history_revisions[original])); |
| 11147 | } |
| 11148 | for &slot in &filtered.summary_slots { |
| 11149 | if let Some((summary, revision)) = |
| 11150 | app.tool_run_cache.summaries.get(&filtered.original[slot]) |
| 11151 | { |
| 11152 | cells[slot] = summary; |
| 11153 | revs[slot] = *revision; |
| 11154 | } |
| 11155 | } |
| 11156 | app.collapsed_cell_map.clone_from(&filtered.original); |
| 11157 | sink += std::hint::black_box(cells.len() + revs.len()); |
| 11158 | } |
| 11159 | let after = started.elapsed() / frames; |
| 11160 | eprintln!( |
| 11161 | "#6652 collapsed inputs: {history_len} cells, before {before:?}/frame, after {after:?}/frame ({sink})" |
| 11162 | ); |
| 11163 | } |
| 11164 | } |
| 11165 | } |
| 11166 | |
| 11167 | #[cfg(test)] |
| 11168 | #[path = "mounted_composer_tests.rs"] |
| 11169 | mod mounted_composer_tests; |
| 11170 | |
| 11171 | #[cfg(test)] |
| 11172 | #[path = "mounted_transcript_tests.rs"] |
| 11173 | mod mounted_transcript_tests; |
| 11174 | |
| 11175 | #[cfg(test)] |
| 11176 | fn test_native_ocean_caps() -> codewhale_ratatui::Caps { |
| 11177 | crate::tui::color_compat::ColorCompatBackend::new( |
| 11178 | std::io::sink(), |
| 11179 | palette::ColorDepth::TrueColor, |
| 11180 | palette::PaletteMode::Dark, |
| 11181 | ) |
| 11182 | .native_ocean_caps() |
| 11183 | } |
| 11184 |