| 1 | //! Frame composition: the draw entry point, the builders that assemble what a |
| 2 | //! frame needs, and streaming-text accumulation into history cells. |
| 3 | //! |
| 4 | //! Moved verbatim out of `ui.rs`. |
| 5 | |
| 6 | use super::*; |
| 7 | use crate::tui::infoline::{InfoLine, InfoSegment, InfoSegmentId, infoline_hitboxes}; |
| 8 | use codewhale_tui_kit::osc8; |
| 9 | use ratatui::buffer::{Buffer, CellDiffOption}; |
| 10 | |
| 11 | /// Context window percentage for the metrics line's reading — the same |
| 12 | /// snapshot the posture bar's ≥80% microcopy reads, so the two can never |
| 13 | /// disagree. |
| 14 | pub(crate) fn info_context_percent(app: &App) -> u8 { |
| 15 | crate::tui::phase_strip::context_percent_from_app(app) |
| 16 | } |
| 17 | |
| 18 | /// Format the session's cumulative usage chip for the metrics line. `/cost` |
| 19 | /// has its own detailed receipt and coverage report; it does not call this |
| 20 | /// formatter. Chips without a cost display produce an empty string. |
| 21 | /// |
| 22 | /// Incomplete cost includes its receipt's reason, including an unclassified |
| 23 | /// billing route. A provider switch cannot erase earlier missing coverage. |
| 24 | pub(crate) fn session_cost_label(app: &App) -> String { |
| 25 | use codewhale_engine::route_billing::UsageChip; |
| 26 | let usage_chip = app.cumulative_usage_chip(); |
| 27 | match &usage_chip { |
| 28 | UsageChip::Money(amount) => Some(amount.clone()), |
| 29 | UsageChip::PricedSubtotal { .. } | UsageChip::Unknown(_) => { |
| 30 | codewhale_engine::route_billing::format_usage_chip(&usage_chip, app.ui_locale) |
| 31 | } |
| 32 | _ => None, |
| 33 | } |
| 34 | .unwrap_or_default() |
| 35 | } |
| 36 | |
| 37 | /// The clock-dependent billing tier of the active route, when the route has |
| 38 | /// one: DeepSeek's V4 Pro/Flash and Flash halve their rates off-peak. `None` |
| 39 | /// for flat-priced routes, for other vendors, and while auto routing has not |
| 40 | /// pinned a concrete model. |
| 41 | pub(crate) fn billing_tier_label(app: &App, now: chrono::DateTime<chrono::Utc>) -> Option<String> { |
| 42 | use codewhale_config::ProviderKind; |
| 43 | use codewhale_localization::{MessageId, tr}; |
| 44 | if app.auto_model || !matches!(app.api_provider, ProviderKind::Deepseek) { |
| 45 | return None; |
| 46 | } |
| 47 | let peak = codewhale_engine::pricing::deepseek_time_tier(&app.model, now)?; |
| 48 | let id = if peak { |
| 49 | MessageId::InfoLinePeak |
| 50 | } else { |
| 51 | MessageId::InfoLineOffPeak |
| 52 | }; |
| 53 | Some(tr(app.ui_locale, id).into_owned()) |
| 54 | } |
| 55 | |
| 56 | /// Output tokens for the metrics line: the live stream's running estimate, |
| 57 | /// else the last turn's provider receipt. Request throughput is independently |
| 58 | /// sourced from SessionMetrics, so a long tool call cannot lower that rate. |
| 59 | fn output_tokens(app: &App) -> Option<u64> { |
| 60 | if app.is_loading && app.streaming_output_token_estimate > 0 { |
| 61 | return Some(app.streaming_output_token_estimate); |
| 62 | } |
| 63 | app.session |
| 64 | .last_completion_tokens |
| 65 | .filter(|tokens| *tokens > 0) |
| 66 | .map(u64::from) |
| 67 | } |
| 68 | |
| 69 | /// Build the metrics line's segments from live `App` state. Shedding is the |
| 70 | /// widget's job; this only states the facts, in display order: model, |
| 71 | /// context, cost, balance, time to first token, output rate, output tokens. |
| 72 | /// |
| 73 | /// Repository and branch left this row (2026-09-02): the launch header and |
| 74 | /// the git bottom view own them. Fleet, whale and automation counts left too — |
| 75 | /// the posture bar's live counts own activity. |
| 76 | /// |
| 77 | /// Session metrics follow the matching [`StatusItem`] in `app.status_items`, |
| 78 | /// which `/statusline` edits and `tui.status_items` persists. The active goal |
| 79 | /// and available-update notice follow their own live state. |
| 80 | pub(crate) fn info_segments(app: &App, width: u16) -> Vec<InfoSegment> { |
| 81 | use codewhale_localization::MessageId; |
| 82 | use codewhale_palette::ChromeInk; |
| 83 | use codewhale_runtime::config::StatusItem; |
| 84 | let mut segments = Vec::new(); |
| 85 | let tier = crate::tui::underwater::ShellTier::for_chrome_width(width); |
| 86 | let shows = |item: StatusItem| app.status_items.contains(&item); |
| 87 | let pct = info_context_percent(app); |
| 88 | let context_label = app.tr(MessageId::InfoLineContext); |
| 89 | |
| 90 | // Where this session writes (#6112): the workspace leaf and the branch |
| 91 | // the next commit lands on. Both read cached state only — the branch |
| 92 | // comes from `app.workspace_context`, refreshed off the render path on |
| 93 | // the workspace-context TTL, so neither chip costs IO per frame. They |
| 94 | // lead the row: identity of place before identity of route. The branch |
| 95 | // chip degrades to absent outside a repository rather than printing a |
| 96 | // permanent dash. |
| 97 | if shows(StatusItem::Workspace) { |
| 98 | let name = crate::tui::workspace_context::status_workspace_name( |
| 99 | &app.workspace, |
| 100 | app.workspace_is_linked_worktree, |
| 101 | ); |
| 102 | segments.push(InfoSegment::new( |
| 103 | InfoSegmentId::Workspace, |
| 104 | "", |
| 105 | crate::tui::workspace_context::truncate_left( |
| 106 | &name, |
| 107 | crate::tui::workspace_context::STATUS_CHIP_MAX_WIDTH, |
| 108 | ), |
| 109 | ChromeInk::MetadataValue, |
| 110 | )); |
| 111 | } |
| 112 | if shows(StatusItem::GitBranch) |
| 113 | && let Some(branch) = app |
| 114 | .workspace_context |
| 115 | .as_deref() |
| 116 | .and_then(crate::tui::workspace_context::branch_from_context) |
| 117 | { |
| 118 | segments.push(InfoSegment::new( |
| 119 | InfoSegmentId::GitBranch, |
| 120 | "", |
| 121 | crate::tui::workspace_context::truncate_left( |
| 122 | &if app.workspace_is_linked_worktree { |
| 123 | format!("{branch} (wt)") |
| 124 | } else { |
| 125 | branch.to_string() |
| 126 | }, |
| 127 | crate::tui::workspace_context::STATUS_CHIP_MAX_WIDTH, |
| 128 | ), |
| 129 | ChromeInk::MetadataValue, |
| 130 | )); |
| 131 | } |
| 132 | |
| 133 | // Route identity — the old identity band's fact, same shed discipline: |
| 134 | // provider first, then effort, whole names or none. When no model is |
| 135 | // configured the segment says so and waits. |
| 136 | // Off the row when the user says so: `/model`, the picker and the launch |
| 137 | // header all still name the route. |
| 138 | if shows(StatusItem::Model) { |
| 139 | let (_, model) = app.effective_route_identity_display(); |
| 140 | // A keyless first run carries a default model id but nothing can |
| 141 | // answer it: the chip says "not connected", matching the launch |
| 142 | // card's no-model line (U3), instead of naming a route that fails. |
| 143 | if model.is_empty() || app.onboarding_needs_api_key { |
| 144 | segments.push(InfoSegment::new( |
| 145 | InfoSegmentId::Model, |
| 146 | app.tr(MessageId::StartupDefaultSubjectModel).as_ref(), |
| 147 | app.tr(MessageId::InfoLineNotConnected).as_ref(), |
| 148 | ChromeInk::Waiting, |
| 149 | )); |
| 150 | } else { |
| 151 | // The context reading and the metrics claim the rest of the row; |
| 152 | // the route sheds its own qualifiers first. |
| 153 | let budget = crate::tui::phase_strip::info_route_budget(width); |
| 154 | let fields = info_route_fields(app, tier, budget).unwrap_or_else(|| { |
| 155 | vec![crate::tui::phase_strip::RouteIdentityField { |
| 156 | kind: crate::tui::phase_strip::RouteFieldKind::Model, |
| 157 | text: crate::tui::phase_strip::bare_model_reading( |
| 158 | model, |
| 159 | width, |
| 160 | shows(StatusItem::ContextPercent).then_some((context_label.as_ref(), pct)), |
| 161 | ), |
| 162 | }] |
| 163 | }); |
| 164 | segments.push(InfoSegment::route( |
| 165 | fields, |
| 166 | crate::tui::color_compat::ascii_safe_enabled(), |
| 167 | )); |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // The context reading: painted here and nowhere else, at every |
| 172 | // fullness. The 0.9.12 row went silent below 50% and left most of a |
| 173 | // session with no context signal at all (#5950); watching the number |
| 174 | // climb from 4% is the whole point of the reading. At the 80% cap the |
| 175 | // whole reading turns to the error token — it is the one fact on this |
| 176 | // row that becomes a problem rather than a status. |
| 177 | if shows(StatusItem::ContextPercent) { |
| 178 | segments.push(InfoSegment::new( |
| 179 | InfoSegmentId::Context, |
| 180 | context_label.as_ref(), |
| 181 | format!("{pct}%"), |
| 182 | // The posture bar one row above calls this exact threshold |
| 183 | // `ChromeInk::Attention` (`phase_strip::at_context_cap`, also >= 80). |
| 184 | // One condition, one family: a full context is consequential, not a |
| 185 | // failure — the next turn still runs and `/compact` is the remedy. |
| 186 | if pct >= 80 { |
| 187 | ChromeInk::Attention |
| 188 | } else { |
| 189 | ChromeInk::Info |
| 190 | }, |
| 191 | )); |
| 192 | } |
| 193 | |
| 194 | // The active goal's live reading: elapsed time plus the model's latest |
| 195 | // reported progress with its bar. Painted only while a goal is actually |
| 196 | // active — the percent is the model's own estimate, and the row never |
| 197 | // invents one for a goal that has not reported. |
| 198 | if app.goal.status == codewhale_engine::tools::goal::GoalStatus::Active |
| 199 | && app.goal.objective.is_some() |
| 200 | && let Some(started) = app.goal.started_at |
| 201 | { |
| 202 | let secs = started.elapsed().as_secs(); |
| 203 | let elapsed = if secs < 60 { |
| 204 | format!("{secs}s") |
| 205 | } else { |
| 206 | format!("{}m", secs / 60) |
| 207 | }; |
| 208 | let value = match app.goal.progress.as_ref() { |
| 209 | Some(progress) => format!( |
| 210 | "({elapsed}) {}% {}", |
| 211 | progress.percent, |
| 212 | codewhale_engine::tools::goal::goal_progress_bar(progress.percent) |
| 213 | ), |
| 214 | None => format!("({elapsed})"), |
| 215 | }; |
| 216 | segments.push(InfoSegment::new( |
| 217 | InfoSegmentId::Goal, |
| 218 | app.tr(MessageId::GoalProgressLabel).as_ref(), |
| 219 | value, |
| 220 | ChromeInk::Info, |
| 221 | )); |
| 222 | } |
| 223 | |
| 224 | let cost = session_cost_label(app); |
| 225 | if shows(StatusItem::Cost) && !cost.is_empty() { |
| 226 | segments.push(InfoSegment::new( |
| 227 | InfoSegmentId::Cost, |
| 228 | "", |
| 229 | cost, |
| 230 | ChromeInk::MetadataValue, |
| 231 | )); |
| 232 | } |
| 233 | |
| 234 | // DeepSeek bills by the clock: the same flag that halves the rates |
| 235 | // off-peak is painted beside the cost, so the operator can see which tier |
| 236 | // the next turn buys without opening /cost. Gated on the cost item, whose |
| 237 | // owner asked for price readings by name. |
| 238 | if shows(StatusItem::Cost) |
| 239 | && let Some(tier) = billing_tier_label(app, chrono::Utc::now()) |
| 240 | { |
| 241 | segments.push(InfoSegment::new( |
| 242 | InfoSegmentId::BillingTier, |
| 243 | "", |
| 244 | tier, |
| 245 | ChromeInk::MetadataValue, |
| 246 | )); |
| 247 | } |
| 248 | |
| 249 | // The prepaid-credit reading: opt-in, and the same status item that |
| 250 | // authorises the background fetch (`should_fetch_provider_balance`), so |
| 251 | // the row can only show a number this session actually asked for. |
| 252 | if shows(StatusItem::Balance) |
| 253 | && let Some(balance) = app.balance_cell.lock().ok().and_then(|guard| { |
| 254 | guard |
| 255 | .as_ref() |
| 256 | .and_then(codewhale_engine::pricing::BalanceInfo::chip_label) |
| 257 | }) |
| 258 | { |
| 259 | segments.push(InfoSegment::new( |
| 260 | InfoSegmentId::Balance, |
| 261 | app.tr(MessageId::FooterBalancePrefix).as_ref(), |
| 262 | balance, |
| 263 | ChromeInk::MetadataValue, |
| 264 | )); |
| 265 | } |
| 266 | |
| 267 | // The DeepSeek-harness session metrics, from the same accumulators |
| 268 | // `/cost` prints: nothing here is estimated except the live stream's |
| 269 | // running token count, which the provider's receipt replaces. |
| 270 | if (shows(StatusItem::SessionMetrics) || shows(StatusItem::Ttft)) |
| 271 | && let Some(ttft) = app.session_metrics.ttft_average() |
| 272 | { |
| 273 | segments.push(InfoSegment::new( |
| 274 | InfoSegmentId::Ttft, |
| 275 | app.tr(MessageId::InfoLineTtft).as_ref(), |
| 276 | crate::tui::session_metrics::format_duration(ttft), |
| 277 | ChromeInk::MetadataValue, |
| 278 | )); |
| 279 | } |
| 280 | if (shows(StatusItem::SessionMetrics) || shows(StatusItem::OutputRate)) |
| 281 | && let Some(rate) = app.session_metrics.tokens_per_second() |
| 282 | { |
| 283 | segments.push(InfoSegment::new( |
| 284 | InfoSegmentId::Rate, |
| 285 | "", |
| 286 | format!( |
| 287 | "{} {}", |
| 288 | crate::tui::session_metrics::format_rate(rate), |
| 289 | app.tr(MessageId::SessionMetricsTokensPerSecond) |
| 290 | ), |
| 291 | ChromeInk::MetadataValue, |
| 292 | )); |
| 293 | } |
| 294 | if let Some(tokens) = output_tokens(app) { |
| 295 | if shows(StatusItem::Cache) |
| 296 | && let Some(cache_pct) = |
| 297 | crate::tui::session_metrics::snapshot_from_app(app).cache_hit_percent |
| 298 | { |
| 299 | segments.push(InfoSegment::new( |
| 300 | InfoSegmentId::Cache, |
| 301 | "cache", |
| 302 | format!("{cache_pct}%"), |
| 303 | ChromeInk::MetadataValue, |
| 304 | )); |
| 305 | } |
| 306 | if shows(StatusItem::Tokens) { |
| 307 | segments.push(InfoSegment::new( |
| 308 | InfoSegmentId::OutputTokens, |
| 309 | "↓", |
| 310 | crate::tui::session_metrics::format_tokens(tokens), |
| 311 | ChromeInk::MetadataValue, |
| 312 | )); |
| 313 | } |
| 314 | } else { |
| 315 | if shows(StatusItem::Cache) |
| 316 | && let Some(cache_pct) = |
| 317 | crate::tui::session_metrics::snapshot_from_app(app).cache_hit_percent |
| 318 | { |
| 319 | segments.push(InfoSegment::new( |
| 320 | InfoSegmentId::Cache, |
| 321 | "cache", |
| 322 | format!("{cache_pct}%"), |
| 323 | ChromeInk::MetadataValue, |
| 324 | )); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | if let Some(label) = app.update_available.as_deref() { |
| 329 | segments.push(InfoSegment::new( |
| 330 | InfoSegmentId::Update, |
| 331 | "", |
| 332 | label, |
| 333 | ChromeInk::Info, |
| 334 | )); |
| 335 | } |
| 336 | |
| 337 | segments |
| 338 | } |
| 339 | |
| 340 | /// Route fields the info line paints, or `None` when it paints the |
| 341 | /// "not connected" chip instead. The segment retains its fields for pointer routing. |
| 342 | fn info_route_fields( |
| 343 | app: &App, |
| 344 | tier: crate::tui::underwater::ShellTier, |
| 345 | budget: usize, |
| 346 | ) -> Option<Vec<crate::tui::phase_strip::RouteIdentityField>> { |
| 347 | if app.onboarding_needs_api_key { |
| 348 | return None; |
| 349 | } |
| 350 | crate::tui::phase_strip::route_identity_fields(app, tier, budget) |
| 351 | } |
| 352 | |
| 353 | /// The info line's controls that actually painted in this frame. |
| 354 | /// |
| 355 | /// The route target intentionally contains no copied route metadata. The |
| 356 | /// provider picker retains catalog, readiness, credential, and apply |
| 357 | /// authority; chrome only exposes its entry point. |
| 358 | #[derive(Debug, Clone, Copy, Default)] |
| 359 | struct InfoLineInteractionHitboxes { |
| 360 | context: Option<Rect>, |
| 361 | /// The provider name inside the route segment, when the row is wide |
| 362 | /// enough to render one. |
| 363 | route: Option<Rect>, |
| 364 | /// The model name and its effort tier — one span, because they are |
| 365 | /// always adjacent and `/model` owns both. |
| 366 | model: Option<Rect>, |
| 367 | update: Option<Rect>, |
| 368 | } |
| 369 | |
| 370 | /// Split the route segment's rect back into its fields. |
| 371 | /// |
| 372 | /// The segment renders as `provider · model · effort`; a click on the |
| 373 | /// provider belongs to `/provider` and a click on the model or its effort |
| 374 | /// tier belongs to `/model`. Widths come from the same field texts the |
| 375 | /// segment was built from, so the split cannot disagree with what is on |
| 376 | /// screen. Returns `(provider, model-and-effort)`. |
| 377 | fn split_route_hitbox( |
| 378 | fields: &[crate::tui::phase_strip::RouteIdentityField], |
| 379 | area: Rect, |
| 380 | ) -> (Option<Rect>, Option<Rect>) { |
| 381 | use crate::tui::phase_strip::RouteFieldKind; |
| 382 | let mut provider = None; |
| 383 | let mut model: Option<Rect> = None; |
| 384 | for (kind, rect) in crate::tui::infoline::route_field_cells(fields, area) { |
| 385 | match kind { |
| 386 | RouteFieldKind::Provider => provider = Some(rect), |
| 387 | // Model and effort are adjacent and share a destination, so the |
| 388 | // span grows rather than replacing — a two-target registration |
| 389 | // for one idea just gives the pointer a seam to fall into. |
| 390 | RouteFieldKind::Model | RouteFieldKind::Effort => { |
| 391 | model = Some(match model { |
| 392 | Some(prev) => Rect { |
| 393 | x: prev.x, |
| 394 | y: prev.y, |
| 395 | width: rect.right().saturating_sub(prev.x), |
| 396 | height: 1, |
| 397 | }, |
| 398 | None => rect, |
| 399 | }); |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | (provider, model) |
| 404 | } |
| 405 | |
| 406 | /// Render the info line into its one row and record its segment |
| 407 | /// hitboxes (spec §5b `Constraint::Length(1)`). The session shell and launch |
| 408 | /// screen both use this row, keeping the visible identity and notice facts |
| 409 | /// consistent between pre- and post-session states. Segment rects are |
| 410 | /// recorded for hover (this frame's highlight resolves against the previous |
| 411 | /// frame's rects, the standard one-frame-lag registry pattern) and for typed |
| 412 | /// click routing. |
| 413 | fn render_info_row( |
| 414 | f: &mut Frame, |
| 415 | app: &mut App, |
| 416 | area: Rect, |
| 417 | identity_only: bool, |
| 418 | ) -> InfoLineInteractionHitboxes { |
| 419 | if area.height == 0 { |
| 420 | app.viewport.last_infoline_hitboxes.clear(); |
| 421 | return InfoLineInteractionHitboxes::default(); |
| 422 | } |
| 423 | // The two bottom rows share the composer's one-cell inset. Paint the |
| 424 | // full band before insetting so hover/click geometry uses the same area. |
| 425 | Block::default() |
| 426 | .style(Style::default().bg(app.ui_theme.header_bg)) |
| 427 | .render(area, f.buffer_mut()); |
| 428 | let area = area.inner(ratatui::layout::Margin::new(u16::from(area.width >= 8), 0)); |
| 429 | let mut segments = info_segments(app, area.width); |
| 430 | if identity_only { |
| 431 | segments.retain(|segment| { |
| 432 | matches!( |
| 433 | segment.id, |
| 434 | InfoSegmentId::Model |
| 435 | | InfoSegmentId::Workspace |
| 436 | | InfoSegmentId::GitBranch |
| 437 | | InfoSegmentId::Update |
| 438 | ) |
| 439 | }); |
| 440 | } |
| 441 | let hovered = app.last_mouse_pos.and_then(|(mx, my)| { |
| 442 | app.viewport |
| 443 | .last_infoline_hitboxes |
| 444 | .iter() |
| 445 | .find(|hb| { |
| 446 | matches!( |
| 447 | hb.id, |
| 448 | InfoSegmentId::Model | InfoSegmentId::Context | InfoSegmentId::Update |
| 449 | ) && hb.area.x <= mx |
| 450 | && mx < hb.area.right() |
| 451 | && hb.area.y == my |
| 452 | }) |
| 453 | .map(|hb| hb.id) |
| 454 | }); |
| 455 | // The metrics line no longer pins `/help` forever (founder, 2026-09-08). |
| 456 | // The route still appears until its binding has been used, then retires |
| 457 | // with the other footer hints so the row stays quiet once help is learned. |
| 458 | let help_hint = if crate::tui::footer_hints::retired( |
| 459 | &app.footer_hint_uses, |
| 460 | crate::tui::footer_hints::HELP_ROUTE, |
| 461 | ) { |
| 462 | String::new() |
| 463 | } else { |
| 464 | crate::tui::shell_key_routing::info_help_hint(app.ui_locale) |
| 465 | }; |
| 466 | let info = InfoLine::new(&app.ui_theme, &help_hint, &segments) |
| 467 | .ascii_safe(crate::tui::color_compat::ascii_safe_enabled()) |
| 468 | .hovered(hovered) |
| 469 | .compact(app.metrics_line == codewhale_runtime::config::ChromeRowPreset::Compact); |
| 470 | let hitboxes = infoline_hitboxes(&info, area); |
| 471 | let route_area = hitboxes |
| 472 | .iter() |
| 473 | .find(|hitbox| hitbox.id == InfoSegmentId::Model) |
| 474 | .map(|hitbox| hitbox.area); |
| 475 | let route_fields = segments |
| 476 | .iter() |
| 477 | .find(|segment| !segment.route_fields.is_empty()) |
| 478 | .map(|segment| segment.route_fields.as_slice()); |
| 479 | let (provider_area, model_area) = match (route_area, route_fields) { |
| 480 | (Some(area), Some(fields)) => split_route_hitbox(fields, area), |
| 481 | // No configured model: the segment says so and is not a route control. |
| 482 | // No drawn segment: nothing to point at either way. |
| 483 | (area, None) => (None, area), |
| 484 | (None, Some(_)) => (None, None), |
| 485 | }; |
| 486 | let interaction_hitboxes = InfoLineInteractionHitboxes { |
| 487 | context: crate::tui::infoline::context_meter_hitbox(&info, area), |
| 488 | route: provider_area, |
| 489 | model: model_area, |
| 490 | update: hitboxes |
| 491 | .iter() |
| 492 | .find(|hitbox| hitbox.id == InfoSegmentId::Update) |
| 493 | .map(|hitbox| hitbox.area), |
| 494 | }; |
| 495 | // Keep the row's quiet background under the widget itself. |
| 496 | let buf = f.buffer_mut(); |
| 497 | Block::default() |
| 498 | .style(Style::default().bg(app.ui_theme.header_bg)) |
| 499 | .render(area, buf); |
| 500 | ratatui::widgets::Widget::render(info, area, buf); |
| 501 | if !identity_only |
| 502 | && !app.viewport.working_glow_visible |
| 503 | && app.posture_bar == codewhale_runtime::config::ChromeRowPreset::Full |
| 504 | && !crate::tui::pet_watch::main_view(app) |
| 505 | && !app.onboarding_needs_api_key |
| 506 | && hovered != Some(InfoSegmentId::Model) |
| 507 | && !app.last_mouse_pos.is_some_and(|(x, y)| { |
| 508 | route_area.is_some_and(|route| route.x <= x && x < route.right() && route.y == y) |
| 509 | }) |
| 510 | && app.motion_policy().should_request_animation_frames() |
| 511 | && matches!( |
| 512 | crate::tui::underwater::ShellPhase::from_app(app), |
| 513 | crate::tui::underwater::ShellPhase::Working |
| 514 | ) |
| 515 | && matches!( |
| 516 | crate::tui::underwater::LiveActivity::from_app(app).kind(), |
| 517 | crate::tui::underwater::LiveActivityKind::Working |
| 518 | | crate::tui::underwater::LiveActivityKind::Reasoning |
| 519 | ) |
| 520 | && let Some((mut caps, started)) = app.viewport.ocean_caps.zip(app.turn_started_at) |
| 521 | && caps.depth == codewhale_ratatui::color::ColorDepth::TrueColor |
| 522 | && let Some(appearance) = |
| 523 | codewhale_ratatui::detect::appearance_for_background(app.ui_theme.header_bg) |
| 524 | && app.ui_theme.header_bg != app.ui_theme.surface_bg |
| 525 | && matches!(app.ui_theme.status_working, ratatui::style::Color::Rgb(..)) |
| 526 | && let Some(model_area) = model_area |
| 527 | && let Some(model) = match route_fields { |
| 528 | Some(fields) => fields |
| 529 | .iter() |
| 530 | .find(|field| field.kind == crate::tui::phase_strip::RouteFieldKind::Model) |
| 531 | .map(|field| field.text.as_str()), |
| 532 | None => segments |
| 533 | .iter() |
| 534 | .find(|segment| segment.id == InfoSegmentId::Model && segment.label.is_empty()) |
| 535 | .map(|segment| segment.value.as_str()), |
| 536 | } |
| 537 | { |
| 538 | use unicode_width::UnicodeWidthStr as _; |
| 539 | let width = model.width().min(usize::from(model_area.width)); |
| 540 | if width > 0 { |
| 541 | caps.appearance = appearance; |
| 542 | let theme = codewhale_ratatui::Theme::new(caps); |
| 543 | let mode = |
| 544 | codewhale_ratatui::MotionMode::from_settings(app.low_motion, app.fancy_animations); |
| 545 | codewhale_ratatui::paint_working_glow( |
| 546 | buf, |
| 547 | Rect { |
| 548 | width: width as u16, |
| 549 | ..model_area |
| 550 | }, |
| 551 | model, |
| 552 | started.elapsed(), |
| 553 | codewhale_ratatui::MotionPolicy::new(mode, &theme), |
| 554 | app.ui_theme.status_working, |
| 555 | app.ui_theme.header_bg, |
| 556 | ); |
| 557 | app.viewport.working_glow_visible = true; |
| 558 | } |
| 559 | } |
| 560 | app.viewport.last_infoline_hitboxes = hitboxes; |
| 561 | interaction_hitboxes |
| 562 | } |
| 563 | |
| 564 | /// Paint the workbar: live runs first (in start order), then settled ones, |
| 565 | /// each with the runtime's count of follow-ups queued on its busy agents. |
| 566 | fn render_workbar(f: &mut Frame, app: &App, area: Rect) { |
| 567 | let queued_for = |panel: &crate::tui::widgets::workflow_panel::WorkflowPanel| { |
| 568 | panel |
| 569 | .phases |
| 570 | .iter() |
| 571 | .flat_map(|phase| phase.rows.iter()) |
| 572 | .filter(|row| row.status.is_running()) |
| 573 | .filter_map(|row| app.agent_queued_follow_ups.get(&row.task_id)) |
| 574 | .sum::<usize>() |
| 575 | }; |
| 576 | let (live, settled): (Vec<_>, Vec<_>) = app |
| 577 | .workflow_runs |
| 578 | .iter() |
| 579 | .partition(|panel| panel.lifecycle.is_running()); |
| 580 | let runs: Vec<crate::tui::widgets::workbar::WorkbarRun<'_>> = live |
| 581 | .into_iter() |
| 582 | .chain(settled) |
| 583 | .map(|panel| crate::tui::widgets::workbar::WorkbarRun { |
| 584 | panel, |
| 585 | queued: queued_for(panel), |
| 586 | }) |
| 587 | .collect(); |
| 588 | let now_ms = std::time::SystemTime::now() |
| 589 | .duration_since(std::time::UNIX_EPOCH) |
| 590 | .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)) |
| 591 | .unwrap_or_default(); |
| 592 | let buf = f.buffer_mut(); |
| 593 | Block::default() |
| 594 | .style(Style::default().bg(app.ui_theme.footer_bg)) |
| 595 | .render(area, buf); |
| 596 | crate::tui::widgets::workbar::render(area, buf, &runs, now_ms, &app.ui_theme, app.ui_locale); |
| 597 | } |
| 598 | |
| 599 | /// Register the chrome that already answers a click, so it also answers the |
| 600 | /// pointer. |
| 601 | /// |
| 602 | /// "What responds to the pointer going over it right now across the entire |
| 603 | /// app" — the honest answer had been: links, truncated text, and the info |
| 604 | /// line. The jump-to-latest button, the plugin call-to-action, and the |
| 605 | /// workflow panel all handled clicks in `mouse_ui` and lit up for nothing, |
| 606 | /// which teaches a person that pointing at things does not work here. |
| 607 | /// |
| 608 | /// This runs after the frame body has recorded its rects and before hover is |
| 609 | /// resolved, so it stays one list rather than a `register_rect` scattered |
| 610 | /// through every widget that happens to remember. |
| 611 | fn register_clickable_chrome_for_hover(app: &App) { |
| 612 | use codewhale_localization::MessageId; |
| 613 | let targets: [(Option<Rect>, MessageId); 5] = [ |
| 614 | ( |
| 615 | app.viewport.jump_to_latest_button_area, |
| 616 | MessageId::KbJumpTopBottom, |
| 617 | ), |
| 618 | ( |
| 619 | // The pinned prompt header jumps to the user message it names. |
| 620 | app.viewport.pinned_prompt_area, |
| 621 | MessageId::PinnedPromptJumpToMessage, |
| 622 | ), |
| 623 | ( |
| 624 | app.viewport.last_plugin_cta_review_area, |
| 625 | MessageId::PluginCtaReview, |
| 626 | ), |
| 627 | ( |
| 628 | app.viewport.last_plugin_cta_dismiss_area, |
| 629 | MessageId::KbCloseMenu, |
| 630 | ), |
| 631 | ( |
| 632 | // A workbar row opens `/workflows`. |
| 633 | app.viewport.last_workbar_area, |
| 634 | MessageId::CmdWorkflowDescription, |
| 635 | ), |
| 636 | ]; |
| 637 | for (area, label) in targets { |
| 638 | let Some(area) = area else { continue }; |
| 639 | crate::tui::hover_layer::register_rect( |
| 640 | crate::tui::hover_hit::HoverTargetKind::Link, |
| 641 | area, |
| 642 | codewhale_localization::tr(app.ui_locale, label).into_owned(), |
| 643 | false, |
| 644 | ); |
| 645 | } |
| 646 | |
| 647 | // The composer's `[↵]` submit control. It registers only when a click |
| 648 | // there would actually send: an affordance that lights up and then does |
| 649 | // nothing is the same defect as one that acts without lighting up. |
| 650 | if let Some(composer) = app.viewport.last_composer_area |
| 651 | && let Some(submit) = crate::tui::widgets::active_composer_submit_rect(app, composer) |
| 652 | && (app.composer_enter_would_submit(true, Instant::now()) |
| 653 | || app.decide_composer_submit(crate::tui::app::ComposerSubmitChord::Enter) |
| 654 | == crate::tui::app::ComposerSubmitAction::SendQueuedNow) |
| 655 | { |
| 656 | crate::tui::hover_layer::register_rect( |
| 657 | crate::tui::hover_hit::HoverTargetKind::Link, |
| 658 | submit, |
| 659 | codewhale_localization::tr( |
| 660 | app.ui_locale, |
| 661 | codewhale_localization::MessageId::KbSendDraft, |
| 662 | ) |
| 663 | .into_owned(), |
| 664 | false, |
| 665 | ); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | /// Register the info line's drawn controls as one typed input surface. |
| 670 | /// |
| 671 | /// Both the launch stage and a live session use this exact registration, so |
| 672 | /// mouse routing cannot advertise a header segment on only one shell state. |
| 673 | fn register_info_interaction_targets(app: &mut App, hitboxes: InfoLineInteractionHitboxes) { |
| 674 | if let (Some(hitbox), Some(context_budget)) = ( |
| 675 | hitboxes.context, |
| 676 | crate::tui::tideline::ContextBudgetSnapshot::from_app(app), |
| 677 | ) { |
| 678 | app.viewport |
| 679 | .interaction_targets |
| 680 | .register(crate::tui::tideline::InteractionTarget { |
| 681 | id: crate::tui::tideline::InteractionTargetId::HEADER_CONTEXT, |
| 682 | area: hitbox, |
| 683 | focus: crate::tui::tideline::InteractionFocus::Direct, |
| 684 | keyboard_action: Some(crate::tui::tideline::InteractionAction::InspectContext), |
| 685 | mouse_action: Some(crate::tui::tideline::InteractionAction::InspectContext), |
| 686 | inspect_detail: crate::tui::tideline::InspectDetail::ContextBudget(context_budget), |
| 687 | }); |
| 688 | } |
| 689 | if let Some(hitbox) = hitboxes.route { |
| 690 | app.viewport |
| 691 | .interaction_targets |
| 692 | .register(crate::tui::tideline::InteractionTarget { |
| 693 | id: crate::tui::tideline::InteractionTargetId::HEADER_ROUTE, |
| 694 | area: hitbox, |
| 695 | focus: crate::tui::tideline::InteractionFocus::Direct, |
| 696 | keyboard_action: Some(crate::tui::tideline::InteractionAction::OpenProviderPicker), |
| 697 | mouse_action: Some(crate::tui::tideline::InteractionAction::OpenProviderPicker), |
| 698 | inspect_detail: crate::tui::tideline::InspectDetail::Route, |
| 699 | }); |
| 700 | } |
| 701 | if let Some(hitbox) = hitboxes.model { |
| 702 | app.viewport |
| 703 | .interaction_targets |
| 704 | .register(crate::tui::tideline::InteractionTarget { |
| 705 | id: crate::tui::tideline::InteractionTargetId::HEADER_MODEL, |
| 706 | area: hitbox, |
| 707 | focus: crate::tui::tideline::InteractionFocus::Direct, |
| 708 | keyboard_action: Some(crate::tui::tideline::InteractionAction::OpenModelPicker), |
| 709 | mouse_action: Some(crate::tui::tideline::InteractionAction::OpenModelPicker), |
| 710 | inspect_detail: crate::tui::tideline::InspectDetail::Route, |
| 711 | }); |
| 712 | } |
| 713 | if let Some(hitbox) = hitboxes.update { |
| 714 | app.viewport |
| 715 | .interaction_targets |
| 716 | .register(crate::tui::tideline::InteractionTarget { |
| 717 | id: crate::tui::tideline::InteractionTargetId::HEADER_UPDATE, |
| 718 | area: hitbox, |
| 719 | focus: crate::tui::tideline::InteractionFocus::Direct, |
| 720 | keyboard_action: None, |
| 721 | mouse_action: Some(crate::tui::tideline::InteractionAction::OpenUpdate), |
| 722 | inspect_detail: crate::tui::tideline::InspectDetail::Update, |
| 723 | }); |
| 724 | } |
| 725 | |
| 726 | for target in app.viewport.interaction_targets.iter() { |
| 727 | let label = match target.mouse_action { |
| 728 | Some(crate::tui::tideline::InteractionAction::InspectContext) => format!( |
| 729 | "{} · {}", |
| 730 | codewhale_localization::tr( |
| 731 | app.ui_locale, |
| 732 | codewhale_localization::MessageId::CtxMenuContextInspector, |
| 733 | ), |
| 734 | codewhale_localization::tr( |
| 735 | app.ui_locale, |
| 736 | codewhale_localization::MessageId::CtxMenuContextInspectorDesc, |
| 737 | ), |
| 738 | ), |
| 739 | Some(crate::tui::tideline::InteractionAction::OpenProviderPicker) => format!( |
| 740 | "{} · {}", |
| 741 | codewhale_localization::tr( |
| 742 | app.ui_locale, |
| 743 | codewhale_localization::MessageId::RoutePanelHeader, |
| 744 | ), |
| 745 | codewhale_localization::tr( |
| 746 | app.ui_locale, |
| 747 | codewhale_localization::MessageId::CmdProviderDescription, |
| 748 | ), |
| 749 | ), |
| 750 | // `/model` is a command name, not prose, so it stays verbatim in |
| 751 | // every locale; only the description is translated. |
| 752 | Some(crate::tui::tideline::InteractionAction::OpenModelPicker) => format!( |
| 753 | "/model · {}", |
| 754 | codewhale_localization::tr( |
| 755 | app.ui_locale, |
| 756 | codewhale_localization::MessageId::CmdModelDescription, |
| 757 | ), |
| 758 | ), |
| 759 | Some(crate::tui::tideline::InteractionAction::OpenUpdate) => format!( |
| 760 | "/update · {}", |
| 761 | codewhale_localization::tr( |
| 762 | app.ui_locale, |
| 763 | codewhale_localization::MessageId::CmdUpdateDescription, |
| 764 | ), |
| 765 | ), |
| 766 | Some(crate::tui::tideline::InteractionAction::ShowDockPanel(panel)) => { |
| 767 | panel.title().to_string() |
| 768 | } |
| 769 | Some(crate::tui::tideline::InteractionAction::OpenAutomations) => { |
| 770 | "/automation".to_string() |
| 771 | } |
| 772 | Some(crate::tui::tideline::InteractionAction::DismissDock) => { |
| 773 | codewhale_localization::tr( |
| 774 | app.ui_locale, |
| 775 | codewhale_localization::MessageId::KbCloseMenu, |
| 776 | ) |
| 777 | .into_owned() |
| 778 | } |
| 779 | None => continue, |
| 780 | }; |
| 781 | crate::tui::hover_layer::register_rect( |
| 782 | crate::tui::hover_hit::HoverTargetKind::Link, |
| 783 | target.area, |
| 784 | label, |
| 785 | false, |
| 786 | ); |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | /// The posture bar's live counts are the bottom-of-screen way into the |
| 791 | /// dock: each one opens the view it counts (agents → AGENTS, shells / tasks |
| 792 | /// → BACKGROUND, automations → their own view, the idle `todo` word → TODO). |
| 793 | /// Dock destinations use the same `ShowDockPanel` action as the strip's tabs. |
| 794 | fn register_footer_count_targets( |
| 795 | app: &mut App, |
| 796 | facts: &crate::tui::phase_strip::TidelineFooterFacts, |
| 797 | count_rects: &[(usize, Rect)], |
| 798 | ) { |
| 799 | for (index, area) in count_rects { |
| 800 | let Some(action) = facts.count_actions.get(*index).copied() else { |
| 801 | continue; |
| 802 | }; |
| 803 | app.viewport |
| 804 | .interaction_targets |
| 805 | .register(crate::tui::tideline::InteractionTarget { |
| 806 | id: crate::tui::tideline::InteractionTargetId::FOOTER_COUNT, |
| 807 | area: *area, |
| 808 | focus: crate::tui::tideline::InteractionFocus::Direct, |
| 809 | keyboard_action: Some(action), |
| 810 | mouse_action: Some(action), |
| 811 | inspect_detail: crate::tui::tideline::InspectDetail::Route, |
| 812 | }); |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | /// Map the host terminal rect onto the session shell canvas. |
| 817 | /// |
| 818 | /// Wide terminals use the full available width (v0.8.65 behavior; #5322). A |
| 819 | /// brief v0.9 gutter capped usable columns beyond 112 and left dead margins on |
| 820 | /// large displays / tmux panes; that cap is gone. Keep this helper so layout |
| 821 | /// and PTY oracles share one geometry entry point if a future setting wants a |
| 822 | /// configurable measure again. |
| 823 | pub(crate) fn session_shell_area(area: Rect) -> Rect { |
| 824 | area |
| 825 | } |
| 826 | |
| 827 | pub(crate) fn start_request_preview( |
| 828 | app: &mut App, |
| 829 | config: &Config, |
| 830 | engine: &EngineHandle, |
| 831 | prompt: Option<String>, |
| 832 | json: bool, |
| 833 | base_prompt_only: bool, |
| 834 | ) { |
| 835 | app.preview_cancel.cancel(); |
| 836 | app.preview_cancel = Default::default(); |
| 837 | let cancel = app.preview_cancel.clone(); |
| 838 | let permit = match dispatch_completion_permit(app) { |
| 839 | Ok(permit) => permit, |
| 840 | Err(err) => { |
| 841 | app.show_command_result( |
| 842 | format!("Cannot preview request: {err}"), |
| 843 | StatusToastLevel::Error, |
| 844 | ); |
| 845 | return; |
| 846 | } |
| 847 | }; |
| 848 | let inputs = build_preview_request_inputs(app, config, engine, prompt); |
| 849 | let origin = engine.clone(); |
| 850 | let session = app.current_session_id.clone(); |
| 851 | let workspace = app.workspace.clone(); |
| 852 | let turn = app.turn_counter; |
| 853 | let model = app.model.clone(); |
| 854 | let provider = app.provider_identity.clone(); |
| 855 | let mode = app.mode; |
| 856 | let auto = app.auto_model; |
| 857 | let reasoning = app.reasoning_effort; |
| 858 | tokio::spawn(async move { |
| 859 | let result = tokio::select! { |
| 860 | biased; |
| 861 | () = cancel.cancelled() => return, |
| 862 | result = tokio::time::timeout(DISPATCH_TASK_BOUND, inputs) => result, |
| 863 | }; |
| 864 | permit.send(Box::new(move |app, engine, _| { |
| 865 | if cancel.is_cancelled() |
| 866 | || !origin.tx_op.same_channel(&engine.tx_op) |
| 867 | || workspace != app.workspace |
| 868 | || session != app.current_session_id |
| 869 | || turn != app.turn_counter |
| 870 | || model != app.model |
| 871 | || provider != app.provider_identity |
| 872 | || mode != app.mode |
| 873 | || auto != app.auto_model |
| 874 | || reasoning != app.reasoning_effort |
| 875 | { |
| 876 | return Ok(()); |
| 877 | } |
| 878 | if let Ok(inputs) = &result |
| 879 | && (inputs.allow_shell != app.allow_shell || inputs.trust_mode != app.trust_mode |
| 880 | || inputs.approval_mode != app.approval_mode || inputs.auto_approve != app_auto_approve_enabled(app) |
| 881 | || inputs.allowed_tools != app.active_allowed_tools) { |
| 882 | app.show_command_result("Request preview expired because tool permissions changed. Run it again to inspect the current settings.", StatusToastLevel::Warning); |
| 883 | return Ok(()); |
| 884 | } |
| 885 | let sent = result.map_err(anyhow::Error::from).and_then(|inputs| { |
| 886 | engine.try_send(Op::PreviewOutboundRequest { |
| 887 | inputs: Box::new(inputs), |
| 888 | json, |
| 889 | base_prompt_only, |
| 890 | }) |
| 891 | }); |
| 892 | if let Err(err) = sent { |
| 893 | app.show_command_result(format!("Cannot preview request: {err}"), StatusToastLevel::Error); |
| 894 | } |
| 895 | Ok(()) |
| 896 | })); |
| 897 | }); |
| 898 | } |
| 899 | |
| 900 | /// Snapshot the posture a real `Op::SendMessage` would carry, and — when the |
| 901 | /// user supplied a hypothetical prompt — resolve the next turn's route with |
| 902 | /// the **same shared planner** dispatch uses (#1004). |
| 903 | /// |
| 904 | /// The hypothetical prompt is taken through the deterministic part of the real |
| 905 | /// submit path, in the real order: the **active skill** it would be wrapped |
| 906 | /// with, file and git mention resolution with the same error propagation, and |
| 907 | /// the paused-command note a real submit appends. That is what makes the body |
| 908 | /// the engine hashes the body a real turn would build. It is never added to |
| 909 | /// the conversation, no state is consumed, and the previewed request itself is |
| 910 | /// never sent. |
| 911 | /// |
| 912 | /// Two things a real submit does that an inspection must not, and what happens |
| 913 | /// instead: |
| 914 | /// |
| 915 | /// - **`message_submit` hooks.** They run first, before mentions, skill |
| 916 | /// wrapping, route planning, and the tool policy, and they may replace the |
| 917 | /// text or block the turn outright. Running them would give a *preview* the |
| 918 | /// side effects of a submit. So when any are configured, nothing downstream |
| 919 | /// of the text can be claimed exact and the whole manifest reports |
| 920 | /// [`codewhale_engine::core::engine::preview::PreviewUnresolved::MessageSubmitHooksConfigured`] — |
| 921 | /// including under a |
| 922 | /// fixed model, because the tool policy is derived from the content too. |
| 923 | /// - **Consuming the active skill.** A real submit *takes* `app.active_skill`. |
| 924 | /// The preview clones it: the skill is still pending after an inspection, |
| 925 | /// and the previewed body is the one it would have produced. Dropping it |
| 926 | /// instead — which the first pass did — previewed an unwrapped prompt and |
| 927 | /// quietly under-reported the request by the whole skill instruction. |
| 928 | /// |
| 929 | /// Without a prompt there is no next-turn route to resolve under auto model |
| 930 | /// routing and no next-turn body under any routing, so this reports a typed |
| 931 | /// unresolved state instead of recycling the installed route. |
| 932 | pub(crate) fn build_preview_request_inputs( |
| 933 | app: &App, |
| 934 | config: &Config, |
| 935 | engine_handle: &EngineHandle, |
| 936 | hypothetical_prompt: Option<String>, |
| 937 | ) -> futures_util::future::BoxFuture< |
| 938 | 'static, |
| 939 | codewhale_engine::core::engine::preview::PreviewRequestInputs, |
| 940 | > { |
| 941 | use codewhale_engine::core::engine::preview::{ |
| 942 | PreviewNextTurn, PreviewRequestInputs, PreviewUnresolved, |
| 943 | }; |
| 944 | |
| 945 | let requested_model = if app.auto_model { |
| 946 | "auto".to_string() |
| 947 | } else { |
| 948 | app.model.clone() |
| 949 | }; |
| 950 | let prompt_supplied = hypothetical_prompt.is_some(); |
| 951 | let mut inputs = PreviewRequestInputs { |
| 952 | mode: app.mode, |
| 953 | allow_shell: app.allow_shell, |
| 954 | trust_mode: app.trust_mode, |
| 955 | auto_approve: app_auto_approve_enabled(app), |
| 956 | approval_mode: app.approval_mode, |
| 957 | allowed_tools: app.active_allowed_tools.clone(), |
| 958 | dynamic_tools: Vec::new(), |
| 959 | provenance: codewhale_engine::core::ops::UserInputProvenance::ExternalUser, |
| 960 | requested_model, |
| 961 | requested_reasoning: app.reasoning_effort.as_setting().to_string(), |
| 962 | auto_model: app.auto_model, |
| 963 | hypothetical_prompt_supplied: prompt_supplied, |
| 964 | next_turn: None, |
| 965 | unresolved: PreviewUnresolved::NoPrompt, |
| 966 | }; |
| 967 | |
| 968 | let Some(prompt) = hypothetical_prompt else { |
| 969 | if app.auto_model { |
| 970 | inputs.unresolved = PreviewUnresolved::AutoRouteNeedsPrompt; |
| 971 | } |
| 972 | return Box::pin(std::future::ready(inputs)); |
| 973 | }; |
| 974 | if auto_router::should_resolve_auto_model_selection(app) { |
| 975 | inputs.unresolved = PreviewUnresolved::AutoRouteClassificationNotExecuted; |
| 976 | return Box::pin(std::future::ready(inputs)); |
| 977 | } |
| 978 | if app |
| 979 | .hooks |
| 980 | .has_hooks_for_event(codewhale_config::hooks::HookEvent::MessageSubmit) |
| 981 | { |
| 982 | inputs.unresolved = PreviewUnresolved::MessageSubmitHooksConfigured; |
| 983 | return Box::pin(std::future::ready(inputs)); |
| 984 | } |
| 985 | |
| 986 | // Clone, never `take`: an inspection may not consume the pending skill. |
| 987 | let message = QueuedMessage { |
| 988 | display: prompt.clone(), |
| 989 | skill_instruction: app.active_skill.clone(), |
| 990 | skill_provenance: app.active_skill_provenance.clone(), |
| 991 | extension_command: None, |
| 992 | approved_plan: None, |
| 993 | owner_input: false, |
| 994 | history_echoed: false, |
| 995 | }; |
| 996 | let context = |
| 997 | super::dispatch::MentionContext::capture(app, &message, std::env::current_dir().ok()); |
| 998 | let paused_dispatch = plan_paused_command_message(app, &prompt); |
| 999 | let objective = paused_dispatch.goal_objective(app); |
| 1000 | let goal_status = app.goal.status; |
| 1001 | let goal_budget = app.goal.token_budget; |
| 1002 | let translation = app.translation_enabled; |
| 1003 | let verbosity = app.verbosity.clone(); |
| 1004 | let route = app_scoped_runtime_config(app, config); |
| 1005 | let provider = app.api_provider; |
| 1006 | let app_model = app.model.clone(); |
| 1007 | let reasoning_effort = app.reasoning_effort; |
| 1008 | let auto_router_context = auto_router::recent_auto_router_context(&app.api_messages); |
| 1009 | let preflight_required = engine_handle.client_preflight_required(); |
| 1010 | let auto_compact_user_configured = app.auto_compact_user_configured; |
| 1011 | let auto_compact = app.auto_compact; |
| 1012 | let auto_compact_threshold_percent = app.auto_compact_threshold_percent; |
| 1013 | |
| 1014 | Box::pin(async move { |
| 1015 | let resolved = |
| 1016 | tokio::task::spawn_blocking(move || context.content(&message, &mut Default::default())) |
| 1017 | .await; |
| 1018 | let mut content = match resolved |
| 1019 | .map_err(anyhow::Error::from) |
| 1020 | .and_then(|value| value) |
| 1021 | { |
| 1022 | Ok(content) => content, |
| 1023 | Err(error) => { |
| 1024 | inputs.unresolved = PreviewUnresolved::PromptResolutionFailed(error.to_string()); |
| 1025 | return inputs; |
| 1026 | } |
| 1027 | }; |
| 1028 | if let Some(note) = paused_dispatch.note() { |
| 1029 | content.push_str(note); |
| 1030 | } |
| 1031 | let (app_route_identity, route_config) = match route { |
| 1032 | Ok(route) => route, |
| 1033 | Err(error) => { |
| 1034 | inputs.unresolved = PreviewUnresolved::PlanFailed(error); |
| 1035 | return inputs; |
| 1036 | } |
| 1037 | }; |
| 1038 | let planned = plan_turn_route(TurnRoutePlanRequest { |
| 1039 | accounting_origin: None, |
| 1040 | route_config: &route_config, |
| 1041 | app_route_identity: &app_route_identity, |
| 1042 | api_provider: provider, |
| 1043 | app_model: &app_model, |
| 1044 | auto_model: inputs.auto_model, |
| 1045 | reasoning_effort, |
| 1046 | mode: inputs.mode, |
| 1047 | content: &content, |
| 1048 | auto_router_context: &auto_router_context, |
| 1049 | should_auto_resolve: false, |
| 1050 | allow_auto_router_response_cache: false, |
| 1051 | preflight_required, |
| 1052 | auto_compact_user_configured, |
| 1053 | auto_compact, |
| 1054 | auto_compact_threshold_percent, |
| 1055 | }) |
| 1056 | .await; |
| 1057 | |
| 1058 | match planned { |
| 1059 | Ok(planned) => { |
| 1060 | let prompt_context = |
| 1061 | codewhale_engine::core::engine::NextTurnPromptContext::for_planned_turn( |
| 1062 | planned.route.identity.provider, |
| 1063 | planned.route.model.clone(), |
| 1064 | codewhale_engine::route_budget::known_route_limits( |
| 1065 | planned.route.candidate.limits(), |
| 1066 | ), |
| 1067 | inputs.mode, |
| 1068 | objective, |
| 1069 | goal_status, |
| 1070 | goal_budget, |
| 1071 | translation, |
| 1072 | verbosity, |
| 1073 | ); |
| 1074 | inputs.next_turn = Some(Box::new(PreviewNextTurn { |
| 1075 | content, |
| 1076 | route: Box::new(planned.route), |
| 1077 | prompt_context, |
| 1078 | reasoning_effort: planned.effective_reasoning_effort, |
| 1079 | reasoning_effort_auto: planned.auto_controls_reasoning, |
| 1080 | auto_route_source: planned |
| 1081 | .auto_selection |
| 1082 | .as_ref() |
| 1083 | .map(|selection| selection.source.label().to_string()), |
| 1084 | routing_source: planned.routing_source, |
| 1085 | compaction: planned.compaction, |
| 1086 | })); |
| 1087 | } |
| 1088 | Err(error) => inputs.unresolved = PreviewUnresolved::PlanFailed(error), |
| 1089 | } |
| 1090 | inputs |
| 1091 | }) |
| 1092 | } |
| 1093 | |
| 1094 | pub(crate) fn build_engine_config(app: &App, config: &Config) -> EngineConfig { |
| 1095 | let identity = app |
| 1096 | .provider_identity |
| 1097 | .as_ref() |
| 1098 | .filter(|identity| config.verify_provider_identity(identity).is_ok()); |
| 1099 | let max_subagents = app |
| 1100 | .max_subagents |
| 1101 | .clamp(1, codewhale_runtime::config::MAX_SUBAGENTS); |
| 1102 | EngineConfig { |
| 1103 | user_input_responder: true, |
| 1104 | session_checkpoint_backend: Some( |
| 1105 | codewhale_engine::core::events::SessionCheckpointProjection::Exact, |
| 1106 | ), |
| 1107 | model: app.model.clone(), |
| 1108 | active_route_limits: app.active_route_limits, |
| 1109 | workspace: app.workspace.clone(), |
| 1110 | // The App owns the session id (claimed before the Runtime store lock |
| 1111 | // and used for every checkpoint/autosave); the engine adopts it so the |
| 1112 | // engine conversation and the persisted session are the same record. |
| 1113 | session_id: app.current_session_id.clone(), |
| 1114 | subagent_state_root: None, |
| 1115 | child_posture: None, |
| 1116 | allow_shell: app.allow_shell, |
| 1117 | trust_mode: app.trust_mode, |
| 1118 | extra_trusted_paths: config.extra_trusted_paths.clone(), |
| 1119 | mcp_config_path: config.mcp_config_path(), |
| 1120 | mcp_auth_context: Default::default(), |
| 1121 | mcp_oauth_callback_port: config.mcp_oauth_callback_port, |
| 1122 | mcp_oauth_callback_url: config.mcp_oauth_callback_url.clone(), |
| 1123 | skills_dir: app.skills_dir.clone(), |
| 1124 | skills_config: app.skills_config.clone(), |
| 1125 | agent_preset: app.agent_preset(), |
| 1126 | plugin_registry: Some(std::sync::Arc::clone(&app.plugin_registry)), |
| 1127 | instructions: configured_instruction_sources(config), |
| 1128 | project_context_pack_enabled: config.project_context_pack_enabled(), |
| 1129 | translation_enabled: app.translation_enabled, |
| 1130 | verbosity: app.verbosity.clone(), |
| 1131 | // Only an explicit `[tui].max_model_steps` installs a step ceiling. |
| 1132 | max_steps: config.max_model_steps(), |
| 1133 | max_subagents, |
| 1134 | max_admitted_subagents: identity |
| 1135 | .map_or_else( |
| 1136 | || config.max_admitted_subagents(), |
| 1137 | |identity| config.max_admitted_subagents_for_provider(identity), |
| 1138 | ) |
| 1139 | .max(max_subagents), |
| 1140 | launch_concurrency: identity.map_or_else( |
| 1141 | || config.launch_concurrency(), |
| 1142 | |identity| config.launch_concurrency_for_provider(identity), |
| 1143 | ), |
| 1144 | subagents_enabled: identity |
| 1145 | .is_some_and(|identity| config.subagents_enabled_for_provider(identity)), |
| 1146 | features: config.features(), |
| 1147 | auto_review_policy: |
| 1148 | codewhale_engine::core::authority::auto_review::AutoReviewPolicy::from_config(config), |
| 1149 | compaction: app.compaction_config(), |
| 1150 | todos: app.todos.clone(), |
| 1151 | plan_state: app.plan_state.clone(), |
| 1152 | goal_state: app.last_known_goal_state.as_ref().map_or_else( |
| 1153 | || { |
| 1154 | codewhale_engine::tools::goal::new_shared_goal_state_from_host_status( |
| 1155 | app.goal.objective.clone(), |
| 1156 | app.goal.token_budget, |
| 1157 | app.goal.status, |
| 1158 | ) |
| 1159 | }, |
| 1160 | |goal| { |
| 1161 | codewhale_engine::tools::goal::new_shared_goal_state_from_snapshot( |
| 1162 | &goal.to_runtime_snapshot(), |
| 1163 | ) |
| 1164 | }, |
| 1165 | ), |
| 1166 | goal_complete_judge: config.goal_complete_judge(), |
| 1167 | goal_blocked_judge: config.goal_blocked_judge(), |
| 1168 | max_spawn_depth: identity.map_or_else( |
| 1169 | || config.subagent_max_spawn_depth(), |
| 1170 | |identity| config.subagent_max_spawn_depth_for_provider(identity), |
| 1171 | ), |
| 1172 | allowed_tools: app.active_allowed_tools.clone(), |
| 1173 | disallowed_tools: None, |
| 1174 | max_tool_calls: None, |
| 1175 | hook_executor: app.runtime_services.hook_executor.clone(), |
| 1176 | network_policy: config.network.clone().map(|toml_cfg| { |
| 1177 | codewhale_net::network_policy::NetworkPolicyDecider::with_default_audit( |
| 1178 | codewhale_net::network_policy::NetworkPolicy::from(toml_cfg), |
| 1179 | ) |
| 1180 | }), |
| 1181 | snapshots_enabled: config.snapshots_config().enabled, |
| 1182 | snapshots_max_workspace_bytes: config |
| 1183 | .snapshots_config() |
| 1184 | .max_workspace_gb |
| 1185 | .saturating_mul(1024 * 1024 * 1024), |
| 1186 | record_restore_points: true, |
| 1187 | lsp_config: config.lsp.clone().map(codewhale_lsp::LspConfig::from), |
| 1188 | runtime_services: app.runtime_services.clone(), |
| 1189 | subagent_model_overrides: config.subagent_model_overrides(), |
| 1190 | fleet_roster: std::sync::Arc::new( |
| 1191 | codewhale_engine::fleet::identity::load_effective_roster( |
| 1192 | &config.fleet_config(), |
| 1193 | &app.workspace, |
| 1194 | Some(app.extension_plugin_view().as_ref()), |
| 1195 | ), |
| 1196 | ), |
| 1197 | subagent_api_timeout: Duration::from_secs(identity.map_or_else( |
| 1198 | || config.subagent_api_timeout_secs(), |
| 1199 | |identity| config.subagent_api_timeout_secs_for_provider(identity), |
| 1200 | )), |
| 1201 | stream_chunk_timeout: Duration::from_secs(app.stream_chunk_timeout_secs), |
| 1202 | turn_wall_clock: config.turn_wall_clock(), |
| 1203 | stream_max_content_bytes: config.stream_max_content_bytes(), |
| 1204 | stream_max_duration: config.stream_max_duration(), |
| 1205 | stream_retry_limits: config.stream_retry_limits(), |
| 1206 | stream_open_timeout: config.stream_open_timeout(), |
| 1207 | subagent_heartbeat_timeout: Duration::from_secs(identity.map_or_else( |
| 1208 | || config.subagent_heartbeat_timeout_secs(), |
| 1209 | |identity| config.subagent_heartbeat_timeout_secs_for_provider(identity), |
| 1210 | )), |
| 1211 | prefer_bwrap: config.prefers_bwrap(), |
| 1212 | tool_launcher: config.tool_launcher.clone(), |
| 1213 | bwrap_extensions: codewhale_sandbox::BwrapMountExtensions { |
| 1214 | read_only_roots: config.bwrap_ro_roots.clone(), |
| 1215 | device_roots: config.bwrap_dev_roots.clone(), |
| 1216 | }, |
| 1217 | read_denylist: codewhale_sandbox::read_guard::ReadDenylist::from_config(config), |
| 1218 | memory_enabled: config.memory_enabled(), |
| 1219 | memory_path: config.memory_path(), |
| 1220 | speech_output_dir: config.speech_output_dir(), |
| 1221 | vision_config: config.vision_model_config(), |
| 1222 | strict_tool_mode: config.strict_tool_mode.unwrap_or(false), |
| 1223 | goal_objective: app.goal.objective.clone(), |
| 1224 | goal_token_budget: app.goal.token_budget, |
| 1225 | goal_status: app.goal.status, |
| 1226 | goal_max_continuations: config.goal_max_continuations(), |
| 1227 | goal_continuation_delay_seconds: config.goal_continuation_delay_seconds(), |
| 1228 | goal_enforce_token_budget: config.goal_enforce_token_budget(), |
| 1229 | reasoning_only_max_reprompts: config.reasoning_only_max_reprompts(), |
| 1230 | reasoning_only_on_output_limit: config.reasoning_only_on_output_limit(), |
| 1231 | reasoning_only_reprompt_message: Some(config.reasoning_only_reprompt_message().to_string()), |
| 1232 | locale_tag: app.ui_locale.tag().to_string(), |
| 1233 | workshop: { |
| 1234 | codewhale_runtime::active_workshop::install_active_workshop(config.workshop.as_ref()); |
| 1235 | config.workshop.clone() |
| 1236 | }, |
| 1237 | search_provider: config.search_provider(), |
| 1238 | search_api_key: config.search.as_ref().and_then(|s| s.api_key.clone()), |
| 1239 | search_base_url: config.search.as_ref().and_then(|s| s.base_url.clone()), |
| 1240 | search_native: config.search_native(), |
| 1241 | search_third_party: config.search.as_ref().and_then(|search| search.third_party), |
| 1242 | search_consent_implied: config.search_consent_implied(), |
| 1243 | tools_always_load: config.tools_always_load(), |
| 1244 | user_input_limits: codewhale_engine::tools::user_input::UserInputLimits::from_config( |
| 1245 | config, |
| 1246 | ), |
| 1247 | user_input_timeout: config.user_input_timeout(), |
| 1248 | goal_max_steps: Some(config.goal_max_steps()), |
| 1249 | tools: config.tools.clone(), |
| 1250 | workspace_follow_symlinks: app.workspace_follow_symlinks, |
| 1251 | exec_policy_engine: config.exec_policy_engine.clone(), |
| 1252 | terminal_chrome_enabled: true, |
| 1253 | advisor_config: config |
| 1254 | .advisor |
| 1255 | .as_ref() |
| 1256 | .map(codewhale_engine::tools::subagent::AdvisorConfig::from_toml) |
| 1257 | .unwrap_or_else(codewhale_engine::tools::subagent::AdvisorConfig::disabled), |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | #[cfg(test)] |
| 1262 | pub(crate) fn build_app_system_prompt(app: &App, config: &Config) -> SystemPrompt { |
| 1263 | build_app_system_prompt_with_goal(app, config, app.goal.objective.as_deref()) |
| 1264 | } |
| 1265 | |
| 1266 | pub(crate) fn build_app_system_prompt_with_goal( |
| 1267 | app: &App, |
| 1268 | config: &Config, |
| 1269 | goal_objective: Option<&str>, |
| 1270 | ) -> SystemPrompt { |
| 1271 | let instructions = configured_instruction_sources(config); |
| 1272 | let user_memory_block = codewhale_runtime::native_memory::native_prompt_block( |
| 1273 | config.memory_enabled(), |
| 1274 | &config.memory_path(), |
| 1275 | &app.workspace, |
| 1276 | ); |
| 1277 | // Keep the previewed/rebuilt prompt identical to the engine's: the |
| 1278 | // recovery hint is part of the prefix when a prior workspace session |
| 1279 | // ended mid-turn (#5715). |
| 1280 | let recovery_hint = codewhale_engine::session_manager::session_recovery_hint( |
| 1281 | &app.workspace, |
| 1282 | app.current_session_id.as_deref(), |
| 1283 | ); |
| 1284 | let settings = codewhale_engine::project_context::InstructionSettings::from_config(config); |
| 1285 | let raw = codewhale_engine::project_context::capture_instruction_context( |
| 1286 | &app.workspace, |
| 1287 | &instructions, |
| 1288 | &settings, |
| 1289 | ); |
| 1290 | let effort = codewhale_engine::core::engine::turn_loop::resolve_auto_effort( |
| 1291 | Some(app.reasoning_effort.as_setting()), |
| 1292 | app.api_provider, |
| 1293 | &config.active_route_base_url(), |
| 1294 | &app.model, |
| 1295 | ); |
| 1296 | let budgets = codewhale_engine::project_context::InstructionBudgets::resolve_or_default( |
| 1297 | &settings.budget, |
| 1298 | codewhale_engine::route_runtime::ContextWindowResolution { |
| 1299 | tokens: app.effective_context_window(), |
| 1300 | source: app.effective_context_window_source(), |
| 1301 | } |
| 1302 | .instruction_budget_tokens(), |
| 1303 | Some({ |
| 1304 | let (provider, model, limits, window) = app.effective_budget_route(); |
| 1305 | codewhale_engine::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 1306 | provider, |
| 1307 | model, |
| 1308 | limits, |
| 1309 | window.map(|window| window.tokens), |
| 1310 | None, |
| 1311 | effort.as_deref(), |
| 1312 | ) as usize |
| 1313 | }), |
| 1314 | ); |
| 1315 | prompts::system_prompt_with_instruction_assembly_for_host( |
| 1316 | &app.workspace, |
| 1317 | None, |
| 1318 | Some(&app.skills_dir), |
| 1319 | Some(&instructions), |
| 1320 | prompts::PromptSessionContext { |
| 1321 | user_memory_block: user_memory_block.as_deref(), |
| 1322 | goal_objective, |
| 1323 | project_context_pack_enabled: config.project_context_pack_enabled(), |
| 1324 | locale_tag: app.ui_locale.tag(), |
| 1325 | translation_enabled: app.translation_enabled, |
| 1326 | model_id: &app.model, |
| 1327 | context_window_override: Some(app.effective_context_window()), |
| 1328 | verbosity: app.verbosity.as_deref(), |
| 1329 | recovery_hint: recovery_hint.as_deref(), |
| 1330 | skills_config: app.skills_config.clone(), |
| 1331 | plugin_registry: Some(app.extension_plugin_view().as_ref()), |
| 1332 | mode: app.mode, |
| 1333 | }, |
| 1334 | prompts::PromptHost::Interactive, |
| 1335 | Some((&raw, &settings, budgets)), |
| 1336 | ) |
| 1337 | .0 |
| 1338 | } |
| 1339 | |
| 1340 | fn consume_window_reroot_event( |
| 1341 | app: &mut App, |
| 1342 | journal_entries_before: usize, |
| 1343 | rebranch: codewhale_runtime::session_tree::Rebranch, |
| 1344 | ) -> Option<(&'static str, &'static str)> { |
| 1345 | if app.api_messages.is_empty() { |
| 1346 | return None; |
| 1347 | } |
| 1348 | let cause = app.window_reroot_cause.take(); |
| 1349 | let reason = if rebranch.replaced_from_root() { |
| 1350 | Some("first_message_changed") |
| 1351 | } else if rebranch.previous_active == 0 && journal_entries_before > 0 { |
| 1352 | Some("active_path_empty") |
| 1353 | } else { |
| 1354 | None |
| 1355 | }; |
| 1356 | reason.map(|reason| (reason, cause.unwrap_or("unattributed"))) |
| 1357 | } |
| 1358 | |
| 1359 | fn record_window_reroot( |
| 1360 | session_id: Option<&str>, |
| 1361 | reason: &str, |
| 1362 | cause: &str, |
| 1363 | previous_window: usize, |
| 1364 | window: usize, |
| 1365 | journal_entries: usize, |
| 1366 | ) { |
| 1367 | let details = serde_json::json!({ |
| 1368 | "session_id": session_id, |
| 1369 | "reason": reason, |
| 1370 | "cause": cause, |
| 1371 | "previous_window": previous_window, |
| 1372 | "window": window, |
| 1373 | "journal_entries": journal_entries, |
| 1374 | }); |
| 1375 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 1376 | handle.spawn_blocking(move || { |
| 1377 | codewhale_runtime::audit::log_sensitive_event("session.window.rerooted", details); |
| 1378 | }); |
| 1379 | } |
| 1380 | } |
| 1381 | |
| 1382 | /// Build the session snapshot every product caller queues into the |
| 1383 | /// persistence actor. Journal-only (#6214 T3): the `messages` projection is |
| 1384 | /// left empty because the queue drops it anyway, and serialization rehydrates |
| 1385 | /// it from the journal — the on-disk bytes are unchanged. Callers must not |
| 1386 | /// read `.messages` off the returned snapshot; save or serialize it. |
| 1387 | pub(crate) fn build_session_snapshot( |
| 1388 | app: &mut App, |
| 1389 | manager: &SessionManager, |
| 1390 | ) -> Result<SavedSession, String> { |
| 1391 | let model = app.model_selection_for_persistence(); |
| 1392 | let work_state = match app.try_work_state_snapshot() { |
| 1393 | Ok(work_state) => work_state, |
| 1394 | Err(err) => app.last_known_work_state.clone().ok_or_else(|| { |
| 1395 | format!("automatic session snapshot skipped while Work state is busy: {err}") |
| 1396 | })?, |
| 1397 | }; |
| 1398 | // Drop what a bounded save already archived (#6842) so the live journal |
| 1399 | // matches the document. No I/O: the ids come from the save path. |
| 1400 | if let Some(session_id) = app.current_session_id.as_deref() { |
| 1401 | let archived = codewhale_engine::session_manager::take_archived_journal_ids(session_id); |
| 1402 | if let Err(error) = app.session_journal.remove_entries(&archived) { |
| 1403 | tracing::warn!(%error, "kept archived journal entries in memory"); |
| 1404 | } |
| 1405 | } |
| 1406 | let journal_entries_before = app.session_journal.entries.len(); |
| 1407 | let rebranch = app |
| 1408 | .session_journal |
| 1409 | .rebranch_active_messages_stamped(&app.api_messages, &app.api_message_stamps); |
| 1410 | if let Some((reason, cause)) = |
| 1411 | consume_window_reroot_event(app, journal_entries_before, rebranch) |
| 1412 | { |
| 1413 | record_window_reroot( |
| 1414 | app.current_session_id.as_deref(), |
| 1415 | reason, |
| 1416 | cause, |
| 1417 | rebranch.previous_active, |
| 1418 | app.api_messages.len(), |
| 1419 | app.session_journal.entries.len(), |
| 1420 | ); |
| 1421 | } |
| 1422 | let mut session = codewhale_engine::session_manager::create_saved_session_journal_only( |
| 1423 | app.current_session_id |
| 1424 | .clone() |
| 1425 | .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()), |
| 1426 | &app.api_messages, |
| 1427 | app.session_journal.clone(), |
| 1428 | &model, |
| 1429 | &app.workspace, |
| 1430 | u64::from(app.session.total_tokens), |
| 1431 | app.system_prompt.as_ref(), |
| 1432 | Some(app.mode.as_setting()), |
| 1433 | ); |
| 1434 | session.agent_preset = app.agent_preset(); |
| 1435 | session.write_receipt = if app.current_session_id.is_none() { |
| 1436 | Some( |
| 1437 | manager |
| 1438 | .expect_absent_session(&session.metadata.id) |
| 1439 | .map_err(|error| error.to_string())?, |
| 1440 | ) |
| 1441 | } else { |
| 1442 | app.session_write_receipt.clone() |
| 1443 | }; |
| 1444 | let computed_title = session.metadata.title.clone(); |
| 1445 | if let Some(cached) = app |
| 1446 | .current_session_metadata |
| 1447 | .as_ref() |
| 1448 | .filter(|cached| cached.id == session.metadata.id) |
| 1449 | { |
| 1450 | session.metadata.created_at = cached.created_at; |
| 1451 | session |
| 1452 | .metadata |
| 1453 | .parent_session_id |
| 1454 | .clone_from(&cached.parent_session_id); |
| 1455 | session.metadata.forked_from_message_count = cached.forked_from_message_count; |
| 1456 | session.metadata.archived = cached.archived; |
| 1457 | session.metadata.title.clone_from(&cached.title); |
| 1458 | session.metadata.title_is_custom = cached.title_is_custom; |
| 1459 | session |
| 1460 | .metadata |
| 1461 | .runtime_store |
| 1462 | .clone_from(&cached.runtime_store); |
| 1463 | } |
| 1464 | if let Some(binding) = app |
| 1465 | .runtime_services |
| 1466 | .task_manager |
| 1467 | .as_ref() |
| 1468 | .and_then(|tasks| tasks.session_store_binding()) |
| 1469 | { |
| 1470 | session.metadata.runtime_store = Some(binding); |
| 1471 | } |
| 1472 | if !session.metadata.title_is_custom |
| 1473 | && session.metadata.title == codewhale_engine::session_manager::DEFAULT_SESSION_TITLE |
| 1474 | && computed_title != codewhale_engine::session_manager::DEFAULT_SESSION_TITLE |
| 1475 | { |
| 1476 | session.metadata.title = computed_title; |
| 1477 | } |
| 1478 | if let Some(cached) = app.current_session_metadata.as_mut() |
| 1479 | && cached.id == session.metadata.id |
| 1480 | { |
| 1481 | cached.title.clone_from(&session.metadata.title); |
| 1482 | cached.title_is_custom = session.metadata.title_is_custom; |
| 1483 | cached.archived = session.metadata.archived; |
| 1484 | } |
| 1485 | session |
| 1486 | .metadata |
| 1487 | .set_model_provider_route(app.api_provider.as_str(), app.provider_id_for_persistence()); |
| 1488 | app.sync_cost_to_metadata(&mut session.metadata); |
| 1489 | session.context_references = app.session_context_references.clone(); |
| 1490 | session.artifacts = app.session_artifacts.clone(); |
| 1491 | session.turn_outcomes = app.session_turn_outcomes.clone(); |
| 1492 | session.delegated_writes = app |
| 1493 | .delegated_writes |
| 1494 | .iter() |
| 1495 | .filter(|((owner, _), _)| owner == &session.metadata.id) |
| 1496 | .map(|((_, seq), paths)| (*seq, paths.iter().cloned().collect())) |
| 1497 | .collect(); |
| 1498 | session.work_state = work_state; |
| 1499 | session.last_auto_route = app.auto_route_for_persistence(); |
| 1500 | session.window_title.clone_from(&app.window_title); |
| 1501 | session.composer_color.clone_from(&app.composer_color); |
| 1502 | app.current_session_metadata = Some(session.metadata.clone()); |
| 1503 | // Claim ownership of this session for the process. From here on the |
| 1504 | // Runtime API refuses external renames/archives of it with a typed 409 |
| 1505 | // rather than writing something the next snapshot would revert. |
| 1506 | // |
| 1507 | // Claiming here rather than at each of the ten `current_session_id` |
| 1508 | // assignment sites is deliberate: this is the function that establishes |
| 1509 | // "the TUI holds the authoritative copy", which is exactly the condition |
| 1510 | // the conflict protects. A session that has never been snapshotted has no |
| 1511 | // in-memory state to lose, so leaving it unclaimed is correct, not a gap. |
| 1512 | manager.claim_live_session(&session.metadata.id); |
| 1513 | Ok(session) |
| 1514 | } |
| 1515 | |
| 1516 | /// The stream sanitizer lives with the other output sanitizers in |
| 1517 | /// `codewhale-sanitize`; the event loop reaches it through this module. |
| 1518 | pub(crate) use codewhale_sanitize::sanitize::sanitize_stream_chunk; |
| 1519 | |
| 1520 | /// Ensure an in-flight streaming Assistant cell exists in history and return |
| 1521 | /// its index. Thinking cells go through `streaming_thinking::ensure_active_entry` |
| 1522 | /// (active cell) instead. |
| 1523 | pub(crate) fn ensure_streaming_assistant_history_cell(app: &mut App) -> usize { |
| 1524 | if let Some(index) = app.streaming_message_index { |
| 1525 | return index; |
| 1526 | } |
| 1527 | app.add_message(HistoryCell::Assistant { |
| 1528 | content: String::new(), |
| 1529 | streaming: true, |
| 1530 | }); |
| 1531 | let index = app.history.len().saturating_sub(1); |
| 1532 | app.streaming_message_index = Some(index); |
| 1533 | index |
| 1534 | } |
| 1535 | |
| 1536 | pub(crate) fn append_streaming_text(app: &mut App, index: usize, text: &str) { |
| 1537 | if text.is_empty() { |
| 1538 | return; |
| 1539 | } |
| 1540 | app.resync_history_revisions(); |
| 1541 | let Some(previous_revision) = app.history_revisions.get(index).copied() else { |
| 1542 | return; |
| 1543 | }; |
| 1544 | let chained_from_revision = app |
| 1545 | .streaming_source_receipt |
| 1546 | .filter(|receipt| receipt.cell_index == index && receipt.to_revision == previous_revision) |
| 1547 | .map_or(previous_revision, |receipt| receipt.from_revision); |
| 1548 | let mut content_len = None; |
| 1549 | if let Some(HistoryCell::Assistant { content, .. }) = app.history.get_mut(index) { |
| 1550 | content.push_str(text); |
| 1551 | content_len = Some(content.len()); |
| 1552 | // Bump only the streaming cell's per-cell revision so the transcript |
| 1553 | // cache re-renders just this cell. Without this, the cache would |
| 1554 | // either skip the update entirely (now that the global |
| 1555 | // history_version is no longer fanned out across every cell) or fall |
| 1556 | // back to a full re-wrap of the entire transcript every chunk. |
| 1557 | app.bump_history_cell(index); |
| 1558 | } |
| 1559 | let Some(content_len) = content_len else { |
| 1560 | return; |
| 1561 | }; |
| 1562 | if let Some(to_revision) = app.history_revisions.get(index).copied() { |
| 1563 | app.streaming_source_receipt = Some(crate::tui::transcript::StreamingSourceReceipt { |
| 1564 | cell_index: index, |
| 1565 | from_revision: chained_from_revision, |
| 1566 | to_revision, |
| 1567 | content_len, |
| 1568 | }); |
| 1569 | } |
| 1570 | } |
| 1571 | |
| 1572 | fn estimate_output_tokens_from_text(text: &str) -> u64 { |
| 1573 | let chars = text.chars().count() as u64; |
| 1574 | if chars == 0 { |
| 1575 | 0 |
| 1576 | } else { |
| 1577 | chars.saturating_add(3) / 4 |
| 1578 | } |
| 1579 | } |
| 1580 | |
| 1581 | pub(crate) fn accrue_streaming_token_estimate(app: &mut App, visible_text: &str) { |
| 1582 | if visible_text.is_empty() { |
| 1583 | return; |
| 1584 | } |
| 1585 | app.streaming_output_token_estimate = app |
| 1586 | .streaming_output_token_estimate |
| 1587 | .saturating_add(estimate_output_tokens_from_text(visible_text)); |
| 1588 | } |
| 1589 | |
| 1590 | /// Take a finished text block's remaining buffer, leaving a reasoning block |
| 1591 | /// untouched (#7123). A text drain must never carry reasoning into the |
| 1592 | /// assistant cell, and must never take a block that is not its own: taking a |
| 1593 | /// reasoning tail here would append it to the prose and drop it from the card. |
| 1594 | pub(crate) fn drain_text_block(state: &mut codewhale_tui_kit::streaming::StreamingState) -> String { |
| 1595 | if state.block_is_thinking(0) { |
| 1596 | String::new() |
| 1597 | } else { |
| 1598 | state.finalize_block_text(0) |
| 1599 | } |
| 1600 | } |
| 1601 | |
| 1602 | pub(crate) fn commit_streaming_display_tick( |
| 1603 | app: &mut App, |
| 1604 | stream_display_clock: &mut StreamDisplayClock, |
| 1605 | now: Instant, |
| 1606 | ) -> bool { |
| 1607 | if !stream_display_clock.take_due(now) { |
| 1608 | return false; |
| 1609 | } |
| 1610 | |
| 1611 | let mut updated = false; |
| 1612 | let pending = app.streaming_state.pending_len(0); |
| 1613 | let budget = if app.streaming_state.block_is_thinking(0) { |
| 1614 | pending |
| 1615 | } else { |
| 1616 | codewhale_tui_kit::streaming::reveal_budget(stream_display_clock.interval(), pending) |
| 1617 | }; |
| 1618 | let committed = app.streaming_state.commit_text(0, budget); |
| 1619 | if !committed.is_empty() { |
| 1620 | // #7123: route by the block's own kind. An assistant cell stays live |
| 1621 | // from an earlier text block while a later thinking block streams, so |
| 1622 | // preferring `streaming_message_index` wrote reasoning into the prose |
| 1623 | // body, splitting one sentence across the thinking card and the |
| 1624 | // answer that follows it. |
| 1625 | if app.streaming_state.block_is_thinking(0) { |
| 1626 | let entry_idx = app |
| 1627 | .streaming_thinking_active_entry |
| 1628 | .unwrap_or_else(|| streaming_thinking::ensure_active_entry(app)); |
| 1629 | if app.translation_enabled { |
| 1630 | streaming_thinking::set_placeholder(app, entry_idx); |
| 1631 | } else { |
| 1632 | streaming_thinking::append_at(app, entry_idx, &committed, now); |
| 1633 | } |
| 1634 | } else { |
| 1635 | let index = app |
| 1636 | .streaming_message_index |
| 1637 | .unwrap_or_else(|| ensure_streaming_assistant_history_cell(app)); |
| 1638 | append_streaming_text(app, index, &committed); |
| 1639 | accrue_streaming_token_estimate(app, &committed); |
| 1640 | } |
| 1641 | updated = true; |
| 1642 | } |
| 1643 | |
| 1644 | if app.thinking_read_window.advance_settling(now) { |
| 1645 | app.thinking_revision_owed = true; |
| 1646 | } |
| 1647 | if streaming_thinking::render_owed_revision(app, now) { |
| 1648 | updated = true; |
| 1649 | } |
| 1650 | if app.streaming_state.has_pending_stream_text(0) |
| 1651 | || app.thinking_revision_owed |
| 1652 | || app.thinking_read_window.is_settling() |
| 1653 | { |
| 1654 | stream_display_clock.note_delta(now); |
| 1655 | } |
| 1656 | |
| 1657 | updated |
| 1658 | } |
| 1659 | |
| 1660 | /// Build the pending-input preview widget from current `App` state. |
| 1661 | /// |
| 1662 | /// v0.6.6 (#122) wires the live buckets: |
| 1663 | /// - `pending_steers` — steers sent into the running turn that the engine |
| 1664 | /// has not recorded yet (`inflight_steers`, `preparing_steers`). |
| 1665 | /// - `queued_messages` — Enter while busy; drained at end-of-turn. An |
| 1666 | /// unaccepted steer also lands here (#6297) so it is never lost. In Operate, |
| 1667 | /// the foreground operator dispatches these as additional background tasks. |
| 1668 | pub(crate) fn build_pending_input_preview(app: &App) -> PendingInputPreview { |
| 1669 | let mut preview = PendingInputPreview::new(); |
| 1670 | preview.locale = app.ui_locale; |
| 1671 | let selected_attachment = app.selected_composer_attachment_index(); |
| 1672 | let mut attachment_index = 0usize; |
| 1673 | preview.context_items = |
| 1674 | crate::tui::file_mention::pending_context_previews(&app.input, app.ui_locale) |
| 1675 | .into_iter() |
| 1676 | .map(|item| { |
| 1677 | let selected = if item.removable { |
| 1678 | let selected = selected_attachment == Some(attachment_index); |
| 1679 | attachment_index += 1; |
| 1680 | selected |
| 1681 | } else { |
| 1682 | false |
| 1683 | }; |
| 1684 | ContextPreviewItem { |
| 1685 | kind: item.kind, |
| 1686 | label: item.label, |
| 1687 | detail: item.detail, |
| 1688 | included: item.included, |
| 1689 | removable: item.removable, |
| 1690 | selected, |
| 1691 | } |
| 1692 | }) |
| 1693 | .collect(); |
| 1694 | // #6190: a steer the engine has not recorded yet is exactly what this |
| 1695 | // bucket's "sending into turn" label describes, so it shares it rather |
| 1696 | // than growing a fourth bucket and a fifteenth locale string. |
| 1697 | preview.pending_steers = app |
| 1698 | .inflight_steers |
| 1699 | .iter() |
| 1700 | .map(|steer| &steer.message) |
| 1701 | .chain(app.preparing_steers.iter().map(|steer| &steer.message)) |
| 1702 | .map(|m| m.display.clone()) |
| 1703 | .collect(); |
| 1704 | preview.queued_messages = app |
| 1705 | .queued_messages |
| 1706 | .iter() |
| 1707 | .map(|m| m.display.clone()) |
| 1708 | .collect(); |
| 1709 | preview.pending_approvals = crate::tui::pending_requests::footer_rows(app); |
| 1710 | preview.offline = app.offline_mode; |
| 1711 | preview.editing_queued_message = app.queued_draft.as_ref().map(|draft| { |
| 1712 | if app.input.trim().is_empty() { |
| 1713 | draft.display.clone() |
| 1714 | } else { |
| 1715 | app.input.clone() |
| 1716 | } |
| 1717 | }); |
| 1718 | preview |
| 1719 | } |
| 1720 | |
| 1721 | pub(crate) fn render(f: &mut Frame, app: &mut App, _config: &Config) -> Option<(u16, u16)> { |
| 1722 | app.viewport.working_glow_visible = false; |
| 1723 | app.viewport.activity_sweep_visible = false; |
| 1724 | app.viewport.settle_flash_visible = false; |
| 1725 | app.viewport.ocean_semantic_surfaces.clear(); |
| 1726 | let size = f.area(); |
| 1727 | // Hover targets belong to the whole composed frame. Resetting inside the |
| 1728 | // transcript erased targets registered later by the composer and modals. |
| 1729 | crate::tui::hover_layer::begin_frame(); |
| 1730 | app.pet_watch.prepare_frame(); |
| 1731 | // Image previews decode off-thread. `poll` runs at the top of the event |
| 1732 | // loop, before the draw decision, so a preview that just finished can |
| 1733 | // request its own frame; this reconciles the cache with the attachment |
| 1734 | // list, which is a vector comparison when the draft has not changed. |
| 1735 | let attached_images = crate::tui::widgets::attachment_preview::attached_image_paths(app); |
| 1736 | if !attached_images.is_empty() && !crate::tui::color_compat::ascii_safe_enabled() { |
| 1737 | app.attachment_preview.track(&attached_images); |
| 1738 | } |
| 1739 | let shell_area = session_shell_area(size); |
| 1740 | // Keep the view stack's focus-context texture prototype (#4823) in step |
| 1741 | // with the parsed setting each frame: a plain enum/theme copy, no |
| 1742 | // allocation. `Off` leaves the render byte-identical to before. |
| 1743 | app.view_stack |
| 1744 | .set_focus_texture(app.focus_texture, app.ui_theme); |
| 1745 | app.view_stack.set_locale(app.ui_locale); |
| 1746 | app.sidebar_hover = crate::tui::app::SidebarHoverState::default(); |
| 1747 | app.viewport.last_prompt_area = None; |
| 1748 | app.viewport.interaction_targets.clear(); |
| 1749 | // Keep the OSC-0 whale title truthful to the current shell phase so |
| 1750 | // alt-tabbed sessions communicate state without a second in-app spinner. |
| 1751 | crate::tui::underwater::sync_title_activity(app); |
| 1752 | |
| 1753 | // Clear entire area with the configured app background. |
| 1754 | let background = Block::default().style(Style::default().bg(app.ui_theme.surface_bg)); |
| 1755 | f.render_widget(background, size); |
| 1756 | |
| 1757 | if app.onboarding != OnboardingState::None || app.redaction_gate { |
| 1758 | let ocean = crate::tui::ocean::OceanColumn::still_room( |
| 1759 | size, |
| 1760 | &app.ui_theme, |
| 1761 | app.viewport.ocean_caps, |
| 1762 | ); |
| 1763 | let _theme = crate::tui::views::ModalThemeScope::with_ocean( |
| 1764 | Some(app.ui_theme), |
| 1765 | ocean, |
| 1766 | app.viewport.ocean_caps, |
| 1767 | ); |
| 1768 | if app.onboarding == OnboardingState::None { |
| 1769 | crate::tui::redaction_gate::render(f, size, app); |
| 1770 | return None; |
| 1771 | } |
| 1772 | onboarding::render(f, size, app); |
| 1773 | // Onboarding is a backdrop, not a separate screen manager. Render any |
| 1774 | // native view above every onboarding step so shared pickers and the |
| 1775 | // first-run privacy disclosure cannot become invisible outside the |
| 1776 | // Provider step. |
| 1777 | if !app.view_stack.is_empty() { |
| 1778 | let area = onboarding::render_provider_notice(f, size, app); |
| 1779 | app.view_stack.render(area, f.buffer_mut()); |
| 1780 | } |
| 1781 | return None; |
| 1782 | } |
| 1783 | |
| 1784 | // The opening screen is no longer a separate surface. Founder ruling: |
| 1785 | // "we don't have to have a different look for the opening screen ... we |
| 1786 | // can make it an asset that exists there instead". The launch card is now |
| 1787 | // the idle transcript's own empty state (`underwater::launch_empty_state`), |
| 1788 | // so the composer below it is the real one, the footer and info line are |
| 1789 | // the ones every other screen wears, and Tab means what it means |
| 1790 | // everywhere else — there is no second input authority left to arbitrate. |
| 1791 | |
| 1792 | if app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::PetHabitat) { |
| 1793 | crate::tui::pet_watch::render_full(f, app); |
| 1794 | return None; |
| 1795 | } |
| 1796 | |
| 1797 | let pet_main = crate::tui::pet_watch::main_view(app); |
| 1798 | |
| 1799 | // Mini-window mode: when the host terminal window is pinned into its |
| 1800 | // small always-on-top form, hide the shell chrome and keep only what the |
| 1801 | // user opted to keep (`[mini_window]` in config.toml, or mutated live by |
| 1802 | // `/config mini_window.keep_*`). The message stream takes the rest. |
| 1803 | let mini = crate::tui::window_control::pinned(); |
| 1804 | let mini_cfg = app.mini_window.clone(); |
| 1805 | // The info line owns the shell's last row as exactly one row (spec §5b: |
| 1806 | // `Constraint::Length(1)`). It used to be the header; the founder moved |
| 1807 | // it to the bottom (SHELL-DESIGN-20260901 §2.0) so scrolling up reads as |
| 1808 | // intentional. `keep_header` still governs it in mini mode — the row it |
| 1809 | // names moved, not the preference. |
| 1810 | // Evaluate the fully-idle predicate exactly once per frame. It decides |
| 1811 | // how many rows the rail may reserve and whether the idle ocean draws |
| 1812 | // its brand mark (in ChatWidget); calling it twice would let the |
| 1813 | // reservation and the render disagree inside a single frame. |
| 1814 | let idle_empty = crate::tui::widgets::should_render_empty_state(app); |
| 1815 | // `tui.metrics_line = "hidden"` gives the row to the transcript (#5950). |
| 1816 | // The empty shell keeps route identity visible; render_info_row omits |
| 1817 | // session readings until a conversation exists. |
| 1818 | let info_height = if pet_main |
| 1819 | || (mini && !mini_cfg.keep_header) |
| 1820 | || app.metrics_line == codewhale_runtime::config::ChromeRowPreset::Hidden |
| 1821 | { |
| 1822 | 0 |
| 1823 | } else { |
| 1824 | info_row_height_for(size.height) |
| 1825 | }; |
| 1826 | // The merged Tideline footer is the single bottom row (spec §3: slots |
| 1827 | // 6+8 collapsed; §5b `Constraint::Length(1)`): phase·cost·posture on the |
| 1828 | // left, depth·keys on the right. It hides with the rest of the footer |
| 1829 | // chrome in mini mode, never with the composer. |
| 1830 | // `tui.posture_bar = "hidden"` likewise (#5950). |
| 1831 | let footer_height = if pet_main { |
| 1832 | crate::tui::phase_strip::height() |
| 1833 | } else if (mini && !mini_cfg.keep_footer) |
| 1834 | || app.posture_bar == codewhale_runtime::config::ChromeRowPreset::Hidden |
| 1835 | { |
| 1836 | 0 |
| 1837 | } else { |
| 1838 | crate::tui::phase_strip::height() |
| 1839 | }; |
| 1840 | let slash_menu_entries = visible_slash_menu_entries(app, SLASH_MENU_LIMIT); |
| 1841 | let mention_menu_limit = app.mention_menu_limit; |
| 1842 | let mention_menu_entries = |
| 1843 | crate::tui::file_mention::visible_mention_menu_entries(app, mention_menu_limit); |
| 1844 | if !mention_menu_entries.is_empty() && app.mention_menu_selected >= mention_menu_entries.len() { |
| 1845 | app.mention_menu_selected = mention_menu_entries.len().saturating_sub(1); |
| 1846 | } |
| 1847 | let rail_budget = rail_row_budget(app, shell_area.width, shell_area.height, idle_empty); |
| 1848 | let top_work_strip_height = if pet_main { |
| 1849 | crate::tui::work_surface::collapse_strip(app); |
| 1850 | 0 |
| 1851 | } else if mini && !mini_cfg.keep_todo { |
| 1852 | // Mini mode hides the strip; when the side rail is also hidden (the |
| 1853 | // default), drop the work-surface interaction state so stale |
| 1854 | // hitboxes from the pre-pin layout cannot swallow transcript clicks |
| 1855 | // or trigger phantom strip actions (review M1). A visible rail/strip |
| 1856 | // refreshes that state during its own render. |
| 1857 | if !mini_cfg.keep_sidebar { |
| 1858 | crate::tui::work_surface::collapse_strip(app); |
| 1859 | } |
| 1860 | 0 |
| 1861 | } else { |
| 1862 | crate::tui::work_surface::height(app, shell_area.width, shell_area.height, rail_budget) |
| 1863 | }; |
| 1864 | |
| 1865 | // Nothing paints above the stage any more, so the body is the whole |
| 1866 | // shell area. The old two-pass split existed only to pin a header to row |
| 1867 | // zero against ratatui's Flex defaults (#1834); with no header there is |
| 1868 | // nothing to pin. |
| 1869 | let body_area = shell_area; |
| 1870 | |
| 1871 | let body_height = body_area.height; |
| 1872 | let density_rows = crate::tui::widgets::composer_max_height(app.composer_density); |
| 1873 | let composer_max_height = body_height |
| 1874 | .saturating_sub( |
| 1875 | MIN_CHAT_HEIGHT |
| 1876 | .saturating_add(footer_height) |
| 1877 | .saturating_add(info_height) |
| 1878 | .saturating_add(top_work_strip_height), |
| 1879 | ) |
| 1880 | .max(MIN_COMPOSER_HEIGHT) |
| 1881 | .min((body_height / 2).max(density_rows)); |
| 1882 | let composer_height = if !pet_main && mini && !mini_cfg.keep_input { |
| 1883 | 0 |
| 1884 | } else { |
| 1885 | let composer_widget = ComposerWidget::new( |
| 1886 | app, |
| 1887 | composer_max_height, |
| 1888 | &slash_menu_entries, |
| 1889 | &mention_menu_entries, |
| 1890 | ); |
| 1891 | composer_widget.desired_height(shell_area.width) |
| 1892 | }; |
| 1893 | |
| 1894 | // Pending-input preview (queued / steered messages). Empty when nothing's |
| 1895 | // queued, so zero height when idle. Phase 2 of #85 — solves the |
| 1896 | // "messages typed during a running turn vanish" complaint by giving the |
| 1897 | // user immediate visible feedback above the composer. |
| 1898 | let pending_preview = build_pending_input_preview(app); |
| 1899 | let desired_preview_height = if !pet_main && mini { |
| 1900 | 0 |
| 1901 | } else { |
| 1902 | pending_preview.desired_height(shell_area.width) |
| 1903 | }; |
| 1904 | |
| 1905 | // The background-work chip (#5286) that used to pin a row above the |
| 1906 | // composer is gone: the posture bar's live counts own "what is in |
| 1907 | // flight" (one owner per fact), and nothing sits between the transcript |
| 1908 | // and the composer that is not a queued draft or an expanded panel. |
| 1909 | |
| 1910 | // The workbar (#4121): one row per workflow run, directly under the |
| 1911 | // posture bar, so live progress sits beside the controls that act on it |
| 1912 | // and never between the transcript and the composer. Zero rows when no |
| 1913 | // run is showing. |
| 1914 | let desired_workbar_height = if pet_main || mini { |
| 1915 | 0 |
| 1916 | } else { |
| 1917 | crate::tui::widgets::workbar::desired_rows(app.workflow_runs.len()) |
| 1918 | }; |
| 1919 | let plugin_cta_height = if !pet_main && mini && !mini_cfg.keep_input { |
| 1920 | 0 |
| 1921 | } else { |
| 1922 | app.plugin_cta_row_height() |
| 1923 | }; |
| 1924 | let approval_height = app.view_stack.top_docked_height(body_area.width); |
| 1925 | let auxiliary_budget = body_height.saturating_sub( |
| 1926 | top_work_strip_height |
| 1927 | .saturating_add(MIN_CHAT_HEIGHT) |
| 1928 | .saturating_add(composer_height) |
| 1929 | .saturating_add(footer_height) |
| 1930 | .saturating_add(info_height) |
| 1931 | .saturating_add(plugin_cta_height) |
| 1932 | .saturating_add(approval_height), |
| 1933 | ); |
| 1934 | // Queued-only previews author the direct controls in row two (and fall |
| 1935 | // back to controls-only when just one row remains). Mixed previews retain |
| 1936 | // up to three compact rows at the release floor. |
| 1937 | let preview_cap = if size.height >= 20 { 4 } else { 3 }; |
| 1938 | // The image thumbnail sits between the queued-input preview and the |
| 1939 | // composer. It competes for the same spare rows as the queued preview, |
| 1940 | // and the queued preview wins: a draft the person typed is worth more |
| 1941 | // than a picture they can still see in its own window. On a short |
| 1942 | // terminal the thumbnail also gives way on its own (a quarter of the |
| 1943 | // body), so the transcript never collapses to make room for it. |
| 1944 | let desired_attachment_preview_height = if (mini && !mini_cfg.keep_input) || pet_main { |
| 1945 | 0 |
| 1946 | } else { |
| 1947 | crate::tui::widgets::attachment_preview::AttachmentPreviewWidget::for_app(app) |
| 1948 | .map(|widget| widget.desired_height(shell_area.width)) |
| 1949 | .unwrap_or(0) |
| 1950 | }; |
| 1951 | let attachment_preview_height = desired_attachment_preview_height |
| 1952 | .min(body_height / 4) |
| 1953 | .min(auxiliary_budget.saturating_sub(desired_preview_height.min(preview_cap))); |
| 1954 | let preview_height = desired_preview_height.min( |
| 1955 | auxiliary_budget |
| 1956 | .saturating_sub(attachment_preview_height) |
| 1957 | .min(preview_cap), |
| 1958 | ); |
| 1959 | let workbar_height = desired_workbar_height.min( |
| 1960 | auxiliary_budget |
| 1961 | .saturating_sub(attachment_preview_height) |
| 1962 | .saturating_sub(preview_height), |
| 1963 | ); |
| 1964 | |
| 1965 | // Two pinned rows bracket the composer from below (SHELL-DESIGN-20260901 |
| 1966 | // §2.0 item 3, §2.3b): the posture bar — permission · mode · live counts |
| 1967 | // · the one hint that applies now, with the remote-control state or a |
| 1968 | // live notice pinned right — then the metrics line — model · ctx · cost |
| 1969 | // · ttft · tok/s · ↓ tokens, with the help hint pinned right. Both rows |
| 1970 | // are reserved in every phase, so a turn moving between idle, thinking, |
| 1971 | // tool use, approval, completion, failure, and cancellation rewrites |
| 1972 | // text inside fixed rows — the composer is never displaced. |
| 1973 | // The work surface (roster, to-do) lives BELOW those two rows by default |
| 1974 | // and only when it has content — scrolling up is intentional history — |
| 1975 | // while `top` placement keeps the strip above the transcript. The strip |
| 1976 | // owns a slot at each end and only one has height, so every other slot |
| 1977 | // keeps its index in both placements (the stage and preview are |
| 1978 | // addressed by position below). |
| 1979 | // Bottom never falls back (only side rails do), so the configured |
| 1980 | // placement is the effective one here. |
| 1981 | let strip_below = |
| 1982 | app.work_surface.placement == crate::tui::work_surface::WorkSurfacePlacement::Bottom; |
| 1983 | let (strip_above_height, strip_below_height) = if strip_below { |
| 1984 | (0, top_work_strip_height) |
| 1985 | } else { |
| 1986 | (top_work_strip_height, 0) |
| 1987 | }; |
| 1988 | let body_chunks = Layout::default() |
| 1989 | .direction(Direction::Vertical) |
| 1990 | .flex(ratatui::layout::Flex::Start) |
| 1991 | .constraints([ |
| 1992 | Constraint::Length(strip_above_height), // Tasks + To-do above transcript (`top`) |
| 1993 | Constraint::Min(1), // Chat area |
| 1994 | Constraint::Length(preview_height), // Pending input preview (0 if empty) |
| 1995 | Constraint::Length(attachment_preview_height), // Image thumbnail (0 if none) |
| 1996 | Constraint::Length(plugin_cta_height), // Live plugin CTA (0 unless matched) |
| 1997 | Constraint::Length(approval_height), |
| 1998 | Constraint::Length(composer_height), // Composer |
| 1999 | Constraint::Length(footer_height), // Posture bar |
| 2000 | Constraint::Length(workbar_height), // Workbar: one row per workflow run |
| 2001 | Constraint::Length(info_height), // Metrics line |
| 2002 | Constraint::Length(strip_below_height), // Roster + To-do under the chrome (`bottom`) |
| 2003 | ]) |
| 2004 | .split(body_area); |
| 2005 | let strip_slot = if strip_below { 10 } else { 0 }; |
| 2006 | let preview_slot = 2; |
| 2007 | let attachment_preview_slot = 3; |
| 2008 | let plugin_cta_slot = 4; |
| 2009 | let approval_slot = 5; |
| 2010 | let composer_slot = 6; |
| 2011 | let footer_slot = 7; |
| 2012 | let workbar_slot = 8; |
| 2013 | let info_slot = 9; |
| 2014 | |
| 2015 | if approval_height > 0 { |
| 2016 | let dock_area = body_chunks[approval_slot]; |
| 2017 | let dock_canvas = Rect::new( |
| 2018 | dock_area.x, |
| 2019 | body_area.y, |
| 2020 | dock_area.width, |
| 2021 | dock_area.bottom().saturating_sub(body_area.y), |
| 2022 | ); |
| 2023 | app.view_stack.set_approval_dock_canvas(Some(dock_canvas)); |
| 2024 | } else { |
| 2025 | app.view_stack.set_approval_dock_canvas(None); |
| 2026 | } |
| 2027 | if matches!( |
| 2028 | app.view_stack.top_kind(), |
| 2029 | Some(ModalKind::Approval | ModalKind::UserInput) |
| 2030 | ) { |
| 2031 | app.viewport.last_prompt_area = app.view_stack.top_occupied_region(size); |
| 2032 | } |
| 2033 | // Bottom prompts cover part of the ordinary chat slot. Resolve scrolling |
| 2034 | // against the rows that remain visible, or End leaves the newest content |
| 2035 | // underneath the prompt and PageUp counts rows the user cannot see. |
| 2036 | let mut visible_chat_area = body_chunks[1]; |
| 2037 | if let Some(prompt) = app.viewport.last_prompt_area { |
| 2038 | visible_chat_area.height = visible_chat_area |
| 2039 | .height |
| 2040 | .min(prompt.y.saturating_sub(visible_chat_area.y)); |
| 2041 | } |
| 2042 | let (work_chat_area, side_work_area) = if pet_main || (mini && !mini_cfg.keep_sidebar) { |
| 2043 | // Mini mode without the side rail: the transcript takes the whole |
| 2044 | // chat row. split_chat is skipped so the rail never reserves columns. |
| 2045 | (visible_chat_area, None) |
| 2046 | } else { |
| 2047 | crate::tui::work_surface::split_chat( |
| 2048 | app, |
| 2049 | visible_chat_area, |
| 2050 | rail_min_chat_width(idle_empty), |
| 2051 | ) |
| 2052 | }; |
| 2053 | |
| 2054 | if top_work_strip_height > 0 { |
| 2055 | crate::tui::work_surface::render(f, body_chunks[strip_slot], app); |
| 2056 | } else if let Some(work_area) = side_work_area { |
| 2057 | crate::tui::work_surface::render(f, work_area, app); |
| 2058 | } |
| 2059 | |
| 2060 | // Render the transcript and optional file-tree sidecar. The underwater |
| 2061 | // default deliberately has no legacy right sidebar: Tasks and To-do own |
| 2062 | // the strip above, Fleet owns `/fleet`, and dense context owns its |
| 2063 | // inspector. Keeping the sidebar here was the architectural reason the |
| 2064 | // rejected build still read as the old TUI under a gradient. |
| 2065 | let shell_ocean; |
| 2066 | { |
| 2067 | // Defensive backstop (#400): fill the entire body area with ink |
| 2068 | // background before any sub-widgets render, so cells that end up |
| 2069 | // uncovered by layout splits (e.g. after file-tree toggle or |
| 2070 | // resize) don't retain stale content from a previous frame. |
| 2071 | Block::default() |
| 2072 | .style(Style::default().bg(app.ui_theme.surface_bg)) |
| 2073 | .render(work_chat_area, f.buffer_mut()); |
| 2074 | |
| 2075 | // When the file-tree pane is visible and the terminal is wide |
| 2076 | // enough, reserve the left ~25% for the file tree. |
| 2077 | let chat_area = |
| 2078 | if app.file_tree.is_some() && work_chat_area.width >= FILE_TREE_MIN_HOST_WIDTH { |
| 2079 | app.file_tree_visible = true; |
| 2080 | let split = Layout::default() |
| 2081 | .direction(Direction::Horizontal) |
| 2082 | .constraints([Constraint::Percentage(25), Constraint::Percentage(75)]) |
| 2083 | .split(work_chat_area); |
| 2084 | let tree_area = split[0]; |
| 2085 | let remaining = split[1]; |
| 2086 | |
| 2087 | // Render the file-tree pane. |
| 2088 | if let Some(ref mut state) = app.file_tree { |
| 2089 | crate::tui::file_tree::render_file_tree(f, tree_area, state, app.ui_theme.mode); |
| 2090 | } |
| 2091 | |
| 2092 | remaining |
| 2093 | } else { |
| 2094 | app.file_tree_visible = false; |
| 2095 | work_chat_area |
| 2096 | }; |
| 2097 | app.sidebar_hover_tooltip = None; |
| 2098 | |
| 2099 | if pet_main { |
| 2100 | // Hidden shell surfaces must relinquish their pointer targets. |
| 2101 | // The common composer below still publishes its exact native plan. |
| 2102 | app.viewport.last_transcript_area = None; |
| 2103 | app.viewport.pinned_prompt_area = None; |
| 2104 | app.viewport.pinned_prompt_message = None; |
| 2105 | app.launch.row_hitboxes.clear(); |
| 2106 | crate::tui::pet_watch::render_main(f, chat_area, app); |
| 2107 | shell_ocean = None; |
| 2108 | } else if app.agent_focus.is_some() && !app.launch.return_to_session { |
| 2109 | // A focused worker's full transcript owns the conversation area; |
| 2110 | // the ocean column and every other shell surface stay as they are. |
| 2111 | // |
| 2112 | // The widget below is built only to sample the ocean column, but |
| 2113 | // its constructor also consumes `pending_scroll_delta` into the |
| 2114 | // (invisible) main-transcript scroll state — which would starve |
| 2115 | // the focused transcript of every PageUp/PageDown and wheel |
| 2116 | // event. Park the delta across the sample so `render_focus` |
| 2117 | // receives it and the focused pane scrolls exactly like the main |
| 2118 | // transcript. |
| 2119 | let parked_scroll_delta = app.viewport.pending_scroll_delta; |
| 2120 | app.viewport.pending_scroll_delta = 0; |
| 2121 | { |
| 2122 | let chat_widget = ChatWidget::new(app, chat_area).with_ocean_viewport(size); |
| 2123 | shell_ocean = chat_widget.ocean_column(); |
| 2124 | } |
| 2125 | app.viewport.pending_scroll_delta = parked_scroll_delta; |
| 2126 | // The constructor above sampled an invisible main transcript; |
| 2127 | // only the actual focused painter may publish semantic regions. |
| 2128 | app.viewport.ocean_semantic_surfaces.clear(); |
| 2129 | // The sampling constructor above records the pinned prompt header's |
| 2130 | // hit box from the main session's transcript, but the focus pane |
| 2131 | // never paints that header — its first row is the agent banner. |
| 2132 | // Drop the stale box so the banner cannot answer a click meant for |
| 2133 | // the (hidden) main transcript. |
| 2134 | app.viewport.pinned_prompt_area = None; |
| 2135 | app.viewport.pinned_prompt_message = None; |
| 2136 | crate::tui::agent_focus::refresh_focus(app); |
| 2137 | let buf = f.buffer_mut(); |
| 2138 | crate::tui::agent_focus::render_focus(app, chat_area, buf); |
| 2139 | } else { |
| 2140 | if app.launch.visible |
| 2141 | && !app.launch.return_to_session |
| 2142 | && app.onboarding == crate::tui::app::OnboardingState::None |
| 2143 | { |
| 2144 | app.launch |
| 2145 | .mark_reveal_started_at |
| 2146 | .get_or_insert_with(std::time::Instant::now); |
| 2147 | } |
| 2148 | let chat_widget = ChatWidget::new(app, chat_area).with_ocean_viewport(size); |
| 2149 | shell_ocean = chat_widget.ocean_column(); |
| 2150 | let buf = f.buffer_mut(); |
| 2151 | chat_widget.render(chat_area, buf); |
| 2152 | } |
| 2153 | // The launch card's rows are clickable where they painted. The row |
| 2154 | // offsets come from the same builder that produced the lines, so a |
| 2155 | // hitbox cannot describe a row the transcript did not draw — and a |
| 2156 | // fully dissolved card painted nothing this frame, so it owns no |
| 2157 | // rows either. |
| 2158 | if !pet_main |
| 2159 | && app.launch.card_paintable( |
| 2160 | app.ambient_clock_ms, |
| 2161 | app.motion_policy().allows_decorative(), |
| 2162 | ) |
| 2163 | { |
| 2164 | crate::tui::underwater::refresh_launch_row_hitboxes(app, chat_area); |
| 2165 | } else if !app.launch.row_hitboxes.is_empty() { |
| 2166 | app.launch.row_hitboxes.clear(); |
| 2167 | } |
| 2168 | } |
| 2169 | |
| 2170 | // Render pending-input preview (queued/steered messages, if any). |
| 2171 | if preview_height > 0 { |
| 2172 | let buf = f.buffer_mut(); |
| 2173 | pending_preview.render(body_chunks[preview_slot], buf); |
| 2174 | } |
| 2175 | |
| 2176 | // The cell thumbnail of the attached image, above the composer so the |
| 2177 | // picture is visible before the turn is sent. |
| 2178 | if attachment_preview_height > 0 |
| 2179 | && let Some(widget) = |
| 2180 | crate::tui::widgets::attachment_preview::AttachmentPreviewWidget::for_app(app) |
| 2181 | { |
| 2182 | let area = body_chunks[attachment_preview_slot]; |
| 2183 | widget.render(area, f.buffer_mut()); |
| 2184 | } |
| 2185 | |
| 2186 | if plugin_cta_height > 0 { |
| 2187 | let buf = f.buffer_mut(); |
| 2188 | crate::tui::plugin_suggestions::draw_plugin_cta(app, body_chunks[plugin_cta_slot], buf); |
| 2189 | } else { |
| 2190 | app.viewport.last_plugin_cta_area = None; |
| 2191 | app.viewport.last_plugin_cta_review_area = None; |
| 2192 | app.viewport.last_plugin_cta_dismiss_area = None; |
| 2193 | } |
| 2194 | |
| 2195 | // Render once and retain that exact plan for caret and pointer projection. |
| 2196 | let composer_plan = { |
| 2197 | let composer_widget = ComposerWidget::new( |
| 2198 | app, |
| 2199 | composer_max_height, |
| 2200 | &slash_menu_entries, |
| 2201 | &mention_menu_entries, |
| 2202 | ); |
| 2203 | composer_widget.render_plan(body_chunks[composer_slot], f.buffer_mut()) |
| 2204 | }; |
| 2205 | let cursor_pos = composer_plan.cursor.map(|pos| (pos.x, pos.y)); |
| 2206 | app.viewport.last_composer_area = Some(body_chunks[composer_slot]); |
| 2207 | app.view_stack |
| 2208 | .set_composer_top(Some(body_chunks[composer_slot].y)); |
| 2209 | app.viewport.last_composer_content = Some(composer_plan.geometry.inner); |
| 2210 | app.viewport.last_composer_scroll_offset = composer_plan.scroll_offset; |
| 2211 | app.viewport.last_composer_top_padding = composer_plan.top_padding; |
| 2212 | // The posture bar is the first row under the composer: permission chip |
| 2213 | // (never sheds), mode, live counts, the one hint that applies now, with |
| 2214 | // the remote-control state or a live notice pinned right. |
| 2215 | if footer_height > 0 { |
| 2216 | let area = body_chunks[footer_slot]; |
| 2217 | let mut facts = crate::tui::phase_strip::tideline_footer_from_app(app, area.width); |
| 2218 | if pet_main { |
| 2219 | // The pet header owns phase and notices. This row retains the |
| 2220 | // existing permission/mode controls, live counts and cap warning. |
| 2221 | facts.turn_clock = None; |
| 2222 | facts.session_clock = None; |
| 2223 | facts.right = None; |
| 2224 | if !app.is_loading { |
| 2225 | facts.hint = None; |
| 2226 | } |
| 2227 | } |
| 2228 | let working_glow = if matches!( |
| 2229 | crate::tui::underwater::ShellPhase::from_app(app), |
| 2230 | crate::tui::underwater::ShellPhase::Working |
| 2231 | | crate::tui::underwater::ShellPhase::Verifying |
| 2232 | ) { |
| 2233 | app.viewport |
| 2234 | .ocean_caps |
| 2235 | .zip(app.turn_started_at) |
| 2236 | .map(|(caps, started)| { |
| 2237 | ( |
| 2238 | caps, |
| 2239 | started.elapsed(), |
| 2240 | codewhale_ratatui::MotionMode::from_settings( |
| 2241 | app.low_motion, |
| 2242 | app.fancy_animations, |
| 2243 | ), |
| 2244 | ) |
| 2245 | }) |
| 2246 | } else { |
| 2247 | None |
| 2248 | }; |
| 2249 | let footer = facts |
| 2250 | .widget( |
| 2251 | &app.ui_theme, |
| 2252 | crate::tui::color_compat::ascii_safe_enabled(), |
| 2253 | ) |
| 2254 | .compact(app.posture_bar == codewhale_runtime::config::ChromeRowPreset::Compact) |
| 2255 | .working_glow(working_glow); |
| 2256 | app.viewport.working_glow_visible = footer.working_clock_visible(area) |
| 2257 | && working_glow.is_some_and(|(caps, _, mode)| { |
| 2258 | caps.depth == codewhale_ratatui::color::ColorDepth::TrueColor && mode.animates() |
| 2259 | }) |
| 2260 | && matches!(app.ui_theme.footer_bg, ratatui::style::Color::Rgb(..)) |
| 2261 | && matches!(app.ui_theme.text_body, ratatui::style::Color::Rgb(..)); |
| 2262 | let buf = f.buffer_mut(); |
| 2263 | Block::default() |
| 2264 | .style(Style::default().bg(app.ui_theme.footer_bg)) |
| 2265 | .render(area, buf); |
| 2266 | let count_rects = crate::tui::phase_strip::render_tideline_footer(area, buf, &footer); |
| 2267 | register_footer_count_targets(app, &facts, &count_rects); |
| 2268 | } |
| 2269 | |
| 2270 | if workbar_height > 0 { |
| 2271 | let area = body_chunks[workbar_slot]; |
| 2272 | render_workbar(f, app, area); |
| 2273 | app.viewport.last_workbar_area = Some(area); |
| 2274 | } else { |
| 2275 | app.viewport.last_workbar_area = None; |
| 2276 | } |
| 2277 | |
| 2278 | // The metrics line sits directly under the posture bar: model · ctx · |
| 2279 | // cost · ttft · tok/s · ↓ tokens, with the help hint pinned right. |
| 2280 | let mut info_interactions = InfoLineInteractionHitboxes::default(); |
| 2281 | if info_height > 0 { |
| 2282 | info_interactions = render_info_row(f, app, body_chunks[info_slot], idle_empty); |
| 2283 | } else { |
| 2284 | app.viewport.last_infoline_hitboxes.clear(); |
| 2285 | } |
| 2286 | register_info_interaction_targets(app, info_interactions); |
| 2287 | |
| 2288 | // The underwater shell is one water column, not a stack of independently |
| 2289 | // shaded panels. Continue the transcript's absolute-row ramp through each |
| 2290 | // ordinary shell surface after its foreground has rendered. Semantic |
| 2291 | // backgrounds remain exact through different-ground guards and the |
| 2292 | // frame-derived explicit styled-surface mask, including aliased colors. |
| 2293 | if let Some(column) = shell_ocean { |
| 2294 | app.viewport |
| 2295 | .ocean_semantic_surfaces |
| 2296 | .push(body_chunks[composer_slot]); |
| 2297 | // The working canvas may keep a small responsive gutter, but the water |
| 2298 | // does not stop at that content edge. One full-frame `surface_bg` pass |
| 2299 | // paints the cleared terminal floor and every ordinary surface band |
| 2300 | // so wide layouts read as one ocean rather than a blue card floating |
| 2301 | // between black banks. `paint_matching` leaves every semantic widget |
| 2302 | // background untouched. |
| 2303 | column.paint_matching_native( |
| 2304 | size, |
| 2305 | f.buffer_mut(), |
| 2306 | app.ui_theme.surface_bg, |
| 2307 | &app.ui_theme, |
| 2308 | &app.viewport.ocean_semantic_surfaces, |
| 2309 | ); |
| 2310 | if plugin_cta_height > 0 { |
| 2311 | column.paint_matching_native( |
| 2312 | body_chunks[plugin_cta_slot], |
| 2313 | f.buffer_mut(), |
| 2314 | app.ui_theme.composer_bg, |
| 2315 | &app.ui_theme, |
| 2316 | &app.viewport.ocean_semantic_surfaces, |
| 2317 | ); |
| 2318 | } |
| 2319 | if footer_height > 0 { |
| 2320 | column.paint_matching_native( |
| 2321 | body_chunks[footer_slot], |
| 2322 | f.buffer_mut(), |
| 2323 | app.ui_theme.footer_bg, |
| 2324 | &app.ui_theme, |
| 2325 | &app.viewport.ocean_semantic_surfaces, |
| 2326 | ); |
| 2327 | } |
| 2328 | if workbar_height > 0 { |
| 2329 | column.paint_matching_native( |
| 2330 | body_chunks[workbar_slot], |
| 2331 | f.buffer_mut(), |
| 2332 | app.ui_theme.footer_bg, |
| 2333 | &app.ui_theme, |
| 2334 | &app.viewport.ocean_semantic_surfaces, |
| 2335 | ); |
| 2336 | } |
| 2337 | if info_height > 0 { |
| 2338 | column.paint_matching_native( |
| 2339 | body_chunks[info_slot], |
| 2340 | f.buffer_mut(), |
| 2341 | app.ui_theme.header_bg, |
| 2342 | &app.ui_theme, |
| 2343 | &app.viewport.ocean_semantic_surfaces, |
| 2344 | ); |
| 2345 | } |
| 2346 | if top_work_strip_height > 0 { |
| 2347 | column.paint_matching_native( |
| 2348 | body_chunks[strip_slot], |
| 2349 | f.buffer_mut(), |
| 2350 | app.ui_theme.composer_bg, |
| 2351 | &app.ui_theme, |
| 2352 | &app.viewport.ocean_semantic_surfaces, |
| 2353 | ); |
| 2354 | } else if let Some(work_area) = side_work_area { |
| 2355 | column.paint_matching_native( |
| 2356 | work_area, |
| 2357 | f.buffer_mut(), |
| 2358 | app.ui_theme.composer_bg, |
| 2359 | &app.ui_theme, |
| 2360 | &app.viewport.ocean_semantic_surfaces, |
| 2361 | ); |
| 2362 | } |
| 2363 | } |
| 2364 | register_clickable_chrome_for_hover(app); |
| 2365 | crate::tui::hover_layer::apply_resolved_effects( |
| 2366 | f.buffer_mut(), |
| 2367 | app.effective_low_motion_for_status(), |
| 2368 | &app.ui_theme, |
| 2369 | ); |
| 2370 | if !app.view_stack.is_empty() { |
| 2371 | // The live transcript overlay snapshots the app's history + active |
| 2372 | // cell on each render so streaming mutations propagate. Other views |
| 2373 | // are static and skip this refresh. |
| 2374 | if app.view_stack.top_kind() == Some(ModalKind::LiveTranscript) { |
| 2375 | refresh_live_transcript_overlay(app); |
| 2376 | } else if app.view_stack.top_kind() == Some(ModalKind::ContextInspector) { |
| 2377 | refresh_context_inspector_overlay(app); |
| 2378 | } |
| 2379 | let buf = f.buffer_mut(); |
| 2380 | let _theme = crate::tui::views::ModalThemeScope::with_ocean( |
| 2381 | Some(app.ui_theme), |
| 2382 | shell_ocean, |
| 2383 | app.viewport.ocean_caps, |
| 2384 | ); |
| 2385 | app.view_stack.render(size, buf); |
| 2386 | // Any view on the stack owns the keyboard and paints over the |
| 2387 | // composer, and no view draws its own text caret, so the composer's |
| 2388 | // caret must not surface through the modal (#6545). |
| 2389 | return None; |
| 2390 | } |
| 2391 | |
| 2392 | cursor_pos |
| 2393 | } |
| 2394 | |
| 2395 | /// Hide the real terminal caret before ratatui applies a frame diff. |
| 2396 | /// |
| 2397 | /// A diff moves the terminal cursor through every changed run. Electron/xterm |
| 2398 | /// IME bridges (notably Tabby on Windows, #5023) can observe those transient |
| 2399 | /// positions even though the final frame is correct, which makes the native |
| 2400 | /// candidate window jump around the screen. Keep the caret hidden for the |
| 2401 | /// whole diff and pair this with [`finish_frame_cursor`] after the draw. |
| 2402 | pub(super) fn prepare_frame_cursor<B: ratatui::backend::Backend>( |
| 2403 | terminal: &mut Terminal<B>, |
| 2404 | ) -> std::result::Result<(), B::Error> { |
| 2405 | terminal.hide_cursor() |
| 2406 | } |
| 2407 | |
| 2408 | /// Restore the composer caret in IME-safe order: position first, reveal last. |
| 2409 | /// |
| 2410 | /// Ratatui's `Frame::set_cursor_position` path currently calls `show_cursor` |
| 2411 | /// before `set_cursor_position`. That briefly exposes the stale or last-diff |
| 2412 | /// position to the terminal's IME bridge. Owning the final two operations here |
| 2413 | /// preserves ratatui's internal cursor tracking while ensuring there is only |
| 2414 | /// one visible caret position per completed frame (#5023). |
| 2415 | pub(super) fn finish_frame_cursor<B: ratatui::backend::Backend>( |
| 2416 | terminal: &mut Terminal<B>, |
| 2417 | cursor_pos: Option<(u16, u16)>, |
| 2418 | ) -> std::result::Result<(), B::Error> { |
| 2419 | if let Some(cursor_pos) = cursor_pos { |
| 2420 | terminal.set_cursor_position(cursor_pos)?; |
| 2421 | terminal.show_cursor()?; |
| 2422 | } |
| 2423 | Ok(()) |
| 2424 | } |
| 2425 | |
| 2426 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 2427 | pub(crate) enum FrameRepaint { |
| 2428 | Diff, |
| 2429 | Recapture, |
| 2430 | Clear, |
| 2431 | } |
| 2432 | |
| 2433 | fn repaint_changed_links(buffer: &mut Buffer, previous: &[osc8::LinkRegion]) { |
| 2434 | osc8::FRAME_LINKS.with(|links| { |
| 2435 | let links = links.borrow(); |
| 2436 | let current = if osc8::enabled() { |
| 2437 | links.as_slice() |
| 2438 | } else { |
| 2439 | &[] |
| 2440 | }; |
| 2441 | if current == previous { |
| 2442 | return; |
| 2443 | } |
| 2444 | |
| 2445 | let changed = current |
| 2446 | .iter() |
| 2447 | .filter(|region| !previous.contains(region)) |
| 2448 | .chain(previous.iter().filter(|region| !current.contains(region))); |
| 2449 | for region in changed { |
| 2450 | for x in region.col_start..=region.col_end { |
| 2451 | if let Some(cell) = buffer.cell_mut((x, region.row)) |
| 2452 | && cell.diff_option == CellDiffOption::None |
| 2453 | { |
| 2454 | cell.diff_option = CellDiffOption::AlwaysUpdate; |
| 2455 | } |
| 2456 | } |
| 2457 | } |
| 2458 | }); |
| 2459 | } |
| 2460 | |
| 2461 | pub(super) fn draw_frame_with_repaint<W: Write>( |
| 2462 | terminal: &mut Terminal<ColorCompatBackend<W>>, |
| 2463 | repaint: FrameRepaint, |
| 2464 | render: impl FnOnce(&mut Frame<'_>), |
| 2465 | ) -> Result<()> { |
| 2466 | if repaint != FrameRepaint::Diff { |
| 2467 | terminal.backend_mut().write_all(TERMINAL_ORIGIN_RESET)?; |
| 2468 | } |
| 2469 | if repaint == FrameRepaint::Clear { |
| 2470 | terminal.clear()?; |
| 2471 | } |
| 2472 | let previous_links = terminal.backend_mut().take_previous_frame_links(); |
| 2473 | terminal.draw(|frame| { |
| 2474 | render(frame); |
| 2475 | if repaint == FrameRepaint::Recapture { |
| 2476 | for cell in &mut frame.buffer_mut().content { |
| 2477 | #[allow(deprecated)] |
| 2478 | let skipped = cell.skip; |
| 2479 | if cell.diff_option == CellDiffOption::None && !skipped { |
| 2480 | cell.diff_option = CellDiffOption::AlwaysUpdate; |
| 2481 | } |
| 2482 | } |
| 2483 | } else { |
| 2484 | repaint_changed_links(frame.buffer_mut(), &previous_links); |
| 2485 | } |
| 2486 | })?; |
| 2487 | Ok(()) |
| 2488 | } |
| 2489 | |
| 2490 | /// Draw a complete application frame within a synchronized-update batch. |
| 2491 | /// Focus recapture covers the viewport without erasing it first; resize and |
| 2492 | /// external handoffs retain the clear-and-redraw path. A recapture can also |
| 2493 | /// cause one additional ordinary diff because Ratatui compares cell directives. |
| 2494 | pub(crate) fn draw_app_frame_inner( |
| 2495 | terminal: &mut AppTerminal, |
| 2496 | app: &mut App, |
| 2497 | config: &Config, |
| 2498 | repaint: FrameRepaint, |
| 2499 | ) -> Result<()> { |
| 2500 | terminal.backend_mut().set_palette_mode(app.ui_theme.mode); |
| 2501 | terminal.backend_mut().set_theme(app.theme_id, app.ui_theme); |
| 2502 | app.viewport.ocean_caps = Some(terminal.backend().native_ocean_caps()); |
| 2503 | app.viewport.detected_background = terminal.backend().detected_background(); |
| 2504 | // DEC 2026 wrapping is on by default but can be turned off for |
| 2505 | // terminals that mishandle it (Ptyxis 50.x + VTE 0.84.x flashes the |
| 2506 | // whole viewport on every wrapped frame instead of deferring as the |
| 2507 | // standard requires). Settings::synchronized_output_enabled resolves |
| 2508 | // the user's setting against the Ptyxis env auto-detect. |
| 2509 | let resized = app.viewport.pending_terminal_size.take(); |
| 2510 | let result = synchronized_frame(terminal, app.synchronized_output_enabled, |terminal| { |
| 2511 | if let Some(size) = resized { |
| 2512 | let refit = terminal.resize(Rect::new(0, 0, size.width, size.height)); |
| 2513 | if let Err(err) = refit { |
| 2514 | tracing::warn!(?err, "terminal resize failed; falling back to clear+draw"); |
| 2515 | } |
| 2516 | // ConHost and Terminal.app can briefly report the previous size. |
| 2517 | terminal.backend_mut().force_size(size); |
| 2518 | terminal.backend_mut().set_terminal_size(size); |
| 2519 | } |
| 2520 | // The terminal cursor itself is also input-method geometry. Hide it |
| 2521 | // before clear/diff operations move it, then restore the one composer |
| 2522 | // position after ratatui finishes drawing (#5023). |
| 2523 | prepare_frame_cursor(terminal)?; |
| 2524 | let repaint = if resized.is_some() { |
| 2525 | FrameRepaint::Clear |
| 2526 | } else { |
| 2527 | repaint |
| 2528 | }; |
| 2529 | let mut cursor_pos = None; |
| 2530 | let mut frame_area = ratatui::layout::Rect::default(); |
| 2531 | draw_frame_with_repaint(terminal, repaint, |f| { |
| 2532 | frame_area = f.area(); |
| 2533 | cursor_pos = render(f, app, config); |
| 2534 | })?; |
| 2535 | finish_frame_cursor(terminal, cursor_pos)?; |
| 2536 | if cursor_pos.is_none() |
| 2537 | && let Some(anchor) = app.view_stack.cursor_anchor(frame_area) |
| 2538 | { |
| 2539 | terminal.set_cursor_position(anchor)?; |
| 2540 | } |
| 2541 | Ok(()) |
| 2542 | }); |
| 2543 | if resized.is_some() { |
| 2544 | terminal.backend_mut().clear_forced_size(); |
| 2545 | } |
| 2546 | result |
| 2547 | } |
| 2548 | |
| 2549 | /// End and flush the synchronized frame even when resizing or drawing fails. |
| 2550 | pub(super) fn synchronized_frame<B, T>( |
| 2551 | terminal: &mut Terminal<B>, |
| 2552 | enabled: bool, |
| 2553 | draw: impl FnOnce(&mut Terminal<B>) -> Result<T>, |
| 2554 | ) -> Result<T> |
| 2555 | where |
| 2556 | B: ratatui::backend::Backend + Write, |
| 2557 | { |
| 2558 | if enabled { |
| 2559 | let _ = terminal.backend_mut().write_all(BEGIN_SYNC_UPDATE); |
| 2560 | } |
| 2561 | let result = draw(terminal); |
| 2562 | if enabled { |
| 2563 | let _ = terminal.backend_mut().write_all(END_SYNC_UPDATE); |
| 2564 | } |
| 2565 | let _ = std::io::Write::flush(terminal.backend_mut()); |
| 2566 | result |
| 2567 | } |
| 2568 | |
| 2569 | /// Count how many `HistoryCell::User` entries currently live in the |
| 2570 | /// transcript. Used by the backtrack state machine to decide whether |
| 2571 | /// there's anything to rewind to. Walks `app.history` directly so it |
| 2572 | /// stays accurate even mid-stream (the streaming Assistant cell never |
| 2573 | /// counts as a user turn). |
| 2574 | pub(crate) fn count_user_history_cells(app: &App) -> usize { |
| 2575 | app.history |
| 2576 | .iter() |
| 2577 | .filter(|cell| matches!(cell, HistoryCell::User { .. })) |
| 2578 | .count() |
| 2579 | } |
| 2580 | |
| 2581 | /// Find the absolute index of the Nth-from-tail `HistoryCell::User` in |
| 2582 | /// `app.history`. `depth` of 0 selects the most recent user cell. |
| 2583 | /// Returns `None` if `depth` is out of range. |
| 2584 | pub(crate) fn find_user_cell_index_from_tail(app: &App, depth: usize) -> Option<usize> { |
| 2585 | let mut count = 0usize; |
| 2586 | for (idx, cell) in app.history.iter().enumerate().rev() { |
| 2587 | if matches!(cell, HistoryCell::User { .. }) { |
| 2588 | if count == depth { |
| 2589 | return Some(idx); |
| 2590 | } |
| 2591 | count += 1; |
| 2592 | } |
| 2593 | } |
| 2594 | None |
| 2595 | } |
| 2596 | |
| 2597 | /// Truncate `text` to at most `max_chars` characters, cutting at the last |
| 2598 | /// natural phrase boundary (`.`, `,`, `:`, `;`, `—`, `-`, or whitespace) |
| 2599 | /// so words are never split. Appends `…` only when text was actually cut. |
| 2600 | pub(crate) fn short_title_truncate(text: &str, max_chars: usize) -> String { |
| 2601 | if text.chars().count() <= max_chars { |
| 2602 | return text.to_string(); |
| 2603 | } |
| 2604 | // Find the boundary as a character index. `str::rfind` returns a byte |
| 2605 | // offset, which mis-counts multi-byte UTF-8 text when fed back into |
| 2606 | // `chars().take()`, so operate on `Vec<char>` instead. |
| 2607 | let candidate: Vec<char> = text.chars().take(max_chars).collect(); |
| 2608 | let boundary = candidate |
| 2609 | .iter() |
| 2610 | .rposition(|&c| matches!(c, '.' | ',' | ':' | ';' | '—' | '-')) |
| 2611 | .or_else(|| candidate.iter().rposition(|&c| c == ' ')) |
| 2612 | .unwrap_or(max_chars.min(candidate.len()).saturating_sub(1)); |
| 2613 | let cut: String = text.chars().take(boundary.max(1)).collect(); |
| 2614 | format!("{cut}…") |
| 2615 | } |
| 2616 | |
| 2617 | pub(crate) fn compact_user_context_display(content: &str) -> String { |
| 2618 | content |
| 2619 | .split("\n\n---\n\nLocal context from @mentions:") |
| 2620 | .next() |
| 2621 | .unwrap_or(content) |
| 2622 | .to_string() |
| 2623 | } |
| 2624 | |
| 2625 | #[cfg(test)] |
| 2626 | pub(crate) fn transcript_scroll_percent(top: usize, visible: usize, total: usize) -> Option<u16> { |
| 2627 | if total <= visible { |
| 2628 | return None; |
| 2629 | } |
| 2630 | |
| 2631 | let max_top = total.saturating_sub(visible); |
| 2632 | if max_top == 0 { |
| 2633 | return None; |
| 2634 | } |
| 2635 | |
| 2636 | let clamped_top = top.min(max_top); |
| 2637 | let percent = ((clamped_top as f64 / max_top as f64) * 100.0).round() as u16; |
| 2638 | Some(percent.min(100)) |
| 2639 | } |
| 2640 | |
| 2641 | pub(crate) fn estimated_context_tokens(app: &App) -> Option<i64> { |
| 2642 | // ONE estimator: this is `compaction::estimate_input_tokens_for_pressure` |
| 2643 | // over the same message list (per-message cache, framing included) — |
| 2644 | // deliberately not the 1.5x conservative variant. The meter, the >=80% |
| 2645 | // depth warning, and the auto-compact gate must agree about where the |
| 2646 | // threshold is: the inflated estimate used to show "ctx 82%" while the |
| 2647 | // gate read ~55% and correctly refused to compact (#6297). The 1.5x |
| 2648 | // inflation stays where it belongs — request-overflow protection |
| 2649 | // (`estimate_input_tokens_conservative`). |
| 2650 | let message_count = app.api_messages.len(); |
| 2651 | let mut cache = app.context_token_cache.borrow_mut(); |
| 2652 | if cache.message_tokens.len() > message_count { |
| 2653 | cache.message_tokens.truncate(message_count); |
| 2654 | } |
| 2655 | while cache.message_tokens.len() < message_count { |
| 2656 | let index = cache.message_tokens.len(); |
| 2657 | cache |
| 2658 | .message_tokens |
| 2659 | .push(estimate_tokens(&app.api_messages[index..=index])); |
| 2660 | } |
| 2661 | // The final assistant/tool message may grow while streaming. Recompute |
| 2662 | // only that tail entry; historical messages remain O(1) on steady frames. |
| 2663 | if message_count > 0 { |
| 2664 | let last = message_count - 1; |
| 2665 | cache.message_tokens[last] = estimate_tokens(&app.api_messages[last..=last]); |
| 2666 | } |
| 2667 | let message_tokens = cache.message_tokens.iter().copied().sum::<usize>(); |
| 2668 | let system_tokens = |
| 2669 | estimate_input_tokens_conservative(&[], app.system_prompt.as_ref()).saturating_sub(48); |
| 2670 | let estimated = message_tokens |
| 2671 | .saturating_add(system_tokens) |
| 2672 | .saturating_add(message_count.saturating_mul(12)) |
| 2673 | .saturating_add(48); |
| 2674 | i64::try_from(estimated).ok() |
| 2675 | } |
| 2676 | |
| 2677 | pub(crate) fn context_usage_snapshot(app: &App) -> Option<(i64, u32, f64)> { |
| 2678 | let max = app.effective_context_window(); |
| 2679 | context_usage_snapshot_for_window(app, max) |
| 2680 | } |
| 2681 | |
| 2682 | pub(crate) fn context_usage_snapshot_for_window(app: &App, max: u32) -> Option<(i64, u32, f64)> { |
| 2683 | // Before a conversation starts, the assembled startup prompt alone is not |
| 2684 | // conversation usage, and compacting an empty session cannot reclaim it. |
| 2685 | // A submitted first turn has started the conversation even before the |
| 2686 | // engine mirrors its messages back, and so has any provider usage; those |
| 2687 | // keep the real pressure reading. |
| 2688 | let conversation_started = |
| 2689 | !app.api_messages.is_empty() || app.is_loading || count_user_history_cells(app) > 0; |
| 2690 | if !conversation_started && app.last_billed_input_tokens.unwrap_or(0) == 0 { |
| 2691 | return Some((0, max, 0.0)); |
| 2692 | } |
| 2693 | // Lift to the provider-billed prompt exactly as the auto-compaction gate, |
| 2694 | // the context inspector and the `/context` headline do (#5577): a provider |
| 2695 | // billing above the local estimate must not leave the footer under-showing |
| 2696 | // the pressure those surfaces report. |
| 2697 | let billed = app.last_billed_input_tokens.map(i64::from); |
| 2698 | let used = match (estimated_context_tokens(app), billed) { |
| 2699 | (Some(estimated), Some(billed)) => estimated.max(0).max(billed), |
| 2700 | (Some(estimated), None) => estimated.max(0), |
| 2701 | (None, Some(billed)) => billed, |
| 2702 | (None, None) => return None, |
| 2703 | }; |
| 2704 | |
| 2705 | let percent = if max == 0 { |
| 2706 | 0.0 |
| 2707 | } else { |
| 2708 | let max_f64 = f64::from(max); |
| 2709 | let used_f64 = used as f64; |
| 2710 | ((used_f64 / max_f64) * 100.0).clamp(0.0, 100.0) |
| 2711 | }; |
| 2712 | Some((used, max, percent)) |
| 2713 | } |
| 2714 | |
| 2715 | /// True while a `workflow` tool is executing in the foreground (active cell) |
| 2716 | /// or still shown as running in history. Used to keep per-subagent completion |
| 2717 | /// notifications quiet during a workflow run under `final-only`. |
| 2718 | pub(crate) fn workflow_tool_is_running(app: &App) -> bool { |
| 2719 | fn is_running_workflow(cell: &HistoryCell) -> bool { |
| 2720 | matches!( |
| 2721 | cell, |
| 2722 | HistoryCell::Tool(ToolCell::Generic(tool)) |
| 2723 | if tool.name == "workflow" && tool.status.is_active() |
| 2724 | ) |
| 2725 | } |
| 2726 | app.history.iter().any(is_running_workflow) |
| 2727 | || app |
| 2728 | .active_cell |
| 2729 | .as_ref() |
| 2730 | .is_some_and(|active| active.entries().iter().any(is_running_workflow)) |
| 2731 | } |
| 2732 | |
| 2733 | #[cfg(test)] |
| 2734 | mod tests { |
| 2735 | use std::time::Instant; |
| 2736 | |
| 2737 | use super::{ |
| 2738 | drain_text_block, estimate_output_tokens_from_text, register_info_interaction_targets, |
| 2739 | render_info_row, short_title_truncate, |
| 2740 | }; |
| 2741 | use ratatui::{Terminal, backend::TestBackend}; |
| 2742 | |
| 2743 | #[test] |
| 2744 | fn estimated_streaming_tokens_round_up_from_text_chars() { |
| 2745 | assert_eq!(estimate_output_tokens_from_text(""), 0); |
| 2746 | assert_eq!(estimate_output_tokens_from_text("abc"), 1); |
| 2747 | assert_eq!(estimate_output_tokens_from_text("abcd"), 1); |
| 2748 | assert_eq!(estimate_output_tokens_from_text("abcde"), 2); |
| 2749 | } |
| 2750 | |
| 2751 | /// #7123: the text drain must never take a reasoning block. A reasoning |
| 2752 | /// tail handed to the assistant cell would appear as prose, which is the |
| 2753 | /// split sentence this fix exists to prevent. |
| 2754 | #[test] |
| 2755 | fn issue_7123_drain_text_block_leaves_a_reasoning_block_alone() { |
| 2756 | use codewhale_tui_kit::streaming::StreamingState; |
| 2757 | |
| 2758 | let mut state = StreamingState::new(); |
| 2759 | state.start_thinking(0); |
| 2760 | state.push_content(0, "reasoning tail"); |
| 2761 | assert_eq!( |
| 2762 | drain_text_block(&mut state), |
| 2763 | "", |
| 2764 | "a reasoning block must not be drained into the prose" |
| 2765 | ); |
| 2766 | assert_eq!( |
| 2767 | state.pending_len(0), |
| 2768 | "reasoning tail".len(), |
| 2769 | "the reasoning tail must stay buffered for its own drain" |
| 2770 | ); |
| 2771 | |
| 2772 | let mut state = StreamingState::new(); |
| 2773 | state.start_text(0); |
| 2774 | state.push_content(0, "prose tail"); |
| 2775 | assert_eq!(drain_text_block(&mut state), "prose tail"); |
| 2776 | assert_eq!(state.pending_len(0), 0); |
| 2777 | |
| 2778 | // An empty state has no block at index 0; the drain is a no-op rather |
| 2779 | // than a panic. |
| 2780 | let mut state = StreamingState::new(); |
| 2781 | assert_eq!(drain_text_block(&mut state), ""); |
| 2782 | } |
| 2783 | |
| 2784 | #[test] |
| 2785 | fn issue_7142_reroot_cause_survives_empty_snapshot_and_attributes_transitions() { |
| 2786 | use codewhale_models::{ContentBlock, Message, Role}; |
| 2787 | use std::sync::Arc; |
| 2788 | |
| 2789 | let msg = |text: &str| Message { |
| 2790 | role: Role::User, |
| 2791 | content: vec![ContentBlock::Text { |
| 2792 | text: text.to_string(), |
| 2793 | cache_control: None, |
| 2794 | }], |
| 2795 | }; |
| 2796 | |
| 2797 | let mut app = crate::tui::test_support::test_app_with_options( |
| 2798 | crate::tui::test_support::test_tui_options("."), |
| 2799 | ); |
| 2800 | app.push_api_message(msg("first")); |
| 2801 | let before = app.session_journal.entries.len(); |
| 2802 | let rebranch = app |
| 2803 | .session_journal |
| 2804 | .rebranch_active_messages_stamped(&app.api_messages, &app.api_message_stamps); |
| 2805 | assert_eq!( |
| 2806 | super::consume_window_reroot_event(&mut app, before, rebranch), |
| 2807 | None |
| 2808 | ); |
| 2809 | assert_eq!(app.window_reroot_cause, None); |
| 2810 | |
| 2811 | app.set_api_messages(Arc::new(Vec::new())); |
| 2812 | assert_eq!(app.window_reroot_cause, Some("engine_projection_empty")); |
| 2813 | let before = app.session_journal.entries.len(); |
| 2814 | let rebranch = app |
| 2815 | .session_journal |
| 2816 | .rebranch_active_messages_stamped(&app.api_messages, &app.api_message_stamps); |
| 2817 | assert_eq!( |
| 2818 | super::consume_window_reroot_event(&mut app, before, rebranch), |
| 2819 | None |
| 2820 | ); |
| 2821 | assert_eq!(app.window_reroot_cause, Some("engine_projection_empty")); |
| 2822 | |
| 2823 | app.push_api_message(msg("second")); |
| 2824 | assert_eq!(app.window_reroot_cause, Some("engine_projection_empty")); |
| 2825 | let before = app.session_journal.entries.len(); |
| 2826 | let rebranch = app |
| 2827 | .session_journal |
| 2828 | .rebranch_active_messages_stamped(&app.api_messages, &app.api_message_stamps); |
| 2829 | assert_eq!( |
| 2830 | super::consume_window_reroot_event(&mut app, before, rebranch), |
| 2831 | Some(("active_path_empty", "engine_projection_empty")) |
| 2832 | ); |
| 2833 | assert_eq!(app.window_reroot_cause, None); |
| 2834 | |
| 2835 | app.api_messages_mut().clear(); |
| 2836 | app.session_journal.leaf_id = None; |
| 2837 | app.window_reroot_cause = None; |
| 2838 | app.push_api_message(msg("third")); |
| 2839 | assert_eq!(app.window_reroot_cause, Some("user_turn_after_empty_path")); |
| 2840 | let before = app.session_journal.entries.len(); |
| 2841 | let rebranch = app |
| 2842 | .session_journal |
| 2843 | .rebranch_active_messages_stamped(&app.api_messages, &app.api_message_stamps); |
| 2844 | assert_eq!( |
| 2845 | super::consume_window_reroot_event(&mut app, before, rebranch), |
| 2846 | Some(("active_path_empty", "user_turn_after_empty_path")) |
| 2847 | ); |
| 2848 | assert_eq!(app.window_reroot_cause, None); |
| 2849 | |
| 2850 | app.api_messages_mut().clear(); |
| 2851 | app.session_journal.leaf_id = None; |
| 2852 | app.window_reroot_cause = None; |
| 2853 | app.set_api_messages(Arc::new(vec![msg("fourth")])); |
| 2854 | assert_eq!( |
| 2855 | app.window_reroot_cause, |
| 2856 | Some("engine_projection_no_active_path") |
| 2857 | ); |
| 2858 | let before = app.session_journal.entries.len(); |
| 2859 | let rebranch = app |
| 2860 | .session_journal |
| 2861 | .rebranch_active_messages_stamped(&app.api_messages, &app.api_message_stamps); |
| 2862 | assert_eq!( |
| 2863 | super::consume_window_reroot_event(&mut app, before, rebranch), |
| 2864 | Some(("active_path_empty", "engine_projection_no_active_path")) |
| 2865 | ); |
| 2866 | assert_eq!(app.window_reroot_cause, None); |
| 2867 | |
| 2868 | app.window_reroot_cause = Some("session_restore"); |
| 2869 | let before = app.session_journal.entries.len(); |
| 2870 | let rebranch = app |
| 2871 | .session_journal |
| 2872 | .rebranch_active_messages_stamped(&app.api_messages, &app.api_message_stamps); |
| 2873 | assert_eq!( |
| 2874 | super::consume_window_reroot_event(&mut app, before, rebranch), |
| 2875 | None |
| 2876 | ); |
| 2877 | assert_eq!(app.window_reroot_cause, None); |
| 2878 | } |
| 2879 | |
| 2880 | /// Chrome that answers a click must also answer the pointer, or the app |
| 2881 | /// teaches people that pointing at things does not work here. |
| 2882 | #[test] |
| 2883 | fn clickable_chrome_registers_a_hover_target() { |
| 2884 | let _guard = crate::tui::hover_layer::HOVER_TEST_LOCK.lock().unwrap(); |
| 2885 | crate::tui::hover_layer::begin_frame(); |
| 2886 | let mut app = crate::tui::test_support::test_app_with_options( |
| 2887 | crate::tui::test_support::test_tui_options("."), |
| 2888 | ); |
| 2889 | let button = ratatui::layout::Rect::new(70, 10, 3, 3); |
| 2890 | app.viewport.jump_to_latest_button_area = Some(button); |
| 2891 | |
| 2892 | super::register_clickable_chrome_for_hover(&app); |
| 2893 | |
| 2894 | let registered = crate::tui::hover_layer::registered_targets(); |
| 2895 | assert!( |
| 2896 | registered.iter().any(|hit| hit.area == button), |
| 2897 | "the jump-to-latest button handles a click in mouse_ui and must \ |
| 2898 | light up under the pointer; registered: {registered:?}" |
| 2899 | ); |
| 2900 | } |
| 2901 | |
| 2902 | /// The pinned prompt header answers a click in `mouse_ui`; it must light |
| 2903 | /// up under the pointer like every other clickable chrome. |
| 2904 | #[test] |
| 2905 | fn pinned_prompt_header_registers_a_hover_target() { |
| 2906 | let _guard = crate::tui::hover_layer::HOVER_TEST_LOCK.lock().unwrap(); |
| 2907 | crate::tui::hover_layer::begin_frame(); |
| 2908 | let mut app = crate::tui::test_support::test_app_with_options( |
| 2909 | crate::tui::test_support::test_tui_options("."), |
| 2910 | ); |
| 2911 | let header = ratatui::layout::Rect::new(4, 3, 40, 1); |
| 2912 | app.viewport.pinned_prompt_area = Some(header); |
| 2913 | |
| 2914 | super::register_clickable_chrome_for_hover(&app); |
| 2915 | |
| 2916 | let registered = crate::tui::hover_layer::registered_targets(); |
| 2917 | assert!( |
| 2918 | registered.iter().any(|hit| hit.area == header), |
| 2919 | "the pinned prompt header handles a click in mouse_ui and must \ |
| 2920 | light up under the pointer; registered: {registered:?}" |
| 2921 | ); |
| 2922 | } |
| 2923 | |
| 2924 | /// The composer's `[↵]` answered clicks and showed nothing under the |
| 2925 | /// pointer — the last of the clickable-but-dark controls. It lights up |
| 2926 | /// only when a click there would actually send. |
| 2927 | #[test] |
| 2928 | fn composer_send_target_lights_up_only_when_it_would_send() { |
| 2929 | let _guard = crate::tui::hover_layer::HOVER_TEST_LOCK.lock().unwrap(); |
| 2930 | let mut app = crate::tui::test_support::test_app_with_options( |
| 2931 | crate::tui::test_support::test_tui_options("."), |
| 2932 | ); |
| 2933 | app.launch.visible = false; |
| 2934 | app.composer_border = true; |
| 2935 | let area = ratatui::layout::Rect::new(0, 20, 80, 4); |
| 2936 | app.viewport.last_composer_area = Some(area); |
| 2937 | app.viewport.last_composer_content = Some(ratatui::layout::Rect::new(1, 21, 73, 2)); |
| 2938 | let submit = codewhale_ratatui::native_composer_geometry(area, true, false) |
| 2939 | .submit |
| 2940 | .expect("enclosed composer submit"); |
| 2941 | |
| 2942 | // Empty draft: the click path refuses, so the pointer must not promise. |
| 2943 | app.input.clear(); |
| 2944 | app.cursor_position = 0; |
| 2945 | crate::tui::hover_layer::begin_frame(); |
| 2946 | super::register_clickable_chrome_for_hover(&app); |
| 2947 | assert!( |
| 2948 | !crate::tui::hover_layer::registered_targets() |
| 2949 | .iter() |
| 2950 | .any(|hit| hit.area == submit), |
| 2951 | "an inert send target must not advertise itself" |
| 2952 | ); |
| 2953 | |
| 2954 | app.input = "ship it".to_string(); |
| 2955 | app.cursor_position = app.input.chars().count(); |
| 2956 | crate::tui::hover_layer::begin_frame(); |
| 2957 | super::register_clickable_chrome_for_hover(&app); |
| 2958 | assert!( |
| 2959 | crate::tui::hover_layer::registered_targets() |
| 2960 | .iter() |
| 2961 | .any(|hit| hit.area == submit), |
| 2962 | "a live send target must light up under the pointer" |
| 2963 | ); |
| 2964 | } |
| 2965 | |
| 2966 | #[test] |
| 2967 | fn infoline_route_segment_registers_interaction_target() { |
| 2968 | let mut app = crate::tui::test_support::test_app_with_options( |
| 2969 | crate::tui::test_support::test_tui_options("."), |
| 2970 | ); |
| 2971 | app.onboarding_needs_api_key = false; |
| 2972 | let mut terminal = |
| 2973 | Terminal::new(TestBackend::new(160, 1)).expect("info-line test terminal should build"); |
| 2974 | |
| 2975 | terminal |
| 2976 | .draw(|frame| { |
| 2977 | let area = frame.area(); |
| 2978 | let hitboxes = render_info_row(frame, &mut app, area, false); |
| 2979 | register_info_interaction_targets(&mut app, hitboxes); |
| 2980 | }) |
| 2981 | .expect("info line should render"); |
| 2982 | |
| 2983 | let segment = app |
| 2984 | .viewport |
| 2985 | .last_infoline_hitboxes |
| 2986 | .iter() |
| 2987 | .find(|hitbox| hitbox.id == crate::tui::infoline::InfoSegmentId::Model) |
| 2988 | .expect("a wide info line should paint its model segment"); |
| 2989 | let target_for = |id| { |
| 2990 | app.viewport |
| 2991 | .interaction_targets |
| 2992 | .iter() |
| 2993 | .find(|target| target.id == id) |
| 2994 | .cloned() |
| 2995 | .unwrap_or_else(|| panic!("painted route segment should register {id:?}")) |
| 2996 | }; |
| 2997 | // The segment reads `provider · model · effort`. Pointing at the |
| 2998 | // provider is a different request from pointing at the model, so the |
| 2999 | // one target became two: the whole span used to open `/provider` no |
| 3000 | // matter which name was under the pointer. |
| 3001 | let provider = target_for(crate::tui::tideline::InteractionTargetId::HEADER_ROUTE); |
| 3002 | let model = target_for(crate::tui::tideline::InteractionTargetId::HEADER_MODEL); |
| 3003 | |
| 3004 | assert_eq!(provider.area.x, segment.area.x); |
| 3005 | assert!( |
| 3006 | provider.area.right() < model.area.x, |
| 3007 | "provider {:?} and model {:?} must not overlap", |
| 3008 | provider.area, |
| 3009 | model.area |
| 3010 | ); |
| 3011 | assert_eq!(model.area.right(), segment.area.right()); |
| 3012 | assert_eq!( |
| 3013 | provider.keyboard_action, |
| 3014 | Some(crate::tui::tideline::InteractionAction::OpenProviderPicker) |
| 3015 | ); |
| 3016 | assert_eq!( |
| 3017 | model.keyboard_action, |
| 3018 | Some(crate::tui::tideline::InteractionAction::OpenModelPicker) |
| 3019 | ); |
| 3020 | for target in [&provider, &model] { |
| 3021 | assert_eq!(target.mouse_action, target.keyboard_action); |
| 3022 | assert_eq!( |
| 3023 | target.inspect_detail, |
| 3024 | crate::tui::tideline::InspectDetail::Route |
| 3025 | ); |
| 3026 | } |
| 3027 | } |
| 3028 | |
| 3029 | /// U3: a keyless first run keeps a default model id, but nothing can |
| 3030 | /// answer it. The route chip says "not connected" instead of naming that |
| 3031 | /// route, and it is not a route control until a model is connected. |
| 3032 | #[test] |
| 3033 | fn keyless_launch_route_chip_says_not_connected() { |
| 3034 | let mut app = crate::tui::test_support::test_app_with_options( |
| 3035 | crate::tui::test_support::test_tui_options("."), |
| 3036 | ); |
| 3037 | app.ui_locale = codewhale_localization::Locale::En; |
| 3038 | app.onboarding_needs_api_key = true; |
| 3039 | let (_, model) = app.effective_route_identity_display(); |
| 3040 | assert!(!model.is_empty(), "the fixture carries a default model id"); |
| 3041 | let mut terminal = |
| 3042 | Terminal::new(TestBackend::new(160, 1)).expect("info-line test terminal should build"); |
| 3043 | let mut hitboxes = super::InfoLineInteractionHitboxes::default(); |
| 3044 | terminal |
| 3045 | .draw(|frame| { |
| 3046 | let area = frame.area(); |
| 3047 | hitboxes = render_info_row(frame, &mut app, area, false); |
| 3048 | }) |
| 3049 | .expect("info line should render"); |
| 3050 | let row: String = terminal |
| 3051 | .backend() |
| 3052 | .buffer() |
| 3053 | .content() |
| 3054 | .iter() |
| 3055 | .map(|cell| cell.symbol().to_string()) |
| 3056 | .collect(); |
| 3057 | assert!(row.contains("not connected"), "{row:?}"); |
| 3058 | assert!(!row.contains(&model), "a dead route is not named: {row:?}"); |
| 3059 | assert!(hitboxes.route.is_none(), "no provider control: {row:?}"); |
| 3060 | |
| 3061 | // Once a key lands the same row names the route again. |
| 3062 | app.onboarding_needs_api_key = false; |
| 3063 | let segments = super::info_segments(&app, 160); |
| 3064 | assert!( |
| 3065 | segments.iter().any( |
| 3066 | |segment| segment.id == crate::tui::infoline::InfoSegmentId::Model |
| 3067 | && segment.value.contains(&model) |
| 3068 | ), |
| 3069 | "{segments:?}" |
| 3070 | ); |
| 3071 | } |
| 3072 | |
| 3073 | /// "Where did the github info go?" — the workspace segment names the |
| 3074 | /// repository when `origin` resolves to a forge slug, and only falls back |
| 3075 | /// to the folder basename when it does not. The basename rides along as |
| 3076 | /// the segment's shorter form so a long slug never costs the row a whole |
| 3077 | /// fact. |
| 3078 | #[test] |
| 3079 | fn truncates_at_ascii_word_boundary() { |
| 3080 | assert_eq!(short_title_truncate("hello world foo", 10), "hello…"); |
| 3081 | } |
| 3082 | |
| 3083 | #[test] |
| 3084 | fn truncates_non_ascii_titles_by_char_count_not_bytes() { |
| 3085 | // `str::rfind` returns a byte offset; using it as a char count used to |
| 3086 | // cut past the limit and mid-word on multi-byte input. |
| 3087 | assert_eq!( |
| 3088 | short_title_truncate("你好 world and more", 10), |
| 3089 | "你好 world…" |
| 3090 | ); |
| 3091 | } |
| 3092 | |
| 3093 | #[test] |
| 3094 | fn truncates_at_punctuation_boundary() { |
| 3095 | assert_eq!(short_title_truncate("hello, world", 8), "hello…"); |
| 3096 | } |
| 3097 | |
| 3098 | #[test] |
| 3099 | fn truncates_mid_word_when_no_boundary_exists() { |
| 3100 | assert_eq!(short_title_truncate("abcdefghij", 5), "abcd…"); |
| 3101 | } |
| 3102 | |
| 3103 | #[test] |
| 3104 | fn leaves_short_titles_untouched() { |
| 3105 | assert_eq!(short_title_truncate("short", 10), "short"); |
| 3106 | } |
| 3107 | |
| 3108 | // ── #5950: the bottom chrome is the user's to compose ───────────── |
| 3109 | |
| 3110 | use crate::tui::app::App; |
| 3111 | use crate::tui::infoline::{InfoLine, InfoSegmentId}; |
| 3112 | use codewhale_runtime::config::StatusItem; |
| 3113 | |
| 3114 | /// A session whose context is `pct` full, by pinning the route's window |
| 3115 | /// to a multiple of what this conversation actually estimates. Nothing |
| 3116 | /// here fakes the reading itself — it goes through |
| 3117 | /// `context_usage_snapshot` like the live shell does. |
| 3118 | fn app_with_context_percent(pct: u8) -> App { |
| 3119 | use codewhale_models::{ContentBlock, Message}; |
| 3120 | let mut app = crate::tui::test_support::test_app_with_options( |
| 3121 | crate::tui::test_support::test_tui_options("."), |
| 3122 | ); |
| 3123 | // A keyless test config would paint "not connected" (U3); these |
| 3124 | // readings are about a connected route. |
| 3125 | app.onboarding_needs_api_key = false; |
| 3126 | app.api_messages = std::sync::Arc::new(vec![Message { |
| 3127 | role: codewhale_models::Role::User, |
| 3128 | content: vec![ContentBlock::Text { |
| 3129 | text: "context ".repeat(400), |
| 3130 | cache_control: None, |
| 3131 | }], |
| 3132 | }]); |
| 3133 | let (used, _, _) = |
| 3134 | super::context_usage_snapshot(&app).expect("a conversation has a context reading"); |
| 3135 | let window = (used as f64 * 100.0 / f64::from(pct)).round().max(1.0); |
| 3136 | app.active_route_limits = Some(codewhale_config::route::RouteLimits { |
| 3137 | context_tokens: Some(window as u64), |
| 3138 | ..Default::default() |
| 3139 | }); |
| 3140 | assert_eq!( |
| 3141 | super::info_context_percent(&app), |
| 3142 | pct, |
| 3143 | "fixture should land exactly on {pct}%" |
| 3144 | ); |
| 3145 | app |
| 3146 | } |
| 3147 | |
| 3148 | /// The metrics line as the user reads it, at `width`. |
| 3149 | fn metrics_row(app: &App, width: u16) -> String { |
| 3150 | let segments = super::info_segments(app, width); |
| 3151 | let hint = crate::tui::shell_key_routing::info_help_hint(app.ui_locale); |
| 3152 | let backend = TestBackend::new(width, 1); |
| 3153 | let mut terminal = Terminal::new(backend).expect("metrics-line terminal"); |
| 3154 | terminal |
| 3155 | .draw(|frame| { |
| 3156 | use ratatui::widgets::Widget as _; |
| 3157 | let area = frame.area(); |
| 3158 | InfoLine::new(&app.ui_theme, &hint, &segments).render(area, frame.buffer_mut()); |
| 3159 | }) |
| 3160 | .expect("draw"); |
| 3161 | terminal |
| 3162 | .backend() |
| 3163 | .buffer() |
| 3164 | .content() |
| 3165 | .iter() |
| 3166 | .map(|cell| cell.symbol().to_string()) |
| 3167 | .collect::<String>() |
| 3168 | } |
| 3169 | |
| 3170 | #[test] |
| 3171 | fn footer_keeps_reasoning_label_for_every_effort_tier() { |
| 3172 | use codewhale_engine::reasoning_preference::ReasoningEffort; |
| 3173 | |
| 3174 | let mut app = app_with_context_percent(1); |
| 3175 | app.api_provider = codewhale_config::ProviderKind::Openai; |
| 3176 | app.active_route_base_url = "https://api.openai.com/v1".to_string(); |
| 3177 | app.model = "gpt-5.6".to_string(); |
| 3178 | app.auto_model = false; |
| 3179 | app.ui_locale = codewhale_localization::Locale::En; |
| 3180 | |
| 3181 | let mut missing = Vec::new(); |
| 3182 | for effort in [ |
| 3183 | ReasoningEffort::Off, |
| 3184 | ReasoningEffort::Minimal, |
| 3185 | ReasoningEffort::Low, |
| 3186 | ReasoningEffort::Medium, |
| 3187 | ReasoningEffort::High, |
| 3188 | ReasoningEffort::XHigh, |
| 3189 | ReasoningEffort::Ultra, |
| 3190 | ReasoningEffort::Auto, |
| 3191 | ReasoningEffort::Max, |
| 3192 | ] { |
| 3193 | app.reasoning_effort = effort; |
| 3194 | let label = app.reasoning_effort_display_label(); |
| 3195 | assert!(!label.is_empty(), "{effort:?} must have a label"); |
| 3196 | let row = metrics_row(&app, 80); |
| 3197 | if !row.contains(&format!("thinking: {label}")) { |
| 3198 | missing.push(format!("{effort:?}: {row:?}")); |
| 3199 | } |
| 3200 | } |
| 3201 | assert!(missing.is_empty(), "missing footer labels: {missing:#?}"); |
| 3202 | } |
| 3203 | |
| 3204 | /// The reading used to go silent below 50% fullness, which is most of a |
| 3205 | /// session (#5950). It is a reading, not an alarm: it states 10% as |
| 3206 | /// readily as 60%, and only the ink changes at the thresholds. |
| 3207 | #[test] |
| 3208 | fn context_reading_paints_at_every_fullness() { |
| 3209 | for pct in [10u8, 60] { |
| 3210 | let app = app_with_context_percent(pct); |
| 3211 | let segment = super::info_segments(&app, 160) |
| 3212 | .into_iter() |
| 3213 | .find(|segment| segment.id == InfoSegmentId::Context) |
| 3214 | .unwrap_or_else(|| panic!("{pct}%: the context reading must be on the row")); |
| 3215 | assert_eq!(segment.value, format!("{pct}%")); |
| 3216 | assert_eq!( |
| 3217 | segment.ink, |
| 3218 | codewhale_palette::ChromeInk::Info, |
| 3219 | "{pct}%: below the cap the reading is a status, not a failure" |
| 3220 | ); |
| 3221 | // Narrow rows keep it too: the reading is the row's floor and |
| 3222 | // sheds after everything else, including the help hint. |
| 3223 | for width in [40u16, 80, 160] { |
| 3224 | let row = metrics_row(&app, width); |
| 3225 | assert!( |
| 3226 | row.contains(&format!("context {pct}%")), |
| 3227 | "{pct}% at {width} columns: {row:?}" |
| 3228 | ); |
| 3229 | } |
| 3230 | } |
| 3231 | } |
| 3232 | |
| 3233 | #[test] |
| 3234 | fn oversized_custom_route_keeps_the_context_reading_and_model_picker_on_small_screens() { |
| 3235 | let mut app = app_with_context_percent(84); |
| 3236 | app.pending_turn_route = Some(( |
| 3237 | codewhale_config::ProviderKind::Custom, |
| 3238 | "custom-model-with-a-long-tenant-specific-deployment-and-version".to_owned(), |
| 3239 | false, |
| 3240 | )); |
| 3241 | for width in [40, 45] { |
| 3242 | let row = metrics_row(&app, width); |
| 3243 | assert!( |
| 3244 | row.contains("/model") && row.contains("context 84%"), |
| 3245 | "{row}" |
| 3246 | ); |
| 3247 | } |
| 3248 | assert!( |
| 3249 | metrics_row(&app, 160) |
| 3250 | .contains("custom-model-with-a-long-tenant-specific-deployment-and-version") |
| 3251 | ); |
| 3252 | } |
| 3253 | |
| 3254 | /// The warning ink still belongs to the thresholds it always used: the |
| 3255 | /// error token from 80% up, and not one percent earlier. |
| 3256 | #[test] |
| 3257 | fn context_reading_keeps_its_warning_threshold() { |
| 3258 | for (pct, expected) in [ |
| 3259 | (10u8, codewhale_palette::ChromeInk::Info), |
| 3260 | (79, codewhale_palette::ChromeInk::Info), |
| 3261 | (80, codewhale_palette::ChromeInk::Attention), |
| 3262 | ] { |
| 3263 | let app = app_with_context_percent(pct); |
| 3264 | let segment = super::info_segments(&app, 160) |
| 3265 | .into_iter() |
| 3266 | .find(|segment| segment.id == InfoSegmentId::Context) |
| 3267 | .expect("context reading"); |
| 3268 | assert_eq!(segment.ink, expected, "{pct}%"); |
| 3269 | } |
| 3270 | } |
| 3271 | |
| 3272 | /// `/statusline` drives this row. Between 0.9.12 and #5950 the picker |
| 3273 | /// persisted a list nothing read, so every toggle in it was a lie. |
| 3274 | #[test] |
| 3275 | fn statusline_toggle_removes_its_segment_on_the_next_frame() { |
| 3276 | use crate::tui::views::{ModalView, ViewAction, ViewEvent}; |
| 3277 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; |
| 3278 | |
| 3279 | let mut app = app_with_context_percent(10); |
| 3280 | assert!( |
| 3281 | metrics_row(&app, 160).contains("context 10%"), |
| 3282 | "the reading starts on the row" |
| 3283 | ); |
| 3284 | |
| 3285 | let mut picker = crate::tui::views::status_picker::StatusPickerView::new( |
| 3286 | &app.status_items, |
| 3287 | app.api_provider, |
| 3288 | app.ui_locale, |
| 3289 | ); |
| 3290 | // Walk to the context row the way a user does, then uncheck it. |
| 3291 | let context_row = StatusItem::all() |
| 3292 | .iter() |
| 3293 | .filter(|item| item.is_available_for(app.api_provider)) |
| 3294 | .position(|item| *item == StatusItem::ContextPercent) |
| 3295 | .expect("the picker offers the context reading"); |
| 3296 | for _ in 0..context_row { |
| 3297 | picker.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); |
| 3298 | } |
| 3299 | let action = picker.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE)); |
| 3300 | let ViewAction::Emit(ViewEvent::StatusItemsUpdated { items, .. }) = action else { |
| 3301 | panic!("space should emit a live preview: {action:?}"); |
| 3302 | }; |
| 3303 | assert!(!items.contains(&StatusItem::ContextPercent)); |
| 3304 | |
| 3305 | // What the handler does with the event, and then the next frame. |
| 3306 | app.status_items = items; |
| 3307 | let row = metrics_row(&app, 160); |
| 3308 | assert!( |
| 3309 | !row.contains("context "), |
| 3310 | "the toggle must take it off: {row:?}" |
| 3311 | ); |
| 3312 | assert!( |
| 3313 | row.contains("deepseek"), |
| 3314 | "and must take nothing else with it: {row:?}" |
| 3315 | ); |
| 3316 | } |
| 3317 | |
| 3318 | /// A custom OpenAI-compatible route without an endpoint receipt cannot |
| 3319 | /// prove its effective tier. The route segment used to print |
| 3320 | /// `high→effective unavailable` — a placeholder that could never resolve |
| 3321 | /// (#5950). It now states no effort field at all, while a first-party |
| 3322 | /// route keeps its tier label. |
| 3323 | #[test] |
| 3324 | fn unprovable_effort_states_no_field_instead_of_a_placeholder() { |
| 3325 | use crate::tui::phase_strip::{RouteFieldKind, route_identity_fields}; |
| 3326 | use crate::tui::underwater::ShellTier; |
| 3327 | |
| 3328 | let mut app = app_with_context_percent(10); |
| 3329 | app.set_provider_identity(codewhale_config::ProviderKind::Custom, "my-gateway"); |
| 3330 | app.auto_model = false; |
| 3331 | app.active_route_base_url = "https://gateway.example/v1".to_string(); |
| 3332 | app.model = "vendor-model-x".to_string(); |
| 3333 | app.reasoning_effort = codewhale_engine::reasoning_preference::ReasoningEffort::High; |
| 3334 | assert_eq!( |
| 3335 | app.reasoning_effort_display_label(), |
| 3336 | "high→effective unavailable", |
| 3337 | "the full label still tells /status the truth" |
| 3338 | ); |
| 3339 | assert_eq!(app.provable_reasoning_effort_label(), None); |
| 3340 | let fields = route_identity_fields(&app, ShellTier::Wide, 200).expect("route fields"); |
| 3341 | assert!( |
| 3342 | fields |
| 3343 | .iter() |
| 3344 | .all(|field| field.kind != RouteFieldKind::Effort), |
| 3345 | "no effort field on an unprovable route: {fields:?}" |
| 3346 | ); |
| 3347 | let row = metrics_row(&app, 200); |
| 3348 | assert!(row.contains("vendor-model-x"), "{row:?}"); |
| 3349 | // The unresolvable effort placeholder stays out; the localized |
| 3350 | // missing-cost explanation ("rate unavailable") is a separate, |
| 3351 | // legitimate reading. |
| 3352 | assert!(!row.contains("high→effective unavailable"), "{row:?}"); |
| 3353 | assert!(!row.contains("high"), "{row:?}"); |
| 3354 | |
| 3355 | // First-party routes are unchanged: the tier label stays. |
| 3356 | let app = app_with_context_percent(10); |
| 3357 | let label = app |
| 3358 | .provable_reasoning_effort_label() |
| 3359 | .expect("a first-party route proves its tier"); |
| 3360 | assert_eq!(label, app.reasoning_effort_display_label()); |
| 3361 | let fields = route_identity_fields(&app, ShellTier::Wide, 200).expect("route fields"); |
| 3362 | assert!( |
| 3363 | fields |
| 3364 | .iter() |
| 3365 | .any(|field| field.kind == RouteFieldKind::Effort |
| 3366 | && field.text == format!("thinking: {label}")), |
| 3367 | "{fields:?}" |
| 3368 | ); |
| 3369 | } |
| 3370 | |
| 3371 | /// DeepSeek's clock-tiered routes show which tier the next turn buys, |
| 3372 | /// beside the cost; flat routes and other vendors show nothing. |
| 3373 | #[test] |
| 3374 | fn deepseek_tiered_routes_paint_the_billing_tier_beside_the_cost() { |
| 3375 | use chrono::TimeZone as _; |
| 3376 | use codewhale_config::ProviderKind; |
| 3377 | let mut app = app_with_context_percent(10); |
| 3378 | app.auto_model = false; |
| 3379 | app.api_provider = ProviderKind::Deepseek; |
| 3380 | app.model = "deepseek-v4-flash".to_string(); |
| 3381 | // Wednesday 2026-09-16: 02:00Z is inside the 01:00-04:00 peak |
| 3382 | // window, 12:00Z outside every window. |
| 3383 | let peak = chrono::Utc.with_ymd_and_hms(2026, 9, 16, 2, 0, 0).unwrap(); |
| 3384 | let off = chrono::Utc.with_ymd_and_hms(2026, 9, 16, 12, 0, 0).unwrap(); |
| 3385 | assert_eq!( |
| 3386 | super::billing_tier_label(&app, peak).as_deref(), |
| 3387 | Some("peak") |
| 3388 | ); |
| 3389 | assert_eq!( |
| 3390 | super::billing_tier_label(&app, off).as_deref(), |
| 3391 | Some("off-peak") |
| 3392 | ); |
| 3393 | let ids: Vec<InfoSegmentId> = super::info_segments(&app, 200) |
| 3394 | .iter() |
| 3395 | .map(|segment| segment.id) |
| 3396 | .collect(); |
| 3397 | assert!(ids.contains(&InfoSegmentId::BillingTier), "{ids:?}"); |
| 3398 | let row = metrics_row(&app, 200); |
| 3399 | assert!(row.contains("peak"), "the tier reads in the row: {row:?}"); |
| 3400 | |
| 3401 | // A flat-priced DeepSeek model has no tier to show. |
| 3402 | app.model = "deepseek-chat".to_string(); |
| 3403 | assert_eq!(super::billing_tier_label(&app, peak), None); |
| 3404 | let ids: Vec<InfoSegmentId> = super::info_segments(&app, 200) |
| 3405 | .iter() |
| 3406 | .map(|segment| segment.id) |
| 3407 | .collect(); |
| 3408 | assert!(!ids.contains(&InfoSegmentId::BillingTier), "{ids:?}"); |
| 3409 | |
| 3410 | // Another vendor serving a DeepSeek id is priced on its own terms. |
| 3411 | app.model = "deepseek-v4-flash".to_string(); |
| 3412 | app.api_provider = ProviderKind::Openai; |
| 3413 | assert_eq!(super::billing_tier_label(&app, peak), None); |
| 3414 | |
| 3415 | // Auto routing has not pinned a model, so there is nothing to claim. |
| 3416 | app.api_provider = ProviderKind::Deepseek; |
| 3417 | app.auto_model = true; |
| 3418 | assert_eq!(super::billing_tier_label(&app, peak), None); |
| 3419 | } |
| 3420 | |
| 3421 | /// A provider switch must not fabricate a price: the glance carries |
| 3422 | /// confirmed dollars, so an unpriced session renders no cost at all. |
| 3423 | #[test] |
| 3424 | fn cost_shows_confirmed_dollars_only_across_route_changes() { |
| 3425 | use codewhale_engine::route_billing::BillingPresentation; |
| 3426 | let mut app = app_with_context_percent(10); |
| 3427 | app.session.cost_coverage_unknown_legacy = true; |
| 3428 | |
| 3429 | app.billing_presentation = BillingPresentation::Metered; |
| 3430 | assert!(matches!( |
| 3431 | app.cumulative_usage_chip(), |
| 3432 | codewhale_engine::route_billing::UsageChip::Unknown(_) |
| 3433 | )); |
| 3434 | assert_eq!( |
| 3435 | super::session_cost_label(&app), |
| 3436 | "", |
| 3437 | "an unpriced session shows no money" |
| 3438 | ); |
| 3439 | let row = metrics_row(&app, 200); |
| 3440 | assert!(!row.contains('$'), "no invented price: {row:?}"); |
| 3441 | |
| 3442 | app.billing_presentation = BillingPresentation::Unknown; |
| 3443 | assert!(matches!( |
| 3444 | app.cumulative_usage_chip(), |
| 3445 | codewhale_engine::route_billing::UsageChip::Unknown(_) |
| 3446 | )); |
| 3447 | assert_eq!(super::session_cost_label(&app), ""); |
| 3448 | let ids: Vec<InfoSegmentId> = super::info_segments(&app, 200) |
| 3449 | .iter() |
| 3450 | .map(|segment| segment.id) |
| 3451 | .collect(); |
| 3452 | assert!(!ids.contains(&InfoSegmentId::Cost), "{ids:?}"); |
| 3453 | let row = metrics_row(&app, 200); |
| 3454 | assert!( |
| 3455 | !row.contains('$'), |
| 3456 | "a route change invents nothing: {row:?}" |
| 3457 | ); |
| 3458 | assert!( |
| 3459 | row.contains("context 10%"), |
| 3460 | "and nothing else moves: {row:?}" |
| 3461 | ); |
| 3462 | |
| 3463 | // A confirmed price on an otherwise unclassified route still prints. |
| 3464 | app.session.cost_coverage_unknown_legacy = false; |
| 3465 | app.session.cost_priced_turns = 1; |
| 3466 | app.session.session_cost = 0.42; |
| 3467 | assert!( |
| 3468 | matches!( |
| 3469 | app.cumulative_usage_chip(), |
| 3470 | codewhale_engine::route_billing::UsageChip::Money(_) |
| 3471 | ), |
| 3472 | "{:?}", |
| 3473 | app.cumulative_usage_chip() |
| 3474 | ); |
| 3475 | assert!(!super::session_cost_label(&app).is_empty()); |
| 3476 | } |
| 3477 | |
| 3478 | #[test] |
| 3479 | fn metrics_line_uses_measured_request_average_during_tool_waits_and_live_text() { |
| 3480 | use crate::tui::session_metrics::{full_text, snapshot_from_app}; |
| 3481 | |
| 3482 | let mut app = app_with_context_percent(60); |
| 3483 | app.ui_locale = codewhale_localization::Locale::En; |
| 3484 | app.status_items = vec![StatusItem::SessionMetrics, StatusItem::Tokens]; |
| 3485 | app.is_loading = true; |
| 3486 | app.turn_started_at = Some(std::time::Instant::now() - std::time::Duration::from_secs(120)); |
| 3487 | app.streaming_output_token_estimate = 60_000; |
| 3488 | assert!( |
| 3489 | super::info_segments(&app, 200) |
| 3490 | .iter() |
| 3491 | .all(|segment| segment.id != InfoSegmentId::Rate), |
| 3492 | "live text estimates do not invent measured request throughput" |
| 3493 | ); |
| 3494 | app.session_metrics |
| 3495 | .record_model_call(120, 4_800, Some(1_000), Some(5_000)); |
| 3496 | let rate = |app: &App| { |
| 3497 | super::info_segments(app, 200) |
| 3498 | .into_iter() |
| 3499 | .find(|segment| segment.id == InfoSegmentId::Rate) |
| 3500 | .map(|segment| segment.value) |
| 3501 | }; |
| 3502 | assert_eq!(rate(&app).as_deref(), Some("24 avg tok/s")); |
| 3503 | let detailed = full_text(snapshot_from_app(&app), app.ui_locale, false); |
| 3504 | assert!(detailed.contains("24 avg tok/s"), "{detailed}"); |
| 3505 | |
| 3506 | // Finishing a long turn or replacing the displayed token receipt must |
| 3507 | // not switch the rate to the turn timer (which includes tool waits). |
| 3508 | app.is_loading = false; |
| 3509 | app.session.last_completion_tokens = Some(9_000); |
| 3510 | assert_eq!(rate(&app).as_deref(), Some("24 avg tok/s")); |
| 3511 | app.status_items = vec![StatusItem::Tokens]; |
| 3512 | assert_eq!(rate(&app), None, "the existing status toggle still owns it"); |
| 3513 | } |
| 3514 | |
| 3515 | #[test] |
| 3516 | fn default_compact_footer_keeps_measured_performance_at_working_widths() { |
| 3517 | use ratatui::{Terminal, backend::TestBackend}; |
| 3518 | let mut app = app_with_context_percent(60); |
| 3519 | app.ui_locale = codewhale_localization::Locale::En; |
| 3520 | app.status_items = StatusItem::default_footer(); |
| 3521 | app.metrics_line = codewhale_runtime::config::ChromeRowPreset::Compact; |
| 3522 | app.session_metrics |
| 3523 | .record_model_call(120, 4_800, Some(1_000), Some(5_000)); |
| 3524 | for width in [80, 100, 140] { |
| 3525 | let mut terminal = Terminal::new(TestBackend::new(width, 1)).unwrap(); |
| 3526 | terminal |
| 3527 | .draw(|frame| { |
| 3528 | super::render_info_row(frame, &mut app, frame.area(), false); |
| 3529 | }) |
| 3530 | .unwrap(); |
| 3531 | let row: String = terminal |
| 3532 | .backend() |
| 3533 | .buffer() |
| 3534 | .content() |
| 3535 | .iter() |
| 3536 | .map(|cell| cell.symbol()) |
| 3537 | .collect(); |
| 3538 | assert!(row.contains("ttft 1.0s"), "{width}: {row}"); |
| 3539 | assert!(row.contains("24 avg tok/s"), "{width}: {row}"); |
| 3540 | assert!(!row.contains("/help"), "{width}: {row}"); |
| 3541 | } |
| 3542 | } |
| 3543 | |
| 3544 | #[test] |
| 3545 | fn performance_readings_can_be_selected_independently() { |
| 3546 | let mut app = app_with_context_percent(60); |
| 3547 | app.session_metrics |
| 3548 | .record_model_call(120, 4_800, Some(1_000), Some(5_000)); |
| 3549 | for (item, expected) in [ |
| 3550 | (StatusItem::Ttft, InfoSegmentId::Ttft), |
| 3551 | (StatusItem::OutputRate, InfoSegmentId::Rate), |
| 3552 | ] { |
| 3553 | app.status_items = vec![item]; |
| 3554 | let ids: Vec<_> = super::info_segments(&app, 80) |
| 3555 | .into_iter() |
| 3556 | .map(|s| s.id) |
| 3557 | .collect(); |
| 3558 | assert_eq!(ids, vec![expected]); |
| 3559 | } |
| 3560 | } |
| 3561 | |
| 3562 | /// Every selected status item owns its segment; without live notices an |
| 3563 | /// empty list leaves the metrics line empty. |
| 3564 | #[test] |
| 3565 | fn every_metrics_segment_answers_to_a_status_item() { |
| 3566 | let mut app = app_with_context_percent(60); |
| 3567 | app.session.last_prompt_tokens = Some(1_000); |
| 3568 | app.session_metrics |
| 3569 | .record_model_call(1_200, 30_000, Some(400), Some(30_400)); |
| 3570 | app.streaming_output_token_estimate = 1_200; |
| 3571 | app.is_loading = true; |
| 3572 | app.turn_started_at = Some(std::time::Instant::now() - std::time::Duration::from_secs(30)); |
| 3573 | *app.balance_cell.lock().expect("balance cell") = |
| 3574 | Some(codewhale_engine::pricing::BalanceInfo { |
| 3575 | currency: "USD".to_string(), |
| 3576 | total_balance: "4.32".to_string(), |
| 3577 | topped_up_balance: String::new(), |
| 3578 | granted_balance: String::new(), |
| 3579 | }); |
| 3580 | app.status_items = StatusItem::all().to_vec(); |
| 3581 | app.workspace_context = Some("main | clean".to_string()); |
| 3582 | |
| 3583 | let ids: Vec<InfoSegmentId> = super::info_segments(&app, 200) |
| 3584 | .iter() |
| 3585 | .map(|segment| segment.id) |
| 3586 | .collect(); |
| 3587 | for expected in [ |
| 3588 | InfoSegmentId::Model, |
| 3589 | InfoSegmentId::Context, |
| 3590 | InfoSegmentId::Balance, |
| 3591 | InfoSegmentId::Ttft, |
| 3592 | InfoSegmentId::Rate, |
| 3593 | InfoSegmentId::OutputTokens, |
| 3594 | InfoSegmentId::Workspace, |
| 3595 | InfoSegmentId::GitBranch, |
| 3596 | ] { |
| 3597 | assert!(ids.contains(&expected), "{expected:?} missing from {ids:?}"); |
| 3598 | } |
| 3599 | |
| 3600 | app.status_items = Vec::new(); |
| 3601 | assert!( |
| 3602 | super::info_segments(&app, 200).is_empty(), |
| 3603 | "an empty status list leaves the metrics line empty" |
| 3604 | ); |
| 3605 | } |
| 3606 | |
| 3607 | #[test] |
| 3608 | fn empty_session_keeps_opted_in_workspace_identity_visible() { |
| 3609 | let _guard = crate::tui::hover_layer::HOVER_TEST_LOCK.lock().unwrap(); |
| 3610 | let mut app = app_with_context_percent(0); |
| 3611 | app.workspace = std::path::PathBuf::from("/fixture/checkout"); |
| 3612 | app.workspace_context = Some("feature-6112 | clean".to_string()); |
| 3613 | app.status_items = vec![StatusItem::Workspace, StatusItem::GitBranch]; |
| 3614 | app.update_available = Some("↑ v9.9.9".to_string()); |
| 3615 | app.metrics_line = codewhale_runtime::config::ChromeRowPreset::Compact; |
| 3616 | let backend = ratatui::backend::TestBackend::new(100, 1); |
| 3617 | let mut terminal = ratatui::Terminal::new(backend).unwrap(); |
| 3618 | terminal |
| 3619 | .draw(|frame| { |
| 3620 | let area = frame.area(); |
| 3621 | let hitboxes = super::render_info_row(frame, &mut app, area, true); |
| 3622 | super::register_info_interaction_targets(&mut app, hitboxes); |
| 3623 | }) |
| 3624 | .unwrap(); |
| 3625 | let rendered: String = terminal |
| 3626 | .backend() |
| 3627 | .buffer() |
| 3628 | .content() |
| 3629 | .iter() |
| 3630 | .map(|cell| cell.symbol()) |
| 3631 | .collect(); |
| 3632 | assert!(rendered.contains("checkout"), "{rendered}"); |
| 3633 | assert!(rendered.contains("feature-6112"), "{rendered}"); |
| 3634 | assert!(rendered.contains("v9.9.9"), "{rendered}"); |
| 3635 | let target = *app |
| 3636 | .viewport |
| 3637 | .interaction_targets |
| 3638 | .iter() |
| 3639 | .find(|target| target.id == crate::tui::tideline::InteractionTargetId::HEADER_UPDATE) |
| 3640 | .expect("visible update notice is actionable"); |
| 3641 | assert_eq!( |
| 3642 | target.mouse_action, |
| 3643 | Some(crate::tui::tideline::InteractionAction::OpenUpdate) |
| 3644 | ); |
| 3645 | app.last_mouse_pos = Some((target.area.x, target.area.y)); |
| 3646 | terminal |
| 3647 | .draw(|frame| { |
| 3648 | let area = frame.area(); |
| 3649 | super::render_info_row(frame, &mut app, area, true); |
| 3650 | }) |
| 3651 | .unwrap(); |
| 3652 | assert!( |
| 3653 | terminal.backend().buffer()[(target.area.x, target.area.y)] |
| 3654 | .modifier |
| 3655 | .contains(ratatui::style::Modifier::UNDERLINED) |
| 3656 | ); |
| 3657 | for launch_visible in [true, false] { |
| 3658 | app.launch.visible = launch_visible; |
| 3659 | let events = crate::tui::mouse_ui::handle_mouse_event( |
| 3660 | &mut app, |
| 3661 | crossterm::event::MouseEvent { |
| 3662 | kind: crossterm::event::MouseEventKind::Down( |
| 3663 | crossterm::event::MouseButton::Left, |
| 3664 | ), |
| 3665 | column: target.area.x, |
| 3666 | row: target.area.y, |
| 3667 | modifiers: crossterm::event::KeyModifiers::NONE, |
| 3668 | }, |
| 3669 | Instant::now(), |
| 3670 | ); |
| 3671 | assert!(matches!( |
| 3672 | events.as_slice(), |
| 3673 | [crate::tui::views::ViewEvent::CommandPaletteSelected { |
| 3674 | action: crate::tui::views::CommandPaletteAction::ExecuteCommand { command }, |
| 3675 | }] if command == "/update" |
| 3676 | )); |
| 3677 | } |
| 3678 | let mut notice = super::super::UpdateNotice { |
| 3679 | current: "0.10.1".to_string(), |
| 3680 | latest: "0.10.2".to_string(), |
| 3681 | staged: Some(false), |
| 3682 | }; |
| 3683 | assert_eq!(notice.chip_label(), "↑ v0.10.2"); |
| 3684 | notice.staged = Some(true); |
| 3685 | assert_eq!(notice.chip_label(), "↑ v0.10.2 ready"); |
| 3686 | } |
| 3687 | |
| 3688 | /// #6112: the opt-in workspace and branch chips read cached state only — |
| 3689 | /// the workspace path and the TTL-refreshed `workspace_context` string — |
| 3690 | /// so neither costs IO per frame. Outside a repository the branch chip |
| 3691 | /// degrades to absent rather than pinning a placeholder dash. |
| 3692 | #[test] |
| 3693 | fn workspace_and_git_branch_chips_follow_cached_workspace_context() { |
| 3694 | let mut app = app_with_context_percent(60); |
| 3695 | app.status_items = vec![StatusItem::Workspace, StatusItem::GitBranch]; |
| 3696 | |
| 3697 | let segments = super::info_segments(&app, 200); |
| 3698 | let workspace = segments |
| 3699 | .iter() |
| 3700 | .find(|segment| segment.id == InfoSegmentId::Workspace) |
| 3701 | .expect("workspace chip renders from the workspace path alone"); |
| 3702 | assert_eq!( |
| 3703 | workspace.value, |
| 3704 | crate::tui::workspace_context::workspace_basename(&app.workspace) |
| 3705 | ); |
| 3706 | assert!( |
| 3707 | segments |
| 3708 | .iter() |
| 3709 | .all(|segment| segment.id != InfoSegmentId::GitBranch), |
| 3710 | "outside a repository the branch chip is absent" |
| 3711 | ); |
| 3712 | |
| 3713 | // A detached HEAD reads in its recorded short-SHA form. |
| 3714 | app.workspace_context = Some("detached:abc1234 | clean".to_string()); |
| 3715 | let branch = super::info_segments(&app, 200) |
| 3716 | .into_iter() |
| 3717 | .find(|segment| segment.id == InfoSegmentId::GitBranch) |
| 3718 | .expect("branch chip renders from cached context"); |
| 3719 | assert_eq!(branch.value, "detached:abc1234"); |
| 3720 | app.workspace_is_linked_worktree = true; |
| 3721 | let linked = super::info_segments(&app, 200) |
| 3722 | .into_iter() |
| 3723 | .find(|segment| segment.id == InfoSegmentId::GitBranch) |
| 3724 | .unwrap(); |
| 3725 | assert_eq!(linked.value, "detached:abc1234 (wt)"); |
| 3726 | assert!(!StatusItem::default_footer().contains(&StatusItem::Workspace)); |
| 3727 | assert!(!StatusItem::default_footer().contains(&StatusItem::GitBranch)); |
| 3728 | |
| 3729 | // Off means off. |
| 3730 | app.status_items = Vec::new(); |
| 3731 | assert!(super::info_segments(&app, 200).is_empty()); |
| 3732 | } |
| 3733 | } |
| 3734 | |
| 3735 | #[cfg(test)] |
| 3736 | mod one_owner_tests; |
| 3737 | |
| 3738 | #[cfg(test)] |
| 3739 | mod pet_main_tests { |
| 3740 | use super::*; |
| 3741 | use crate::tui::{ |
| 3742 | approval::{ApprovalRequest, ApprovalView}, |
| 3743 | pet_watch, |
| 3744 | shell_key_routing::Focus, |
| 3745 | }; |
| 3746 | use ratatui::{Terminal, backend::TestBackend}; |
| 3747 | |
| 3748 | fn app() -> App { |
| 3749 | let mut app = crate::tui::test_support::test_app_with_options( |
| 3750 | crate::tui::test_support::test_tui_options("."), |
| 3751 | ); |
| 3752 | app.onboarding = OnboardingState::None; |
| 3753 | app.redaction_gate = false; |
| 3754 | app.ui_locale = codewhale_localization::Locale::En; |
| 3755 | app.pet_watch.detach_for_test(); |
| 3756 | pet_watch::set_enabled(&mut app, true); |
| 3757 | app |
| 3758 | } |
| 3759 | fn paint( |
| 3760 | app: &mut App, |
| 3761 | width: u16, |
| 3762 | height: u16, |
| 3763 | ) -> (ratatui::buffer::Buffer, Option<(u16, u16)>) { |
| 3764 | let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); |
| 3765 | let mut cursor = None; |
| 3766 | terminal |
| 3767 | .draw(|frame| cursor = render(frame, app, &Config::default())) |
| 3768 | .unwrap(); |
| 3769 | (terminal.backend().buffer().clone(), cursor) |
| 3770 | } |
| 3771 | fn text(buf: &ratatui::buffer::Buffer) -> String { |
| 3772 | buf.content.iter().map(|cell| cell.symbol()).collect() |
| 3773 | } |
| 3774 | fn capture(app: &App, name: &str, buf: &ratatui::buffer::Buffer, light: bool) { |
| 3775 | // Use the actual output backend's color projection, including light |
| 3776 | // contrast and terminal depth, before exporting the terminal cells. |
| 3777 | let mut buf = buf.clone(); |
| 3778 | for cell in &mut buf.content { |
| 3779 | crate::tui::color_compat::adapt_cell_colors( |
| 3780 | cell, |
| 3781 | codewhale_palette::ColorDepth::detect(), |
| 3782 | app.ui_theme.mode, |
| 3783 | app.theme_id, |
| 3784 | &app.ui_theme, |
| 3785 | Some(app.ui_theme.surface_bg), |
| 3786 | ); |
| 3787 | } |
| 3788 | if let Some(dir) = std::env::var_os("CODEWHALE_PET_CAPTURE_DIR") { |
| 3789 | let dir = PathBuf::from(dir); |
| 3790 | std::fs::create_dir_all(&dir).unwrap(); |
| 3791 | let profile = if light { |
| 3792 | codewhale_ratatui::testing::Profile::LightTrue |
| 3793 | } else { |
| 3794 | codewhale_ratatui::testing::Profile::DarkTrue |
| 3795 | }; |
| 3796 | std::fs::write( |
| 3797 | dir.join(format!("{name}.svg")), |
| 3798 | codewhale_ratatui::testing::svg(&buf, &profile.theme()), |
| 3799 | ) |
| 3800 | .unwrap(); |
| 3801 | } |
| 3802 | } |
| 3803 | #[test] |
| 3804 | fn pet_main_retains_native_composer_caret_pointer_and_paste_at_every_size() { |
| 3805 | for (width, height) in [(40, 12), (60, 16), (80, 24), (100, 32), (140, 40)] { |
| 3806 | let mut app = app(); |
| 3807 | app.composer_border = true; |
| 3808 | app.input = "Help me build 中文".into(); |
| 3809 | app.cursor_position = app.input.chars().count(); |
| 3810 | let (buf, cursor) = paint(&mut app, width, height); |
| 3811 | assert_eq!(app.focus(), Focus::Composer); |
| 3812 | let cursor = cursor.expect("pet mode keeps the actual composer caret"); |
| 3813 | let composer = app.viewport.last_composer_area.unwrap(); |
| 3814 | assert!(composer.contains(cursor.into()), "{width}x{height}"); |
| 3815 | assert!(app.viewport.last_transcript_area.is_none()); |
| 3816 | assert!(app.work_surface.last_area.is_none()); |
| 3817 | assert!(app.viewport.last_infoline_hitboxes.is_empty()); |
| 3818 | assert!(text(&buf).contains("F5")); |
| 3819 | capture(&app, &format!("main-{width}x{height}"), &buf, false); |
| 3820 | assert!(handle_composer_mouse( |
| 3821 | &mut app, |
| 3822 | crossterm::event::MouseEvent { |
| 3823 | kind: crossterm::event::MouseEventKind::Down( |
| 3824 | crossterm::event::MouseButton::Left |
| 3825 | ), |
| 3826 | column: cursor.0, |
| 3827 | row: cursor.1, |
| 3828 | modifiers: KeyModifiers::NONE, |
| 3829 | }, |
| 3830 | Instant::now() |
| 3831 | )); |
| 3832 | assert_eq!(app.cursor_position, app.input.chars().count()); |
| 3833 | crate::tui::paste::handle_paste( |
| 3834 | &mut app, |
| 3835 | crate::tui::paste::PasteSource::Terminal(" pasted"), |
| 3836 | ); |
| 3837 | assert!(app.input.ends_with(" pasted")); |
| 3838 | assert!(app.view_stack.is_empty()); |
| 3839 | } |
| 3840 | } |
| 3841 | #[test] |
| 3842 | fn pet_main_inspection_uses_the_same_key_and_pointer_route_and_returns_to_the_draft() { |
| 3843 | let mut app = app(); |
| 3844 | app.input = "kept draft".into(); |
| 3845 | app.cursor_position = app.input.chars().count(); |
| 3846 | app.add_message(HistoryCell::Assistant { |
| 3847 | content: "INSPECTION_RECEIPT".into(), |
| 3848 | streaming: true, |
| 3849 | }); |
| 3850 | let session = app.current_session_id.clone(); |
| 3851 | let (buf, _) = paint(&mut app, 100, 32); |
| 3852 | assert!(!text(&buf).contains("INSPECTION_RECEIPT")); |
| 3853 | assert!(!pet_watch::handle_key( |
| 3854 | &mut app, |
| 3855 | &KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE) |
| 3856 | )); |
| 3857 | assert!(pet_watch::handle_key( |
| 3858 | &mut app, |
| 3859 | &KeyEvent::new(KeyCode::F(5), KeyModifiers::NONE) |
| 3860 | )); |
| 3861 | let (buf, cursor) = paint(&mut app, 100, 32); |
| 3862 | assert!(text(&buf).contains("INSPECTION_RECEIPT")); |
| 3863 | assert!(cursor.is_none()); |
| 3864 | app.view_stack |
| 3865 | .handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); |
| 3866 | assert_eq!(app.focus(), Focus::Composer); |
| 3867 | assert!(pet_watch::main_view(&app)); |
| 3868 | paint(&mut app, 100, 32); |
| 3869 | let hint = app.pet_watch.inspect_area.unwrap(); |
| 3870 | crate::tui::mouse_ui::handle_mouse_event( |
| 3871 | &mut app, |
| 3872 | crossterm::event::MouseEvent { |
| 3873 | kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left), |
| 3874 | column: hint.x, |
| 3875 | row: hint.y, |
| 3876 | modifiers: KeyModifiers::NONE, |
| 3877 | }, |
| 3878 | Instant::now(), |
| 3879 | ); |
| 3880 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::PetHabitat)); |
| 3881 | app.view_stack |
| 3882 | .handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); |
| 3883 | assert_eq!(app.input, "kept draft"); |
| 3884 | assert_eq!(app.current_session_id, session); |
| 3885 | pet_watch::set_enabled(&mut app, false); |
| 3886 | let (buf, cursor) = paint(&mut app, 100, 32); |
| 3887 | assert!(text(&buf).contains("INSPECTION_RECEIPT")); |
| 3888 | assert!(cursor.is_some()); |
| 3889 | } |
| 3890 | #[test] |
| 3891 | fn pet_main_keeps_queue_feedback_and_cannot_take_approval_focus() { |
| 3892 | let mut app = app(); |
| 3893 | app.is_loading = true; |
| 3894 | app.queue_message(crate::tui::app::QueuedMessage::new( |
| 3895 | "QUEUED_FIXTURE_MESSAGE".into(), |
| 3896 | None, |
| 3897 | )); |
| 3898 | let (buf, _) = paint(&mut app, 80, 24); |
| 3899 | assert!(text(&buf).contains("QUEUED_FIXTURE_MESSAGE")); |
| 3900 | app.view_stack.push(ApprovalView::new(ApprovalRequest::new( |
| 3901 | "pet-approval", |
| 3902 | "exec_shell", |
| 3903 | "Review command", |
| 3904 | &serde_json::json!({"command":"git status"}), |
| 3905 | "pet-approval-key", |
| 3906 | ))); |
| 3907 | assert!(!pet_watch::handle_key( |
| 3908 | &mut app, |
| 3909 | &KeyEvent::new(KeyCode::F(5), KeyModifiers::NONE) |
| 3910 | )); |
| 3911 | let (_, cursor) = paint(&mut app, 80, 24); |
| 3912 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::Approval)); |
| 3913 | assert_eq!(app.focus(), Focus::Modal(ModalKind::Approval)); |
| 3914 | assert!(cursor.is_none()); |
| 3915 | assert_eq!(app.queued_messages.len(), 1); |
| 3916 | } |
| 3917 | #[test] |
| 3918 | fn pet_main_light_render_keeps_the_same_live_composer() { |
| 3919 | let mut app = app(); |
| 3920 | app.theme_id = codewhale_palette::ThemeId::ShorelineLight; |
| 3921 | app.ui_theme = app.theme_id.ui_theme(); |
| 3922 | app.input = "What should we work on?".into(); |
| 3923 | app.cursor_position = app.input.chars().count(); |
| 3924 | let (buf, cursor) = paint(&mut app, 100, 32); |
| 3925 | assert!(cursor.is_some()); |
| 3926 | assert_eq!(app.focus(), Focus::Composer); |
| 3927 | capture(&app, "main-light-100x32", &buf, true); |
| 3928 | } |
| 3929 | #[test] |
| 3930 | fn pet_inspector_keeps_the_copy_receipt_visible_and_returns_to_the_draft() { |
| 3931 | let _env = crate::test_support::lock_test_env(); |
| 3932 | let tmp = tempfile::TempDir::new().unwrap(); |
| 3933 | let _home = crate::test_support::EnvVarGuard::set("HOME", tmp.path()); |
| 3934 | let _state = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 3935 | for light in [false, true] { |
| 3936 | let mut app = app(); |
| 3937 | if light { |
| 3938 | app.theme_id = codewhale_palette::ThemeId::ShorelineLight; |
| 3939 | app.ui_theme = app.theme_id.ui_theme(); |
| 3940 | } |
| 3941 | app.clipboard = crate::tui::clipboard::ClipboardHandler::for_test(false, false); |
| 3942 | app.input = "My next message".into(); |
| 3943 | let reply = "Pet mode\n\nYour view is remembered when Codewhale starts.\n\n- F5 opens replies and agents.\n- Escape returns to your draft.\n- c copies the last finished reply."; |
| 3944 | let index = app.history.len(); |
| 3945 | app.add_message(HistoryCell::Assistant { |
| 3946 | content: reply.into(), |
| 3947 | streaming: false, |
| 3948 | }); |
| 3949 | app.record_completed_assistant_output(index, reply); |
| 3950 | assert!(pet_watch::handle_key( |
| 3951 | &mut app, |
| 3952 | &KeyEvent::new(KeyCode::F(5), KeyModifiers::NONE) |
| 3953 | )); |
| 3954 | let result = |
| 3955 | crate::commands::execute_with_config("/copy", &mut app, &Config::default()); |
| 3956 | assert!(!result.is_error); |
| 3957 | let (buf, cursor) = paint(&mut app, 100, 32); |
| 3958 | let output = text(&buf); |
| 3959 | assert!( |
| 3960 | output.contains("Accepted the last completed assistant response"), |
| 3961 | "copy feedback must be painted above the hidden transcript: {output}" |
| 3962 | ); |
| 3963 | assert!(output.contains("c copy finished reply")); |
| 3964 | assert!(cursor.is_none()); |
| 3965 | capture( |
| 3966 | &app, |
| 3967 | if light { |
| 3968 | "inspector-copy-light-100x32" |
| 3969 | } else { |
| 3970 | "inspector-copy-dark-100x32" |
| 3971 | }, |
| 3972 | &buf, |
| 3973 | light, |
| 3974 | ); |
| 3975 | app.view_stack |
| 3976 | .handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); |
| 3977 | assert_eq!(app.input, "My next message"); |
| 3978 | assert_eq!(app.focus(), Focus::Composer); |
| 3979 | } |
| 3980 | } |
| 3981 | } |
| 3982 |