返回 CodeWhale
tests.rs
根目录 / crates / tui / src / tui / app / tests.rs
1 use super::*;
2 use crate::test_support::{EnvVarGuard, lock_test_env};
3 use crate::tui::clipboard::{ClipboardContent, ClipboardHandler, PastedImage};
4 use crate::tui::history::{GenericToolCell, HistoryCell, ToolCell, ToolStatus};
5 use crate::tui::motion::MotionMode;
6 use codewhale_config::ProviderKind;
7 use codewhale_engine::tools::plan::{PlanItemArg, StepStatus, UpdatePlanArgs};
8 use codewhale_engine::tools::todo::TodoStatus;
9 use codewhale_models::Usage;
10 use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig};
11 use codewhale_runtime::settings::Settings;
12
13 fn test_options(yolo: bool) -> TuiOptions {
14 TuiOptions {
15 model: "test-model".to_string(),
16 allow_shell: yolo,
17 // Keep unit tests independent from the developer's saved
18 // `default_mode` setting.
19 start_in_agent_mode: true,
20 skip_onboarding: false,
21 yolo,
22 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
23 }
24 }
25
26 #[test]
27 fn shorter_api_snapshots_keep_preserved_stamps_in_place() {
28 let mut app = App::new(test_options(false), &Config::default());
29 let message = |text: &str| Message {
30 role: codewhale_models::Role::User,
31 content: vec![codewhale_models::ContentBlock::Text {
32 text: text.to_string(),
33 cache_control: None,
34 }],
35 };
36 let first = DateTime::<Utc>::from_timestamp(1_700_000_000, 0).unwrap();
37 let third = first + chrono::Duration::minutes(2);
38 app.api_messages =
39 std::sync::Arc::new(vec![message("first"), message("second"), message("third")]);
40 app.api_message_stamps = vec![first, first + chrono::Duration::minutes(1), third];
41 app.set_api_messages(Arc::new(vec![message("first"), message("second")]));
42 assert_eq!(app.api_messages.len(), 2);
43 assert_eq!(app.api_message_stamps.len(), 2);
44 app.set_api_messages(Arc::new(vec![message("first")]));
45 assert_eq!(app.api_messages.len(), 1);
46 assert_eq!(app.api_message_stamps, vec![first]);
47 }
48
49 #[test]
50 fn set_api_messages_installs_the_shared_snapshot_without_copying() {
51 let mut app = App::new(test_options(false), &Config::default());
52 let snapshot = Arc::new(vec![Message {
53 role: codewhale_models::Role::User,
54 content: vec![codewhale_models::ContentBlock::Text {
55 text: "hello".to_string(),
56 cache_control: None,
57 }],
58 }]);
59 app.set_api_messages(Arc::clone(&snapshot));
60 assert!(Arc::ptr_eq(&app.api_messages, &snapshot));
61 // Mutating the mirror detaches; the engine snapshot is untouched.
62 app.push_api_message(Message {
63 role: codewhale_models::Role::Assistant,
64 content: vec![],
65 });
66 assert_eq!(snapshot.len(), 1);
67 assert_eq!(app.api_messages.len(), 2);
68 app.session_turn_outcomes = vec![
69 codewhale_engine::session_manager::SavedTurnOutcome::failed("shared failure", 1),
70 codewhale_engine::session_manager::SavedTurnOutcome::failed("replaced failure", 2),
71 ];
72 let replacement = Arc::new(vec![snapshot[0].clone(), snapshot[0].clone()]);
73 app.set_api_messages(Arc::clone(&replacement));
74 assert!(Arc::ptr_eq(&app.api_messages, &replacement));
75 assert_eq!(app.session_turn_outcomes.len(), 1);
76 assert_eq!(app.session_turn_outcomes[0].error, "shared failure");
77 }
78
79 #[test]
80 fn app_motion_policy_and_transcript_bridge_cover_every_settings_mode() {
81 let mut app = App::new(test_options(false), &Config::default());
82 app.constrained_frame_rate = false;
83
84 for (low_motion, fancy_animations, expected_mode, static_status) in [
85 (false, true, MotionMode::Full, false),
86 (true, true, MotionMode::Reduced, true),
87 (false, false, MotionMode::Still, true),
88 // The explicit accessibility preference wins when both switches are off.
89 (true, false, MotionMode::Reduced, true),
90 ] {
91 app.low_motion = low_motion;
92 app.fancy_animations = fancy_animations;
93
94 assert_eq!(app.motion_policy().mode(), expected_mode);
95 assert_eq!(app.effective_low_motion_for_status(), static_status);
96 let options = app.transcript_render_options();
97 assert_eq!(options.low_motion, static_status);
98 assert_eq!(options.motion_mode, expected_mode);
99 }
100 }
101
102 #[cfg(unix)]
103 fn create_dir_symlink(target: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> {
104 std::os::unix::fs::symlink(target, link)
105 }
106
107 #[cfg(windows)]
108 fn create_dir_symlink(target: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> {
109 std::os::windows::fs::symlink_dir(target, link)
110 }
111
112 #[test]
113 fn feature_intro_scenario() {
114 // Scenario consolidation of: feature_intro_is_silent_while_onboarding_is_in_progress, feature_intro_is_silent_when_auth_setup_is_incomplete
115 // from feature_intro_is_silent_while_onboarding_is_in_progress
116 {
117 let mut app = App::new(test_options(false), &Config::default());
118 app.onboarding = OnboardingState::Welcome;
119 let before = app.history.len();
120 app.maybe_show_feature_intro();
121 assert_eq!(
122 app.history.len(),
123 before,
124 "must not nudge while onboarding is in progress"
125 );
126 }
127 // from feature_intro_is_silent_when_auth_setup_is_incomplete
128 {
129 // --skip-onboarding with no provider key must not claim setup is ready (#3985).
130 let mut app = App::new(test_options(false), &Config::default());
131 app.onboarding = OnboardingState::None;
132 app.onboarding_needs_api_key = true;
133 let before = app.history.len();
134 app.maybe_show_feature_intro();
135 assert_eq!(
136 app.history.len(),
137 before,
138 "must not show 'setup is ready' when API key / auth is missing"
139 );
140 }
141 }
142
143 #[test]
144 fn feature_intro_shows_once_persists_then_is_idempotent() {
145 let _env_lock = lock_test_env();
146 let tmp = std::env::temp_dir().join(format!("cw-feature-intro-{}", std::process::id()));
147 let _ = std::fs::remove_dir_all(&tmp);
148 std::fs::create_dir_all(&tmp).unwrap();
149 let config_path = tmp.join("config.toml");
150 let _env = EnvVarGuard::set(
151 "DEEPSEEK_CONFIG_PATH",
152 config_path.to_string_lossy().as_ref(),
153 );
154 let _ = std::fs::remove_file(tmp.join("settings.toml"));
155
156 let mut app = App::new(test_options(false), &Config::default());
157 app.onboarding = OnboardingState::None;
158 // Isolated config has no key; pin readiness so the ready-tip path is exercised.
159 app.onboarding_needs_api_key = false;
160 let before = app.history.len();
161
162 app.maybe_show_feature_intro();
163 assert_eq!(app.history.len(), before, "intro must not hide empty state");
164 assert!(
165 app.visible_notice_text()
166 .as_deref()
167 .is_some_and(|message| message.contains("fleet") && message.contains("/fleet setup"))
168 );
169
170 // Persisted flag now set → a second call is a no-op.
171 assert!(
172 Settings::load()
173 .expect("settings should load")
174 .feature_intro_shown,
175 "feature_intro_shown should be persisted"
176 );
177 app.maybe_show_feature_intro();
178 assert_eq!(
179 app.history.len(),
180 before,
181 "intro must not repeat once the flag is persisted"
182 );
183
184 let _ = std::fs::remove_dir_all(&tmp);
185 }
186
187 #[test]
188 fn account_preferences_notice_shows_once_per_sign_in_and_can_be_dismissed() {
189 let _env_lock = lock_test_env();
190 let tmp = tempfile::tempdir().unwrap();
191 let config_path = tmp.path().join("config.toml");
192 let _env = EnvVarGuard::set(
193 "DEEPSEEK_CONFIG_PATH",
194 config_path.to_string_lossy().as_ref(),
195 );
196 let shown = |app: &App| {
197 let notice = app
198 .tr(MessageId::AccountPreferencesNotLoaded)
199 .replace("{command}", "codewhale login");
200 app.status_toasts
201 .iter()
202 .filter(|toast| toast.text == notice && toast.kind == StatusToastKind::Standing)
203 .count()
204 };
205
206 let mut app = App::new(test_options(false), &Config::default());
207 app.notify_account_preferences_not_loaded_for("first-sign-in");
208 app.notify_account_preferences_not_loaded_for("first-sign-in");
209 assert_eq!(shown(&app), 1);
210 assert_eq!(
211 Settings::load()
212 .expect("settings should load")
213 .account_preferences_notice_shown
214 .as_deref(),
215 Some("first-sign-in")
216 );
217 assert!(app.dismiss_account_preferences_notice());
218 assert_eq!(shown(&app), 0);
219
220 let mut later_session = App::new(test_options(false), &Config::default());
221 later_session.notify_account_preferences_not_loaded_for("first-sign-in");
222 assert_eq!(shown(&later_session), 0, "the same sign-in is told once");
223 later_session.notify_account_preferences_not_loaded_for("second-sign-in");
224 assert_eq!(shown(&later_session), 1, "a later sign-in is told again");
225 }
226
227 #[test]
228 fn initial_input_submit_marks_startup_dispatch() {
229 let mut options = test_options(false);
230 options.initial_input = Some(InitialInput::Submit(
231 "阅读项目 and wait for instructions".to_string(),
232 ));
233
234 let app = App::new(options, &Config::default());
235
236 assert!(
237 !app.launch.visible,
238 "an intentional submitted prompt must bypass the startup hero"
239 );
240 assert_eq!(app.input, "阅读项目 and wait for instructions");
241 assert_eq!(
242 app.cursor_position,
243 "阅读项目 and wait for instructions".chars().count()
244 );
245 assert!(app.auto_submit_initial_input);
246 }
247
248 #[test]
249 fn clean_launch_keeps_startup_hero_despite_a_startup_notice() {
250 let _env_lock = lock_test_env();
251 let tmp = tempfile::tempdir().expect("tempdir");
252 let config_path = tmp.path().join("config.toml");
253 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
254 std::fs::write(tmp.path().join("settings.toml"), "launch_screen = false\n")
255 .expect("legacy settings");
256 let mut options = test_options(false);
257 options.startup_notice =
258 Some("Provider route changed; inspect the route before sending".into());
259
260 let app = App::new(options, &Config::default());
261
262 assert!(
263 app.launch.visible,
264 "a fresh interactive launch must keep the Tideline startup hero visible; a notice is not an intentional resume or prompt"
265 );
266 }
267
268 #[test]
269 fn explicit_resume_bypasses_startup_hero() {
270 let _env_lock = lock_test_env();
271 let tmp = tempfile::tempdir().expect("tempdir");
272 let config_path = tmp.path().join("config.toml");
273 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
274 let mut options = test_options(false);
275 options.resume_session_id = Some("explicit-resume".into());
276
277 let app = App::new(options, &Config::default());
278
279 assert!(
280 !app.launch.visible,
281 "an explicit resume must preserve the existing session path"
282 );
283 }
284
285 #[test]
286 fn remote_control_initial_input_bypasses_startup_hero() {
287 let _env_lock = lock_test_env();
288 let tmp = tempfile::tempdir().expect("tempdir");
289 let config_path = tmp.path().join("config.toml");
290 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
291 let mut options = test_options(false);
292 options.initial_input = Some(InitialInput::RemoteControl);
293
294 let app = App::new(options, &Config::default());
295
296 assert!(
297 !app.launch.visible,
298 "an intentional remote-control launch must preserve its existing direct-session path"
299 );
300 }
301
302 #[test]
303 fn composer_arrows_scenario() {
304 // Scenario consolidation of: composer_arrows_scroll_default_is_true_without_mouse_capture, composer_arrows_scroll_default_is_false_with_mouse_capture_on_non_windows, composer_arrows_scroll_default_is_false_with_mouse_capture_on_windows, composer_arrows_scroll_default_is_true_without_mouse_capture_on_windows
305 // from composer_arrows_scroll_default_is_true_without_mouse_capture
306 {
307 assert!(default_composer_arrows_scroll_for_platform(false, false));
308 }
309 // from composer_arrows_scroll_default_is_false_with_mouse_capture_on_non_windows
310 {
311 assert!(!default_composer_arrows_scroll_for_platform(true, false));
312 }
313 // from composer_arrows_scroll_default_is_false_with_mouse_capture_on_windows
314 {
315 assert!(!default_composer_arrows_scroll_for_platform(true, true));
316 }
317 // from composer_arrows_scroll_default_is_true_without_mouse_capture_on_windows
318 {
319 assert!(default_composer_arrows_scroll_for_platform(false, true));
320 }
321 }
322
323 #[test]
324 fn move_cursor_scenario() {
325 // Scenario consolidation of: move_cursor_line_start_multiline, move_cursor_line_start_singleline, move_cursor_line_end_multiline, move_cursor_line_end_at_newline_stays_at_line_end, move_cursor_line_end_last_line, move_cursor_line_start_already_at_start
326 // from move_cursor_line_start_multiline
327 {
328 let mut app = App::new(test_options(false), &Config::default());
329 app.input = "abc\ndef\nghi".to_string();
330 app.cursor_position = "abc\ndef\nghi".chars().count(); // absolute end
331 app.move_cursor_line_start();
332 assert_eq!(app.cursor_position, "abc\ndef\n".len()); // start of "ghi"
333 }
334 // from move_cursor_line_start_singleline
335 {
336 let mut app = App::new(test_options(false), &Config::default());
337 app.input = "hello".to_string();
338 app.cursor_position = 3;
339 app.move_cursor_line_start();
340 assert_eq!(app.cursor_position, 0);
341 }
342 // from move_cursor_line_end_multiline
343 {
344 let mut app = App::new(test_options(false), &Config::default());
345 app.input = "abc\ndef\nghi".to_string();
346 app.cursor_position = 0; // start of first line
347 app.move_cursor_line_end();
348 assert_eq!(app.cursor_position, "abc".len()); // before first '\n'
349 }
350 // from move_cursor_line_end_at_newline_stays_at_line_end
351 {
352 let mut app = App::new(test_options(false), &Config::default());
353 app.input = "abc\ndef\nghi".to_string();
354 app.cursor_position = "abc".len(); // on the '\n'
355 app.move_cursor_line_end();
356 assert_eq!(app.cursor_position, "abc".len()); // stays at line end
357 }
358 // from move_cursor_line_end_last_line
359 {
360 let mut app = App::new(test_options(false), &Config::default());
361 app.input = "abc\ndef".to_string();
362 app.cursor_position = "abc\n".len(); // start of last line
363 app.move_cursor_line_end();
364 assert_eq!(app.cursor_position, "abc\ndef".chars().count()); // absolute end
365 }
366 // from move_cursor_line_start_already_at_start
367 {
368 let mut app = App::new(test_options(false), &Config::default());
369 app.input = "abc\ndef".to_string();
370 app.cursor_position = "abc\n".len(); // start of second line
371 app.move_cursor_line_start();
372 assert_eq!(app.cursor_position, "abc\n".len()); // unchanged
373 }
374 }
375
376 #[test]
377 fn test_trust_mode_follows_yolo_on_startup() {
378 let _env_lock = lock_test_env();
379 let tmp = tempfile::tempdir().expect("tempdir");
380 let config_path = tmp.path().join("config.toml");
381 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
382 let mut options = test_options(true);
383 options.config_path = Some(config_path);
384 let app = App::new(options, &Config::default());
385 assert!(app.trust_mode);
386 }
387
388 #[test]
389 fn reasoning_effort_display_label_keeps_codex_top_tiers_distinct() {
390 assert_eq!(
391 ReasoningEffort::Off.display_label_for_provider(ProviderKind::OpenaiCodex),
392 "low"
393 );
394 assert_eq!(
395 ReasoningEffort::Medium.display_label_for_provider(ProviderKind::OpenaiCodex),
396 "medium"
397 );
398 // The roster publishes xhigh, max and ultra as separate rungs, so the
399 // label must not collapse them onto the old ceiling.
400 assert_eq!(
401 ReasoningEffort::XHigh.display_label_for_provider(ProviderKind::OpenaiCodex),
402 "xhigh"
403 );
404 assert_eq!(
405 ReasoningEffort::Max.display_label_for_provider(ProviderKind::OpenaiCodex),
406 "max"
407 );
408 assert_eq!(
409 ReasoningEffort::Ultra.display_label_for_provider(ProviderKind::OpenaiCodex),
410 "ultra"
411 );
412 assert_eq!(
413 ReasoningEffort::Max.display_label_for_provider(ProviderKind::Deepseek),
414 "max"
415 );
416 assert_eq!(
417 ReasoningEffort::High.display_label_for_provider(ProviderKind::OpenaiCodex),
418 "high"
419 );
420
421 let mut app = App::new(test_options(false), &Config::default());
422 app.api_provider = ProviderKind::OpenaiCodex;
423 app.reasoning_effort = ReasoningEffort::Max;
424 app.auto_model = false;
425 assert_eq!(app.reasoning_effort_display_label(), "max");
426
427 app.reasoning_effort = ReasoningEffort::Auto;
428 app.last_effective_reasoning_effort =
429 Some(EffectiveReasoningEffort::Tier(ReasoningEffort::Max));
430 assert_eq!(app.reasoning_effort_display_label(), "auto→max");
431 }
432
433 #[test]
434 fn fixed_auto_reasoning_label_preserves_untiered_effective_receipt() {
435 let mut app = App::new(test_options(false), &Config::default());
436 app.api_provider = ProviderKind::Zai;
437 app.auto_model = false;
438 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL.to_string();
439 app.active_route_base_url =
440 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string();
441 app.reasoning_effort = ReasoningEffort::Auto;
442 app.last_effective_reasoning_effort =
443 Some(EffectiveReasoningEffort::ThinkingEnabledGranularityUnavailable);
444
445 assert_eq!(
446 app.reasoning_effort_display_label(),
447 "auto→thinking enabled; granularity unavailable"
448 );
449 }
450
451 #[test]
452 fn cache_replay_keeps_untiered_reasoning_enabled() {
453 let mut app = App::new(test_options(false), &Config::default());
454 app.api_provider = ProviderKind::Zai;
455 app.auto_model = false;
456 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL.to_string();
457 app.reasoning_effort = ReasoningEffort::Auto;
458 app.last_effective_reasoning_effort =
459 Some(EffectiveReasoningEffort::ThinkingEnabledGranularityUnavailable);
460
461 assert_eq!(
462 app.reasoning_effort_api_value_for_replay(
463 ProviderKind::Zai,
464 ProviderKind::Zai.as_str(),
465 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
466 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL,
467 ),
468 Some("high")
469 );
470
471 app.api_provider = ProviderKind::Minimax;
472 app.model = codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL.to_string();
473 assert_eq!(
474 app.reasoning_effort_api_value_for_replay(
475 ProviderKind::Minimax,
476 ProviderKind::Minimax.as_str(),
477 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL,
478 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL,
479 ),
480 Some("high")
481 );
482
483 app.last_effective_reasoning_effort = Some(EffectiveReasoningEffort::Unavailable);
484 assert_eq!(
485 app.reasoning_effort_api_value_for_replay(
486 ProviderKind::Zai,
487 ProviderKind::Zai.as_str(),
488 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
489 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL,
490 ),
491 None
492 );
493 }
494
495 #[test]
496 fn cache_replay_normalizes_reasoning_against_the_concrete_auto_route() {
497 let mut app = App::new(test_options(false), &Config::default());
498 app.api_provider = ProviderKind::Deepseek;
499 app.model = "auto".to_string();
500 app.auto_model = true;
501
502 app.reasoning_effort = ReasoningEffort::Off;
503 assert_eq!(
504 app.reasoning_effort_api_value_for_replay(
505 ProviderKind::OpenaiCodex,
506 ProviderKind::OpenaiCodex.as_str(),
507 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_BASE_URL,
508 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL,
509 ),
510 Some("low"),
511 "Codex must apply its Off-to-Low floor even when DeepSeek is configured"
512 );
513
514 app.reasoning_effort = ReasoningEffort::Medium;
515 assert_eq!(
516 app.reasoning_effort_api_value_for_replay(
517 ProviderKind::Moonshot,
518 ProviderKind::Moonshot.as_str(),
519 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
520 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
521 ),
522 Some("medium"),
523 "Kimi Code K3 must retain its exact-route Medium tier"
524 );
525 }
526
527 #[test]
528 fn cache_replay_target_uses_the_last_completed_auto_route() {
529 let mut app = App::new(test_options(false), &Config::default());
530 app.model = "auto".to_string();
531 app.auto_model = true;
532 app.last_effective_provider = Some(ProviderKind::OpenaiCodex);
533 app.last_effective_provider_identity = Some(ProviderKind::OpenaiCodex.as_str().to_string());
534 app.last_effective_model =
535 Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string());
536 app.session.last_base_url =
537 Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_BASE_URL.to_string());
538 app.push_turn_cache_record(TurnCacheRecord {
539 provider: Some(ProviderKind::OpenaiCodex),
540 provider_identity: Some(ProviderKind::OpenaiCodex.as_str().to_string()),
541 model: Some(
542 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(),
543 ),
544 auto_model: true,
545 input_tokens: 1,
546 output_tokens: 1,
547 cache_hit_tokens: None,
548 cache_miss_tokens: None,
549 cache_write_tokens: None,
550 reasoning_tokens: None,
551 cost_audit: None,
552 reasoning_replay_tokens: None,
553 recorded_at: std::time::Instant::now(),
554 });
555
556 let target = app
557 .cache_replay_target()
558 .expect("completed Auto route must be replayable");
559
560 assert_eq!(target.provider, ProviderKind::OpenaiCodex);
561 assert_eq!(target.provider_identity, ProviderKind::OpenaiCodex.as_str());
562 assert_eq!(
563 target.provider_id.as_deref(),
564 Some(ProviderKind::OpenaiCodex.as_str())
565 );
566 assert_eq!(
567 target.model,
568 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL
569 );
570 assert_eq!(
571 target.base_url.as_deref(),
572 Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_BASE_URL)
573 );
574
575 // A restored Auto session has no turn ring or raw endpoint. Once warmup
576 // safely re-resolves that route, its exact key becomes sufficient
577 // endpoint evidence for a following inspect.
578 app.session.turn_cache_history.clear();
579 app.session.last_base_url = None;
580 app.session.last_warmup_key = Some(CacheWarmupKey {
581 provider: ProviderKind::OpenaiCodex.as_str().to_string(),
582 model: codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(),
583 base_url: codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_BASE_URL
584 .to_string(),
585 static_prefix_hash: "static".to_string(),
586 tool_catalog_hash: "tools".to_string(),
587 project_pack_hash: "project".to_string(),
588 skills_hash: "skills".to_string(),
589 });
590 assert_eq!(
591 app.cache_replay_target()
592 .and_then(|target| target.base_url)
593 .as_deref(),
594 Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_BASE_URL)
595 );
596 }
597
598 #[test]
599 fn auto_reasoning_change_invalidates_the_previous_route_and_receipt() {
600 let mut app = App::new(test_options(false), &Config::default());
601 app.api_provider = ProviderKind::Deepseek;
602 app.model = "auto".to_string();
603 app.auto_model = true;
604 app.reasoning_effort = ReasoningEffort::Low;
605 app.reasoning_effort_preference = Some(ReasoningEffort::Low);
606 app.last_effective_provider = Some(ProviderKind::OpenaiCodex);
607 app.last_effective_provider_identity = Some(ProviderKind::OpenaiCodex.as_str().to_string());
608 app.last_effective_model =
609 Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string());
610 app.last_auto_route_receipt = Some(codewhale_engine::model_routing::AutoRouteReceipt {
611 tier: codewhale_engine::model_routing::AutoRouteTier::Strong,
612 pair: codewhale_engine::model_routing::AutoRoutePair {
613 strong: codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(),
614 fast: None,
615 },
616 scope: codewhale_engine::model_routing::AutoRouteScope::ResolvedProvider,
617 data_path: codewhale_engine::model_routing::AutoRouteDataPath::LocalHeuristic,
618 reason: codewhale_engine::model_routing::AutoRouteReason::LocalFallback(
619 codewhale_engine::model_routing::AutoRouteHeuristicReason::DeclaredDefault,
620 ),
621 decision: None,
622 router_failure: None,
623 });
624 app.last_effective_reasoning_effort =
625 Some(EffectiveReasoningEffort::Tier(ReasoningEffort::Max));
626
627 assert!(
628 app.cache_replay_target().is_some(),
629 "the completed route is replayable before its classifier input changes"
630 );
631
632 app.cycle_effort();
633
634 assert_eq!(app.reasoning_effort, ReasoningEffort::Medium);
635 assert_eq!(
636 app.status_toasts.back().map(|notice| notice.text.as_str()),
637 Some("Reasoning effort: med"),
638 "the change must describe the new unresolved request, not the old Codex receipt"
639 );
640 assert_eq!(app.last_effective_reasoning_effort, None);
641 assert_eq!(app.last_effective_provider, None);
642 assert_eq!(app.last_effective_provider_identity, None);
643 assert_eq!(app.last_effective_model, None);
644 assert_eq!(app.last_auto_route_receipt, None);
645 assert!(
646 app.cache_replay_target().is_none(),
647 "cache replay must wait for a route accepted under the new reasoning request"
648 );
649
650 let work = app
651 .work_state_snapshot()
652 .expect("Work snapshot")
653 .expect("effort activity creates graph state");
654 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
655 effective, ..
656 } = work
657 .graph
658 .expect("Work Graph")
659 .activities
660 .last()
661 .cloned()
662 .expect("effort activity");
663 assert_eq!(
664 effective,
665 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Medium,
666 "the activity receipt must not reuse the previous turn's effective tier"
667 );
668 }
669
670 #[test]
671 fn thinking_is_locked_but_mode_moves_while_a_turn_is_running() {
672 let mut app = App::new(test_options(false), &Config::default());
673 app.mode = AppMode::Agent;
674 app.reasoning_effort = ReasoningEffort::Max;
675 app.is_loading = true;
676
677 let before_effort = app.reasoning_effort;
678 app.cycle_effort();
679 assert_eq!(
680 app.reasoning_effort, before_effort,
681 "thinking must not change while busy"
682 );
683 assert!(
684 app.status_toasts
685 .back()
686 .map(|notice| notice.text.as_str())
687 .unwrap_or_default()
688 .contains("locked"),
689 "expected a 'locked' status message, got {:?}",
690 app.status_toasts.back()
691 );
692
693 app.select_mode(AppMode::Plan);
694 assert_ne!(app.mode, AppMode::Agent, "mode changes mid-turn");
695 }
696
697 #[test]
698 fn cycle_effort_updates_effort_status_and_compaction() {
699 // Ctrl+T parity with the hotbar's `reasoning.cycle` action: cycling the
700 // effort must surface a status message and refresh the compaction budget,
701 // not just silently flip the setting.
702 let mut app = App::new(test_options(false), &Config::default());
703 app.api_provider = ProviderKind::Deepseek;
704 app.auto_model = false;
705 app.reasoning_effort = ReasoningEffort::Off;
706 // Sentinel so the test can observe update_model_compaction_budget().
707 app.compact_threshold = 0;
708
709 app.cycle_effort();
710
711 assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
712 assert_eq!(app.reasoning_effort_preference, Some(ReasoningEffort::Low));
713 assert_eq!(
714 app.status_toasts.back().map(|notice| notice.text.as_str()),
715 Some("Reasoning effort: low"),
716 "Ctrl+T must give visible feedback like the hotbar action"
717 );
718 assert_ne!(
719 app.compact_threshold, 0,
720 "cycling effort must refresh the compaction budget"
721 );
722 assert!(app.needs_redraw);
723
724 let work = app
725 .work_state_snapshot()
726 .expect("Work snapshot")
727 .expect("effort activity creates graph state");
728 let graph = work.graph.expect("Work Graph");
729 let activity = graph.activities.last().expect("effort activity");
730 match activity {
731 codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
732 requested,
733 effective,
734 provider_kind,
735 provider,
736 operation,
737 ..
738 } => {
739 assert_eq!(
740 *requested,
741 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Low
742 );
743 assert_eq!(
744 *effective,
745 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Low
746 );
747 assert_eq!(*provider_kind, Some(ProviderKind::Deepseek));
748 assert_eq!(provider, "deepseek");
749 assert!(operation.is_none());
750 }
751 }
752 let wire = serde_json::to_value(activity).expect("serialize activity");
753 assert_eq!(wire["kind"], "reasoning_effort_changed");
754 assert!(
755 wire.get("text").is_none(),
756 "activity must not carry reasoning text"
757 );
758 }
759
760 #[test]
761 fn glm_5_turbo_records_enabled_with_granularity_unavailable() {
762 let mut app = App::new(test_options(false), &Config::default());
763 app.set_provider_identity_record(
764 codewhale_runtime::config::Config::default()
765 .resolve_provider_identity(ProviderKind::Zai.as_str())
766 .expect("captured fixture provider"),
767 );
768 app.auto_model = false;
769 app.active_route_base_url =
770 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string();
771 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL.to_string();
772 app.reasoning_effort = ReasoningEffort::High;
773
774 app.cycle_effort();
775
776 assert_eq!(app.reasoning_effort, ReasoningEffort::Max);
777 assert_eq!(
778 app.visible_notice_text().as_deref(),
779 Some("Reasoning effort: max→thinking enabled; granularity unavailable")
780 );
781 assert_eq!(
782 app.reasoning_effort_display_label(),
783 "max→thinking enabled; granularity unavailable"
784 );
785 let work = app
786 .work_state_snapshot()
787 .expect("Work snapshot")
788 .expect("effort activity creates graph state");
789 let activity = work
790 .graph
791 .expect("Work Graph")
792 .activities
793 .last()
794 .cloned()
795 .expect("effort activity");
796 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
797 requested,
798 effective,
799 provider,
800 ..
801 } = &activity;
802 assert_eq!(
803 *requested,
804 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Max
805 );
806 assert_eq!(
807 *effective,
808 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::ThinkingEnabledGranularityUnavailable
809 );
810 assert_eq!(provider, "zai");
811 assert_eq!(
812 serde_json::to_value(activity).expect("serialize activity")["effective"],
813 "thinking_enabled_granularity_unavailable"
814 );
815 }
816
817 #[test]
818 fn glm_5_1_records_enabled_with_granularity_unavailable() {
819 let mut app = App::new(test_options(false), &Config::default());
820 app.set_provider_identity_record(
821 codewhale_runtime::config::Config::default()
822 .resolve_provider_identity(ProviderKind::Zai.as_str())
823 .expect("captured fixture provider"),
824 );
825 app.auto_model = false;
826 app.active_route_base_url =
827 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string();
828 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_1_MODEL.to_string();
829 app.reasoning_effort = ReasoningEffort::High;
830
831 app.cycle_effort();
832
833 assert_eq!(
834 app.reasoning_effort_display_label(),
835 "max→thinking enabled; granularity unavailable"
836 );
837 let work = app
838 .work_state_snapshot()
839 .expect("Work snapshot")
840 .expect("effort activity creates graph state");
841 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
842 effective, ..
843 } = work
844 .graph
845 .expect("Work Graph")
846 .activities
847 .last()
848 .cloned()
849 .expect("effort activity");
850 assert_eq!(
851 effective,
852 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::ThinkingEnabledGranularityUnavailable
853 );
854 }
855
856 #[test]
857 fn unknown_model_on_exact_zai_endpoint_records_effective_unavailable() {
858 let mut app = App::new(test_options(false), &Config::default());
859 app.set_provider_identity_record(
860 codewhale_runtime::config::Config::default()
861 .resolve_provider_identity(ProviderKind::Zai.as_str())
862 .expect("captured fixture provider"),
863 );
864 app.auto_model = false;
865 app.active_route_base_url =
866 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string();
867 app.model = "glm-future-unknown".to_string();
868 app.reasoning_effort = ReasoningEffort::High;
869
870 app.cycle_effort();
871
872 assert_eq!(
873 app.reasoning_effort_display_label(),
874 "max→effective unavailable"
875 );
876 let work = app
877 .work_state_snapshot()
878 .expect("Work snapshot")
879 .expect("effort activity creates graph state");
880 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
881 effective, ..
882 } = work
883 .graph
884 .expect("Work Graph")
885 .activities
886 .last()
887 .cloned()
888 .expect("effort activity");
889 assert_eq!(
890 effective,
891 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Unavailable
892 );
893 }
894
895 #[test]
896 fn compatible_zai_gateway_records_effective_unavailable() {
897 let mut app = App::new(test_options(false), &Config::default());
898 app.set_provider_identity_record(
899 codewhale_runtime::config::Config::default()
900 .resolve_provider_identity(ProviderKind::Zai.as_str())
901 .expect("captured fixture provider"),
902 );
903 app.auto_model = false;
904 app.active_route_base_url = "https://gateway.example/v1".to_string();
905 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string();
906 app.reasoning_effort = ReasoningEffort::High;
907
908 app.cycle_effort();
909
910 assert_eq!(app.reasoning_effort, ReasoningEffort::Max);
911 assert_eq!(
912 app.visible_notice_text().as_deref(),
913 Some("Reasoning effort: max→effective unavailable")
914 );
915 assert_eq!(
916 app.reasoning_effort_display_label(),
917 "max→effective unavailable"
918 );
919 let work = app
920 .work_state_snapshot()
921 .expect("Work snapshot")
922 .expect("effort activity creates graph state");
923 let activity = work
924 .graph
925 .expect("Work Graph")
926 .activities
927 .last()
928 .cloned()
929 .expect("effort activity");
930 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
931 requested,
932 effective,
933 provider,
934 ..
935 } = &activity;
936 assert_eq!(
937 *requested,
938 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Max
939 );
940 assert_eq!(
941 *effective,
942 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Unavailable
943 );
944 assert_eq!(provider, "zai");
945 assert_eq!(
946 serde_json::to_value(activity).expect("serialize activity")["effective"],
947 "unavailable"
948 );
949 }
950
951 #[test]
952 fn minimax_m3_high_and_max_receipts_do_not_claim_tier_granularity() {
953 for (previous, requested, label) in [
954 (ReasoningEffort::Off, ReasoningEffort::Auto, "auto"),
955 (ReasoningEffort::Auto, ReasoningEffort::Off, "off"),
956 ] {
957 let mut app = App::new(test_options(false), &Config::default());
958 app.set_provider_identity_record(
959 codewhale_runtime::config::Config::default()
960 .resolve_provider_identity(ProviderKind::Minimax.as_str())
961 .expect("captured fixture provider"),
962 );
963 app.auto_model = false;
964 app.active_route_base_url =
965 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL.to_string();
966 app.model = codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL.to_string();
967 app.reasoning_effort = previous;
968
969 app.cycle_effort();
970
971 assert_eq!(app.reasoning_effort, requested);
972 assert_eq!(app.reasoning_effort_display_label(), label);
973 let work = app
974 .work_state_snapshot()
975 .expect("Work snapshot")
976 .expect("effort activity creates graph state");
977 let activity = work
978 .graph
979 .expect("Work Graph")
980 .activities
981 .last()
982 .cloned()
983 .expect("effort activity");
984 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
985 effective,
986 endpoint_identity,
987 model,
988 ..
989 } = activity;
990 assert_eq!(
991 effective,
992 if requested == ReasoningEffort::Auto {
993 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Auto
994 } else {
995 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Off
996 }
997 );
998 assert_eq!(
999 endpoint_identity.as_deref(),
1000 Some(codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_BASE_URL)
1001 );
1002 assert_eq!(
1003 model.as_deref(),
1004 Some(codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL)
1005 );
1006 }
1007 }
1008
1009 #[test]
1010 fn minimax_anthropic_m3_high_and_max_receipts_match_adaptive_wire_truth() {
1011 for (previous, requested, label) in [
1012 (ReasoningEffort::Off, ReasoningEffort::Auto, "auto"),
1013 (ReasoningEffort::Auto, ReasoningEffort::Off, "off"),
1014 ] {
1015 let mut app = App::new(test_options(false), &Config::default());
1016 app.set_provider_identity_record(
1017 codewhale_runtime::config::Config::default()
1018 .resolve_provider_identity(ProviderKind::MinimaxAnthropic.as_str())
1019 .expect("captured fixture provider"),
1020 );
1021 app.auto_model = false;
1022 app.active_route_base_url =
1023 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_ANTHROPIC_BASE_URL.to_string();
1024 app.model = codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL.to_string();
1025 app.reasoning_effort = previous;
1026
1027 app.cycle_effort();
1028
1029 assert_eq!(app.reasoning_effort, requested);
1030 assert_eq!(app.reasoning_effort_display_label(), label);
1031 let work = app
1032 .work_state_snapshot()
1033 .expect("Work snapshot")
1034 .expect("effort activity creates graph state");
1035 let activity = work
1036 .graph
1037 .expect("Work Graph")
1038 .activities
1039 .last()
1040 .cloned()
1041 .expect("effort activity");
1042 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
1043 effective,
1044 provider_kind,
1045 provider,
1046 endpoint_identity,
1047 model,
1048 ..
1049 } = activity;
1050 assert_eq!(
1051 effective,
1052 if requested == ReasoningEffort::Auto {
1053 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Auto
1054 } else {
1055 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Off
1056 }
1057 );
1058 assert_eq!(provider_kind, Some(ProviderKind::MinimaxAnthropic));
1059 assert_eq!(provider, "minimax-anthropic");
1060 assert_eq!(
1061 endpoint_identity.as_deref(),
1062 Some(codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_ANTHROPIC_BASE_URL)
1063 );
1064 assert_eq!(
1065 model.as_deref(),
1066 Some(codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL)
1067 );
1068 }
1069 }
1070
1071 #[test]
1072 fn named_custom_route_displays_and_persists_effective_unavailable() {
1073 let mut app = App::new(test_options(false), &Config::default());
1074 app.set_provider_identity(ProviderKind::Custom, "my-gateway");
1075 app.auto_model = false;
1076 app.active_route_base_url = "https://gateway.example/v1?api_key=must-not-persist".to_string();
1077 app.model = "vendor-model-x".to_string();
1078 app.reasoning_effort = ReasoningEffort::High;
1079
1080 app.cycle_effort();
1081
1082 assert_eq!(app.reasoning_effort, ReasoningEffort::Max);
1083 assert_eq!(
1084 app.reasoning_effort_display_label(),
1085 "max→effective unavailable"
1086 );
1087 let work = app
1088 .work_state_snapshot()
1089 .expect("Work snapshot")
1090 .expect("unknown route activity creates valid graph state");
1091 let activity = work
1092 .graph
1093 .expect("Work Graph")
1094 .activities
1095 .last()
1096 .cloned()
1097 .expect("effort activity");
1098 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
1099 effective,
1100 provider_kind,
1101 provider,
1102 endpoint_identity,
1103 model,
1104 ..
1105 } = activity;
1106 assert_eq!(
1107 effective,
1108 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Unavailable
1109 );
1110 assert_eq!(provider_kind, Some(ProviderKind::Custom));
1111 assert_eq!(provider, "my-gateway");
1112 let endpoint = endpoint_identity.expect("redacted endpoint provenance");
1113 assert!(endpoint.contains("gateway.example"), "{endpoint}");
1114 assert!(!endpoint.contains("must-not-persist"), "{endpoint}");
1115 assert_eq!(model.as_deref(), Some("vendor-model-x"));
1116 }
1117
1118 #[test]
1119 fn custom_routes_named_with_builtin_slugs_retain_custom_kind_and_fail_closed() {
1120 for identity in ["openai", "zai"] {
1121 let mut app = App::new(test_options(false), &Config::default());
1122 app.set_provider_identity(ProviderKind::Custom, identity);
1123 app.auto_model = false;
1124 app.active_route_base_url = "https://gateway.example/v1".to_string();
1125 app.model = "vendor-model-x".to_string();
1126 app.reasoning_effort = ReasoningEffort::High;
1127
1128 app.cycle_effort();
1129
1130 assert_eq!(
1131 app.reasoning_effort_display_label(),
1132 "max→effective unavailable"
1133 );
1134 let work = app
1135 .work_state_snapshot()
1136 .expect("Work snapshot")
1137 .expect("effort activity creates graph state");
1138 let activity = work
1139 .graph
1140 .expect("Work Graph")
1141 .activities
1142 .last()
1143 .cloned()
1144 .expect("effort activity");
1145 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
1146 effective,
1147 provider_kind,
1148 provider,
1149 ..
1150 } = activity;
1151 assert_eq!(
1152 effective,
1153 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Unavailable
1154 );
1155 assert_eq!(provider_kind, Some(ProviderKind::Custom));
1156 assert_eq!(provider, identity);
1157 }
1158 }
1159
1160 #[test]
1161 fn zai_gateway_off_and_high_receipts_remain_unavailable() {
1162 for (previous, requested, label) in [
1163 (ReasoningEffort::High, ReasoningEffort::Max, "max"),
1164 (ReasoningEffort::Max, ReasoningEffort::Auto, "auto"),
1165 ] {
1166 let mut app = App::new(test_options(false), &Config::default());
1167 app.set_provider_identity_record(
1168 codewhale_runtime::config::Config::default()
1169 .resolve_provider_identity(ProviderKind::Zai.as_str())
1170 .expect("captured fixture provider"),
1171 );
1172 app.auto_model = false;
1173 app.active_route_base_url = "https://gateway.example/v1".to_string();
1174 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string();
1175 app.reasoning_effort = previous;
1176
1177 app.cycle_effort();
1178
1179 assert_eq!(app.reasoning_effort, requested);
1180 assert_eq!(
1181 app.reasoning_effort_display_label(),
1182 format!("{label}→effective unavailable")
1183 );
1184 }
1185 }
1186
1187 #[test]
1188 fn kimi_code_high_and_max_work_receipts_preserve_exact_tiers() {
1189 for (previous, requested) in [
1190 (ReasoningEffort::Auto, ReasoningEffort::Low),
1191 (ReasoningEffort::High, ReasoningEffort::Max),
1192 ] {
1193 let mut app = App::new(test_options(false), &Config::default());
1194 app.set_provider_identity_record(
1195 codewhale_runtime::config::Config::default()
1196 .resolve_provider_identity(ProviderKind::Moonshot.as_str())
1197 .expect("captured fixture provider"),
1198 );
1199 app.auto_model = false;
1200 app.active_route_base_url =
1201 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL.to_string();
1202 app.model = codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL.to_string();
1203 app.reasoning_effort = previous;
1204
1205 app.cycle_effort();
1206
1207 let work = app
1208 .work_state_snapshot()
1209 .expect("Work snapshot")
1210 .expect("effort activity creates graph state");
1211 let activity = work
1212 .graph
1213 .expect("Work Graph")
1214 .activities
1215 .last()
1216 .cloned()
1217 .unwrap();
1218 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
1219 effective,
1220 endpoint_identity,
1221 model,
1222 ..
1223 } = activity;
1224 assert_eq!(effective, requested.into());
1225 assert_eq!(
1226 endpoint_identity.as_deref(),
1227 Some(codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL)
1228 );
1229 assert_eq!(
1230 model.as_deref(),
1231 Some(codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL)
1232 );
1233 }
1234 }
1235
1236 #[test]
1237 fn active_turn_zai_receipt_overrides_all_mutable_parallel_route_metadata() {
1238 let mut app = App::new(test_options(false), &Config::default());
1239 app.api_provider = ProviderKind::Deepseek;
1240 app.active_route_base_url =
1241 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL.to_string();
1242 app.model = "deepseek-chat".to_string();
1243 app.reasoning_effort = ReasoningEffort::High;
1244 app.active_turn = Some(ActiveTurnMetadata {
1245 turn_id: "turn-zai-receipt".to_string(),
1246 created_at: chrono::Utc::now(),
1247 route: Some(codewhale_engine::core::events::TurnRoute {
1248 provider: ProviderKind::Zai,
1249 provider_identity: "openai".to_string(),
1250 model: "mutable-wrong-model".to_string(),
1251 auto_model: false,
1252 receipt: Some(codewhale_engine::route_receipt::TurnRouteReceipt::new(
1253 ProviderKind::Zai,
1254 "zai",
1255 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL,
1256 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
1257 "test-secret-never-persisted",
1258 )),
1259 billing: Some(codewhale_engine::core::events::RouteBillingEnvelope {
1260 openrouter_vendor: None,
1261 billing_surface: None,
1262 endpoint_fingerprint: None,
1263 provider_live_pricing: None,
1264 billing_mode: codewhale_engine::cost_status::RouteBillingMode::Unknown,
1265 dispatched_at: chrono::Utc::now(),
1266 }),
1267 base_url: codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string(),
1268 billing_product: codewhale_engine::route_billing::RouteProduct::Unproven,
1269 }),
1270 auto_route_receipt: None,
1271 suggestion_authority: None,
1272 });
1273
1274 assert_eq!(
1275 app.reasoning_effort_display_label(),
1276 "high→thinking enabled; granularity unavailable"
1277 );
1278
1279 app.apply_reasoning_effort_cycle().unwrap();
1280 let work = app
1281 .work_state_snapshot()
1282 .expect("Work snapshot")
1283 .expect("effort activity creates graph state");
1284 let activity = work
1285 .graph
1286 .expect("Work Graph")
1287 .activities
1288 .last()
1289 .cloned()
1290 .expect("effort activity");
1291 let codewhale_engine::work_graph::WorkActivityEvent::ReasoningEffortChanged {
1292 provider_kind,
1293 provider,
1294 endpoint_identity,
1295 model,
1296 ..
1297 } = activity;
1298 assert_eq!(provider_kind, Some(ProviderKind::Zai));
1299 assert_eq!(provider, "zai");
1300 assert_eq!(
1301 endpoint_identity.as_deref(),
1302 Some(codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL)
1303 );
1304 assert_eq!(
1305 model.as_deref(),
1306 Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL)
1307 );
1308 }
1309
1310 #[test]
1311 fn pending_zai_route_without_endpoint_receipt_is_effective_unavailable() {
1312 let mut app = App::new(test_options(false), &Config::default());
1313 app.api_provider = ProviderKind::Deepseek;
1314 app.auto_model = false;
1315 app.reasoning_effort = ReasoningEffort::Max;
1316 app.pending_turn_route = Some((
1317 ProviderKind::Zai,
1318 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string(),
1319 true,
1320 ));
1321
1322 assert_eq!(
1323 app.reasoning_effort_display_label(),
1324 "max→effective unavailable"
1325 );
1326 }
1327
1328 #[test]
1329 fn reasoning_effort_scenario() {
1330 // Scenario consolidation of: reasoning_effort_display_receipts_route_normalization, reasoning_effort_api_values_are_provider_aware_for_codex
1331 // from reasoning_effort_display_receipts_route_normalization
1332 {
1333 let mut app = App::new(test_options(false), &Config::default());
1334 app.api_provider = ProviderKind::Moonshot;
1335 app.auto_model = false;
1336 app.reasoning_effort = ReasoningEffort::Low;
1337 app.active_route_base_url =
1338 codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL.to_string();
1339 app.model = "kimi-k2.5".to_string();
1340
1341 assert_eq!(app.reasoning_effort_display_label(), "low→high");
1342
1343 app.active_route_base_url =
1344 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL.to_string();
1345 app.model = "k3".to_string();
1346 assert_eq!(app.reasoning_effort_display_label(), "low");
1347
1348 app.reasoning_effort = ReasoningEffort::Off;
1349 assert_eq!(app.reasoning_effort_display_label(), "off→low");
1350 }
1351 // from reasoning_effort_api_values_are_provider_aware_for_codex
1352 {
1353 assert_eq!(
1354 ReasoningEffort::Off.normalize_for_provider(ProviderKind::OpenaiCodex),
1355 ReasoningEffort::Low
1356 );
1357 assert_eq!(
1358 ReasoningEffort::Auto.normalize_for_provider(ProviderKind::OpenaiCodex),
1359 ReasoningEffort::Medium
1360 );
1361 // Codex sends the rung the operator picked: the roster offers xhigh,
1362 // max and ultra as separate efforts per model.
1363 assert_eq!(
1364 ReasoningEffort::XHigh.api_value_for_provider(ProviderKind::OpenaiCodex),
1365 Some("xhigh")
1366 );
1367 assert_eq!(
1368 ReasoningEffort::Max.api_value_for_provider(ProviderKind::OpenaiCodex),
1369 Some("max")
1370 );
1371 assert_eq!(
1372 ReasoningEffort::Ultra.api_value_for_provider(ProviderKind::OpenaiCodex),
1373 Some("ultra")
1374 );
1375 assert_eq!(
1376 ReasoningEffort::Off.api_value_for_provider(ProviderKind::OpenaiCodex),
1377 Some("low")
1378 );
1379 assert_eq!(
1380 ReasoningEffort::Max.api_value_for_provider(ProviderKind::Deepseek),
1381 Some("max")
1382 );
1383 assert_eq!(
1384 ReasoningEffort::from_setting("ultracode"),
1385 ReasoningEffort::Ultra
1386 );
1387 }
1388 }
1389
1390 #[test]
1391 fn ollama_cloud_normal_turns_preserve_the_documented_reasoning_ladder() {
1392 let base_url = codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_BASE_URL;
1393 let model = codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_MODEL;
1394 for effort in [
1395 ReasoningEffort::Off,
1396 ReasoningEffort::Low,
1397 ReasoningEffort::Medium,
1398 ReasoningEffort::High,
1399 ReasoningEffort::Max,
1400 ] {
1401 assert_eq!(
1402 effort.normalize_for_route(ProviderKind::OllamaCloud, base_url, model),
1403 effort,
1404 "{effort:?} must remain distinct on Ollama's documented Cloud ladder"
1405 );
1406 }
1407 assert_eq!(
1408 ReasoningEffort::Minimal.normalize_for_route(ProviderKind::OllamaCloud, base_url, model,),
1409 ReasoningEffort::Low
1410 );
1411 assert_eq!(
1412 ReasoningEffort::XHigh.normalize_for_route(ProviderKind::OllamaCloud, base_url, model),
1413 ReasoningEffort::Max
1414 );
1415 }
1416
1417 #[test]
1418 fn reasoning_effort_uses_one_strict_alias_table_and_legacy_fallback() {
1419 for raw in ["off", "none", "disabled", "false"] {
1420 assert_eq!(ReasoningEffort::parse_strict(raw), Ok(ReasoningEffort::Off));
1421 }
1422 for raw in ["low", "minimum", "light"] {
1423 assert_eq!(ReasoningEffort::parse_strict(raw), Ok(ReasoningEffort::Low));
1424 }
1425 // `minimal` is its own rung: `parse_strict(as_setting(Minimal))` must not
1426 // lose the variant by collapsing it onto `Low` (Slice 4, D3).
1427 assert_eq!(
1428 ReasoningEffort::parse_strict("minimal"),
1429 Ok(ReasoningEffort::Minimal)
1430 );
1431 for raw in ["medium", "mid"] {
1432 assert_eq!(
1433 ReasoningEffort::parse_strict(raw),
1434 Ok(ReasoningEffort::Medium)
1435 );
1436 }
1437 assert_eq!(
1438 ReasoningEffort::parse_strict("xhigh"),
1439 Ok(ReasoningEffort::XHigh)
1440 );
1441 for raw in ["ultra", "ultracode"] {
1442 assert_eq!(
1443 ReasoningEffort::parse_strict(raw),
1444 Ok(ReasoningEffort::Ultra)
1445 );
1446 }
1447 for raw in ["max", "maximum"] {
1448 assert_eq!(ReasoningEffort::parse_strict(raw), Ok(ReasoningEffort::Max));
1449 }
1450 assert!(ReasoningEffort::parse_strict("surprise").is_err());
1451 assert_eq!(
1452 ReasoningEffort::from_setting("surprise"),
1453 ReasoningEffort::Auto
1454 );
1455 }
1456
1457 #[test]
1458 fn reasoning_effort_normalizes_each_exact_k3_route_without_neighbor_leakage() {
1459 let kimi_base = codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL;
1460 let moonshot_base = codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL;
1461 assert_eq!(
1462 ReasoningEffort::Off.normalize_for_route(ProviderKind::Moonshot, kimi_base, "k3"),
1463 ReasoningEffort::Low,
1464 "membership K3 stays on K3 by mapping off to its lowest thinking tier"
1465 );
1466 assert_eq!(
1467 ReasoningEffort::Auto.normalize_for_route(ProviderKind::Moonshot, kimi_base, "k3"),
1468 ReasoningEffort::Auto,
1469 "route normalization preserves the Auto sentinel until dispatch selects a concrete tier"
1470 );
1471 assert_eq!(
1472 ReasoningEffort::Low.normalize_for_route(ProviderKind::Moonshot, kimi_base, "k3"),
1473 ReasoningEffort::Low
1474 );
1475 assert_eq!(
1476 ReasoningEffort::Medium.normalize_for_route(ProviderKind::Moonshot, kimi_base, "k3"),
1477 ReasoningEffort::Medium
1478 );
1479 assert_eq!(
1480 ReasoningEffort::Low.normalize_for_route(ProviderKind::Moonshot, moonshot_base, "k3"),
1481 ReasoningEffort::High
1482 );
1483 assert_eq!(
1484 ReasoningEffort::Medium.normalize_for_route(
1485 ProviderKind::Moonshot,
1486 kimi_base,
1487 "kimi-for-coding",
1488 ),
1489 ReasoningEffort::High
1490 );
1491
1492 assert_eq!(
1493 ReasoningEffort::Off.normalize_for_route(
1494 ProviderKind::Moonshot,
1495 moonshot_base,
1496 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
1497 ),
1498 ReasoningEffort::Low,
1499 "direct K3 is always-thinking, so off becomes its lowest supported tier"
1500 );
1501 assert_eq!(
1502 ReasoningEffort::Low.normalize_for_route(
1503 ProviderKind::Moonshot,
1504 moonshot_base,
1505 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
1506 ),
1507 ReasoningEffort::Low
1508 );
1509 assert_eq!(
1510 ReasoningEffort::Medium.normalize_for_route(
1511 ProviderKind::Moonshot,
1512 moonshot_base,
1513 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
1514 ),
1515 ReasoningEffort::High
1516 );
1517 assert_eq!(
1518 ReasoningEffort::Off.normalize_for_route(
1519 ProviderKind::Moonshot,
1520 "https://proxy.example/v1",
1521 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL,
1522 ),
1523 ReasoningEffort::Off,
1524 "a neighboring gateway must not inherit direct-platform always-thinking semantics"
1525 );
1526 }
1527
1528 #[test]
1529 fn picker_uses_scenario() {
1530 // Scenario consolidation of: picker_uses_catalog_reasoning_efforts_for_grok_46, picker_uses_catalog_reasoning_efforts_for_grok_45
1531 // from picker_uses_catalog_reasoning_efforts_for_grok_46
1532 {
1533 let labels: Vec<&str> = crate::tui::model_picker::picker_efforts_for_route(
1534 ProviderKind::Xai,
1535 ProviderKind::Xai.provider().default_base_url(),
1536 codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL,
1537 false,
1538 )
1539 .iter()
1540 .map(|effort| effort.as_setting())
1541 .collect();
1542 assert_eq!(labels, vec!["auto", "low", "medium", "high", "xhigh"]);
1543 }
1544 // from picker_uses_catalog_reasoning_efforts_for_grok_45
1545 {
1546 let labels: Vec<&str> = crate::tui::model_picker::picker_efforts_for_route(
1547 ProviderKind::Xai,
1548 ProviderKind::Xai.provider().default_base_url(),
1549 codewhale_config::catalog::reviewed::constants::XAI_GROK_4_5_MODEL,
1550 false,
1551 )
1552 .iter()
1553 .map(|effort| effort.as_setting())
1554 .collect();
1555 assert_eq!(labels, vec!["auto", "low", "medium", "high"]);
1556 }
1557 }
1558
1559 #[test]
1560 fn reasoning_effort_preserves_grok_46_ladder_only_on_exact_xai_route() {
1561 let xai = codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL;
1562 let model = codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL;
1563 for (requested, expected) in [
1564 (ReasoningEffort::Off, ReasoningEffort::High),
1565 (ReasoningEffort::Low, ReasoningEffort::Low),
1566 (ReasoningEffort::Medium, ReasoningEffort::Medium),
1567 (ReasoningEffort::High, ReasoningEffort::High),
1568 (ReasoningEffort::XHigh, ReasoningEffort::XHigh),
1569 (ReasoningEffort::Max, ReasoningEffort::XHigh),
1570 (ReasoningEffort::Ultra, ReasoningEffort::XHigh),
1571 (ReasoningEffort::Auto, ReasoningEffort::Auto),
1572 ] {
1573 assert_eq!(
1574 requested.normalize_for_route(ProviderKind::Xai, xai, model),
1575 expected,
1576 "{requested:?}"
1577 );
1578 }
1579 assert_eq!(
1580 ReasoningEffort::Medium.normalize_for_route(
1581 ProviderKind::Xai,
1582 "https://gateway.example/v1",
1583 model,
1584 ),
1585 ReasoningEffort::High,
1586 "a custom endpoint must not inherit the official catalog effort ladder"
1587 );
1588 let custom = "https://gateway.example/v1";
1589 assert!(ReasoningEffort::offering_for_reasoning(ProviderKind::Xai, custom, model).is_none());
1590 assert!(ReasoningEffort::catalog_effort_values(ProviderKind::Xai, custom, model).is_none());
1591 assert_eq!(
1592 crate::tui::model_picker::picker_efforts_for_route(ProviderKind::Xai, custom, model, false),
1593 vec![
1594 ReasoningEffort::Auto,
1595 ReasoningEffort::Off,
1596 ReasoningEffort::High,
1597 ReasoningEffort::Max,
1598 ]
1599 );
1600 }
1601
1602 fn xai_grok_46_startup_config() -> Config {
1603 {
1604 let __cw_config_init_0_0 = Some("xai".to_string());
1605 let __cw_config_init_0_1 = Some(ProvidersConfig {
1606 xai: ProviderConfig {
1607 api_key: Some("xai-startup-test-key".to_string()),
1608 base_url: Some(
1609 codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL.to_string(),
1610 ),
1611 model: Some(
1612 codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL.to_string(),
1613 ),
1614 ..ProviderConfig::default()
1615 },
1616 ..ProvidersConfig::default()
1617 });
1618 let mut __cw_config_init_0_value: Config = Config::default();
1619 __cw_config_init_0_value.provider = __cw_config_init_0_0;
1620 __cw_config_init_0_value.providers = __cw_config_init_0_1;
1621 __cw_config_init_0_value
1622 }
1623 }
1624
1625 fn xai_grok_46_startup_app(config: &Config) -> App {
1626 let mut options = test_options(false);
1627 options.model = codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL.to_string();
1628 App::new(options, config)
1629 }
1630
1631 #[test]
1632 fn app_new_scenario() {
1633 // Scenario consolidation of: app_new_uses_grok_46_official_high_when_effort_is_unset, app_new_maps_persisted_grok_46_off_to_high_and_max_to_xhigh, app_new_defaults_auto_compact_on_for_256k_class_models_when_unset, app_new_defaults_auto_compact_on_for_v4_class_models_when_unset, app_new_respects_explicit_auto_compact_false_for_256k_class_models, app_new_respects_explicit_auto_compact_false_for_v4_class_models, app_new_with_explicit_api_key_does_not_trigger_onboarding, app_new_respects_allow_shell_option_when_not_yolo
1634 // from app_new_uses_grok_46_official_high_when_effort_is_unset
1635 {
1636 let _lock = lock_test_env();
1637 let tmp = tempfile::TempDir::new().expect("tempdir");
1638 let config_path = tmp.path().join("config.toml");
1639 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1640 let config = xai_grok_46_startup_config();
1641 let app = xai_grok_46_startup_app(&config);
1642
1643 assert_eq!(app.api_provider, ProviderKind::Xai);
1644 assert_eq!(
1645 app.model,
1646 codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL
1647 );
1648 assert_eq!(
1649 app.active_route_base_url,
1650 codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL
1651 );
1652 assert_eq!(app.reasoning_effort, ReasoningEffort::High);
1653 assert_eq!(app.reasoning_effort_display_label(), "high");
1654 }
1655 // from app_new_maps_persisted_grok_46_off_to_high_and_max_to_xhigh
1656 {
1657 let _lock = lock_test_env();
1658 let tmp = tempfile::TempDir::new().expect("tempdir");
1659 let config_path = tmp.path().join("config.toml");
1660 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1661 let config = xai_grok_46_startup_config();
1662
1663 for (raw, expected, display) in [
1664 ("off", ReasoningEffort::High, "high"),
1665 ("max", ReasoningEffort::XHigh, "xhigh"),
1666 ("auto", ReasoningEffort::Auto, "auto"),
1667 ] {
1668 std::fs::write(
1669 tmp.path().join("settings.toml"),
1670 format!("reasoning_effort = \"{raw}\"\n"),
1671 )
1672 .expect("settings");
1673
1674 let app = xai_grok_46_startup_app(&config);
1675 assert_eq!(app.reasoning_effort, expected, "raw setting {raw}");
1676 assert_eq!(app.reasoning_effort_display_label(), display);
1677 }
1678 }
1679 // from app_new_defaults_auto_compact_on_for_256k_class_models_when_unset
1680 {
1681 let _lock = lock_test_env();
1682 let tmp = tempfile::TempDir::new().expect("tempdir");
1683 let config_path = tmp.path().join("config.toml");
1684 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1685
1686 let mut options = test_options(false);
1687 options.model = "trinity-large-thinking".to_string();
1688 let app = App::new(options, &Config::default());
1689
1690 assert!(app.auto_compact);
1691 assert!(!app.auto_compact_user_configured);
1692 assert_eq!(app.auto_compact_threshold_percent, 80.0);
1693 assert_eq!(app.compact_threshold, 195_584);
1694 }
1695 // from app_new_defaults_auto_compact_on_for_v4_class_models_when_unset
1696 {
1697 let _lock = lock_test_env();
1698 let tmp = tempfile::TempDir::new().expect("tempdir");
1699 let config_path = tmp.path().join("config.toml");
1700 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1701
1702 let mut options = test_options(false);
1703 options.model = "deepseek-v4-pro".to_string();
1704 let app = App::new(options, &Config::default());
1705
1706 assert!(app.auto_compact);
1707 assert!(!app.auto_compact_user_configured);
1708 assert_eq!(app.auto_compact_threshold_percent, 80.0);
1709 assert_eq!(app.compact_threshold, 800_000);
1710 }
1711 // from app_new_respects_explicit_auto_compact_false_for_256k_class_models
1712 {
1713 let _lock = lock_test_env();
1714 let tmp = tempfile::TempDir::new().expect("tempdir");
1715 let config_path = tmp.path().join("config.toml");
1716 std::fs::write(tmp.path().join("settings.toml"), "auto_compact = false\n")
1717 .expect("settings");
1718 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1719
1720 let mut options = test_options(false);
1721 options.model = "trinity-large-thinking".to_string();
1722 let app = App::new(options, &Config::default());
1723
1724 assert!(!app.auto_compact);
1725 assert!(app.auto_compact_user_configured);
1726 assert_eq!(app.compact_threshold, 195_584);
1727 }
1728 // from app_new_respects_explicit_auto_compact_false_for_v4_class_models
1729 {
1730 let _lock = lock_test_env();
1731 let tmp = tempfile::TempDir::new().expect("tempdir");
1732 let config_path = tmp.path().join("config.toml");
1733 std::fs::write(tmp.path().join("settings.toml"), "auto_compact = false\n")
1734 .expect("settings");
1735 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1736
1737 let mut options = test_options(false);
1738 options.model = "deepseek-v4-pro".to_string();
1739 let app = App::new(options, &Config::default());
1740
1741 assert!(!app.auto_compact);
1742 assert!(app.auto_compact_user_configured);
1743 assert_eq!(app.compact_threshold, 800_000);
1744 }
1745 // from app_new_with_explicit_api_key_does_not_trigger_onboarding
1746 {
1747 let _lock = lock_test_env();
1748 let tmp = tempfile::TempDir::new().expect("tempdir");
1749 let config_path = tmp.path().join("config.toml");
1750 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1751 let _provider_env = EnvVarGuard::remove("CODEWHALE_PROVIDER");
1752 let _legacy_provider_env = EnvVarGuard::remove("DEEPSEEK_PROVIDER");
1753
1754 let config =
1755 Config::default().with_legacy_root(Some("sk-test-onboarding-key".to_string()), None);
1756 let app = App::new(test_options(false), &config);
1757 assert!(
1758 !app.onboarding_needs_api_key,
1759 "explicit config.api_key must satisfy the onboarding check"
1760 );
1761 }
1762 // from app_new_respects_allow_shell_option_when_not_yolo
1763 {
1764 let mut options = test_options(false);
1765 options.allow_shell = false;
1766 options.start_in_agent_mode = true; // avoid coupling to settings.default_mode
1767 let app = App::new(options, &Config::default());
1768 assert!(!app.allow_shell);
1769 }
1770 }
1771
1772 #[test]
1773 fn cycle_effort_scenario() {
1774 // Scenario consolidation of: cycle_effort_walks_grok_46_official_ladder, cycle_effort_walks_grok_45_official_ladder_without_xhigh
1775 // from cycle_effort_walks_grok_46_official_ladder
1776 {
1777 let mut app = App::new(test_options(false), &Config::default());
1778 app.set_provider_identity_record(
1779 codewhale_runtime::config::Config::default()
1780 .resolve_provider_identity(ProviderKind::Xai.as_str())
1781 .expect("captured fixture provider"),
1782 );
1783 app.auto_model = false;
1784 app.active_route_base_url =
1785 codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL.to_string();
1786 app.model = codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL.to_string();
1787 app.reasoning_effort = ReasoningEffort::High;
1788
1789 let expected = [
1790 ReasoningEffort::XHigh,
1791 ReasoningEffort::Auto,
1792 ReasoningEffort::Low,
1793 ReasoningEffort::Medium,
1794 ReasoningEffort::High,
1795 ];
1796 for next in expected {
1797 app.cycle_effort();
1798 assert_eq!(app.reasoning_effort, next, "next {:?}", next);
1799 }
1800 }
1801 // from cycle_effort_walks_grok_45_official_ladder_without_xhigh
1802 {
1803 let mut app = App::new(test_options(false), &Config::default());
1804 app.set_provider_identity_record(
1805 codewhale_runtime::config::Config::default()
1806 .resolve_provider_identity(ProviderKind::Xai.as_str())
1807 .expect("captured fixture provider"),
1808 );
1809 app.auto_model = false;
1810 app.active_route_base_url =
1811 codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL.to_string();
1812 app.model = codewhale_config::catalog::reviewed::constants::XAI_GROK_4_5_MODEL.to_string();
1813 app.reasoning_effort = ReasoningEffort::High;
1814
1815 app.cycle_effort();
1816 assert_eq!(app.reasoning_effort, ReasoningEffort::Auto);
1817 app.cycle_effort();
1818 assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
1819 app.cycle_effort();
1820 assert_eq!(app.reasoning_effort, ReasoningEffort::Medium);
1821 app.cycle_effort();
1822 assert_eq!(app.reasoning_effort, ReasoningEffort::High);
1823 }
1824 }
1825
1826 #[test]
1827 fn set_model_selection_normalizes_codex_fixed_model_effort() {
1828 let mut app = App::new(test_options(false), &Config::default());
1829 app.api_provider = ProviderKind::OpenaiCodex;
1830 app.reasoning_effort = ReasoningEffort::Off;
1831 app.reasoning_effort_preference = Some(ReasoningEffort::Off);
1832
1833 app.set_model_selection("gpt-5.5-codex".to_string());
1834
1835 assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
1836 assert_eq!(app.reasoning_effort_preference, Some(ReasoningEffort::Off));
1837 assert!(!app.auto_model);
1838 assert_eq!(app.reasoning_effort_display_label(), "low");
1839 }
1840
1841 #[test]
1842 fn auto_model_selection_preserves_only_explicit_reasoning_effort() {
1843 let mut app = App::new(test_options(false), &Config::default());
1844 app.reasoning_effort = ReasoningEffort::Max;
1845 app.reasoning_effort_preference = None;
1846
1847 app.set_model_selection("auto".to_string());
1848
1849 assert!(app.auto_model);
1850 assert_eq!(app.reasoning_effort, ReasoningEffort::Auto);
1851 assert_eq!(app.reasoning_effort_preference, None);
1852
1853 for (provider, requested, normalized) in [
1854 (
1855 ProviderKind::Deepseek,
1856 ReasoningEffort::Low,
1857 ReasoningEffort::High,
1858 ),
1859 (
1860 ProviderKind::OpenaiCodex,
1861 ReasoningEffort::Off,
1862 ReasoningEffort::Low,
1863 ),
1864 ] {
1865 app.api_provider = provider;
1866 app.auto_model = false;
1867 app.model = "fixed-model".to_string();
1868 app.reasoning_effort = normalized;
1869 app.reasoning_effort_preference = Some(requested);
1870
1871 app.set_model_selection("auto".to_string());
1872
1873 assert_eq!(app.reasoning_effort, requested, "{provider:?}");
1874 assert_eq!(
1875 app.reasoning_effort_preference,
1876 Some(requested),
1877 "{provider:?}"
1878 );
1879 }
1880 }
1881
1882 #[test]
1883 fn app_new_normalizes_saved_codex_reasoning_effort() {
1884 let _lock = lock_test_env();
1885 let tmp = tempfile::TempDir::new().expect("tempdir");
1886 let config_path = tmp.path().join("config.toml");
1887 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1888 let _token = EnvVarGuard::set("OPENAI_CODEX_ACCESS_TOKEN", "test-codex-startup-token");
1889 let config = {
1890 let __cw_config_init_2_0 = Some("openai-codex".to_string());
1891 let __cw_config_init_2_1 = Some(ProvidersConfig {
1892 openai_codex: ProviderConfig {
1893 model: Some(
1894 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(),
1895 ),
1896 ..ProviderConfig::default()
1897 },
1898 ..ProvidersConfig::default()
1899 });
1900 let mut __cw_config_init_2_value: Config = Config::default();
1901 __cw_config_init_2_value.provider = __cw_config_init_2_0;
1902 __cw_config_init_2_value.providers = __cw_config_init_2_1;
1903 __cw_config_init_2_value
1904 };
1905
1906 for (raw, expected, display) in [
1907 ("off", ReasoningEffort::Low, "low"),
1908 ("auto", ReasoningEffort::Medium, "medium"),
1909 ("max", ReasoningEffort::Max, "max"),
1910 ("xhigh", ReasoningEffort::XHigh, "xhigh"),
1911 ("ultra", ReasoningEffort::Ultra, "ultra"),
1912 ] {
1913 std::fs::write(
1914 tmp.path().join("settings.toml"),
1915 format!("reasoning_effort = \"{raw}\"\n"),
1916 )
1917 .expect("settings");
1918
1919 let app = App::new(test_options(false), &config);
1920
1921 assert_eq!(app.api_provider, ProviderKind::OpenaiCodex);
1922 assert_eq!(app.reasoning_effort, expected, "raw setting {raw}");
1923 assert_eq!(
1924 app.reasoning_effort_preference,
1925 Some(ReasoningEffort::from_setting(raw)),
1926 "raw setting {raw}"
1927 );
1928 assert_eq!(app.reasoning_effort_display_label(), display);
1929 }
1930 }
1931
1932 #[test]
1933 fn app_new_exposes_direct_moonshot_k3_off_as_effective_low() {
1934 let _lock = lock_test_env();
1935 let tmp = tempfile::TempDir::new().expect("tempdir");
1936 let config_path = tmp.path().join("config.toml");
1937 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1938 std::fs::write(
1939 tmp.path().join("settings.toml"),
1940 "reasoning_effort = \"off\"\n",
1941 )
1942 .expect("settings");
1943 let config = {
1944 let __cw_config_init_3_0 = Some("moonshot".to_string());
1945 let __cw_config_init_3_1 = Some(ProvidersConfig {
1946 moonshot: ProviderConfig {
1947 api_key: Some("moonshot-startup-test-key".to_string()),
1948 base_url: Some(
1949 codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL.to_string(),
1950 ),
1951 model: Some(
1952 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL
1953 .to_string(),
1954 ),
1955 ..ProviderConfig::default()
1956 },
1957 ..ProvidersConfig::default()
1958 });
1959 let mut __cw_config_init_3_value: Config = Config::default();
1960 __cw_config_init_3_value.provider = __cw_config_init_3_0;
1961 __cw_config_init_3_value.providers = __cw_config_init_3_1;
1962 __cw_config_init_3_value
1963 };
1964
1965 let mut options = test_options(false);
1966 options.model =
1967 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL.to_string();
1968 let app = App::new(options, &config);
1969
1970 assert_eq!(app.api_provider, ProviderKind::Moonshot);
1971 assert_eq!(
1972 app.model,
1973 codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL
1974 );
1975 assert_eq!(
1976 app.active_route_base_url,
1977 codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL
1978 );
1979 assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
1980 assert_eq!(app.reasoning_effort_display_label(), "low");
1981 }
1982
1983 #[test]
1984 fn codex_startup_threads_fresh_roster_context_into_active_route_limits() {
1985 let _lock = lock_test_env();
1986 let tmp = tempfile::tempdir().expect("tempdir");
1987 let canonical_home = tmp
1988 .path()
1989 .canonicalize()
1990 .expect("canonical private fixture home");
1991 let config_path = tmp.path().join("config.toml");
1992 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
1993 let _home = EnvVarGuard::set("CODEWHALE_HOME", &canonical_home);
1994 let mut config = {
1995 let __cw_config_init_4_0 = Some("openai-codex".to_string());
1996 let __cw_config_init_4_1 = Some(ProvidersConfig {
1997 openai_codex: ProviderConfig {
1998 model: Some(
1999 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(),
2000 ),
2001 ..ProviderConfig::default()
2002 },
2003 ..ProvidersConfig::default()
2004 });
2005 let mut __cw_config_init_4_value: Config = Config::default();
2006 __cw_config_init_4_value.provider = __cw_config_init_4_0;
2007 __cw_config_init_4_value.providers = __cw_config_init_4_1;
2008 __cw_config_init_4_value
2009 };
2010
2011 codewhale_runtime::oauth::install_test_chatgpt_registration(&mut config)
2012 .expect("owned ChatGPT registration");
2013 codewhale_runtime::codex_model_roster::install_test_chatgpt_roster_with_metadata(
2014 &config,
2015 vec![codewhale_runtime::codex_model_roster::CodexModelMetadata {
2016 id: codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(),
2017 display_name: None,
2018 context_window: Some(128_000),
2019 reasoning: Some(true),
2020 efforts: vec!["high".to_string()],
2021 }],
2022 )
2023 .expect("account-scoped roster");
2024
2025 let mut options = test_options(false);
2026 options.model = codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string();
2027 let app = App::new(options, &config);
2028
2029 assert_eq!(app.api_provider, ProviderKind::OpenaiCodex);
2030 assert_eq!(
2031 app.active_route_limits
2032 .and_then(|limits| limits.context_tokens),
2033 Some(128_000)
2034 );
2035 assert_eq!(
2036 codewhale_engine::route_budget::route_context_window_tokens(
2037 app.api_provider,
2038 &app.model,
2039 app.active_route_limits,
2040 ),
2041 128_000
2042 );
2043 }
2044
2045 #[test]
2046 fn settings_default_provider_auth_check_uses_provider_scoped_key() {
2047 let _lock = lock_test_env();
2048 let tmp = tempfile::TempDir::new().expect("tempdir");
2049 let config_path = tmp.path().join("config.toml");
2050 std::fs::write(
2051 tmp.path().join("settings.toml"),
2052 "default_provider = \"openai\"\n",
2053 )
2054 .expect("settings");
2055 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
2056 let _deepseek_key = EnvVarGuard::remove("DEEPSEEK_API_KEY");
2057 let _openai_key = EnvVarGuard::remove("OPENAI_API_KEY");
2058
2059 let config = {
2060 let __cw_config_init_5_0 = Some(ProvidersConfig {
2061 openai: ProviderConfig {
2062 api_key: Some("openai-config-key".to_string()),
2063 ..ProviderConfig::default()
2064 },
2065 ..ProvidersConfig::default()
2066 });
2067 let mut __cw_config_init_5_value: Config = Config::default();
2068 __cw_config_init_5_value.providers = __cw_config_init_5_0;
2069 __cw_config_init_5_value
2070 };
2071
2072 let app = App::new(test_options(false), &config);
2073
2074 assert_eq!(app.api_provider, ProviderKind::Openai);
2075 assert!(
2076 !app.onboarding_needs_api_key,
2077 "OpenAI provider config key should satisfy startup auth without a DeepSeek key"
2078 );
2079 assert!(!app.api_key_env_only);
2080 }
2081
2082 #[test]
2083 fn saved_startup_provider_overrides_config_file_provider() {
2084 let _lock = lock_test_env();
2085 let tmp = tempfile::TempDir::new().expect("tempdir");
2086 let config_path = tmp.path().join("config.toml");
2087 std::fs::write(
2088 tmp.path().join("settings.toml"),
2089 "default_provider = \"deepseek\"\ndefault_model = \"deepseek-v4-pro\"\n",
2090 )
2091 .expect("settings");
2092 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
2093
2094 let config = {
2095 let __cw_config_init_6_0 = Some("xiaomi-mimo".to_string());
2096 let __cw_config_init_6_1 = Some(ProvidersConfig {
2097 deepseek: ProviderConfig {
2098 api_key: Some("deepseek-config-key".to_string()),
2099 model: Some("deepseek-v4-pro".to_string()),
2100 ..ProviderConfig::default()
2101 },
2102 xiaomi_mimo: ProviderConfig {
2103 api_key: Some("mimo-config-key".to_string()),
2104 model: Some("mimo-v2.5-pro".to_string()),
2105 ..ProviderConfig::default()
2106 },
2107 ..ProvidersConfig::default()
2108 });
2109 let mut __cw_config_init_6_value: Config = Config::default();
2110 __cw_config_init_6_value.provider = __cw_config_init_6_0;
2111 __cw_config_init_6_value.providers = __cw_config_init_6_1;
2112 __cw_config_init_6_value
2113 };
2114
2115 let mut options = test_options(false);
2116 options.model = "mimo-v2.5-pro".to_string();
2117 let app = App::new(options, &config);
2118
2119 assert_eq!(app.api_provider, ProviderKind::Deepseek);
2120 assert_eq!(app.model, "deepseek-v4-pro");
2121 assert!(
2122 !app.onboarding_needs_api_key,
2123 "the saved startup provider's config key should satisfy startup auth"
2124 );
2125 }
2126
2127 #[test]
2128 fn selected_fleet_operator_outranks_remembered_startup_route_and_reasoning() {
2129 let _lock = lock_test_env();
2130 let tmp = tempfile::TempDir::new().expect("tempdir");
2131 let config_path = tmp.path().join("config.toml");
2132 std::fs::write(
2133 tmp.path().join("settings.toml"),
2134 r#"default_provider = "openrouter"
2135 reasoning_effort = "off"
2136
2137 [provider_models]
2138 deepseek = "deepseek-v4-pro"
2139 openrouter = "openai/gpt-5"
2140 "#,
2141 )
2142 .expect("settings");
2143 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
2144
2145 let config = {
2146 let __cw_config_init_7_0 = Some("deepseek".to_string());
2147 let __cw_config_init_7_1 = Some("high".to_string());
2148 let __cw_config_init_7_2 = true;
2149 let __cw_config_init_7_3 = true;
2150 let __cw_config_init_7_4 = Some(ProvidersConfig {
2151 deepseek: ProviderConfig {
2152 api_key: Some("deepseek-config-key".to_string()),
2153 model: Some("deepseek-v4-flash-vision-exp".to_string()),
2154 ..ProviderConfig::default()
2155 },
2156 openrouter: ProviderConfig {
2157 api_key: Some("openrouter-config-key".to_string()),
2158 model: Some("openai/gpt-5".to_string()),
2159 ..ProviderConfig::default()
2160 },
2161 ..ProvidersConfig::default()
2162 });
2163 let mut __cw_config_init_7_value: Config = Config::default();
2164 __cw_config_init_7_value.provider = __cw_config_init_7_0;
2165 __cw_config_init_7_value.reasoning_effort = __cw_config_init_7_1;
2166 __cw_config_init_7_value.fleet_operator_route_applied = __cw_config_init_7_2;
2167 __cw_config_init_7_value.fleet_operator_reasoning_applied = __cw_config_init_7_3;
2168 __cw_config_init_7_value.providers = __cw_config_init_7_4;
2169 __cw_config_init_7_value
2170 };
2171
2172 let mut options = test_options(false);
2173 options.model = "deepseek-v4-flash-vision-exp".to_string();
2174 let app = App::new(options, &config);
2175
2176 assert_eq!(app.api_provider, ProviderKind::Deepseek);
2177 assert_eq!(app.model, "deepseek-v4-flash-vision-exp");
2178 assert_eq!(app.reasoning_effort, ReasoningEffort::High);
2179 assert_eq!(app.reasoning_effort_preference, Some(ReasoningEffort::High));
2180 }
2181
2182 #[test]
2183 fn explicit_launch_provider_overrides_saved_startup_provider() {
2184 let _lock = lock_test_env();
2185 let tmp = tempfile::TempDir::new().expect("tempdir");
2186 let config_path = tmp.path().join("config.toml");
2187 std::fs::write(
2188 tmp.path().join("settings.toml"),
2189 "default_provider = \"deepseek\"\ndefault_model = \"deepseek-v4-pro\"\n",
2190 )
2191 .expect("settings");
2192 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
2193 let _provider = EnvVarGuard::set("CODEWHALE_PROVIDER", "xiaomi-mimo");
2194
2195 let config = {
2196 let __cw_config_init_8_0 = Some("xiaomi-mimo".to_string());
2197 let __cw_config_init_8_1 = Some(ProvidersConfig {
2198 deepseek: ProviderConfig {
2199 api_key: Some("deepseek-config-key".to_string()),
2200 model: Some("deepseek-v4-pro".to_string()),
2201 ..ProviderConfig::default()
2202 },
2203 xiaomi_mimo: ProviderConfig {
2204 api_key: Some("mimo-config-key".to_string()),
2205 model: Some("mimo-v2.5-pro".to_string()),
2206 ..ProviderConfig::default()
2207 },
2208 ..ProvidersConfig::default()
2209 });
2210 let mut __cw_config_init_8_value: Config = Config::default();
2211 __cw_config_init_8_value.provider = __cw_config_init_8_0;
2212 __cw_config_init_8_value.providers = __cw_config_init_8_1;
2213 __cw_config_init_8_value
2214 };
2215
2216 let mut options = test_options(false);
2217 options.model = "mimo-v2.5-pro".to_string();
2218 let app = App::new(options, &config);
2219
2220 assert_eq!(app.api_provider, ProviderKind::XiaomiMimo);
2221 assert_eq!(app.model, "mimo-v2.6-pro");
2222 }
2223
2224 #[test]
2225 fn pending_turn_cost_moves_displayed_total_mid_turn() {
2226 let mut app = App::new(test_options(false), &Config::default());
2227
2228 // Two model calls land per-step receipts while the turn is still running:
2229 // the displayed total must move now, not at TurnComplete (#5578).
2230 app.accrue_pending_turn_cost_estimate(CostEstimate::usd_only(0.06));
2231 app.accrue_pending_turn_cost_estimate(CostEstimate::usd_only(0.04));
2232 assert_eq!(
2233 app.displayed_session_cost_for_currency(CostCurrency::Usd),
2234 0.1
2235 );
2236 assert_eq!(app.session_cost_for_currency(CostCurrency::Usd), 0.1);
2237
2238 // TurnComplete: provisional hands off to the authoritative cumulative
2239 // price. A slightly lower settled figure must not make the display
2240 // reverse (#244), and nothing may count twice.
2241 app.clear_pending_turn_cost();
2242 app.accrue_session_cost_estimate(CostEstimate::usd_only(0.09));
2243 assert_eq!(app.session.session_cost, 0.09);
2244 assert_eq!(
2245 app.displayed_session_cost_for_currency(CostCurrency::Usd),
2246 0.1
2247 );
2248 }
2249
2250 #[test]
2251 fn pending_turn_usage_moves_token_surfaces_without_double_counting() {
2252 let mut app = App::new(test_options(false), &Config::default());
2253 let usage = Usage {
2254 input_tokens: 100,
2255 output_tokens: 20,
2256 prompt_cache_hit_tokens: Some(60),
2257 prompt_cache_miss_tokens: Some(40),
2258 prompt_cache_write_tokens: Some(5),
2259 ..Usage::default()
2260 };
2261
2262 app.session.accrue_pending_turn_usage(&usage);
2263 assert_eq!(app.session.displayed_total_tokens(), 120);
2264 assert_eq!(app.session.displayed_total_input_tokens(), 100);
2265 assert_eq!(app.session.displayed_total_output_tokens(), 20);
2266 assert_eq!(app.session.displayed_total_cache_hit_tokens(), 60);
2267 assert_eq!(app.session.displayed_total_cache_miss_tokens(), 35);
2268 assert_eq!(app.session.displayed_total_cache_write_tokens(), 5);
2269
2270 app.session.clear_pending_turn_usage();
2271 app.session.total_tokens = 120;
2272 app.session.total_input_tokens = 100;
2273 app.session.total_output_tokens = 20;
2274 app.session.total_cache_hit_tokens = 60;
2275 app.session.total_cache_miss_tokens = 35;
2276 app.session.total_cache_write_tokens = 5;
2277 assert_eq!(app.session.displayed_total_tokens(), 120);
2278 assert_eq!(app.session.displayed_total_cache_write_tokens(), 5);
2279 }
2280
2281 #[test]
2282 fn context_pressure_toast_kind_is_not_inferred_from_display_text() {
2283 let mut app = App::new(test_options(false), &Config::default());
2284 app.sticky_status = Some(StatusToast::new(
2285 "Context high: 90%",
2286 StatusToastLevel::Warning,
2287 None,
2288 ));
2289 assert!(!app.dismiss_context_pressure_warning());
2290 assert!(app.sticky_status.is_some());
2291
2292 app.sticky_status = Some(StatusToast::context_pressure(
2293 "localized pressure warning",
2294 codewhale_runtime::context_budget::PressureLevel::High,
2295 ));
2296 assert!(app.dismiss_context_pressure_warning());
2297 assert!(app.sticky_status.is_none());
2298 }
2299
2300 #[test]
2301 fn critical_context_pressure_remains_visible_over_transient_info_toasts() {
2302 let mut app = App::new(test_options(false), &Config::default());
2303 app.sticky_status = Some(StatusToast::context_pressure(
2304 "Context critical: 95%",
2305 codewhale_runtime::context_budget::PressureLevel::Critical,
2306 ));
2307 app.push_status_toast("Saved", StatusToastLevel::Info, None);
2308
2309 assert_eq!(
2310 app.active_status_toast(crate::tui::underwater::ShellPhase::Working)
2311 .map(|toast| toast.text),
2312 Some("Context critical: 95%".to_string())
2313 );
2314 }
2315
2316 #[test]
2317 fn cny_display_scenario() {
2318 // Scenario consolidation of: cny_display_falls_back_to_usd_for_usd_only_costs, cny_display_keeps_cny_when_costs_have_cny_rates, cny_display_does_not_fall_back_to_an_unproven_usd_total
2319 // from cny_display_falls_back_to_usd_for_usd_only_costs
2320 {
2321 let mut app = App::new(test_options(false), &Config::default());
2322 app.cost_currency = CostCurrency::Cny;
2323 app.accrue_session_cost_estimate(CostEstimate::usd_only(0.42));
2324 app.session.cost_priced_turns = 1;
2325
2326 let displayed = app.displayed_session_cost_for_currency(CostCurrency::Cny);
2327
2328 assert_eq!(displayed, 0.42);
2329 assert_eq!(app.session_cost_for_currency(CostCurrency::Cny), 0.42);
2330 assert_eq!(app.format_cost_amount(displayed), "$0.42");
2331 }
2332 // from cny_display_keeps_cny_when_costs_have_cny_rates
2333 {
2334 let mut app = App::new(test_options(false), &Config::default());
2335 app.cost_currency = CostCurrency::Cny;
2336 app.accrue_session_cost_estimate(CostEstimate {
2337 usd: 0.42,
2338 cny: 2.5,
2339 });
2340 app.session.cost_priced_turns = 1;
2341 app.session.cost_cny_priced_turns = 1;
2342
2343 let displayed = app.displayed_session_cost_for_currency(CostCurrency::Cny);
2344
2345 assert_eq!(displayed, 2.5);
2346 assert_eq!(app.format_cost_amount(displayed), "¥2.50");
2347 }
2348 // from cny_display_does_not_fall_back_to_an_unproven_usd_total
2349 {
2350 let mut app = App::new(test_options(false), &Config::default());
2351 app.cost_currency = CostCurrency::Cny;
2352 app.accrue_session_cost_estimate(CostEstimate::usd_only(0.42));
2353
2354 assert_eq!(
2355 app.cost_display_currency(CostCurrency::Cny),
2356 CostCurrency::Cny
2357 );
2358 assert_eq!(
2359 app.displayed_session_cost_for_currency(CostCurrency::Cny),
2360 0.0
2361 );
2362 }
2363 }
2364
2365 #[test]
2366 fn subscription_route_hides_stale_session_dollars_in_footer() {
2367 let mut app = App::new(test_options(false), &Config::default());
2368 app.accrue_session_cost_estimate(CostEstimate::usd_only(12.34));
2369 app.billing_presentation =
2370 codewhale_engine::route_billing::BillingPresentation::Subscription("Codex OAuth quota");
2371 // Stale unaudited dollars must never render on a plan route; the usage
2372 // chip carries the plan-aware line instead of money or silence.
2373 let chip = app.cumulative_usage_chip();
2374 assert!(
2375 !matches!(chip, codewhale_engine::route_billing::UsageChip::Money(_)),
2376 "{chip:?}"
2377 );
2378 let rendered = codewhale_engine::route_billing::format_usage_chip(
2379 &chip,
2380 codewhale_localization::Locale::En,
2381 )
2382 .unwrap_or_default();
2383 assert!(!rendered.contains('$'), "{rendered}");
2384 assert!(rendered.contains("Codex OAuth quota"), "{rendered}");
2385 }
2386
2387 #[test]
2388 fn session_cost_label_renders_money_or_unknown_without_plan_names_or_local() {
2389 let unknown = codewhale_localization::tr(
2390 codewhale_localization::Locale::En,
2391 codewhale_localization::MessageId::CmdCostUnknownValue,
2392 )
2393 .into_owned();
2394
2395 let mut sub = App::new(test_options(false), &Config::default());
2396 sub.billing_presentation =
2397 codewhale_engine::route_billing::BillingPresentation::Subscription("Codex OAuth quota");
2398 assert_eq!(sub.session_cost_label(), unknown);
2399 assert_eq!(sub.status_cost_label().as_deref(), Some(unknown.as_str()));
2400
2401 let mut local = App::new(test_options(false), &Config::default());
2402 local.billing_presentation = codewhale_engine::route_billing::BillingPresentation::Local;
2403 assert_eq!(local.session_cost_label(), unknown);
2404 assert_eq!(local.status_cost_label().as_deref(), Some(unknown.as_str()));
2405
2406 let mut metered = App::new(test_options(false), &Config::default());
2407 metered.api_provider = ProviderKind::Deepseek;
2408 metered.model = "deepseek-v4-flash".to_string();
2409 metered.billing_presentation = codewhale_engine::route_billing::BillingPresentation::Metered;
2410 assert_eq!(metered.session_cost_label(), "$0.00");
2411 assert_eq!(metered.status_cost_label(), None);
2412
2413 metered.session.cost_priced_turns = 1;
2414 metered.accrue_session_cost_estimate(CostEstimate::usd_only(0.42));
2415 assert_eq!(metered.session_cost_label(), "$0.42");
2416 assert_eq!(metered.status_cost_label(), None);
2417
2418 metered.session.cost_unpriced_turns = 1;
2419 assert_eq!(metered.session_cost_label(), "$0.42");
2420 assert_eq!(metered.status_cost_label().as_deref(), Some("$0.42"));
2421 }
2422
2423 #[test]
2424 fn late_reported_usage_prunes_stale_request_outcome_unknown_reason() {
2425 let mut app = App::new(test_options(false), &Config::default());
2426 let route = codewhale_engine::cost_status::EffectiveRouteEnvelope::capture(
2427 None,
2428 ProviderKind::Deepseek,
2429 "deepseek",
2430 "deepseek-v4-flash",
2431 Some(ProviderKind::Deepseek.provider().default_base_url()),
2432 chrono::Utc::now(),
2433 );
2434 let drop_pool = codewhale_engine::cost_status::background_cost_for_runtime_drop(
2435 &codewhale_engine::cost_status::RuntimeUsageDropRecord {
2436 reason: codewhale_engine::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown,
2437 source_id: "cw-7882-late-source".to_string(),
2438 route: route.clone(),
2439 },
2440 );
2441 app.absorb_pending_background_cost(&drop_pool);
2442 assert_eq!(app.session.cost_unpriced_turns, 1);
2443 assert!(
2444 app.session
2445 .cost_unpriced_reasons
2446 .contains("request_outcome_unknown")
2447 );
2448
2449 let settled = codewhale_engine::cost_status::NativeUsageSource::capture(
2450 "cw-7882-late-source",
2451 codewhale_engine::cost_status::UsageSpendOwner::Auxiliary,
2452 )
2453 .reported(
2454 &route,
2455 &codewhale_models::Usage {
2456 input_tokens: 1_000,
2457 output_tokens: 200,
2458 ..Default::default()
2459 },
2460 );
2461 let settled_pool = codewhale_engine::cost_status::background_cost_for_runtime_usage(&settled);
2462 app.absorb_pending_background_cost(&settled_pool);
2463 assert_eq!(app.session.cost_priced_turns, 1);
2464 assert_eq!(app.session.cost_unpriced_turns, 0);
2465 assert!(
2466 !app.session
2467 .cost_unpriced_reasons
2468 .contains("request_outcome_unknown")
2469 );
2470 assert!(
2471 !app.session
2472 .cost_cny_unpriced_reasons
2473 .contains("request_outcome_unknown")
2474 );
2475 }
2476
2477 #[test]
2478 fn provider_switch_keeps_audited_cumulative_spend_visible() {
2479 let mut app = App::new(test_options(false), &Config::default());
2480 let usage = codewhale_models::Usage {
2481 input_tokens: 10_000,
2482 output_tokens: 1_000,
2483 ..Default::default()
2484 };
2485 let priced = codewhale_engine::pricing::audit_turn_cost_for_provider_at(
2486 ProviderKind::Deepseek,
2487 "deepseek-v4-flash",
2488 &usage,
2489 chrono::Utc::now(),
2490 );
2491 app.record_turn_cost_audit(&priced);
2492 app.accrue_session_cost_estimate(priced.estimate.expect("priced"));
2493
2494 app.api_provider = ProviderKind::OpenaiCodex;
2495 app.model = "gpt-5.5".to_string();
2496 app.billing_presentation =
2497 codewhale_engine::route_billing::BillingPresentation::Subscription("Codex OAuth quota");
2498 assert!(matches!(
2499 app.cumulative_usage_chip(),
2500 codewhale_engine::route_billing::UsageChip::Money(_)
2501 ));
2502 assert!(
2503 codewhale_engine::route_billing::format_usage_chip(
2504 &app.cumulative_usage_chip(),
2505 app.ui_locale
2506 )
2507 .is_some_and(|label| !label.is_empty())
2508 );
2509
2510 let unknown = codewhale_engine::pricing::audit_turn_cost_for_route_at(
2511 ProviderKind::Openai,
2512 "gpt-5.5",
2513 Some(codewhale_engine::pricing::UNCLASSIFIED_BILLING_SURFACE),
2514 &usage,
2515 chrono::Utc::now(),
2516 );
2517 app.record_turn_cost_audit(&unknown);
2518 assert!(matches!(
2519 app.cumulative_usage_chip(),
2520 codewhale_engine::route_billing::UsageChip::PricedSubtotal { legacy: false, .. }
2521 ));
2522 }
2523
2524 #[test]
2525 fn slash_command_classifier_treats_absolute_path_as_message() {
2526 assert!(looks_like_slash_command_input("/"));
2527 assert!(looks_like_slash_command_input("/help"));
2528 assert!(looks_like_slash_command_input("/model deepseek-v4-pro"));
2529 assert!(!looks_like_slash_command_input("/ hello"));
2530 assert!(!looks_like_slash_command_input(" / hello"));
2531 assert!(!looks_like_slash_command_input(
2532 "/usr/lib/x86_64-linux-gnu/ 是标准路径吗?"
2533 ));
2534 }
2535
2536 #[test]
2537 fn bang_shell_scenario() {
2538 // Scenario consolidation of: bang_shell_prefix_parses_compact_and_spaced_forms, bang_shell_prefix_rejects_empty_command
2539 // from bang_shell_prefix_parses_compact_and_spaced_forms
2540 {
2541 assert_eq!(shell_command_from_bang_input("!pwd"), Ok(Some("pwd")));
2542 assert_eq!(shell_command_from_bang_input("! pwd"), Ok(Some("pwd")));
2543 assert_eq!(
2544 shell_command_from_bang_input(" ! cargo test -p codewhale-tui sidebar"),
2545 Ok(Some("cargo test -p codewhale-tui sidebar"))
2546 );
2547 assert_eq!(shell_command_from_bang_input("normal message"), Ok(None));
2548 }
2549 // from bang_shell_prefix_rejects_empty_command
2550 {
2551 assert_eq!(
2552 shell_command_from_bang_input("!"),
2553 Err("Usage: ! <shell command>")
2554 );
2555 assert_eq!(
2556 shell_command_from_bang_input("! "),
2557 Err("Usage: ! <shell command>")
2558 );
2559 }
2560 }
2561
2562 #[test]
2563 fn stop_word_matching_requires_one_token() {
2564 let words = vec!["stop".to_string(), "wait".to_string(), "pause".to_string()];
2565 assert_eq!(is_stop_word("STOP", &words).as_deref(), Some("stop"));
2566 assert_eq!(is_stop_word("+ stop", &words).as_deref(), Some("stop"));
2567 assert_eq!(is_stop_word("!wait", &words).as_deref(), Some("wait"));
2568 assert_eq!(is_stop_word("pause.", &words).as_deref(), Some("pause"));
2569 assert!(is_stop_word("please stop", &words).is_none());
2570 assert!(is_stop_word("don't stop", &words).is_none());
2571 }
2572
2573 #[test]
2574 fn submit_input_records_absolute_slash_path_as_message_history() {
2575 let mut app = App::new(test_options(false), &Config::default());
2576 let input = "/usr/lib/x86_64-linux-gnu/ 是标准路径吗?";
2577 app.input = input.to_string();
2578 app.cursor_position = input.chars().count();
2579
2580 let submitted = app.submit_input().expect("expected submitted input");
2581
2582 assert_eq!(submitted, input);
2583 assert_eq!(app.input_history.last().map(String::as_str), Some(input));
2584 }
2585
2586 #[test]
2587 fn submit_input_recalls_slash_commands_and_persists_them_for_the_next_session() {
2588 let _env_lock = lock_test_env();
2589 let home = tempfile::tempdir().expect("isolated home");
2590 let _home = EnvVarGuard::set("HOME", home.path());
2591 let _profile = EnvVarGuard::set("USERPROFILE", home.path());
2592 let _state = EnvVarGuard::set("CODEWHALE_HOME", home.path().join(".codewhale"));
2593 let mut app = App::new(test_options(false), &Config::default());
2594 app.input_history.clear();
2595 for input in ["/theme", "/theme", "/theme", "/compact", "/compact"] {
2596 app.input = input.to_string();
2597 app.cursor_position = input.chars().count();
2598 assert_eq!(app.submit_input().as_deref(), Some(input));
2599 }
2600 assert_eq!(app.input_history, ["/theme", "/compact"]);
2601 app.history_up();
2602 assert_eq!(app.input, "/compact");
2603 app.history_up();
2604 assert_eq!(app.input, "/theme");
2605
2606 crate::composer_history::flush_history_writer_for_tests(std::time::Duration::from_secs(5));
2607 let mut resumed = App::new(test_options(false), &Config::default());
2608 resumed.history_up();
2609 assert_eq!(resumed.input, "/compact");
2610 resumed.history_up();
2611 assert_eq!(resumed.input, "/theme");
2612 }
2613
2614 #[test]
2615 fn restore_last_scenario() {
2616 // Scenario consolidation of: restore_last_submitted_prompt_rehydrates_empty_composer, restore_last_submitted_prompt_preserves_existing_draft, restore_last_cleared_input_restores_saved_draft, restore_last_cleared_input_does_nothing_when_composer_not_empty
2617 // from restore_last_submitted_prompt_rehydrates_empty_composer
2618 {
2619 let mut app = App::new(test_options(false), &Config::default());
2620 app.last_submitted_prompt = Some("fix the typo\nand retry".to_string());
2621
2622 assert!(app.restore_last_submitted_prompt_if_empty());
2623
2624 assert_eq!(app.input, "fix the typo\nand retry");
2625 assert_eq!(app.cursor_position, app.input.chars().count());
2626 assert!(app.needs_redraw);
2627 }
2628 // from restore_last_submitted_prompt_preserves_existing_draft
2629 {
2630 let mut app = App::new(test_options(false), &Config::default());
2631 app.last_submitted_prompt = Some("previous prompt".to_string());
2632 app.input = "new draft".to_string();
2633 app.cursor_position = app.input.chars().count();
2634
2635 assert!(!app.restore_last_submitted_prompt_if_empty());
2636
2637 assert_eq!(app.input, "new draft");
2638 assert_eq!(app.cursor_position, "new draft".chars().count());
2639 }
2640 // from restore_last_cleared_input_restores_saved_draft
2641 {
2642 let mut app = App::new(test_options(false), &Config::default());
2643 app.input = "previous".to_string();
2644 app.cursor_position = 8;
2645 app.clear_input_recoverable();
2646 assert!(app.input.is_empty());
2647
2648 let restored = app.restore_last_cleared_input_if_empty();
2649 assert!(restored);
2650 assert_eq!(app.input, "previous");
2651 assert!(app.clear_undo_buffer.is_none());
2652 }
2653 // from restore_last_cleared_input_does_nothing_when_composer_not_empty
2654 {
2655 let mut app = App::new(test_options(false), &Config::default());
2656 app.clear_undo_buffer = Some("old".to_string());
2657 app.input = "current".to_string();
2658 assert!(!app.restore_last_cleared_input_if_empty());
2659 }
2660 }
2661
2662 #[test]
2663 fn composer_strips_scenario() {
2664 // Scenario consolidation of: composer_strips_raw_sgr_mouse_report_when_mouse_capture_is_enabled, composer_strips_corrupted_mouse_report_burst, composer_strips_raw_sgr_mouse_report_when_mouse_capture_is_disabled, composer_strips_tail_only_mouse_report_burst_when_mouse_capture_is_disabled, composer_strips_osc8_hyperlink_fragment, composer_strips_closing_osc8_fragment, composer_strips_kitty_keyboard_protocol_fragment, composer_strips_dec_private_mode_set_reset_fragments, composer_strips_mixed_control_sequence_burst
2665 // from composer_strips_raw_sgr_mouse_report_when_mouse_capture_is_enabled
2666 {
2667 let mut app = App::new(test_options(false), &Config::default());
2668 app.use_mouse_capture = true;
2669
2670 app.insert_str("[<35;44;18M");
2671
2672 assert_eq!(app.input, "");
2673 assert_eq!(app.cursor_position, 0);
2674 }
2675 // from composer_strips_corrupted_mouse_report_burst
2676 {
2677 let mut app = App::new(test_options(false), &Config::default());
2678 app.use_mouse_capture = true;
2679 app.insert_str("draft ");
2680 let leaked = "43;19M[<35;44;18M[<35;45;18M5;46;18M;48;18M";
2681
2682 app.insert_str(leaked);
2683
2684 assert_eq!(app.input, "draft ");
2685 assert_eq!(app.cursor_position, "draft ".chars().count());
2686 }
2687 // from composer_strips_raw_sgr_mouse_report_when_mouse_capture_is_disabled
2688 {
2689 let mut app = App::new(test_options(false), &Config::default());
2690
2691 app.insert_str("[<35;44;18M");
2692
2693 assert_eq!(app.input, "");
2694 assert_eq!(app.cursor_position, 0);
2695 }
2696 // from composer_strips_tail_only_mouse_report_burst_when_mouse_capture_is_disabled
2697 {
2698 let mut app = App::new(test_options(false), &Config::default());
2699 app.insert_str("draft ");
2700
2701 app.insert_str(";76;20M35;74;22M35;73;23M");
2702
2703 assert_eq!(app.input, "draft ");
2704 assert_eq!(app.cursor_position, "draft ".chars().count());
2705 }
2706 // from composer_strips_osc8_hyperlink_fragment
2707 {
2708 let mut app = App::new(test_options(false), &Config::default());
2709 app.use_mouse_capture = true;
2710 app.insert_str("draft ");
2711
2712 // OSC 8 prefix with URL body but no terminator delivered yet —
2713 // exactly what crossterm hands us if its event reader is
2714 // interrupted mid-sequence and the leading ESC is consumed by the
2715 // parser before the rest gets reclassified as Char(c).
2716 app.insert_str("]8;;https://example.com");
2717
2718 assert_eq!(app.input, "draft ");
2719 assert_eq!(app.cursor_position, "draft ".chars().count());
2720 }
2721 // from composer_strips_closing_osc8_fragment
2722 {
2723 let mut app = App::new(test_options(false), &Config::default());
2724 app.use_mouse_capture = true;
2725 app.insert_str("hello ");
2726
2727 // The closing wrapper `]8;;` (with a stray ST `\\` from a
2728 // chopped escape) can arrive on its own when the parser ate
2729 // the start of the sequence in a previous read but caught the
2730 // tail as keystrokes.
2731 app.insert_str("]8;;\\");
2732
2733 assert_eq!(app.input, "hello ");
2734 assert_eq!(app.cursor_position, "hello ".chars().count());
2735 }
2736 // from composer_strips_kitty_keyboard_protocol_fragment
2737 {
2738 let mut app = App::new(test_options(false), &Config::default());
2739 app.use_mouse_capture = true;
2740 app.insert_str("ready ");
2741
2742 // Kitty keyboard protocol responses look like `\x1b[?1u`,
2743 // `\x1b[>1u`, `\x1b[<1u`, or `\x1b[?u`. With the ESC consumed,
2744 // the tail shape is `[?…u`, `[>…u`, or `[<…u`.
2745 app.insert_str("[?1u[>1u[<1u[?u");
2746
2747 assert_eq!(app.input, "ready ");
2748 assert_eq!(app.cursor_position, "ready ".chars().count());
2749 }
2750 // from composer_strips_dec_private_mode_set_reset_fragments
2751 {
2752 let mut app = App::new(test_options(false), &Config::default());
2753 app.use_mouse_capture = true;
2754 app.insert_str("ok ");
2755
2756 // Regression for #2592: DEC private mode set/reset chatter ends in
2757 // `h`/`l`, not `u`, so the `u`-only terminator used to leak the
2758 // leading `[`. Bracketed paste, mouse capture, focus reporting, and
2759 // synchronized output all leak during dense streaming.
2760 app.insert_str("[?2004h[?2004l[?1000h[?1004h[?2026h[?25l");
2761
2762 assert_eq!(app.input, "ok ");
2763 assert_eq!(app.cursor_position, "ok ".chars().count());
2764 }
2765 // from composer_strips_mixed_control_sequence_burst
2766 {
2767 let mut app = App::new(test_options(false), &Config::default());
2768 app.use_mouse_capture = true;
2769 app.insert_str("hi");
2770
2771 // Mixed dense burst combining all three fragment families
2772 // described in #1915.
2773 app.insert_str("[<35;44;18M]8;;https://example.com[?1u");
2774
2775 assert_eq!(app.input, "hi");
2776 assert_eq!(app.cursor_position, 2);
2777 }
2778 }
2779
2780 #[test]
2781 fn composer_preserves_scenario() {
2782 // Scenario consolidation of: composer_preserves_draft_suffix_when_stripping_mouse_report, composer_preserves_numeric_draft_when_stripping_mouse_report
2783 // from composer_preserves_draft_suffix_when_stripping_mouse_report
2784 {
2785 let mut app = App::new(test_options(false), &Config::default());
2786 app.use_mouse_capture = true;
2787 app.insert_str("commit -m");
2788
2789 app.insert_str("[<65;44;18M");
2790
2791 assert_eq!(app.input, "commit -m");
2792 assert_eq!(app.cursor_position, "commit -m".chars().count());
2793 }
2794 // from composer_preserves_numeric_draft_when_stripping_mouse_report
2795 {
2796 let mut app = App::new(test_options(false), &Config::default());
2797 app.use_mouse_capture = true;
2798 app.insert_str("123");
2799
2800 app.insert_str("[<65;44;18M");
2801
2802 assert_eq!(app.input, "123");
2803 assert_eq!(app.cursor_position, 3);
2804 }
2805 }
2806
2807 #[test]
2808 fn composer_keeps_scenario() {
2809 // Scenario consolidation of: composer_keeps_coordinate_like_text_when_mouse_capture_is_disabled, composer_keeps_normal_bracket_text_with_mouse_capture_enabled, composer_keeps_coordinate_like_text_with_mouse_capture_enabled, composer_keeps_bracket_question_word_text, composer_keeps_legitimate_url_text_with_mouse_capture_enabled, composer_keeps_legitimate_bracket_question_text, composer_keeps_legitimate_closing_bracket_digit_text
2810 // from composer_keeps_coordinate_like_text_when_mouse_capture_is_disabled
2811 {
2812 let mut app = App::new(test_options(false), &Config::default());
2813
2814 app.insert_str("Size 12;34M");
2815
2816 assert_eq!(app.input, "Size 12;34M");
2817 assert_eq!(app.cursor_position, "Size 12;34M".chars().count());
2818 }
2819 // from composer_keeps_normal_bracket_text_with_mouse_capture_enabled
2820 {
2821 let mut app = App::new(test_options(false), &Config::default());
2822 app.use_mouse_capture = true;
2823
2824 app.insert_str("Use [<tag>] normally");
2825
2826 assert_eq!(app.input, "Use [<tag>] normally");
2827 }
2828 // from composer_keeps_coordinate_like_text_with_mouse_capture_enabled
2829 {
2830 let mut app = App::new(test_options(false), &Config::default());
2831 app.use_mouse_capture = true;
2832
2833 app.insert_str("Size 12;34M");
2834
2835 assert_eq!(app.input, "Size 12;34M");
2836 }
2837 // from composer_keeps_bracket_question_word_text
2838 {
2839 let mut app = App::new(test_options(false), &Config::default());
2840 app.use_mouse_capture = true;
2841
2842 // The `h`/`l` terminator only counts after a numeric parameter, so
2843 // ordinary prose where a letter follows `[?` directly is preserved.
2844 app.insert_str("[?help] and [?later]");
2845
2846 assert_eq!(app.input, "[?help] and [?later]");
2847 }
2848 // from composer_keeps_legitimate_url_text_with_mouse_capture_enabled
2849 {
2850 let mut app = App::new(test_options(false), &Config::default());
2851 app.use_mouse_capture = true;
2852
2853 // URLs typed by the user must survive the filter — only
2854 // recognized control-sequence shapes are stripped.
2855 app.insert_str("see https://example.com/path?a=1&b=2 for info");
2856
2857 assert_eq!(app.input, "see https://example.com/path?a=1&b=2 for info");
2858 }
2859 // from composer_keeps_legitimate_bracket_question_text
2860 {
2861 let mut app = App::new(test_options(false), &Config::default());
2862 app.use_mouse_capture = true;
2863
2864 // Text that uses brackets, question marks, and lowercase `u` —
2865 // shapes that overlap Kitty fragments — must not be eaten.
2866 app.insert_str("[is this ok?] sure");
2867
2868 assert_eq!(app.input, "[is this ok?] sure");
2869 }
2870 // from composer_keeps_legitimate_closing_bracket_digit_text
2871 {
2872 let mut app = App::new(test_options(false), &Config::default());
2873 app.use_mouse_capture = true;
2874
2875 // Plain `]8` followed by spaces and words must survive — only
2876 // the OSC 8 shape `]8;` (with the mandatory `;` separator)
2877 // should be treated as a fragment.
2878 app.insert_str("array[]8 elements");
2879
2880 assert_eq!(app.input, "array[]8 elements");
2881 }
2882 }
2883
2884 // === Bug #1915: broader terminal control-sequence fragments leaking
2885 // into the composer during dense streaming output. The narrow SGR
2886 // mouse-report filter installed in e63a4ba4a covers `[<…M` style
2887 // bursts, but not OSC 8 hyperlink fragments (`]8;;http…`) or Kitty
2888 // keyboard protocol responses (`[?u`, `[>1u`). These can arrive when
2889 // crossterm's event reader is mid-sequence and the unparsed tail is
2890 // delivered as individual Char(c) keystrokes that land in the input.
2891
2892 // initial_onboarding_state tests
2893 // These pin the logic that decides whether the TUI shows the
2894 // first missing decision or goes straight to the chat view. Getting this
2895 // wrong either locks first-run users out of provider setup or nags returning
2896 // users whose configuration is already usable.
2897
2898 #[test]
2899 fn skip_onboarding_suppresses_all_onboarding_states() {
2900 assert_eq!(
2901 initial_onboarding_state(true, false, true, true, true),
2902 OnboardingState::None
2903 );
2904 assert_eq!(
2905 initial_onboarding_state(true, true, true, true, true),
2906 OnboardingState::None
2907 );
2908 }
2909
2910 #[test]
2911 fn fully_configured_returning_user_skips_onboarding() {
2912 assert_eq!(
2913 initial_onboarding_state(false, true, false, false, false),
2914 OnboardingState::None
2915 );
2916 }
2917
2918 #[test]
2919 fn returning_user_missing_api_key_starts_at_composer() {
2920 assert_eq!(
2921 initial_onboarding_state(false, true, false, true, false),
2922 OnboardingState::None
2923 );
2924 assert_eq!(
2925 initial_onboarding_state(false, true, false, true, true),
2926 OnboardingState::None
2927 );
2928 }
2929
2930 #[test]
2931 fn first_run_user_without_a_key_starts_at_composer() {
2932 assert_eq!(
2933 initial_onboarding_state(false, false, true, true, true),
2934 OnboardingState::None
2935 );
2936 assert_eq!(
2937 initial_onboarding_state(false, false, false, true, true),
2938 OnboardingState::None
2939 );
2940 }
2941
2942 #[test]
2943 fn first_run_user_with_a_key_gets_workspace_trust_when_needed() {
2944 assert_eq!(
2945 initial_onboarding_state(false, false, false, false, true),
2946 OnboardingState::TrustDirectory
2947 );
2948 assert_eq!(
2949 initial_onboarding_state(false, false, false, false, false),
2950 OnboardingState::None
2951 );
2952 }
2953
2954 #[test]
2955 fn onboarding_workspace_trust_gate_fires_when_key_present_and_trust_needed() {
2956 assert!(onboarding_is_workspace_trust_gate(false, true, false, true));
2957 assert!(!onboarding_is_workspace_trust_gate(true, true, false, true));
2958 assert!(!onboarding_is_workspace_trust_gate(false, true, true, true));
2959 assert!(onboarding_is_workspace_trust_gate(
2960 false, false, false, true
2961 ));
2962 }
2963
2964 #[test]
2965 fn onboarded_user_still_gets_workspace_trust_prompt_when_needed() {
2966 assert_eq!(
2967 initial_onboarding_state(false, true, false, false, true),
2968 OnboardingState::TrustDirectory
2969 );
2970 }
2971
2972 // App::new tests: missing key is detected
2973
2974 #[test]
2975 fn app_new_detects_missing_api_key_with_default_config() {
2976 let _lock = lock_test_env();
2977 let tmp = tempfile::TempDir::new().expect("tempdir");
2978 let config_path = tmp.path().join("config.toml");
2979 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
2980 let _provider_env = EnvVarGuard::remove("CODEWHALE_PROVIDER");
2981 let _legacy_provider_env = EnvVarGuard::remove("DEEPSEEK_PROVIDER");
2982 let _api_key_envs: Vec<_> = [
2983 "DEEPSEEK_API_KEY",
2984 "NVIDIA_API_KEY",
2985 "NVIDIA_NIM_API_KEY",
2986 "OPENAI_API_KEY",
2987 "ATLASCLOUD_API_KEY",
2988 "WANJIE_ARK_API_KEY",
2989 "WANJIE_API_KEY",
2990 "WANJIE_MAAS_API_KEY",
2991 "OPENROUTER_API_KEY",
2992 "NOVITA_API_KEY",
2993 "FIREWORKS_API_KEY",
2994 "SILICONFLOW_API_KEY",
2995 "MOONSHOT_API_KEY",
2996 "KIMI_API_KEY",
2997 "SGLANG_API_KEY",
2998 "VLLM_API_KEY",
2999 "OLLAMA_API_KEY",
3000 ]
3001 .into_iter()
3002 .map(EnvVarGuard::remove)
3003 .collect();
3004
3005 // Config::default() carries no api_key, and this test isolates process
3006 // env/settings so previous tests or developer shells cannot satisfy it.
3007 let app = App::new(test_options(false), &Config::default());
3008 assert!(
3009 app.onboarding_needs_api_key,
3010 "default config (no key) must set onboarding_needs_api_key"
3011 );
3012 }
3013
3014 #[test]
3015 fn first_run_app_without_a_key_opens_provider_setup() {
3016 let _lock = lock_test_env();
3017 let home = tempfile::TempDir::new().expect("isolated first-run home");
3018 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path().to_string_lossy().as_ref());
3019 let config_path = home.path().join("config.toml");
3020 let _config_path = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
3021 let _provider_env = EnvVarGuard::remove("CODEWHALE_PROVIDER");
3022 let _legacy_provider_env = EnvVarGuard::remove("DEEPSEEK_PROVIDER");
3023 let _api_key_envs: Vec<_> = [
3024 "DEEPSEEK_API_KEY",
3025 "NVIDIA_API_KEY",
3026 "NVIDIA_NIM_API_KEY",
3027 "OPENAI_API_KEY",
3028 "ATLASCLOUD_API_KEY",
3029 "WANJIE_ARK_API_KEY",
3030 "WANJIE_API_KEY",
3031 "WANJIE_MAAS_API_KEY",
3032 "OPENROUTER_API_KEY",
3033 "NOVITA_API_KEY",
3034 "FIREWORKS_API_KEY",
3035 "SILICONFLOW_API_KEY",
3036 "MOONSHOT_API_KEY",
3037 "KIMI_API_KEY",
3038 "SGLANG_API_KEY",
3039 "VLLM_API_KEY",
3040 "OLLAMA_API_KEY",
3041 ]
3042 .into_iter()
3043 .map(EnvVarGuard::remove)
3044 .collect();
3045
3046 let app = App::new(test_options(false), &Config::default());
3047 // CW-7167: a keyless launch opens the composer; the provider is asked for
3048 // on the first send.
3049 assert_eq!(app.onboarding, OnboardingState::None);
3050 assert!(app.onboarding_needs_api_key);
3051 assert!(app.onboarding_missing_key_recovery);
3052 // A new user has no saved route, so the picker opens on the provider
3053 // list, not on the built-in default's missing key.
3054 assert!(!app.onboarding_recovers_configured_route());
3055 // Language is asked in /setup, so the launch screen is not "2/3".
3056 assert!(!app.onboarding_had_language_step);
3057 }
3058
3059 #[test]
3060 fn new_caches_workspace_skills_for_slash_menu() {
3061 let tmp = tempfile::TempDir::new().expect("tempdir");
3062 let workspace = tmp.path().join("workspace");
3063 let skill_dir = workspace.join(".agents").join("skills").join("local-skill");
3064 std::fs::create_dir_all(&skill_dir).expect("skill dir");
3065 crate::test_support::trust_workspace(&workspace);
3066 std::fs::write(
3067 skill_dir.join("SKILL.md"),
3068 "---\nname: local-skill\ndescription: Local workspace skill\n---\nUse the local skill.\n",
3069 )
3070 .expect("skill file");
3071
3072 let mut options = test_options(false);
3073 options.workspace = workspace.clone();
3074 options.skills_dir = tmp.path().join("global-skills");
3075 let app = App::new(options, &Config::default());
3076
3077 assert_eq!(app.skills_dir, workspace.join(".agents").join("skills"));
3078 assert!(app.cached_skills.iter().any(|(name, description)| {
3079 name == "local-skill" && description == "Local workspace skill"
3080 }));
3081 }
3082
3083 #[test]
3084 fn cached_skills_merges_across_candidate_directories() {
3085 let tmp = tempfile::TempDir::new().expect("tempdir");
3086 let workspace = tmp.path().join("workspace");
3087 crate::test_support::trust_workspace(&workspace);
3088
3089 // Higher-precedence directory contains a stale empty dir for `foo`
3090 // (no SKILL.md). This used to shadow the real definition further
3091 // down the candidate list when the cache only scanned a single dir.
3092 std::fs::create_dir_all(workspace.join(".agents").join("skills").join("foo"))
3093 .expect("stale empty dir");
3094
3095 // Lower-precedence directory has the real skill.
3096 let real_dir = workspace.join(".claude").join("skills").join("foo");
3097 std::fs::create_dir_all(&real_dir).expect("real skill dir");
3098 std::fs::write(
3099 real_dir.join("SKILL.md"),
3100 "---\nname: foo\ndescription: Real foo skill\n---\nbody\n",
3101 )
3102 .expect("skill file");
3103
3104 let mut options = test_options(false);
3105 options.workspace = workspace.clone();
3106 options.skills_dir = tmp.path().join("global-skills");
3107 let app = App::new(options, &Config::default());
3108
3109 assert!(
3110 app.cached_skills
3111 .iter()
3112 .any(|(name, description)| name == "foo" && description == "Real foo skill"),
3113 "cached_skills should fall through to lower-precedence dir when higher-precedence one has an empty stub: {:?}",
3114 app.cached_skills,
3115 );
3116 }
3117
3118 #[test]
3119 fn cached_skills_respect_codewhale_only_scan_config() {
3120 let tmp = tempfile::TempDir::new().expect("tempdir");
3121 let workspace = tmp.path().join("workspace");
3122 crate::test_support::trust_workspace(&workspace);
3123
3124 let claude_dir = workspace
3125 .join(".claude")
3126 .join("skills")
3127 .join("claude-skill");
3128 std::fs::create_dir_all(&claude_dir).expect("claude skill dir");
3129 std::fs::write(
3130 claude_dir.join("SKILL.md"),
3131 "---\nname: claude-skill\ndescription: Claude skill\n---\nbody\n",
3132 )
3133 .expect("write claude skill");
3134
3135 let codewhale_dir = workspace
3136 .join(".codewhale")
3137 .join("skills")
3138 .join("codewhale-skill");
3139 std::fs::create_dir_all(&codewhale_dir).expect("codewhale skill dir");
3140 std::fs::write(
3141 codewhale_dir.join("SKILL.md"),
3142 "---\nname: codewhale-skill\ndescription: CodeWhale skill\n---\nbody\n",
3143 )
3144 .expect("write codewhale skill");
3145
3146 let mut options = test_options(false);
3147 options.workspace = workspace.clone();
3148 options.skills_dir = tmp.path().join("global-skills");
3149 let app = App::new(options, &{
3150 let __cw_config_init_9_0 = Some(codewhale_runtime::config::SkillsConfig {
3151 scan_codewhale_only: Some(true),
3152 ..Default::default()
3153 });
3154 let mut __cw_config_init_9_value: Config = Default::default();
3155 __cw_config_init_9_value.skills = __cw_config_init_9_0;
3156 __cw_config_init_9_value
3157 });
3158
3159 assert_eq!(app.skills_dir, workspace.join(".codewhale").join("skills"));
3160 assert!(
3161 app.cached_skills
3162 .iter()
3163 .any(|(name, _)| name == "codewhale-skill"),
3164 "CodeWhale skill should be cached: {:?}",
3165 app.cached_skills
3166 );
3167 assert!(
3168 !app.cached_skills
3169 .iter()
3170 .any(|(name, _)| name == "claude-skill"),
3171 "strict scan should not cache Claude skills: {:?}",
3172 app.cached_skills
3173 );
3174 }
3175
3176 #[test]
3177 fn resolve_skills_dir_requires_codewhale_skills_to_be_directory() {
3178 let tmp = tempfile::TempDir::new().expect("tempdir");
3179 let workspace = tmp.path().join("workspace");
3180 std::fs::create_dir_all(workspace.join(".codewhale")).expect("codewhale dir");
3181 std::fs::write(
3182 workspace.join(".codewhale").join("skills"),
3183 "not a directory",
3184 )
3185 .expect("skills file");
3186
3187 let global_skills_dir = tmp.path().join("global-skills");
3188 let config = {
3189 let __cw_config_init_10_0 = Some(codewhale_runtime::config::SkillsConfig {
3190 scan_codewhale_only: Some(true),
3191 ..Default::default()
3192 });
3193 let mut __cw_config_init_10_value: Config = Default::default();
3194 __cw_config_init_10_value.skills = __cw_config_init_10_0;
3195 __cw_config_init_10_value
3196 };
3197
3198 let resolved = resolve_skills_dir(&workspace, &global_skills_dir, &config);
3199
3200 assert_eq!(resolved, global_skills_dir);
3201 }
3202
3203 #[test]
3204 fn resolve_skills_dir_ignores_untrusted_workspace_skills() {
3205 let tmp = tempfile::TempDir::new().expect("tempdir");
3206 let global_skills_dir = tmp.path().join("global-skills");
3207 for relative in [".agents/skills", "skills"] {
3208 let workspace = tmp
3209 .path()
3210 .join(format!("ws-{}", relative.replace('/', "-")));
3211 let local_skills = workspace.join(relative);
3212 std::fs::create_dir_all(&local_skills).expect("skills dir");
3213 let config = {
3214 let __cw_config_init_11_0 = Some(global_skills_dir.to_string_lossy().into_owned());
3215 let __cw_config_init_11_1 = Some(codewhale_runtime::config::SkillsConfig {
3216 flat_workspace_root: Some(true),
3217 ..Default::default()
3218 });
3219 let mut __cw_config_init_11_value: Config = Default::default();
3220 __cw_config_init_11_value.skills_dir = __cw_config_init_11_0;
3221 __cw_config_init_11_value.skills = __cw_config_init_11_1;
3222 __cw_config_init_11_value
3223 };
3224
3225 assert_eq!(
3226 resolve_skills_dir(&workspace, &global_skills_dir, &config),
3227 global_skills_dir,
3228 "untrusted {relative} must not be resolved as the skills dir"
3229 );
3230 crate::test_support::trust_workspace(&workspace);
3231 assert_eq!(
3232 resolve_skills_dir(&workspace, &global_skills_dir, &config),
3233 local_skills,
3234 "trusted {relative} resolves as before"
3235 );
3236 }
3237 }
3238
3239 #[test]
3240 fn cached_skills_include_configured_directory() {
3241 let tmp = tempfile::TempDir::new().expect("tempdir");
3242 let workspace = tmp.path().join("workspace");
3243
3244 let configured_dir = tmp.path().join("configured-skills");
3245 let configured_skill_dir = configured_dir.join("configured-skill");
3246 std::fs::create_dir_all(&configured_skill_dir).expect("configured skill dir");
3247 std::fs::write(
3248 configured_skill_dir.join("SKILL.md"),
3249 "---\nname: configured-skill\ndescription: Configured skill\n---\nbody\n",
3250 )
3251 .expect("write configured skill");
3252
3253 let mut options = test_options(false);
3254 options.workspace = workspace.clone();
3255 options.skills_dir = configured_dir.clone();
3256 let config = {
3257 let __cw_config_init_12_0 = Some(configured_dir.to_string_lossy().into_owned());
3258 let mut __cw_config_init_12_value: Config = Default::default();
3259 __cw_config_init_12_value.skills_dir = __cw_config_init_12_0;
3260 __cw_config_init_12_value
3261 };
3262 let app = App::new(options, &config);
3263
3264 assert!(
3265 app.cached_skills
3266 .iter()
3267 .any(|(name, description)| name == "configured-skill"
3268 && description == "Configured skill"),
3269 "configured skill dir should be merged: {:?}",
3270 app.cached_skills
3271 );
3272 }
3273
3274 #[test]
3275 fn cached_skills_preserve_configured_directory_in_codewhale_only_scan() {
3276 let tmp = tempfile::TempDir::new().expect("tempdir");
3277 let workspace = tmp.path().join("workspace");
3278 crate::test_support::trust_workspace(&workspace);
3279
3280 let codewhale_skill_dir = workspace
3281 .join(".codewhale")
3282 .join("skills")
3283 .join("workspace-codewhale");
3284 std::fs::create_dir_all(&codewhale_skill_dir).expect("workspace codewhale skill dir");
3285 std::fs::write(
3286 codewhale_skill_dir.join("SKILL.md"),
3287 "---\nname: workspace-codewhale\ndescription: Workspace CodeWhale skill\n---\nbody\n",
3288 )
3289 .expect("write workspace codewhale skill");
3290
3291 let configured_dir = tmp.path().join("configured-skills");
3292 let configured_skill_dir = configured_dir.join("configured-skill");
3293 std::fs::create_dir_all(&configured_skill_dir).expect("configured skill dir");
3294 std::fs::write(
3295 configured_skill_dir.join("SKILL.md"),
3296 "---\nname: configured-skill\ndescription: Configured skill\n---\nbody\n",
3297 )
3298 .expect("write configured skill");
3299
3300 let mut options = test_options(false);
3301 options.workspace = workspace.clone();
3302 options.skills_dir = configured_dir.clone();
3303 let config = {
3304 let __cw_config_init_13_0 = Some(configured_dir.to_string_lossy().into_owned());
3305 let __cw_config_init_13_1 = Some(codewhale_runtime::config::SkillsConfig {
3306 scan_codewhale_only: Some(true),
3307 ..Default::default()
3308 });
3309 let mut __cw_config_init_13_value: Config = Default::default();
3310 __cw_config_init_13_value.skills_dir = __cw_config_init_13_0;
3311 __cw_config_init_13_value.skills = __cw_config_init_13_1;
3312 __cw_config_init_13_value
3313 };
3314 let app = App::new(options, &config);
3315
3316 assert_eq!(app.skills_dir, configured_dir);
3317 assert!(
3318 app.cached_skills
3319 .iter()
3320 .any(|(name, _)| name == "workspace-codewhale"),
3321 "workspace CodeWhale skill should still be cached: {:?}",
3322 app.cached_skills
3323 );
3324 assert!(
3325 app.cached_skills
3326 .iter()
3327 .any(|(name, _)| name == "configured-skill"),
3328 "explicit configured skills_dir should still be cached: {:?}",
3329 app.cached_skills
3330 );
3331 }
3332
3333 #[test]
3334 fn cached_skills_reject_codewhale_only_workspace_symlink_escape() {
3335 let tmp = tempfile::TempDir::new().expect("tempdir");
3336 let workspace = tmp.path().join("workspace");
3337 let escape_target = tmp.path().join("escape-target");
3338 let escaped_skill_dir = escape_target.join("escaped-skill");
3339 std::fs::create_dir_all(workspace.join(".codewhale")).expect("codewhale dir");
3340 std::fs::create_dir_all(&escaped_skill_dir).expect("escaped skill dir");
3341 std::fs::write(
3342 escaped_skill_dir.join("SKILL.md"),
3343 "---\nname: escaped-skill\ndescription: Escaped skill\n---\nbody\n",
3344 )
3345 .expect("write escaped skill");
3346
3347 let link_path = workspace.join(".codewhale").join("skills");
3348 if create_dir_symlink(&escape_target, &link_path).is_err() {
3349 return;
3350 }
3351
3352 let global_skills_dir = tmp.path().join("global-skills");
3353 let mut options = test_options(false);
3354 options.workspace = workspace.clone();
3355 options.skills_dir = global_skills_dir.clone();
3356 let config = {
3357 let __cw_config_init_14_0 = Some(codewhale_runtime::config::SkillsConfig {
3358 scan_codewhale_only: Some(true),
3359 ..Default::default()
3360 });
3361 let mut __cw_config_init_14_value: Config = Default::default();
3362 __cw_config_init_14_value.skills = __cw_config_init_14_0;
3363 __cw_config_init_14_value
3364 };
3365 let app = App::new(options, &config);
3366
3367 assert_eq!(app.skills_dir, global_skills_dir);
3368 assert!(
3369 !app.cached_skills
3370 .iter()
3371 .any(|(name, _)| name == "escaped-skill"),
3372 "strict app cache must not follow escaped workspace CodeWhale symlinks: {:?}",
3373 app.cached_skills
3374 );
3375 }
3376
3377 #[test]
3378 fn paste_defers_oversized_text_consolidation_until_submit() {
3379 // (#3263): a large paste stays inline so the user can still edit it.
3380 // At submit time, the inline text is replaced by the @mention so the
3381 // model reads the full content from the paste file instead of receiving
3382 // it twice.
3383 let tmp = tempfile::TempDir::new().expect("tempdir");
3384 let mut opts = test_options(false);
3385 opts.workspace = tmp.path().to_path_buf();
3386 let mut app = App::new(opts, &Config::default());
3387 let full_content = "y".repeat(MAX_SUBMITTED_INPUT_CHARS + 256);
3388
3389 app.insert_paste_text(&full_content);
3390
3391 assert_eq!(app.input, full_content);
3392 assert_eq!(app.cursor_position, app.input.chars().count());
3393 let pastes_dir = tmp.path().join(".codewhale/pastes");
3394 assert!(
3395 !pastes_dir.exists() || std::fs::read_dir(&pastes_dir).unwrap().next().is_none(),
3396 "paste file should not be written before submit"
3397 );
3398 assert!(
3399 app.status_toasts
3400 .iter()
3401 .all(|toast| !toast.text.contains("backed up")),
3402 "backup toast should not appear before submit"
3403 );
3404
3405 let submitted = app.submit_input().expect("expected submitted input");
3406 // The submission is an attachment card, never a bare path: a size
3407 // header, the @-mention that attaches the file for the model, and a
3408 // bounded preview of the pasted content.
3409 assert!(
3410 submitted.starts_with("[Pasted content attached · "),
3411 "submission must open with the attachment header, got: {}",
3412 &submitted[..submitted.len().min(80)]
3413 );
3414 assert!(
3415 submitted.contains("\n@.codewhale/pastes/paste-"),
3416 "the @-mention must survive verbatim for file-mention resolution"
3417 );
3418 assert!(
3419 submitted.contains("--- preview ---\nyyy"),
3420 "a bounded preview of the pasted content must be visible"
3421 );
3422 let mention_line = submitted
3423 .lines()
3424 .find(|line| line.starts_with("@.codewhale/pastes/"))
3425 .expect("mention line");
3426 let mention = &mention_line[1..]; // strip leading '@'
3427 assert!(mention.ends_with(".md"), "expected .md extension");
3428 let abs = tmp.path().join(mention);
3429 assert!(abs.is_file(), "paste file must exist at {abs:?}");
3430 let written = std::fs::read_to_string(&abs).expect("read");
3431 assert_eq!(written, full_content);
3432 assert!(
3433 app.status_toasts
3434 .iter()
3435 .any(|toast| toast.text.contains("backed up")),
3436 "expected backup toast after submit"
3437 );
3438 }
3439
3440 #[test]
3441 fn oversized_paste_submission_never_renders_as_a_bare_path() {
3442 // The reported incident: a large paste became a transcript row that
3443 // showed only `@.codewhale/pastes/paste-….md` — a mysterious path where
3444 // the user's message should be. The submission must carry a visible
3445 // size header and content preview around the mention so the user can
3446 // always see what they sent.
3447 let tmp = tempfile::TempDir::new().expect("tempdir");
3448 let mut opts = test_options(false);
3449 opts.workspace = tmp.path().to_path_buf();
3450 let mut app = App::new(opts, &Config::default());
3451 let full_content = format!(
3452 "IMPORTANT INSTRUCTIONS\n{}",
3453 "x".repeat(MAX_SUBMITTED_INPUT_CHARS + 10)
3454 );
3455
3456 app.insert_paste_text(&full_content);
3457 let submitted = app.submit_input().expect("expected submitted input");
3458
3459 assert_ne!(submitted, submitted.lines().nth(1).expect("mention line"));
3460 assert!(
3461 submitted.contains("IMPORTANT INSTRUCTIONS"),
3462 "the preview must surface the pasted content's first line"
3463 );
3464 assert!(
3465 submitted.contains(&format!("· {} chars]", full_content.chars().count())),
3466 "the header must state the full pasted size"
3467 );
3468 // The full oversized content must NOT be inlined — the file is the
3469 // single source of truth for the model.
3470 assert!(
3471 !submitted.contains(&"x".repeat(MAX_SUBMITTED_INPUT_CHARS)),
3472 "the inline copy must stay bounded; the @-mention attaches the file"
3473 );
3474 }
3475
3476 #[test]
3477 fn paste_under_threshold_does_not_consolidate() {
3478 // Negative path: a small paste must NOT spawn a paste file. The
3479 // input stays inline so the user can edit it freely.
3480 let tmp = tempfile::TempDir::new().expect("tempdir");
3481 let mut opts = test_options(false);
3482 opts.workspace = tmp.path().to_path_buf();
3483 let mut app = App::new(opts, &Config::default());
3484 let small = "hello world\nthis is fine".to_string();
3485
3486 app.insert_paste_text(&small);
3487
3488 assert_eq!(app.input, small);
3489 assert!(!app.input.starts_with("@.codewhale/pastes/"));
3490 // No paste file gets written for under-cap pastes.
3491 let pastes_dir = tmp.path().join(".codewhale/pastes");
3492 assert!(
3493 !pastes_dir.exists() || std::fs::read_dir(&pastes_dir).unwrap().next().is_none(),
3494 "no paste file should be written for under-cap content"
3495 );
3496 }
3497
3498 #[test]
3499 fn large_multiline_paste_preserves_exact_bytes_through_submit() {
3500 // #4719: large multi-line pastes must not byte-corrupt before submission.
3501 // Real dogfood saw paths like `codewhale-v091-exact-88a158-ci` arrive as
3502 // `work-88a158-ci` — assert exact fidelity for a representative payload.
3503 let tmp = tempfile::TempDir::new().expect("tempdir");
3504 let mut opts = test_options(false);
3505 opts.workspace = tmp.path().to_path_buf();
3506 let mut app = App::new(opts, &Config::default());
3507
3508 let payload = format!(
3509 "Mission path: /Volumes/WorkSSD/project/worktrees/codewhale-v091-exact-88a158-ci\n\
3510 SHA: 0dfe9170a10e081fe48b23239f22d33260f4fa24\n\
3511 Branch: codex/v091-local-candidate-20260722\n\
3512 Paths that must not truncate: codewhale-v091-exact-88a158-ci worktrees/codewhale-v091-exact-88a158-ci\n\
3513 Mixed punctuation: a;b:c[m]<n> digits 0123456789 and hyphens-ok\n\
3514 Unicode: 你好世界 café — keep every codepoint.\n\
3515 {}",
3516 "line-body-".repeat(200)
3517 );
3518 // Stay under MAX_SUBMITTED_INPUT_CHARS so submit returns the inline text
3519 // (no @paste consolidation) and we can compare exact bytes.
3520 assert!(
3521 payload.chars().count() < MAX_SUBMITTED_INPUT_CHARS,
3522 "fixture must stay under submit consolidation threshold"
3523 );
3524
3525 app.insert_paste_text(&payload);
3526 assert_eq!(
3527 app.input, payload,
3528 "composer input must equal pasted payload exactly"
3529 );
3530
3531 let submitted = app.submit_input().expect("submit");
3532 assert_eq!(
3533 submitted, payload,
3534 "submitted bytes must equal pasted payload exactly"
3535 );
3536 }
3537
3538 #[test]
3539 fn submit_input_consolidates_oversized_input_into_paste_file() {
3540 let tmp = tempfile::TempDir::new().expect("tempdir");
3541 let mut opts = test_options(false);
3542 opts.workspace = tmp.path().to_path_buf();
3543 let mut app = App::new(opts, &Config::default());
3544 let full_content = "x".repeat(MAX_SUBMITTED_INPUT_CHARS + 128);
3545 app.input = full_content.clone();
3546 app.cursor_position = app.input.chars().count();
3547
3548 let submitted = app.submit_input().expect("expected submitted input");
3549
3550 // The submitted text is an attachment card: size header, the @-mention
3551 // that attaches the file for the model, and a bounded preview (#3263
3552 // follow-up: never a bare path).
3553 assert!(
3554 submitted.starts_with("[Pasted content attached · "),
3555 "submission must open with the attachment header, got: {}",
3556 &submitted[..submitted.len().min(80)]
3557 );
3558 let mention_line = submitted
3559 .lines()
3560 .find(|line| line.starts_with("@.codewhale/pastes/paste-"))
3561 .expect("mention line");
3562 assert!(
3563 mention_line.ends_with(".md"),
3564 "expected .md extension, got: {mention_line}"
3565 );
3566
3567 // The paste file must exist on disk with the full original content.
3568 let mention = &mention_line[1..]; // strip leading '@'
3569 let abs_path = tmp.path().join(mention);
3570 assert!(abs_path.is_file(), "paste file must exist at {abs_path:?}");
3571 let written = std::fs::read_to_string(&abs_path).expect("read paste file");
3572 assert_eq!(written, full_content);
3573
3574 // A status toast should have been pushed.
3575 assert!(
3576 app.status_toasts
3577 .iter()
3578 .any(|toast| toast.text.contains("backed up")),
3579 "expected backup toast, got: {:?}",
3580 app.status_toasts
3581 .iter()
3582 .map(|t| &t.text)
3583 .collect::<Vec<_>>()
3584 );
3585
3586 // The composer must be clear after submit.
3587 assert!(app.input.is_empty());
3588 }
3589
3590 #[test]
3591 fn submit_input_holds_oversized_input_when_paste_file_cannot_be_written() {
3592 let tmp = tempfile::TempDir::new().expect("tempdir");
3593 // `.codewhale` is a file, so `.codewhale/pastes` cannot be created.
3594 std::fs::write(tmp.path().join(".codewhale"), "not a dir").expect("seed file");
3595 let mut opts = test_options(false);
3596 opts.workspace = tmp.path().to_path_buf();
3597 let mut app = App::new(opts, &Config::default());
3598 let full_content = "y".repeat(MAX_SUBMITTED_INPUT_CHARS + 128);
3599 app.input = full_content.clone();
3600 app.cursor_position = app.input.chars().count();
3601
3602 assert_eq!(
3603 app.submit_input(),
3604 None,
3605 "a truncated prompt must not be sent"
3606 );
3607 assert_eq!(
3608 app.input, full_content,
3609 "the full text stays in the composer"
3610 );
3611 // The toast is short enough to survive the footer's clause-shedding...
3612 assert!(
3613 app.status_toasts
3614 .iter()
3615 .any(|toast| toast.text.starts_with("Not sent")
3616 && toast.text.contains("paste file not saved")),
3617 "expected a short not-sent toast"
3618 );
3619 // ...and the actionable reason, with the write error, is in the transcript.
3620 assert!(
3621 app.history.iter().any(|cell| matches!(
3622 cell,
3623 HistoryCell::System { content }
3624 if content.starts_with("Not sent")
3625 && content.contains("shorten it")
3626 && !content.contains("{error}")
3627 )),
3628 "expected the full reason in the transcript"
3629 );
3630 }
3631
3632 #[test]
3633 fn app_starts_without_seeded_transcript_messages() {
3634 let app = App::new(test_options(false), &Config::default());
3635 assert!(app.history.is_empty());
3636 assert_eq!(app.history_version, 0);
3637 }
3638
3639 #[test]
3640 fn clear_todos_resets_todos_list() {
3641 let mut app = App::new(test_options(false), &Config::default());
3642
3643 // Seed some todos.
3644 {
3645 let mut todos = app.todos.try_lock().expect("todos lock");
3646 todos.add("buy milk".to_string(), TodoStatus::Pending);
3647 todos.add("write code".to_string(), TodoStatus::InProgress);
3648 assert_eq!(todos.snapshot().items.len(), 2);
3649 }
3650
3651 assert!(app.clear_todos());
3652
3653 let todos = app.todos.try_lock().expect("todos lock");
3654 assert!(todos.snapshot().items.is_empty());
3655 }
3656
3657 #[test]
3658 fn clear_todos_resets_plan_state() {
3659 let mut app = App::new(test_options(false), &Config::default());
3660
3661 {
3662 let mut plan = app
3663 .plan_state
3664 .try_lock()
3665 .expect("plan lock should be available");
3666 plan.update(UpdatePlanArgs {
3667 explanation: Some("test plan".to_string()),
3668 plan: vec![PlanItemArg {
3669 step: "step 1".to_string(),
3670 status: StepStatus::InProgress,
3671 }],
3672 ..UpdatePlanArgs::default()
3673 });
3674 assert!(!plan.snapshot().is_empty());
3675 }
3676
3677 assert!(app.clear_todos());
3678
3679 let plan = app
3680 .plan_state
3681 .try_lock()
3682 .expect("plan lock should be available");
3683 assert!(plan.snapshot().is_empty());
3684 }
3685
3686 #[test]
3687 fn work_state_snapshot_round_trips_todos_and_plan() {
3688 let app = App::new(test_options(false), &Config::default());
3689 {
3690 let mut todos = app.todos.try_lock().expect("todos lock");
3691 todos.add("inspect".to_string(), TodoStatus::Completed);
3692 todos.add("patch".to_string(), TodoStatus::InProgress);
3693 }
3694 {
3695 let mut plan = app.plan_state.try_lock().expect("plan lock");
3696 plan.update(UpdatePlanArgs {
3697 objective: Some("Keep Work durable".to_string()),
3698 plan: vec![PlanItemArg {
3699 step: "verify".to_string(),
3700 status: StepStatus::InProgress,
3701 }],
3702 ..UpdatePlanArgs::default()
3703 });
3704 }
3705 let state = app
3706 .work_state_snapshot()
3707 .expect("snapshot locks")
3708 .expect("non-empty state");
3709
3710 let mut restored = App::new(test_options(false), &Config::default());
3711 let restored_workspace = restored.workspace.clone();
3712 restored
3713 .restore_work_state("restored-session", &restored_workspace, Some(&state))
3714 .expect("restore Work state");
3715 assert_eq!(
3716 restored.work_state_snapshot().expect("snapshot"),
3717 Some(state)
3718 );
3719 }
3720
3721 #[test]
3722 fn work_restore_reconciles_fleet_from_the_restored_workspace() {
3723 let restored_workspace = tempfile::tempdir().expect("restored workspace");
3724 let ledger = codewhale_engine::fleet::ledger::FleetLedger::open(restored_workspace.path())
3725 .expect("open restored Fleet ledger");
3726 ledger
3727 .enqueue(codewhale_protocol::fleet::FleetInboxEntry {
3728 run_id: codewhale_protocol::fleet::FleetRunId::from("run-restore"),
3729 task_id: "task-restore".to_string(),
3730 priority: 0,
3731 enqueued_at: "2026-07-18T00:00:00Z".to_string(),
3732 lease_deadline: None,
3733 attempts: 0,
3734 })
3735 .expect("enqueue restored Fleet task");
3736
3737 let source = codewhale_engine::work_graph::new_shared_work_runtime(
3738 codewhale_engine::tools::todo::new_shared_todo_list(),
3739 codewhale_engine::tools::plan::new_shared_plan_state(),
3740 );
3741 source
3742 .register_operation(
3743 "restored-session",
3744 codewhale_engine::work_graph::OperationIntent::new(
3745 "fleet:run-restore/task-restore",
3746 "restored Fleet task",
3747 true,
3748 "fleet",
3749 "restore-test",
3750 ),
3751 )
3752 .expect("register Fleet binding");
3753 let captured = source
3754 .capture(Some("restored-session"))
3755 .expect("capture source Work state")
3756 .expect("non-empty source Work state");
3757 let state = codewhale_engine::session_manager::SessionWorkState {
3758 graph: Some(captured.graph),
3759 todos: captured.todos,
3760 plan: captured.plan,
3761 };
3762
3763 let mut app = App::new(test_options(false), &Config::default());
3764 assert_ne!(app.workspace, restored_workspace.path());
3765 app.restore_work_state("restored-session", restored_workspace.path(), Some(&state))
3766 .expect("restore Work state from target workspace");
3767 let graph = app
3768 .runtime_services
3769 .work
3770 .as_ref()
3771 .expect("Work runtime")
3772 .capture(Some("restored-session"))
3773 .expect("capture restored Work state")
3774 .expect("restored graph")
3775 .graph;
3776 let operation = graph
3777 .nodes
3778 .iter()
3779 .find(|node| {
3780 node.binding
3781 .as_ref()
3782 .is_some_and(|binding| binding.external == "fleet:run-restore/task-restore")
3783 })
3784 .expect("restored Fleet operation");
3785 assert_eq!(
3786 operation.state,
3787 codewhale_engine::work_graph::NodeState::Initializing,
3788 "the target workspace ledger must outrank the app's previous workspace"
3789 );
3790 }
3791
3792 #[test]
3793 fn failed_workspace_owner_reconcile_leaves_previous_work_state_intact() {
3794 let restored_workspace = tempfile::tempdir().expect("restored workspace");
3795 let ledger = codewhale_engine::fleet::ledger::FleetLedger::open(restored_workspace.path())
3796 .expect("open restored Fleet ledger");
3797 ledger
3798 .enqueue(codewhale_protocol::fleet::FleetInboxEntry {
3799 run_id: codewhale_protocol::fleet::FleetRunId::from("run-regress"),
3800 task_id: "task-regress".to_string(),
3801 priority: 0,
3802 enqueued_at: "2026-07-18T00:00:00Z".to_string(),
3803 lease_deadline: None,
3804 attempts: 0,
3805 })
3806 .expect("enqueue older Fleet owner state");
3807
3808 let incoming = codewhale_engine::work_graph::new_shared_work_runtime(
3809 codewhale_engine::tools::todo::new_shared_todo_list(),
3810 codewhale_engine::tools::plan::new_shared_plan_state(),
3811 );
3812 incoming
3813 .register_operation(
3814 "incoming-session",
3815 codewhale_engine::work_graph::OperationIntent::new(
3816 "fleet:run-regress/task-regress",
3817 "newer saved Fleet task",
3818 true,
3819 "fleet",
3820 "regression-test",
3821 ),
3822 )
3823 .expect("register incoming Fleet binding");
3824 incoming
3825 .reconcile_operation(
3826 "incoming-session",
3827 codewhale_engine::work_graph::OperationOwnerSnapshot::new(
3828 "fleet:run-regress/task-regress",
3829 codewhale_engine::work_graph::OwnerState::Running,
3830 2,
3831 2,
3832 ),
3833 )
3834 .expect("record newer saved owner sequence");
3835 let incoming = incoming
3836 .capture(Some("incoming-session"))
3837 .expect("capture incoming state")
3838 .expect("incoming graph");
3839 let incoming = codewhale_engine::session_manager::SessionWorkState {
3840 graph: Some(incoming.graph),
3841 todos: incoming.todos,
3842 plan: incoming.plan,
3843 };
3844
3845 let mut app = App::new(test_options(false), &Config::default());
3846 let work = app
3847 .runtime_services
3848 .work
3849 .as_ref()
3850 .expect("Work runtime")
3851 .clone();
3852 work.register_operation(
3853 "previous-session",
3854 codewhale_engine::work_graph::OperationIntent::new(
3855 "shell:shell_previous",
3856 "previous operation",
3857 false,
3858 "exec_shell",
3859 "previous-test",
3860 ),
3861 )
3862 .expect("register previous state");
3863 let before = work
3864 .capture(Some("previous-session"))
3865 .expect("capture previous state")
3866 .expect("previous graph");
3867
3868 let error = app
3869 .restore_work_state(
3870 "incoming-session",
3871 restored_workspace.path(),
3872 Some(&incoming),
3873 )
3874 .expect_err("owner sequence regression must fail closed");
3875 assert!(error.contains("sequence regressed"), "{error}");
3876 assert_eq!(
3877 work.capture(Some("previous-session"))
3878 .expect("capture state after failed restore")
3879 .expect("previous graph remains"),
3880 before,
3881 "failed restore must not replace any part of the previous Work state"
3882 );
3883 }
3884
3885 #[test]
3886 fn entering_operate_preserves_user_rail_panel() {
3887 let mut app = App::new(test_options(false), &Config::default());
3888 app.work_surface.panel = crate::tui::work_surface::RailPanel::Agents;
3889
3890 assert!(app.set_mode(AppMode::Plan));
3891 assert_eq!(
3892 app.work_surface.panel,
3893 crate::tui::work_surface::RailPanel::Agents
3894 );
3895 }
3896
3897 #[test]
3898 fn effective_route_display_tracks_inflight_and_last_auto_provider() {
3899 let mut app = App::new(test_options(false), &Config::default());
3900 app.auto_model = true;
3901 app.pending_turn_route = Some((ProviderKind::Zai, "glm-5.2".to_string(), true));
3902 assert_eq!(
3903 app.effective_route_display(),
3904 (ProviderKind::Zai, "glm-5.2".to_string())
3905 );
3906
3907 app.pending_turn_route = None;
3908 app.last_effective_provider = Some(ProviderKind::Xai);
3909 app.last_effective_model = Some("grok-4.5".to_string());
3910 assert_eq!(
3911 app.effective_route_display(),
3912 (ProviderKind::Xai, "grok-4.5".to_string())
3913 );
3914 }
3915
3916 #[test]
3917 fn test_mode_scenario() {
3918 // Scenario consolidation of: test_mode_switch_does_not_emit_redundant_toast, test_mode_switch_toasts_do_not_disrupt_non_mode_toasts
3919 // from test_mode_switch_does_not_emit_redundant_toast
3920 {
3921 let mut app = App::new(test_options(false), &Config::default());
3922 let first_mode = AppMode::Plan;
3923 let second_mode = AppMode::Agent;
3924
3925 app.set_mode(first_mode);
3926
3927 assert!(app.status_toasts.is_empty());
3928
3929 app.set_mode(second_mode);
3930
3931 assert!(app.status_toasts.is_empty());
3932 }
3933 // from test_mode_switch_toasts_do_not_disrupt_non_mode_toasts
3934 {
3935 let mut app = App::new(test_options(false), &Config::default());
3936 app.show_event_notice("Task queued", crate::tui::app::StatusToastLevel::Success);
3937
3938 app.set_mode(AppMode::Plan);
3939
3940 app.set_mode(AppMode::Agent);
3941
3942 assert_eq!(app.status_toasts.len(), 1);
3943 assert!(
3944 app.status_toasts
3945 .iter()
3946 .any(|toast| toast.text == "Task queued")
3947 );
3948 }
3949 }
3950
3951 #[test]
3952 fn test_clear_input() {
3953 let mut app = App::new(test_options(false), &Config::default());
3954 app.input = "test input".to_string();
3955 app.cursor_position = app.input.len();
3956 app.clear_input();
3957 assert!(app.input.is_empty());
3958 assert_eq!(app.cursor_position, 0);
3959 }
3960
3961 #[test]
3962 fn test_queue_message() {
3963 let mut app = App::new(test_options(false), &Config::default());
3964 app.queue_message(QueuedMessage::new("test message".to_string(), None));
3965 assert_eq!(app.queued_message_count(), 1);
3966 assert!(app.queued_messages.front().is_some());
3967 }
3968
3969 #[test]
3970 fn queue_message_at_cap_returns_message_to_composer() {
3971 let mut app = App::new(test_options(false), &Config::default());
3972 for index in 0..MAX_QUEUED_MESSAGES {
3973 app.queue_message(QueuedMessage::new(format!("m{index}"), None));
3974 }
3975 app.queue_message(QueuedMessage::new("overflow".to_string(), None));
3976 assert_eq!(app.queued_message_count(), MAX_QUEUED_MESSAGES);
3977 assert_eq!(app.input, "overflow");
3978 }
3979
3980 #[test]
3981 fn test_remove_scenario() {
3982 // Scenario consolidation of: test_remove_queued_message, test_remove_queued_message_invalid_index
3983 // from test_remove_queued_message
3984 {
3985 let mut app = App::new(test_options(false), &Config::default());
3986 app.queue_message(QueuedMessage::new("first".to_string(), None));
3987 app.queue_message(QueuedMessage::new("second".to_string(), None));
3988
3989 // Remove first (index 0)
3990 let removed = app.remove_queued_message(0);
3991 assert!(removed.is_some());
3992 assert_eq!(app.queued_message_count(), 1);
3993
3994 // Remove second (now at index 0)
3995 let removed = app.remove_queued_message(0);
3996 assert!(removed.is_some());
3997 assert_eq!(app.queued_message_count(), 0);
3998 }
3999 // from test_remove_queued_message_invalid_index
4000 {
4001 let mut app = App::new(test_options(false), &Config::default());
4002 app.queue_message(QueuedMessage::new("test".to_string(), None));
4003
4004 // Try to remove non-existent index
4005 let removed = app.remove_queued_message(100);
4006 assert!(removed.is_none());
4007 }
4008 }
4009
4010 #[test]
4011 fn test_set_mode_updates_state() {
4012 let mut app = App::new(test_options(false), &Config::default());
4013 app.set_mode(AppMode::Plan);
4014 assert_eq!(app.mode, AppMode::Plan);
4015 app.set_mode(AppMode::Agent);
4016 assert_eq!(app.mode, AppMode::Agent);
4017 }
4018
4019 #[test]
4020 fn set_mode_scenario() {
4021 {
4022 let config = {
4023 let __cw_config_init_15_0 = Some("never".to_string());
4024 let mut __cw_config_init_15_value: Config = Default::default();
4025 __cw_config_init_15_value.approval_policy = __cw_config_init_15_0;
4026 __cw_config_init_15_value
4027 };
4028 let mut options = test_options(false);
4029 options.start_in_agent_mode = true;
4030 let mut app = App::new(options, &config);
4031 assert_eq!(app.mode, AppMode::Agent);
4032 assert_eq!(app.approval_mode, ApprovalMode::Never);
4033
4034 app.set_mode(AppMode::Plan);
4035 app.approval_mode = ApprovalMode::Suggest;
4036
4037 app.set_mode(AppMode::Agent);
4038 assert_eq!(app.mode, AppMode::Agent);
4039 assert_eq!(app.approval_mode, ApprovalMode::Never);
4040 }
4041 }
4042
4043 #[test]
4044 fn base_policy_for_mode_projects_the_mode_permission_table() {
4045 // Pure projection of (mode, prefs) — the single source of truth for #3386.
4046 let prefs = ModeSessionPrefs {
4047 agent_allow_shell: true,
4048 agent_trust_mode: true,
4049 agent_approval_mode: ApprovalMode::Never,
4050 };
4051
4052 // Plan: read-only, no shell, no trust, Suggest — and it never inherits the
4053 // (here elevated) Agent baseline.
4054 let plan = base_policy_for_mode(AppMode::Plan, &prefs);
4055 assert_eq!(plan.mode, AppMode::Plan);
4056 assert!(!plan.allow_shell);
4057 assert!(!plan.trust_mode);
4058 assert_eq!(plan.approval_mode, ApprovalMode::Suggest);
4059
4060 // Agent: exactly the durable baseline.
4061 let agent = base_policy_for_mode(AppMode::Agent, &prefs);
4062 assert_eq!(agent.mode, AppMode::Agent);
4063 assert!(agent.allow_shell);
4064 assert!(agent.trust_mode);
4065 assert_eq!(agent.approval_mode, ApprovalMode::Never);
4066
4067 // Work uses the Agent baseline.
4068 let work = base_policy_for_mode(AppMode::Agent, &prefs);
4069 assert_eq!(work.allow_shell, agent.allow_shell);
4070 assert_eq!(work.trust_mode, agent.trust_mode);
4071 assert_eq!(work.approval_mode, ApprovalMode::Never);
4072
4073 // Full Access is represented by the Bypass posture, not a mode row or a
4074 // separate auto-approve field (#3736).
4075
4076 // A minimal Agent baseline projects through Agent unchanged.
4077 let minimal = ModeSessionPrefs {
4078 agent_allow_shell: false,
4079 agent_trust_mode: false,
4080 agent_approval_mode: ApprovalMode::Suggest,
4081 };
4082 let agent_min = base_policy_for_mode(AppMode::Agent, &minimal);
4083 assert!(!agent_min.allow_shell);
4084 assert!(!agent_min.trust_mode);
4085 assert_eq!(agent_min.approval_mode, ApprovalMode::Suggest);
4086 }
4087
4088 #[test]
4089 fn every_dial_step_writes_one_permissions_receipt() {
4090 let _env_lock = lock_test_env();
4091 let tmp = tempfile::tempdir().expect("tempdir");
4092 let config_path = tmp.path().join("config.toml");
4093 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4094 let mut options = test_options(false);
4095 options.start_in_agent_mode = true;
4096 options.config_path = Some(config_path);
4097 let mut app = App::new(options, &Config::default());
4098 app.set_agent_approval_posture(ApprovalMode::AcceptEdits);
4099 app.history.clear();
4100 app.yolo_compat_notified = true;
4101
4102 let mut receipts = Vec::new();
4103 for _ in 0..5 {
4104 let before = app.history.len();
4105 assert!(app.step_permission_dial(false).changed());
4106 let added: Vec<String> = app.history[before..]
4107 .iter()
4108 .filter_map(|cell| match cell {
4109 HistoryCell::System { content } if content.starts_with("Permissions changed") => {
4110 Some(content.clone())
4111 }
4112 _ => None,
4113 })
4114 .collect();
4115 assert_eq!(added.len(), 1, "one receipt per press: {added:?}");
4116 receipts.extend(added);
4117 }
4118 assert_eq!(
4119 receipts,
4120 [
4121 "Permissions changed to Plan",
4122 "Permissions changed to Auto-Review",
4123 "Permissions changed to Full Access",
4124 "Permissions changed to Ask",
4125 "Permissions changed to Accept Edits",
4126 ]
4127 );
4128 }
4129
4130 #[test]
4131 fn cycle_approval_scenario() {
4132 // Scenario consolidation of: the permission dial walk, cycle_approval_posture_emits_rebinding_notice_once
4133 // from the permission dial walk
4134 {
4135 let _env_lock = lock_test_env();
4136 let tmp = tempfile::tempdir().expect("tempdir");
4137 let config_path = tmp.path().join("config.toml");
4138 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4139 let mut options = test_options(false);
4140 options.start_in_agent_mode = true;
4141 options.config_path = Some(config_path);
4142 let mut app = App::new(options, &Config::default());
4143 app.set_agent_approval_posture(ApprovalMode::Suggest);
4144
4145 for (mode, posture) in [
4146 (AppMode::Agent, ApprovalMode::AcceptEdits),
4147 (AppMode::Plan, ApprovalMode::AcceptEdits),
4148 (AppMode::Agent, ApprovalMode::Auto),
4149 (AppMode::Agent, ApprovalMode::Bypass),
4150 (AppMode::Agent, ApprovalMode::Suggest),
4151 ] {
4152 assert!(app.step_permission_dial(false).changed());
4153 assert_eq!(app.mode, mode);
4154 assert_eq!(app.mode_prefs.agent_approval_mode, posture);
4155 if mode == AppMode::Agent {
4156 assert_eq!(app.approval_mode, posture);
4157 }
4158 }
4159 let persisted =
4160 std::fs::read_to_string(tmp.path().join("settings.toml")).expect("settings");
4161 assert!(persisted.contains("permission_posture = \"ask\""));
4162 }
4163 {
4164 let _env_lock = lock_test_env();
4165 let tmp = tempfile::tempdir().expect("tempdir");
4166 let config_path = tmp.path().join("config.toml");
4167 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4168 let mut options = test_options(false);
4169 options.start_in_agent_mode = true;
4170 options.config_path = Some(config_path);
4171 let mut config = Config::default();
4172 config.auto_review = Some(codewhale_runtime::config::AutoReviewConfig {
4173 disabled: true,
4174 ..Default::default()
4175 });
4176 let mut app = App::new(options, &config);
4177 app.set_agent_approval_posture(ApprovalMode::Suggest);
4178
4179 for (mode, posture) in [
4180 (AppMode::Agent, ApprovalMode::AcceptEdits),
4181 (AppMode::Plan, ApprovalMode::AcceptEdits),
4182 (AppMode::Agent, ApprovalMode::Bypass),
4183 (AppMode::Agent, ApprovalMode::Suggest),
4184 ] {
4185 assert!(app.step_permission_dial(false).changed());
4186 assert_eq!(app.mode, mode);
4187 assert_eq!(app.mode_prefs.agent_approval_mode, posture);
4188 if mode == AppMode::Agent {
4189 assert_eq!(app.approval_mode, posture);
4190 }
4191 }
4192 }
4193 // from cycle_approval_posture_emits_rebinding_notice_once
4194 {
4195 let _env_lock = lock_test_env();
4196 let tmp = tempfile::tempdir().expect("tempdir");
4197 let config_path = tmp.path().join("config.toml");
4198 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4199 let mut options = test_options(false);
4200 options.start_in_agent_mode = true;
4201 options.config_path = Some(config_path);
4202 let mut app = App::new(options, &Config::default());
4203
4204 assert!(app.select_approval_posture(ApprovalMode::Auto));
4205 let notices = app
4206 .status_toasts
4207 .iter()
4208 .filter(|toast| toast.text.contains("moved to Ctrl+T"))
4209 .count();
4210 assert_eq!(notices, 1, "first cycle posts the rebinding notice");
4211
4212 assert!(app.select_approval_posture(ApprovalMode::Bypass));
4213 let notices = app
4214 .status_toasts
4215 .iter()
4216 .filter(|toast| toast.text.contains("moved to Ctrl+T"))
4217 .count();
4218 assert_eq!(notices, 1, "notice is one-shot per session");
4219 }
4220 }
4221
4222 #[test]
4223 fn auto_review_posture_transition_emits_broad_allow_pause_note_when_suspended() {
4224 let _env_lock = lock_test_env();
4225 let tmp = tempfile::tempdir().expect("tempdir");
4226 let config_path = tmp.path().join("config.toml");
4227 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4228 let mut options = test_options(false);
4229 options.start_in_agent_mode = true;
4230 options.config_path = Some(config_path);
4231
4232 let mut broad_shell_allow = codewhale_runtime::config::AutoReviewRuleConfig::default();
4233 broad_shell_allow.id = Some("broad-shell".to_string());
4234 broad_shell_allow.action_kind = Some("shell".to_string());
4235 broad_shell_allow.reason = Some("allow shell".to_string());
4236
4237 let mut cfg = Config::default();
4238 cfg.auto_review = Some(codewhale_runtime::config::AutoReviewConfig {
4239 allow: vec![broad_shell_allow],
4240 ..Default::default()
4241 });
4242 let mut app = App::new(options.clone(), &cfg);
4243 app.ui_locale = codewhale_localization::Locale::En;
4244 app.set_agent_approval_posture(ApprovalMode::Suggest);
4245
4246 let before = app.history.len();
4247 assert!(app.select_approval_posture(ApprovalMode::Auto));
4248 let notes: Vec<_> = app.history[before..]
4249 .iter()
4250 .filter_map(|cell| match cell {
4251 HistoryCell::System { content }
4252 if content.contains("Broad allow rules are paused while Auto-Review is on") =>
4253 {
4254 Some(content.clone())
4255 }
4256 _ => None,
4257 })
4258 .collect();
4259 assert_eq!(notes.len(), 1, "{notes:?}");
4260
4261 assert!(app.select_approval_posture(ApprovalMode::Suggest));
4262 let step_before = app.history.len();
4263 assert!(app.select_approval_posture(ApprovalMode::Auto));
4264 let notes_second: Vec<_> = app.history[step_before..]
4265 .iter()
4266 .filter_map(|cell| match cell {
4267 HistoryCell::System { content }
4268 if content.contains("Broad allow rules are paused while Auto-Review is on") =>
4269 {
4270 Some(content.clone())
4271 }
4272 _ => None,
4273 })
4274 .collect();
4275 assert_eq!(notes_second.len(), 1, "{notes_second:?}");
4276
4277 let mut clean_app = App::new(options, &Config::default());
4278 clean_app.ui_locale = codewhale_localization::Locale::En;
4279 clean_app.set_agent_approval_posture(ApprovalMode::Suggest);
4280 let clean_before = clean_app.history.len();
4281 assert!(clean_app.select_approval_posture(ApprovalMode::Auto));
4282 let clean_notes: Vec<_> = clean_app.history[clean_before..]
4283 .iter()
4284 .filter_map(|cell| match cell {
4285 HistoryCell::System { content } if content.contains("Broad allow rules are paused") => {
4286 Some(content.clone())
4287 }
4288 _ => None,
4289 })
4290 .collect();
4291 assert!(clean_notes.is_empty(), "{clean_notes:?}");
4292 }
4293
4294 #[test]
4295 fn startup_in_auto_review_emits_broad_allow_pause_note_once() {
4296 let _env_lock = lock_test_env();
4297 let tmp = tempfile::tempdir().expect("tempdir");
4298 let config_path = tmp.path().join("config.toml");
4299 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4300 let mut options = test_options(false);
4301 options.start_in_agent_mode = true;
4302 options.config_path = Some(config_path);
4303
4304 let mut broad_shell_allow = codewhale_runtime::config::AutoReviewRuleConfig::default();
4305 broad_shell_allow.id = Some("broad-shell".to_string());
4306 broad_shell_allow.action_kind = Some("shell".to_string());
4307 broad_shell_allow.reason = Some("allow shell".to_string());
4308
4309 let mut cfg = Config::default();
4310 cfg.approval_policy = Some("auto-review".to_string());
4311 cfg.auto_review = Some(codewhale_runtime::config::AutoReviewConfig {
4312 allow: vec![broad_shell_allow],
4313 ..Default::default()
4314 });
4315 let mut app = App::new(options.clone(), &cfg);
4316 app.ui_locale = codewhale_localization::Locale::En;
4317 let count_notes = |a: &App| {
4318 let expected = a.tr(MessageId::AutoReceiptBroadAllowsPaused);
4319 a.history
4320 .iter()
4321 .filter(|cell| matches!(cell, HistoryCell::System { content } if content == expected.as_ref()))
4322 .count()
4323 };
4324 assert_eq!(count_notes(&app), 1);
4325
4326 app.apply_cli_permission_mode(Some(
4327 codewhale_engine::runtime_options::PermissionMode::AutoReview,
4328 ));
4329 assert_eq!(count_notes(&app), 1);
4330
4331 let mut clean_cfg = Config::default();
4332 clean_cfg.approval_policy = Some("auto-review".to_string());
4333 let clean_app = App::new(options.clone(), &clean_cfg);
4334 assert_eq!(count_notes(&clean_app), 0);
4335
4336 let mut cli_cfg = cfg;
4337 cli_cfg.approval_policy = None;
4338 let mut cli_app = App::new(options, &cli_cfg);
4339 cli_app.ui_locale = codewhale_localization::Locale::En;
4340 assert_eq!(count_notes(&cli_app), 0);
4341 cli_app.apply_cli_permission_mode(Some(
4342 codewhale_engine::runtime_options::PermissionMode::AutoReview,
4343 ));
4344 assert_eq!(cli_app.approval_mode, ApprovalMode::Auto);
4345 assert_eq!(count_notes(&cli_app), 1);
4346 }
4347
4348 #[test]
4349 fn plan_permission_cycle_moves_the_baseline_and_leaves_plan_read_only() {
4350 let _env_lock = lock_test_env();
4351 let tmp = tempfile::tempdir().expect("tempdir");
4352 let config_path = tmp.path().join("config.toml");
4353 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4354 let mut options = test_options(false);
4355 options.config_path = Some(config_path);
4356 let mut app = App::new(options, &Config::default());
4357 app.set_agent_approval_posture(ApprovalMode::Auto);
4358 app.set_mode(AppMode::Plan);
4359
4360 assert!(
4361 app.select_approval_posture(ApprovalMode::Bypass),
4362 "permissions must still change while in Plan"
4363 );
4364 assert_eq!(
4365 app.mode_prefs.agent_approval_mode,
4366 ApprovalMode::Bypass,
4367 "the durable baseline advances Auto -> Full Access"
4368 );
4369 assert_eq!(
4370 app.approval_mode,
4371 ApprovalMode::Suggest,
4372 "Plan's live policy is untouched: it stays read-only and asks"
4373 );
4374 assert_eq!(
4375 app.mode,
4376 AppMode::Plan,
4377 "changing permissions must not move the mode"
4378 );
4379 assert!(
4380 app.status_toasts
4381 .iter()
4382 .any(|toast| toast.text.contains("applies in Work")),
4383 "the receipt must say when the new posture starts applying"
4384 );
4385
4386 let persisted = std::fs::read_to_string(tmp.path().join("settings.toml")).expect("settings");
4387 assert!(
4388 persisted.contains("permission_posture = \"full-access\""),
4389 "the posture is durable, not dropped because Plan was active: {persisted}"
4390 );
4391
4392 app.set_mode(AppMode::Agent);
4393 assert_eq!(
4394 app.approval_mode,
4395 ApprovalMode::Bypass,
4396 "leaving Plan projects the posture chosen while in Plan"
4397 );
4398 }
4399
4400 #[test]
4401 fn busy_permission_cycle_moves_the_live_posture() {
4402 let _env_lock = lock_test_env();
4403 let tmp = tempfile::tempdir().expect("tempdir");
4404 let config_path = tmp.path().join("config.toml");
4405 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4406 let mut options = test_options(false);
4407 options.config_path = Some(config_path);
4408 let mut app = App::new(options, &Config::default());
4409 let before = (app.mode, app.mode_prefs.agent_approval_mode);
4410 app.is_loading = true;
4411
4412 assert!(app.step_permission_dial(false).changed());
4413 assert_ne!((app.mode, app.mode_prefs.agent_approval_mode), before);
4414 assert!(
4415 !app.visible_notice_text()
4416 .as_deref()
4417 .is_some_and(|message| message.contains("locked"))
4418 );
4419 }
4420
4421 #[test]
4422 fn permission_postures_persist_across_restart() {
4423 let _env_lock = lock_test_env();
4424 for expected in [
4425 ApprovalMode::AcceptEdits,
4426 ApprovalMode::Auto,
4427 ApprovalMode::Bypass,
4428 ApprovalMode::Suggest,
4429 ] {
4430 let tmp = tempfile::tempdir().expect("tempdir");
4431 let path = tmp.path().join("config.toml");
4432 let config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &path);
4433 let mut options = test_options(false);
4434 options.start_in_agent_mode = true;
4435 options.config_path = Some(path.clone());
4436 let mut app = App::new(options.clone(), &Config::default());
4437 if app.approval_mode == expected {
4438 assert!(app.select_approval_posture(ApprovalMode::Auto));
4439 }
4440 assert!(app.select_approval_posture(expected));
4441 assert_eq!(app.approval_mode, expected);
4442 assert_eq!(app.trust_mode, expected == ApprovalMode::Bypass);
4443
4444 let restarted = App::new(options, &Config::default());
4445 assert_eq!(restarted.approval_mode, expected);
4446 assert_eq!(restarted.mode_prefs.agent_approval_mode, expected);
4447 assert_eq!(restarted.trust_mode, expected == ApprovalMode::Bypass);
4448 drop(config_env);
4449 }
4450 }
4451
4452 #[test]
4453 fn shift_tab_migrates_user_root_policy_to_durable_tui_posture() {
4454 let _env_lock = lock_test_env();
4455 let tmp = tempfile::tempdir().expect("tempdir");
4456 let config_path = tmp.path().join("config.toml");
4457 let settings_path = tmp.path().join("settings.toml");
4458 std::fs::write(&config_path, "# keep\napproval_policy = \"on-request\"\n")
4459 .expect("root config");
4460 std::fs::write(&settings_path, "permission_posture = \"full-access\"\n").expect("settings");
4461 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4462 let _approval_env = EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY");
4463 let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)
4464 .expect("load config");
4465 let mut options = test_options(false);
4466 options.start_in_agent_mode = true;
4467 options.config_path = Some(config_path.clone());
4468
4469 let mut app = App::new(options.clone(), &config);
4470 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
4471 assert!(app.approval_policy_locked());
4472
4473 assert!(app.step_permission_dial(true).posture_changed);
4474 assert_eq!(app.approval_mode, ApprovalMode::AcceptEdits);
4475 assert!(!app.approval_policy_locked());
4476 let saved_config = std::fs::read_to_string(&config_path).expect("saved config");
4477 assert!(saved_config.contains("# keep"));
4478 assert!(!saved_config.contains("approval_policy"));
4479 let saved_settings = std::fs::read_to_string(&settings_path).expect("saved settings");
4480 assert!(saved_settings.contains("permission_posture = \"accept-edits\""));
4481
4482 let restarted_config =
4483 codewhale_plugins::providers::load_config(Some(config_path), None).expect("reload config");
4484 let restarted = App::new(options, &restarted_config);
4485 assert_eq!(restarted.approval_mode, ApprovalMode::AcceptEdits);
4486 assert!(!restarted.approval_policy_locked());
4487 }
4488
4489 #[test]
4490 fn legacy_yolo_migrates_root_policy_to_agent_full_access() {
4491 let _env_lock = lock_test_env();
4492 let tmp = tempfile::tempdir().expect("tempdir");
4493 let config_path = tmp.path().join("config.toml");
4494 let settings_path = tmp.path().join("settings.toml");
4495 let workspace = tmp.path().join("workspace");
4496 std::fs::create_dir_all(&workspace).expect("workspace");
4497 std::fs::write(&config_path, "# keep\napproval_policy = \"on-request\"\n")
4498 .expect("legacy config");
4499 std::fs::write(&settings_path, "default_mode = \"yolo\"\n").expect("legacy settings");
4500 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4501 let _approval_env = EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY");
4502 let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)
4503 .expect("load config");
4504 let mut options = test_options(false);
4505 options.start_in_agent_mode = false;
4506 options.workspace = workspace;
4507 options.config_path = Some(config_path.clone());
4508
4509 let app = App::new(options.clone(), &config);
4510
4511 assert_eq!(app.mode, AppMode::Agent);
4512 assert_eq!(app.approval_mode, ApprovalMode::Bypass);
4513 assert!(!app.approval_policy_locked());
4514 let saved_config = std::fs::read_to_string(&config_path).expect("saved config");
4515 assert!(saved_config.contains("# keep"));
4516 assert!(!saved_config.contains("approval_policy"));
4517 let saved_settings = std::fs::read_to_string(&settings_path).expect("saved settings");
4518 assert!(saved_settings.contains("default_mode = \"agent\""));
4519 assert!(saved_settings.contains("permission_posture = \"full-access\""));
4520
4521 let restarted_config =
4522 codewhale_plugins::providers::load_config(Some(config_path), None).expect("reload config");
4523 let restarted = App::new(options, &restarted_config);
4524 assert_eq!(restarted.mode, AppMode::Agent);
4525 assert_eq!(restarted.approval_mode, ApprovalMode::Bypass);
4526 assert!(!restarted.approval_policy_locked());
4527 }
4528
4529 #[test]
4530 fn legacy_yolo_honors_a_missing_explicit_config_path_without_home_fallback() {
4531 let _env_lock = lock_test_env();
4532 let tmp = tempfile::tempdir().expect("tempdir");
4533 let home = tmp.path().join("home");
4534 let home_config_dir = home.join(codewhale_config::CODEWHALE_APP_DIR);
4535 let override_dir = tmp.path().join("missing-override");
4536 let missing_override = override_dir.join("config.toml");
4537 let workspace = tmp.path().join("workspace");
4538 std::fs::create_dir_all(&home_config_dir).expect("home config dir");
4539 std::fs::create_dir_all(&override_dir).expect("override dir");
4540 std::fs::create_dir_all(&workspace).expect("workspace");
4541 let home_config = home_config_dir.join("config.toml");
4542 std::fs::write(
4543 &home_config,
4544 "# actual fallback\napproval_policy = \"on-request\"\n",
4545 )
4546 .expect("home config");
4547 let override_settings = override_dir.join("settings.toml");
4548 std::fs::write(&override_settings, "default_mode = \"yolo\"\n").expect("legacy settings");
4549
4550 let _home = EnvVarGuard::set("HOME", &home);
4551 let _user_profile = EnvVarGuard::set("USERPROFILE", &home);
4552 let _codewhale_home = EnvVarGuard::remove("CODEWHALE_HOME");
4553 let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
4554 let _deepseek_config = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &missing_override);
4555 let _approval_env = EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY");
4556
4557 let config = codewhale_plugins::providers::load_config(None, None)
4558 .expect("load explicit missing config");
4559 assert_eq!(config.approval_policy, None);
4560 let mut options = test_options(false);
4561 options.start_in_agent_mode = false;
4562 options.workspace = workspace;
4563 options.config_path = None;
4564
4565 let app = App::new(options, &config);
4566
4567 assert_eq!(app.mode, AppMode::Agent);
4568 assert_eq!(app.approval_mode, ApprovalMode::Bypass);
4569 assert!(!app.approval_policy_locked());
4570 assert!(
4571 !missing_override.exists(),
4572 "settings migration must not create an unrelated config document"
4573 );
4574 let saved_home_config = std::fs::read_to_string(&home_config).expect("untouched home config");
4575 assert!(saved_home_config.contains("# actual fallback"));
4576 assert!(saved_home_config.contains("approval_policy = \"on-request\""));
4577 let saved_settings =
4578 std::fs::read_to_string(&override_settings).expect("normalized override settings");
4579 assert!(saved_settings.contains("default_mode = \"agent\""));
4580 assert!(saved_settings.contains("permission_posture = \"full-access\""));
4581 }
4582
4583 #[test]
4584 fn managed_requirements_ignore_saved_full_access_and_lock_changes() {
4585 let _env_lock = lock_test_env();
4586 let tmp = tempfile::tempdir().expect("tempdir");
4587 let config_path = tmp.path().join("config.toml");
4588 let requirements_path = tmp.path().join("requirements.toml");
4589 std::fs::write(
4590 tmp.path().join("settings.toml"),
4591 "permission_posture = \"full-access\"\n",
4592 )
4593 .expect("settings");
4594 std::fs::write(
4595 &requirements_path,
4596 "allowed_approval_policies = [\"on-request\"]\n",
4597 )
4598 .expect("requirements");
4599 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4600 let config = {
4601 let __cw_config_init_16_0 = Some(requirements_path.to_string_lossy().into_owned());
4602 let mut __cw_config_init_16_value: Config = Config::default();
4603 __cw_config_init_16_value.requirements_path = __cw_config_init_16_0;
4604 __cw_config_init_16_value
4605 };
4606
4607 let mut app = App::new(test_options(false), &config);
4608
4609 assert!(app.approval_policy_locked());
4610 assert!(app.approval_policy_requirements_managed());
4611 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
4612 assert!(!app.select_approval_posture(ApprovalMode::AcceptEdits));
4613 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
4614 assert!(
4615 app.status_toasts
4616 .iter()
4617 .any(|toast| toast.text.contains("controlled"))
4618 );
4619 let step = app.step_permission_dial(false);
4620 assert!(!step.posture_changed);
4621 assert_eq!(
4622 app.mode,
4623 AppMode::Plan,
4624 "a locked posture still reaches Plan"
4625 );
4626 }
4627
4628 #[test]
4629 fn sandbox_requirements_prevent_full_access_overrides() {
4630 let _env_lock = lock_test_env();
4631 let tmp = tempfile::tempdir().expect("tempdir");
4632 let config_path = tmp.path().join("config.toml");
4633 let requirements_path = tmp.path().join("requirements.toml");
4634 std::fs::write(
4635 &requirements_path,
4636 "allowed_sandbox_modes = [\"workspace-write\"]\n",
4637 )
4638 .expect("requirements");
4639 let _home = EnvVarGuard::set("CODEWHALE_HOME", tmp.path());
4640 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4641 let config = {
4642 let __cw_config_init_17_0 = Some(requirements_path.to_string_lossy().into_owned());
4643 let mut __cw_config_init_17_value: Config = Config::default();
4644 __cw_config_init_17_value.requirements_path = __cw_config_init_17_0;
4645 __cw_config_init_17_value
4646 };
4647
4648 for (settings, cli_yolo) in [
4649 ("permission_posture = \"full-access\"\n", false),
4650 ("", true),
4651 ("default_mode = \"yolo\"\n", false),
4652 ] {
4653 std::fs::write(tmp.path().join("settings.toml"), settings).expect("settings");
4654 let mut options = test_options(cli_yolo);
4655 options.workspace = tmp.path().to_path_buf();
4656 let mut app = App::new(options, &config);
4657
4658 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
4659 assert!(!app.trust_mode);
4660 assert!(!app.yolo);
4661 assert!(app.approval_policy_requirements_managed());
4662 assert!(!app.select_approval_posture(ApprovalMode::AcceptEdits));
4663 assert!(matches!(
4664 codewhale_engine::core::authority::sandbox_policy_for_turn(
4665 app.mode,
4666 app.approval_mode,
4667 config.sandbox_mode.as_deref(),
4668 &app.workspace,
4669 codewhale_engine::core::authority::SandboxNetworkAccess::Restricted,
4670 ),
4671 codewhale_sandbox::SandboxPolicy::WorkspaceWrite { .. }
4672 ));
4673 }
4674 }
4675
4676 #[test]
4677 fn yolo_entry_points_honor_a_locked_approval_policy() {
4678 let _env_lock = lock_test_env();
4679 let tmp = tempfile::tempdir().expect("tempdir");
4680 let requirements_path = tmp.path().join("requirements.toml");
4681 std::fs::write(
4682 &requirements_path,
4683 "allowed_approval_policies = [\"on-request\"]\n",
4684 )
4685 .expect("requirements");
4686 let config = {
4687 let __cw_config_init_18_0 = Some(requirements_path.to_string_lossy().into_owned());
4688 let mut __cw_config_init_18_value: Config = Config::default();
4689 __cw_config_init_18_value.requirements_path = __cw_config_init_18_0;
4690 __cw_config_init_18_value
4691 };
4692
4693 let mut options = test_options(false);
4694 options.yolo = true;
4695 options.allow_shell = false;
4696 let app = App::new(options, &config);
4697
4698 assert!(app.approval_policy_locked());
4699 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
4700 assert!(!app.allow_shell);
4701 assert!(!app.trust_mode);
4702 assert!(!app.yolo);
4703 }
4704
4705 #[test]
4706 fn set_mode_captures_agent_edits_as_the_durable_baseline() {
4707 // Editing the permission surface in Agent updates the baseline that a later
4708 // Plan -> Agent (or YOLO -> Agent) restores to (#3386).
4709 let mut options = test_options(false);
4710 options.allow_shell = false;
4711 options.start_in_agent_mode = true;
4712 let mut app = App::new(options, &Config::default());
4713 assert_eq!(app.mode, AppMode::Agent);
4714 app.allow_shell = false;
4715 app.set_agent_approval_posture(ApprovalMode::Suggest);
4716
4717 // Initial baseline restores to no-shell / Suggest.
4718 app.set_mode(AppMode::Plan);
4719 app.set_mode(AppMode::Agent);
4720 assert!(!app.allow_shell);
4721 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
4722
4723 // User now turns shell on and tightens approvals while in Agent.
4724 app.allow_shell = true;
4725 app.approval_mode = ApprovalMode::Never;
4726
4727 // A Plan hop and back must restore the *edited* baseline, not the original.
4728 app.set_mode(AppMode::Plan);
4729 assert!(!app.allow_shell, "Plan is read-only");
4730 app.set_mode(AppMode::Agent);
4731 assert!(app.allow_shell, "edited shell baseline restored");
4732 assert_eq!(app.approval_mode, ApprovalMode::Never);
4733 }
4734
4735 #[test]
4736 fn yolo_start_with_default_config_restores_interactive_agent_shell_baseline() {
4737 // Isolate from the developer's live settings.toml — a saved
4738 // `permission_posture` (e.g. full-access) must not leak into the
4739 // durable baseline these assertions depend on.
4740 let _env_lock = lock_test_env();
4741 let tmp = tempfile::tempdir().expect("tempdir");
4742 let config_path = tmp.path().join("config.toml");
4743 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4744 let mut options = test_options(true);
4745 options.config_path = Some(config_path);
4746 let mut app = App::new(options, &Config::default());
4747 // --yolo starts in Agent mode with the full-access compat shim (M6).
4748 assert_eq!(app.mode, AppMode::Agent);
4749 assert!(app.yolo);
4750 assert!(app.allow_shell);
4751 assert!(app.trust_mode);
4752 assert_eq!(app.approval_mode, ApprovalMode::Bypass);
4753
4754 app.set_mode(AppMode::Agent);
4755 assert!(
4756 app.allow_shell,
4757 "default interactive Agent baseline should expose approval-gated shell after YOLO downshift"
4758 );
4759 assert!(!app.trust_mode);
4760 assert_eq!(app.approval_mode, ApprovalMode::AcceptEdits);
4761 }
4762
4763 #[test]
4764 fn leaving_yolo_after_startup_restores_baseline_policies() {
4765 // Isolate from the developer's live settings.toml — a saved
4766 // `permission_posture` (e.g. full-access) must not leak into the
4767 // durable baseline these assertions depend on.
4768 let _env_lock = lock_test_env();
4769 let tmp = tempfile::tempdir().expect("tempdir");
4770 let config_path = tmp.path().join("config.toml");
4771 let _config_env = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
4772 let config = {
4773 let __cw_config_init_19_0 = Some(false);
4774 let mut __cw_config_init_19_value: Config = Default::default();
4775 __cw_config_init_19_value.allow_shell = __cw_config_init_19_0;
4776 __cw_config_init_19_value
4777 };
4778
4779 let mut options = test_options(true);
4780 options.config_path = Some(config_path);
4781 let mut app = App::new(options, &config);
4782 // --yolo starts in Agent mode with the full-access compat shim (M6).
4783 assert_eq!(app.mode, AppMode::Agent);
4784 assert!(app.yolo);
4785 assert!(app.allow_shell);
4786 assert!(app.trust_mode);
4787 assert_eq!(app.approval_mode, ApprovalMode::Bypass);
4788
4789 app.set_mode(AppMode::Agent);
4790 assert!(!app.allow_shell);
4791 assert!(!app.trust_mode);
4792 assert_eq!(app.approval_mode, ApprovalMode::AcceptEdits);
4793 }
4794
4795 #[test]
4796 fn configured_approval_policy_initializes_live_approval_mode() {
4797 let config = {
4798 let __cw_config_init_20_0 = Some("never".to_string());
4799 let mut __cw_config_init_20_value: Config = Default::default();
4800 __cw_config_init_20_value.approval_policy = __cw_config_init_20_0;
4801 __cw_config_init_20_value
4802 };
4803 let mut options = test_options(false);
4804 options.start_in_agent_mode = true;
4805
4806 let app = App::new(options, &config);
4807
4808 assert_eq!(app.mode, AppMode::Agent);
4809 assert_eq!(app.approval_mode, ApprovalMode::Never);
4810 }
4811
4812 #[test]
4813 fn test_mark_history_updated() {
4814 let mut app = App::new(test_options(false), &Config::default());
4815 let initial_version = app.history_version;
4816 app.mark_history_updated();
4817 assert!(app.history_version > initial_version);
4818 }
4819
4820 #[test]
4821 fn live_motion_invalidation_only_bumps_live_transcript_rows() {
4822 let mut app = App::new(test_options(false), &Config::default());
4823 app.history = vec![
4824 HistoryCell::Assistant {
4825 content: "settled".to_string(),
4826 streaming: false,
4827 },
4828 HistoryCell::Assistant {
4829 content: "streaming".to_string(),
4830 streaming: true,
4831 },
4832 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
4833 name: "read_file".to_string(),
4834 status: ToolStatus::Running,
4835 input_summary: None,
4836 output: None,
4837 prompts: None,
4838 spillover_path: None,
4839 output_summary: None,
4840 is_diff: false,
4841 })),
4842 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
4843 name: "agent".to_string(),
4844 status: ToolStatus::Running,
4845 input_summary: Some("action: spawn".to_string()),
4846 output: None,
4847 prompts: None,
4848 spillover_path: None,
4849 output_summary: None,
4850 is_diff: false,
4851 })),
4852 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
4853 name: "read_file".to_string(),
4854 status: ToolStatus::Success,
4855 input_summary: None,
4856 output: Some("done".to_string()),
4857 prompts: None,
4858 spillover_path: None,
4859 output_summary: None,
4860 is_diff: false,
4861 })),
4862 ];
4863 app.resync_history_revisions();
4864 let history_before = app.history_revisions.clone();
4865
4866 let active = app.active_cell.get_or_insert_with(ActiveCell::new);
4867 active.push_untracked(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
4868 name: "web_search".to_string(),
4869 status: ToolStatus::Running,
4870 input_summary: None,
4871 output: None,
4872 prompts: None,
4873 spillover_path: None,
4874 output_summary: None,
4875 is_diff: false,
4876 })));
4877 let app_active_before = app.active_cell_revision;
4878 let cell_active_before = app.active_cell.as_ref().expect("active cell").revision();
4879
4880 app.mark_live_motion_updated();
4881
4882 assert_eq!(app.history_revisions[0], history_before[0]);
4883 assert_ne!(app.history_revisions[1], history_before[1]);
4884 assert_ne!(app.history_revisions[2], history_before[2]);
4885 assert_eq!(app.history_revisions[3], history_before[3]);
4886 assert_eq!(app.history_revisions[4], history_before[4]);
4887 assert_ne!(app.active_cell_revision, app_active_before);
4888 assert_ne!(
4889 app.active_cell.as_ref().expect("active cell").revision(),
4890 cell_active_before
4891 );
4892
4893 let history_after_all_live = app.history_revisions.clone();
4894 let app_active_after_all_live = app.active_cell_revision;
4895 let cell_active_after_all_live = app.active_cell.as_ref().expect("active cell").revision();
4896 app.mark_live_history_motion_updated();
4897
4898 assert_eq!(app.history_revisions[0], history_after_all_live[0]);
4899 assert_ne!(app.history_revisions[1], history_after_all_live[1]);
4900 assert_ne!(app.history_revisions[2], history_after_all_live[2]);
4901 assert_eq!(app.history_revisions[3], history_after_all_live[3]);
4902 assert_eq!(app.history_revisions[4], history_after_all_live[4]);
4903 assert_eq!(app.active_cell_revision, app_active_after_all_live);
4904 assert_eq!(
4905 app.active_cell.as_ref().expect("active cell").revision(),
4906 cell_active_after_all_live
4907 );
4908 }
4909
4910 #[test]
4911 fn expanded_tool_scenario() {
4912 // Scenario consolidation of: expanded_tool_runs_rebase_when_history_prefix_shifts, expanded_tool_runs_prune_when_history_is_truncated
4913 // from expanded_tool_runs_rebase_when_history_prefix_shifts
4914 {
4915 let mut app = App::new(test_options(false), &Config::default());
4916 app.expanded_tool_runs = std::collections::HashSet::from([2usize, 6usize]);
4917
4918 app.shift_history_maps_down(3);
4919
4920 assert_eq!(app.expanded_tool_runs, std::collections::HashSet::from([4]));
4921 }
4922 // from expanded_tool_runs_prune_when_history_is_truncated
4923 {
4924 let mut app = App::new(test_options(false), &Config::default());
4925 for idx in 0..5 {
4926 app.add_message(HistoryCell::System {
4927 content: format!("cell {idx}"),
4928 });
4929 }
4930 app.expanded_tool_runs = std::collections::HashSet::from([1usize, 4usize]);
4931
4932 app.truncate_history_to(3);
4933
4934 assert_eq!(app.expanded_tool_runs, std::collections::HashSet::from([1]));
4935 }
4936 }
4937
4938 #[test]
4939 fn tool_run_expansion_toggle_opens_and_closes_run() {
4940 let mut app = App::new(test_options(false), &Config::default());
4941 app.tool_collapse_mode = ToolCollapseMode::Compact;
4942 app.tool_collapse_threshold = 3;
4943 for name in ["read_file", "list_dir", "web_search"] {
4944 app.add_message(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
4945 name: name.to_string(),
4946 status: ToolStatus::Success,
4947 input_summary: None,
4948 output: Some("ok".to_string()),
4949 prompts: None,
4950 spillover_path: None,
4951 output_summary: None,
4952 is_diff: false,
4953 })));
4954 }
4955
4956 assert!(app.toggle_tool_run_expansion_at(0));
4957 assert!(app.expanded_tool_runs.contains(&0));
4958 assert!(app.toggle_tool_run_expansion_at(2));
4959 assert!(!app.expanded_tool_runs.contains(&0));
4960 assert!(!app.toggle_tool_run_expansion_at(99));
4961 }
4962
4963 #[test]
4964 fn tool_run_expansion_toggle_handles_active_run() {
4965 let mut app = App::new(test_options(false), &Config::default());
4966 app.tool_collapse_mode = ToolCollapseMode::Compact;
4967 app.tool_collapse_threshold = 3;
4968 app.add_message(HistoryCell::User {
4969 content: "go".to_string(),
4970 });
4971
4972 let active_start = app.history.len();
4973 let active = app.active_cell.get_or_insert_with(ActiveCell::new);
4974 for name in ["read_file", "list_dir", "web_search"] {
4975 active.push_untracked(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
4976 name: name.to_string(),
4977 status: ToolStatus::Success,
4978 input_summary: None,
4979 output: Some("ok".to_string()),
4980 prompts: None,
4981 spillover_path: None,
4982 output_summary: None,
4983 is_diff: false,
4984 })));
4985 }
4986
4987 assert!(app.toggle_tool_run_expansion_at(active_start));
4988 assert!(app.expanded_tool_runs.contains(&active_start));
4989 assert!(app.toggle_tool_run_expansion_at(active_start + 2));
4990 assert!(!app.expanded_tool_runs.contains(&active_start));
4991 }
4992
4993 #[test]
4994 fn test_scroll_operations() {
4995 let mut app = App::new(test_options(false), &Config::default());
4996 // Just verify scroll methods can be called without panic
4997 app.scroll_up(5);
4998 app.scroll_down(3);
4999 }
5000
5001 #[test]
5002 fn resize_preserves_scrolled_transcript_position() {
5003 let mut app = App::new(test_options(false), &Config::default());
5004 app.viewport.transcript_scroll = TranscriptScroll::at_line(42);
5005 app.viewport.last_transcript_top = 42;
5006 app.viewport.pending_scroll_delta = 5;
5007
5008 app.handle_resize(120, 40);
5009
5010 let meta = vec![
5011 TranscriptLineMeta::Spacer {
5012 copy_prefix_width: 0
5013 };
5014 240
5015 ];
5016 let (_, top) = app.viewport.transcript_scroll.resolve_top(&meta, 200);
5017 assert_eq!(top, 42);
5018 assert_eq!(app.viewport.pending_scroll_delta, 0);
5019 }
5020
5021 #[test]
5022 fn resize_keeps_tail_state_when_user_was_at_tail() {
5023 let mut app = App::new(test_options(false), &Config::default());
5024 app.viewport.transcript_scroll = TranscriptScroll::to_bottom();
5025 app.viewport.last_transcript_top = 42;
5026
5027 app.handle_resize(120, 40);
5028
5029 assert!(app.viewport.transcript_scroll.is_at_tail());
5030 }
5031
5032 #[test]
5033 fn resize_seeds_visible_height_for_paging_before_next_render() {
5034 let mut app = App::new(test_options(false), &Config::default());
5035 app.viewport.last_transcript_visible = 12;
5036
5037 app.handle_resize(120, 40);
5038 assert_eq!(app.viewport.last_transcript_visible, 38);
5039
5040 app.handle_resize(120, 1);
5041 assert_eq!(app.viewport.last_transcript_visible, 1);
5042 }
5043
5044 #[test]
5045 fn test_add_message() {
5046 let mut app = App::new(test_options(false), &Config::default());
5047 let initial_len = app.history.len();
5048 app.add_message(HistoryCell::User {
5049 content: "test".to_string(),
5050 });
5051 assert_eq!(app.history.len(), initial_len + 1);
5052 }
5053
5054 #[test]
5055 fn test_compaction_config() {
5056 let _home = crate::test_support::SealedHome::new();
5057 let mut app = App::new(test_options(false), &Config::default());
5058 app.set_model_selection("auto".to_string());
5059 assert_eq!(app.compaction_config().model, DEFAULT_TEXT_MODEL);
5060
5061 let budget = AutoRouteBudget {
5062 provider: ProviderKind::Deepseek,
5063 provider_identity: "deepseek".into(),
5064 model: "deepseek-v4-flash".into(),
5065 limits: None,
5066 window: codewhale_engine::route_runtime::ContextWindowResolution {
5067 tokens: 1_000_000,
5068 source: codewhale_engine::route_runtime::ContextWindowSource::Catalog,
5069 },
5070 restored: false,
5071 };
5072 app.last_effective_model = Some(budget.model.clone());
5073 assert_eq!(app.compaction_config().model, DEFAULT_TEXT_MODEL);
5074
5075 app.last_effective_provider = Some(budget.provider);
5076 app.last_effective_provider_identity = Some(budget.provider_identity.clone());
5077 app.last_effective_budget = Some(budget);
5078 let config = app.compaction_config();
5079 assert_eq!(config.model, "deepseek-v4-flash");
5080 assert_eq!(config.effective_context_window, Some(1_000_000));
5081 }
5082
5083 #[test]
5084 fn test_update_model_compaction_budget() {
5085 let mut app = App::new(test_options(false), &Config::default());
5086 // Pin the inputs so the budget math is deterministic and does not
5087 // depend on the developer's local `auto_compact_threshold_percent`
5088 // setting (App::new loads real settings) or on auto-model resolution.
5089 app.auto_model = false;
5090 app.api_provider = ProviderKind::Deepseek;
5091 app.active_route_limits = None;
5092 app.active_context_window_override = None;
5093 // The installed window outranks the route limits, so a fixture that only
5094 // clears the limits keeps the window `App::new` resolved for its default
5095 // model and the budget is computed against the wrong one. Production
5096 // clears it through `set_model_selection`; mutating `app.model` directly
5097 // has to do the same.
5098 app.active_context_window = None;
5099 app.auto_compact_threshold_percent = 80.0;
5100
5101 // A large-context model earns a proportionally larger compaction
5102 // budget; an unknown model falls back to the fixed default threshold.
5103 app.model = "deepseek-v4-pro".to_string();
5104 app.update_model_compaction_budget();
5105 let large_window_threshold = app.compact_threshold;
5106
5107 app.model = "unknown-test-model".to_string();
5108 app.update_model_compaction_budget();
5109 let unknown_threshold = app.compact_threshold;
5110
5111 assert!(
5112 unknown_threshold > 0,
5113 "unknown model must still get a positive budget"
5114 );
5115 assert!(
5116 large_window_threshold > unknown_threshold,
5117 "a large-context model ({large_window_threshold}) should budget more \
5118 than an unknown model ({unknown_threshold})"
5119 );
5120 }
5121
5122 #[test]
5123 fn test_input_history_navigation() {
5124 let mut app = App::new(test_options(false), &Config::default());
5125 app.input_history.push("first".to_string());
5126 app.input_history.push("second".to_string());
5127
5128 // Navigate up
5129 app.history_up();
5130 assert!(app.history_index.is_some());
5131
5132 // Navigate down
5133 app.history_down();
5134 }
5135
5136 #[test]
5137 fn paste_while_navigating_history_detaches_before_down_can_discard_it() {
5138 // A paste (insert_str family) while a history entry is on screen must
5139 // detach navigation like typing does; otherwise the next Down replaces
5140 // the buffer and silently destroys the pasted text.
5141 let mut app = App::new(test_options(false), &Config::default());
5142 app.input_history.push("older".to_string());
5143 app.input_history.push("newer".to_string());
5144 app.input = "draft".to_string();
5145
5146 app.history_up();
5147 assert_eq!(app.input, "newer");
5148 app.insert_str(" pasted");
5149 assert!(app.history_index.is_none());
5150 assert_eq!(app.input, "newer pasted");
5151
5152 app.history_down();
5153 assert_eq!(
5154 app.input, "newer pasted",
5155 "detached edit must survive history keys"
5156 );
5157 }
5158
5159 #[test]
5160 fn external_edit_while_navigating_history_detaches_stale_state() {
5161 // Same hazard through the $EDITOR round-trip: the edited buffer replaces
5162 // recalled history, so the stale index, draft, selection, and attachment
5163 // positions must not survive it.
5164 let mut app = App::new(test_options(false), &Config::default());
5165 app.input_history.push("older".to_string());
5166 app.input = "draft".to_string();
5167
5168 app.history_up();
5169 assert_eq!(app.input, "older");
5170 app.apply_external_edit("edited in vi".to_string());
5171 assert!(app.history_index.is_none());
5172 assert!(app.history_navigation_draft.is_none());
5173 assert!(app.selection_anchor.is_none());
5174 assert_eq!(app.input, "edited in vi");
5175
5176 app.history_down();
5177 assert_eq!(
5178 app.input, "edited in vi",
5179 "detached edit must survive history keys"
5180 );
5181 }
5182
5183 #[test]
5184 fn input_history_scenario() {
5185 // Scenario consolidation of: input_history_down_restores_live_draft_after_accidental_up, input_history_navigation_clears_stale_selection, input_history_restores_empty_draft_at_end_of_navigation
5186 // from input_history_down_restores_live_draft_after_accidental_up
5187 {
5188 let mut app = App::new(test_options(false), &Config::default());
5189 app.input_history.push("previous prompt".to_string());
5190 app.input = "careful current draft".to_string();
5191 app.cursor_position = "careful".chars().count();
5192
5193 app.history_up();
5194 assert_eq!(app.input, "previous prompt");
5195
5196 app.history_down();
5197 assert_eq!(app.input, "careful current draft");
5198 assert_eq!(app.cursor_position, "careful".chars().count());
5199 assert!(app.history_index.is_none());
5200 }
5201 // from input_history_navigation_clears_stale_selection
5202 {
5203 let mut app = App::new(test_options(false), &Config::default());
5204 app.input_history.push("previous input".to_string());
5205 app.input = "hello world".to_string();
5206 app.cursor_position = "hello ".chars().count();
5207 app.selection_anchor = Some(app.input.chars().count());
5208
5209 app.history_up();
5210 assert_eq!(app.input, "previous input");
5211 assert!(app.selection_anchor.is_none());
5212
5213 app.insert_char('x');
5214 assert_eq!(app.input, "previous inputx");
5215 }
5216 // from input_history_restores_empty_draft_at_end_of_navigation
5217 {
5218 let mut app = App::new(test_options(false), &Config::default());
5219 app.input_history.push("previous prompt".to_string());
5220
5221 app.history_up();
5222 assert_eq!(app.input, "previous prompt");
5223
5224 app.history_down();
5225 assert!(app.input.is_empty());
5226 assert_eq!(app.cursor_position, 0);
5227 assert!(app.history_index.is_none());
5228 }
5229 }
5230
5231 #[test]
5232 fn word_cursor_helpers_move_by_whitespace_delimited_words() {
5233 let mut app = App::new(test_options(false), &Config::default());
5234 app.input = "alpha beta gamma".to_string();
5235 app.cursor_position = 0;
5236
5237 app.move_cursor_word_forward();
5238 assert_eq!(app.cursor_position, "alpha ".chars().count());
5239
5240 app.move_cursor_word_forward();
5241 assert_eq!(app.cursor_position, "alpha beta ".chars().count());
5242
5243 app.move_cursor_word_backward();
5244 assert_eq!(app.cursor_position, "alpha ".chars().count());
5245 }
5246
5247 #[test]
5248 fn editing_history_entry_leaves_navigation_mode() {
5249 let mut app = App::new(test_options(false), &Config::default());
5250 app.input_history.push("previous prompt".to_string());
5251 app.input = "current draft".to_string();
5252 app.cursor_position = app.input.chars().count();
5253
5254 app.history_up();
5255 app.insert_char('!');
5256 app.history_down();
5257
5258 assert_eq!(app.input, "previous prompt!");
5259 assert!(app.history_index.is_none());
5260 }
5261
5262 #[test]
5263 fn history_search_scenario() {
5264 // Scenario consolidation of: history_search_filters_matches_and_skips_duplicates, history_search_matches_unicode_case_insensitively, history_search_accepts_match_without_submitting, history_search_cancel_restores_pre_search_draft
5265 // from history_search_filters_matches_and_skips_duplicates
5266 {
5267 let mut app = App::new(test_options(false), &Config::default());
5268 app.input_history.clear();
5269 app.input_history.push("alpha one".to_string());
5270 app.input_history.push("beta two".to_string());
5271 app.input_history.push("alpha one".to_string());
5272 app.draft_history.push_back("draft alpha".to_string());
5273
5274 app.start_history_search();
5275 app.history_search_insert_str("alpha");
5276
5277 assert_eq!(
5278 app.history_search_matches(),
5279 vec!["draft alpha".to_string(), "alpha one".to_string()]
5280 );
5281 }
5282 // from history_search_matches_unicode_case_insensitively
5283 {
5284 let mut app = App::new(test_options(false), &Config::default());
5285 app.input_history.clear();
5286 app.input_history.push("CAFÉ prompt".to_string());
5287
5288 app.start_history_search();
5289 app.history_search_insert_str("café");
5290
5291 assert_eq!(
5292 app.history_search_matches(),
5293 vec!["CAFÉ prompt".to_string()]
5294 );
5295 }
5296 // from history_search_accepts_match_without_submitting
5297 {
5298 let mut app = App::new(test_options(false), &Config::default());
5299 app.input_history.clear();
5300 app.input_history.push("older prompt".to_string());
5301
5302 app.start_history_search();
5303 app.history_search_insert_str("older");
5304
5305 assert!(app.accept_history_search());
5306 assert_eq!(app.input, "older prompt");
5307 assert_eq!(app.cursor_position, "older prompt".chars().count());
5308 assert!(app.composer_history_search.is_none());
5309 }
5310 // from history_search_cancel_restores_pre_search_draft
5311 {
5312 let mut app = App::new(test_options(false), &Config::default());
5313 app.input_history.clear();
5314 app.input = "current draft".to_string();
5315 app.cursor_position = 7;
5316 app.input_history.push("older prompt".to_string());
5317
5318 app.start_history_search();
5319 app.history_search_insert_str("older");
5320 app.cancel_history_search();
5321
5322 assert_eq!(app.input, "current draft");
5323 assert_eq!(app.cursor_position, 7);
5324 assert!(app.composer_history_search.is_none());
5325 }
5326 }
5327
5328 #[test]
5329 fn recoverable_clear_stashes_nonempty_draft() {
5330 let mut app = App::new(test_options(false), &Config::default());
5331 app.input_history.clear();
5332 app.input = "recover this".to_string();
5333 app.cursor_position = app.input.chars().count();
5334
5335 app.clear_input_recoverable();
5336 app.start_history_search();
5337 app.history_search_insert_str("recover");
5338
5339 assert_eq!(
5340 app.history_search_matches(),
5341 vec!["recover this".to_string()]
5342 );
5343 }
5344
5345 #[test]
5346 fn clear_undo_scenario() {
5347 // Scenario consolidation of: clear_undo_buffer_is_set_on_clear_input_recoverable, clear_undo_buffer_is_none_when_clearing_empty_input
5348 // from clear_undo_buffer_is_set_on_clear_input_recoverable
5349 {
5350 let mut app = App::new(test_options(false), &Config::default());
5351 app.input = "hello".to_string();
5352 app.cursor_position = 5;
5353
5354 app.clear_input_recoverable();
5355
5356 assert!(app.input.is_empty());
5357 assert_eq!(app.clear_undo_buffer.as_deref(), Some("hello"));
5358 }
5359 // from clear_undo_buffer_is_none_when_clearing_empty_input
5360 {
5361 let mut app = App::new(test_options(false), &Config::default());
5362 assert!(app.input.is_empty());
5363
5364 app.clear_input_recoverable();
5365
5366 assert!(app.clear_undo_buffer.is_none());
5367 }
5368 }
5369
5370 #[test]
5371 fn composer_paste_flushes_pending_burst_and_normalizes_crlf() {
5372 let mut app = App::new(test_options(false), &Config::default());
5373 app.use_paste_burst_detection = true;
5374 let now = Instant::now();
5375 let key = crossterm::event::KeyEvent::new(
5376 crossterm::event::KeyCode::Char('x'),
5377 crossterm::event::KeyModifiers::NONE,
5378 );
5379
5380 assert!(crate::tui::paste::handle_paste_burst_key(
5381 &mut app, &key, now
5382 ));
5383 assert!(
5384 app.input.is_empty(),
5385 "first burst char should stay buffered"
5386 );
5387
5388 app.insert_paste_text("a\r\nb\rc");
5389
5390 assert_eq!(app.input, "xa\nb\nc");
5391 assert_eq!(app.cursor_position, "xa\nb\nc".chars().count());
5392 assert!(!app.paste_burst.is_active());
5393 }
5394
5395 #[test]
5396 fn bracketed_paste_preserves_bare_carriage_return_line_breaks() {
5397 let mut app = App::new(test_options(false), &Config::default());
5398
5399 app.insert_paste_text("alpha\r indented\r# literal heading\r- literal list");
5400
5401 assert_eq!(
5402 app.input,
5403 "alpha\n indented\n# literal heading\n- literal list"
5404 );
5405 assert_eq!(app.cursor_position, app.input.chars().count());
5406 }
5407
5408 #[test]
5409 fn enter_during_active_paste_burst_appends_newline_to_buffer_not_submit() {
5410 // #1073: when chars are still being assembled into a paste burst and
5411 // an Enter arrives (the trailing newline of the paste), the Enter
5412 // must be absorbed into the burst buffer — not fired as a submit.
5413 let mut app = App::new(test_options(false), &Config::default());
5414 app.use_paste_burst_detection = true;
5415 let now = Instant::now();
5416 app.paste_burst.append_char_to_buffer('h', now);
5417 app.paste_burst.append_char_to_buffer('i', now);
5418 assert!(app.paste_burst.is_active());
5419 assert!(app.input.is_empty());
5420
5421 let result = app.handle_composer_enter(true, Instant::now());
5422
5423 assert!(
5424 result.is_none(),
5425 "Enter during active paste burst must not submit"
5426 );
5427 let flushed = app.paste_burst.flush_before_modified_input();
5428 assert_eq!(
5429 flushed.as_deref(),
5430 Some("hi\n"),
5431 "newline must land in the burst buffer so the next flush carries it"
5432 );
5433 }
5434
5435 #[test]
5436 fn enter_inside_paste_burst_window_after_flush_inserts_newline_not_submit() {
5437 // #1073: after a burst has flushed (text now in `input`), the
5438 // suppression window stays open for ~120ms. An Enter arriving in
5439 // that window is the trailing newline of the paste, not a user
5440 // submit — insert it as a literal newline into the composer.
5441 let mut app = App::new(test_options(false), &Config::default());
5442 app.use_paste_burst_detection = true;
5443 app.input = "hello".to_string();
5444 app.cursor_position = "hello".chars().count();
5445 let now = Instant::now();
5446 app.paste_burst.extend_window(now);
5447 assert!(!app.paste_burst.is_active());
5448 assert!(
5449 app.paste_burst.newline_should_insert_instead_of_submit(now),
5450 "suppression window should be open"
5451 );
5452
5453 let result = app.handle_composer_enter(true, Instant::now());
5454
5455 assert!(
5456 result.is_none(),
5457 "Enter inside post-flush suppression window must not submit"
5458 );
5459 assert_eq!(
5460 app.input, "hello\n",
5461 "newline must be inserted into the composer instead of firing a submit"
5462 );
5463 assert!(!app.composer_enter_would_submit(true, Instant::now()));
5464 assert!(app.composer_enter_would_submit(false, Instant::now()));
5465 assert_eq!(
5466 app.handle_composer_enter(false, Instant::now()).as_deref(),
5467 Some("hello\n")
5468 );
5469 }
5470
5471 /// The absorbed Enter above must not buy the window more time. Re-arming on
5472 /// it meant a user pressing Enter to send kept extending suppression by
5473 /// another 120ms per press, so the composer only ever grew newlines and
5474 /// never submitted.
5475 #[test]
5476 fn enter_absorbed_after_flush_does_not_re_arm_the_suppression_window() {
5477 let mut app = App::new(test_options(false), &Config::default());
5478 app.use_paste_burst_detection = true;
5479 app.input = "hello".to_string();
5480 app.cursor_position = "hello".chars().count();
5481 let now = Instant::now();
5482 app.paste_burst.extend_window(now);
5483
5484 assert!(
5485 app.handle_composer_enter(true, Instant::now()).is_none(),
5486 "first Enter is absorbed as the paste's possible trailing newline"
5487 );
5488 assert_eq!(app.input, "hello\n");
5489
5490 // The window must still expire relative to `now` — the moment the burst
5491 // last saw real input — not relative to the Enter that was absorbed.
5492 assert!(
5493 !app.paste_burst
5494 .newline_should_insert_instead_of_submit(now + Duration::from_millis(121)),
5495 "absorbing an Enter must not extend the suppression window"
5496 );
5497 }
5498
5499 #[test]
5500 fn enter_outside_any_paste_burst_window_submits_normally() {
5501 // Regression guard: the suppression must not trip when the user
5502 // actually wants to submit.
5503 let mut app = App::new(test_options(false), &Config::default());
5504 app.use_paste_burst_detection = true;
5505 app.input = "hello world".to_string();
5506 app.cursor_position = "hello world".chars().count();
5507
5508 let result = app.handle_composer_enter(true, Instant::now());
5509
5510 assert_eq!(
5511 result.as_deref(),
5512 Some("hello world"),
5513 "Enter outside any paste burst window must submit normally"
5514 );
5515 assert!(
5516 app.input.is_empty(),
5517 "submit_input should clear the composer"
5518 );
5519 }
5520
5521 #[test]
5522 fn enter_with_paste_burst_detection_disabled_submits_normally() {
5523 // When the user has explicitly turned off paste-burst detection
5524 // (`bracketed_paste = false` is independent, this is the
5525 // `paste_burst_detection` setting), the suppression must be
5526 // skipped — otherwise turning it off would not actually turn it
5527 // off.
5528 let mut app = App::new(test_options(false), &Config::default());
5529 app.use_paste_burst_detection = false;
5530 app.input = "ship it".to_string();
5531 app.cursor_position = "ship it".chars().count();
5532 let now = Instant::now();
5533 app.paste_burst.extend_window(now);
5534
5535 let result = app.handle_composer_enter(true, Instant::now());
5536
5537 assert_eq!(result.as_deref(), Some("ship it"));
5538 }
5539
5540 fn clipboard_paste(app: &mut App, content: ClipboardContent) -> bool {
5541 app.clipboard = ClipboardHandler::with_content_for_test(content);
5542 crate::tui::paste::handle_paste(app, crate::tui::paste::PasteSource::Shortcut)
5543 }
5544
5545 #[test]
5546 fn clipboard_text_paste_matches_bracketed_paste_state() {
5547 let text = "alpha\r\nbeta";
5548 let mut bracketed = App::new(test_options(false), &Config::default());
5549 let mut clipboard = App::new(test_options(false), &Config::default());
5550
5551 crate::tui::paste::handle_paste(
5552 &mut bracketed,
5553 crate::tui::paste::PasteSource::Terminal(text),
5554 );
5555 assert!(clipboard_paste(
5556 &mut clipboard,
5557 ClipboardContent::Text(text.to_string())
5558 ));
5559
5560 assert_eq!(clipboard.input, bracketed.input);
5561 assert_eq!(clipboard.cursor_position, bracketed.cursor_position);
5562 assert_eq!(clipboard.slash_menu_hidden, bracketed.slash_menu_hidden);
5563 assert_eq!(clipboard.mention_menu_hidden, bracketed.mention_menu_hidden);
5564 }
5565
5566 #[test]
5567 fn release_only_paste_edge_leaves_text_to_the_terminal_and_still_attaches_an_image() {
5568 use crate::tui::paste::{PasteSource, handle_paste};
5569
5570 let mut app = App::new(test_options(false), &Config::default());
5571 app.clipboard = ClipboardHandler::with_content_for_test(ClipboardContent::Text(
5572 "already pasted".to_string(),
5573 ));
5574 handle_paste(&mut app, PasteSource::Terminal("already pasted"));
5575 handle_paste(&mut app, PasteSource::ReleaseOnly);
5576 assert_eq!(app.input, "already pasted");
5577
5578 let mut app = App::new(test_options(false), &Config::default());
5579 app.clipboard = ClipboardHandler::with_content_for_test(ClipboardContent::Image(
5580 crate::tui::clipboard::PastedImage {
5581 path: std::path::PathBuf::from("/tmp/pasted.png"),
5582 width: 8,
5583 height: 4,
5584 byte_len: 2048,
5585 },
5586 ));
5587
5588 handle_paste(&mut app, PasteSource::ReleaseOnly);
5589 assert!(app.input.contains("pasted.png"), "{}", app.input);
5590 assert_eq!(app.input.matches("pasted.png").count(), 1, "{}", app.input);
5591 }
5592
5593 #[test]
5594 fn ssh_direct_clipboard_paste_points_to_terminal_owned_bracketed_paste() {
5595 let mut app = App::new(test_options(false), &Config::default());
5596 app.input = "keep this draft".to_string();
5597 app.cursor_position = app.input.chars().count();
5598 app.clipboard = ClipboardHandler::for_test(true, true);
5599
5600 crate::tui::paste::handle_paste(&mut app, crate::tui::paste::PasteSource::Shortcut);
5601 assert_eq!(app.input, "keep this draft");
5602 let hint = app
5603 .status_toasts
5604 .back()
5605 .map(|notice| notice.text.as_str())
5606 .expect("remote paste hint")
5607 .to_string();
5608 assert!(hint.contains("SSH paste uses your local terminal"));
5609 assert!(hint.contains("Cmd+V on macOS"));
5610 assert!(hint.contains("Ctrl+Shift+V on Linux/Windows"));
5611 }
5612
5613 #[test]
5614 fn clipboard_image_paste_keeps_adjacent_text_and_concise_status() {
5615 let mut app = App::new(test_options(false), &Config::default());
5616 app.input = "before after".to_string();
5617 app.cursor_position = "before".chars().count();
5618
5619 assert!(clipboard_paste(
5620 &mut app,
5621 ClipboardContent::Image(PastedImage {
5622 path: PathBuf::from("/tmp/pasted.png"),
5623 width: 8,
5624 height: 4,
5625 byte_len: 2048,
5626 })
5627 ));
5628
5629 assert!(
5630 app.input
5631 .contains("before\n[Attached image: 8x4 PNG (2KB) at /tmp/pasted.png]")
5632 );
5633 assert!(app.input.contains("] after"));
5634 let status = app
5635 .status_toasts
5636 .back()
5637 .map(|notice| notice.text.as_str())
5638 .expect("status message");
5639 assert_eq!(status, "Attached image: 8x4 PNG (2KB)");
5640 }
5641
5642 #[test]
5643 fn pasted_text_and_image_placeholders_survive_history_and_queue_paths() {
5644 let mut app = App::new(test_options(false), &Config::default());
5645 app.insert_paste_text("line 1\r\nline 2");
5646 app.insert_media_attachment("image", Path::new("/tmp/pasted.png"), Some("8x4 PNG (2KB)"));
5647
5648 let submitted = app.submit_input().expect("submitted input");
5649 assert!(submitted.contains("line 1\nline 2"));
5650 assert!(submitted.contains("[Attached image: 8x4 PNG (2KB) at /tmp/pasted.png]"));
5651
5652 app.history_up();
5653 assert_eq!(app.input, submitted);
5654 assert_eq!(app.composer_attachment_count(), 1);
5655
5656 app.clear_input();
5657 app.queue_message(QueuedMessage::new(
5658 submitted.clone(),
5659 Some("Use this skill".to_string()),
5660 ));
5661 assert!(app.pop_last_queued_into_draft());
5662 assert_eq!(app.input, submitted);
5663 assert_eq!(app.composer_attachment_count(), 1);
5664 assert_eq!(
5665 app.queued_draft
5666 .as_ref()
5667 .and_then(|draft| draft.skill_instruction.as_deref()),
5668 Some("Use this skill")
5669 );
5670 }
5671
5672 #[test]
5673 fn selected_attachment_row_removes_placeholder_without_manual_editing() {
5674 let mut app = App::new(test_options(false), &Config::default());
5675 app.input = "before".to_string();
5676 app.cursor_position = "before".chars().count();
5677 app.insert_media_attachment("image", Path::new("/tmp/pasted.png"), Some("8x4 PNG"));
5678 app.insert_str("after");
5679
5680 app.move_cursor_start();
5681 assert!(app.select_previous_composer_attachment());
5682 assert_eq!(app.selected_composer_attachment_index(), Some(0));
5683 assert!(app.remove_selected_composer_attachment());
5684
5685 assert!(!app.input.contains("[Attached image:"));
5686 assert!(app.input.contains("before"));
5687 assert!(app.input.contains("after"));
5688 assert_eq!(app.composer_attachment_count(), 0);
5689 assert!(app.selected_composer_attachment_index().is_none());
5690 }
5691
5692 #[test]
5693 fn kill_to_end_of_line_cuts_from_middle_of_word() {
5694 let mut app = App::new(test_options(false), &Config::default());
5695 app.input = "hello world".to_string();
5696 app.cursor_position = 6; // before 'w'
5697 assert!(app.kill_to_end_of_line());
5698 assert_eq!(app.input, "hello ");
5699 assert_eq!(app.cursor_position, 6);
5700 assert_eq!(app.kill_buffer, "world");
5701 }
5702
5703 #[test]
5704 fn kill_at_eol_consumes_following_newline() {
5705 let mut app = App::new(test_options(false), &Config::default());
5706 app.input = "line one\nline two".to_string();
5707 app.cursor_position = 8; // sitting on the '\n'
5708 assert!(app.kill_to_end_of_line());
5709 assert_eq!(app.input, "line oneline two");
5710 assert_eq!(app.cursor_position, 8);
5711 assert_eq!(app.kill_buffer, "\n");
5712
5713 // Empty input: kill is a no-op and the buffer is untouched.
5714 let mut empty = App::new(test_options(false), &Config::default());
5715 assert!(!empty.kill_to_end_of_line());
5716 assert!(empty.input.is_empty());
5717 assert!(empty.kill_buffer.is_empty());
5718 }
5719
5720 #[test]
5721 fn yank_inserts_kill_buffer_and_preserves_it() {
5722 let mut app = App::new(test_options(false), &Config::default());
5723 app.input = "abc def".to_string();
5724 app.cursor_position = 4; // before 'd'
5725 assert!(app.kill_to_end_of_line());
5726 assert_eq!(app.input, "abc ");
5727 assert_eq!(app.kill_buffer, "def");
5728
5729 // Move cursor to the start and yank twice — kill_buffer must persist.
5730 app.cursor_position = 0;
5731 assert!(app.yank());
5732 assert!(app.yank());
5733 assert_eq!(app.input, "defdefabc ");
5734 assert_eq!(app.cursor_position, 6);
5735 assert_eq!(app.kill_buffer, "def");
5736
5737 // Yank with empty buffer is a no-op.
5738 let mut empty = App::new(test_options(false), &Config::default());
5739 assert!(!empty.yank());
5740 assert!(empty.input.is_empty());
5741 }
5742
5743 // ---- Issue #90: quit confirmation timeout ----
5744
5745 #[test]
5746 fn quit_is_not_armed_by_default() {
5747 let app = App::new(test_options(false), &Config::default());
5748 assert!(!app.quit_is_armed());
5749 assert!(app.quit_armed_until.is_none());
5750 }
5751
5752 #[test]
5753 fn arm_quit_sets_two_second_window() {
5754 let mut app = App::new(test_options(false), &Config::default());
5755 app.arm_quit();
5756 assert!(app.quit_is_armed());
5757 let deadline = app.quit_armed_until.expect("deadline set");
5758 let remaining = deadline.saturating_duration_since(Instant::now());
5759 // Allow a generous margin for slow CI machines: 1.5s..=2.0s.
5760 assert!(
5761 remaining >= Duration::from_millis(1500) && remaining <= Duration::from_secs(2),
5762 "expected ~2s window, got {remaining:?}",
5763 );
5764 assert!(app.needs_redraw, "armed prompt should request a redraw");
5765 }
5766
5767 #[test]
5768 fn disarm_quit_scenario() {
5769 // Scenario consolidation of: disarm_quit_clears_the_timer, disarm_quit_when_not_armed_is_a_noop
5770 // from disarm_quit_clears_the_timer
5771 {
5772 let mut app = App::new(test_options(false), &Config::default());
5773 app.arm_quit();
5774 app.needs_redraw = false;
5775 app.disarm_quit();
5776 assert!(!app.quit_is_armed());
5777 assert!(app.quit_armed_until.is_none());
5778 assert!(app.needs_redraw, "disarming should request a redraw");
5779 }
5780 // from disarm_quit_when_not_armed_is_a_noop
5781 {
5782 let mut app = App::new(test_options(false), &Config::default());
5783 app.needs_redraw = false;
5784 app.disarm_quit();
5785 assert!(!app.needs_redraw, "no redraw when nothing changed");
5786 }
5787 }
5788
5789 #[test]
5790 fn quit_armed_scenario() {
5791 // Scenario consolidation of: quit_armed_expires_after_window, quit_armed_tick_is_noop_within_window
5792 // from quit_armed_expires_after_window
5793 {
5794 let mut app = App::new(test_options(false), &Config::default());
5795 // Pin the deadline in the past to simulate a stale timer.
5796 app.quit_armed_until = Some(Instant::now() - Duration::from_millis(10));
5797 assert!(
5798 !app.quit_is_armed(),
5799 "expired timer must not count as armed"
5800 );
5801
5802 app.needs_redraw = false;
5803 app.tick_quit_armed();
5804 assert!(app.quit_armed_until.is_none(), "tick clears expired timer");
5805 assert!(
5806 app.needs_redraw,
5807 "expiry triggers a redraw to repaint footer"
5808 );
5809 }
5810 // from quit_armed_tick_is_noop_within_window
5811 {
5812 let mut app = App::new(test_options(false), &Config::default());
5813 app.arm_quit();
5814 app.needs_redraw = false;
5815 app.tick_quit_armed();
5816 assert!(
5817 app.quit_is_armed(),
5818 "tick within window keeps the timer armed"
5819 );
5820 assert!(!app.needs_redraw, "no redraw when nothing changed");
5821 }
5822 }
5823
5824 #[test]
5825 fn re_arming_after_expiry_starts_a_fresh_window() {
5826 let mut app = App::new(test_options(false), &Config::default());
5827 app.quit_armed_until = Some(Instant::now() - Duration::from_secs(5));
5828 app.tick_quit_armed();
5829 assert!(app.quit_armed_until.is_none());
5830 app.arm_quit();
5831 let deadline = app.quit_armed_until.expect("re-armed");
5832 assert!(deadline > Instant::now(), "fresh deadline in the future");
5833 }
5834
5835 // ---- Issue #208: in-flight input routing ----
5836
5837 #[test]
5838 fn submit_disposition_scenario() {
5839 // Scenario consolidation of: submit_disposition_immediate_when_idle_and_online, submit_disposition_queue_when_busy_and_online_not_streaming, submit_disposition_queue_when_busy_and_streaming, submit_disposition_queue_when_offline_and_idle, submit_disposition_offline_busy_queues
5840 // from submit_disposition_immediate_when_idle_and_online
5841 {
5842 let app = App::new(test_options(false), &Config::default());
5843 assert!(!app.is_loading);
5844 assert!(!app.offline_mode);
5845 assert_eq!(
5846 app.decide_submit_disposition(),
5847 SubmitDisposition::Immediate
5848 );
5849 }
5850 // from submit_disposition_queue_when_busy_and_online_not_streaming
5851 {
5852 // Bare Enter has one stable busy-state meaning even before the provider
5853 // emits its first token: queue a follow-up for the next turn.
5854 let mut app = App::new(test_options(false), &Config::default());
5855 app.is_loading = true;
5856 app.offline_mode = false;
5857 // streaming_message_index is None (default) → waiting phase
5858 assert_eq!(app.decide_submit_disposition(), SubmitDisposition::Queue);
5859 }
5860 // from submit_disposition_queue_when_busy_and_streaming
5861 {
5862 let mut app = App::new(test_options(false), &Config::default());
5863 app.is_loading = true;
5864 app.offline_mode = false;
5865 app.streaming_message_index = Some(0);
5866 assert_eq!(app.decide_submit_disposition(), SubmitDisposition::Queue);
5867 }
5868 // from submit_disposition_queue_when_offline_and_idle
5869 {
5870 let mut app = App::new(test_options(false), &Config::default());
5871 app.is_loading = false;
5872 app.offline_mode = true;
5873 assert_eq!(app.decide_submit_disposition(), SubmitDisposition::Queue);
5874 }
5875 // from submit_disposition_offline_busy_queues
5876 {
5877 let mut app = App::new(test_options(false), &Config::default());
5878 app.is_loading = true;
5879 app.offline_mode = true;
5880 // Offline mode always queues, even when streaming
5881 app.streaming_message_index = Some(0);
5882 assert_eq!(app.decide_submit_disposition(), SubmitDisposition::Queue);
5883 }
5884 }
5885
5886 #[test]
5887 fn composer_submit_state_by_chord_matrix() {
5888 use super::{ComposerSubmitAction, ComposerSubmitChord};
5889
5890 let mut app = App::new(test_options(false), &Config::default());
5891 app.input = "hello".to_string();
5892 assert_eq!(
5893 app.decide_composer_submit(ComposerSubmitChord::Enter),
5894 ComposerSubmitAction::Submit(SubmitDisposition::Immediate)
5895 );
5896 assert_eq!(
5897 app.decide_composer_submit(ComposerSubmitChord::CtrlEnter),
5898 ComposerSubmitAction::Submit(SubmitDisposition::Immediate)
5899 );
5900
5901 app.is_loading = true;
5902 assert_eq!(
5903 app.decide_composer_submit(ComposerSubmitChord::Enter),
5904 ComposerSubmitAction::Submit(SubmitDisposition::Queue)
5905 );
5906 assert_eq!(
5907 app.decide_composer_submit(ComposerSubmitChord::CtrlEnter),
5908 ComposerSubmitAction::Submit(SubmitDisposition::Steer)
5909 );
5910
5911 app.streaming_message_index = Some(0);
5912 assert_eq!(
5913 app.decide_composer_submit(ComposerSubmitChord::Enter),
5914 ComposerSubmitAction::Submit(SubmitDisposition::Queue)
5915 );
5916 assert_eq!(
5917 app.decide_composer_submit(ComposerSubmitChord::CtrlEnter),
5918 ComposerSubmitAction::Submit(SubmitDisposition::Steer)
5919 );
5920
5921 app.queue_message(QueuedMessage::new("older queued".to_string(), None));
5922 app.input.clear();
5923 assert_eq!(
5924 app.decide_composer_submit(ComposerSubmitChord::Enter),
5925 ComposerSubmitAction::SendQueuedNow
5926 );
5927 assert_eq!(
5928 app.decide_composer_submit(ComposerSubmitChord::CtrlEnter),
5929 ComposerSubmitAction::SendQueuedNow
5930 );
5931
5932 app.is_loading = false;
5933 app.streaming_message_index = None;
5934 assert_eq!(
5935 app.decide_composer_submit(ComposerSubmitChord::Enter),
5936 ComposerSubmitAction::SendQueuedNow
5937 );
5938 app.offline_mode = true;
5939 assert_eq!(
5940 app.decide_composer_submit(ComposerSubmitChord::Enter),
5941 ComposerSubmitAction::Noop
5942 );
5943
5944 app.input = "offline follow-up".to_string();
5945 assert_eq!(
5946 app.decide_composer_submit(ComposerSubmitChord::CtrlEnter),
5947 ComposerSubmitAction::Submit(SubmitDisposition::Queue)
5948 );
5949 }
5950
5951 #[test]
5952 fn settle_queue_after_turn_holds_queue_on_interrupted_and_failed_turns() {
5953 use codewhale_engine::core::events::TurnOutcomeStatus;
5954
5955 let mut app = App::new(test_options(false), &Config::default());
5956 app.queue_message(QueuedMessage::new("first".to_string(), None));
5957 app.queue_message(QueuedMessage::new("second".to_string(), None));
5958
5959 assert!(
5960 app.settle_queue_after_turn(TurnOutcomeStatus::Interrupted)
5961 .is_none()
5962 );
5963 assert_eq!(app.held_restored_queue, 2);
5964 assert_eq!(app.queued_message_count(), 2);
5965
5966 assert_eq!(
5967 app.decide_composer_submit(ComposerSubmitChord::Enter),
5968 ComposerSubmitAction::SendQueuedNow
5969 );
5970
5971 let first = app
5972 .take_queued_message_for_dispatch(0)
5973 .expect("take held message");
5974 assert_eq!(first.display, "first");
5975 assert_eq!(app.held_restored_queue, 1);
5976
5977 assert!(
5978 app.settle_queue_after_turn(TurnOutcomeStatus::Completed)
5979 .is_none()
5980 );
5981 assert_eq!(app.held_restored_queue, 1);
5982 assert_eq!(app.queued_message_count(), 1);
5983
5984 let second = app
5985 .take_queued_message_for_dispatch(0)
5986 .expect("take second held message");
5987 assert_eq!(second.display, "second");
5988 assert_eq!(app.held_restored_queue, 0);
5989
5990 app.queue_message(QueuedMessage::new("third".to_string(), None));
5991 assert!(
5992 app.settle_queue_after_turn(TurnOutcomeStatus::Failed)
5993 .is_none()
5994 );
5995 assert_eq!(app.held_restored_queue, 1);
5996 assert_eq!(app.queued_message_count(), 1);
5997
5998 let third = app
5999 .take_queued_message_for_dispatch(0)
6000 .expect("take held message after failure");
6001 assert_eq!(third.display, "third");
6002 assert_eq!(app.held_restored_queue, 0);
6003
6004 app.queue_message(QueuedMessage::new("auto-popped".to_string(), None));
6005 let popped = app
6006 .settle_queue_after_turn(TurnOutcomeStatus::Completed)
6007 .expect("completed turn with no held messages auto-pops next queued message");
6008 assert_eq!(popped.display, "auto-popped");
6009 assert_eq!(app.held_restored_queue, 0);
6010 assert_eq!(app.queued_message_count(), 0);
6011 }
6012
6013 #[test]
6014 fn sticky_error_ttl_is_capped_and_clears_on_composer_activity() {
6015 let mut app = App::new(test_options(false), &Config::default());
6016 app.set_sticky_status("workflow failed", StatusToastLevel::Error, None);
6017 let sticky = app.sticky_status.as_ref().expect("sticky error");
6018 assert_eq!(sticky.ttl_ms, Some(App::STICKY_ERROR_TTL_MS));
6019 app.insert_char('a');
6020 assert!(app.sticky_status.is_none());
6021 }
6022
6023 #[test]
6024 fn pop_last_scenario() {
6025 // Scenario consolidation of: pop_last_queued_into_draft_pops_back_and_arms_draft, pop_last_queued_into_draft_noop_when_composer_dirty, pop_last_queued_into_draft_noop_when_draft_already_armed, pop_last_queued_into_draft_noop_when_queue_empty
6026 // from pop_last_queued_into_draft_pops_back_and_arms_draft
6027 {
6028 let mut app = App::new(test_options(false), &Config::default());
6029 app.queue_message(QueuedMessage::new(
6030 "first".to_string(),
6031 Some("skill-A".to_string()),
6032 ));
6033 app.queue_message(QueuedMessage::new(
6034 "last".to_string(),
6035 Some("skill-B".to_string()),
6036 ));
6037
6038 assert!(app.pop_last_queued_into_draft());
6039 assert_eq!(app.input, "last");
6040 assert_eq!(app.cursor_position, "last".chars().count());
6041 assert_eq!(app.queued_messages.len(), 1);
6042 let draft = app.queued_draft.clone().expect("draft is set");
6043 assert_eq!(draft.display, "last");
6044 assert_eq!(draft.skill_instruction.as_deref(), Some("skill-B"));
6045 }
6046 // from pop_last_queued_into_draft_noop_when_composer_dirty
6047 {
6048 let mut app = App::new(test_options(false), &Config::default());
6049 app.queue_message(QueuedMessage::new("queued".to_string(), None));
6050 app.input = "typing".to_string();
6051 app.cursor_position = char_count(&app.input);
6052
6053 assert!(!app.pop_last_queued_into_draft());
6054 assert_eq!(app.input, "typing");
6055 assert_eq!(app.queued_messages.len(), 1);
6056 assert!(app.queued_draft.is_none());
6057 }
6058 // from pop_last_queued_into_draft_noop_when_draft_already_armed
6059 {
6060 let mut app = App::new(test_options(false), &Config::default());
6061 app.queue_message(QueuedMessage::new("queued".to_string(), None));
6062 app.queued_draft = Some(QueuedMessage::new("editing".to_string(), None));
6063
6064 assert!(!app.pop_last_queued_into_draft());
6065 assert_eq!(app.queued_messages.len(), 1);
6066 assert_eq!(
6067 app.queued_draft.as_ref().map(|d| d.display.as_str()),
6068 Some("editing")
6069 );
6070 }
6071 // from pop_last_queued_into_draft_noop_when_queue_empty
6072 {
6073 let mut app = App::new(test_options(false), &Config::default());
6074 assert!(!app.pop_last_queued_into_draft());
6075 assert!(app.input.is_empty());
6076 assert!(app.queued_draft.is_none());
6077 }
6078 }
6079
6080 #[test]
6081 fn cancel_queued_draft_edit_restores_original_message() {
6082 let mut app = App::new(test_options(false), &Config::default());
6083 app.queue_message(QueuedMessage::new("first".to_string(), None));
6084 app.queue_message(QueuedMessage::new(
6085 "original follow-up".to_string(),
6086 Some("skill".to_string()),
6087 ));
6088 assert!(app.pop_last_queued_into_draft());
6089 app.input = "edited but not submitted".to_string();
6090 app.cursor_position = char_count(&app.input);
6091
6092 assert!(app.cancel_queued_draft_edit());
6093
6094 assert!(app.input.is_empty());
6095 assert!(app.queued_draft.is_none());
6096 assert_eq!(app.queued_messages.len(), 2);
6097 let restored = app.queued_messages.back().expect("restored message");
6098 assert_eq!(restored.display, "original follow-up");
6099 assert_eq!(restored.skill_instruction.as_deref(), Some("skill"));
6100 assert_eq!(
6101 app.clear_undo_buffer.as_deref(),
6102 Some("edited but not submitted"),
6103 "the interrupted edit remains recoverable via normal draft recovery"
6104 );
6105 }
6106
6107 #[test]
6108 fn cancel_held_queued_draft_edit_stays_held_before_live_tail() {
6109 use codewhale_engine::core::events::TurnOutcomeStatus;
6110
6111 let mut app = App::new(test_options(false), &Config::default());
6112 app.queue_message(QueuedMessage::new("held-1".to_string(), None));
6113 app.queue_message(QueuedMessage::new("held-2".to_string(), None));
6114 assert!(
6115 app.settle_queue_after_turn(TurnOutcomeStatus::Failed)
6116 .is_none()
6117 );
6118 app.queue_message(QueuedMessage::new("live-1".to_string(), None));
6119 assert_eq!(app.held_restored_queue, 2);
6120
6121 assert!(app.pop_first_queued_into_draft());
6122 assert_eq!(app.held_restored_queue, 1);
6123 assert!(app.queued_draft_was_held);
6124 app.input = "edited held-1".to_string();
6125
6126 assert!(app.cancel_queued_draft_edit());
6127 assert!(!app.queued_draft_was_held);
6128 assert_eq!(app.held_restored_queue, 2);
6129 let displays: Vec<&str> = app
6130 .queued_messages
6131 .iter()
6132 .map(|message| message.display.as_str())
6133 .collect();
6134 assert_eq!(displays, vec!["held-2", "held-1", "live-1"]);
6135 assert!(
6136 app.settle_queue_after_turn(TurnOutcomeStatus::Completed)
6137 .is_none()
6138 );
6139 }
6140
6141 #[test]
6142 fn non_completed_turn_holds_open_live_draft_on_cancel() {
6143 use codewhale_engine::core::events::TurnOutcomeStatus;
6144
6145 let mut app = App::new(test_options(false), &Config::default());
6146 app.queue_message(QueuedMessage::new("live-draft".to_string(), None));
6147 assert!(app.pop_last_queued_into_draft());
6148 assert!(!app.queued_draft_was_held);
6149
6150 assert!(
6151 app.settle_queue_after_turn(TurnOutcomeStatus::Interrupted)
6152 .is_none()
6153 );
6154 assert!(app.queued_draft_was_held);
6155 app.queue_message(QueuedMessage::new("live-after".to_string(), None));
6156
6157 assert!(app.cancel_queued_draft_edit());
6158 assert_eq!(app.held_restored_queue, 1);
6159 let displays: Vec<&str> = app
6160 .queued_messages
6161 .iter()
6162 .map(|message| message.display.as_str())
6163 .collect();
6164 assert_eq!(displays, vec!["live-draft", "live-after"]);
6165 assert!(
6166 app.settle_queue_after_turn(TurnOutcomeStatus::Completed)
6167 .is_none()
6168 );
6169 }
6170
6171 #[test]
6172 fn finalize_streaming_scenario() {
6173 // Scenario consolidation of: finalize_streaming_assistant_marks_existing_cell_interrupted, finalize_streaming_assistant_handles_empty_content, finalize_streaming_assistant_no_op_without_index, finalize_streaming_assistant_is_idempotent_on_double_call
6174 // from finalize_streaming_assistant_marks_existing_cell_interrupted
6175 {
6176 let mut app = App::new(test_options(false), &Config::default());
6177 app.add_message(HistoryCell::Assistant {
6178 content: "partial reply so far".to_string(),
6179 streaming: true,
6180 });
6181 let idx = app.history.len() - 1;
6182 app.streaming_message_index = Some(idx);
6183
6184 app.finalize_streaming_assistant_as_interrupted();
6185
6186 assert!(app.streaming_message_index.is_none());
6187 match &app.history[idx] {
6188 HistoryCell::Assistant { content, streaming } => {
6189 assert!(content.starts_with("[interrupted]"), "got: {content}");
6190 assert!(content.contains("partial reply so far"));
6191 assert!(!*streaming);
6192 }
6193 other => panic!("expected Assistant cell, got {other:?}"),
6194 }
6195 }
6196 // from finalize_streaming_assistant_handles_empty_content
6197 {
6198 let mut app = App::new(test_options(false), &Config::default());
6199 app.add_message(HistoryCell::Assistant {
6200 content: String::new(),
6201 streaming: true,
6202 });
6203 let idx = app.history.len() - 1;
6204 app.streaming_message_index = Some(idx);
6205
6206 app.finalize_streaming_assistant_as_interrupted();
6207
6208 match &app.history[idx] {
6209 HistoryCell::Assistant { content, streaming } => {
6210 assert_eq!(content, "[interrupted]");
6211 assert!(!*streaming);
6212 }
6213 other => panic!("expected Assistant cell, got {other:?}"),
6214 }
6215 }
6216 // from finalize_streaming_assistant_no_op_without_index
6217 {
6218 let mut app = App::new(test_options(false), &Config::default());
6219 // No streaming index set; should not panic and should leave history unchanged.
6220 let prev_len = app.history.len();
6221 app.finalize_streaming_assistant_as_interrupted();
6222 assert_eq!(app.history.len(), prev_len);
6223 assert!(app.streaming_message_index.is_none());
6224 }
6225 // from finalize_streaming_assistant_is_idempotent_on_double_call
6226 {
6227 let mut app = App::new(test_options(false), &Config::default());
6228 app.add_message(HistoryCell::Assistant {
6229 content: "something".to_string(),
6230 streaming: true,
6231 });
6232 let idx = app.history.len() - 1;
6233 app.streaming_message_index = Some(idx);
6234
6235 app.finalize_streaming_assistant_as_interrupted();
6236 // Second call without resetting state must be safe.
6237 app.finalize_streaming_assistant_as_interrupted();
6238
6239 match &app.history[idx] {
6240 HistoryCell::Assistant { content, .. } => {
6241 // Second call still finds index None — content unchanged from first.
6242 assert!(content.starts_with("[interrupted] "));
6243 assert_eq!(content.matches("[interrupted]").count(), 1);
6244 }
6245 other => panic!("expected Assistant cell, got {other:?}"),
6246 }
6247 }
6248 }
6249
6250 #[test]
6251 fn delete_word_scenario() {
6252 // Scenario consolidation of: delete_word_backward_removes_previous_word_only, delete_word_backward_handles_trailing_space_and_utf8, delete_word_forward_handles_leading_space_and_utf8
6253 // from delete_word_backward_removes_previous_word_only
6254 {
6255 let mut app = App::new(test_options(false), &Config::default());
6256 app.input = "hello world".to_string();
6257 app.cursor_position = char_count(&app.input);
6258
6259 app.delete_word_backward();
6260
6261 assert_eq!(app.input, "hello ");
6262 assert_eq!(app.cursor_position, char_count("hello "));
6263 }
6264 // from delete_word_backward_handles_trailing_space_and_utf8
6265 {
6266 let mut app = App::new(test_options(false), &Config::default());
6267 app.input = "cafe 你好 ".to_string();
6268 app.cursor_position = char_count(&app.input);
6269
6270 app.delete_word_backward();
6271
6272 assert_eq!(app.input, "cafe ");
6273 assert_eq!(app.cursor_position, char_count("cafe "));
6274 }
6275 // from delete_word_forward_handles_leading_space_and_utf8
6276 {
6277 let mut app = App::new(test_options(false), &Config::default());
6278 app.input = "hello 你好 world".to_string();
6279 app.cursor_position = char_count("hello");
6280
6281 app.delete_word_forward();
6282
6283 assert_eq!(app.input, "hello world");
6284 assert_eq!(app.cursor_position, char_count("hello"));
6285 }
6286 }
6287
6288 #[test]
6289 fn delete_to_start_of_line_respects_multiline_cursor() {
6290 let mut app = App::new(test_options(false), &Config::default());
6291 app.input = "first\nsecond line".to_string();
6292 app.cursor_position = char_count("first\nsecond");
6293
6294 app.delete_to_start_of_line();
6295
6296 assert_eq!(app.input, "first\n line");
6297 assert_eq!(app.cursor_position, char_count("first\n"));
6298 }
6299
6300 #[test]
6301 fn kill_and_yank_handle_multibyte_utf8() {
6302 let mut app = App::new(test_options(false), &Config::default());
6303 // "café 你好" — char_count = 7 (c,a,f,é, ,你,好); UTF-8 bytes differ.
6304 app.input = "café 你好".to_string();
6305 app.cursor_position = 5; // before '你'
6306 assert!(app.kill_to_end_of_line());
6307 assert_eq!(app.input, "café ");
6308 assert_eq!(app.cursor_position, 5);
6309 assert_eq!(app.kill_buffer, "你好");
6310
6311 // Yank back at the same spot — must not panic on char boundaries.
6312 assert!(app.yank());
6313 assert_eq!(app.input, "café 你好");
6314 assert_eq!(app.cursor_position, 7);
6315 }
6316
6317 #[test]
6318 fn selection_range_scenario() {
6319 // Scenario consolidation of: selection_range_returns_none_when_no_anchor, selection_range_returns_ordered_range, selection_range_normalizes_order, selection_range_returns_none_when_anchor_equals_cursor
6320 // from selection_range_returns_none_when_no_anchor
6321 {
6322 let mut app = App::new(test_options(false), &Config::default());
6323 app.input = "hello world".to_string();
6324 app.cursor_position = 5;
6325 app.selection_anchor = None;
6326 assert!(app.selection_range().is_none());
6327 }
6328 // from selection_range_returns_ordered_range
6329 {
6330 let mut app = App::new(test_options(false), &Config::default());
6331 app.input = "hello world".to_string();
6332 app.cursor_position = 5;
6333 app.selection_anchor = Some(2);
6334 assert_eq!(app.selection_range(), Some((2, 5)));
6335 }
6336 // from selection_range_normalizes_order
6337 {
6338 let mut app = App::new(test_options(false), &Config::default());
6339 app.input = "hello world".to_string();
6340 app.cursor_position = 2;
6341 app.selection_anchor = Some(5);
6342 assert_eq!(app.selection_range(), Some((2, 5)));
6343 }
6344 // from selection_range_returns_none_when_anchor_equals_cursor
6345 {
6346 let mut app = App::new(test_options(false), &Config::default());
6347 app.input = "hello".to_string();
6348 app.cursor_position = 3;
6349 app.selection_anchor = Some(3);
6350 assert!(app.selection_range().is_none());
6351 }
6352 }
6353
6354 #[test]
6355 fn delete_selection_scenario() {
6356 // Scenario consolidation of: delete_selection_removes_selected_text, delete_selection_noop_when_no_selection, delete_selection_handles_cjk_and_emoji_ranges
6357 // from delete_selection_removes_selected_text
6358 {
6359 let mut app = App::new(test_options(false), &Config::default());
6360 app.input = "hello world".to_string();
6361 app.cursor_position = 5;
6362 app.selection_anchor = Some(2);
6363 assert!(app.delete_selection());
6364 assert_eq!(app.input, "he world");
6365 assert_eq!(app.cursor_position, 2);
6366 assert!(app.selection_anchor.is_none());
6367 }
6368 // from delete_selection_noop_when_no_selection
6369 {
6370 let mut app = App::new(test_options(false), &Config::default());
6371 app.input = "hello".to_string();
6372 app.cursor_position = 3;
6373 app.selection_anchor = None;
6374 assert!(!app.delete_selection());
6375 assert_eq!(app.input, "hello");
6376 assert_eq!(app.cursor_position, 3);
6377 }
6378 // from delete_selection_handles_cjk_and_emoji_ranges
6379 {
6380 let mut app = App::new(test_options(false), &Config::default());
6381 app.input = "a你👩‍👩‍👧‍👦好b".to_string();
6382 // Select 你 + family emoji (7 chars) + 好: chars 1..10.
6383 app.selection_anchor = Some(1);
6384 app.cursor_position = 10;
6385 assert_eq!(app.selected_text(), "你👩‍👩‍👧‍👦好");
6386 assert!(app.delete_selection());
6387 assert_eq!(app.input, "ab");
6388 assert_eq!(app.cursor_position, 1);
6389 }
6390 }
6391
6392 #[test]
6393 fn insert_char_replaces_selection() {
6394 let mut app = App::new(test_options(false), &Config::default());
6395 app.input = "hello world".to_string();
6396 app.cursor_position = 5;
6397 app.selection_anchor = Some(2);
6398 app.insert_char('X');
6399 assert_eq!(app.input, "heX world");
6400 assert_eq!(app.cursor_position, 3);
6401 assert!(app.selection_anchor.is_none());
6402 }
6403
6404 #[test]
6405 fn delete_char_removes_selection_instead_of_single_char() {
6406 let mut app = App::new(test_options(false), &Config::default());
6407 app.input = "hello world".to_string();
6408 app.cursor_position = 5;
6409 app.selection_anchor = Some(2);
6410 app.delete_char();
6411 assert_eq!(app.input, "he world");
6412 assert_eq!(app.cursor_position, 2);
6413 }
6414
6415 #[test]
6416 fn selected_text_returns_correct_substring() {
6417 let mut app = App::new(test_options(false), &Config::default());
6418 app.input = "hello world".to_string();
6419 app.cursor_position = 5;
6420 app.selection_anchor = Some(2);
6421 assert_eq!(app.selected_text(), "llo");
6422 }
6423
6424 #[test]
6425 fn insert_str_replaces_selection() {
6426 let mut app = App::new(test_options(false), &Config::default());
6427 app.input = "hello world".to_string();
6428 app.cursor_position = 5;
6429 app.selection_anchor = Some(2);
6430 app.insert_str("yo");
6431 assert_eq!(app.input, "heyo world");
6432 assert_eq!(app.cursor_position, 4);
6433 assert!(app.selection_anchor.is_none());
6434 }
6435
6436 // === Composer real-editor contract (v0.9.1) ====================================
6437
6438 #[test]
6439 fn grapheme_boundaries_snap_around_zwj_emoji_and_flags() {
6440 // "a👩‍👩‍👧‍👦b" — the family emoji is 7 chars (4 people + 3 ZWJ) but ONE grapheme.
6441 let text = "a👩‍👩‍👧‍👦b";
6442 let family_chars = "👩‍👩‍👧‍👦".chars().count();
6443 assert_eq!(family_chars, 7);
6444 // Stepping right from after 'a' jumps over the whole family.
6445 assert_eq!(next_grapheme_boundary(text, 1), 1 + family_chars);
6446 // Stepping left from before 'b' jumps back to just after 'a'.
6447 assert_eq!(prev_grapheme_boundary(text, 1 + family_chars), 1);
6448 // A cursor stranded mid-cluster snaps to the cluster edges.
6449 assert_eq!(prev_grapheme_boundary(text, 3), 1);
6450 assert_eq!(next_grapheme_boundary(text, 3), 1 + family_chars);
6451
6452 // Flag pair: two regional-indicator chars, one grapheme.
6453 let flag = "🇯🇵";
6454 assert_eq!(flag.chars().count(), 2);
6455 assert_eq!(next_grapheme_boundary(flag, 0), 2);
6456 assert_eq!(prev_grapheme_boundary(flag, 2), 0);
6457 }
6458
6459 #[test]
6460 fn cursor_moves_by_grapheme_over_emoji_and_cjk() {
6461 let mut app = App::new(test_options(false), &Config::default());
6462 app.input = "你👍🏽好".to_string(); // CJK + skin-tone emoji (2 chars) + CJK
6463 app.cursor_position = 0;
6464 app.move_cursor_right();
6465 assert_eq!(app.cursor_position, 1); // after 你
6466 app.move_cursor_right();
6467 assert_eq!(app.cursor_position, 3); // after 👍🏽 (base + modifier)
6468 app.move_cursor_right();
6469 assert_eq!(app.cursor_position, 4); // after 好
6470 app.move_cursor_right();
6471 assert_eq!(app.cursor_position, 4); // clamped at end
6472 app.move_cursor_left();
6473 assert_eq!(app.cursor_position, 3);
6474 app.move_cursor_left();
6475 assert_eq!(app.cursor_position, 1);
6476 app.move_cursor_left();
6477 assert_eq!(app.cursor_position, 0);
6478 app.move_cursor_left();
6479 assert_eq!(app.cursor_position, 0); // clamped at start
6480 }
6481
6482 /// U01-m4: vim Normal-mode clamps, `a`, and `j`/`k` column moves land on
6483 /// grapheme-cluster starts, never inside a combining or skin-tone sequence.
6484 #[test]
6485 fn vim_cursor_moves_never_split_a_grapheme_cluster() {
6486 let mut app = App::new(test_options(false), &Config::default());
6487 app.vim_enabled = true;
6488 // "e" + COMBINING ACUTE: two scalars, one cluster.
6489 app.input = "e\u{301}".to_string();
6490 app.cursor_position = char_count(&app.input);
6491 app.vim_enter_normal();
6492 assert_eq!(
6493 app.cursor_position, 0,
6494 "Normal mode sits on the cluster start"
6495 );
6496 app.vim_enter_append();
6497 assert_eq!(
6498 app.cursor_position, 2,
6499 "`a` appends after the whole cluster"
6500 );
6501
6502 // Scalar column 1 falls inside the other line's skin-tone emoji.
6503 app.input = "ab\n\u{1f44d}\u{1f3fd}c".to_string();
6504 app.cursor_position = 1; // on `b`
6505 app.vim_move_down();
6506 assert_eq!(app.cursor_position, 3, "`j` lands on the emoji's start");
6507 app.input = "\u{1f44d}\u{1f3fd}c\nab".to_string();
6508 app.cursor_position = 5; // on `b`
6509 app.vim_move_up();
6510 assert_eq!(app.cursor_position, 0, "`k` lands on the emoji's start");
6511 }
6512
6513 #[test]
6514 fn backspace_removes_whole_emoji_cluster() {
6515 let mut app = App::new(test_options(false), &Config::default());
6516 app.input = "hi👩‍👩‍👧‍👦".to_string();
6517 app.cursor_position = char_count(&app.input);
6518 app.delete_char();
6519 assert_eq!(app.input, "hi");
6520 assert_eq!(app.cursor_position, 2);
6521 }
6522
6523 #[test]
6524 fn forward_delete_removes_whole_flag_cluster() {
6525 let mut app = App::new(test_options(false), &Config::default());
6526 app.input = "🇯🇵ok".to_string();
6527 app.cursor_position = 0;
6528 app.delete_char_forward();
6529 assert_eq!(app.input, "ok");
6530 assert_eq!(app.cursor_position, 0);
6531 }
6532
6533 #[test]
6534 fn backspace_deletes_cjk_per_character() {
6535 let mut app = App::new(test_options(false), &Config::default());
6536 app.input = "你好".to_string();
6537 app.cursor_position = 2;
6538 app.delete_char();
6539 assert_eq!(app.input, "你");
6540 app.delete_char();
6541 assert_eq!(app.input, "");
6542 }
6543
6544 #[test]
6545 fn vim_x_removes_whole_grapheme_cluster() {
6546 let mut app = App::new(test_options(false), &Config::default());
6547 app.input = "👍🏽a".to_string();
6548 app.cursor_position = 0;
6549 app.vim_delete_char_under_cursor();
6550 assert_eq!(app.input, "a");
6551 assert_eq!(app.cursor_position, 0);
6552 }
6553
6554 #[test]
6555 fn select_all_scenario() {
6556 // Scenario consolidation of: select_all_covers_whole_draft, select_all_on_empty_composer_sets_no_anchor, select_all_then_typing_replaces_everything_recoverably, select_all_then_backspace_is_recoverable_with_ctrl_z
6557 // from select_all_covers_whole_draft
6558 {
6559 let mut app = App::new(test_options(false), &Config::default());
6560 app.input = "hello 你好 🇯🇵".to_string();
6561 app.cursor_position = 3;
6562 app.select_all();
6563 assert_eq!(app.selection_anchor, Some(0));
6564 assert_eq!(app.cursor_position, char_count(&app.input));
6565 assert_eq!(app.selected_text(), "hello 你好 🇯🇵");
6566 }
6567 // from select_all_on_empty_composer_sets_no_anchor
6568 {
6569 let mut app = App::new(test_options(false), &Config::default());
6570 app.select_all();
6571 assert!(app.selection_anchor.is_none());
6572 assert!(app.selection_range().is_none());
6573 }
6574 // from select_all_then_typing_replaces_everything_recoverably
6575 {
6576 let mut app = App::new(test_options(false), &Config::default());
6577 app.input = "precious draft".to_string();
6578 app.select_all();
6579 app.insert_char('x');
6580 assert_eq!(app.input, "x");
6581 assert_eq!(app.cursor_position, 1);
6582 // The overwritten draft is stashed like Ctrl+U would.
6583 assert_eq!(app.clear_undo_buffer.as_deref(), Some("precious draft"));
6584 assert!(app.draft_history.iter().any(|d| d == "precious draft"));
6585 }
6586 // from select_all_then_backspace_is_recoverable_with_ctrl_z
6587 {
6588 let mut app = App::new(test_options(false), &Config::default());
6589 app.input = "do not lose me".to_string();
6590 app.select_all();
6591 app.delete_char();
6592 assert_eq!(app.input, "");
6593 assert!(app.restore_last_cleared_input_if_empty());
6594 assert_eq!(app.input, "do not lose me");
6595 assert_eq!(app.cursor_position, char_count(&app.input));
6596 }
6597 }
6598
6599 #[test]
6600 fn partial_selection_delete_does_not_stash_undo_buffer() {
6601 let mut app = App::new(test_options(false), &Config::default());
6602 app.input = "hello world".to_string();
6603 app.selection_anchor = Some(0);
6604 app.cursor_position = 5;
6605 assert!(app.delete_selection());
6606 assert_eq!(app.input, " world");
6607 assert!(app.clear_undo_buffer.is_none());
6608 }
6609
6610 #[test]
6611 fn shift_home_end_style_selection_uses_line_bounds() {
6612 let mut app = App::new(test_options(false), &Config::default());
6613 app.input = "first line\nsecond line".to_string();
6614 // Cursor in the middle of the second line ("second ".len() == 7).
6615 app.cursor_position = 11 + 7;
6616 // Shift+Home: anchor at cursor, move to line start.
6617 app.selection_anchor = Some(app.cursor_position);
6618 app.move_cursor_line_start();
6619 assert_eq!(app.cursor_position, 11);
6620 assert_eq!(app.selected_text(), "second ");
6621 // Shift+End from the same anchor: move to line end.
6622 app.move_cursor_line_end();
6623 assert_eq!(app.cursor_position, char_count(&app.input));
6624 assert_eq!(app.selected_text(), "line");
6625 }
6626
6627 #[test]
6628 fn word_selection_extends_by_word_and_replaces_on_type() {
6629 let mut app = App::new(test_options(false), &Config::default());
6630 app.input = "alpha beta gamma".to_string();
6631 app.cursor_position = 0;
6632 // Ctrl/Alt+Shift+Right twice: anchor once, extend word-wise.
6633 app.selection_anchor = Some(app.cursor_position);
6634 app.move_cursor_word_forward();
6635 app.move_cursor_word_forward();
6636 assert_eq!(app.selected_text(), "alpha beta ");
6637 app.insert_char('X');
6638 assert_eq!(app.input, "Xgamma");
6639 assert_eq!(app.cursor_position, 1);
6640 }
6641
6642 // === #2574: capability-aware fallback eligibility ===============================
6643
6644 /// Build an `App` whose fallback chain is `[active, fallbacks...]` with each
6645 /// provider's auth controlled via `config.providers` keys. The startup-default
6646 /// settings home is isolated too: an intentional saved default from a previous
6647 /// test or a developer's real profile must not replace the chain primary.
6648 fn app_with_fallback_chain(
6649 active: ProviderKind,
6650 fallbacks: &[codewhale_config::ProviderKind],
6651 keyed: &[ProviderKind],
6652 ) -> App {
6653 let settings_home = tempfile::tempdir().expect("isolated fallback settings home");
6654 let _home = EnvVarGuard::set("HOME", settings_home.path());
6655 let _user_profile = EnvVarGuard::set("USERPROFILE", settings_home.path());
6656 let _codewhale_home =
6657 EnvVarGuard::set("CODEWHALE_HOME", settings_home.path().join(".codewhale"));
6658 let _deepseek_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
6659 let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
6660 let mut providers = ProvidersConfig::default();
6661 for provider in keyed {
6662 let entry = ProviderConfig {
6663 api_key: Some(format!("test-key-{}", provider.as_str())),
6664 ..Default::default()
6665 };
6666 match provider {
6667 ProviderKind::Deepseek => providers.deepseek = entry,
6668 ProviderKind::Openai => providers.openai = entry,
6669 ProviderKind::Openrouter => providers.openrouter = entry,
6670 ProviderKind::Together => providers.together = entry,
6671 ProviderKind::Fireworks => providers.fireworks = entry,
6672 other => panic!("unhandled keyed provider in test helper: {other:?}"),
6673 }
6674 }
6675
6676 let config = {
6677 let __cw_config_init_21_0 = Some(active.as_str().to_string());
6678 let __cw_config_init_21_1 = fallbacks.to_vec();
6679 let __cw_config_init_21_2 = Some(providers);
6680 let mut __cw_config_init_21_value: Config = Default::default();
6681 __cw_config_init_21_value.provider = __cw_config_init_21_0;
6682 __cw_config_init_21_value.fallback_providers = __cw_config_init_21_1;
6683 __cw_config_init_21_value.providers = __cw_config_init_21_2;
6684 __cw_config_init_21_value
6685 };
6686
6687 let mut options = test_options(false);
6688 options.start_in_agent_mode = true;
6689 options.skip_onboarding = true;
6690 App::new(options, &config)
6691 }
6692
6693 #[test]
6694 fn advance_fallback_skips_unauthed_middle_provider_and_lands_on_next_ready() {
6695 let _lock = lock_test_env();
6696 let _openai = EnvVarGuard::remove("OPENAI_API_KEY");
6697 let _openrouter = EnvVarGuard::remove("OPENROUTER_API_KEY");
6698 let _together = EnvVarGuard::remove("TOGETHER_API_KEY");
6699
6700 // Chain: Openai (active, keyed) -> Openrouter (no key) -> Together (keyed).
6701 let mut app = app_with_fallback_chain(
6702 ProviderKind::Openai,
6703 &[
6704 codewhale_config::ProviderKind::Openrouter,
6705 codewhale_config::ProviderKind::Together,
6706 ],
6707 &[ProviderKind::Openai, ProviderKind::Together],
6708 );
6709 assert_eq!(app.fallback_chain_position(), Some(0));
6710
6711 // Openrouter is skipped (needs auth); we land on Together.
6712 let next = app.advance_fallback("network error");
6713 assert_eq!(next, Some(ProviderKind::Together));
6714 assert_eq!(app.api_provider, ProviderKind::Together);
6715 assert_eq!(app.fallback_chain_position(), Some(2));
6716
6717 let reason = app.last_fallback_reason.as_deref().unwrap_or_default();
6718 assert!(
6719 reason.contains("Fell back to together"),
6720 "reason should name the landed provider: {reason}"
6721 );
6722 assert!(
6723 reason.contains("skipped openrouter: needs auth"),
6724 "reason should note the skipped provider: {reason}"
6725 );
6726 }
6727
6728 #[test]
6729 fn advance_fallback_scenario() {
6730 // Scenario consolidation of: advance_fallback_local_provider_is_eligible_without_a_key, advance_fallback_local_primary_may_fall_back_to_local_sibling
6731 // from advance_fallback_local_provider_is_eligible_without_a_key
6732 {
6733 let _lock = lock_test_env();
6734 let _openai = EnvVarGuard::remove("OPENAI_API_KEY");
6735
6736 // Chain: Openai (active, keyed) -> Ollama (local, no key needed).
6737 let mut app = app_with_fallback_chain(
6738 ProviderKind::Openai,
6739 &[codewhale_config::ProviderKind::Ollama],
6740 &[ProviderKind::Openai],
6741 );
6742
6743 let next = app.advance_fallback("timeout");
6744 assert_eq!(
6745 next,
6746 Some(ProviderKind::Ollama),
6747 "self-hosted providers are ready without a key"
6748 );
6749 assert_eq!(app.api_provider, ProviderKind::Ollama);
6750 let reason = app.last_fallback_reason.as_deref().unwrap_or_default();
6751 assert!(reason.contains("Fell back to ollama"), "{reason}");
6752 assert!(
6753 !reason.contains("skipped"),
6754 "no providers should be skipped: {reason}"
6755 );
6756 }
6757 // from advance_fallback_local_primary_may_fall_back_to_local_sibling
6758 {
6759 let _lock = lock_test_env();
6760
6761 // Local primary (Ollama) -> local sibling (vLLM). Both are self-hosted, so
6762 // the local/private posture is preserved and the fallback is allowed.
6763 let mut app = app_with_fallback_chain(
6764 ProviderKind::Ollama,
6765 &[codewhale_config::ProviderKind::Vllm],
6766 &[],
6767 );
6768
6769 let next = app.advance_fallback("local runtime unavailable");
6770 assert_eq!(
6771 next,
6772 Some(ProviderKind::Vllm),
6773 "local->local fallback stays within the private posture"
6774 );
6775 assert_eq!(app.api_provider, ProviderKind::Vllm);
6776 let reason = app.last_fallback_reason.as_deref().unwrap_or_default();
6777 assert!(reason.contains("Fell back to vllm"), "{reason}");
6778 }
6779 }
6780
6781 #[test]
6782 fn advance_fallback_all_unready_exhausts_with_clear_reason() {
6783 let _lock = lock_test_env();
6784 let _openai = EnvVarGuard::remove("OPENAI_API_KEY");
6785 let _openrouter = EnvVarGuard::remove("OPENROUTER_API_KEY");
6786 let _together = EnvVarGuard::remove("TOGETHER_API_KEY");
6787
6788 // Chain: Openai (active, keyed) -> Openrouter (no key) -> Together (no key).
6789 // Every fallback entry is unready, so the chain exhausts.
6790 let mut app = app_with_fallback_chain(
6791 ProviderKind::Openai,
6792 &[
6793 codewhale_config::ProviderKind::Openrouter,
6794 codewhale_config::ProviderKind::Together,
6795 ],
6796 &[ProviderKind::Openai],
6797 );
6798
6799 let next = app.advance_fallback("rate limited");
6800 assert_eq!(next, None, "no ready fallback remains");
6801 // Active provider is unchanged on exhaustion.
6802 assert_eq!(app.api_provider, ProviderKind::Openai);
6803
6804 let reason = app.last_fallback_reason.as_deref().unwrap_or_default();
6805 assert!(
6806 reason.contains("Fallback chain exhausted"),
6807 "reason should state exhaustion: {reason}"
6808 );
6809 assert!(
6810 reason.contains("skipped openrouter: needs auth")
6811 && reason.contains("skipped together: needs auth"),
6812 "reason should note every skipped provider: {reason}"
6813 );
6814 }
6815
6816 #[test]
6817 fn startup_and_fallback_skip_inactive_external_only_routes_without_io() {
6818 let _lock = lock_test_env();
6819 let temp = tempfile::tempdir().expect("external fallback fixtures");
6820 let codex_path = temp.path().join("codex-auth.json");
6821 let grok_path = temp.path().join("grok-auth.json");
6822 let codex_raw = "inactive Codex bytes must not be read";
6823 let grok_raw = "inactive Grok bytes must not be read";
6824 std::fs::write(&codex_path, codex_raw).expect("write Codex trap");
6825 std::fs::write(&grok_path, grok_raw).expect("write Grok trap");
6826 let _home = EnvVarGuard::set("CODEWHALE_HOME", temp.path().join("owned-home"));
6827 let _codex_path = EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &codex_path);
6828 let _grok_path = EnvVarGuard::set("GROK_AUTH_PATH", &grok_path);
6829 let _codex_access = EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN");
6830 let _legacy_codex_access = EnvVarGuard::remove("CODEX_ACCESS_TOKEN");
6831 let _xai_key = EnvVarGuard::remove("XAI_API_KEY");
6832 let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY");
6833 let _cli_source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE");
6834
6835 let config = {
6836 let __cw_config_init_22_0 = Some(ProviderKind::Deepseek.as_str().to_string());
6837 let __cw_config_init_22_1 = vec![
6838 codewhale_config::ProviderKind::OpenaiCodex,
6839 codewhale_config::ProviderKind::Xai,
6840 ];
6841 let __cw_config_init_22_2 = Some(ProvidersConfig {
6842 openai_codex: ProviderConfig {
6843 auth_mode: Some("oauth".to_string()),
6844 external_credentials: Some(
6845 codewhale_config::ExternalCredentialConsentToml::read_only(
6846 codewhale_config::ProviderKind::OpenaiCodex,
6847 codewhale_config::ExternalCredentialSource::CodexCli,
6848 codex_path.clone(),
6849 ),
6850 ),
6851 ..Default::default()
6852 },
6853 xai: ProviderConfig {
6854 auth_mode: Some("oauth".to_string()),
6855 external_credentials: Some(
6856 codewhale_config::ExternalCredentialConsentToml::read_only(
6857 codewhale_config::ProviderKind::Xai,
6858 codewhale_config::ExternalCredentialSource::GrokCli,
6859 grok_path.clone(),
6860 ),
6861 ),
6862 ..Default::default()
6863 },
6864 ..Default::default()
6865 });
6866 let mut __cw_config_init_22_value: Config = Default::default();
6867 __cw_config_init_22_value.provider = __cw_config_init_22_0;
6868 __cw_config_init_22_value.fallback_providers = __cw_config_init_22_1;
6869 __cw_config_init_22_value.providers = __cw_config_init_22_2;
6870 __cw_config_init_22_value
6871 }
6872 .with_legacy_root(Some("active-deepseek-key".to_string()), None);
6873 let mut options = test_options(false);
6874 options.skip_onboarding = true;
6875
6876 codewhale_runtime::external_credentials::reset_side_effect_trap();
6877 let mut app = App::new(options, &config);
6878 assert_eq!(
6879 codewhale_runtime::external_credentials::side_effect_trap_counts(),
6880 (0, 0),
6881 "startup readiness must not inspect inactive external credentials"
6882 );
6883 assert_eq!(app.advance_fallback("active route unavailable"), None);
6884 assert_eq!(
6885 codewhale_runtime::external_credentials::side_effect_trap_counts(),
6886 (0, 0),
6887 "fallback selection must skip external-only inactive routes without inspection"
6888 );
6889 let reason = app.last_fallback_reason.as_deref().unwrap_or_default();
6890 assert!(
6891 reason.contains("skipped openai-codex: needs auth"),
6892 "{reason}"
6893 );
6894 assert!(reason.contains("skipped xai: needs auth"), "{reason}");
6895 assert_eq!(
6896 std::fs::read_to_string(&codex_path).expect("Codex trap unchanged"),
6897 codex_raw
6898 );
6899 assert_eq!(
6900 std::fs::read_to_string(&grok_path).expect("Grok trap unchanged"),
6901 grok_raw
6902 );
6903 }
6904
6905 #[test]
6906 fn advance_fallback_local_primary_does_not_fall_back_to_cloud() {
6907 let _lock = lock_test_env();
6908 let _openai = EnvVarGuard::remove("OPENAI_API_KEY");
6909 let _deepseek = EnvVarGuard::remove("DEEPSEEK_API_KEY");
6910
6911 // Local primary (Ollama) -> cloud fallback (DeepSeek, fully keyed). The
6912 // cloud entry is policy-blocked even though it is otherwise ready, so the
6913 // chain exhausts rather than leaking a local/private route out to cloud.
6914 let mut app = app_with_fallback_chain(
6915 ProviderKind::Ollama,
6916 &[codewhale_config::ProviderKind::Deepseek],
6917 &[ProviderKind::Deepseek],
6918 );
6919
6920 let next = app.advance_fallback("local runtime unavailable");
6921 assert_eq!(next, None, "local->cloud fallback must be blocked");
6922 assert_eq!(app.api_provider, ProviderKind::Ollama);
6923
6924 let reason = app.last_fallback_reason.as_deref().unwrap_or_default();
6925 assert!(
6926 reason.contains("local/private policy"),
6927 "block reason must be visible and specific: {reason}"
6928 );
6929 assert!(
6930 !reason.contains("needs auth"),
6931 "the block is policy, not missing auth: {reason}"
6932 );
6933 }
6934
6935 #[test]
6936 fn advance_fallback_cloud_primary_can_hop_cloud_to_local_to_cloud() {
6937 let _lock = lock_test_env();
6938 let _openai = EnvVarGuard::remove("OPENAI_API_KEY");
6939 let _deepseek = EnvVarGuard::remove("DEEPSEEK_API_KEY");
6940
6941 // The local/private guard is origin-based. A cloud primary may route to a
6942 // local fallback and then to another cloud fallback if the cloud candidate
6943 // is otherwise ready; only local/private primaries are blocked from leaking
6944 // out to cloud.
6945 let mut app = app_with_fallback_chain(
6946 ProviderKind::Openai,
6947 &[
6948 codewhale_config::ProviderKind::Ollama,
6949 codewhale_config::ProviderKind::Deepseek,
6950 ],
6951 &[ProviderKind::Openai, ProviderKind::Deepseek],
6952 );
6953
6954 let local = app.advance_fallback("cloud provider timed out");
6955 assert_eq!(local, Some(ProviderKind::Ollama));
6956 assert_eq!(app.api_provider, ProviderKind::Ollama);
6957
6958 let cloud = app.advance_fallback("local runtime unavailable");
6959 assert_eq!(cloud, Some(ProviderKind::Deepseek));
6960 assert_eq!(app.api_provider, ProviderKind::Deepseek);
6961
6962 let reason = app.last_fallback_reason.as_deref().unwrap_or_default();
6963 assert!(reason.contains("Fell back to deepseek"), "{reason}");
6964 assert!(
6965 !reason.contains("local/private policy"),
6966 "cloud-primary chains should not trigger local/private blocking: {reason}"
6967 );
6968 }
6969
6970 #[test]
6971 fn status_classifier_does_not_paint_negated_success_green() {
6972 use super::StatusToastLevel;
6973 // Failures that happen to contain a success keyword ("saved", "found")
6974 // must not toast green (#3757 UX review).
6975 let (level, _, _) = App::classify_engine_status("Custom provider was not saved.");
6976 assert_ne!(level, StatusToastLevel::Success);
6977 let (level, _, _) = App::classify_engine_status("Queued message not found");
6978 assert_ne!(level, StatusToastLevel::Success);
6979 let (level, _, _) = App::classify_engine_status("Could not enable subagents");
6980 assert_ne!(level, StatusToastLevel::Success);
6981 let (level, _, _) = App::classify_engine_status("No sessions found");
6982 assert_ne!(level, StatusToastLevel::Success);
6983
6984 // Genuine successes still classify green.
6985 let (level, _, _) = App::classify_engine_status("Team profile saved: reviewer.toml");
6986 assert_eq!(level, StatusToastLevel::Success);
6987
6988 // Both cancel spellings classify as Warning.
6989 let (level, _, _) = App::classify_engine_status("Turn canceled");
6990 assert_eq!(level, StatusToastLevel::Warning);
6991 let (level, _, _) = App::classify_engine_status("Turn cancelled");
6992 assert_eq!(level, StatusToastLevel::Warning);
6993 }
6994
6995 #[test]
6996 fn onboarding_provider_copy_is_provider_neutral_in_en() {
6997 use codewhale_localization::{Locale, MessageId, tr};
6998
6999 let title = tr(Locale::En, MessageId::OnboardProviderTitle);
7000 let blurb = tr(Locale::En, MessageId::OnboardProviderBlurb);
7001 assert!(!title.to_ascii_lowercase().contains("deepseek"), "{title}");
7002 assert!(!blurb.to_ascii_lowercase().contains("deepseek"), "{blurb}");
7003 let choose = tr(Locale::En, MessageId::OnboardProviderChoose);
7004 assert!(
7005 !choose.to_ascii_lowercase().contains("deepseek"),
7006 "{choose}"
7007 );
7008 }
7009
7010 #[test]
7011 fn agent_current_activity_bounds_redacts_and_strips_control_sequences() {
7012 let secret = "sk-activity-secret-1234567890";
7013 let raw = format!(
7014 "\u{1b}[31mrunning\u{1b}[0m\napi_key={secret}\n\u{1b}]8;;https://example.invalid\u{7}details\u{1b}]8;;\u{7}\u{1}"
7015 );
7016 let activity = AgentCurrentActivity::bounded(
7017 AgentCurrentActivityStatus::Running,
7018 Some(raw.clone()),
7019 Some(format!("\u{1b}[33mFile.read\u{1b}[0m {secret}")),
7020 Some(4),
7021 );
7022
7023 let detail = activity.detail.expect("bounded detail");
7024 let tool = activity.current_tool.expect("bounded tool");
7025 assert!(detail.contains("running"), "{detail:?}");
7026 assert!(detail.contains("api_key=[redacted]"), "{detail:?}");
7027 assert!(detail.contains("details"), "{detail:?}");
7028 assert!(tool.contains("File.read"), "{tool:?}");
7029 assert!(tool.contains("[redacted]"), "{tool:?}");
7030 for safe in [&detail, &tool] {
7031 assert!(!safe.contains(secret), "{safe:?}");
7032 assert!(!safe.contains('\u{1b}'), "{safe:?}");
7033 assert!(!safe.contains('\u{1}'), "{safe:?}");
7034 assert!(!safe.contains("example.invalid"), "{safe:?}");
7035 }
7036 assert_eq!(activity.step, Some(4));
7037 assert_eq!(
7038 raw.matches(secret).count(),
7039 1,
7040 "source text stays untouched"
7041 );
7042 }
7043
7044 // ---------------------------------------------------------------------------
7045 // Startup-default persistence (mode + thinking)
7046 // ---------------------------------------------------------------------------
7047 //
7048 // Before this lane, `settings.default_mode` was written in exactly two places
7049 // — a setup-preset apply and `/config` — so interactive mode cycling never
7050 // persisted and Operate silently reverted to Act on restart. Reasoning effort
7051 // persisted, but only through the model/effort picker, so Ctrl+T and the
7052 // hotbar `reasoning.cycle` action were equally lossy.
7053
7054 /// Seal `HOME`/`CODEWHALE_HOME` onto a temp dir so these tests can assert the
7055 /// real write/reload round trip without touching the developer's settings.
7056 fn sealed_settings_home(tmp: &std::path::Path) -> Vec<EnvVarGuard> {
7057 vec![
7058 EnvVarGuard::set("HOME", tmp),
7059 EnvVarGuard::set("USERPROFILE", tmp),
7060 EnvVarGuard::set("CODEWHALE_HOME", tmp.join(".codewhale")),
7061 EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"),
7062 EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"),
7063 ]
7064 }
7065
7066 #[test]
7067 fn interactive_mode_cycle_persists_the_startup_default() {
7068 let _lock = lock_test_env();
7069 let tmp = tempfile::TempDir::new().expect("tempdir");
7070 let _env = sealed_settings_home(tmp.path());
7071 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7072
7073 let mut app = App::new(test_options(false), &Config::default());
7074 app.mode = AppMode::Agent;
7075 app.approval_mode = ApprovalMode::AcceptEdits;
7076 assert!(app.step_permission_dial(false).mode_changed);
7077
7078 assert_eq!(
7079 app.mode,
7080 AppMode::Plan,
7081 "Accept Edits -> Plan is the dial's next stop"
7082 );
7083 let reloaded = Settings::load().expect("reload settings");
7084 assert_eq!(
7085 reloaded.default_mode, "plan",
7086 "the mode the user cycled into must be the startup default"
7087 );
7088 assert_eq!(
7089 AppMode::from_setting(&reloaded.default_mode),
7090 AppMode::Plan,
7091 "a restart must restore the last user choice"
7092 );
7093 assert!(
7094 app.startup_defaults.drain_failures().is_empty(),
7095 "a successful write must not report a failure"
7096 );
7097 }
7098
7099 #[test]
7100 fn explicit_mode_selection_and_hotbar_share_the_persistence_owner() {
7101 let _lock = lock_test_env();
7102 let tmp = tempfile::TempDir::new().expect("tempdir");
7103 let _env = sealed_settings_home(tmp.path());
7104 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7105
7106 let mut app = App::new(test_options(false), &Config::default());
7107 assert_eq!(app.select_mode(AppMode::Plan), SettingSelection::Changed);
7108 assert_eq!(Settings::load().expect("reload").default_mode, "plan");
7109
7110 assert_eq!(app.select_mode(AppMode::Agent), SettingSelection::Changed);
7111 assert_eq!(Settings::load().expect("reload").default_mode, "agent");
7112 }
7113
7114 #[test]
7115 fn session_restore_and_effective_turn_paths_do_not_rewrite_the_startup_default() {
7116 let _lock = lock_test_env();
7117 let tmp = tempfile::TempDir::new().expect("tempdir");
7118 let _env = sealed_settings_home(tmp.path());
7119 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7120
7121 let mut app = App::new(test_options(false), &Config::default());
7122 app.select_mode(AppMode::Plan);
7123 assert_eq!(Settings::load().expect("reload").default_mode, "plan");
7124
7125 // `set_mode` is the session-only primitive used by session restore and
7126 // preset application. It must move the live session without claiming the
7127 // user picked a new startup default.
7128 assert!(app.set_mode(AppMode::Agent));
7129 assert_eq!(app.mode, AppMode::Agent);
7130 assert_eq!(
7131 Settings::load().expect("reload").default_mode,
7132 "plan",
7133 "restoring a session must not rewrite the startup default"
7134 );
7135 }
7136
7137 #[test]
7138 fn reselecting_restored_live_mode_updates_the_startup_default() {
7139 let _lock = lock_test_env();
7140 let tmp = tempfile::TempDir::new().expect("tempdir");
7141 let _env = sealed_settings_home(tmp.path());
7142 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7143
7144 Settings::transact(|settings| {
7145 settings.default_mode = "agent".to_string();
7146 Ok(())
7147 })
7148 .expect("seed startup default");
7149 let mut app = App::new(test_options(false), &Config::default());
7150 assert!(app.set_mode(AppMode::Plan), "simulate session restore");
7151 assert_eq!(Settings::load().expect("reload").default_mode, "agent");
7152
7153 assert_eq!(
7154 app.select_mode(AppMode::Plan),
7155 SettingSelection::PersistedSame,
7156 "an accepted selection that did not move live mode is not a refusal"
7157 );
7158 assert_eq!(
7159 Settings::load().expect("reload").default_mode,
7160 "plan",
7161 "the explicit same-live selection must still become the startup default"
7162 );
7163 }
7164
7165 #[test]
7166 fn mode_change_while_a_turn_runs_is_live_and_persisted() {
7167 let _lock = lock_test_env();
7168 let tmp = tempfile::TempDir::new().expect("tempdir");
7169 let _env = sealed_settings_home(tmp.path());
7170 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7171
7172 let mut app = App::new(test_options(false), &Config::default());
7173 app.select_mode(AppMode::Plan);
7174 app.is_loading = true;
7175 assert!(app.step_permission_dial(false).mode_changed);
7176 app.startup_defaults.flush();
7177
7178 assert_eq!(app.mode, AppMode::Agent);
7179 assert_eq!(app.approval_mode, ApprovalMode::Auto);
7180 assert_eq!(
7181 Settings::load().expect("reload").default_mode,
7182 app.mode.as_setting(),
7183 "a mid-turn change is a real selection"
7184 );
7185 }
7186
7187 #[test]
7188 fn reasoning_cycle_persists_through_the_same_owner_as_the_picker() {
7189 let _lock = lock_test_env();
7190 let tmp = tempfile::TempDir::new().expect("tempdir");
7191 let _env = sealed_settings_home(tmp.path());
7192 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7193
7194 let mut app = App::new(test_options(false), &Config::default());
7195 app.api_provider = ProviderKind::Deepseek;
7196 app.auto_model = false;
7197 app.reasoning_effort = ReasoningEffort::Off;
7198
7199 // Ctrl+T and the hotbar `reasoning.cycle` action both land in
7200 // `apply_reasoning_effort_cycle`.
7201 app.apply_reasoning_effort_cycle().unwrap();
7202
7203 // One step up DeepSeek's ladder from Off is Low, not the old shortcut's High.
7204 assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
7205 assert_eq!(
7206 Settings::load()
7207 .expect("reload settings")
7208 .reasoning_effort
7209 .as_deref(),
7210 Some("low"),
7211 "a restart must restore the last thinking choice"
7212 );
7213 }
7214
7215 #[test]
7216 fn failed_startup_default_write_is_reported_not_swallowed() {
7217 let _lock = lock_test_env();
7218 let tmp = tempfile::TempDir::new().expect("tempdir");
7219 // A regular file where the home directory must be: every settings write
7220 // below it fails.
7221 let blocked_home = tmp.path().join("codewhale-home-file");
7222 std::fs::write(&blocked_home, "not a directory").expect("blocking file");
7223 let _home = EnvVarGuard::set("HOME", tmp.path());
7224 let _user_profile = EnvVarGuard::set("USERPROFILE", tmp.path());
7225 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &blocked_home);
7226 let _deepseek_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
7227 let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
7228 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7229
7230 let mut app = App::new(test_options(false), &Config::default());
7231 assert_eq!(
7232 app.select_mode(AppMode::Plan),
7233 SettingSelection::Changed,
7234 "the live session still changes; only the durable write fails"
7235 );
7236 assert_eq!(app.mode, AppMode::Plan);
7237
7238 app.drain_startup_default_failures();
7239 let toast = app
7240 .status_toasts
7241 .iter()
7242 .find(|toast| toast.text.contains("startup mode"))
7243 .expect("a failed startup-default write must surface a toast");
7244 assert!(
7245 toast.text.contains("was not saved"),
7246 "toast must say the write did not land, got {:?}",
7247 toast.text
7248 );
7249 assert!(
7250 !toast.text.contains(".codewhale"),
7251 "a failure toast must not carry the settings path, got {:?}",
7252 toast.text
7253 );
7254 }
7255
7256 // ---------------------------------------------------------------------------
7257 // Startup-default write ordering
7258 // ---------------------------------------------------------------------------
7259 //
7260 // Each write is a load / modify / save transaction over one `settings.toml`.
7261 // These tests run on a real multi-threaded runtime so the writes actually go
7262 // through `spawn_blocking`, and assert the outcome is decided by the order the
7263 // user acted in — not by which blocking task the scheduler happened to pick.
7264 // `StartupDefaultsWriter::flush` is the determinism hook: it blocks until the
7265 // queue is empty and no transaction is in flight.
7266
7267 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7268 async fn rapid_mode_selections_persist_the_last_one_not_the_last_to_finish() {
7269 let _lock = lock_test_env();
7270 let tmp = tempfile::TempDir::new().expect("tempdir");
7271 let _env = sealed_settings_home(tmp.path());
7272 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7273
7274 let mut app = App::new(test_options(false), &Config::default());
7275 // Faster than a human can Tab, and deliberately revisiting modes so a
7276 // reordered transaction would land on a value that is also "plausible".
7277 for mode in [
7278 AppMode::Plan,
7279 AppMode::Plan,
7280 AppMode::Agent,
7281 AppMode::Plan,
7282 AppMode::Plan,
7283 AppMode::Agent,
7284 AppMode::Plan,
7285 ] {
7286 app.select_mode(mode);
7287 }
7288 app.startup_defaults.flush();
7289
7290 assert_eq!(app.mode, AppMode::Plan);
7291 assert_eq!(
7292 Settings::load().expect("reload").default_mode,
7293 "plan",
7294 "the last selection must win, whatever order the writers ran in"
7295 );
7296 assert!(
7297 app.startup_defaults.drain_failures().is_empty(),
7298 "no write in the burst may fail"
7299 );
7300 }
7301
7302 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7303 async fn rapid_thinking_selections_persist_the_last_one() {
7304 let _lock = lock_test_env();
7305 let tmp = tempfile::TempDir::new().expect("tempdir");
7306 let _env = sealed_settings_home(tmp.path());
7307 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7308
7309 let mut app = App::new(test_options(false), &Config::default());
7310 app.api_provider = ProviderKind::Deepseek;
7311 app.auto_model = false;
7312 app.reasoning_effort = ReasoningEffort::Off;
7313
7314 for _ in 0..6 {
7315 app.apply_reasoning_effort_cycle().unwrap();
7316 }
7317 app.startup_defaults.flush();
7318
7319 let expected = app.reasoning_effort.as_setting_for_route(
7320 app.api_provider,
7321 &app.active_route_base_url,
7322 &app.model,
7323 );
7324 assert_eq!(
7325 Settings::load()
7326 .expect("reload")
7327 .reasoning_effort
7328 .as_deref(),
7329 Some(expected),
7330 "the tier the session ended on must be the tier on disk"
7331 );
7332 }
7333
7334 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7335 async fn fixed_route_thinking_cycle_persists_raw_preference() {
7336 let _lock = lock_test_env();
7337 let tmp = tempfile::TempDir::new().expect("tempdir");
7338 let _env = sealed_settings_home(tmp.path());
7339 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7340
7341 let mut app = App::new(test_options(false), &Config::default());
7342 app.set_provider_identity_record(
7343 codewhale_runtime::config::Config::default()
7344 .resolve_provider_identity(ProviderKind::Moonshot.as_str())
7345 .expect("captured fixture provider"),
7346 );
7347 app.auto_model = false;
7348 app.active_route_base_url =
7349 codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL.to_string();
7350 app.model = codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL.to_string();
7351 app.reasoning_effort = ReasoningEffort::Max;
7352
7353 app.apply_reasoning_effort_cycle().unwrap();
7354 app.startup_defaults.flush();
7355
7356 // Cycling off the top of K3's ladder wraps to Auto rather than Off now
7357 // that the cycle walks `picker_efforts_for_route`. What this test is
7358 // about is unchanged: whatever tier the cycle lands on is the raw
7359 // preference that has to survive a restart, not whatever the route
7360 // executes.
7361 assert_eq!(app.reasoning_effort, ReasoningEffort::Auto);
7362 assert_eq!(app.reasoning_effort_preference, Some(ReasoningEffort::Auto));
7363 assert_eq!(
7364 Settings::load()
7365 .expect("reload")
7366 .reasoning_effort
7367 .as_deref(),
7368 Some("auto"),
7369 "the raw preference the cycle landed on must survive restart"
7370 );
7371 }
7372
7373 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7374 async fn queued_mode_and_thinking_writes_finish_before_a_synchronous_selection() {
7375 let _lock = lock_test_env();
7376 let tmp = tempfile::TempDir::new().expect("tempdir");
7377 let _env = sealed_settings_home(tmp.path());
7378 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7379 let mut app = App::new(test_options(false), &Config::default());
7380 app.api_provider = ProviderKind::Deepseek;
7381 app.auto_model = false;
7382 app.reasoning_effort = ReasoningEffort::Off;
7383 assert_eq!(app.select_mode(AppMode::Plan), SettingSelection::Changed);
7384 app.apply_reasoning_effort_cycle().unwrap();
7385
7386 // A newer synchronous effort selection drains the older queued mode and
7387 // effort first, so a late background writer cannot restore the old effort.
7388 app.startup_defaults
7389 .apply_blocking(crate::tui::startup_defaults::StartupDefaults::reasoning_effort("high"))
7390 .expect("effort write must land");
7391 let saved = Settings::load_persisted().expect("reload");
7392 assert_eq!(saved.default_mode, "plan");
7393 assert_eq!(saved.reasoning_effort.as_deref(), Some("high"));
7394 assert_eq!(app.select_mode(AppMode::Agent), SettingSelection::Changed);
7395 app.startup_defaults.flush();
7396 let saved = Settings::load_persisted().expect("reload");
7397 assert_eq!(saved.default_mode, "agent");
7398 assert_eq!(saved.reasoning_effort.as_deref(), Some("high"));
7399 assert!(app.startup_defaults.drain_failures().is_empty());
7400 }
7401
7402 // ---------------------------------------------------------------------------
7403 // Startup defaults vs. the *other* settings writers
7404 // ---------------------------------------------------------------------------
7405 //
7406 // `StartupDefaultsWriter` only serializes the transactions it owns. The tests
7407 // above prove that much. What follows is the boundary the writer cannot provide
7408 // on its own: `settings.toml` has direct writers in the same process — most
7409 // sharply the Shift+Tab permission posture on the same event loop — and each of
7410 // them loads the whole file, changes some fields, and writes the whole file
7411 // back. Two such writers that do not share a load/modify/save lock each write
7412 // back the other's pre-image, and whichever saves last silently reverts the
7413 // other's field. That boundary now lives in `Settings::transact`.
7414
7415 /// Seal the settings file onto `tmp` via the config-path override, and hand back
7416 /// the root config path the posture writers need. Caller must already hold
7417 /// `lock_test_env()`.
7418 fn sealed_settings_with_root_config(
7419 tmp: &std::path::Path,
7420 ) -> (std::path::PathBuf, Vec<EnvVarGuard>) {
7421 let config_path = tmp.join("config.toml");
7422 let guards = vec![
7423 EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path),
7424 EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"),
7425 EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY"),
7426 ];
7427 (config_path, guards)
7428 }
7429
7430 /// Tab (queued mode write) and Shift+Tab (synchronous posture write) hit the
7431 /// same file through different writers. Neither may lose the other's field.
7432 ///
7433 /// This is the concrete pair from the v0.9.1 report: mode cycling spawns a
7434 /// background `default_mode` transaction, the very next keystroke persists
7435 /// `permission_posture` inline, and before `Settings::transact` the two loaded
7436 /// the same bytes — so the later save reverted whichever field the earlier one
7437 /// had just written.
7438 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7439 async fn mode_and_permission_posture_writes_do_not_clobber_each_other() {
7440 let _lock = lock_test_env();
7441 let tmp = tempfile::TempDir::new().expect("tempdir");
7442 let (config_path, _env) = sealed_settings_with_root_config(tmp.path());
7443 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7444
7445 let mut options = test_options(false);
7446 options.start_in_agent_mode = true;
7447 options.config_path = Some(config_path);
7448 let mut app = App::new(options, &Config::default());
7449 app.approval_mode = ApprovalMode::Suggest;
7450 app.mode = AppMode::Agent;
7451
7452 // Alternate the two writers faster than a human can press keys. Plan is
7453 // skipped because it refuses permission changes by design (#3386), so every
7454 // iteration below genuinely performs both writes.
7455 for next_mode in [
7456 AppMode::Plan,
7457 AppMode::Agent,
7458 AppMode::Plan,
7459 AppMode::Agent,
7460 AppMode::Plan,
7461 ] {
7462 assert_eq!(
7463 app.select_mode(next_mode),
7464 SettingSelection::Changed,
7465 "mode selection must change mode"
7466 );
7467 assert!(
7468 app.select_approval_posture(app.mode_prefs.agent_approval_mode.cycle_permission_next()),
7469 "the posture write must succeed, or the assertion below is vacuous"
7470 );
7471 }
7472 app.startup_defaults.flush();
7473
7474 let expected_posture = App::approval_posture_setting(app.mode_prefs.agent_approval_mode);
7475 let saved = Settings::load_persisted().expect("reload settings");
7476 assert_eq!(
7477 saved.default_mode, "plan",
7478 "the posture writer must not revert the mode the user cycled into"
7479 );
7480 assert_eq!(
7481 saved.permission_posture.as_deref(),
7482 Some(expected_posture),
7483 "the mode writer must not revert the posture the user cycled into"
7484 );
7485 assert!(
7486 app.startup_defaults.drain_failures().is_empty(),
7487 "no write in the burst may fail"
7488 );
7489 }
7490
7491 /// The same boundary for the thinking write against an unrelated direct writer.
7492 ///
7493 /// `Settings::transact` here stands in for every load/modify/save site that is
7494 /// not the startup-defaults writer — `/set --save`, the sidebar and work-surface
7495 /// size persists, the preset apply, the pin reorder. They all share one lock now,
7496 /// so a queued thinking write and an unrelated key cannot revert each other.
7497 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7498 async fn thinking_and_an_unrelated_direct_setting_write_do_not_clobber_each_other() {
7499 let _lock = lock_test_env();
7500 let tmp = tempfile::TempDir::new().expect("tempdir");
7501 let _env = sealed_settings_home(tmp.path());
7502 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7503
7504 let mut app = App::new(test_options(false), &Config::default());
7505 app.api_provider = ProviderKind::Deepseek;
7506 app.auto_model = false;
7507 app.reasoning_effort = ReasoningEffort::Off;
7508
7509 for index in 0..6 {
7510 app.apply_reasoning_effort_cycle().unwrap();
7511 // Interleaved on the same thread, exactly as the event loop would when a
7512 // `/set --save` or a divider drag lands between two Ctrl+T presses.
7513 Settings::transact(|settings| settings.set("max_history", &(100 + index).to_string()))
7514 .expect("the direct write must land");
7515 }
7516 app.startup_defaults.flush();
7517
7518 let expected_effort = app.reasoning_effort.as_setting_for_route(
7519 app.api_provider,
7520 &app.active_route_base_url,
7521 &app.model,
7522 );
7523 let saved = Settings::load_persisted().expect("reload settings");
7524 assert_eq!(
7525 saved.reasoning_effort.as_deref(),
7526 Some(expected_effort),
7527 "the direct writer must not revert the thinking level"
7528 );
7529 assert_eq!(
7530 saved.max_input_history, 105,
7531 "the thinking writer must not revert the last direct write"
7532 );
7533 assert!(app.startup_defaults.drain_failures().is_empty());
7534 }
7535
7536 /// Last write wins across *both* kinds of writer, and only for its own field.
7537 ///
7538 /// The startup-default writer decides ordering among its own queued
7539 /// transactions; `Settings::transact` decides atomicity against everything else.
7540 /// Together the final file must be the last value the user chose for every field
7541 /// they touched — not a mixture that depends on which blocking task the
7542 /// scheduler picked.
7543 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7544 async fn rapid_mixed_writes_settle_on_the_last_value_for_every_field() {
7545 let _lock = lock_test_env();
7546 let tmp = tempfile::TempDir::new().expect("tempdir");
7547 let (config_path, _env) = sealed_settings_with_root_config(tmp.path());
7548 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7549
7550 let mut options = test_options(false);
7551 options.start_in_agent_mode = true;
7552 options.config_path = Some(config_path);
7553 let mut app = App::new(options, &Config::default());
7554 app.api_provider = ProviderKind::Deepseek;
7555 app.auto_model = false;
7556 app.reasoning_effort = ReasoningEffort::Off;
7557 app.approval_mode = ApprovalMode::Suggest;
7558 app.mode = AppMode::Agent;
7559
7560 for index in 0..5 {
7561 // Queued (background) writers.
7562 assert_eq!(
7563 app.select_mode(if index % 2 == 0 {
7564 AppMode::Plan
7565 } else {
7566 AppMode::Agent
7567 }),
7568 SettingSelection::Changed
7569 );
7570 app.apply_reasoning_effort_cycle().unwrap();
7571 // Synchronous direct writers.
7572 assert!(
7573 app.select_approval_posture(app.mode_prefs.agent_approval_mode.cycle_permission_next())
7574 );
7575 Settings::transact(|settings| settings.set("max_history", &(200 + index).to_string()))
7576 .expect("the direct write must land");
7577 }
7578 // A synchronous mode selection must land after every queued writer.
7579 app.startup_defaults
7580 .apply_blocking(crate::tui::startup_defaults::StartupDefaults::mode(
7581 app.mode,
7582 ))
7583 .expect("mode write must land");
7584 app.startup_defaults.flush();
7585
7586 let expected_effort = app.reasoning_effort.as_setting_for_route(
7587 app.api_provider,
7588 &app.active_route_base_url,
7589 &app.model,
7590 );
7591 let expected_posture = App::approval_posture_setting(app.mode_prefs.agent_approval_mode);
7592 let saved = Settings::load_persisted().expect("reload settings");
7593 assert_eq!(saved.default_mode, app.mode.as_setting());
7594 assert_eq!(saved.reasoning_effort.as_deref(), Some(expected_effort));
7595 assert_eq!(saved.permission_posture.as_deref(), Some(expected_posture));
7596 assert_eq!(saved.max_input_history, 204);
7597 assert!(app.startup_defaults.drain_failures().is_empty());
7598 }
7599
7600 /// A test that never sealed its environment must not be able to write, and must
7601 /// not pay for another test's sealed scope.
7602 ///
7603 /// Almost every `App` test cycles modes without sealing `HOME`. Those calls have
7604 /// to be inert: not "usually inert because no other test happens to have opted
7605 /// in", but inert by construction, because the alternative is rewriting the
7606 /// developer's real `~/.codewhale/settings.toml` during `cargo test`.
7607 #[test]
7608 fn mode_cycling_in_an_unsealed_test_writes_nothing() {
7609 let mut app = App::new(test_options(false), &Config::default());
7610 app.mode = AppMode::Agent;
7611 assert_eq!(
7612 app.select_mode(AppMode::Plan),
7613 SettingSelection::Changed,
7614 "the live session must still change"
7615 );
7616 assert_eq!(app.mode, AppMode::Plan);
7617 assert_eq!(
7618 app.startup_defaults.pending_len(),
7619 0,
7620 "an unsealed test must enqueue nothing a later sealed drain could inherit"
7621 );
7622 assert!(
7623 app.startup_defaults.drain_failures().is_empty(),
7624 "a skipped test write is not a user-visible failure"
7625 );
7626 }
7627
7628 // ---------------------------------------------------------------------------
7629 // The live-route turn lock reaches the slash surfaces (#2982)
7630 // ---------------------------------------------------------------------------
7631 //
7632 // The lock used to live only in the selectors — Tab, Ctrl+T, the pickers, the
7633 // hotbar. `/set` and `/config <key> <value>` reached the same live route through
7634 // a different door, and both are reachable mid-turn: the composer accepts
7635 // Shift+Enter and the slash menu while `is_loading`. So during a running turn a
7636 // slash command could swap the model, thinking level, or provider out from
7637 // under the engine *and* persist it. The refusal now sits in one place, above
7638 // every disk write and every `App` mutation.
7639
7640 /// Every live-route key and alias, exercised through the same entry point the
7641 /// slash commands use. Live state, persisted state, the startup-default queue,
7642 /// and setup progress must all be exactly where they started.
7643 #[test]
7644 fn slash_config_and_set_refuse_every_live_route_key_while_a_turn_runs() {
7645 let _lock = lock_test_env();
7646 let tmp = tempfile::TempDir::new().expect("tempdir");
7647 let _env = sealed_settings_home(tmp.path());
7648 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7649
7650 Settings::transact(|settings| {
7651 settings.default_mode = "plan".to_string();
7652 settings.default_model = Some("deepseek-chat".to_string());
7653 settings.reasoning_effort = Some("off".to_string());
7654 Ok(())
7655 })
7656 .expect("seed the persisted route");
7657 let before = Settings::load_persisted().expect("read the seeded settings");
7658
7659 let mut app = App::new(test_options(false), &Config::default());
7660 app.api_provider = ProviderKind::Deepseek;
7661 app.auto_model = false;
7662 app.set_model_selection("deepseek-chat".to_string());
7663 app.reasoning_effort = ReasoningEffort::Off;
7664 let _ = app.set_mode(AppMode::Plan);
7665 app.is_loading = true;
7666
7667 let live_mode = app.mode;
7668 let live_model = app.model.clone();
7669 let live_effort = app.reasoning_effort;
7670 let live_provider = app.api_provider;
7671
7672 // Both `--save` and session-only forms: the refusal is above the branch
7673 // that decides whether to persist, so neither may get through.
7674 for persist in [true, false] {
7675 for (key, value) in [
7676 ("model", "deepseek-v4-pro"),
7677 ("default_model", "deepseek-v4-pro"),
7678 ("reasoning_effort", "high"),
7679 ("effort", "high"),
7680 ("provider", "openai"),
7681 ] {
7682 let result = crate::commands::set_config_value(&mut app, key, value, persist);
7683 assert!(
7684 result.is_error,
7685 "/set {key} {value} (persist={persist}) must be refused mid-turn"
7686 );
7687 let message = result.message.unwrap_or_default();
7688 assert!(
7689 message.contains("locked while a turn is running"),
7690 "the refusal must say why, got {message:?}"
7691 );
7692 }
7693 }
7694
7695 assert_eq!(app.mode, live_mode, "live mode must not move");
7696 assert_eq!(app.model, live_model, "the live route model must not move");
7697 assert_eq!(
7698 app.reasoning_effort, live_effort,
7699 "the live thinking tier must not move"
7700 );
7701 assert_eq!(
7702 app.api_provider, live_provider,
7703 "the live provider must not move"
7704 );
7705
7706 let after = Settings::load_persisted().expect("reload settings");
7707 assert_eq!(after.default_mode, before.default_mode);
7708 assert_eq!(after.default_model, before.default_model);
7709 assert_eq!(after.reasoning_effort, before.reasoning_effort);
7710 assert_eq!(after.provider_models, before.provider_models);
7711
7712 assert_eq!(
7713 app.startup_defaults.pending_len(),
7714 0,
7715 "a refused command must not queue a startup-default write"
7716 );
7717 app.startup_defaults.flush();
7718 assert!(
7719 app.startup_defaults.drain_failures().is_empty(),
7720 "a refusal is not a write failure"
7721 );
7722 assert_eq!(
7723 Settings::load_persisted()
7724 .expect("reload after flush")
7725 .default_mode,
7726 before.default_mode,
7727 "nothing may land after the queue is drained either"
7728 );
7729 assert!(
7730 !codewhale_config::SetupState::path()
7731 .expect("setup state path")
7732 .exists(),
7733 "a refused route change must not record provider/model setup progress"
7734 );
7735 }
7736
7737 /// `default_mode` is a restart default that `set_config_value` deliberately does
7738 /// not apply to the live session, so the turn lock must leave it alone. Locking
7739 /// it would refuse a key that cannot affect the running turn.
7740 #[test]
7741 fn restart_only_default_mode_is_still_settable_while_a_turn_runs() {
7742 let _lock = lock_test_env();
7743 let tmp = tempfile::TempDir::new().expect("tempdir");
7744 let _env = sealed_settings_home(tmp.path());
7745 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7746
7747 let mut app = App::new(test_options(false), &Config::default());
7748 let _ = app.set_mode(AppMode::Plan);
7749 app.is_loading = true;
7750
7751 let result = crate::commands::set_config_value(&mut app, "default_mode", "operate", true);
7752 assert!(
7753 !result.is_error,
7754 "default_mode is restart-only, got {:?}",
7755 result.message
7756 );
7757 assert_eq!(
7758 Settings::load_persisted().expect("reload").default_mode,
7759 "agent"
7760 );
7761 assert_eq!(
7762 app.mode,
7763 AppMode::Plan,
7764 "a restart default must not move the live session"
7765 );
7766 }
7767
7768 // ---------------------------------------------------------------------------
7769 // Shutdown
7770 // ---------------------------------------------------------------------------
7771
7772 /// The last thing a user does before quitting is very often the selection they
7773 /// most want to keep. Those writes are queued off the event loop on purpose, so
7774 /// without an explicit join at shutdown the process can exit with the newest
7775 /// selection still sitting in the queue.
7776 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7777 async fn shutdown_flushes_the_last_selection_and_returns_late_failures() {
7778 let _lock = lock_test_env();
7779 let tmp = tempfile::TempDir::new().expect("tempdir");
7780 let _env = sealed_settings_home(tmp.path());
7781 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7782
7783 let mut app = App::new(test_options(false), &Config::default());
7784 // Deliberately *not* flushed and never drained by an event-loop iteration:
7785 // this is the "Tab, then immediately quit" shape.
7786 assert_eq!(app.select_mode(AppMode::Plan), SettingSelection::Changed);
7787
7788 let failures = app.startup_defaults.shutdown();
7789 assert!(failures.is_empty(), "the write must land, not fail");
7790 assert_eq!(
7791 Settings::load_persisted().expect("reload").default_mode,
7792 "plan",
7793 "the last immediate selection must be on disk after shutdown"
7794 );
7795 }
7796
7797 /// A write that fails after the final redraw cannot be toasted — the toast
7798 /// surface will never be painted again. `shutdown` therefore *returns* the
7799 /// failures so the caller can print them on the restored terminal, and the
7800 /// message it produces is localized and path-free.
7801 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
7802 async fn a_late_startup_default_failure_is_returned_not_only_logged() {
7803 let _lock = lock_test_env();
7804 let tmp = tempfile::TempDir::new().expect("tempdir");
7805 // A regular file where the home directory must be: every settings write
7806 // below it fails.
7807 let blocked_home = tmp.path().join("codewhale-home-file");
7808 std::fs::write(&blocked_home, "not a directory").expect("blocking file");
7809 let _home = EnvVarGuard::set("HOME", tmp.path());
7810 let _user_profile = EnvVarGuard::set("USERPROFILE", tmp.path());
7811 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &blocked_home);
7812 let _deepseek_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
7813 let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
7814 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7815
7816 let mut app = App::new(test_options(false), &Config::default());
7817 assert_eq!(app.select_mode(AppMode::Plan), SettingSelection::Changed);
7818
7819 let failures = app.startup_defaults.shutdown();
7820 let failure = failures
7821 .first()
7822 .expect("a failed write must be reported at shutdown, not swallowed");
7823 assert_eq!(
7824 failure.subjects,
7825 vec![crate::tui::startup_defaults::StartupDefaultSubject::Mode]
7826 );
7827
7828 let message = app.startup_default_failure_message(failure);
7829 assert!(
7830 message.contains("startup mode") && message.contains("was not saved"),
7831 "the shutdown notice must name what was lost, got {message:?}"
7832 );
7833 assert!(
7834 !message.contains(".codewhale") && !message.contains(tmp.path().to_str().unwrap()),
7835 "the shutdown notice must not print the settings path, got {message:?}"
7836 );
7837 }
7838
7839 // ---------------------------------------------------------------------------
7840 // Selector truth: refusal, live change, and persisted-same are three outcomes
7841 // ---------------------------------------------------------------------------
7842 //
7843 // `select_mode` used to return a bool. A refusal and an accepted same-live
7844 // selection both came back `false`, so `/mode`, the Alt+A/P/Y shortcuts, and the
7845 // hotbar mode rows all reported "Already in X mode." for both — including for
7846 // the case that had just rewritten the startup default.
7847
7848 /// The three outcomes are distinguishable, and only a live change is a live
7849 /// change.
7850 #[test]
7851 fn mode_selection_reports_refusal_change_and_persisted_same_distinctly() {
7852 let _lock = lock_test_env();
7853 let tmp = tempfile::TempDir::new().expect("tempdir");
7854 let _env = sealed_settings_home(tmp.path());
7855 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7856
7857 let mut app = App::new(test_options(false), &Config::default());
7858 let _ = app.set_mode(AppMode::Agent);
7859
7860 assert_eq!(app.select_mode(AppMode::Plan), SettingSelection::Changed);
7861 assert!(SettingSelection::Changed.changed_live_state());
7862 assert!(SettingSelection::Changed.accepted());
7863
7864 assert_eq!(
7865 app.select_mode(AppMode::Plan),
7866 SettingSelection::PersistedSame
7867 );
7868 assert!(
7869 !SettingSelection::PersistedSame.changed_live_state(),
7870 "a persisted-same selection must not resync the engine"
7871 );
7872 assert!(
7873 SettingSelection::PersistedSame.accepted(),
7874 "a persisted-same selection did write the startup default"
7875 );
7876
7877 app.is_loading = true;
7878 assert_eq!(app.select_mode(AppMode::Agent), SettingSelection::Changed);
7879 assert!(!SettingSelection::Refused.accepted());
7880 assert_eq!(app.mode, AppMode::Agent, "mode is not turn-locked");
7881 }
7882
7883 /// Every accepted same-live selection shows a saved receipt, and a mid-turn
7884 /// switch reads as a switch — the two must not read the same.
7885 #[test]
7886 fn slash_mode_distinguishes_a_saved_startup_default_from_a_switch() {
7887 let _lock = lock_test_env();
7888 let tmp = tempfile::TempDir::new().expect("tempdir");
7889 let _env = sealed_settings_home(tmp.path());
7890 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7891
7892 let mut app = App::new(test_options(false), &Config::default());
7893 let _ = app.set_mode(AppMode::Plan);
7894 Settings::transact(|settings| {
7895 settings.default_mode = "agent".to_string();
7896 Ok(())
7897 })
7898 .expect("seed a startup default that disagrees with the live mode");
7899
7900 // Same live mode, different startup default: `/mode operate` is a real save.
7901 let receipt = crate::commands::switch_mode(&mut app, AppMode::Plan);
7902 assert!(
7903 receipt.contains("saved as startup default"),
7904 "the save must be reported, got {receipt:?}"
7905 );
7906 app.startup_defaults.flush();
7907 assert_eq!(
7908 Settings::load_persisted().expect("reload").default_mode,
7909 "plan"
7910 );
7911
7912 app.is_loading = true;
7913 let switched = crate::commands::switch_mode(&mut app, AppMode::Agent);
7914 assert!(
7915 switched.starts_with("Switched to"),
7916 "mode is not turn-locked, got {switched:?}"
7917 );
7918 assert_ne!(switched, receipt);
7919 }
7920
7921 /// The hotbar mode rows share the receipt: dispatching a row for the live mode
7922 /// is `Handled` (no engine resync) but still tells the user it saved.
7923 #[test]
7924 fn hotbar_mode_row_for_the_live_mode_still_shows_the_saved_receipt() {
7925 let _lock = lock_test_env();
7926 let tmp = tempfile::TempDir::new().expect("tempdir");
7927 let _env = sealed_settings_home(tmp.path());
7928 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
7929
7930 let mut app = App::new(test_options(false), &Config::default());
7931 let _ = app.set_mode(AppMode::Plan);
7932 let outcome = app.select_mode(AppMode::Plan);
7933 app.report_mode_selection(AppMode::Plan, outcome);
7934
7935 assert_eq!(outcome, SettingSelection::PersistedSame);
7936 assert!(
7937 app.status_toasts
7938 .back()
7939 .map(|notice| notice.text.as_str())
7940 .is_some_and(|message| message.contains("saved as startup default")),
7941 "got {:?}",
7942 app.status_toasts.back()
7943 );
7944 app.startup_defaults.flush();
7945 assert_eq!(
7946 Settings::load_persisted().expect("reload").default_mode,
7947 "plan"
7948 );
7949 }
7950
7951 /// v0.9.1 kimi-k3 dogfood report: `settings.toml`'s `[provider_models]` is a memory of the last
7952 /// `/model` pick, so it must not override a model the user named for *this*
7953 /// launch. A dogfood user ran `codewhale --provider moonshot --model kimi-k3`
7954 /// and the session header kept showing the remembered `kimi-k2.7-code` while
7955 /// `doctor` reported `kimi-k3`; header and route have to agree.
7956 #[test]
7957 fn an_explicit_launch_model_outranks_the_remembered_provider_model() {
7958 let _lock = lock_test_env();
7959 let temp = tempfile::tempdir().expect("sealed state root");
7960 let _home = EnvVarGuard::set("CODEWHALE_HOME", temp.path());
7961 let config_path = temp.path().join("config.toml");
7962 std::fs::write(
7963 &config_path,
7964 "provider = \"moonshot\"\n\n[providers.moonshot]\napi_key = \"k\"\nmodel = \"kimi-k3\"\n",
7965 )
7966 .expect("seed config");
7967 std::fs::write(
7968 temp.path().join("settings.toml"),
7969 "[provider_models]\nmoonshot = \"kimi-k2.7-code\"\n",
7970 )
7971 .expect("seed settings");
7972 let _config_path_guard = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &config_path);
7973 let _codewhale_config_path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
7974
7975 // Without an explicit request this launch, the remembered pick still wins:
7976 // that stickiness is what `/model` exists for.
7977 let _no_flag = EnvVarGuard::remove("CODEWHALE_MODEL");
7978 let _no_legacy_flag = EnvVarGuard::remove("DEEPSEEK_MODEL");
7979 let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)
7980 .expect("load sealed config");
7981 let remembered = App::new(
7982 TuiOptions {
7983 model: config.default_model(),
7984 ..test_options(false)
7985 },
7986 &config,
7987 );
7988 assert_eq!(
7989 remembered.model, "kimi-k2.7-code",
7990 "the remembered /model pick remains the default when nothing was named"
7991 );
7992
7993 // `--model` reaches this binary as CODEWHALE_MODEL. It must win.
7994 let _model_flag = EnvVarGuard::set("CODEWHALE_MODEL", "kimi-k3");
7995 let config = codewhale_plugins::providers::load_config(Some(config_path), None)
7996 .expect("load explicit launch snapshot");
7997 let requested = App::new(
7998 TuiOptions {
7999 model: config.default_model(),
8000 ..test_options(false)
8001 },
8002 &config,
8003 );
8004 assert_eq!(
8005 requested.model, "kimi-k3",
8006 "an explicit --model must never be silently replaced by session memory"
8007 );
8008 }
8009
8010 #[test]
8011 fn ambient_clock_advances_by_clamped_steps() {
8012 let mut app = App::new(test_options(false), &Config::default());
8013 // First sample establishes the baseline without advancing.
8014 assert_eq!(app.sample_ambient_clock_ms(), 0);
8015 // Simulate a long gap between draws (a burst of stream work): the clock
8016 // may advance by at most one clamped step, so positions derived from it
8017 // cannot teleport across the gap.
8018 app.ambient_clock_sampled_at = Some(Instant::now() - Duration::from_secs(9));
8019 let advanced = app.sample_ambient_clock_ms();
8020 assert!(
8021 advanced <= App::AMBIENT_MAX_STEP_MS,
8022 "a 9s draw gap must clamp to one step, got {advanced}ms"
8023 );
8024 }
8025
8026 #[test]
8027 fn ambient_idle_settles_after_grace_and_wakes_on_activity() {
8028 let mut app = App::new(test_options(false), &Config::default());
8029 let start = Instant::now();
8030 // Fresh idle: not yet settled, anchor recorded.
8031 assert!(!app.ambient_idle_settled(false, start));
8032 // Still inside the grace window.
8033 assert!(!app.ambient_idle_settled(
8034 false,
8035 start + Duration::from_millis(App::AMBIENT_IDLE_SETTLE_MS - 500)
8036 ));
8037 // Past the grace window: the aquarium is still.
8038 assert!(app.ambient_idle_settled(
8039 false,
8040 start + Duration::from_millis(App::AMBIENT_IDLE_SETTLE_MS + 500)
8041 ));
8042 // Any live activity clears the anchor and wakes the scene…
8043 assert!(!app.ambient_idle_settled(true, start + Duration::from_secs(60)));
8044 // …and idleness afterwards restarts the full grace period.
8045 assert!(!app.ambient_idle_settled(false, start + Duration::from_secs(61)));
8046 }
8047
8048 #[test]
8049 fn launch_onboarding_scenario() {
8050 // Scenario consolidation of: launch_onboarding_skips_picker_when_xai_oauth_needs_reauth, launch_onboarding_opens_picker_for_generic_missing_key, launch_onboarding_clean_when_onboarded_with_key, launch_onboarding_starts_first_run_at_composer
8051 // from launch_onboarding_skips_picker_when_xai_oauth_needs_reauth
8052 {
8053 // #5032: an onboarded user whose active xAI OAuth credential is missing
8054 // must NOT be sent back to the generic provider picker every launch.
8055 let (onboarding, recovery) = launch_onboarding_decision(
8056 false, // skip_onboarding
8057 true, // was_onboarded
8058 false, // needs_language
8059 true, // needs_api_key
8060 false, // needs_workspace_trust
8061 true, // xai_oauth_needs_reauth
8062 );
8063 assert_eq!(onboarding, OnboardingState::None);
8064 assert!(!recovery);
8065 }
8066 // from launch_onboarding_opens_picker_for_generic_missing_key
8067 {
8068 // A generic missing key (not the xAI-OAuth re-auth case) starts at the
8069 // composer with missing-key recovery armed for the first send.
8070 let (onboarding, recovery) =
8071 launch_onboarding_decision(false, true, false, true, false, false);
8072 assert_eq!(onboarding, OnboardingState::None);
8073 assert!(recovery);
8074 }
8075 // from launch_onboarding_clean_when_onboarded_with_key
8076 {
8077 let (onboarding, recovery) =
8078 launch_onboarding_decision(false, true, false, false, false, false);
8079 assert_eq!(onboarding, OnboardingState::None);
8080 assert!(!recovery);
8081 }
8082 // from launch_onboarding_starts_first_run_at_composer
8083 {
8084 // xAI OAuth re-auth never reopens the generic picker, first run or not.
8085 let (onboarding, recovery) =
8086 launch_onboarding_decision(false, false, false, true, false, true);
8087 assert_eq!(onboarding, OnboardingState::None);
8088 assert!(!recovery);
8089
8090 let (keyless, recovery) = launch_onboarding_decision(false, false, true, true, true, false);
8091 assert_eq!(keyless, OnboardingState::None);
8092 assert!(recovery);
8093
8094 let (trust, _) = launch_onboarding_decision(false, false, false, false, true, false);
8095 assert_eq!(trust, OnboardingState::TrustDirectory);
8096
8097 let (ready, _) = launch_onboarding_decision(false, false, false, false, false, false);
8098 assert_eq!(ready, OnboardingState::None);
8099 }
8100 }
8101
8102 /// Memory note M3: a resume owns the loaded session, so its journal and
8103 /// history move into the App instead of being cloned beside a copy that is
8104 /// dropped right after. The journal's entry buffer is the *same allocation*
8105 /// afterwards, and the result matches the borrowing path exactly.
8106 #[test]
8107 fn owned_restore_moves_the_journal_and_matches_the_borrowing_restore() {
8108 let message = |text: &str| Message {
8109 role: codewhale_models::Role::User,
8110 content: vec![codewhale_models::ContentBlock::Text {
8111 text: text.to_string(),
8112 cache_control: None,
8113 }],
8114 };
8115 let messages = vec![message("first"), message("second")];
8116 let t0 = DateTime::<Utc>::from_timestamp(1_700_000_000, 0).unwrap();
8117 let t1 = t0 + chrono::Duration::seconds(12);
8118 let saved = codewhale_engine::session_manager::create_saved_session_with_id_mode_and_stamps(
8119 "owned-restore".to_string(),
8120 &messages,
8121 &[t0, t1],
8122 "test-model",
8123 Path::new("."),
8124 0,
8125 None,
8126 None,
8127 );
8128
8129 let mut borrowed = App::new(test_options(false), &Config::default());
8130 borrowed.restore_api_messages(
8131 codewhale_engine::runtime_handoff::project_owned_messages_for_restore(
8132 saved.messages.clone(),
8133 ),
8134 &saved,
8135 );
8136
8137 let mut owned_session = saved.clone();
8138 let entries_buffer = owned_session
8139 .journal
8140 .as_ref()
8141 .expect("journal")
8142 .entries
8143 .as_ptr();
8144 let mut owned = App::new(test_options(false), &Config::default());
8145 owned.restore_api_messages_from_owned(&mut owned_session);
8146
8147 assert_eq!(
8148 owned.session_journal.entries.as_ptr(),
8149 entries_buffer,
8150 "the journal must be moved into the App, not cloned"
8151 );
8152 assert!(owned_session.journal.is_none());
8153 assert!(owned_session.messages.is_empty());
8154 assert_eq!(
8155 owned.session_journal.entries,
8156 borrowed.session_journal.entries
8157 );
8158 assert_eq!(owned.api_messages, borrowed.api_messages);
8159 assert_eq!(owned.api_message_stamps, vec![t0, t1]);
8160 assert_eq!(owned.api_message_stamps, borrowed.api_message_stamps);
8161
8162 // A legacy session without a journal rebuilds it from the history, on
8163 // both paths alike.
8164 let mut legacy = saved.clone();
8165 legacy.journal = None;
8166 let mut legacy_borrowed = App::new(test_options(false), &Config::default());
8167 legacy_borrowed.restore_api_messages(
8168 codewhale_engine::runtime_handoff::project_owned_messages_for_restore(
8169 legacy.messages.clone(),
8170 ),
8171 &legacy,
8172 );
8173 let mut legacy_owned = App::new(test_options(false), &Config::default());
8174 legacy_owned.restore_api_messages_from_owned(&mut legacy);
8175 assert_eq!(legacy_owned.api_messages, legacy_borrowed.api_messages);
8176 assert_eq!(
8177 legacy_owned.session_journal.entries.len(),
8178 legacy_borrowed.session_journal.entries.len()
8179 );
8180 assert_eq!(legacy_owned.api_message_stamps.len(), 2);
8181 }
8182
8183 /// Walk Ctrl+T for two full laps on a concrete route and assert that every
8184 /// press changes the effective tier — the value `/status`, the effort status
8185 /// line, and Work receipts report — not merely the requested label.
8186 fn assert_every_ctrl_t_press_changes_the_effective_tier(
8187 provider: ProviderKind,
8188 base_url: &str,
8189 model: &str,
8190 ) -> Vec<ReasoningEffort> {
8191 let mut app = App::new(test_options(false), &Config::default());
8192 app.set_provider_identity_record(
8193 codewhale_runtime::config::Config::default()
8194 .resolve_provider_identity(provider.as_str())
8195 .expect("captured fixture provider"),
8196 );
8197 app.auto_model = false;
8198 app.active_route_base_url = base_url.to_string();
8199 app.model = model.to_string();
8200 app.reasoning_effort = ReasoningEffort::Auto;
8201 let ladder =
8202 crate::tui::model_picker::picker_efforts_for_route(provider, base_url, model, false);
8203 let mut effective = app.effective_reasoning_effort_for_active_route(app.reasoning_effort);
8204 let mut walked = Vec::new();
8205 // Two full laps: the report was about presses after the first lap.
8206 for press in 0..ladder.len() * 2 {
8207 assert_eq!(app.cycle_effort(), SettingSelection::Changed);
8208 let next = app.effective_reasoning_effort_for_active_route(app.reasoning_effort);
8209 assert_ne!(
8210 next, effective,
8211 "{model}: press {press} ({:?}) left the effective tier at {effective:?}",
8212 app.reasoning_effort
8213 );
8214 effective = next;
8215 walked.push(app.reasoning_effort);
8216 }
8217 let mut expected = ladder.clone();
8218 expected.rotate_left(1);
8219 expected.extend(expected.clone());
8220 assert_eq!(walked, expected, "{model} walks the picker ladder");
8221 ladder
8222 }
8223
8224 #[test]
8225 fn every_ctrl_t_press_changes_the_effective_thinking_tier() {
8226 // #6650: Ctrl+T walked rungs that resolved to the tier already in effect,
8227 // so presses looked dead.
8228 let _catalog = codewhale_engine::provider_lake::lock_live_snapshot();
8229 codewhale_engine::provider_lake::clear_live_snapshot();
8230 for (provider, base_url, model) in [
8231 (
8232 ProviderKind::Deepseek,
8233 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
8234 "deepseek-v4.1-flash",
8235 ),
8236 (
8237 ProviderKind::Deepseek,
8238 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
8239 "deepseek-v4.1",
8240 ),
8241 (
8242 ProviderKind::Moonshot,
8243 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
8244 codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL,
8245 ),
8246 (
8247 ProviderKind::Xai,
8248 codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL,
8249 codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL,
8250 ),
8251 ] {
8252 assert_every_ctrl_t_press_changes_the_effective_tier(provider, base_url, model);
8253 }
8254 }
8255
8256 #[test]
8257 fn ctrl_t_skips_catalog_rungs_that_resolve_to_an_offered_tier() {
8258 // A catalog can publish effort spellings the route collapses: DeepSeek
8259 // sends `medium`/`xhigh` as `high`, and Z.ai GLM-5.2 sends `low`/`medium`
8260 // as `high`. Each Ctrl+T press must still reach a new effective tier.
8261 use ReasoningEffort::{Auto, High, Low, Max, Off};
8262 let _catalog = codewhale_engine::provider_lake::lock_live_snapshot();
8263 codewhale_engine::provider_lake::clear_live_snapshot();
8264 let fetched_at = u64::try_from(chrono::Utc::now().timestamp()).expect("timestamp");
8265 let offering = |provider: ProviderKind, model: &str, values: &[&str]| {
8266 codewhale_config::catalog::CatalogOffering {
8267 provider: provider.as_str().to_string(),
8268 wire_model_id: model.to_string(),
8269 endpoint_key: "chat".to_string(),
8270 reasoning_options: vec![serde_json::json!({ "type": "effort", "values": values })],
8271 source: codewhale_config::catalog::CatalogSource::ModelsDevLive { fetched_at },
8272 ..Default::default()
8273 }
8274 };
8275 codewhale_engine::provider_lake::set_live_snapshot(
8276 codewhale_config::catalog::CatalogSnapshot {
8277 offerings: vec![
8278 offering(
8279 ProviderKind::Deepseek,
8280 "deepseek-v4.1-flash",
8281 &["low", "medium", "high", "xhigh", "max"],
8282 ),
8283 offering(
8284 ProviderKind::Zai,
8285 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
8286 &["off", "low", "medium", "high", "max"],
8287 ),
8288 ],
8289 },
8290 codewhale_engine::provider_lake::LiveSource::ModelsDev,
8291 );
8292
8293 let deepseek = assert_every_ctrl_t_press_changes_the_effective_tier(
8294 ProviderKind::Deepseek,
8295 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
8296 "deepseek-v4.1-flash",
8297 );
8298 let zai = assert_every_ctrl_t_press_changes_the_effective_tier(
8299 ProviderKind::Zai,
8300 codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL,
8301 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
8302 );
8303 codewhale_engine::provider_lake::clear_live_snapshot();
8304
8305 assert_eq!(deepseek, vec![Auto, Low, High, Max]);
8306 assert_eq!(zai, vec![Auto, Off, High, Max]);
8307 }
8308
8309 #[test]
8310 fn ctrl_t_moves_past_a_persisted_alias_the_ladder_dropped() {
8311 // DeepSeek has no `medium`; it resolves to `high`, so the next press must
8312 // reach `max` rather than re-select `high`.
8313 let _catalog = codewhale_engine::provider_lake::lock_live_snapshot();
8314 let mut app = App::new(test_options(false), &Config::default());
8315 app.api_provider = ProviderKind::Deepseek;
8316 app.auto_model = false;
8317 app.active_route_base_url =
8318 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL.to_string();
8319 app.model = "deepseek-v4.1-flash".to_string();
8320 app.reasoning_effort = ReasoningEffort::Medium;
8321
8322 app.cycle_effort();
8323
8324 assert_eq!(app.reasoning_effort, ReasoningEffort::Max);
8325 }
8326
8327 #[test]
8328 fn skills_cache_hides_model_only_and_preserves_argument_hint() {
8329 let tmp = tempfile::tempdir().unwrap();
8330 let workspace = tmp.path().join("workspace");
8331 crate::test_support::trust_workspace(&workspace);
8332 let root = workspace.join(".codewhale/skills");
8333 for (name, policy) in [
8334 ("model", "user-invocable: false"),
8335 (
8336 "user",
8337 "disable-model-invocation: true\nargument-hint: '[path]'",
8338 ),
8339 (
8340 "disabled",
8341 "disable-model-invocation: true\nuser-invocable: false",
8342 ),
8343 ] {
8344 let dir = root.join(name);
8345 std::fs::create_dir_all(&dir).unwrap();
8346 std::fs::write(
8347 dir.join("SKILL.md"),
8348 format!("---\nname: {name}\ndescription: routing\n{policy}\n---\nbody"),
8349 )
8350 .unwrap();
8351 }
8352 let mut options = test_options(false);
8353 options.workspace = workspace;
8354 options.skills_dir = root;
8355 let app = App::new(options, &Config::default());
8356 assert!(
8357 app.cached_skills
8358 .iter()
8359 .all(|(name, _)| name != "model" && name != "disabled")
8360 );
8361 assert!(
8362 app.cached_skills
8363 .iter()
8364 .any(|(name, description)| name == "user" && description.contains("[path]"))
8365 );
8366 }
8367
8368 #[cfg(unix)]
8369 #[test]
8370 fn oversized_paste_is_not_written_through_a_linked_pastes_directory() {
8371 let tmp = tempfile::TempDir::new().expect("tempdir");
8372 let outside = tempfile::TempDir::new().expect("outside");
8373 std::os::unix::fs::symlink(outside.path(), tmp.path().join(".codewhale")).expect("link");
8374 let mut opts = test_options(false);
8375 opts.workspace = tmp.path().to_path_buf();
8376 let mut app = App::new(opts, &Config::default());
8377 app.insert_paste_text(&"y".repeat(MAX_SUBMITTED_INPUT_CHARS + 256));
8378
8379 let _ = app.submit_input();
8380
8381 assert!(
8382 std::fs::read_dir(outside.path()).unwrap().next().is_none(),
8383 "the pasted text must not land outside the workspace"
8384 );
8385 }
8386
8387 #[cfg(not(windows))]
8388 #[test]
8389 fn dropped_screenshot_path_becomes_an_image_attachment() {
8390 let dir = tempfile::tempdir().expect("tempdir");
8391 let shot = dir.path().join("Screenshot 2026-10-04 at 22.25.47.png");
8392 std::fs::write(&shot, codewhale_engine::image_attach::test_support::PNG_1X1).expect("fixture");
8393 // Terminal.app / iTerm2 deliver a drop as a shell-escaped paste.
8394 let dropped = shot.display().to_string().replace(' ', "\\ ");
8395 let mut app = App::new(test_options(false), &Config::default());
8396 app.input = "what is wrong here?".to_string();
8397 app.cursor_position = app.input.chars().count();
8398
8399 app.insert_paste_text(&dropped);
8400
8401 let line = format!("[Attached image: {}]", shot.display());
8402 assert!(app.input.contains(&line), "{}", app.input);
8403 assert!(!app.input.contains("\\ "), "{}", app.input);
8404 assert_eq!(app.composer_attachment_count(), 1);
8405 assert_eq!(
8406 app.status_toasts.back().map(|notice| notice.text.as_str()),
8407 Some(format!("Attached image: {}", shot.display()).as_str())
8408 );
8409 let expanded = codewhale_engine::image_attach::expand_attachment_blocks(&app.input);
8410 assert!(expanded.notices.is_empty(), "{expanded:?}");
8411 assert!(
8412 expanded
8413 .blocks
8414 .iter()
8415 .any(|block| matches!(block, codewhale_models::ContentBlock::ImageUrl { .. }))
8416 );
8417 }
8418
8419 #[test]
8420 fn image_path_pasted_on_a_command_line_stays_literal() {
8421 let dir = tempfile::tempdir().expect("tempdir");
8422 let shot = dir.path().join("shot.png");
8423 std::fs::write(&shot, codewhale_engine::image_attach::test_support::PNG_1X1).expect("fixture");
8424 let mut app = App::new(test_options(false), &Config::default());
8425 app.input = "/rename ".to_string();
8426 app.cursor_position = app.input.chars().count();
8427
8428 app.insert_paste_text(&shot.display().to_string());
8429
8430 assert_eq!(app.input, format!("/rename {}", shot.display()));
8431 assert_eq!(app.composer_attachment_count(), 0);
8432 }
8433
8434 #[cfg(not(windows))]
8435 #[test]
8436 fn a_typed_drop_with_the_question_on_its_line_still_sends_the_image() {
8437 let dir = tempfile::tempdir().expect("tempdir");
8438 let shot = dir.path().join("Screenshot 2026-10-04 at 22.25.47.png");
8439 std::fs::write(&shot, codewhale_engine::image_attach::test_support::PNG_1X1).expect("fixture");
8440 let mut app = App::new(test_options(false), &Config::default());
8441 // Arrived as keystrokes, so the paste-time check never saw it.
8442 app.input = format!(
8443 "{} why does it show jobs 2?",
8444 shot.display().to_string().replace(' ', "\\ ")
8445 );
8446 app.cursor_position = app.input.chars().count();
8447
8448 let submitted = app.submit_input().expect("submitted");
8449
8450 assert!(
8451 submitted.starts_with(&format!("[Attached image: {}]\n", shot.display())),
8452 "{submitted}"
8453 );
8454 assert!(
8455 submitted.ends_with("why does it show jobs 2?"),
8456 "{submitted}"
8457 );
8458 let expanded = codewhale_engine::image_attach::expand_attachment_blocks(&submitted);
8459 assert!(expanded.notices.is_empty(), "{expanded:?}");
8460 assert!(
8461 expanded
8462 .blocks
8463 .iter()
8464 .any(|block| matches!(block, codewhale_models::ContentBlock::ImageUrl { .. }))
8465 );
8466 }
8467
8468 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
8469 async fn pet_view_choice_restores_without_launch_overlay_and_preserves_other_settings() {
8470 let _lock = lock_test_env();
8471 let tmp = tempfile::TempDir::new().unwrap();
8472 let _env = sealed_settings_home(tmp.path());
8473 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
8474 let path = tmp.path().join(".codewhale/settings.toml");
8475 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8476 std::fs::write(
8477 &path,
8478 "# keep this comment\nlow_motion = true\ncontextual_tips = false\n",
8479 )
8480 .unwrap();
8481 let mut app = App::new(test_options(false), &Config::default());
8482 assert!(
8483 !app.pet_watch.enabled,
8484 "old settings keep their existing view"
8485 );
8486 app.pet_watch.detach_for_test();
8487 app.input = "unfinished draft".into();
8488 assert!(
8489 !crate::commands::execute_with_config("/pet on", &mut app, &Config::default()).is_error
8490 );
8491 assert!(app.pet_watch.enabled);
8492 assert!(app.view_stack.is_empty());
8493 assert_eq!(app.input, "unfinished draft");
8494 app.startup_defaults.flush();
8495 let restored = App::new(test_options(false), &Config::default());
8496 assert!(restored.pet_watch.enabled);
8497 assert!(
8498 !restored.launch.visible,
8499 "the welcome overlay must not hide the remembered view"
8500 );
8501 assert!(restored.low_motion);
8502 assert!(restored.view_stack.is_empty());
8503 let saved = std::fs::read_to_string(&path).unwrap();
8504 assert!(saved.contains("# keep this comment"));
8505 assert!(!Settings::load_persisted().unwrap().contextual_tips);
8506
8507 // Both public selectors enqueue in user-action order; quit immediately
8508 // after the last choice and prove the existing shutdown join persists it.
8509 for value in [false, true, false, true] {
8510 app.pet_watch.detach_for_test();
8511 let result = crate::commands::execute_with_config(
8512 &format!(
8513 "/config pet_mode {} --save",
8514 if value { "true" } else { "false" }
8515 ),
8516 &mut app,
8517 &Config::default(),
8518 );
8519 assert!(!result.is_error);
8520 }
8521 assert!(
8522 !crate::commands::execute_with_config("/pet off", &mut app, &Config::default()).is_error
8523 );
8524 assert!(app.startup_defaults.shutdown().is_empty());
8525 assert!(!Settings::load_persisted().unwrap().pet_mode);
8526 assert!(
8527 !App::new(test_options(false), &Config::default())
8528 .pet_watch
8529 .enabled
8530 );
8531
8532 // Session overrides and rejected values must not change the saved choice.
8533 app.pet_watch.detach_for_test();
8534 assert!(
8535 !crate::commands::execute_with_config(
8536 "/config pet_mode true",
8537 &mut app,
8538 &Config::default()
8539 )
8540 .is_error
8541 );
8542 assert!(
8543 crate::commands::execute_with_config(
8544 "/config pet_mode banana --save",
8545 &mut app,
8546 &Config::default()
8547 )
8548 .is_error
8549 );
8550 assert!(app.pet_watch.enabled);
8551 app.startup_defaults.flush();
8552 assert!(!Settings::load_persisted().unwrap().pet_mode);
8553 }
8554
8555 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
8556 async fn whale_name_and_colour_survive_a_restart_and_follow_another_writer() {
8557 let _lock = lock_test_env();
8558 let tmp = tempfile::TempDir::new().unwrap();
8559 let _env = sealed_settings_home(tmp.path());
8560 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
8561 let path = tmp.path().join(".codewhale/settings.toml");
8562 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8563 std::fs::write(&path, "# keep this comment\nlow_motion = true\n").unwrap();
8564 let mut app = App::new(test_options(false), &Config::default());
8565 assert_eq!(app.pet_watch.name(), None);
8566 app.pet_watch.detach_for_test();
8567 for command in ["/whale name Moby Dick", "/whale color harbor"] {
8568 let result = crate::commands::execute_with_config(command, &mut app, &Config::default());
8569 assert!(!result.is_error, "{command}: {:?}", result.message);
8570 }
8571 assert!(
8572 crate::commands::execute_with_config("/whale color blue", &mut app, &Config::default())
8573 .is_error
8574 );
8575 assert_eq!(app.pet_watch.name(), Some("Moby Dick"));
8576 app.startup_defaults.flush();
8577 let saved = std::fs::read_to_string(&path).unwrap();
8578 assert!(saved.contains("# keep this comment"), "{saved}");
8579 assert!(saved.contains("whale_name = \"Moby Dick\""), "{saved}");
8580 assert!(saved.contains("whale_color = \"harbor\""), "{saved}");
8581
8582 let mut restored = App::new(test_options(false), &Config::default());
8583 assert_eq!(restored.pet_watch.name(), Some("Moby Dick"));
8584 assert_eq!(restored.pet_watch.color(), Some([0x78, 0x96, 0xdf]));
8585 assert!(restored.low_motion);
8586
8587 Settings::transact(|settings| {
8588 settings.set("whale_name", "Ahab")?;
8589 settings.set("whale_color", "#0a141e")
8590 })
8591 .unwrap();
8592 restored.pet_watch.detach_for_test();
8593 restored.pet_watch.enabled = true;
8594 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
8595 let mut now = std::time::Instant::now() + std::time::Duration::from_secs(3);
8596 while restored.pet_watch.name() != Some("Ahab") && std::time::Instant::now() < deadline {
8597 crate::tui::pet_watch::tick(&mut restored, now);
8598 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
8599 now += std::time::Duration::from_secs(3);
8600 }
8601 assert_eq!(restored.pet_watch.name(), Some("Ahab"));
8602 assert_eq!(restored.pet_watch.color(), Some([10, 20, 30]));
8603 }
8604
8605 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8606 async fn pet_view_save_failure_keeps_the_live_view_and_reports_without_overwriting_bad_settings() {
8607 let _lock = lock_test_env();
8608 let tmp = tempfile::TempDir::new().unwrap();
8609 let _env = sealed_settings_home(tmp.path());
8610 let _writes = crate::tui::startup_defaults::allow_writes_in_tests();
8611 let path = tmp.path().join(".codewhale/settings.toml");
8612 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8613 let bad = "# preserve for repair\npet_mode = [broken";
8614 std::fs::write(&path, bad).unwrap();
8615 let mut app = App::new(test_options(false), &Config::default());
8616 app.pet_watch.detach_for_test();
8617 app.ui_locale = codewhale_localization::Locale::Fr;
8618 assert!(
8619 !crate::commands::execute_with_config("/pet on", &mut app, &Config::default()).is_error
8620 );
8621 assert!(app.pet_watch.enabled);
8622 app.startup_defaults.flush();
8623 let failures = app.startup_defaults.drain_failures();
8624 assert_eq!(failures.len(), 1);
8625 assert_eq!(
8626 failures[0].subjects,
8627 vec![crate::tui::startup_defaults::StartupDefaultSubject::PetMode]
8628 );
8629 let message = app.startup_default_failure_message(&failures[0]);
8630 assert!(message.contains(app.tr(MessageId::ConfigLabelPetMode).as_ref()));
8631 assert!(!message.contains(tmp.path().to_str().unwrap()));
8632 assert_eq!(std::fs::read_to_string(&path).unwrap(), bad);
8633 assert!(
8634 app.pet_watch.enabled,
8635 "a failed save does not undo the live view"
8636 );
8637 }
8638
8639 #[test]
8640 fn a_session_start_notice_names_active_agent_approved_plugins() {
8641 use codewhale_plugins::host_services::{
8642 AgentApproval, AgentPosture, PersonVia, PluginApprover, ReviewApproval,
8643 };
8644
8645 let _lock = lock_test_env();
8646 let tmp = tempfile::TempDir::new().expect("tempdir");
8647 let home = tmp.path().join("home");
8648 let workspace = tmp.path().join("project");
8649 let other_project = tmp.path().join("otherproject");
8650 for dir in [&home, &workspace, &other_project] {
8651 std::fs::create_dir_all(dir).expect("dir");
8652 }
8653 let _env = sealed_settings_home(&home);
8654
8655 let ctx = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv();
8656 for (dir_root, name) in [
8657 (workspace.join(".codewhale/plugins"), "agent-one"),
8658 (workspace.join(".codewhale/plugins"), "agent-two"),
8659 (workspace.join(".codewhale/plugins"), "agent-off"),
8660 (workspace.join(".codewhale/plugins"), "person-ok"),
8661 (ctx.user_plugins_dir().to_path_buf(), "agent-other"),
8662 ] {
8663 let skill = dir_root.join(name).join("skills/hello");
8664 std::fs::create_dir_all(&skill).expect("skill dir");
8665 std::fs::write(
8666 dir_root.join(name).join("plugin.toml"),
8667 format!(
8668 "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n"
8669 ),
8670 )
8671 .expect("manifest");
8672 std::fs::write(
8673 skill.join("SKILL.md"),
8674 "---\nname: hello\ndescription: hi\n---\nbody\n",
8675 )
8676 .expect("skill");
8677 }
8678 #[cfg(unix)]
8679 std::fs::set_permissions(
8680 ctx.user_plugins_dir(),
8681 std::os::unix::fs::PermissionsExt::from_mode(0o700),
8682 )
8683 .expect("private user plugin dir");
8684
8685 {
8686 let mut other_registry = ctx.registry_for_workspace(&other_project);
8687 let other_ws_str = other_registry.workspace().to_string_lossy().into_owned();
8688 let agent_elsewhere = PluginApprover::Agent(AgentApproval {
8689 posture: AgentPosture::AutoReview,
8690 workspace: other_ws_str,
8691 thread_id: Some("th-other-1".to_string()),
8692 turn_id: Some("turn-other-1".to_string()),
8693 tool_call_id: Some("call-other-1".to_string()),
8694 });
8695 let other_hs = other_registry
8696 .host_service_review_for("agent-other", &agent_elsewhere)
8697 .map(|review| review.token);
8698 std::sync::Arc::make_mut(&mut other_registry)
8699 .trust_and_enable_by(
8700 "agent-other",
8701 ReviewApproval {
8702 approved_by: agent_elsewhere.clone(),
8703 host_services: other_hs,
8704 },
8705 agent_elsewhere,
8706 )
8707 .expect("agent-other");
8708 }
8709
8710 let mut clean_registry = ctx.registry_for_workspace(&workspace);
8711 let ws_str = clean_registry.workspace().to_string_lossy().into_owned();
8712 assert!(!clean_registry.get("agent-other").unwrap().active());
8713 assert!(clean_registry.get("agent-other").unwrap().outside_reach);
8714 {
8715 let agent_off = PluginApprover::Agent(AgentApproval {
8716 posture: AgentPosture::FullAccess,
8717 workspace: ws_str.clone(),
8718 thread_id: Some("th-off-1".to_string()),
8719 turn_id: Some("turn-off-1".to_string()),
8720 tool_call_id: Some("call-off-1".to_string()),
8721 });
8722 let off_hs = clean_registry
8723 .host_service_review_for("agent-off", &agent_off)
8724 .map(|review| review.token);
8725 let reg = std::sync::Arc::make_mut(&mut clean_registry);
8726 let person = PluginApprover::person(PersonVia::Terminal);
8727 reg.trust_and_enable_by(
8728 "person-ok",
8729 ReviewApproval {
8730 approved_by: person.clone(),
8731 host_services: None,
8732 },
8733 person,
8734 )
8735 .expect("person-ok");
8736 reg.trust_reviewed(
8737 "agent-off",
8738 ReviewApproval {
8739 approved_by: agent_off,
8740 host_services: off_hs,
8741 },
8742 )
8743 .expect("agent-off");
8744 }
8745
8746 let clean_app = App::new_with_plugin_registry(
8747 crate::tui::test_support::test_tui_options(&workspace),
8748 &Config::default(),
8749 clean_registry.clone(),
8750 );
8751 assert!(clean_app.launch.visible);
8752 assert!(clean_app.history.is_empty());
8753 assert!(
8754 !clean_app.status_toasts.iter().any(|toast| toast
8755 .text
8756 .contains("Agent-approved plugins active in this project")),
8757 "{:?}",
8758 clean_app.status_toasts
8759 );
8760
8761 let mut registry = clean_registry;
8762 {
8763 let agent_full = PluginApprover::Agent(AgentApproval {
8764 posture: AgentPosture::FullAccess,
8765 workspace: ws_str.clone(),
8766 thread_id: Some("th-1".to_string()),
8767 turn_id: Some("turn-1".to_string()),
8768 tool_call_id: Some("call-1".to_string()),
8769 });
8770 let full_hs = registry
8771 .host_service_review_for("agent-one", &agent_full)
8772 .map(|review| review.token);
8773 let agent_auto = PluginApprover::Agent(AgentApproval {
8774 posture: AgentPosture::AutoReview,
8775 workspace: ws_str,
8776 thread_id: Some("th-2".to_string()),
8777 turn_id: Some("turn-2".to_string()),
8778 tool_call_id: Some("call-2".to_string()),
8779 });
8780 let auto_hs = registry
8781 .host_service_review_for("agent-two", &agent_auto)
8782 .map(|review| review.token);
8783 let reg = std::sync::Arc::make_mut(&mut registry);
8784 reg.trust_and_enable_by(
8785 "agent-one",
8786 ReviewApproval {
8787 approved_by: agent_full.clone(),
8788 host_services: full_hs,
8789 },
8790 agent_full,
8791 )
8792 .expect("agent-one");
8793 reg.trust_and_enable_by(
8794 "agent-two",
8795 ReviewApproval {
8796 approved_by: agent_auto.clone(),
8797 host_services: auto_hs,
8798 },
8799 agent_auto,
8800 )
8801 .expect("agent-two");
8802 }
8803
8804 let mut app = App::new_with_plugin_registry(
8805 crate::tui::test_support::test_tui_options(&workspace),
8806 &Config::default(),
8807 registry,
8808 );
8809 assert!(app.launch.visible);
8810 assert!(app.history.is_empty());
8811 fn notices(app: &App) -> Vec<&StatusToast> {
8812 app.status_toasts
8813 .iter()
8814 .filter(|toast| {
8815 toast
8816 .text
8817 .contains("Agent-approved plugins active in this project")
8818 })
8819 .collect()
8820 }
8821 let initial = notices(&app);
8822 assert_eq!(initial.len(), 1, "{initial:?}");
8823 let text = initial[0].text.clone();
8824 assert_eq!(initial[0].level, StatusToastLevel::Warning);
8825 assert!(initial[0].ttl_ms.is_none());
8826 assert!(text.contains("agent-one"), "{text}");
8827 assert!(text.contains("agent-two"), "{text}");
8828 assert!(!text.contains("agent-off"), "{text}");
8829 assert!(!text.contains("agent-other"), "{text}");
8830 assert!(!text.contains("person-ok"), "{text}");
8831
8832 app.refresh_agent_approved_plugins_notice();
8833 assert_eq!(notices(&app).len(), 1);
8834
8835 std::sync::Arc::make_mut(&mut app.plugin_registry)
8836 .trust("agent-one")
8837 .expect("person trust agent-one");
8838 app.refresh_agent_approved_plugins_notice();
8839 let after_one = notices(&app);
8840 assert_eq!(after_one.len(), 1);
8841 assert!(!after_one[0].text.contains("agent-one"), "{after_one:?}");
8842 assert!(after_one[0].text.contains("agent-two"), "{after_one:?}");
8843
8844 std::sync::Arc::make_mut(&mut app.plugin_registry)
8845 .trust("agent-two")
8846 .expect("person trust agent-two");
8847 app.refresh_agent_approved_plugins_notice();
8848 assert!(notices(&app).is_empty(), "{:?}", notices(&app));
8849 }
8850
8850 lines RUST