| 1 | use crate::commands::CommandResult; |
| 2 | use crate::tui::app::{App, AppAction, TuiOptions}; |
| 3 | use crate::tui::views::ModalKind; |
| 4 | use codewhale_config::AppMode; |
| 5 | use codewhale_localization::Locale; |
| 6 | use codewhale_runtime::config::Config; |
| 7 | use std::path::PathBuf; |
| 8 | use tempfile::tempdir; |
| 9 | |
| 10 | fn help(app: &mut App, topic: Option<&str>) -> CommandResult { |
| 11 | let input = topic |
| 12 | .map(|topic| format!("/help {topic}")) |
| 13 | .unwrap_or_else(|| "/help".into()); |
| 14 | crate::commands::execute(&input, app) |
| 15 | } |
| 16 | |
| 17 | fn codewhale_links(app: &mut App) -> CommandResult { |
| 18 | crate::commands::execute("/links", app) |
| 19 | } |
| 20 | |
| 21 | fn home_dashboard(app: &mut App) -> CommandResult { |
| 22 | crate::commands::execute("/overview", app) |
| 23 | } |
| 24 | |
| 25 | fn create_test_app() -> App { |
| 26 | let options = TuiOptions { |
| 27 | skills_dir: PathBuf::from("/tmp/test-skills"), |
| 28 | ..crate::tui::test_support::test_tui_options(PathBuf::from("/tmp/test-workspace")) |
| 29 | }; |
| 30 | let mut app = App::new(options, &Config::default()); |
| 31 | app.ui_locale = codewhale_localization::Locale::En; |
| 32 | app.api_provider = codewhale_config::ProviderKind::Deepseek; |
| 33 | app.model = "deepseek-v4-pro".to_string(); |
| 34 | app.auto_model = false; |
| 35 | app.model_ids_passthrough = false; |
| 36 | app |
| 37 | } |
| 38 | |
| 39 | #[test] |
| 40 | fn help_topic_resolves_a_discovered_skill_and_both_shapes() { |
| 41 | // #3912: `/help <skill>` said "Unknown command" for a skill that |
| 42 | // executes and autocompletes. |
| 43 | let mut app = create_test_app(); |
| 44 | app.cached_skills = vec![( |
| 45 | "codereview".to_string(), |
| 46 | "Review a diff for defects".to_string(), |
| 47 | )]; |
| 48 | |
| 49 | for topic in [ |
| 50 | "codereview", |
| 51 | "CodeReview", |
| 52 | "$codereview", |
| 53 | "/skill codereview", |
| 54 | ] { |
| 55 | let result = help(&mut app, Some(topic)); |
| 56 | let message = result |
| 57 | .message |
| 58 | .as_deref() |
| 59 | .unwrap_or_else(|| panic!("{topic} should resolve to skill help")); |
| 60 | assert!(message.contains("Review a diff for defects"), "{message}"); |
| 61 | assert!(message.contains("$codereview"), "{message}"); |
| 62 | assert!(message.contains("/skill codereview"), "{message}"); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | #[test] |
| 67 | fn help_topic_still_errors_for_an_unknown_name() { |
| 68 | let mut app = create_test_app(); |
| 69 | app.cached_skills = vec![("codereview".to_string(), "Review a diff".to_string())]; |
| 70 | let result = help(&mut app, Some("definitely-not-a-thing")); |
| 71 | assert!(result.is_error, "unknown topics must still be an error"); |
| 72 | assert!( |
| 73 | !result |
| 74 | .message |
| 75 | .as_deref() |
| 76 | .unwrap_or_default() |
| 77 | .contains("Review a diff"), |
| 78 | "the skill fallback must not match an unrelated topic" |
| 79 | ); |
| 80 | } |
| 81 | |
| 82 | #[test] |
| 83 | fn test_help_unknown_command() { |
| 84 | let mut app = create_test_app(); |
| 85 | let result = help(&mut app, Some("nonexistent")); |
| 86 | assert!(result.message.is_some()); |
| 87 | assert!(result.message.unwrap().contains("Unknown command")); |
| 88 | assert!(result.action.is_none()); |
| 89 | } |
| 90 | |
| 91 | #[test] |
| 92 | fn test_help_known_command() { |
| 93 | let mut app = create_test_app(); |
| 94 | let result = help(&mut app, Some("clear")); |
| 95 | assert!(result.message.is_some()); |
| 96 | let msg = result.message.unwrap(); |
| 97 | assert!(msg.contains("clear")); |
| 98 | assert!(msg.contains("Clear conversation history")); |
| 99 | assert!(msg.contains("Usage: /clear")); |
| 100 | } |
| 101 | |
| 102 | #[test] |
| 103 | fn test_help_config_topic_uses_interactive_editor_text() { |
| 104 | let mut app = create_test_app(); |
| 105 | let result = help(&mut app, Some("config")); |
| 106 | let msg = result.message.expect("help topic should return message"); |
| 107 | assert!(msg.contains("config")); |
| 108 | assert!(msg.contains("Inspect and change settings")); |
| 109 | assert!(msg.contains("Usage: /config")); |
| 110 | assert!(msg.contains("context_window = 262144")); |
| 111 | assert!(msg.contains("/config context_window")); |
| 112 | assert!(msg.contains("/config search.provider")); |
| 113 | assert!(msg.contains("/config prompt_suggestion")); |
| 114 | assert!(msg.contains("/config notifications")); |
| 115 | } |
| 116 | |
| 117 | #[test] |
| 118 | fn test_help_links_topic_shows_aliases() { |
| 119 | let mut app = create_test_app(); |
| 120 | let result = help(&mut app, Some("links")); |
| 121 | let msg = result.message.expect("help topic should return message"); |
| 122 | assert!(msg.contains("links")); |
| 123 | assert!(msg.contains("Show Codewhale, community, and provider links")); |
| 124 | assert!(msg.contains("Usage: /links")); |
| 125 | assert!(msg.contains("Aliases: api, lianjie")); |
| 126 | |
| 127 | let root = tempdir().unwrap(); |
| 128 | crate::test_support::trust_workspace(root.path()); |
| 129 | let directory = root.path().join(".codewhale/commands"); |
| 130 | std::fs::create_dir_all(&directory).unwrap(); |
| 131 | std::fs::write(directory.join("custom-links.md"), "---\ndescription: User link helper\nusage: /custom-links <target>\naliases: api\n---\nuser link $ARGUMENTS").unwrap(); |
| 132 | let mut app = crate::tui::test_support::test_app_with_options( |
| 133 | crate::tui::test_support::test_tui_options(root.path()), |
| 134 | ); |
| 135 | app.ui_locale = Locale::En; |
| 136 | app.cached_skills = vec![ |
| 137 | ("custom-links".into(), "Wrong skill fallback".into()), |
| 138 | ("links".into(), "Wrong builtin fallback".into()), |
| 139 | ]; |
| 140 | crate::commands::user_registry::reload(Some(root.path())); |
| 141 | for topic in ["custom-links", "api"] { |
| 142 | let result = help(&mut app, Some(topic)); |
| 143 | assert!(!result.is_error); |
| 144 | let text = result.message.unwrap(); |
| 145 | assert!(text.starts_with("custom-links\n\n")); |
| 146 | assert!(text.contains("User link helper")); |
| 147 | assert!(text.contains("Usage: /custom-links <target>")); |
| 148 | assert!(text.contains("Aliases: api"), "{text}"); |
| 149 | assert!(!text.contains("Wrong skill fallback")); |
| 150 | } |
| 151 | let text = help(&mut app, Some("links")).message.unwrap(); |
| 152 | assert!(text.starts_with("links\n\n")); |
| 153 | assert!(text.contains("Aliases: lianjie")); |
| 154 | assert!(!text.contains("Aliases: api")); |
| 155 | assert!(!text.contains("Wrong builtin fallback")); |
| 156 | } |
| 157 | |
| 158 | #[test] |
| 159 | fn dashboard_and_board_dispatch_open_agent_board() { |
| 160 | let mut app = create_test_app(); |
| 161 | for cmd in ["/dashboard", "/board"] { |
| 162 | let result = crate::commands::execute(cmd, &mut app); |
| 163 | assert!(!result.is_error, "{cmd}: {result:?}"); |
| 164 | assert!(matches!(result.action, Some(AppAction::OpenAgentBoard))); |
| 165 | } |
| 166 | let help_msg = help(&mut app, Some("dashboard")) |
| 167 | .message |
| 168 | .expect("dashboard help message"); |
| 169 | assert!(help_msg.contains("Usage: /dashboard"), "{help_msg}"); |
| 170 | assert!(help_msg.contains("Aliases: board"), "{help_msg}"); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn test_help_memory_topic_shows_usage_and_description() { |
| 175 | let mut app = create_test_app(); |
| 176 | let result = help(&mut app, Some("memory")); |
| 177 | let msg = result.message.expect("help topic should return message"); |
| 178 | assert!(msg.contains("memory")); |
| 179 | assert!(msg.contains("persistent structured user memory")); |
| 180 | assert!(msg.contains( |
| 181 | "Usage: /memory [status|path|search|get|remember|import|export|reindex|clear|help]" |
| 182 | )); |
| 183 | } |
| 184 | |
| 185 | #[test] |
| 186 | fn test_help_pushes_overlay() { |
| 187 | let mut app = create_test_app(); |
| 188 | assert_ne!(app.view_stack.top_kind(), Some(ModalKind::Help)); |
| 189 | let result = help(&mut app, None); |
| 190 | assert_eq!(result.message, None); |
| 191 | assert_eq!(result.action, None); |
| 192 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::Help)); |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn test_help_does_not_duplicate_overlay() { |
| 197 | let mut app = create_test_app(); |
| 198 | assert!(app.view_stack.is_empty()); |
| 199 | help(&mut app, None); |
| 200 | let initial_kind = app.view_stack.top_kind(); |
| 201 | help(&mut app, None); |
| 202 | assert_eq!(app.view_stack.top_kind(), initial_kind); |
| 203 | assert!(app.view_stack.pop().is_some()); |
| 204 | assert!( |
| 205 | app.view_stack.is_empty(), |
| 206 | "one dismissal must remove the only help modal" |
| 207 | ); |
| 208 | } |
| 209 | |
| 210 | #[test] |
| 211 | fn test_codewhale_links() { |
| 212 | let mut app = create_test_app(); |
| 213 | let result = codewhale_links(&mut app); |
| 214 | assert!(result.message.is_some()); |
| 215 | let msg = result.message.unwrap(); |
| 216 | assert!(msg.contains("Codewhale & community")); |
| 217 | assert!(msg.contains("https://codewhale.net/en/docs")); |
| 218 | assert!(msg.contains("https://codewhale.net/en/community")); |
| 219 | assert!(msg.contains("https://github.com/codewhale-hq/CodeWhale")); |
| 220 | assert!(msg.contains("https://app.codewhale.net")); |
| 221 | assert!(msg.contains("separate sign-in")); |
| 222 | assert!(msg.contains("not connected to the current local session")); |
| 223 | assert!(msg.contains("Provider Links")); |
| 224 | assert!(msg.contains("DeepSeek (deepseek) <- current")); |
| 225 | assert!(msg.contains("https://platform.deepseek.com/api_keys")); |
| 226 | assert!(msg.contains("Xiaomi MiMo (xiaomi-mimo)")); |
| 227 | assert!(msg.contains("https://platform.xiaomimimo.com/token-plan")); |
| 228 | assert!(msg.contains("Moonshot/Kimi (moonshot)")); |
| 229 | assert!(msg.contains("https://platform.kimi.ai/console/api-keys")); |
| 230 | assert!(msg.contains("https://platform.kimi.ai/docs/overview")); |
| 231 | assert!(msg.contains("https://api.kimi.com/coding/v1")); |
| 232 | assert!(msg.contains("https://www.kimi.com/code/console")); |
| 233 | assert!(msg.contains("never imports Kimi CLI credentials")); |
| 234 | assert!(msg.contains("https://console.openmodel.ai/")); |
| 235 | assert!(msg.contains("https://docs.openmodel.ai/en/docs/getting-started/authentication")); |
| 236 | assert!(msg.contains("https://console.sakana.ai/api-keys")); |
| 237 | assert!(msg.contains("https://console.sakana.ai/get-started")); |
| 238 | assert!(msg.contains("Baidu Qianfan (qianfan)")); |
| 239 | assert!(msg.contains("https://cloud.baidu.com/doc/qianfan/index.html")); |
| 240 | assert!(msg.contains("Local Ollama is keyless by default")); |
| 241 | assert!(msg.contains("codewhale auth chatgpt")); |
| 242 | assert!( |
| 243 | !msg.contains("codex login"), |
| 244 | "official sign-in must not direct users to external CLI credentials" |
| 245 | ); |
| 246 | assert!(msg.contains("no canonical vendor credential page exists")); |
| 247 | assert!(msg.contains("OPENAI_API_KEY")); |
| 248 | assert!(msg.contains("XIAOMI_MIMO_TOKEN_PLAN_API_KEY")); |
| 249 | assert!(!msg.contains("https://codewhale.dev/docs/providers")); |
| 250 | assert!(result.action.is_none()); |
| 251 | } |
| 252 | |
| 253 | #[test] |
| 254 | fn provider_links_emit_urls_as_inline_code_for_narrow_transcripts() { |
| 255 | let mut app = create_test_app(); |
| 256 | let result = codewhale_links(&mut app); |
| 257 | let msg = result.message.expect("links should return a message"); |
| 258 | |
| 259 | assert!(msg.contains("`https://platform.openai.com/api-keys`")); |
| 260 | assert!( |
| 261 | msg.contains("`https://platform.minimax.io/user-center/basic-information/interface-key`") |
| 262 | ); |
| 263 | |
| 264 | for line in msg.lines().filter(|line| line.contains("http")) { |
| 265 | let Some(url_start) = line.find("http") else { |
| 266 | continue; |
| 267 | }; |
| 268 | assert!( |
| 269 | line[..url_start].ends_with('`') && line[url_start..].contains('`'), |
| 270 | "provider URL should be inline-code wrapped so narrow TUI renders do not emit oversized OSC8 link payloads: {line}" |
| 271 | ); |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn project_links_follow_the_available_public_site_locale() { |
| 277 | let mut app = create_test_app(); |
| 278 | app.ui_locale = Locale::ZhHans; |
| 279 | |
| 280 | let msg = codewhale_links(&mut app) |
| 281 | .message |
| 282 | .expect("links should return a message"); |
| 283 | |
| 284 | assert!(msg.contains("`https://codewhale.net/zh/docs`")); |
| 285 | assert!(msg.contains("`https://codewhale.net/zh/community`")); |
| 286 | assert!(msg.contains("`https://app.codewhale.net`")); |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn test_home_dashboard_includes_all_sections() { |
| 291 | let mut app = create_test_app(); |
| 292 | app.session.total_conversation_tokens = 1234; |
| 293 | let result = home_dashboard(&mut app); |
| 294 | assert!(result.message.is_some()); |
| 295 | let msg = result.message.unwrap(); |
| 296 | assert!(msg.contains("codewhale")); |
| 297 | assert!(!msg.contains("codewhale Home Dashboard")); |
| 298 | assert!(msg.contains("Model:")); |
| 299 | assert!(msg.contains("Mode:")); |
| 300 | assert!(msg.contains("Workspace:")); |
| 301 | assert!(msg.contains("History:")); |
| 302 | assert!(msg.contains("Tokens:")); |
| 303 | assert!(msg.contains("Quick Actions")); |
| 304 | assert!(msg.contains("Mode Tips")); |
| 305 | assert!(result.action.is_none()); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn test_home_dashboard_shows_queued_when_present() { |
| 310 | let mut app = create_test_app(); |
| 311 | app.queued_messages |
| 312 | .push_back(crate::tui::app::QueuedMessage::new( |
| 313 | "test".to_string(), |
| 314 | None, |
| 315 | )); |
| 316 | let result = home_dashboard(&mut app); |
| 317 | let msg = result.message.unwrap(); |
| 318 | assert!(msg.contains("Queued:")); |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn test_home_dashboard_mode_tips_for_each_mode() { |
| 323 | let modes = [AppMode::Agent, AppMode::Plan]; |
| 324 | for mode in modes { |
| 325 | let mut app = create_test_app(); |
| 326 | app.mode = mode; |
| 327 | let result = home_dashboard(&mut app); |
| 328 | let msg = result.message.unwrap(); |
| 329 | assert!(msg.contains("Mode Tips"), "Missing tips for mode {mode:?}"); |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn test_home_dashboard_quick_actions_reflect_links_and_config_and_hide_removed_commands() { |
| 335 | let mut app = create_test_app(); |
| 336 | let result = home_dashboard(&mut app); |
| 337 | let msg = result |
| 338 | .message |
| 339 | .expect("home dashboard should return message"); |
| 340 | assert!(msg.contains("/workspace - Switch folders or worktrees")); |
| 341 | assert!(msg.contains("/restore - Roll files back to a turn snapshot")); |
| 342 | assert!(msg.contains("/tokens - Show session spend and context")); |
| 343 | assert!(msg.contains("/links - Codewhale, community & provider links")); |
| 344 | assert!(msg.contains("/config - Inspect and change settings")); |
| 345 | assert!( |
| 346 | !msg.lines() |
| 347 | .any(|line| line.trim_start().starts_with("/set ")) |
| 348 | ); |
| 349 | assert!(!msg.contains("/codewhale")); |
| 350 | } |
| 351 | |
| 352 | #[test] |
| 353 | fn home_dashboard_localizes_in_zh_hans() { |
| 354 | use codewhale_localization::Locale; |
| 355 | let mut app = create_test_app(); |
| 356 | app.ui_locale = Locale::ZhHans; |
| 357 | let result = home_dashboard(&mut app); |
| 358 | let msg = result |
| 359 | .message |
| 360 | .expect("home dashboard should return message"); |
| 361 | assert!( |
| 362 | msg.contains("codewhale"), |
| 363 | "missing canonical product title:\n{msg}" |
| 364 | ); |
| 365 | assert!(msg.contains("模型"), "missing zh-Hans model label:\n{msg}"); |
| 366 | assert!( |
| 367 | msg.contains("快捷操作"), |
| 368 | "missing zh-Hans quick actions:\n{msg}" |
| 369 | ); |
| 370 | assert!( |
| 371 | msg.contains("模式提示"), |
| 372 | "missing zh-Hans mode tips:\n{msg}" |
| 373 | ); |
| 374 | } |
| 375 | |
| 376 | #[cfg(test)] |
| 377 | mod home { |
| 378 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; |
| 379 | |
| 380 | #[test] |
| 381 | fn revisited_home_sends_queued_work_unless_a_painted_row_owns_enter() { |
| 382 | use crate::tui::app::QueuedMessage; |
| 383 | use crate::tui::underwater::{LaunchComposerKey, handle_launch_composer_key}; |
| 384 | let mut app = crate::tui::test_support::test_app_with_options( |
| 385 | crate::tui::test_support::test_tui_options("."), |
| 386 | ); |
| 387 | app.launch.dismiss(); |
| 388 | app.offline_mode = false; |
| 389 | app.queue_message(QueuedMessage::new("queued question".into(), None)); |
| 390 | let result = crate::commands::execute("/home", &mut app); |
| 391 | assert!(!result.is_error); |
| 392 | assert!(app.launch.return_to_session); |
| 393 | crate::tui::underwater::refresh_launch_row_hitboxes( |
| 394 | &mut app, |
| 395 | ratatui::layout::Rect::new(0, 0, 80, 20), |
| 396 | ); |
| 397 | assert!(!app.launch.row_hitboxes.is_empty()); |
| 398 | for (selected, expected) in [ |
| 399 | (Some(0), LaunchComposerKey::MenuRun), |
| 400 | (None, LaunchComposerKey::Submit), |
| 401 | ( |
| 402 | Some(app.launch.row_hitboxes.len()), |
| 403 | LaunchComposerKey::Submit, |
| 404 | ), |
| 405 | ] { |
| 406 | app.launch.menu_selected = selected; |
| 407 | assert_eq!( |
| 408 | handle_launch_composer_key( |
| 409 | &mut app, |
| 410 | KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE) |
| 411 | ), |
| 412 | expected |
| 413 | ); |
| 414 | assert_eq!(app.queued_message_count(), 1); |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | #[test] |
| 419 | fn home_preserves_session_draft_and_reveal_and_escape_returns() { |
| 420 | let mut app = crate::tui::test_support::test_app_with_options( |
| 421 | crate::tui::test_support::test_tui_options("."), |
| 422 | ); |
| 423 | app.launch.dismiss(); |
| 424 | app.current_session_id = Some("retained-session".into()); |
| 425 | app.api_messages_mut().push(codewhale_models::Message { |
| 426 | role: codewhale_models::Role::User, |
| 427 | content: vec![codewhale_models::ContentBlock::Text { |
| 428 | text: "Retain this conversation".into(), |
| 429 | cache_control: None, |
| 430 | }], |
| 431 | }); |
| 432 | app.add_message(crate::tui::history::HistoryCell::System { |
| 433 | content: "Retain this transcript".into(), |
| 434 | }); |
| 435 | app.input = "unsent draft".into(); |
| 436 | app.cursor_position = app.input.chars().count(); |
| 437 | app.launch.mark_reveal_started_at = Some(std::time::Instant::now()); |
| 438 | let reveal = app.launch.mark_reveal_started_at; |
| 439 | let messages = app.api_messages.clone(); |
| 440 | let history_len = app.history.len(); |
| 441 | let result = crate::commands::execute("/home", &mut app); |
| 442 | assert!(!result.is_error, "{:?}", result.message); |
| 443 | assert!( |
| 444 | result.action.is_none(), |
| 445 | "navigation must not sync/reset the Engine" |
| 446 | ); |
| 447 | assert!(crate::tui::widgets::should_render_empty_state(&app)); |
| 448 | assert!(app.launch.return_to_session); |
| 449 | assert!(!crate::tui::underwater::launch_motion_active( |
| 450 | &app, false, true |
| 451 | )); |
| 452 | crate::tui::underwater::refresh_launch_row_hitboxes( |
| 453 | &mut app, |
| 454 | ratatui::layout::Rect::new(0, 0, 80, 20), |
| 455 | ); |
| 456 | let rows = crate::tui::underwater::launch_rows_for_app(&app); |
| 457 | assert_eq!( |
| 458 | crate::tui::underwater::launch_row_click_action(&rows[0].id), |
| 459 | crate::tui::underwater::LaunchAction::ReturnToSession, |
| 460 | ); |
| 461 | app.launch.menu_selected = Some(0); |
| 462 | assert_eq!( |
| 463 | crate::tui::underwater::handle_launch_composer_key( |
| 464 | &mut app, |
| 465 | KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), |
| 466 | ), |
| 467 | crate::tui::underwater::LaunchComposerKey::MenuRun, |
| 468 | ); |
| 469 | assert_eq!(app.input, "unsent draft"); |
| 470 | crate::tui::underwater::handle_launch_composer_key( |
| 471 | &mut app, |
| 472 | KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), |
| 473 | ); |
| 474 | assert!(!app.launch.visible); |
| 475 | assert!(!app.launch.return_to_session); |
| 476 | assert_eq!(app.current_session_id.as_deref(), Some("retained-session")); |
| 477 | assert_eq!(app.api_messages, messages); |
| 478 | assert_eq!(app.history.len(), history_len); |
| 479 | assert_eq!(app.input, "unsent draft"); |
| 480 | assert_eq!(app.launch.mark_reveal_started_at, reveal); |
| 481 | assert!(!crate::tui::widgets::should_render_empty_state(&app)); |
| 482 | |
| 483 | for command in ["/overview", "/stats"] { |
| 484 | let result = crate::commands::execute(command, &mut app); |
| 485 | assert!(!result.is_error); |
| 486 | assert!(result.message.unwrap().contains("Quick Actions")); |
| 487 | assert!(!app.launch.visible); |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | #[test] |
| 492 | fn home_refuses_to_cover_active_work() { |
| 493 | let mut app = crate::tui::test_support::test_app_with_options( |
| 494 | crate::tui::test_support::test_tui_options("."), |
| 495 | ); |
| 496 | app.launch.dismiss(); |
| 497 | app.is_loading = true; |
| 498 | let result = crate::commands::execute("/home", &mut app); |
| 499 | assert!(result.is_error); |
| 500 | assert!(!app.launch.visible); |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | fn workspace_switch(app: &mut App, arg: Option<&str>) -> CommandResult { |
| 505 | let input = arg |
| 506 | .map(|arg| format!("/workspace {arg}")) |
| 507 | .unwrap_or_else(|| "/workspace".into()); |
| 508 | crate::commands::execute(&input, app) |
| 509 | } |
| 510 | |
| 511 | #[test] |
| 512 | fn worktree_and_workspace_worktrees_open_the_same_manager() { |
| 513 | let mut app = create_test_app(); |
| 514 | for command in ["/worktree", "/workspace worktrees", "/cwd wt"] { |
| 515 | let result = crate::commands::execute(command, &mut app); |
| 516 | assert_eq!( |
| 517 | result.action, |
| 518 | Some(AppAction::OpenWorktreeManager), |
| 519 | "{command}" |
| 520 | ); |
| 521 | } |
| 522 | let invalid = crate::commands::execute("/worktree create", &mut app); |
| 523 | assert!(invalid.is_error && invalid.action.is_none()); |
| 524 | } |
| 525 | |
| 526 | #[test] |
| 527 | fn workspace_without_arg_shows_current_workspace() { |
| 528 | let mut app = create_test_app(); |
| 529 | let result = workspace_switch(&mut app, None); |
| 530 | let msg = result.message.expect("workspace should be shown"); |
| 531 | assert!(msg.contains("Current workspace:")); |
| 532 | assert!(msg.contains("/tmp/test-workspace")); |
| 533 | assert!(result.action.is_none()); |
| 534 | let home = codewhale_paths::user_home().expect("hermetic home"); |
| 535 | let result = workspace_switch(&mut app, Some("~")); |
| 536 | assert!( |
| 537 | matches!(result.action, Some(AppAction::SwitchWorkspace { workspace }) if workspace == home.canonicalize().unwrap_or(home.clone())) |
| 538 | ); |
| 539 | let child = tempfile::tempdir_in(&home).unwrap(); |
| 540 | let input = format!("~/{}", child.path().file_name().unwrap().to_str().unwrap()); |
| 541 | let result = workspace_switch(&mut app, Some(&input)); |
| 542 | assert!( |
| 543 | matches!(result.action, Some(AppAction::SwitchWorkspace { workspace }) if workspace == child.path().canonicalize().unwrap()) |
| 544 | ); |
| 545 | } |
| 546 | |
| 547 | #[test] |
| 548 | fn workspace_existing_absolute_dir_returns_switch_action() { |
| 549 | let mut app = create_test_app(); |
| 550 | let dir = tempdir().expect("temp dir"); |
| 551 | let result = workspace_switch(&mut app, Some(dir.path().to_str().unwrap())); |
| 552 | assert!(matches!( |
| 553 | result.action, |
| 554 | Some(AppAction::SwitchWorkspace { workspace }) if workspace == dir.path().canonicalize().unwrap() |
| 555 | )); |
| 556 | } |
| 557 | |
| 558 | #[test] |
| 559 | fn workspace_relative_dir_resolves_from_current_workspace() { |
| 560 | let root = tempdir().expect("temp dir"); |
| 561 | let child = root.path().join("child"); |
| 562 | std::fs::create_dir(&child).expect("child dir"); |
| 563 | let mut app = create_test_app(); |
| 564 | app.workspace = root.path().to_path_buf(); |
| 565 | |
| 566 | let result = workspace_switch(&mut app, Some("child")); |
| 567 | assert!(matches!( |
| 568 | result.action, |
| 569 | Some(AppAction::SwitchWorkspace { workspace }) if workspace == child.canonicalize().unwrap() |
| 570 | )); |
| 571 | } |
| 572 | |
| 573 | #[test] |
| 574 | fn workspace_rejects_missing_path() { |
| 575 | let mut app = create_test_app(); |
| 576 | let result = workspace_switch(&mut app, Some("definitely-missing")); |
| 577 | assert!(result.is_error); |
| 578 | assert!(result.message.unwrap().contains("does not exist")); |
| 579 | } |
| 580 | |
| 581 | #[test] |
| 582 | fn workspace_rejects_file_path() { |
| 583 | let root = tempdir().expect("temp dir"); |
| 584 | let file = root.path().join("file.txt"); |
| 585 | std::fs::write(&file, "not a directory").expect("test file"); |
| 586 | let mut app = create_test_app(); |
| 587 | |
| 588 | let result = workspace_switch(&mut app, Some(file.to_str().unwrap())); |
| 589 | assert!(result.is_error); |
| 590 | assert!(result.message.unwrap().contains("not a directory")); |
| 591 | } |
| 592 | |
| 593 | #[cfg(test)] |
| 594 | mod anchor { |
| 595 | use crate::commands::CommandResult; |
| 596 | use crate::tui::app::{App, TuiOptions}; |
| 597 | use codewhale_runtime::config::Config; |
| 598 | use tempfile::TempDir; |
| 599 | |
| 600 | fn anchor(app: &mut App, arg: Option<&str>) -> CommandResult { |
| 601 | let input = arg |
| 602 | .map(|arg| format!("/anchor {arg}")) |
| 603 | .unwrap_or_else(|| "/anchor".into()); |
| 604 | crate::commands::execute(&input, app) |
| 605 | } |
| 606 | |
| 607 | enum AnchorFault { |
| 608 | Read, |
| 609 | Open, |
| 610 | Write, |
| 611 | Replace, |
| 612 | } |
| 613 | |
| 614 | impl codewhale_command_contract::facets::CommandWorkspaceContext for AnchorFault { |
| 615 | fn workspace(&self) -> std::path::PathBuf { |
| 616 | unreachable!("unexpected workspace observation") |
| 617 | } |
| 618 | fn work_state_snapshot(&self) -> Result<Option<String>, String> { |
| 619 | unreachable!("unexpected work observation") |
| 620 | } |
| 621 | fn operation_digest(&mut self) -> Result<String, String> { |
| 622 | unreachable!("unexpected work observation") |
| 623 | } |
| 624 | fn effective_home_dir(&self) -> Option<std::path::PathBuf> { |
| 625 | unreachable!("unexpected home observation") |
| 626 | } |
| 627 | fn inspect_workspace_target( |
| 628 | &self, |
| 629 | _: &std::path::Path, |
| 630 | ) -> codewhale_command_contract::navigation::WorkspaceTarget { |
| 631 | unreachable!("unexpected path inspection") |
| 632 | } |
| 633 | fn read_anchor_document(&self) -> Result<Option<String>, String> { |
| 634 | match self { |
| 635 | Self::Read => Err("read denied".into()), |
| 636 | Self::Replace => Ok(Some("first\n---\nsecond".into())), |
| 637 | _ => unreachable!("append must not read the document"), |
| 638 | } |
| 639 | } |
| 640 | fn append_anchor_bytes( |
| 641 | &mut self, |
| 642 | parts: &[&[u8]], |
| 643 | ) -> Result<std::path::PathBuf, codewhale_command_contract::navigation::AnchorWriteError> |
| 644 | { |
| 645 | use codewhale_command_contract::navigation::AnchorWriteError; |
| 646 | let expected: &[&[u8]] = &[b"\n---\n", b"entry", b"\n"]; |
| 647 | assert_eq!(parts, expected); |
| 648 | match self { |
| 649 | Self::Open => Err(AnchorWriteError::Open("open denied".into())), |
| 650 | Self::Write => Err(AnchorWriteError::Write("partial write".into())), |
| 651 | _ => unreachable!("unexpected append"), |
| 652 | } |
| 653 | } |
| 654 | fn replace_anchor_document(&mut self, bytes: &[u8]) -> Result<(), String> { |
| 655 | assert!(matches!(self, Self::Replace)); |
| 656 | assert_eq!(bytes, b"second"); |
| 657 | Err("replace denied".into()) |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | fn fault_result(fault: &mut AnchorFault, arg: &str) -> CommandResult { |
| 662 | use codewhale_command_contract::handler::{CommandContexts, CommandHandler}; |
| 663 | let CommandHandler::Contextual { handler, .. } = crate::commands::registry() |
| 664 | .get("anchor") |
| 665 | .unwrap() |
| 666 | .contextual_handler() |
| 667 | .unwrap() |
| 668 | else { |
| 669 | panic!("anchor must be contextual"); |
| 670 | }; |
| 671 | handler(CommandContexts::empty().with_workspace(fault), Some(arg)) |
| 672 | } |
| 673 | |
| 674 | fn create_test_app_with_tmpdir(tmpdir: &TempDir) -> App { |
| 675 | let options = TuiOptions { |
| 676 | skills_dir: tmpdir.path().join("skills"), |
| 677 | memory_path: tmpdir.path().join("memory.md"), |
| 678 | mcp_config_path: tmpdir.path().join("mcp.json"), |
| 679 | ..crate::tui::test_support::test_tui_options(tmpdir.path()) |
| 680 | }; |
| 681 | App::new(options, &Config::default()) |
| 682 | } |
| 683 | |
| 684 | #[cfg(unix)] |
| 685 | #[test] |
| 686 | fn confined_anchors_refuse_linked_files_and_directories() { |
| 687 | use std::os::unix::fs::symlink; |
| 688 | |
| 689 | for directory in [".codewhale", ".deepseek"] { |
| 690 | for linked_directory in [false, true] { |
| 691 | let workspace = TempDir::new().unwrap(); |
| 692 | let outside = TempDir::new().unwrap(); |
| 693 | let mut app = create_test_app_with_tmpdir(&workspace); |
| 694 | let original = "first anchor\n---\nsecond anchor"; |
| 695 | let target = outside.path().join("anchors.md"); |
| 696 | std::fs::write(&target, original).unwrap(); |
| 697 | let parent = workspace.path().join(directory); |
| 698 | if linked_directory { |
| 699 | symlink(outside.path(), &parent).unwrap(); |
| 700 | } else { |
| 701 | std::fs::create_dir_all(&parent).unwrap(); |
| 702 | symlink(&target, parent.join("anchors.md")).unwrap(); |
| 703 | } |
| 704 | for command in ["list", "next anchor", "remove 1"] { |
| 705 | assert!(anchor(&mut app, Some(command)).is_error); |
| 706 | assert_eq!(std::fs::read_to_string(&target).unwrap(), original); |
| 707 | } |
| 708 | // Exercise the truncate path independently of the read refusal. |
| 709 | { |
| 710 | let mut bundle = app.command_contexts(); |
| 711 | let parts = bundle |
| 712 | .contexts( |
| 713 | codewhale_command_contract::handler::CommandCapabilities::WORKSPACE, |
| 714 | ) |
| 715 | .into_parts(); |
| 716 | assert!( |
| 717 | parts |
| 718 | .workspace |
| 719 | .unwrap() |
| 720 | .replace_anchor_document(&[]) |
| 721 | .is_err() |
| 722 | ); |
| 723 | } |
| 724 | assert_eq!(std::fs::read_to_string(&target).unwrap(), original); |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | #[cfg(unix)] |
| 730 | #[test] |
| 731 | fn confined_anchors_refuse_dangling_links() { |
| 732 | for directory in [".codewhale", ".deepseek"] { |
| 733 | let workspace = TempDir::new().unwrap(); |
| 734 | let outside = TempDir::new().unwrap(); |
| 735 | let mut app = create_test_app_with_tmpdir(&workspace); |
| 736 | let target = outside.path().join("missing.md"); |
| 737 | let parent = workspace.path().join(directory); |
| 738 | std::fs::create_dir_all(&parent).unwrap(); |
| 739 | std::os::unix::fs::symlink(&target, parent.join("anchors.md")).unwrap(); |
| 740 | assert!(anchor(&mut app, Some("list")).is_error); |
| 741 | assert!(anchor(&mut app, Some("next anchor")).is_error); |
| 742 | { |
| 743 | let mut bundle = app.command_contexts(); |
| 744 | let parts = bundle |
| 745 | .contexts(codewhale_command_contract::handler::CommandCapabilities::WORKSPACE) |
| 746 | .into_parts(); |
| 747 | assert!( |
| 748 | parts |
| 749 | .workspace |
| 750 | .unwrap() |
| 751 | .replace_anchor_document(&[]) |
| 752 | .is_err() |
| 753 | ); |
| 754 | } |
| 755 | assert!(!target.exists()); |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | #[test] |
| 760 | fn test_anchor_without_content_returns_error() { |
| 761 | let tmpdir = TempDir::new().unwrap(); |
| 762 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 763 | let result = anchor(&mut app, None); |
| 764 | assert!(result.is_error); |
| 765 | assert!(result.message.unwrap().contains("Usage:")); |
| 766 | } |
| 767 | |
| 768 | #[test] |
| 769 | fn test_anchor_with_empty_content_returns_error() { |
| 770 | let tmpdir = TempDir::new().unwrap(); |
| 771 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 772 | let result = anchor(&mut app, Some(" ")); |
| 773 | assert!(result.is_error); |
| 774 | assert!(result.message.unwrap().contains("Usage:")); |
| 775 | } |
| 776 | |
| 777 | #[test] |
| 778 | fn test_anchor_add() { |
| 779 | let tmpdir = TempDir::new().unwrap(); |
| 780 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 781 | let result = anchor(&mut app, Some("API status field is unreliable")); |
| 782 | assert!(!result.is_error); |
| 783 | assert!(result.message.unwrap().contains("Anchor pinned")); |
| 784 | |
| 785 | let path = tmpdir.path().join(".deepseek").join("anchors.md"); |
| 786 | assert!(path.exists()); |
| 787 | let content = std::fs::read_to_string(&path).unwrap(); |
| 788 | assert!(content.contains("API status field is unreliable")); |
| 789 | for (mut fault, expected) in [ |
| 790 | ( |
| 791 | AnchorFault::Open, |
| 792 | "Error: Failed to open anchors file: open denied", |
| 793 | ), |
| 794 | ( |
| 795 | AnchorFault::Write, |
| 796 | "Error: Failed to write anchor: partial write", |
| 797 | ), |
| 798 | ] { |
| 799 | let result = fault_result(&mut fault, "entry"); |
| 800 | assert!(result.is_error && result.action.is_none()); |
| 801 | assert_eq!(result.message.as_deref(), Some(expected)); |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | #[test] |
| 806 | fn test_anchor_list_empty() { |
| 807 | let tmpdir = TempDir::new().unwrap(); |
| 808 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 809 | let result = anchor(&mut app, Some("list")); |
| 810 | assert!(!result.is_error); |
| 811 | assert!(result.message.unwrap().contains("No anchors set")); |
| 812 | let result = fault_result(&mut AnchorFault::Read, "list"); |
| 813 | assert!(result.is_error && result.action.is_none()); |
| 814 | assert_eq!( |
| 815 | result.message.as_deref(), |
| 816 | Some("Error: Failed to read anchors file: read denied") |
| 817 | ); |
| 818 | } |
| 819 | |
| 820 | #[test] |
| 821 | fn test_anchor_list_with_items() { |
| 822 | let tmpdir = TempDir::new().unwrap(); |
| 823 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 824 | anchor(&mut app, Some("First anchor")); |
| 825 | anchor(&mut app, Some("Second anchor")); |
| 826 | |
| 827 | let result = anchor(&mut app, Some("list")); |
| 828 | let msg = result.message.unwrap(); |
| 829 | assert!(msg.contains("2 total")); |
| 830 | assert!(msg.contains("1. First anchor")); |
| 831 | assert!(msg.contains("2. Second anchor")); |
| 832 | } |
| 833 | |
| 834 | #[test] |
| 835 | fn test_anchor_remove() { |
| 836 | let tmpdir = TempDir::new().unwrap(); |
| 837 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 838 | anchor(&mut app, Some("First anchor")); |
| 839 | anchor(&mut app, Some("Second anchor")); |
| 840 | |
| 841 | let result = anchor(&mut app, Some("remove 1")); |
| 842 | assert!(!result.is_error); |
| 843 | assert!(result.message.unwrap().contains("Removed anchor #1")); |
| 844 | |
| 845 | let result = anchor(&mut app, Some("list")); |
| 846 | let msg = result.message.unwrap(); |
| 847 | assert!(msg.contains("1 total")); |
| 848 | assert!(msg.contains("Second anchor")); |
| 849 | assert!(!msg.contains("First anchor")); |
| 850 | let result = fault_result(&mut AnchorFault::Replace, "remove 1"); |
| 851 | assert!(result.is_error && result.action.is_none()); |
| 852 | assert_eq!( |
| 853 | result.message.as_deref(), |
| 854 | Some("Error: Failed to write anchors file: replace denied") |
| 855 | ); |
| 856 | } |
| 857 | |
| 858 | #[test] |
| 859 | fn test_anchor_remove_invalid_index() { |
| 860 | let tmpdir = TempDir::new().unwrap(); |
| 861 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 862 | anchor(&mut app, Some("Only anchor")); |
| 863 | |
| 864 | let result = anchor(&mut app, Some("remove 5")); |
| 865 | assert!(result.is_error); |
| 866 | assert!(result.message.unwrap().contains("does not exist")); |
| 867 | } |
| 868 | |
| 869 | #[test] |
| 870 | fn anchor_text_starting_with_a_removal_verb_is_pinned() { |
| 871 | let tmpdir = TempDir::new().unwrap(); |
| 872 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 873 | let result = anchor(&mut app, Some("delete the staging DB only after a backup")); |
| 874 | assert!(!result.is_error, "{:?}", result.message); |
| 875 | assert!(result.message.unwrap().contains("Anchor pinned")); |
| 876 | |
| 877 | let result = anchor(&mut app, Some("Remove\u{3000}1")); |
| 878 | assert!(!result.is_error, "{:?}", result.message); |
| 879 | assert!(result.message.unwrap().contains("Removed anchor #1")); |
| 880 | let result = anchor(&mut app, Some("rm\t1")); |
| 881 | assert!(result.is_error); |
| 882 | assert!(result.message.unwrap().contains("does not exist")); |
| 883 | } |
| 884 | |
| 885 | #[test] |
| 886 | fn test_anchor_remove_non_numeric() { |
| 887 | let tmpdir = TempDir::new().unwrap(); |
| 888 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 889 | let result = anchor(&mut app, Some("remove abc")); |
| 890 | assert!(result.is_error); |
| 891 | assert!(result.message.unwrap().contains("Invalid index")); |
| 892 | } |
| 893 | } |
| 894 |