返回 CodeWhale
one_owner_tests.rs
根目录 / crates / tui / src / tui / ui / frame / one_owner_tests.rs
1 //! One owner per fact: the full metrics preset paints each session fact in exactly
2 //! one chrome row (SHELL-DESIGN-20260901 §2.0 item 3, §2.2, §2.3, §2.3b).
3 //!
4 //! Under the composer: row 1 is the posture bar (permission, mode, live
5 //! counts, the one hint that applies now), row 2 is the metrics line (model,
6 //! context, cost, ttft, tok/s, output tokens); the roster and to-do rows follow
7 //! only when they have content. Every fact below is asserted to appear in
8 //! the composed frame exactly once.
9
10 // These tests print the composed frame as failure evidence. They run under
11 // `cargo test`, never inside the alt-screen, so `tui/mod.rs`'s
12 // `#![deny(clippy::print_stderr)]` — which exists to stop the scroll demon in
13 // production paint paths — does not apply here. The exception is test-module
14 // only; production TUI code still denies unstructured stderr.
15 #![allow(clippy::print_stderr)]
16
17 use std::path::PathBuf;
18 use std::time::{Duration, Instant};
19
20 use ratatui::{Terminal, backend::TestBackend};
21
22 use crate::tui::app::App;
23 use crate::tui::history::HistoryCell;
24 use codewhale_runtime::config::Config;
25
26 fn frame_app() -> App {
27 let mut app = crate::tui::test_support::test_app_with_options(crate::tui::app::TuiOptions {
28 model: "deepseek-v4-flash".to_string(),
29 start_in_agent_mode: true,
30 max_subagents: 4,
31 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
32 });
33 app.onboarding = crate::tui::app::OnboardingState::None;
34 app.launch.visible = false;
35 app.ui_locale = codewhale_localization::Locale::En;
36 app.metrics_line = codewhale_runtime::config::ChromeRowPreset::Full;
37 // The posture bar's permission chip carries the filesystem-scope notice
38 // (`files: workspace (unenforced)`) whenever no sandbox backend can
39 // actually enforce the policy — true on default Linux and all Windows,
40 // false on macOS, which resolves seatbelt. That is 30 columns of chip
41 // that appears or not depending on which machine runs the test, and it
42 // decides what an 80-column shed ladder can still hold: these tests
43 // passed locally and failed on both CI legs until it was pinned. Force
44 // the wider, unenforced reading so every host asserts the same row.
45 app.sandbox_backend = None;
46 // The fixture config carries no key; a keyless launch paints "model not
47 // connected" (U3). These rows are about a connected route.
48 app.onboarding_needs_api_key = false;
49 app.low_motion = true;
50 app
51 }
52
53 fn subagent(
54 id: &str,
55 status: codewhale_engine::tools::subagent::SubAgentStatus,
56 ) -> codewhale_engine::tools::subagent::SubAgentResult {
57 codewhale_engine::tools::subagent::SubAgentResult {
58 usage: None,
59 name: id.to_string(),
60 agent_id: id.to_string(),
61 context_mode: "fresh".to_string(),
62 fork_context: false,
63 workspace: None,
64 git_branch: None,
65 agent_type: codewhale_agent_contract::role::FleetRole::Worker,
66 assignment: codewhale_engine::tools::subagent::SubAgentAssignment {
67 native_preset: None,
68 objective: format!("objective-{id}"),
69 role: Some("worker".to_string()),
70 },
71 model: "deepseek-v4-flash".to_string(),
72 nickname: None,
73 status,
74 worker_status: None,
75 runtime_permissions: None,
76 parent_run_id: None,
77 spawn_depth: 0,
78 child_route: None,
79 result: None,
80 steps_taken: 0,
81 checkpoint: None,
82 needs_input: None,
83 duration_ms: 0,
84 started_at: None,
85 from_prior_session: false,
86 idle_ms: None,
87 heartbeat_timeout_ms: None,
88 }
89 }
90
91 /// A working turn with two running sub-agents and a session that has
92 /// already reported one turn's metrics.
93 fn working_app() -> App {
94 let mut app = frame_app();
95 app.history = vec![HistoryCell::User {
96 content: "audit the shell".to_string(),
97 }];
98 app.resync_history_revisions();
99 app.is_loading = true;
100 app.turn_started_at = Some(Instant::now() - Duration::from_secs(75));
101 app.subagent_cache = vec![
102 subagent(
103 "agent_a",
104 codewhale_engine::tools::subagent::SubAgentStatus::Running,
105 ),
106 subagent(
107 "agent_b",
108 codewhale_engine::tools::subagent::SubAgentStatus::Running,
109 ),
110 ];
111 app.session_metrics
112 .record_model_call(1_200, 29_600, Some(400), Some(30_000));
113 app.session.last_completion_tokens = Some(1_200);
114 app
115 }
116
117 fn draw(app: &mut App, width: u16, height: u16) -> Vec<String> {
118 let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
119 draw_into(app, &mut terminal).0
120 }
121
122 fn draw_into(
123 app: &mut App,
124 terminal: &mut Terminal<TestBackend>,
125 ) -> (Vec<String>, Option<(u16, u16)>) {
126 let config = Config::default();
127 let mut cursor = None;
128 super::prepare_frame_cursor(terminal).unwrap();
129 terminal
130 .draw(|frame| {
131 cursor = super::render(frame, app, &config);
132 })
133 .unwrap();
134 super::finish_frame_cursor(terminal, cursor).unwrap();
135 let buf = terminal.backend().buffer();
136 let rows = (0..buf.area.height)
137 .map(|y| {
138 (0..buf.area.width)
139 .map(|x| buf[(x, y)].symbol())
140 .collect::<String>()
141 })
142 .collect();
143 (rows, cursor)
144 }
145
146 fn count_rows_containing(rows: &[String], needle: &str) -> usize {
147 rows.iter().filter(|row| row.contains(needle)).count()
148 }
149
150 /// Every chrome fact paints in exactly one row of the composed default
151 /// frame: the context reading, the permission dial chip, the model,
152 /// the cost, the agent count, and the help hint.
153 ///
154 /// 160 columns joins the blocker sizes so both working-clock halves can
155 /// paint together when the session half is present; at 80 and 120 the
156 /// clocks shed by design (#5914) against the pinned scope notice. The
157 /// #6084 shed-order fix (sole turn clock uses the session rung) is pinned
158 /// in `phase_strip::tideline_tests`, where the narrower permission chip
159 /// exposes the width band the one-owner fixture's notice collapses.
160 #[test]
161 fn composed_frame_paints_each_fact_in_exactly_one_row() {
162 for (width, height) in [(80u16, 24u16), (120, 32), (160, 40), (200, 40)] {
163 let mut app = working_app();
164 let rows = draw(&mut app, width, height);
165 let pct = super::info_context_percent(&app);
166 let (_, model) = app.effective_route_identity_display();
167 let permission = crate::tui::underwater::dial_chip(&app).0.into_owned();
168 // The context reading paints exactly once, at every fullness
169 // (#5950 — it used to go silent below 50%).
170 let mut facts = vec![
171 // Mark 8: the permission in force is marked `●` and followed by
172 // what its key does, not a parenthesised chord.
173 ("permission chip", format!("● {permission}")),
174 ("model", model),
175 ("cost", super::session_cost_label(&app)),
176 ("ttft", "ttft 400ms".to_string()),
177 ];
178 facts.push(("context reading", format!("context {pct}%")));
179 facts.push(("output rate", "40 avg tok/s".to_string()));
180 if width >= 120 {
181 facts.push(("agent count", "2 agents".to_string()));
182 facts.push((
183 "help hint",
184 crate::tui::shell_key_routing::info_help_hint(app.ui_locale),
185 ));
186 }
187 for (name, needle) in facts {
188 if needle.is_empty() {
189 continue;
190 }
191 assert_eq!(
192 count_rows_containing(&rows, &needle),
193 1,
194 "{width}x{height}: {name} {needle:?} must paint in exactly one row:\n{}",
195 rows.join("\n")
196 );
197 }
198 // Rows under the composer: posture bar, then metrics line, then the
199 // roster — never the other way round.
200 let posture = rows
201 .iter()
202 .position(|row| row.contains("● "))
203 .expect("posture bar");
204 let metrics = rows
205 .iter()
206 .position(|row| row.contains("context "))
207 .expect("metrics line");
208 let composer = app
209 .viewport
210 .last_composer_area
211 .expect("composer area")
212 .bottom();
213 assert_eq!(
214 posture,
215 usize::from(composer),
216 "posture bar is row 1 under the composer"
217 );
218 assert_eq!(metrics, posture + 1, "metrics line is row 2");
219 // The scope notice is pinned on, not inherited from the host: if
220 // this ever goes quiet the widths below stop meaning what they say.
221 assert!(
222 rows[posture].contains("files: workspace (unenforced)"),
223 "{width}x{height}: the fixture must pin the scope notice: {}",
224 rows[posture]
225 );
226 // The bar carries the working clock (#5914) — how long the current
227 // turn has been doing what it is doing, and how long the session has
228 // worked. The turn half is the last live fact to shed (CW-8264), so
229 // it paints at every width here; against this fixture's pinned scope
230 // notice the counts need 120 columns beside it. The session half
231 // sheds first and needs ~175 with the running hint, which also names
232 // the agent arrows (`← for agents · ↓ to manage`). Each paints in
233 // exactly one row wherever it paints. The metrics line carries no
234 // repository, branch or provider.
235 // First turn: the turn half names the phase and stays; the session
236 // reading is the identical duration, so it is suppressed rather than
237 // stated twice (#6041). The shed-order contract itself lives in
238 // tideline_tests.
239 let turn_needle = "agents underway 1m 15s";
240 assert!(rows[posture].contains(turn_needle), "{}", rows[posture]);
241 assert_eq!(
242 count_rows_containing(&rows, turn_needle),
243 1,
244 "{width}x{height}: {turn_needle:?} paints in exactly one row:\n{}",
245 rows.join("\n")
246 );
247 assert!(
248 !rows[posture].contains("worked 1m 15s"),
249 "{width}x{height}: the duplicate session reading must not be stated: {}",
250 rows[posture]
251 );
252 // After a finished turn the totals differ and the worked chip
253 // returns: 1m of finished turns plus the live 1m 15s reads 2m 15s.
254 let mut worked = working_app();
255 worked.cumulative_turn_duration = Duration::from_secs(60);
256 let rows = draw(&mut worked, width, height);
257 if width >= 200 {
258 let worked_needle = "worked 2m 15s";
259 assert!(rows[posture].contains(worked_needle), "{}", rows[posture]);
260 assert_eq!(
261 count_rows_containing(&rows, worked_needle),
262 1,
263 "{width}x{height}: {worked_needle:?} paints in exactly one row:\n{}",
264 rows.join("\n")
265 );
266 }
267 assert!(rows[posture].contains(turn_needle), "{}", rows[posture]);
268 assert!(!rows[metrics].contains('⑂'), "{}", rows[metrics]);
269 // No dead key hints anywhere in the frame.
270 for row in &rows {
271 assert!(!row.contains("F1"), "F1 is not receivable: {row}");
272 assert!(!row.contains("? help"), "bare ? is composer text: {row}");
273 }
274 }
275 }
276
277 /// Idle: the two rows are there, the roster is not, and the last turn's
278 /// metrics survive between turns.
279 #[test]
280 fn idle_frame_keeps_two_chrome_rows_and_last_turn_metrics() {
281 let mut app = working_app();
282 app.is_loading = false;
283 app.turn_started_at = None;
284 app.subagent_cache.clear();
285 // 120 columns: the labeled readings ("thinking: max", "context 0%",
286 // mark 8) are wider than the bare ones, so at 100 columns the output
287 // count (shed priority 7, ahead of the help hint) is shed by design.
288 let rows = draw(&mut app, 120, 32);
289 let composer = app.viewport.last_composer_area.unwrap().bottom() as usize;
290 assert!(rows[composer].contains("● "), "{}", rows[composer]);
291 // The idle fixture sits at 0% context and says so: the reading is on
292 // the row at every fullness (#5950), not only once it is a problem.
293 assert!(
294 rows[composer + 1].contains("context 0%"),
295 "{}",
296 rows[composer + 1]
297 );
298 assert!(
299 rows[composer + 1].contains("40 avg tok/s"),
300 "{}",
301 rows[composer + 1]
302 );
303 assert!(
304 rows[composer + 1].contains("↓ 1.2K"),
305 "{}",
306 rows[composer + 1]
307 );
308 assert_eq!(
309 composer + 2,
310 rows.len(),
311 "nothing under the metrics line when idle"
312 );
313 assert!(
314 !rows[composer].contains("Esc to interrupt"),
315 "{}",
316 rows[composer]
317 );
318 }
319
320 /// At the cap the posture bar's hint says what to do; the reading still
321 /// paints once, in the metrics line.
322 #[test]
323 fn context_cap_warns_once_in_the_posture_bar() {
324 let mut app = working_app();
325 app.active_route_limits = Some(codewhale_config::route::RouteLimits {
326 context_tokens: Some(60),
327 ..Default::default()
328 });
329 // 140 columns: the fixture always paints the filesystem scope notice
330 // (`frame_app` pins `sandbox_backend = None`), so the width has to hold
331 // the warning with the notice present. The clock halves shed first.
332 let rows = draw(&mut app, 140, 32);
333 let pct = super::info_context_percent(&app);
334 assert!(pct >= 80, "fixture must sit at the cap: {pct}");
335 assert_eq!(
336 count_rows_containing(&rows, "surface soon — /compact"),
337 1,
338 "cap warning rows:\n{}",
339 rows.join("\n")
340 );
341 assert_eq!(
342 count_rows_containing(&rows, &format!("{pct}%")),
343 1,
344 "context reading rows:\n{}",
345 rows.join("\n")
346 );
347 }
348
349 /// `tui.posture_bar` / `tui.metrics_line` (#5950): `hidden` gives a row
350 /// back to the transcript — one row per hidden preset, two for both — and
351 /// `compact` keeps the row with its first shed rungs already gone. Every
352 /// other row of the frame stays where it was, so the composer is never
353 /// displaced by the choice.
354 #[test]
355 fn row_presets_reclaim_rows_and_quiet_them_in_the_composed_frame() {
356 use codewhale_runtime::config::ChromeRowPreset;
357 // 160 columns joins the blocker sizes above: the working clock's two
358 // halves only both fit beside the pinned unenforced-scope permission
359 // chip from that width up, and this test asserts the full row's clocks.
360 let (width, height) = (160u16, 32u16);
361 let posture_row = |rows: &[String]| rows.iter().position(|row| row.contains("● "));
362 let metrics_row = |rows: &[String]| rows.iter().position(|row| row.contains("context "));
363
364 let mut app = working_app();
365 let full = draw(&mut app, width, height);
366 let posture = posture_row(&full).expect("full frame paints the posture bar");
367 let metrics = metrics_row(&full).expect("full frame paints the metrics line");
368 assert_eq!(
369 metrics,
370 posture + 1,
371 "the metrics line sits under the posture bar"
372 );
373 // The full row's live facts: a turn clock (this fixture waits on
374 // sub-agents, so #5914 words it `sub-agents underway` rather than
375 // `working`), the live counts and the hint — the three compact drops.
376 assert!(full[posture].contains("1m 15s"), "{:?}", full[posture]);
377 assert!(full[posture].contains("2 agents"), "{:?}", full[posture]);
378 assert!(
379 full[posture].contains("Esc to interrupt"),
380 "{:?}",
381 full[posture]
382 );
383 assert!(full[metrics].contains("tok/s"), "{:?}", full[metrics]);
384
385 // Hide the posture bar: the metrics line takes its row, and the
386 // transcript above gains one.
387 app.posture_bar = ChromeRowPreset::Hidden;
388 let rows = draw(&mut app, width, height);
389 assert_eq!(posture_row(&rows), None, "no posture bar: {rows:#?}");
390 assert_eq!(
391 metrics_row(&rows),
392 Some(metrics),
393 "the metrics line keeps its row"
394 );
395 assert_eq!(
396 count_rows_containing(&rows, "context "),
397 1,
398 "the context reading is still painted once"
399 );
400
401 // Hide both: two rows reclaimed.
402 app.metrics_line = ChromeRowPreset::Hidden;
403 let rows = draw(&mut app, width, height);
404 assert_eq!(posture_row(&rows), None);
405 assert_eq!(metrics_row(&rows), None);
406 assert_eq!(count_rows_containing(&rows, "deepseek-v4-pro"), 0);
407
408 // Compact both: the rows are back, quieter — the posture and the
409 // route/reading/price and measured performance, without secondary counts.
410 app.posture_bar = ChromeRowPreset::Compact;
411 app.metrics_line = ChromeRowPreset::Compact;
412 let rows = draw(&mut app, width, height);
413 let posture = posture_row(&rows).expect("compact paints the posture bar");
414 let metrics = metrics_row(&rows).expect("compact paints the metrics line");
415 assert_eq!(metrics, posture + 1);
416 let permission = crate::tui::underwater::dial_chip(&app);
417 assert!(rows[posture].contains(permission.0.as_ref()));
418 for gone in ["working", "2 agents", "Esc to interrupt"] {
419 assert!(
420 !rows[posture].contains(gone),
421 "{gone} in {:?}",
422 rows[posture]
423 );
424 }
425 assert!(
426 rows[metrics].contains("deepseek-v4-pro"),
427 "{:?}",
428 rows[metrics]
429 );
430 let pct = super::info_context_percent(&app);
431 assert!(
432 rows[metrics].contains(&format!("context {pct}%")),
433 "{:?}",
434 rows[metrics]
435 );
436 assert!(rows[metrics].contains("ttft 400ms"), "{}", rows[metrics]);
437 assert!(rows[metrics].contains("40 avg tok/s"), "{}", rows[metrics]);
438 for gone in [
439 "↓ 1.2K",
440 crate::tui::shell_key_routing::info_help_hint(app.ui_locale).as_str(),
441 ] {
442 assert!(
443 !rows[metrics].contains(gone),
444 "{gone} in {:?}",
445 rows[metrics]
446 );
447 }
448 }
449
450 /// Exercise live preset transitions on the same terminal and App, including
451 /// restoration. Fresh buffers alone cannot expose stale chrome or hitboxes.
452 #[test]
453 fn statusline_full_frame_presets_preserve_transcript_composer_and_hitboxes() {
454 use crate::tui::tideline::{InteractionAction, InteractionTargetId};
455 use codewhale_runtime::config::{ChromeRowPreset, StatusItem};
456 use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
457 use ratatui::layout::Position;
458
459 for (width, height) in [(40, 12), (60, 16), (80, 24), (100, 32)] {
460 let mut app = frame_app();
461 app.history = vec![HistoryCell::User {
462 content: (0..60)
463 .map(|row| format!("transcript-line-{row:02}"))
464 .collect::<Vec<_>>()
465 .join("\n"),
466 }];
467 app.resync_history_revisions();
468 app.input = "ab中文".to_string();
469 app.cursor_position = app.input.chars().count();
470 app.composer_border = true;
471 app.status_items = StatusItem::default_footer();
472 app.posture_bar = ChromeRowPreset::Full;
473 app.metrics_line = ChromeRowPreset::Full;
474 app.session_metrics
475 .record_model_call(1_200, 29_600, Some(400), Some(30_000));
476 app.session.last_completion_tokens = Some(1_200);
477 let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
478 let (full, _) = draw_into(&mut app, &mut terminal);
479 let full_buffer = terminal.backend().buffer().clone();
480 let full_transcript = app.viewport.last_transcript_area.unwrap();
481 let full_composer = app.viewport.last_composer_area.unwrap();
482 let full_visible = count_rows_containing(&full, "transcript-line-");
483 assert!(
484 full_visible > 0 && full_visible < 60,
485 "populated scrollback fixture"
486 );
487
488 for (name, posture, metrics, reclaimed) in [
489 ("full", ChromeRowPreset::Full, ChromeRowPreset::Full, 0),
490 (
491 "metrics-hidden",
492 ChromeRowPreset::Full,
493 ChromeRowPreset::Hidden,
494 1,
495 ),
496 (
497 "posture-hidden",
498 ChromeRowPreset::Hidden,
499 ChromeRowPreset::Full,
500 1,
501 ),
502 (
503 "both-hidden",
504 ChromeRowPreset::Hidden,
505 ChromeRowPreset::Hidden,
506 2,
507 ),
508 (
509 "both-compact",
510 ChromeRowPreset::Compact,
511 ChromeRowPreset::Compact,
512 0,
513 ),
514 (
515 "full-restored",
516 ChromeRowPreset::Full,
517 ChromeRowPreset::Full,
518 0,
519 ),
520 ] {
521 app.posture_bar = posture;
522 app.metrics_line = metrics;
523 let (rows, cursor) = draw_into(&mut app, &mut terminal);
524 let evidence = format!("{width}x{height} {name}\n{}", rows.join("\n"));
525 eprintln!("{evidence}");
526 let transcript = app.viewport.last_transcript_area.unwrap();
527 let composer = app.viewport.last_composer_area.unwrap();
528 assert_eq!(
529 transcript.height,
530 full_transcript.height + reclaimed,
531 "{evidence}"
532 );
533 assert_eq!(composer.y, full_composer.y + reclaimed, "{evidence}");
534 assert_eq!(composer.height, full_composer.height, "{evidence}");
535 assert_eq!(transcript.bottom(), composer.y, "{evidence}");
536 assert_eq!(
537 count_rows_containing(&rows, "transcript-line-"),
538 full_visible + usize::from(reclaimed),
539 "{evidence}"
540 );
541 assert!(
542 rows.iter().any(|row| row.contains("transcript-line-59")),
543 "latest transcript survives: {evidence}"
544 );
545 assert_eq!(app.input, "ab中文");
546 assert!(
547 rows.iter().all(|row| !row.contains('\u{fffd}')),
548 "{evidence}"
549 );
550
551 let cursor = cursor.expect("active composer exposes its caret");
552 let inner = app.viewport.last_composer_content.unwrap();
553 let text = crate::tui::widgets::composer_content_geometry(inner, false).text_area;
554 let submit = crate::tui::widgets::active_composer_submit_rect(&app, composer).unwrap();
555 assert!(
556 text.contains(Position::from(cursor)),
557 "caret inside text grid: {evidence}"
558 );
559 assert_eq!(
560 cursor.0,
561 text.x + 6,
562 "two ASCII and two wide glyphs: {evidence}"
563 );
564 assert!(
565 !submit.contains(Position::from(cursor)),
566 "caret cannot hit Send: {evidence}"
567 );
568 assert!(terminal.backend().cursor_visible());
569 terminal
570 .backend_mut()
571 .assert_cursor_position(Position::from(cursor));
572 // Terminal backends skip continuation cells covered by a wide
573 // glyph. TestBackend can retain a prior border in those cells;
574 // it is not visible terminal text after the wide glyph is drawn.
575 let mut painted_input = String::new();
576 let mut x = text.x;
577 while x < cursor.0 {
578 let symbol = terminal.backend().buffer()[(x, cursor.1)].symbol();
579 painted_input.push_str(symbol);
580 x += unicode_width::UnicodeWidthStr::width(symbol).max(1) as u16;
581 }
582 assert_eq!(painted_input, "ab中文", "{evidence}");
583 app.viewport.composer_click_trace = None;
584 assert!(crate::tui::mouse_ui::handle_composer_mouse(
585 &mut app,
586 MouseEvent {
587 kind: MouseEventKind::Down(MouseButton::Left),
588 column: cursor.0,
589 row: cursor.1,
590 modifiers: KeyModifiers::NONE,
591 },
592 Instant::now()
593 ));
594 assert_eq!(
595 app.cursor_position,
596 app.input.chars().count(),
597 "CJK mouse/caret boundary: {evidence}"
598 );
599
600 let context = app
601 .viewport
602 .interaction_targets
603 .iter()
604 .find(|target| target.id == InteractionTargetId::HEADER_CONTEXT);
605 let model = app
606 .viewport
607 .interaction_targets
608 .iter()
609 .find(|target| target.id == InteractionTargetId::HEADER_MODEL);
610 if metrics == ChromeRowPreset::Hidden {
611 assert!(app.viewport.last_infoline_hitboxes.is_empty(), "{evidence}");
612 assert!(
613 context.is_none() && model.is_none(),
614 "hidden chrome has no stale actions: {evidence}"
615 );
616 assert_eq!(count_rows_containing(&rows, "context "), 0, "{evidence}");
617 } else {
618 let context = context.expect("visible context has an inspector hitbox");
619 let model = model.expect("visible model has a picker hitbox");
620 assert_eq!(
621 context.mouse_action,
622 Some(InteractionAction::InspectContext)
623 );
624 assert_eq!(model.mouse_action, Some(InteractionAction::OpenModelPicker));
625 for target in [context, model] {
626 assert_eq!(target.keyboard_action, target.mouse_action);
627 assert_eq!(target.area.y, height - 1, "{evidence}");
628 assert_eq!(
629 app.viewport
630 .interaction_targets
631 .target_at(target.area.x, target.area.y),
632 Some(target)
633 );
634 assert!(!composer.intersects(target.area), "{evidence}");
635 }
636 assert_eq!(count_rows_containing(&rows, "context 0%"), 1, "{evidence}");
637 }
638 if metrics == ChromeRowPreset::Compact {
639 if width >= 60 {
640 assert!(rows[usize::from(height - 1)].contains("ttft"), "{evidence}");
641 assert!(
642 rows[usize::from(height - 1)].contains("avg tok/s"),
643 "{evidence}"
644 );
645 }
646 for shed in ["↓ 1.2K", "Ctrl+/ help"] {
647 assert!(!rows[usize::from(height - 1)].contains(shed), "{evidence}");
648 }
649 }
650 if name == "full-restored" {
651 let restored = terminal.backend().buffer();
652 assert_eq!(restored.area, full_buffer.area);
653 for y in full_buffer.area.y..full_buffer.area.bottom() {
654 let mut x = full_buffer.area.x;
655 while x < full_buffer.area.right() {
656 let expected = &full_buffer[(x, y)];
657 assert_eq!(
658 &restored[(x, y)],
659 expected,
660 "restoration leaves no stale visible cell or style at ({x}, {y}): {evidence}"
661 );
662 // Covered continuation cells are not rendered by a
663 // terminal, so TestBackend's retained contents there
664 // are not part of visible restoration.
665 x += unicode_width::UnicodeWidthStr::width(expected.symbol()).max(1) as u16;
666 }
667 }
668 }
669 }
670 }
671 }
672
673 /// #5976 supersedes #5950's blanket custom-cost omission, and the cost line
674 /// now carries confirmed dollars only: an unpriced session shows no money at
675 /// any width, and a partly priced one shows exactly the confirmed amount.
676 #[test]
677 fn statusline_cost_shows_confirmed_dollars_only() {
678 use codewhale_config::ProviderKind;
679 use codewhale_engine::route_billing::{BillingPresentation, UsageChip};
680 use codewhale_runtime::config::{ChromeRowPreset, StatusItem};
681
682 for (width, height) in [(40, 12), (60, 16), (80, 24), (100, 32)] {
683 let mut app = frame_app();
684 app.history = vec![HistoryCell::User {
685 content: "Review saved usage".to_string(),
686 }];
687 app.resync_history_revisions();
688 app.set_provider_identity(ProviderKind::Custom, "my-gateway");
689 app.active_route_base_url = "https://gateway.example/v1".to_string();
690 app.model = "vendor-model-x".to_string();
691 app.reasoning_effort = codewhale_engine::reasoning_preference::ReasoningEffort::High;
692 app.billing_presentation = BillingPresentation::Unknown;
693 app.session.cost_coverage_unknown_legacy = true;
694 app.status_items = vec![StatusItem::ContextPercent, StatusItem::Cost];
695 app.posture_bar = ChromeRowPreset::Hidden;
696 app.metrics_line = ChromeRowPreset::Compact;
697 let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
698
699 assert_eq!(app.api_provider, ProviderKind::Custom);
700 assert!(matches!(app.cumulative_usage_chip(), UsageChip::Unknown(_)));
701 assert_eq!(
702 super::session_cost_label(&app),
703 "",
704 "{width}: an unpriced session shows no money"
705 );
706 let (rows, _) = draw_into(&mut app, &mut terminal);
707 let metrics = rows.last().unwrap();
708 assert!(metrics.contains("context 0%"), "{metrics}");
709 assert!(!metrics.contains('$'), "{width}: {metrics}");
710 assert!(!metrics.contains("cost"), "{width}: {metrics}");
711
712 app.status_items.retain(|item| *item != StatusItem::Cost);
713 let (hidden, _) = draw_into(&mut app, &mut terminal);
714 assert_eq!(
715 hidden, rows,
716 "an empty cost line changes no frame at {width}"
717 );
718 app.status_items.push(StatusItem::Cost);
719
720 // A confirmed amount with a coverage gap prints as that amount alone.
721 app.billing_presentation = BillingPresentation::Metered;
722 app.session.cost_coverage_unknown_legacy = false;
723 app.session.cost_priced_turns = 1;
724 app.session.cost_unpriced_turns = 1;
725 app.session.session_cost = 0.42;
726 assert!(
727 matches!(
728 app.cumulative_usage_chip(),
729 UsageChip::PricedSubtotal { .. }
730 ),
731 "{:?}",
732 app.cumulative_usage_chip()
733 );
734 let label = super::session_cost_label(&app);
735 assert!(
736 label.contains("0.42") && !label.contains("unknown"),
737 "{label}"
738 );
739 let (priced, _) = draw_into(&mut app, &mut terminal);
740 if width >= 60 {
741 assert!(priced.last().unwrap().contains(&label), "{priced:?}");
742 }
743 assert_eq!(app.session.cost_unpriced_turns, 1);
744 }
745 }
746
747 #[test]
748 fn statusline_full_frame_context_reading_updates_below_and_at_warning() {
749 use crate::tui::tideline::InteractionTargetId;
750 use codewhale_models::{ContentBlock, Message, Role};
751 use codewhale_palette::ChromeInk;
752 use codewhale_runtime::config::{ChromeRowPreset, StatusItem};
753
754 for (width, height) in [(40, 12), (60, 16), (80, 24), (100, 32)] {
755 let mut app = frame_app();
756 app.history = vec![HistoryCell::User {
757 content: "Keep the context reading visible".to_string(),
758 }];
759 app.resync_history_revisions();
760 app.api_messages = std::sync::Arc::new(vec![Message {
761 role: Role::User,
762 content: vec![ContentBlock::Text {
763 text: "context ".repeat(400),
764 cache_control: None,
765 }],
766 }]);
767 app.input = "next".to_string();
768 app.cursor_position = app.input.chars().count();
769 app.status_items = StatusItem::default_footer();
770 app.posture_bar = ChromeRowPreset::Full;
771 app.metrics_line = ChromeRowPreset::Full;
772 let (used, _, _) = super::context_usage_snapshot(&app).unwrap();
773 let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
774 let mut first_geometry = None;
775 let mut first_frame = None;
776
777 for pct in [0u8, 10, 79, 80, 10, 0] {
778 let window = if pct == 0 {
779 // 0.1% rounds to the displayed 0% even with real context.
780 used as u64 * 1_000
781 } else {
782 (used as f64 * 100.0 / f64::from(pct)).round() as u64
783 };
784 app.active_route_limits = Some(codewhale_config::route::RouteLimits {
785 context_tokens: Some(window),
786 ..Default::default()
787 });
788 assert_eq!(super::info_context_percent(&app), pct);
789 let (rows, cursor) = draw_into(&mut app, &mut terminal);
790 let evidence = format!("{width}x{height} context-{pct}\n{}", rows.join("\n"));
791 eprintln!("{evidence}");
792 let label = format!("context {pct}%");
793 assert_eq!(count_rows_containing(&rows, &label), 1, "{evidence}");
794 assert!(
795 rows.iter()
796 .any(|row| row.contains("Keep the context reading visible")),
797 "{evidence}"
798 );
799 let context = app
800 .viewport
801 .interaction_targets
802 .iter()
803 .find(|target| target.id == InteractionTargetId::HEADER_CONTEXT)
804 .expect("the visible reading stays inspectable");
805 assert_eq!(context.area.y, height - 1, "{evidence}");
806 // Attention, not Failure: the posture bar calls this same >= 80
807 // threshold Attention, and the two must not disagree one row apart.
808 let value_fg = if pct >= 80 {
809 codewhale_palette::grammar::chrome_style(&app.ui_theme, ChromeInk::Attention)
810 .fg
811 .unwrap()
812 } else {
813 codewhale_palette::grammar::chrome_style(&app.ui_theme, ChromeInk::Info)
814 .fg
815 .unwrap()
816 };
817 let label_fg = if pct >= 80 {
818 codewhale_palette::grammar::chrome_style(&app.ui_theme, ChromeInk::Attention)
819 .fg
820 .unwrap()
821 } else {
822 app.ui_theme.text_soft
823 };
824 let buffer = terminal.backend().buffer();
825 // The value starts after the "context " label.
826 for (x, expected) in [(context.area.x, label_fg), (context.area.x + 8, value_fg)] {
827 assert_eq!(
828 buffer[(x, context.area.y)].fg,
829 expected,
830 "warning ink must also clear after 80%: {evidence}",
831 );
832 }
833 let geometry = (
834 app.viewport.last_transcript_area,
835 app.viewport.last_composer_area,
836 cursor,
837 );
838 if let Some(first) = first_geometry {
839 assert_eq!(geometry, first, "{evidence}");
840 } else {
841 first_geometry = Some(geometry);
842 }
843 if pct == 0 {
844 if let Some(first) = first_frame.as_ref() {
845 assert_eq!(
846 terminal.backend().buffer(),
847 first,
848 "returning to 0% clears the warning frame and ink"
849 );
850 } else {
851 first_frame = Some(terminal.backend().buffer().clone());
852 }
853 }
854 }
855 }
856 }
857
858 #[test]
859 fn conversation_mode_label_shows_creator_and_nothing_for_standard() {
860 for (width, height) in [(80u16, 24u16), (120, 32)] {
861 let mut standard = frame_app();
862 let standard_rows = draw(&mut standard, width, height);
863 assert!(
864 standard_rows
865 .iter()
866 .all(|row| !row.contains("Creator mode") && !row.contains("Standard mode")),
867 "{width}x{height}: Standard shows nothing new:\n{}",
868 standard_rows.join("\n")
869 );
870
871 let mut creator = frame_app();
872 creator.install_conversation_mode(Some("creator".to_string()), None);
873 let rows = draw(&mut creator, width, height);
874 assert_eq!(
875 count_rows_containing(&rows, "Creator mode"),
876 1,
877 "{width}x{height}: the mode name paints once, as text:\n{}",
878 rows.join("\n")
879 );
880
881 let mut unavailable = frame_app();
882 unavailable.install_conversation_mode(
883 Some("creator".to_string()),
884 Some("Not ready yet in this version.".to_string()),
885 );
886 let rows = draw(&mut unavailable, width, height);
887 assert_eq!(
888 count_rows_containing(&rows, "Creator mode (unavailable)"),
889 1,
890 "{width}x{height}:\n{}",
891 rows.join("\n")
892 );
893 }
894 }
895
895 lines RUST