| 1 | use super::*; |
| 2 | // `fs` was a cfg(test) import on the parent, and `Path` is now only used by |
| 3 | // the legacy/render seams. Both belong here. |
| 4 | use crate::tui::app::{App, TuiOptions}; |
| 5 | use codewhale_localization::{Locale, MessageId}; |
| 6 | use codewhale_runtime::config::Config; |
| 7 | use std::fs; |
| 8 | use std::path::Path; |
| 9 | use tempfile::TempDir; |
| 10 | |
| 11 | #[test] |
| 12 | fn extension_owner_report_escapes_every_plugin_controlled_field() { |
| 13 | struct Presentation(Locale); |
| 14 | impl CommandPresentationContext for Presentation { |
| 15 | fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> { |
| 16 | let id = crate::commands::contract::key_to_plugin_message_id(key).unwrap(); |
| 17 | let mut output = codewhale_localization::tr(self.0, id).to_string(); |
| 18 | for (name, value) in replacements { |
| 19 | output = output.replace(&format!("{{{name}}}"), value); |
| 20 | } |
| 21 | Ok(output) |
| 22 | } |
| 23 | } |
| 24 | let mut output = String::new(); |
| 25 | append_host_owner_report( |
| 26 | &Presentation(Locale::En), |
| 27 | &mut output, |
| 28 | &codewhale_engine::extension_host::OwnerReport { |
| 29 | cohort: None, |
| 30 | state: Some( |
| 31 | codewhale_engine::extension_host::registry::OwnerState::Failed( |
| 32 | "\u{1b}[31m<script>".into(), |
| 33 | ), |
| 34 | ), |
| 35 | tools: vec".into()], |
| 36 | diagnostics: vec!["\n# approved\u{202e}".into()], |
| 37 | }, |
| 38 | ); |
| 39 | assert!(output.contains("Plugin host:")); |
| 40 | for value in [ |
| 41 | "\u{1b}[31m<script>", |
| 42 | "[tool](https://example.invalid)", |
| 43 | "\n# approved\u{202e}", |
| 44 | ] { |
| 45 | assert!(output.contains(&escape_review_text(value, ReviewTextContext::Prose))); |
| 46 | assert!(!output.contains(value)); |
| 47 | } |
| 48 | let mut localized = String::new(); |
| 49 | append_host_owner_report( |
| 50 | &Presentation(Locale::ZhHans), |
| 51 | &mut localized, |
| 52 | &codewhale_engine::extension_host::OwnerReport { |
| 53 | cohort: None, |
| 54 | state: None, |
| 55 | tools: vec![], |
| 56 | diagnostics: vec![], |
| 57 | }, |
| 58 | ); |
| 59 | assert_eq!( |
| 60 | localized, |
| 61 | "\n插件宿主:\n 状态:未激活\n 活动工具(0):—" |
| 62 | ); |
| 63 | } |
| 64 | |
| 65 | #[test] |
| 66 | fn plugin_config_summary_lists_keys_never_values_and_escapes_them() { |
| 67 | let mut output = String::new(); |
| 68 | append_plugin_config_summary( |
| 69 | &mut output, |
| 70 | "greeter", |
| 71 | &Ok(vec!["greeting".to_string(), "\u{1b}[31mkey".to_string()]), |
| 72 | ); |
| 73 | assert!(output.contains("[plugins.\"greeter\".config]"), "{output}"); |
| 74 | assert!(output.contains("values not shown")); |
| 75 | assert!(output.contains("greeting")); |
| 76 | assert!(output.contains(&escape_review_text( |
| 77 | "\u{1b}[31mkey", |
| 78 | ReviewTextContext::Prose |
| 79 | ))); |
| 80 | assert!(!output.contains('\u{1b}')); |
| 81 | |
| 82 | let mut refused = String::new(); |
| 83 | append_plugin_config_summary( |
| 84 | &mut refused, |
| 85 | "greeter", |
| 86 | &Err("config is 20000 bytes\n# approved".to_string()), |
| 87 | ); |
| 88 | assert!(refused.contains("is refused: "), "{refused}"); |
| 89 | assert!(!refused.contains("\n# approved"), "{refused}"); |
| 90 | } |
| 91 | |
| 92 | fn create_test_app(root: &Path) -> (App, TempDir) { |
| 93 | let temp = TempDir::new().expect("tempdir"); |
| 94 | let config_path = temp.path().join("config.toml"); |
| 95 | let tools_dir = root.join("tools"); |
| 96 | fs::create_dir_all(&tools_dir).unwrap(); |
| 97 | fs::write( |
| 98 | &config_path, |
| 99 | format!( |
| 100 | "[tools]\nplugin_dir = {}\n", |
| 101 | toml::Value::String(tools_dir.to_string_lossy().to_string()) |
| 102 | ), |
| 103 | ) |
| 104 | .unwrap(); |
| 105 | let options = TuiOptions { |
| 106 | config_path: Some(config_path), |
| 107 | skills_dir: temp.path().join("skills"), |
| 108 | memory_path: temp.path().join("memory.md"), |
| 109 | mcp_config_path: temp.path().join("mcp.json"), |
| 110 | ..crate::tui::test_support::test_tui_options(root) |
| 111 | }; |
| 112 | let config = { |
| 113 | let __cw_config_init_0_0 = Some(codewhale_runtime::config::ToolsConfig { |
| 114 | plugin_dir: Some(tools_dir.to_string_lossy().into_owned()), |
| 115 | ..Default::default() |
| 116 | }); |
| 117 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 118 | __cw_config_init_0_value.tools = __cw_config_init_0_0; |
| 119 | __cw_config_init_0_value |
| 120 | }; |
| 121 | let discovery = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv(); |
| 122 | let registry = discovery.registry_for_workspace(root); |
| 123 | let mut app = App::new_with_plugin_registry(options, &config, registry); |
| 124 | app.ui_locale = Locale::En; |
| 125 | (app, temp) |
| 126 | } |
| 127 | |
| 128 | fn write_bundle(root: &Path) { |
| 129 | let bundle = root.join(".codewhale/plugins/demo"); |
| 130 | fs::create_dir_all(bundle.join("skills/hello")).unwrap(); |
| 131 | fs::write( |
| 132 | bundle.join("plugin.toml"), |
| 133 | "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\ndescription = \"Import spreadsheet data safely\"\n[skills]\npath = \"skills\"\n", |
| 134 | ) |
| 135 | .unwrap(); |
| 136 | fs::write( |
| 137 | bundle.join("skills/hello/SKILL.md"), |
| 138 | "---\nname: hello\ndescription: hello\n---\nbody\n", |
| 139 | ) |
| 140 | .unwrap(); |
| 141 | } |
| 142 | |
| 143 | fn write_mcp_review_bundle(root: &Path) { |
| 144 | let bundle = root.join(".codewhale/plugins/review-mcp"); |
| 145 | fs::create_dir_all(&bundle).unwrap(); |
| 146 | fs::write(bundle.join("server.js"), "// reviewed entrypoint\n").unwrap(); |
| 147 | fs::write( |
| 148 | bundle.join("plugin.toml"), |
| 149 | r#"schema_version = 1 |
| 150 | [plugin] |
| 151 | name = "review-mcp" |
| 152 | version = "1.0.0" |
| 153 | |
| 154 | [mcp_servers.local] |
| 155 | command = "node" |
| 156 | args = ["server.js", "--mode=worker", "-e", "console.log('ready')"] |
| 157 | |
| 158 | [mcp_servers.local.env] |
| 159 | PLUGIN_TOKEN = "${PLUGIN_TOKEN_SOURCE}" |
| 160 | |
| 161 | [mcp_servers.remote] |
| 162 | url = "https://example.invalid/mcp" |
| 163 | bearer_token_env_var = "REMOTE_TOKEN" |
| 164 | |
| 165 | [mcp_servers.remote.env_headers] |
| 166 | X_Api_Key = "REMOTE_API_KEY" |
| 167 | |
| 168 | [capabilities] |
| 169 | network_hosts = ["example.invalid"] |
| 170 | "#, |
| 171 | ) |
| 172 | .unwrap(); |
| 173 | } |
| 174 | |
| 175 | #[test] |
| 176 | fn bare_plugin_command_opens_unified_extensions_modal() { |
| 177 | let _lock = crate::test_support::lock_test_env(); |
| 178 | let root = TempDir::new().unwrap(); |
| 179 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 180 | let (mut app, _temp) = create_test_app(root.path()); |
| 181 | |
| 182 | let result = plugins_with_kimi_home_override(&mut app, None, None); |
| 183 | |
| 184 | assert!(matches!( |
| 185 | result.action, |
| 186 | Some(AppAction::OpenExtensions { |
| 187 | tab: crate::tui::views::extensions::ExtensionsTab::Plugins |
| 188 | }) |
| 189 | )); |
| 190 | assert!(result.message.is_none()); |
| 191 | } |
| 192 | |
| 193 | #[test] |
| 194 | fn list_show_validate_are_read_only_and_label_legacy_tools() { |
| 195 | let _lock = crate::test_support::lock_test_env(); |
| 196 | let root = TempDir::new().unwrap(); |
| 197 | let codewhale_home = root.path().join("home"); |
| 198 | // A configured user has a home; that is the state in which the built-in |
| 199 | // bundle is materialized and listed. |
| 200 | fs::create_dir_all(&codewhale_home).unwrap(); |
| 201 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 202 | write_bundle(root.path()); |
| 203 | let (mut app, _temp) = create_test_app(root.path()); |
| 204 | fs::write( |
| 205 | root.path().join("tools/greet.sh"), |
| 206 | "# name: greet\n# description: hello\n", |
| 207 | ) |
| 208 | .unwrap(); |
| 209 | // The app already resolved the legacy tools path during startup. |
| 210 | // Read-only plugin commands must not reopen a credential-bearing |
| 211 | // config file merely to inventory those tools. |
| 212 | fs::write( |
| 213 | app.config_path.as_ref().unwrap(), |
| 214 | "api_key = [\"must-not-be-re-read\"\n", |
| 215 | ) |
| 216 | .unwrap(); |
| 217 | let state_path = codewhale_home.join("plugins/state.json"); |
| 218 | |
| 219 | for arg in [Some("list"), Some("show demo"), Some("validate")] { |
| 220 | let result = plugins_with_kimi_home_override(&mut app, arg, None); |
| 221 | assert!(!result.is_error, "{:?}", result.message); |
| 222 | assert!(!state_path.exists(), "read-only command wrote plugin state"); |
| 223 | } |
| 224 | let list = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 225 | .message |
| 226 | .unwrap(); |
| 227 | assert!(list.contains("Plugin bundles (2)"), "{list}"); |
| 228 | assert!(list.contains(r"agent\-teams"), "{list}"); |
| 229 | assert!(list.contains("workspace · not-reviewed"), "{list}"); |
| 230 | assert!(list.contains("disabled")); |
| 231 | assert!(list.contains("Legacy plugin tools (1)")); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn list_preserves_the_one_shot_on_disk_reload_nudge() { |
| 236 | let _lock = crate::test_support::lock_test_env(); |
| 237 | let root = TempDir::new().unwrap(); |
| 238 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 239 | let (mut app, _temp) = create_test_app(root.path()); |
| 240 | |
| 241 | // Mutate the on-disk catalog after discovery. Listing must report the |
| 242 | // current-main nudge without rediscovering or changing trust state. |
| 243 | write_bundle(root.path()); |
| 244 | let first = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 245 | .message |
| 246 | .unwrap(); |
| 247 | assert!( |
| 248 | first.contains(codewhale_plugins::PLUGIN_RELOAD_NUDGE), |
| 249 | "{first}" |
| 250 | ); |
| 251 | |
| 252 | let second = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 253 | .message |
| 254 | .unwrap(); |
| 255 | assert!( |
| 256 | !second.contains(codewhale_plugins::PLUGIN_RELOAD_NUDGE), |
| 257 | "nudge must appear once per catalog stamp: {second}" |
| 258 | ); |
| 259 | } |
| 260 | |
| 261 | #[test] |
| 262 | fn suggest_ranks_installed_plugins_without_trusting_or_enabling_them() { |
| 263 | let _lock = crate::test_support::lock_test_env(); |
| 264 | let root = TempDir::new().unwrap(); |
| 265 | let codewhale_home = root.path().join("home"); |
| 266 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 267 | write_bundle(root.path()); |
| 268 | let (mut app, _temp) = create_test_app(root.path()); |
| 269 | |
| 270 | for arg in ["suggest", "suggest go"] { |
| 271 | let result = plugins_with_kimi_home_override(&mut app, Some(arg), None); |
| 272 | assert!( |
| 273 | result.is_error, |
| 274 | "expected usage error for {arg}: {result:?}" |
| 275 | ); |
| 276 | } |
| 277 | |
| 278 | let result = |
| 279 | plugins_with_kimi_home_override(&mut app, Some("suggest spreadsheet import"), None); |
| 280 | assert!(!result.is_error, "{result:?}"); |
| 281 | let message = result.message.expect("suggestion message"); |
| 282 | assert!(message.contains("Suggested plugins"), "{message}"); |
| 283 | assert!(message.contains("demo — disabled"), "{message}"); |
| 284 | assert!(message.contains("Why:"), "{message}"); |
| 285 | assert!(message.contains("/plugin trust demo"), "{message}"); |
| 286 | assert!( |
| 287 | message.contains("spreadsheet") || message.contains("import"), |
| 288 | "{message}" |
| 289 | ); |
| 290 | assert!(message.contains("Nothing was installed, trusted, or enabled.")); |
| 291 | assert!(!codewhale_home.join("plugins/state.json").exists()); |
| 292 | let plugin = app.plugin_registry.get("demo").expect("demo plugin"); |
| 293 | assert!(!plugin.enabled && !plugin.trusted()); |
| 294 | } |
| 295 | |
| 296 | #[test] |
| 297 | fn suggest_matches_manifest_keywords_for_a_named_integration() { |
| 298 | let _lock = crate::test_support::lock_test_env(); |
| 299 | let root = TempDir::new().unwrap(); |
| 300 | let codewhale_home = root.path().join("home"); |
| 301 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 302 | let bundle = root.path().join(".codewhale/plugins/supabase"); |
| 303 | fs::create_dir_all(&bundle).unwrap(); |
| 304 | fs::write( |
| 305 | bundle.join("plugin.toml"), |
| 306 | "schema_version = 1\n[plugin]\nname = \"supabase\"\nversion = \"1.0.0\"\ndescription = \"Hosted Postgres and auth\"\nkeywords = [\"supabase\", \"postgres\"]\n", |
| 307 | ) |
| 308 | .unwrap(); |
| 309 | let (mut app, _temp) = create_test_app(root.path()); |
| 310 | |
| 311 | let result = plugins_with_kimi_home_override(&mut app, Some("suggest add supabase auth"), None); |
| 312 | assert!(!result.is_error, "{result:?}"); |
| 313 | let message = result.message.expect("suggestion message"); |
| 314 | assert!(message.contains("supabase"), "{message}"); |
| 315 | assert!(message.contains("/plugin trust supabase"), "{message}"); |
| 316 | assert!(message.contains("Nothing was installed, trusted, or enabled.")); |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn trust_requires_content_and_capability_bound_review_token() { |
| 321 | let _lock = crate::test_support::lock_test_env(); |
| 322 | let root = TempDir::new().unwrap(); |
| 323 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 324 | write_bundle(root.path()); |
| 325 | let (mut app, _temp) = create_test_app(root.path()); |
| 326 | let enable_review = plugins_with_kimi_home_override(&mut app, Some("enable demo"), None); |
| 327 | assert!(!enable_review.is_error); |
| 328 | assert!( |
| 329 | enable_review |
| 330 | .message |
| 331 | .as_deref() |
| 332 | .is_some_and(|message| message.contains("/plugin trust demo ")) |
| 333 | ); |
| 334 | assert!(!app.plugin_registry.get("demo").unwrap().trusted()); |
| 335 | |
| 336 | let review_result = plugins_with_kimi_home_override(&mut app, Some("trust demo"), None); |
| 337 | let Some(AppAction::OpenCommandReview { |
| 338 | content, command, .. |
| 339 | }) = review_result.action |
| 340 | else { |
| 341 | panic!("trust opens a confirmation control"); |
| 342 | }; |
| 343 | assert!( |
| 344 | !content.contains("/plugin trust demo "), |
| 345 | "the hash belongs to the control" |
| 346 | ); |
| 347 | let review = review_result.message.unwrap(); |
| 348 | let confirmation = review |
| 349 | .lines() |
| 350 | .find(|line| line.starts_with("/plugin trust demo ")) |
| 351 | .unwrap(); |
| 352 | assert_eq!(confirmation, command); |
| 353 | let token = confirmation |
| 354 | .split_whitespace() |
| 355 | .last() |
| 356 | .expect("review confirmation token"); |
| 357 | let (content_digest, capability_digest) = token |
| 358 | .split_once('.') |
| 359 | .expect("content and capability digests"); |
| 360 | assert_eq!(content_digest.len(), 64); |
| 361 | assert_eq!(capability_digest.len(), 64); |
| 362 | assert!(content_digest.bytes().all(|byte| byte.is_ascii_hexdigit())); |
| 363 | assert!( |
| 364 | capability_digest |
| 365 | .bytes() |
| 366 | .all(|byte| byte.is_ascii_hexdigit()) |
| 367 | ); |
| 368 | assert!(!app.plugin_registry.get("demo").unwrap().trusted()); |
| 369 | |
| 370 | assert!(plugins_with_kimi_home_override(&mut app, Some("trust demo wrong"), None).is_error); |
| 371 | let shortened = format!( |
| 372 | "trust demo {}.{}", |
| 373 | &content_digest[..12], |
| 374 | &capability_digest[..12] |
| 375 | ); |
| 376 | assert!( |
| 377 | plugins_with_kimi_home_override(&mut app, Some(&shortened), None).is_error, |
| 378 | "the legacy 48-bit content prefix must not authorize trust" |
| 379 | ); |
| 380 | let arg = confirmation.trim_start_matches("/plugin "); |
| 381 | assert!(!plugins_with_kimi_home_override(&mut app, Some(arg), None).is_error); |
| 382 | assert!(!plugins_with_kimi_home_override(&mut app, Some("enable demo"), None).is_error); |
| 383 | assert!(app.plugin_registry.is_active("demo")); |
| 384 | assert!(!plugins_with_kimi_home_override(&mut app, Some("disable demo"), None).is_error); |
| 385 | assert!(!app.plugin_registry.is_active("demo")); |
| 386 | } |
| 387 | |
| 388 | fn write_mixed_bundle(root: &Path) { |
| 389 | let bundle = root.join(".codewhale/plugins/mixed"); |
| 390 | fs::create_dir_all(bundle.join("skills/hello")).unwrap(); |
| 391 | fs::create_dir_all(bundle.join("commands")).unwrap(); |
| 392 | fs::create_dir_all(bundle.join("hooks")).unwrap(); |
| 393 | fs::create_dir_all(bundle.join("lsp")).unwrap(); |
| 394 | fs::write( |
| 395 | bundle.join("plugin.toml"), |
| 396 | "schema_version = 1\n[plugin]\nname = \"mixed\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n[commands]\npath = \"commands\"\n[hooks]\npath = \"hooks\"\n[lsp]\npath = \"lsp\"\n", |
| 397 | ) |
| 398 | .unwrap(); |
| 399 | fs::write( |
| 400 | bundle.join("skills/hello/SKILL.md"), |
| 401 | "---\nname: hello\ndescription: hello\n---\nbody\n", |
| 402 | ) |
| 403 | .unwrap(); |
| 404 | } |
| 405 | |
| 406 | #[test] |
| 407 | fn mixed_bundle_review_and_enable_keep_supported_components_active() { |
| 408 | let _lock = crate::test_support::lock_test_env(); |
| 409 | let root = TempDir::new().unwrap(); |
| 410 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 411 | write_mixed_bundle(root.path()); |
| 412 | let (mut app, _temp) = create_test_app(root.path()); |
| 413 | |
| 414 | let list = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 415 | .message |
| 416 | .unwrap(); |
| 417 | assert!(list.contains("compatibility=partial"), "{list}"); |
| 418 | assert!(list.contains("commands=1"), "{list}"); |
| 419 | assert!(list.contains("hooks=1"), "{list}"); |
| 420 | |
| 421 | let show = plugins_with_kimi_home_override(&mut app, Some("show mixed"), None) |
| 422 | .message |
| 423 | .unwrap(); |
| 424 | assert!(show.contains("Compatibility: partial"), "{show}"); |
| 425 | assert!(show.contains("Inactive components: [lsp]"), "{show}"); |
| 426 | assert!(show.contains("Active components: [none]"), "{show}"); |
| 427 | |
| 428 | let review = plugins_with_kimi_home_override(&mut app, Some("trust mixed"), None) |
| 429 | .message |
| 430 | .unwrap(); |
| 431 | let confirmation = review |
| 432 | .lines() |
| 433 | .find(|line| line.starts_with("/plugin trust mixed ")) |
| 434 | .unwrap(); |
| 435 | let arg = confirmation.trim_start_matches("/plugin "); |
| 436 | assert!(!plugins_with_kimi_home_override(&mut app, Some(arg), None).is_error); |
| 437 | let enabled = plugins_with_kimi_home_override(&mut app, Some("enable mixed"), None); |
| 438 | assert!(!enabled.is_error, "{:?}", enabled.message); |
| 439 | let message = enabled.message.unwrap(); |
| 440 | assert!(message.contains("Compatibility: partial"), "{message}"); |
| 441 | assert!(message.contains("inactive: lsp"), "{message}"); |
| 442 | assert!(app.plugin_registry.is_active("mixed")); |
| 443 | assert_eq!( |
| 444 | app.plugin_registry |
| 445 | .get("mixed") |
| 446 | .unwrap() |
| 447 | .compatibility() |
| 448 | .as_str(), |
| 449 | "partial" |
| 450 | ); |
| 451 | |
| 452 | let show = plugins_with_kimi_home_override(&mut app, Some("show mixed"), None) |
| 453 | .message |
| 454 | .unwrap(); |
| 455 | assert!(show.contains("State: active"), "{show}"); |
| 456 | assert!(show.contains("Inactive components: [lsp]"), "{show}"); |
| 457 | assert!( |
| 458 | show.contains("Active components: [skills, commands, hooks]"), |
| 459 | "{show}" |
| 460 | ); |
| 461 | assert!(show.contains("Qualified skills: [mixed:hello]"), "{show}"); |
| 462 | } |
| 463 | |
| 464 | #[test] |
| 465 | fn mcp_review_discloses_host_authority_and_names_without_secret_values() { |
| 466 | let _lock = crate::test_support::lock_test_env(); |
| 467 | let root = TempDir::new().unwrap(); |
| 468 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 469 | write_mcp_review_bundle(root.path()); |
| 470 | let (mut app, _temp) = create_test_app(root.path()); |
| 471 | let review = plugins_with_kimi_home_override(&mut app, Some("trust review-mcp"), None) |
| 472 | .message |
| 473 | .expect("review output"); |
| 474 | assert!(review.contains("mcp=2 (stdio=1 remote=1)")); |
| 475 | assert!(review.contains("host-user filesystem/network authority")); |
| 476 | assert!(review.contains("PLUGIN\\_TOKEN <- PLUGIN\\_TOKEN\\_SOURCE")); |
| 477 | assert!(review.contains("X\\_Api\\_Key <- REMOTE\\_API\\_KEY")); |
| 478 | assert!(review.contains("bearer_env=REMOTE\\_TOKEN")); |
| 479 | assert!(review.contains("redirects=same-origin-only")); |
| 480 | assert!(review.contains("Qualified skills: [none]")); |
| 481 | for (position, expected) in [(2, "--mode=worker"), (3, "-e"), (4, "console.log('ready')")] { |
| 482 | let prefix = format!("#{position} value="); |
| 483 | let value = review |
| 484 | .split(prefix.as_str()) |
| 485 | .nth(1) |
| 486 | .expect("reviewed argv position"); |
| 487 | let actual = serde_json::Deserializer::from_str(value) |
| 488 | .into_iter::<String>() |
| 489 | .next() |
| 490 | .expect("reviewed JSON value") |
| 491 | .expect("lossless reviewed argv string"); |
| 492 | assert_eq!(actual, expected); |
| 493 | } |
| 494 | assert!(review.contains("oauth=disabled")); |
| 495 | } |
| 496 | |
| 497 | #[test] |
| 498 | fn legacy_tool_detail_remains_available_under_tools_namespace() { |
| 499 | let _lock = crate::test_support::lock_test_env(); |
| 500 | let root = TempDir::new().unwrap(); |
| 501 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 502 | let (mut app, _temp) = create_test_app(root.path()); |
| 503 | fs::write( |
| 504 | root.path().join("tools/greet.sh"), |
| 505 | "# name: greet\n# description: Say hello\n# approval: required\n", |
| 506 | ) |
| 507 | .unwrap(); |
| 508 | let result = plugins_with_kimi_home_override(&mut app, Some("tools greet"), None); |
| 509 | assert!(!result.is_error); |
| 510 | let message = result.message.unwrap(); |
| 511 | assert!(message.contains("Say hello")); |
| 512 | assert!(message.contains("required")); |
| 513 | } |
| 514 | |
| 515 | /// D4: `/plugin tools` names a script whose `approval: auto` was ignored and |
| 516 | /// shows the approval it actually runs with. |
| 517 | #[test] |
| 518 | fn legacy_tools_report_ignored_auto_approval() { |
| 519 | let _lock = crate::test_support::lock_test_env(); |
| 520 | let root = TempDir::new().unwrap(); |
| 521 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 522 | let (mut app, _temp) = create_test_app(root.path()); |
| 523 | fs::write( |
| 524 | root.path().join("tools/greet.sh"), |
| 525 | "# name: greet\n# description: Say hello\n# approval: auto\n", |
| 526 | ) |
| 527 | .unwrap(); |
| 528 | fs::write( |
| 529 | root.path().join("tools/audit.sh"), |
| 530 | "# name: audit\n# description: Audit\n# approval: required\n", |
| 531 | ) |
| 532 | .unwrap(); |
| 533 | // The renderer escapes Markdown in plugin-controlled text. |
| 534 | let warning = "[script_tool_auto_approval_ignored]: script tool 'greet': \\`approval: auto\\` is no longer supported for script tools"; |
| 535 | |
| 536 | let list = plugins_with_kimi_home_override(&mut app, Some("tools"), None) |
| 537 | .message |
| 538 | .unwrap(); |
| 539 | assert!(list.contains(warning), "{list}"); |
| 540 | assert!(!list.contains("script tool 'audit'"), "{list}"); |
| 541 | |
| 542 | let detail = plugins_with_kimi_home_override(&mut app, Some("tools greet"), None) |
| 543 | .message |
| 544 | .unwrap(); |
| 545 | assert!(detail.contains("suggest"), "{detail}"); |
| 546 | assert!(detail.contains(warning), "{detail}"); |
| 547 | let other = plugins_with_kimi_home_override(&mut app, Some("tools audit"), None) |
| 548 | .message |
| 549 | .unwrap(); |
| 550 | assert!( |
| 551 | !other.contains("script_tool_auto_approval_ignored"), |
| 552 | "{other}" |
| 553 | ); |
| 554 | } |
| 555 | |
| 556 | #[test] |
| 557 | fn install_update_uninstall_verbs_validate_arguments() { |
| 558 | let _lock = crate::test_support::lock_test_env(); |
| 559 | let root = TempDir::new().unwrap(); |
| 560 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 561 | let (mut app, _temp) = create_test_app(root.path()); |
| 562 | for arg in ["install", "update", "uninstall"] { |
| 563 | let result = plugins_with_kimi_home_override(&mut app, Some(arg), None); |
| 564 | assert!(result.is_error, "bare `{arg}` must print usage"); |
| 565 | } |
| 566 | let invalid = plugins_with_kimi_home_override(&mut app, Some("install github:"), None); |
| 567 | assert!(invalid.is_error); |
| 568 | assert!( |
| 569 | invalid |
| 570 | .message |
| 571 | .unwrap() |
| 572 | .contains("Invalid plugin install source"), |
| 573 | "invalid specs must be rejected before any network or disk access" |
| 574 | ); |
| 575 | } |
| 576 | |
| 577 | #[test] |
| 578 | fn install_update_uninstall_verbs_drive_the_guided_trust_flow() { |
| 579 | let _lock = crate::test_support::lock_test_env(); |
| 580 | let root = TempDir::new().unwrap(); |
| 581 | let codewhale_home = root.path().join("home"); |
| 582 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 583 | |
| 584 | let source = root.path().join("source/installed-demo"); |
| 585 | fs::create_dir_all(&source).unwrap(); |
| 586 | fs::write( |
| 587 | source.join("plugin.toml"), |
| 588 | "schema_version = 1\n[plugin]\nname = \"installed-demo\"\nversion = \"1.0.0\"\n", |
| 589 | ) |
| 590 | .unwrap(); |
| 591 | |
| 592 | let (mut app, _temp) = create_test_app(root.path()); |
| 593 | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 594 | .worker_threads(2) |
| 595 | .enable_all() |
| 596 | .build() |
| 597 | .unwrap(); |
| 598 | runtime.block_on(async { |
| 599 | let installed = plugins_with_kimi_home_override( |
| 600 | &mut app, |
| 601 | Some(&format!("install {}", source.display())), |
| 602 | None, |
| 603 | ); |
| 604 | assert!(!installed.is_error, "{:?}", installed.message); |
| 605 | let message = installed.message.unwrap(); |
| 606 | assert!(message.contains("disabled and untrusted"), "{message}"); |
| 607 | let confirmation = message |
| 608 | .lines() |
| 609 | .find(|line| line.starts_with("/plugin trust installed-demo ")) |
| 610 | .expect("install must route into the trust review") |
| 611 | .to_string(); |
| 612 | let plugin = app.plugin_registry.get("installed-demo").unwrap(); |
| 613 | assert!(!plugin.enabled && !plugin.trusted()); |
| 614 | assert!( |
| 615 | codewhale_home |
| 616 | .join("plugins/installed-demo/.installed-from") |
| 617 | .exists() |
| 618 | ); |
| 619 | |
| 620 | // An unchanged local source succeeds without changing the review token. |
| 621 | let update = plugins_with_kimi_home_override(&mut app, Some("update installed-demo"), None); |
| 622 | assert!(!update.is_error, "{:?}", update.message); |
| 623 | assert!(update.message.unwrap().contains("already up to date")); |
| 624 | |
| 625 | let arg = confirmation.trim_start_matches("/plugin ").to_string(); |
| 626 | assert!(!plugins_with_kimi_home_override(&mut app, Some(&arg), None).is_error); |
| 627 | assert!( |
| 628 | !plugins_with_kimi_home_override(&mut app, Some("enable installed-demo"), None) |
| 629 | .is_error |
| 630 | ); |
| 631 | assert!(app.plugin_registry.is_active("installed-demo")); |
| 632 | |
| 633 | fs::write( |
| 634 | source.join("plugin.toml"), |
| 635 | "schema_version = 1\n[plugin]\nname = \"installed-demo\"\nversion = \"2.0.0\"\n", |
| 636 | ) |
| 637 | .unwrap(); |
| 638 | let updated = |
| 639 | plugins_with_kimi_home_override(&mut app, Some("update installed-demo"), None); |
| 640 | assert!(!updated.is_error, "{:?}", updated.message); |
| 641 | let message = updated.message.unwrap(); |
| 642 | let current_confirmation = message |
| 643 | .lines() |
| 644 | .find(|line| line.starts_with("/plugin trust installed-demo ")) |
| 645 | .expect("changed local content must route into its current review"); |
| 646 | assert_ne!(current_confirmation, confirmation); |
| 647 | assert!(!app.plugin_registry.is_active("installed-demo")); |
| 648 | assert!(plugins_with_kimi_home_override(&mut app, Some(&arg), None).is_error); |
| 649 | let current_arg = current_confirmation.trim_start_matches("/plugin "); |
| 650 | assert!(!plugins_with_kimi_home_override(&mut app, Some(current_arg), None).is_error); |
| 651 | assert!( |
| 652 | !plugins_with_kimi_home_override(&mut app, Some("enable installed-demo"), None) |
| 653 | .is_error |
| 654 | ); |
| 655 | assert!(app.plugin_registry.is_active("installed-demo")); |
| 656 | |
| 657 | // Uninstall requires disabled, then removes bits and prunes state. |
| 658 | let refused = |
| 659 | plugins_with_kimi_home_override(&mut app, Some("uninstall installed-demo"), None); |
| 660 | assert!(refused.is_error); |
| 661 | assert!(codewhale_home.join("plugins/installed-demo").exists()); |
| 662 | assert!( |
| 663 | !plugins_with_kimi_home_override(&mut app, Some("disable installed-demo"), None) |
| 664 | .is_error |
| 665 | ); |
| 666 | let removed = |
| 667 | plugins_with_kimi_home_override(&mut app, Some("uninstall installed-demo"), None); |
| 668 | assert!(!removed.is_error, "{:?}", removed.message); |
| 669 | assert!(!codewhale_home.join("plugins/installed-demo").exists()); |
| 670 | assert!(app.plugin_registry.get("installed-demo").is_none()); |
| 671 | let raw = fs::read_to_string(codewhale_home.join("plugins/state.json")).unwrap(); |
| 672 | let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap(); |
| 673 | assert!( |
| 674 | parsed["plugins"].as_object().unwrap().is_empty(), |
| 675 | "uninstall must prune the state entry: {raw}" |
| 676 | ); |
| 677 | }); |
| 678 | } |
| 679 | |
| 680 | #[test] |
| 681 | fn dsh_import_reviews_without_installing_then_installs_the_exact_bundle() { |
| 682 | let _lock = crate::test_support::lock_test_env(); |
| 683 | let root = TempDir::new().unwrap(); |
| 684 | let codewhale_home = root.path().join("codewhale-home"); |
| 685 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 686 | let package = root.path().join("dsh-package"); |
| 687 | fs::create_dir_all(package.join("pack-skills/guide")).unwrap(); |
| 688 | fs::write( |
| 689 | package.join("package.json"), |
| 690 | r#"{"name": "@demo/docs-dsh", "version": "2.0.0", "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}}"#, |
| 691 | ) |
| 692 | .unwrap(); |
| 693 | fs::write( |
| 694 | package.join("cordis.patch.yml"), |
| 695 | "- insert:\n - id: docs\n name: '@deepseek-ai/dsh-mcp-client'\n config: {serverName: docs, transport: streamable-http, url: 'https://docs.example.invalid/mcp'}\n - id: skills\n name: '@deepseek-ai/dsh-skill-filesystem'\n config: {customSkillDirs: [pack-skills]}\n - id: theme\n name: '@deepseek-ai/dsh-client-ui-theme'\n", |
| 696 | ) |
| 697 | .unwrap(); |
| 698 | fs::write( |
| 699 | package.join("pack-skills/guide/SKILL.md"), |
| 700 | "---\nname: guide\ndescription: Bundled guide\n---\nBody.\n", |
| 701 | ) |
| 702 | .unwrap(); |
| 703 | |
| 704 | let (mut app, _temp) = create_test_app(root.path()); |
| 705 | let help = plugins_with_kimi_home_override(&mut app, Some("help"), None) |
| 706 | .message |
| 707 | .unwrap(); |
| 708 | assert!(help.contains("/plugin import dsh <package-dir>"), "{help}"); |
| 709 | let review = plugins_with_kimi_home_override( |
| 710 | &mut app, |
| 711 | Some(&format!("import dsh {}", package.display())), |
| 712 | None, |
| 713 | ); |
| 714 | assert!(!review.is_error, "{:?}", review.message); |
| 715 | let message = review.message.unwrap(); |
| 716 | for fact in [ |
| 717 | "@demo/docs-dsh@2.0.0", |
| 718 | "plugin 'docs-dsh'", |
| 719 | "Skills: guide", |
| 720 | "Remote MCP servers: docs", |
| 721 | "Network hosts it will request: docs.example.invalid", |
| 722 | "theme", |
| 723 | "Nothing was installed", |
| 724 | ] { |
| 725 | // Untrusted package text is rendered with review escaping. |
| 726 | assert!( |
| 727 | message.replace('\\', "").contains(fact), |
| 728 | "{fact}: {message}" |
| 729 | ); |
| 730 | } |
| 731 | let approval = message |
| 732 | .lines() |
| 733 | .find_map(|line| line.trim().strip_prefix("/plugin ")) |
| 734 | .expect("review renders an exact approval command") |
| 735 | .to_string(); |
| 736 | assert!(!codewhale_home.join("plugins/docs-dsh").exists()); |
| 737 | |
| 738 | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 739 | .worker_threads(2) |
| 740 | .enable_all() |
| 741 | .build() |
| 742 | .unwrap(); |
| 743 | runtime.block_on(async { |
| 744 | let installed = plugins_with_kimi_home_override(&mut app, Some(&approval), None); |
| 745 | assert!(!installed.is_error, "{:?}", installed.message); |
| 746 | assert!( |
| 747 | installed |
| 748 | .message |
| 749 | .as_deref() |
| 750 | .is_some_and(|m| m.contains("disabled and untrusted")) |
| 751 | ); |
| 752 | }); |
| 753 | let plugin = app.plugin_registry.get("docs-dsh").unwrap(); |
| 754 | assert!(!plugin.enabled && !plugin.trusted()); |
| 755 | assert!( |
| 756 | codewhale_home |
| 757 | .join("plugins/docs-dsh/CONVERSION.md") |
| 758 | .is_file() |
| 759 | ); |
| 760 | } |
| 761 | |
| 762 | #[test] |
| 763 | fn dsh_import_review_surfaces_sibling_plugin_json_hooks_commands_and_agents() { |
| 764 | let _lock = crate::test_support::lock_test_env(); |
| 765 | let root = TempDir::new().unwrap(); |
| 766 | let codewhale_home = root.path().join("codewhale-home"); |
| 767 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 768 | let package = root.path().join("combo-dsh-package"); |
| 769 | fs::create_dir_all(package.join("commands")).unwrap(); |
| 770 | fs::create_dir_all(package.join("agents")).unwrap(); |
| 771 | fs::create_dir_all(package.join("hooks")).unwrap(); |
| 772 | fs::write( |
| 773 | package.join("package.json"), |
| 774 | r#"{"name": "@demo/combo-dsh", "version": "1.0.0", "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}}"#, |
| 775 | ) |
| 776 | .unwrap(); |
| 777 | fs::write(package.join("cordis.patch.yml"), "[]\n").unwrap(); |
| 778 | fs::write(package.join("commands/hello.md"), "# Hello\n").unwrap(); |
| 779 | fs::write( |
| 780 | package.join("agents/reviewer.toml"), |
| 781 | "id = \"reviewer\"\n[role]\nname = \"reviewer\"\ndescription = \"Reviews\"\nprompt = \"Review.\"\n", |
| 782 | ) |
| 783 | .unwrap(); |
| 784 | fs::write( |
| 785 | package.join("hooks/hooks.toml"), |
| 786 | "enabled = true\n[[hooks]]\nname = \"check\"\nevent = \"turn_end\"\ncommand = \"true\"\n", |
| 787 | ) |
| 788 | .unwrap(); |
| 789 | fs::write( |
| 790 | package.join("plugin.json"), |
| 791 | serde_json::json!({ |
| 792 | "$schema": "https://agent-plugins.org/schemas/plugin.json", |
| 793 | "name": "combo-dsh", |
| 794 | "version": "1.0.0", |
| 795 | "description": "ignored sibling description", |
| 796 | "extensions": { |
| 797 | "net.codewhale": { |
| 798 | "commands": {"path": "commands"}, |
| 799 | "agents": {"path": "agents"}, |
| 800 | "hooks": {"path": "hooks"} |
| 801 | } |
| 802 | } |
| 803 | }) |
| 804 | .to_string(), |
| 805 | ) |
| 806 | .unwrap(); |
| 807 | |
| 808 | let (mut app, _temp) = create_test_app(root.path()); |
| 809 | let review = plugins_with_kimi_home_override( |
| 810 | &mut app, |
| 811 | Some(&format!("import dsh {}", package.display())), |
| 812 | None, |
| 813 | ); |
| 814 | assert!(!review.is_error, "{:?}", review.message); |
| 815 | let message = review.message.unwrap(); |
| 816 | for fact in [ |
| 817 | "@demo/combo-dsh@1.0.0", |
| 818 | "plugin 'combo-dsh'", |
| 819 | "Commands: commands/hello.md", |
| 820 | "Agents: agents/reviewer.toml", |
| 821 | "Hooks (run shell commands with your user's authority): hooks/hooks.toml", |
| 822 | "Diagnostics:", |
| 823 | "description", |
| 824 | "Nothing was installed", |
| 825 | ] { |
| 826 | assert!( |
| 827 | message.replace('\\', "").contains(fact), |
| 828 | "{fact}: {message}" |
| 829 | ); |
| 830 | } |
| 831 | assert!(!codewhale_home.join("plugins/combo-dsh").exists()); |
| 832 | |
| 833 | let approval = message |
| 834 | .lines() |
| 835 | .find_map(|line| line.trim().strip_prefix("/plugin ")) |
| 836 | .expect("review renders an exact approval command") |
| 837 | .to_string(); |
| 838 | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 839 | .worker_threads(2) |
| 840 | .enable_all() |
| 841 | .build() |
| 842 | .unwrap(); |
| 843 | runtime.block_on(async { |
| 844 | let installed = plugins_with_kimi_home_override(&mut app, Some(&approval), None); |
| 845 | assert!(!installed.is_error, "{:?}", installed.message); |
| 846 | }); |
| 847 | assert!( |
| 848 | codewhale_home |
| 849 | .join("plugins/combo-dsh/hooks/hooks.toml") |
| 850 | .is_file() |
| 851 | ); |
| 852 | } |
| 853 | |
| 854 | #[test] |
| 855 | fn kimi_managed_import_is_read_only_until_hash_bound_approval() { |
| 856 | let _lock = crate::test_support::lock_test_env(); |
| 857 | let root = TempDir::new().unwrap(); |
| 858 | let codewhale_home = root.path().join("codewhale-home"); |
| 859 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 860 | let managed = root.path().join(".kimi-code/plugins/managed/kimi-demo"); |
| 861 | fs::create_dir_all(managed.join("skills/kimi-demo")).unwrap(); |
| 862 | fs::write( |
| 863 | managed.join("kimi.plugin.json"), |
| 864 | r#"{ |
| 865 | "name": "kimi-demo", |
| 866 | "version": "1.0.0", |
| 867 | "license": "Proprietary", |
| 868 | "skills": "./skills/", |
| 869 | "interface": { |
| 870 | "displayName": "Kimi Demo", |
| 871 | "hostKind": "local", |
| 872 | "platforms": ["macos"] |
| 873 | } |
| 874 | }"#, |
| 875 | ) |
| 876 | .unwrap(); |
| 877 | fs::write( |
| 878 | managed.join("skills/kimi-demo/SKILL.md"), |
| 879 | "---\nname: kimi-demo\ndescription: local managed fixture\n---\n", |
| 880 | ) |
| 881 | .unwrap(); |
| 882 | |
| 883 | let (mut app, _temp) = create_test_app(root.path()); |
| 884 | let help = plugins_with_kimi_home_override(&mut app, Some("help"), None) |
| 885 | .message |
| 886 | .unwrap(); |
| 887 | assert!(help.contains("/plugin import kimi [list]"), "{help}"); |
| 888 | let listed = plugins_with_kimi_home(&mut app, Some("import kimi"), root.path()); |
| 889 | assert!(!listed.is_error, "{:?}", listed.message); |
| 890 | let message = listed.message.unwrap(); |
| 891 | assert!( |
| 892 | message.contains("Kimi Demo") || message.contains("kimi-demo"), |
| 893 | "{message}" |
| 894 | ); |
| 895 | assert!(message.contains("license=Proprietary"), "{message}"); |
| 896 | assert!(message.contains("content hash:"), "{message}"); |
| 897 | assert!(message.contains("External Kimi apps"), "{message}"); |
| 898 | let approval = message |
| 899 | .lines() |
| 900 | .find_map(|line| line.trim().strip_prefix("approve: /plugin ")) |
| 901 | .expect("listing must render an exact approval command") |
| 902 | .to_string(); |
| 903 | assert!(app.plugin_registry.get("kimi-demo").is_none()); |
| 904 | assert!(!codewhale_home.join("plugins/kimi-demo").exists()); |
| 905 | assert!(!codewhale_home.join("plugins/state.json").exists()); |
| 906 | |
| 907 | // The approval token is tied to the bytes that were inspected. |
| 908 | fs::write( |
| 909 | managed.join("skills/kimi-demo/SKILL.md"), |
| 910 | "---\nname: kimi-demo\ndescription: changed fixture\n---\n", |
| 911 | ) |
| 912 | .unwrap(); |
| 913 | let changed = plugins_with_kimi_home(&mut app, Some(&approval), root.path()); |
| 914 | assert!(changed.is_error); |
| 915 | assert!(changed.message.unwrap().contains("changed since review")); |
| 916 | assert!(!codewhale_home.join("plugins/kimi-demo").exists()); |
| 917 | |
| 918 | let refreshed = plugins_with_kimi_home(&mut app, Some("import kimi"), root.path()) |
| 919 | .message |
| 920 | .unwrap(); |
| 921 | let approval = refreshed |
| 922 | .lines() |
| 923 | .find_map(|line| line.trim().strip_prefix("approve: /plugin ")) |
| 924 | .unwrap() |
| 925 | .to_string(); |
| 926 | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 927 | .worker_threads(2) |
| 928 | .enable_all() |
| 929 | .build() |
| 930 | .unwrap(); |
| 931 | runtime.block_on(async { |
| 932 | let installed = plugins_with_kimi_home(&mut app, Some(&approval), root.path()); |
| 933 | assert!(!installed.is_error, "{:?}", installed.message); |
| 934 | assert!( |
| 935 | installed |
| 936 | .message |
| 937 | .as_deref() |
| 938 | .is_some_and(|message| message.contains("disabled and untrusted")) |
| 939 | ); |
| 940 | }); |
| 941 | let plugin = app.plugin_registry.get("kimi-demo").unwrap(); |
| 942 | assert!(!plugin.enabled && !plugin.trusted()); |
| 943 | assert!( |
| 944 | codewhale_home |
| 945 | .join("plugins/kimi-demo/kimi.plugin.json") |
| 946 | .is_file() |
| 947 | ); |
| 948 | } |
| 949 | |
| 950 | #[test] |
| 951 | fn kimi_managed_import_renders_in_the_selected_non_english_locale() { |
| 952 | let root = TempDir::new().unwrap(); |
| 953 | let (mut app, _temp) = create_test_app(root.path()); |
| 954 | app.ui_locale = Locale::Es419; |
| 955 | |
| 956 | let message = plugins_with_kimi_home(&mut app, Some("import kimi"), root.path()) |
| 957 | .message |
| 958 | .expect("localized Kimi listing"); |
| 959 | assert!( |
| 960 | message.contains("Plugins gestionados por Kimi"), |
| 961 | "{message}" |
| 962 | ); |
| 963 | assert!( |
| 964 | message.contains("No se encontraron plugins gestionados válidos"), |
| 965 | "{message}" |
| 966 | ); |
| 967 | assert!( |
| 968 | !message.contains("No valid managed plugins found"), |
| 969 | "{message}" |
| 970 | ); |
| 971 | } |
| 972 | |
| 973 | #[cfg(unix)] |
| 974 | #[test] |
| 975 | fn kimi_managed_import_refuses_linked_children() { |
| 976 | use std::os::unix::fs::symlink; |
| 977 | |
| 978 | let root = TempDir::new().unwrap(); |
| 979 | let managed_root = root.path().join(".kimi-code/plugins/managed"); |
| 980 | let outside = root.path().join("outside"); |
| 981 | fs::create_dir_all(&managed_root).unwrap(); |
| 982 | fs::create_dir_all(&outside).unwrap(); |
| 983 | symlink(&outside, managed_root.join("linked-plugin")).unwrap(); |
| 984 | let (mut app, _temp) = create_test_app(root.path()); |
| 985 | |
| 986 | let result = plugins_with_kimi_home(&mut app, Some("import kimi"), root.path()); |
| 987 | assert!(!result.is_error); |
| 988 | let message = result.message.unwrap(); |
| 989 | assert!(message.contains("Rejected entries"), "{message}"); |
| 990 | assert!(message.contains("links and reparse points are refused")); |
| 991 | assert!(!message.contains("approve: /plugin import kimi approve linked-plugin")); |
| 992 | } |
| 993 | |
| 994 | #[test] |
| 995 | fn export_verb_writes_agent_plugins_bundle() { |
| 996 | let _lock = crate::test_support::lock_test_env(); |
| 997 | let root = TempDir::new().unwrap(); |
| 998 | let codewhale_home = root.path().join("home"); |
| 999 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 1000 | write_bundle(root.path()); |
| 1001 | let (mut app, _temp) = create_test_app(root.path()); |
| 1002 | |
| 1003 | let usage = plugins_with_kimi_home_override(&mut app, Some("export"), None); |
| 1004 | assert!(usage.is_error, "export without arguments is a usage error"); |
| 1005 | let missing = plugins_with_kimi_home_override(&mut app, Some("export nope out"), None); |
| 1006 | assert!(missing.is_error, "exporting an unknown plugin fails"); |
| 1007 | |
| 1008 | let result = plugins_with_kimi_home_override(&mut app, Some("export demo exported/demo"), None); |
| 1009 | assert!(!result.is_error, "{result:?}"); |
| 1010 | let message = result.message.expect("export message"); |
| 1011 | assert!(message.contains("Exported `demo`"), "{message}"); |
| 1012 | assert!(message.contains("plugin.json"), "{message}"); |
| 1013 | |
| 1014 | let bundle = root.path().join("exported/demo"); |
| 1015 | let plugin_json: serde_json::Value = |
| 1016 | serde_json::from_str(&fs::read_to_string(bundle.join("plugin.json")).unwrap()).unwrap(); |
| 1017 | codewhale_plugins::agent_plugin::validate_plugin_json(&plugin_json).unwrap(); |
| 1018 | assert_eq!(plugin_json["name"], "demo"); |
| 1019 | assert_eq!(plugin_json["description"], "Import spreadsheet data safely"); |
| 1020 | assert!(bundle.join("skills/hello/SKILL.md").is_file()); |
| 1021 | assert!(!bundle.join("plugin.toml").exists()); |
| 1022 | // No MCP servers declared, so no mcp.json is written. |
| 1023 | assert!(!bundle.join("mcp.json").exists()); |
| 1024 | // The installed bundle keeps its legacy manifest and stays untouched. |
| 1025 | assert!( |
| 1026 | root.path() |
| 1027 | .join(".codewhale/plugins/demo/plugin.toml") |
| 1028 | .exists() |
| 1029 | ); |
| 1030 | } |
| 1031 | |
| 1032 | #[test] |
| 1033 | fn plugin_dismissals_list_and_reset_both_kinds() { |
| 1034 | let _lock = crate::test_support::lock_test_env(); |
| 1035 | let root = TempDir::new().unwrap(); |
| 1036 | let codewhale_home = root.path().join("home"); |
| 1037 | fs::create_dir_all(&codewhale_home).unwrap(); |
| 1038 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 1039 | let (mut app, _temp) = create_test_app(root.path()); |
| 1040 | codewhale_runtime::settings::Settings::transact_opt(|settings| { |
| 1041 | Ok(settings |
| 1042 | .dismissed_plugin_suggestions |
| 1043 | .insert("keptaway".to_string()) |
| 1044 | .then_some(())) |
| 1045 | }) |
| 1046 | .unwrap(); |
| 1047 | app.plugin_cta.dismissed.insert("keptaway".to_string()); |
| 1048 | app.plugin_cta.dismissed.insert("esconce".to_string()); |
| 1049 | |
| 1050 | let listed = plugins_with_kimi_home_override(&mut app, Some("dismissals"), None) |
| 1051 | .message |
| 1052 | .expect("dismissal list"); |
| 1053 | let kept = listed |
| 1054 | .find("keptaway") |
| 1055 | .unwrap_or_else(|| panic!("{listed}")); |
| 1056 | let session = listed.find("esconce").unwrap_or_else(|| panic!("{listed}")); |
| 1057 | assert!(listed.contains("Don't suggest again"), "{listed}"); |
| 1058 | assert!(listed.contains("This session only"), "{listed}"); |
| 1059 | assert!(kept < session, "{listed}"); |
| 1060 | |
| 1061 | let reset = plugins_with_kimi_home_override(&mut app, Some("dismissals reset KeptAway"), None) |
| 1062 | .message |
| 1063 | .expect("reset receipt"); |
| 1064 | assert!(reset.contains("keptaway"), "{reset}"); |
| 1065 | assert!( |
| 1066 | codewhale_runtime::settings::Settings::load() |
| 1067 | .unwrap() |
| 1068 | .dismissed_plugin_suggestions |
| 1069 | .is_empty(), |
| 1070 | "reset must reach the saved choice" |
| 1071 | ); |
| 1072 | assert!(!app.plugin_cta.dismissed.contains("keptaway")); |
| 1073 | assert!(app.plugin_cta.dismissed.contains("esconce")); |
| 1074 | |
| 1075 | plugins_with_kimi_home_override(&mut app, Some("dismissals reset"), None); |
| 1076 | assert!(app.plugin_cta.dismissed.is_empty()); |
| 1077 | let empty = plugins_with_kimi_home_override(&mut app, Some("dismissals"), None) |
| 1078 | .message |
| 1079 | .expect("empty list"); |
| 1080 | assert!(empty.contains("No plugins are hidden"), "{empty}"); |
| 1081 | } |
| 1082 | |
| 1083 | #[test] |
| 1084 | fn doctor_reports_read_only_then_fix_retires_stale_records_with_a_backup() { |
| 1085 | let _lock = crate::test_support::lock_test_env(); |
| 1086 | let root = TempDir::new().unwrap(); |
| 1087 | let home = root.path().join("home"); |
| 1088 | fs::create_dir_all(&home).unwrap(); |
| 1089 | // The registry's own private state layout: 0700 directory, 0600 file. |
| 1090 | let plugins_dir = home.join("plugins"); |
| 1091 | fs::create_dir_all(&plugins_dir).unwrap(); |
| 1092 | #[cfg(unix)] |
| 1093 | { |
| 1094 | use std::os::unix::fs::PermissionsExt as _; |
| 1095 | fs::set_permissions(&plugins_dir, fs::Permissions::from_mode(0o700)).unwrap(); |
| 1096 | } |
| 1097 | let state_path = plugins_dir.join("state.json"); |
| 1098 | let stale = serde_json::json!({ |
| 1099 | "schema_version": 1, |
| 1100 | "plugins": { |
| 1101 | "workspace/111111111111/old-demo": { |
| 1102 | "generation": 4, |
| 1103 | "enabled": false, |
| 1104 | "trust": null, |
| 1105 | "review_history": [{ |
| 1106 | "content_hash": "c", |
| 1107 | "capability_hash": "k", |
| 1108 | "reviewed_capabilities": codewhale_plugins::manifest::PluginInventory::default(), |
| 1109 | "reviewed_at": "2026-01-01T00:00:00+00:00" |
| 1110 | }] |
| 1111 | } |
| 1112 | } |
| 1113 | }); |
| 1114 | fs::write(&state_path, serde_json::to_vec_pretty(&stale).unwrap()).unwrap(); |
| 1115 | #[cfg(unix)] |
| 1116 | { |
| 1117 | use std::os::unix::fs::PermissionsExt as _; |
| 1118 | fs::set_permissions(&state_path, fs::Permissions::from_mode(0o600)).unwrap(); |
| 1119 | } |
| 1120 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 1121 | let (mut app, _temp) = create_test_app(root.path()); |
| 1122 | |
| 1123 | let report = plugins_with_kimi_home_override(&mut app, Some("doctor"), None); |
| 1124 | assert!(!report.is_error, "{report:?}"); |
| 1125 | let text = report.message.unwrap(); |
| 1126 | assert!(text.contains("nothing was changed"), "{text}"); |
| 1127 | // The renderer escapes markdown, so the hyphen arrives backslashed. |
| 1128 | assert!(text.contains("old\\-demo"), "{text}"); |
| 1129 | assert!(text.contains("/plugin doctor --fix"), "{text}"); |
| 1130 | assert!( |
| 1131 | fs::read_to_string(&state_path) |
| 1132 | .unwrap() |
| 1133 | .contains("old-demo"), |
| 1134 | "the report must not write" |
| 1135 | ); |
| 1136 | |
| 1137 | let fixed = plugins_with_kimi_home_override(&mut app, Some("doctor --fix"), None); |
| 1138 | assert!(!fixed.is_error, "{fixed:?}"); |
| 1139 | assert!( |
| 1140 | fixed |
| 1141 | .message |
| 1142 | .as_deref() |
| 1143 | .unwrap() |
| 1144 | .contains("Retired 1 records") |
| 1145 | ); |
| 1146 | assert!(matches!( |
| 1147 | fixed.action, |
| 1148 | Some(AppAction::PluginRegistryChanged) |
| 1149 | )); |
| 1150 | assert!( |
| 1151 | !fs::read_to_string(&state_path) |
| 1152 | .unwrap() |
| 1153 | .contains("old-demo") |
| 1154 | ); |
| 1155 | assert!( |
| 1156 | fs::read_to_string(plugins_dir.join("state.json.pre-gc")) |
| 1157 | .unwrap() |
| 1158 | .contains("old-demo"), |
| 1159 | "the previous state is kept" |
| 1160 | ); |
| 1161 | |
| 1162 | let usage = plugins_with_kimi_home_override(&mut app, Some("doctor --force"), None); |
| 1163 | assert!(usage.is_error); |
| 1164 | assert!(usage.message.unwrap().contains("Usage: /plugin doctor")); |
| 1165 | } |
| 1166 | |
| 1167 | #[derive(Default)] |
| 1168 | struct ScriptedConsole { |
| 1169 | interactive: bool, |
| 1170 | agent_marked: bool, |
| 1171 | provenance: Option<Result<headless::AgentRunProvenance, String>>, |
| 1172 | answer: bool, |
| 1173 | printed: Vec<String>, |
| 1174 | prompts: Vec<(String, usize)>, |
| 1175 | } |
| 1176 | |
| 1177 | impl headless::Console for ScriptedConsole { |
| 1178 | fn interactive(&self) -> bool { |
| 1179 | self.interactive |
| 1180 | } |
| 1181 | |
| 1182 | fn agent_marked(&self) -> bool { |
| 1183 | self.agent_marked |
| 1184 | } |
| 1185 | |
| 1186 | fn agent_provenance(&self) -> anyhow::Result<headless::AgentRunProvenance> { |
| 1187 | match &self.provenance { |
| 1188 | Some(Ok(provenance)) => Ok(provenance.clone()), |
| 1189 | Some(Err(message)) => Err(anyhow::anyhow!("{message}")), |
| 1190 | None => Ok(headless::AgentRunProvenance::default()), |
| 1191 | } |
| 1192 | } |
| 1193 | |
| 1194 | fn print(&mut self, text: &str) { |
| 1195 | self.printed.push(text.to_string()); |
| 1196 | } |
| 1197 | |
| 1198 | fn confirm(&mut self, prompt: &str) -> bool { |
| 1199 | self.prompts.push((prompt.to_string(), self.printed.len())); |
| 1200 | self.answer |
| 1201 | } |
| 1202 | } |
| 1203 | |
| 1204 | fn mark_installed_from(bundle: &Path, source: &Path) { |
| 1205 | fs::create_dir_all(source).unwrap(); |
| 1206 | fs::write( |
| 1207 | bundle.join(".installed-from"), |
| 1208 | serde_json::json!({ "spec": format!("path:{}", source.display()) }).to_string(), |
| 1209 | ) |
| 1210 | .unwrap(); |
| 1211 | } |
| 1212 | |
| 1213 | fn write_skill_bundle(root: &Path, name: &str, asks: &str) -> std::path::PathBuf { |
| 1214 | let bundle = root.join(".codewhale/plugins").join(name); |
| 1215 | fs::create_dir_all(bundle.join("skills/hello")).unwrap(); |
| 1216 | fs::write( |
| 1217 | bundle.join("plugin.toml"), |
| 1218 | format!( |
| 1219 | "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n{asks}" |
| 1220 | ), |
| 1221 | ) |
| 1222 | .unwrap(); |
| 1223 | fs::write( |
| 1224 | bundle.join("skills/hello/SKILL.md"), |
| 1225 | "---\nname: hello\ndescription: hi\n---\nbody\n", |
| 1226 | ) |
| 1227 | .unwrap(); |
| 1228 | bundle |
| 1229 | } |
| 1230 | |
| 1231 | fn headless_trust( |
| 1232 | registry: &mut std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 1233 | review_token: Option<&str>, |
| 1234 | yes: bool, |
| 1235 | json: bool, |
| 1236 | console: &mut ScriptedConsole, |
| 1237 | ) -> anyhow::Result<()> { |
| 1238 | headless_trust_named(registry, "review-mcp", review_token, yes, json, console) |
| 1239 | } |
| 1240 | |
| 1241 | fn headless_trust_named( |
| 1242 | registry: &mut std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 1243 | name: &str, |
| 1244 | review_token: Option<&str>, |
| 1245 | yes: bool, |
| 1246 | json: bool, |
| 1247 | console: &mut ScriptedConsole, |
| 1248 | ) -> anyhow::Result<()> { |
| 1249 | headless::trust( |
| 1250 | registry, |
| 1251 | Locale::En, |
| 1252 | headless::TrustRequest { |
| 1253 | name: name.to_string(), |
| 1254 | review_token: review_token.map(str::to_string), |
| 1255 | yes, |
| 1256 | json, |
| 1257 | }, |
| 1258 | console, |
| 1259 | ) |
| 1260 | } |
| 1261 | |
| 1262 | #[test] |
| 1263 | fn headless_review_is_the_terminal_review_and_a_terminal_asks_once() { |
| 1264 | let _lock = crate::test_support::lock_test_env(); |
| 1265 | let root = TempDir::new().unwrap(); |
| 1266 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 1267 | write_mcp_review_bundle(root.path()); |
| 1268 | let (mut app, _temp) = create_test_app(root.path()); |
| 1269 | let Some(AppAction::OpenCommandReview { content, .. }) = |
| 1270 | plugins_with_kimi_home_override(&mut app, Some("trust review-mcp"), None).action |
| 1271 | else { |
| 1272 | panic!("trust opens a confirmation control"); |
| 1273 | }; |
| 1274 | assert!(content.contains("Activation boundary:"), "{content}"); |
| 1275 | assert!(content.contains("timeouts="), "{content}"); |
| 1276 | let mut registry = app.plugin_registry.clone(); |
| 1277 | let token = registry.get("review-mcp").unwrap().review_token(); |
| 1278 | |
| 1279 | let mut piped = ScriptedConsole::default(); |
| 1280 | headless_trust(&mut registry, None, false, false, &mut piped).unwrap(); |
| 1281 | assert!(piped.prompts.is_empty()); |
| 1282 | assert!( |
| 1283 | piped.printed[0].starts_with(&content), |
| 1284 | "{:?}", |
| 1285 | piped.printed |
| 1286 | ); |
| 1287 | assert!(piped.printed[0].ends_with(&format!("Bundle review token: {token}"))); |
| 1288 | assert!(piped.printed[1].contains("does not record that anyone read")); |
| 1289 | assert!(!registry.get("review-mcp").unwrap().trusted()); |
| 1290 | |
| 1291 | let mut declined = ScriptedConsole { |
| 1292 | interactive: true, |
| 1293 | ..ScriptedConsole::default() |
| 1294 | }; |
| 1295 | headless_trust(&mut registry, None, false, false, &mut declined).unwrap(); |
| 1296 | assert_eq!(declined.prompts.len(), 1); |
| 1297 | assert!(!registry.get("review-mcp").unwrap().trusted()); |
| 1298 | |
| 1299 | let mut missing_yes = ScriptedConsole::default(); |
| 1300 | let error = headless_trust(&mut registry, Some(&token), false, false, &mut missing_yes) |
| 1301 | .unwrap_err() |
| 1302 | .to_string(); |
| 1303 | assert!(error.contains("--yes"), "{error}"); |
| 1304 | assert!(missing_yes.prompts.is_empty()); |
| 1305 | let mut json_never_prompts = ScriptedConsole { |
| 1306 | interactive: true, |
| 1307 | answer: true, |
| 1308 | ..ScriptedConsole::default() |
| 1309 | }; |
| 1310 | assert!( |
| 1311 | headless_trust( |
| 1312 | &mut registry, |
| 1313 | Some(&token), |
| 1314 | false, |
| 1315 | true, |
| 1316 | &mut json_never_prompts |
| 1317 | ) |
| 1318 | .is_err() |
| 1319 | ); |
| 1320 | assert!(json_never_prompts.prompts.is_empty()); |
| 1321 | assert!(!registry.get("review-mcp").unwrap().trusted()); |
| 1322 | |
| 1323 | let mut accepted = ScriptedConsole { |
| 1324 | interactive: true, |
| 1325 | answer: true, |
| 1326 | ..ScriptedConsole::default() |
| 1327 | }; |
| 1328 | headless_trust(&mut registry, None, false, false, &mut accepted).unwrap(); |
| 1329 | assert_eq!(accepted.prompts.len(), 1, "one question, one answer"); |
| 1330 | assert_eq!( |
| 1331 | accepted.prompts[0].1, 1, |
| 1332 | "the review is printed before the question" |
| 1333 | ); |
| 1334 | assert!(accepted.printed[0].starts_with(&content)); |
| 1335 | assert!(registry.get("review-mcp").unwrap().trusted()); |
| 1336 | assert!(!registry.get("review-mcp").unwrap().enabled); |
| 1337 | |
| 1338 | std::sync::Arc::make_mut(&mut registry) |
| 1339 | .revoke_trust("review-mcp") |
| 1340 | .unwrap(); |
| 1341 | let mut with_token = ScriptedConsole { |
| 1342 | interactive: true, |
| 1343 | answer: true, |
| 1344 | ..ScriptedConsole::default() |
| 1345 | }; |
| 1346 | headless_trust(&mut registry, Some(&token), false, false, &mut with_token).unwrap(); |
| 1347 | assert_eq!(with_token.prompts.len(), 1); |
| 1348 | assert_eq!( |
| 1349 | with_token.prompts[0].1, 1, |
| 1350 | "a token alone never hides the review" |
| 1351 | ); |
| 1352 | assert!(with_token.printed[0].starts_with(&content)); |
| 1353 | assert!(registry.get("review-mcp").unwrap().trusted()); |
| 1354 | } |
| 1355 | |
| 1356 | #[test] |
| 1357 | fn headless_trust_records_the_command_line_the_person_or_the_marked_agent() { |
| 1358 | use codewhale_plugins::host_services::{PersonVia, PluginApprover}; |
| 1359 | let _lock = crate::test_support::lock_test_env(); |
| 1360 | let root = TempDir::new().unwrap(); |
| 1361 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 1362 | write_mcp_review_bundle(root.path()); |
| 1363 | mark_installed_from( |
| 1364 | &root.path().join(".codewhale/plugins/review-mcp"), |
| 1365 | &root.path().join("src/review-mcp"), |
| 1366 | ); |
| 1367 | let (app, _temp) = create_test_app(root.path()); |
| 1368 | let mut registry = app.plugin_registry.clone(); |
| 1369 | let token = registry.get("review-mcp").unwrap().review_token(); |
| 1370 | let marked_agent = PluginApprover::command_line(Some(registry.workspace())); |
| 1371 | let approved_by = |registry: &codewhale_plugins::PluginRegistry| { |
| 1372 | registry.get("review-mcp").unwrap().approved_by.clone() |
| 1373 | }; |
| 1374 | let enabled_by = |registry: &codewhale_plugins::PluginRegistry| { |
| 1375 | registry.get("review-mcp").unwrap().enabled_by.clone() |
| 1376 | }; |
| 1377 | |
| 1378 | let mut unmarked = ScriptedConsole::default(); |
| 1379 | headless_trust(&mut registry, Some(&token), true, false, &mut unmarked).unwrap(); |
| 1380 | assert_eq!(approved_by(®istry), Some(PluginApprover::CommandLine)); |
| 1381 | assert!( |
| 1382 | unmarked |
| 1383 | .printed |
| 1384 | .iter() |
| 1385 | .any(|line| line.contains("trusted from the command line with --yes")), |
| 1386 | "{:?}", |
| 1387 | unmarked.printed |
| 1388 | ); |
| 1389 | headless::enable( |
| 1390 | &mut registry, |
| 1391 | Locale::En, |
| 1392 | "review-mcp", |
| 1393 | false, |
| 1394 | &mut unmarked, |
| 1395 | ) |
| 1396 | .unwrap(); |
| 1397 | assert_eq!(enabled_by(®istry), Some(PluginApprover::CommandLine)); |
| 1398 | |
| 1399 | let mut person = ScriptedConsole { |
| 1400 | interactive: true, |
| 1401 | answer: true, |
| 1402 | ..ScriptedConsole::default() |
| 1403 | }; |
| 1404 | headless_trust(&mut registry, None, false, false, &mut person).unwrap(); |
| 1405 | assert_eq!( |
| 1406 | approved_by(®istry), |
| 1407 | Some(PluginApprover::person(PersonVia::Terminal)) |
| 1408 | ); |
| 1409 | assert!(!registry.get("review-mcp").unwrap().enabled); |
| 1410 | |
| 1411 | headless::revoke( |
| 1412 | &mut registry, |
| 1413 | Locale::En, |
| 1414 | "review-mcp", |
| 1415 | false, |
| 1416 | &mut unmarked, |
| 1417 | ) |
| 1418 | .unwrap(); |
| 1419 | let marked = || ScriptedConsole { |
| 1420 | agent_marked: true, |
| 1421 | ..ScriptedConsole::default() |
| 1422 | }; |
| 1423 | let mut review = marked(); |
| 1424 | headless_trust(&mut registry, None, false, false, &mut review).unwrap(); |
| 1425 | assert!( |
| 1426 | review.printed[1].contains("approved by the agent from a shell command"), |
| 1427 | "{:?}", |
| 1428 | review.printed |
| 1429 | ); |
| 1430 | assert_eq!(approved_by(®istry), None); |
| 1431 | |
| 1432 | let mut agent = marked(); |
| 1433 | headless_trust(&mut registry, Some(&token), true, true, &mut agent).unwrap(); |
| 1434 | assert_eq!(approved_by(®istry), Some(marked_agent.clone())); |
| 1435 | assert!(agent.prompts.is_empty()); |
| 1436 | let reported: serde_json::Value = serde_json::from_str(&agent.printed[0]).unwrap(); |
| 1437 | assert_eq!(reported["approved_by"]["kind"], "agent"); |
| 1438 | assert_eq!(reported["approved_by"]["posture"], "command_line"); |
| 1439 | assert_eq!( |
| 1440 | reported["approved_by"]["workspace"], |
| 1441 | registry.workspace().to_string_lossy().as_ref() |
| 1442 | ); |
| 1443 | headless::enable(&mut registry, Locale::En, "review-mcp", false, &mut agent).unwrap(); |
| 1444 | assert_eq!(enabled_by(®istry), Some(marked_agent)); |
| 1445 | assert!(registry.get("review-mcp").unwrap().active()); |
| 1446 | |
| 1447 | headless::disable(&mut registry, Locale::En, "review-mcp", false, &mut agent).unwrap(); |
| 1448 | headless::revoke(&mut registry, Locale::En, "review-mcp", false, &mut agent).unwrap(); |
| 1449 | assert!(!registry.get("review-mcp").unwrap().trusted()); |
| 1450 | } |
| 1451 | |
| 1452 | #[test] |
| 1453 | fn headless_trust_passes_the_host_service_token_only_for_the_marked_agent() { |
| 1454 | use codewhale_plugins::host_services::{HostService, PluginApprover, TestOffer}; |
| 1455 | let _lock = crate::test_support::lock_test_env(); |
| 1456 | let _offer = TestOffer::only(&[HostService::Network]); |
| 1457 | let root = TempDir::new().unwrap(); |
| 1458 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 1459 | let bundle = write_skill_bundle( |
| 1460 | root.path(), |
| 1461 | "asks-network", |
| 1462 | "[capabilities]\nhost_services = [\"network\"]\n", |
| 1463 | ); |
| 1464 | mark_installed_from(&bundle, &root.path().join("src/asks-network")); |
| 1465 | let (app, _temp) = create_test_app(root.path()); |
| 1466 | let mut registry = app.plugin_registry.clone(); |
| 1467 | let plugin = registry.get("asks-network").unwrap(); |
| 1468 | assert_eq!(plugin.inventory.host_services, vec![HostService::Network]); |
| 1469 | let token = plugin.review_token(); |
| 1470 | let host_service_token = registry |
| 1471 | .host_service_review_for("asks-network", &PluginApprover::CommandLine) |
| 1472 | .unwrap() |
| 1473 | .token; |
| 1474 | assert_ne!(token, host_service_token); |
| 1475 | |
| 1476 | let mut unmarked = ScriptedConsole::default(); |
| 1477 | headless_trust_named( |
| 1478 | &mut registry, |
| 1479 | "asks-network", |
| 1480 | None, |
| 1481 | false, |
| 1482 | false, |
| 1483 | &mut unmarked, |
| 1484 | ) |
| 1485 | .unwrap(); |
| 1486 | let review = &unmarked.printed[0]; |
| 1487 | assert!(review.contains("Network"), "{review}"); |
| 1488 | assert!( |
| 1489 | review.contains("grants none of these host services"), |
| 1490 | "{review}" |
| 1491 | ); |
| 1492 | assert!( |
| 1493 | review.contains(&format!("Bundle review token: {token}")), |
| 1494 | "{review}" |
| 1495 | ); |
| 1496 | assert!(!review.contains(&host_service_token), "{review}"); |
| 1497 | |
| 1498 | headless_trust_named( |
| 1499 | &mut registry, |
| 1500 | "asks-network", |
| 1501 | Some(&token), |
| 1502 | true, |
| 1503 | false, |
| 1504 | &mut unmarked, |
| 1505 | ) |
| 1506 | .unwrap(); |
| 1507 | let plugin = registry.get("asks-network").unwrap(); |
| 1508 | assert_eq!(plugin.approved_by, Some(PluginApprover::CommandLine)); |
| 1509 | assert!(plugin.host_services.is_empty()); |
| 1510 | |
| 1511 | headless::revoke( |
| 1512 | &mut registry, |
| 1513 | Locale::En, |
| 1514 | "asks-network", |
| 1515 | false, |
| 1516 | &mut unmarked, |
| 1517 | ) |
| 1518 | .unwrap(); |
| 1519 | let mut marked = ScriptedConsole { |
| 1520 | agent_marked: true, |
| 1521 | ..ScriptedConsole::default() |
| 1522 | }; |
| 1523 | headless_trust_named( |
| 1524 | &mut registry, |
| 1525 | "asks-network", |
| 1526 | Some(&token), |
| 1527 | true, |
| 1528 | false, |
| 1529 | &mut marked, |
| 1530 | ) |
| 1531 | .unwrap(); |
| 1532 | let plugin = registry.get("asks-network").unwrap(); |
| 1533 | assert_eq!( |
| 1534 | plugin.approved_by, |
| 1535 | Some(PluginApprover::command_line(Some(registry.workspace()))) |
| 1536 | ); |
| 1537 | assert_eq!(plugin.host_services, vec![HostService::Network]); |
| 1538 | } |
| 1539 | |
| 1540 | #[test] |
| 1541 | fn headless_marked_trust_needs_an_install_from_a_folder_in_the_project() { |
| 1542 | use codewhale_plugins::host_services::PluginApprover; |
| 1543 | let _lock = crate::test_support::lock_test_env(); |
| 1544 | let root = TempDir::new().unwrap(); |
| 1545 | let elsewhere = TempDir::new().unwrap(); |
| 1546 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 1547 | write_skill_bundle(root.path(), "hand-placed", ""); |
| 1548 | let outside = write_skill_bundle(root.path(), "from-outside", ""); |
| 1549 | mark_installed_from(&outside, &elsewhere.path().join("src")); |
| 1550 | let remote = write_skill_bundle(root.path(), "from-github", ""); |
| 1551 | fs::write( |
| 1552 | remote.join(".installed-from"), |
| 1553 | r#"{"spec":"github:someone/plugin"}"#, |
| 1554 | ) |
| 1555 | .unwrap(); |
| 1556 | let inside = write_skill_bundle(root.path(), "from-inside", ""); |
| 1557 | mark_installed_from(&inside, &root.path().join("src/from-inside")); |
| 1558 | let (app, _temp) = create_test_app(root.path()); |
| 1559 | let mut registry = app.plugin_registry.clone(); |
| 1560 | let marked = || ScriptedConsole { |
| 1561 | agent_marked: true, |
| 1562 | interactive: true, |
| 1563 | answer: true, |
| 1564 | ..ScriptedConsole::default() |
| 1565 | }; |
| 1566 | |
| 1567 | for name in ["hand-placed", "from-outside", "from-github"] { |
| 1568 | let token = registry.get(name).unwrap().review_token(); |
| 1569 | for review_token in [Some(token.as_str()), None] { |
| 1570 | let error = headless_trust_named( |
| 1571 | &mut registry, |
| 1572 | name, |
| 1573 | review_token, |
| 1574 | review_token.is_some(), |
| 1575 | false, |
| 1576 | &mut marked(), |
| 1577 | ) |
| 1578 | .unwrap_err() |
| 1579 | .to_string(); |
| 1580 | assert!(error.contains("ask the person"), "{name}: {error}"); |
| 1581 | assert!(!registry.get(name).unwrap().trusted(), "{name}"); |
| 1582 | } |
| 1583 | headless_trust_named( |
| 1584 | &mut registry, |
| 1585 | name, |
| 1586 | Some(&token), |
| 1587 | true, |
| 1588 | false, |
| 1589 | &mut ScriptedConsole::default(), |
| 1590 | ) |
| 1591 | .unwrap(); |
| 1592 | assert_eq!( |
| 1593 | registry.get(name).unwrap().approved_by, |
| 1594 | Some(PluginApprover::CommandLine) |
| 1595 | ); |
| 1596 | } |
| 1597 | |
| 1598 | let token = registry.get("from-inside").unwrap().review_token(); |
| 1599 | headless_trust_named( |
| 1600 | &mut registry, |
| 1601 | "from-inside", |
| 1602 | Some(&token), |
| 1603 | true, |
| 1604 | false, |
| 1605 | &mut marked(), |
| 1606 | ) |
| 1607 | .unwrap(); |
| 1608 | assert_eq!( |
| 1609 | registry.get("from-inside").unwrap().approved_by, |
| 1610 | Some(PluginApprover::command_line(Some(registry.workspace()))) |
| 1611 | ); |
| 1612 | } |
| 1613 | |
| 1614 | fn install_temp_home_plugin( |
| 1615 | root: &Path, |
| 1616 | name: &str, |
| 1617 | version: &str, |
| 1618 | ) -> ( |
| 1619 | std::path::PathBuf, |
| 1620 | std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 1621 | ) { |
| 1622 | let source = root.join("src").join(name); |
| 1623 | fs::create_dir_all(source.join("skills/hello")).unwrap(); |
| 1624 | fs::write( |
| 1625 | source.join("plugin.toml"), |
| 1626 | format!( |
| 1627 | "schema_version = 1\n[plugin]\nname = {name:?}\nversion = {version:?}\n[skills]\npath = \"skills\"\n" |
| 1628 | ), |
| 1629 | ) |
| 1630 | .unwrap(); |
| 1631 | fs::write( |
| 1632 | source.join("skills/hello/SKILL.md"), |
| 1633 | "---\nname: hello\ndescription: hi\n---\nbody\n", |
| 1634 | ) |
| 1635 | .unwrap(); |
| 1636 | let (app, _temp) = create_test_app(root); |
| 1637 | let mut registry = app.plugin_registry.clone(); |
| 1638 | let network = codewhale_net::network_policy::NetworkPolicy::default(); |
| 1639 | let ctx = codewhale_plugins::mutation::PluginMutationContext { |
| 1640 | network: &network, |
| 1641 | max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES, |
| 1642 | }; |
| 1643 | let parsed = codewhale_plugins::install::PluginInstallSource::parse( |
| 1644 | source.to_str().expect("utf-8 path"), |
| 1645 | ) |
| 1646 | .unwrap(); |
| 1647 | tokio::runtime::Builder::new_current_thread() |
| 1648 | .enable_all() |
| 1649 | .build() |
| 1650 | .unwrap() |
| 1651 | .block_on(codewhale_plugins::mutation::execute( |
| 1652 | codewhale_plugins::mutation::PluginMutationRequest::Install { source: parsed }, |
| 1653 | &ctx, |
| 1654 | std::sync::Arc::make_mut(&mut registry), |
| 1655 | )) |
| 1656 | .unwrap(); |
| 1657 | let registry = registry.rediscover_for_workspace(registry.workspace()); |
| 1658 | (source, registry) |
| 1659 | } |
| 1660 | |
| 1661 | #[test] |
| 1662 | fn headless_show_prints_review_without_prompting_or_trusting() { |
| 1663 | let _lock = crate::test_support::lock_test_env(); |
| 1664 | let root = TempDir::new().unwrap(); |
| 1665 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 1666 | write_mcp_review_bundle(root.path()); |
| 1667 | let (mut app, _temp) = create_test_app(root.path()); |
| 1668 | let Some(AppAction::OpenCommandReview { content, .. }) = |
| 1669 | plugins_with_kimi_home_override(&mut app, Some("trust review-mcp"), None).action |
| 1670 | else { |
| 1671 | panic!("trust opens a confirmation control"); |
| 1672 | }; |
| 1673 | let registry = app.plugin_registry.clone(); |
| 1674 | let token = registry.get("review-mcp").unwrap().review_token(); |
| 1675 | |
| 1676 | let mut interactive = ScriptedConsole { |
| 1677 | interactive: true, |
| 1678 | answer: true, |
| 1679 | ..ScriptedConsole::default() |
| 1680 | }; |
| 1681 | headless::show(®istry, Locale::En, "review-mcp", false, &mut interactive).unwrap(); |
| 1682 | assert!(interactive.prompts.is_empty()); |
| 1683 | assert!(interactive.printed[0].starts_with(&content)); |
| 1684 | assert!(interactive.printed[0].ends_with(&format!("Bundle review token: {token}"))); |
| 1685 | assert!(!registry.get("review-mcp").unwrap().trusted()); |
| 1686 | |
| 1687 | let mut json_console = ScriptedConsole::default(); |
| 1688 | headless::show(®istry, Locale::En, "review-mcp", true, &mut json_console).unwrap(); |
| 1689 | let parsed: serde_json::Value = serde_json::from_str(&json_console.printed[0]).unwrap(); |
| 1690 | assert_eq!(parsed["action"], "review"); |
| 1691 | assert_eq!(parsed["trusted_by_this_command"], false); |
| 1692 | assert_eq!(parsed["bundle_review_token"], token); |
| 1693 | } |
| 1694 | |
| 1695 | #[test] |
| 1696 | fn headless_update_reports_current_or_new_version_and_network_approval() { |
| 1697 | let _lock = crate::test_support::lock_test_env(); |
| 1698 | let root = TempDir::new().unwrap(); |
| 1699 | let home = root.path().join("home"); |
| 1700 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 1701 | let (source, mut registry) = install_temp_home_plugin(root.path(), "demo", "1.0.0"); |
| 1702 | let network = codewhale_net::network_policy::NetworkPolicy::default(); |
| 1703 | |
| 1704 | let mut console = ScriptedConsole::default(); |
| 1705 | headless::update( |
| 1706 | &mut registry, |
| 1707 | Locale::En, |
| 1708 | "demo", |
| 1709 | &network, |
| 1710 | false, |
| 1711 | &mut console, |
| 1712 | ) |
| 1713 | .unwrap(); |
| 1714 | assert!( |
| 1715 | console.printed.last().unwrap().contains("already current"), |
| 1716 | "{:?}", |
| 1717 | console.printed |
| 1718 | ); |
| 1719 | |
| 1720 | fs::write( |
| 1721 | source.join("plugin.toml"), |
| 1722 | "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.1.0\"\n[skills]\npath = \"skills\"\n", |
| 1723 | ) |
| 1724 | .unwrap(); |
| 1725 | headless::update( |
| 1726 | &mut registry, |
| 1727 | Locale::En, |
| 1728 | "demo", |
| 1729 | &network, |
| 1730 | false, |
| 1731 | &mut console, |
| 1732 | ) |
| 1733 | .unwrap(); |
| 1734 | assert!( |
| 1735 | console.printed.last().unwrap().contains("updated to 1.1.0"), |
| 1736 | "{:?}", |
| 1737 | console.printed |
| 1738 | ); |
| 1739 | assert_eq!( |
| 1740 | registry.get("demo").unwrap().manifest.plugin.version, |
| 1741 | "1.1.0" |
| 1742 | ); |
| 1743 | |
| 1744 | fs::write( |
| 1745 | home.join("plugins/demo/.installed-from"), |
| 1746 | serde_json::json!({ |
| 1747 | "version": 2, |
| 1748 | "spec": "https://example.com/demo.tar.gz", |
| 1749 | "source_checksum": "", |
| 1750 | "content_hash": "", |
| 1751 | "plugin_name": "demo" |
| 1752 | }) |
| 1753 | .to_string(), |
| 1754 | ) |
| 1755 | .unwrap(); |
| 1756 | let err = headless::update( |
| 1757 | &mut registry, |
| 1758 | Locale::En, |
| 1759 | "demo", |
| 1760 | &network, |
| 1761 | false, |
| 1762 | &mut console, |
| 1763 | ) |
| 1764 | .unwrap_err() |
| 1765 | .to_string(); |
| 1766 | assert!( |
| 1767 | err.contains( |
| 1768 | "Network approval required for example.com; run `/network allow example.com` in the terminal UI, or add \"example.com\" to `allow` under [network] in config.toml, then retry" |
| 1769 | ), |
| 1770 | "{err}" |
| 1771 | ); |
| 1772 | } |
| 1773 | |
| 1774 | #[test] |
| 1775 | fn headless_uninstall_disables_enabled_plugin_first_and_removes_it() { |
| 1776 | let _lock = crate::test_support::lock_test_env(); |
| 1777 | let root = TempDir::new().unwrap(); |
| 1778 | let home = root.path().join("home"); |
| 1779 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 1780 | let (_source, mut registry) = install_temp_home_plugin(root.path(), "demo", "1.0.0"); |
| 1781 | let token = registry.get("demo").unwrap().review_token(); |
| 1782 | let mut console = ScriptedConsole::default(); |
| 1783 | headless_trust_named( |
| 1784 | &mut registry, |
| 1785 | "demo", |
| 1786 | Some(&token), |
| 1787 | true, |
| 1788 | false, |
| 1789 | &mut console, |
| 1790 | ) |
| 1791 | .unwrap(); |
| 1792 | headless::enable(&mut registry, Locale::En, "demo", false, &mut console).unwrap(); |
| 1793 | assert!(registry.get("demo").unwrap().enabled); |
| 1794 | let installed_dir = home.join("plugins/demo"); |
| 1795 | assert!(installed_dir.exists()); |
| 1796 | |
| 1797 | let piped_err = headless::uninstall( |
| 1798 | &mut registry, |
| 1799 | Locale::En, |
| 1800 | "demo", |
| 1801 | false, |
| 1802 | false, |
| 1803 | &mut console, |
| 1804 | ) |
| 1805 | .unwrap_err() |
| 1806 | .to_string(); |
| 1807 | assert!(piped_err.contains("--yes"), "{piped_err}"); |
| 1808 | assert!(installed_dir.exists()); |
| 1809 | |
| 1810 | let mut json_interactive = ScriptedConsole { |
| 1811 | interactive: true, |
| 1812 | answer: true, |
| 1813 | ..ScriptedConsole::default() |
| 1814 | }; |
| 1815 | let json_err = headless::uninstall( |
| 1816 | &mut registry, |
| 1817 | Locale::En, |
| 1818 | "demo", |
| 1819 | false, |
| 1820 | true, |
| 1821 | &mut json_interactive, |
| 1822 | ) |
| 1823 | .unwrap_err() |
| 1824 | .to_string(); |
| 1825 | assert!(json_err.contains("--yes"), "{json_err}"); |
| 1826 | assert!(json_interactive.prompts.is_empty()); |
| 1827 | assert!(installed_dir.exists()); |
| 1828 | |
| 1829 | let mut declined = ScriptedConsole { |
| 1830 | interactive: true, |
| 1831 | answer: false, |
| 1832 | ..ScriptedConsole::default() |
| 1833 | }; |
| 1834 | headless::uninstall( |
| 1835 | &mut registry, |
| 1836 | Locale::En, |
| 1837 | "demo", |
| 1838 | false, |
| 1839 | false, |
| 1840 | &mut declined, |
| 1841 | ) |
| 1842 | .unwrap(); |
| 1843 | assert_eq!(declined.prompts.len(), 1); |
| 1844 | assert_eq!(declined.prompts[0].0, "Remove demo 1.0.0?"); |
| 1845 | assert!(installed_dir.exists()); |
| 1846 | assert!(registry.get("demo").unwrap().enabled); |
| 1847 | |
| 1848 | let mut accepted = ScriptedConsole { |
| 1849 | interactive: true, |
| 1850 | answer: true, |
| 1851 | ..ScriptedConsole::default() |
| 1852 | }; |
| 1853 | headless::uninstall( |
| 1854 | &mut registry, |
| 1855 | Locale::En, |
| 1856 | "demo", |
| 1857 | false, |
| 1858 | false, |
| 1859 | &mut accepted, |
| 1860 | ) |
| 1861 | .unwrap(); |
| 1862 | assert_eq!(accepted.prompts.len(), 1); |
| 1863 | assert_eq!(accepted.prompts[0].0, "Remove demo 1.0.0?"); |
| 1864 | assert!(!installed_dir.exists()); |
| 1865 | let rediscovered = registry.rediscover_for_workspace(registry.workspace()); |
| 1866 | assert!(rediscovered.get("demo").is_none()); |
| 1867 | } |
| 1868 | |
| 1869 | #[test] |
| 1870 | fn headless_trust_and_enable_record_auto_review_posture_with_provenance() { |
| 1871 | use codewhale_plugins::host_services::{AgentPosture, PluginApprover}; |
| 1872 | let _lock = crate::test_support::lock_test_env(); |
| 1873 | let root = TempDir::new().unwrap(); |
| 1874 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 1875 | write_mcp_review_bundle(root.path()); |
| 1876 | mark_installed_from( |
| 1877 | &root.path().join(".codewhale/plugins/review-mcp"), |
| 1878 | &root.path().join("src/review-mcp"), |
| 1879 | ); |
| 1880 | let (app, _temp) = create_test_app(root.path()); |
| 1881 | let mut registry = app.plugin_registry.clone(); |
| 1882 | let token = registry.get("review-mcp").unwrap().review_token(); |
| 1883 | |
| 1884 | let provenance = headless::AgentRunProvenance { |
| 1885 | posture: Some(AgentPosture::AutoReview), |
| 1886 | thread_id: Some("thread-auto-1".to_string()), |
| 1887 | turn_id: Some("turn-auto-2".to_string()), |
| 1888 | tool_call_id: Some("call-auto-3".to_string()), |
| 1889 | }; |
| 1890 | let expected = PluginApprover::auto_review( |
| 1891 | registry.workspace(), |
| 1892 | Some("thread-auto-1".to_string()), |
| 1893 | Some("turn-auto-2".to_string()), |
| 1894 | Some("call-auto-3".to_string()), |
| 1895 | ); |
| 1896 | |
| 1897 | let mut review = ScriptedConsole { |
| 1898 | agent_marked: true, |
| 1899 | provenance: Some(Ok(provenance.clone())), |
| 1900 | ..ScriptedConsole::default() |
| 1901 | }; |
| 1902 | headless_trust(&mut registry, None, false, false, &mut review).unwrap(); |
| 1903 | assert!( |
| 1904 | review.printed[1].contains("approved by the agent in Auto-Review"), |
| 1905 | "{:?}", |
| 1906 | review.printed |
| 1907 | ); |
| 1908 | |
| 1909 | let mut trust_console = ScriptedConsole { |
| 1910 | agent_marked: true, |
| 1911 | provenance: Some(Ok(provenance)), |
| 1912 | ..ScriptedConsole::default() |
| 1913 | }; |
| 1914 | headless_trust(&mut registry, Some(&token), true, true, &mut trust_console).unwrap(); |
| 1915 | assert_eq!( |
| 1916 | registry.get("review-mcp").unwrap().approved_by, |
| 1917 | Some(expected.clone()) |
| 1918 | ); |
| 1919 | let reported: serde_json::Value = serde_json::from_str(&trust_console.printed[0]).unwrap(); |
| 1920 | assert_eq!(reported["approved_by"]["kind"], "agent"); |
| 1921 | assert_eq!(reported["approved_by"]["posture"], "auto_review"); |
| 1922 | assert_eq!(reported["approved_by"]["thread_id"], "thread-auto-1"); |
| 1923 | assert_eq!(reported["approved_by"]["turn_id"], "turn-auto-2"); |
| 1924 | assert_eq!(reported["approved_by"]["tool_call_id"], "call-auto-3"); |
| 1925 | |
| 1926 | headless::enable( |
| 1927 | &mut registry, |
| 1928 | Locale::En, |
| 1929 | "review-mcp", |
| 1930 | false, |
| 1931 | &mut trust_console, |
| 1932 | ) |
| 1933 | .unwrap(); |
| 1934 | assert_eq!( |
| 1935 | registry.get("review-mcp").unwrap().enabled_by, |
| 1936 | Some(expected) |
| 1937 | ); |
| 1938 | |
| 1939 | let mut missing_ids = ScriptedConsole { |
| 1940 | agent_marked: true, |
| 1941 | provenance: Some(Ok(headless::AgentRunProvenance { |
| 1942 | posture: Some(AgentPosture::AutoReview), |
| 1943 | thread_id: Some("thread-auto-1".to_string()), |
| 1944 | turn_id: None, |
| 1945 | tool_call_id: Some("call-auto-3".to_string()), |
| 1946 | })), |
| 1947 | ..ScriptedConsole::default() |
| 1948 | }; |
| 1949 | let err = headless::enable( |
| 1950 | &mut registry, |
| 1951 | Locale::En, |
| 1952 | "review-mcp", |
| 1953 | false, |
| 1954 | &mut missing_ids, |
| 1955 | ) |
| 1956 | .unwrap_err(); |
| 1957 | assert!( |
| 1958 | err.to_string().contains("thread, turn and tool call"), |
| 1959 | "{err:#}" |
| 1960 | ); |
| 1961 | |
| 1962 | let mut invalid_posture = ScriptedConsole { |
| 1963 | agent_marked: true, |
| 1964 | provenance: Some(Ok(headless::AgentRunProvenance { |
| 1965 | posture: Some(AgentPosture::FullAccess), |
| 1966 | ..headless::AgentRunProvenance::default() |
| 1967 | })), |
| 1968 | ..ScriptedConsole::default() |
| 1969 | }; |
| 1970 | let posture_err = headless_trust( |
| 1971 | &mut registry, |
| 1972 | Some(&token), |
| 1973 | true, |
| 1974 | false, |
| 1975 | &mut invalid_posture, |
| 1976 | ) |
| 1977 | .unwrap_err(); |
| 1978 | assert!( |
| 1979 | posture_err.to_string().contains("full_access"), |
| 1980 | "{posture_err:#}" |
| 1981 | ); |
| 1982 | } |
| 1983 | |
| 1984 | #[cfg(test)] |
| 1985 | fn user_message(text: &str) -> codewhale_models::Message { |
| 1986 | codewhale_models::Message { |
| 1987 | role: codewhale_models::Role::User, |
| 1988 | content: vec![codewhale_models::ContentBlock::Text { |
| 1989 | text: text.to_string(), |
| 1990 | cache_control: None, |
| 1991 | }], |
| 1992 | } |
| 1993 | } |
| 1994 | |
| 1995 | #[cfg(test)] |
| 1996 | fn fixture_snapshot( |
| 1997 | app: &App, |
| 1998 | session_id: &str, |
| 1999 | source: Option<codewhale_engine::core::ops::SessionSnapshotSource>, |
| 2000 | ) -> codewhale_engine::core::ops::SessionSnapshot { |
| 2001 | let identity = app.admitted_provider_identity().unwrap(); |
| 2002 | codewhale_engine::core::ops::SessionSnapshot { |
| 2003 | source, |
| 2004 | session_id: session_id.to_string(), |
| 2005 | messages: Vec::new(), |
| 2006 | total_tokens: 0, |
| 2007 | model: app.model.clone(), |
| 2008 | model_provider: identity.persisted_kind().to_string(), |
| 2009 | model_provider_id: identity.persisted_id().map(str::to_string), |
| 2010 | workspace: app.workspace.clone(), |
| 2011 | system_prompt: None, |
| 2012 | instruction_assembly: None, |
| 2013 | mode: app.mode.as_setting().to_string(), |
| 2014 | agent_preset: app.agent_preset(), |
| 2015 | } |
| 2016 | } |
| 2017 | |
| 2018 | #[test] |
| 2019 | fn plugin_create_starts_a_creator_conversation_with_the_idea_as_a_draft() { |
| 2020 | use crate::tui::widgets::Renderable; |
| 2021 | use codewhale_engine::conversation_modes::CreatorAvailabilityGuard; |
| 2022 | use codewhale_engine::core::ops::{Op, SessionSnapshotSource}; |
| 2023 | use ratatui::{buffer::Buffer, layout::Rect}; |
| 2024 | |
| 2025 | let _available = CreatorAvailabilityGuard::set(None); |
| 2026 | let _home = crate::test_support::SealedHome::new(); |
| 2027 | let root = TempDir::new().unwrap(); |
| 2028 | let (mut app, _temp) = create_test_app(root.path()); |
| 2029 | app.current_session_id = Some("old-session".to_string()); |
| 2030 | app.capture_session_fixture_source(); |
| 2031 | app.push_api_message(user_message("earlier turn")); |
| 2032 | |
| 2033 | let idea = " first line with two spaces\r\nsecond line "; |
| 2034 | let result = crate::commands::execute_with_config( |
| 2035 | &format!("/plugin create {idea}"), |
| 2036 | &mut app, |
| 2037 | &Config::default(), |
| 2038 | ); |
| 2039 | assert!(!result.is_error, "{:?}", result.message); |
| 2040 | match result.action.as_ref() { |
| 2041 | Some(AppAction::NewSession { |
| 2042 | sync, |
| 2043 | force: false, |
| 2044 | draft: Some(draft), |
| 2045 | }) => { |
| 2046 | assert_eq!(sync.agent_preset.as_deref(), Some("creator")); |
| 2047 | assert_eq!(draft, idea); |
| 2048 | } |
| 2049 | other => panic!("expected NewSession, got {other:?}"), |
| 2050 | } |
| 2051 | assert_eq!(app.conversation_mode, None); |
| 2052 | assert_eq!(app.current_session_id.as_deref(), Some("old-session")); |
| 2053 | assert!(app.input.is_empty()); |
| 2054 | |
| 2055 | let rt = tokio::runtime::Builder::new_current_thread() |
| 2056 | .enable_all() |
| 2057 | .build() |
| 2058 | .unwrap(); |
| 2059 | rt.block_on( |
| 2060 | crate::commands::session_lifecycle_regression_tests::acknowledge_new_session( |
| 2061 | &mut app, &result, |
| 2062 | ), |
| 2063 | ); |
| 2064 | assert_eq!(app.conversation_mode.as_deref(), Some("creator")); |
| 2065 | assert_eq!(app.agent_preset().as_deref(), Some("creator")); |
| 2066 | assert_eq!(app.input, idea); |
| 2067 | assert_eq!(app.cursor_position, idea.chars().count()); |
| 2068 | assert!(!app.line_began_with_slash); |
| 2069 | assert!(app.api_messages.is_empty()); |
| 2070 | assert!(app.queued_messages.is_empty()); |
| 2071 | |
| 2072 | let area = Rect::new(0, 0, 60, 8); |
| 2073 | let mut buf = Buffer::empty(area); |
| 2074 | crate::tui::widgets::ComposerWidget::new(&app, area.height, &[], &[]).render(area, &mut buf); |
| 2075 | let rendered = (0..area.height) |
| 2076 | .map(|y| { |
| 2077 | (0..area.width) |
| 2078 | .map(|x| buf[(x, y)].symbol()) |
| 2079 | .collect::<String>() |
| 2080 | }) |
| 2081 | .collect::<Vec<_>>() |
| 2082 | .join("\n"); |
| 2083 | assert!(rendered.contains("first line"), "{rendered}"); |
| 2084 | assert!(rendered.contains("second line"), "{rendered}"); |
| 2085 | assert!(!rendered.contains("Use the "), "{rendered}"); |
| 2086 | |
| 2087 | let (mut special_app, _special_temp) = create_test_app(root.path()); |
| 2088 | special_app.current_session_id = Some("old-session-2".to_string()); |
| 2089 | special_app.capture_session_fixture_source(); |
| 2090 | let special_idea = format!("{}\u{0003}\u{001b}[31mtail", "a".repeat(2048)); |
| 2091 | let special_result = crate::commands::execute_with_config( |
| 2092 | &format!("/plugin create {special_idea}"), |
| 2093 | &mut special_app, |
| 2094 | &Config::default(), |
| 2095 | ); |
| 2096 | assert!(!special_result.is_error, "{:?}", special_result.message); |
| 2097 | let Some(AppAction::NewSession { |
| 2098 | sync, |
| 2099 | force, |
| 2100 | draft: Some(special_draft), |
| 2101 | }) = special_result.action |
| 2102 | else { |
| 2103 | panic!("expected NewSession with special draft"); |
| 2104 | }; |
| 2105 | assert_eq!(special_draft, special_idea); |
| 2106 | |
| 2107 | let initial_source = SessionSnapshotSource::control(special_app.session_sync_control()); |
| 2108 | let mut engine = codewhale_engine::core::engine::mock_engine_handle(); |
| 2109 | crate::tui::ui::begin_fresh_session( |
| 2110 | &mut special_app, |
| 2111 | &engine.handle, |
| 2112 | sync.clone(), |
| 2113 | force, |
| 2114 | Some(special_draft), |
| 2115 | ) |
| 2116 | .unwrap(); |
| 2117 | assert!(!crate::tui::ui::poll_fresh_session( |
| 2118 | &mut special_app, |
| 2119 | &engine.handle |
| 2120 | )); |
| 2121 | let mut observed_ops = Vec::new(); |
| 2122 | while let Ok(op) = engine.rx_op.try_recv() { |
| 2123 | match op { |
| 2124 | Op::GetSessionSnapshot { tx } => { |
| 2125 | observed_ops.push("GetSessionSnapshot"); |
| 2126 | let snapshot = |
| 2127 | fixture_snapshot(&special_app, "old-session-2", Some(initial_source.clone())); |
| 2128 | let _ = tx.lock().unwrap().take().unwrap().send(snapshot); |
| 2129 | } |
| 2130 | Op::SyncSession { .. } => observed_ops.push("SyncSession"), |
| 2131 | Op::SendMessage(_) | Op::Review { .. } | Op::ContinueGoal { .. } => { |
| 2132 | observed_ops.push("Turn"); |
| 2133 | } |
| 2134 | _ => observed_ops.push("Other"), |
| 2135 | } |
| 2136 | } |
| 2137 | assert_eq!(observed_ops, vec!["GetSessionSnapshot"]); |
| 2138 | assert!(!crate::tui::ui::poll_fresh_session( |
| 2139 | &mut special_app, |
| 2140 | &engine.handle |
| 2141 | )); |
| 2142 | while let Ok(op) = engine.rx_op.try_recv() { |
| 2143 | match op { |
| 2144 | Op::SyncSession { |
| 2145 | control, |
| 2146 | agent_preset, |
| 2147 | .. |
| 2148 | } => { |
| 2149 | observed_ops.push("SyncSession"); |
| 2150 | assert_eq!(agent_preset.as_deref(), Some("creator")); |
| 2151 | let expected_workspace = special_app.workspace.clone(); |
| 2152 | let expected_model = special_app.model.clone(); |
| 2153 | let ack = crate::tui::ui::acknowledge_fresh_session( |
| 2154 | &mut special_app, |
| 2155 | sync.session_id.as_deref().unwrap(), |
| 2156 | Some(&SessionSnapshotSource::control(control)), |
| 2157 | &expected_workspace, |
| 2158 | &expected_model, |
| 2159 | ); |
| 2160 | assert!(ack); |
| 2161 | } |
| 2162 | Op::GetSessionSnapshot { tx } => { |
| 2163 | observed_ops.push("GetSessionSnapshotAck"); |
| 2164 | drop(tx); |
| 2165 | } |
| 2166 | Op::SendMessage(_) | Op::Review { .. } | Op::ContinueGoal { .. } => { |
| 2167 | observed_ops.push("Turn"); |
| 2168 | } |
| 2169 | _ => observed_ops.push("Other"), |
| 2170 | } |
| 2171 | } |
| 2172 | assert_eq!( |
| 2173 | observed_ops, |
| 2174 | vec!["GetSessionSnapshot", "SyncSession", "GetSessionSnapshotAck"] |
| 2175 | ); |
| 2176 | assert!(!observed_ops.contains(&"Turn")); |
| 2177 | assert_eq!(special_app.input, special_idea); |
| 2178 | assert_eq!(special_app.conversation_mode.as_deref(), Some("creator")); |
| 2179 | |
| 2180 | let mut special_buf = Buffer::empty(area); |
| 2181 | crate::tui::widgets::ComposerWidget::new(&special_app, area.height, &[], &[]) |
| 2182 | .render(area, &mut special_buf); |
| 2183 | } |
| 2184 | |
| 2185 | #[test] |
| 2186 | fn plugin_create_without_an_idea_starts_creator_with_an_empty_composer() { |
| 2187 | use codewhale_engine::conversation_modes::CreatorAvailabilityGuard; |
| 2188 | |
| 2189 | let rt = tokio::runtime::Builder::new_current_thread() |
| 2190 | .enable_all() |
| 2191 | .build() |
| 2192 | .unwrap(); |
| 2193 | let _available = CreatorAvailabilityGuard::set(None); |
| 2194 | let _home = crate::test_support::SealedHome::new(); |
| 2195 | let root = TempDir::new().unwrap(); |
| 2196 | |
| 2197 | for cmd in ["/plugin create", "/plugin create \t\r\n"] { |
| 2198 | let (mut app, _temp) = create_test_app(root.path()); |
| 2199 | app.current_session_id = Some("old-session".to_string()); |
| 2200 | app.capture_session_fixture_source(); |
| 2201 | |
| 2202 | let result = crate::commands::execute_with_config(cmd, &mut app, &Config::default()); |
| 2203 | assert!(!result.is_error, "{:?}", result.message); |
| 2204 | match result.action.as_ref() { |
| 2205 | Some(AppAction::NewSession { |
| 2206 | sync, |
| 2207 | force: false, |
| 2208 | draft: None, |
| 2209 | }) => assert_eq!(sync.agent_preset.as_deref(), Some("creator")), |
| 2210 | other => panic!("expected empty-draft NewSession for {cmd:?}, got {other:?}"), |
| 2211 | } |
| 2212 | |
| 2213 | rt.block_on( |
| 2214 | crate::commands::session_lifecycle_regression_tests::acknowledge_new_session( |
| 2215 | &mut app, &result, |
| 2216 | ), |
| 2217 | ); |
| 2218 | assert_eq!(app.conversation_mode.as_deref(), Some("creator")); |
| 2219 | assert!(app.input.is_empty()); |
| 2220 | assert_eq!(app.cursor_position, 0); |
| 2221 | assert!(app.api_messages.is_empty()); |
| 2222 | } |
| 2223 | } |
| 2224 | |
| 2225 | #[test] |
| 2226 | fn plugin_create_says_why_when_creator_is_unavailable_and_changes_nothing() { |
| 2227 | use codewhale_engine::conversation_modes::{CREATOR_KEY_OFF_REASON, CreatorAvailabilityGuard}; |
| 2228 | |
| 2229 | let _home = crate::test_support::SealedHome::new(); |
| 2230 | let root = TempDir::new().unwrap(); |
| 2231 | |
| 2232 | for (forced_reason, expected_substring) in [ |
| 2233 | (CREATOR_KEY_OFF_REASON, CREATOR_KEY_OFF_REASON), |
| 2234 | ( |
| 2235 | "No plugin runtime was found.", |
| 2236 | "No plugin runtime was found.", |
| 2237 | ), |
| 2238 | ] { |
| 2239 | let _guard = CreatorAvailabilityGuard::set(Some(forced_reason)); |
| 2240 | let (mut app, _temp) = create_test_app(root.path()); |
| 2241 | app.current_session_id = Some("old-session".to_string()); |
| 2242 | app.push_api_message(user_message("keep this")); |
| 2243 | app.ui_locale = Locale::En; |
| 2244 | let expected = crate::tui::conversation_mode::unavailable_message( |
| 2245 | app.ui_locale, |
| 2246 | "Creator mode", |
| 2247 | &crate::tui::conversation_mode::display_reason(app.ui_locale, Some(forced_reason)), |
| 2248 | ); |
| 2249 | |
| 2250 | let result = crate::commands::execute_with_config( |
| 2251 | "/plugin create a word counter", |
| 2252 | &mut app, |
| 2253 | &Config::default(), |
| 2254 | ); |
| 2255 | assert!(result.is_error); |
| 2256 | assert!(result.action.is_none()); |
| 2257 | let msg = result.message.unwrap(); |
| 2258 | assert_eq!(msg, format!("Error: {expected}")); |
| 2259 | assert!(msg.contains(expected_substring), "{msg}"); |
| 2260 | assert_eq!(app.current_session_id.as_deref(), Some("old-session")); |
| 2261 | assert_eq!(app.conversation_mode, None); |
| 2262 | assert_eq!(app.api_messages.len(), 1); |
| 2263 | assert!(app.input.is_empty()); |
| 2264 | } |
| 2265 | } |
| 2266 | |
| 2267 | #[test] |
| 2268 | fn plugin_create_is_blocked_like_new_while_messages_are_queued() { |
| 2269 | use codewhale_engine::conversation_modes::CreatorAvailabilityGuard; |
| 2270 | |
| 2271 | let _available = CreatorAvailabilityGuard::set(None); |
| 2272 | let _home = crate::test_support::SealedHome::new(); |
| 2273 | let root = TempDir::new().unwrap(); |
| 2274 | let (mut app, _temp) = create_test_app(root.path()); |
| 2275 | app.current_session_id = Some("old-session".to_string()); |
| 2276 | app.queued_messages |
| 2277 | .push_back(crate::tui::app::QueuedMessage::new( |
| 2278 | "wait for me".to_string(), |
| 2279 | None, |
| 2280 | )); |
| 2281 | |
| 2282 | let plugin_result = crate::commands::execute_with_config( |
| 2283 | "/plugin create queued blocker", |
| 2284 | &mut app, |
| 2285 | &Config::default(), |
| 2286 | ); |
| 2287 | let new_result = |
| 2288 | crate::commands::execute_with_config("/new creator", &mut app, &Config::default()); |
| 2289 | |
| 2290 | assert!(plugin_result.is_error); |
| 2291 | assert!(plugin_result.action.is_none()); |
| 2292 | assert_eq!(plugin_result.message, new_result.message); |
| 2293 | assert_eq!(app.current_session_id.as_deref(), Some("old-session")); |
| 2294 | assert_eq!(app.conversation_mode, None); |
| 2295 | assert_eq!(app.queued_messages.len(), 1); |
| 2296 | assert!(app.input.is_empty()); |
| 2297 | } |
| 2298 | |
| 2299 | #[test] |
| 2300 | fn plugin_named_create_is_still_shown_by_plugin_show() { |
| 2301 | let _lock = crate::test_support::lock_test_env(); |
| 2302 | let root = TempDir::new().unwrap(); |
| 2303 | let codewhale_home = root.path().join("home"); |
| 2304 | fs::create_dir_all(&codewhale_home).unwrap(); |
| 2305 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 2306 | |
| 2307 | let bundle = root.path().join(".codewhale/plugins/create"); |
| 2308 | fs::create_dir_all(bundle.join("skills/hello")).unwrap(); |
| 2309 | fs::write( |
| 2310 | bundle.join("plugin.toml"), |
| 2311 | "schema_version = 1\n[plugin]\nname = \"create\"\nversion = \"2.3.4\"\ndescription = \"Literal create bundle\"\n[skills]\npath = \"skills\"\n", |
| 2312 | ) |
| 2313 | .unwrap(); |
| 2314 | fs::write( |
| 2315 | bundle.join("skills/hello/SKILL.md"), |
| 2316 | "---\nname: hello\ndescription: hello\n---\nbody\n", |
| 2317 | ) |
| 2318 | .unwrap(); |
| 2319 | fs::create_dir_all(root.path().join("tools")).unwrap(); |
| 2320 | fs::write( |
| 2321 | root.path().join("tools/create.sh"), |
| 2322 | "# name: create\n# description: Legacy create script tool\n", |
| 2323 | ) |
| 2324 | .unwrap(); |
| 2325 | |
| 2326 | let (mut app, _temp) = create_test_app(root.path()); |
| 2327 | app.current_session_id = Some("old-session".to_string()); |
| 2328 | |
| 2329 | let shown = |
| 2330 | crate::commands::execute_with_config("/plugin show create", &mut app, &Config::default()); |
| 2331 | assert!(!shown.is_error, "{:?}", shown.message); |
| 2332 | assert!(shown.action.is_none()); |
| 2333 | let shown_msg = shown.message.unwrap(); |
| 2334 | assert!(shown_msg.contains("create"), "{shown_msg}"); |
| 2335 | assert!( |
| 2336 | shown_msg.contains("Qualified skills: [create:hello]"), |
| 2337 | "{shown_msg}" |
| 2338 | ); |
| 2339 | assert_eq!(app.conversation_mode, None); |
| 2340 | |
| 2341 | let tool = |
| 2342 | crate::commands::execute_with_config("/plugin tools create", &mut app, &Config::default()); |
| 2343 | assert!(!tool.is_error, "{:?}", tool.message); |
| 2344 | assert!(tool.action.is_none()); |
| 2345 | let tool_msg = tool.message.unwrap(); |
| 2346 | assert!(tool_msg.contains("Legacy create script tool"), "{tool_msg}"); |
| 2347 | assert_eq!(app.conversation_mode, None); |
| 2348 | } |
| 2349 | |
| 2350 | #[test] |
| 2351 | fn plugin_help_lists_create() { |
| 2352 | let _lock = crate::test_support::lock_test_env(); |
| 2353 | let root = TempDir::new().unwrap(); |
| 2354 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 2355 | let (mut app, _temp) = create_test_app(root.path()); |
| 2356 | |
| 2357 | let localized_usage = codewhale_localization::tr( |
| 2358 | Locale::En, |
| 2359 | codewhale_localization::MessageId::CmdPluginBundleUsage, |
| 2360 | ); |
| 2361 | assert!( |
| 2362 | localized_usage.contains("create [idea]"), |
| 2363 | "{localized_usage}" |
| 2364 | ); |
| 2365 | |
| 2366 | let help = crate::commands::execute_with_config("/plugin help", &mut app, &Config::default()); |
| 2367 | assert!(!help.is_error, "{:?}", help.message); |
| 2368 | let help_msg = help.message.unwrap(); |
| 2369 | assert!(help_msg.contains("/plugin create [idea]"), "{help_msg}"); |
| 2370 | assert!(help_msg.contains("create [idea]"), "{help_msg}"); |
| 2371 | |
| 2372 | assert!( |
| 2373 | PLUGINS_INFO.usage.contains("create"), |
| 2374 | "{}", |
| 2375 | PLUGINS_INFO.usage |
| 2376 | ); |
| 2377 | } |
| 2378 | |
| 2379 | #[test] |
| 2380 | fn plugin_create_and_new_creator_give_the_same_refusal() { |
| 2381 | use codewhale_engine::conversation_modes::{CREATOR_KEY_OFF_REASON, CreatorAvailabilityGuard}; |
| 2382 | |
| 2383 | let _home = crate::test_support::SealedHome::new(); |
| 2384 | let root = TempDir::new().unwrap(); |
| 2385 | |
| 2386 | for reason in [CREATOR_KEY_OFF_REASON, "No plugin runtime was found."] { |
| 2387 | let _guard = CreatorAvailabilityGuard::set(Some(reason)); |
| 2388 | let (mut app, _temp) = create_test_app(root.path()); |
| 2389 | app.current_session_id = Some("old-session".to_string()); |
| 2390 | |
| 2391 | let via_plugin = crate::commands::execute_with_config( |
| 2392 | "/plugin create a word counter", |
| 2393 | &mut app, |
| 2394 | &Config::default(), |
| 2395 | ); |
| 2396 | let via_new = |
| 2397 | crate::commands::execute_with_config("/new creator", &mut app, &Config::default()); |
| 2398 | |
| 2399 | assert!(via_plugin.is_error); |
| 2400 | assert!(via_new.is_error); |
| 2401 | assert!(via_plugin.action.is_none()); |
| 2402 | assert!(via_new.action.is_none()); |
| 2403 | assert_eq!(via_plugin.message, via_new.message); |
| 2404 | assert_eq!(app.current_session_id.as_deref(), Some("old-session")); |
| 2405 | assert_eq!(app.conversation_mode, None); |
| 2406 | } |
| 2407 | } |
| 2408 | |
| 2409 | #[test] |
| 2410 | fn a_failed_fresh_session_drops_the_draft_and_restores_the_earlier_input() { |
| 2411 | use codewhale_engine::conversation_modes::CreatorAvailabilityGuard; |
| 2412 | use codewhale_engine::core::ops::{Op, SessionSnapshotSource}; |
| 2413 | |
| 2414 | let _available = CreatorAvailabilityGuard::set(None); |
| 2415 | let _home = crate::test_support::SealedHome::new(); |
| 2416 | let root = TempDir::new().unwrap(); |
| 2417 | let (mut app, _temp) = create_test_app(root.path()); |
| 2418 | app.current_session_id = Some("old-session".to_string()); |
| 2419 | app.capture_session_fixture_source(); |
| 2420 | app.input = "earlier composer draft".to_string(); |
| 2421 | app.cursor_position = app.input.chars().count(); |
| 2422 | |
| 2423 | let blocked = crate::commands::execute_with_config( |
| 2424 | "/plugin create ignored draft", |
| 2425 | &mut app, |
| 2426 | &Config::default(), |
| 2427 | ); |
| 2428 | assert!(blocked.is_error); |
| 2429 | assert!(blocked.action.is_none()); |
| 2430 | assert_eq!(app.input, "earlier composer draft"); |
| 2431 | |
| 2432 | app.input = " ".to_string(); |
| 2433 | app.cursor_position = 3; |
| 2434 | let queued = crate::commands::execute_with_config( |
| 2435 | "/plugin create candidate draft", |
| 2436 | &mut app, |
| 2437 | &Config::default(), |
| 2438 | ); |
| 2439 | assert!(!queued.is_error, "{:?}", queued.message); |
| 2440 | let Some(AppAction::NewSession { |
| 2441 | sync, |
| 2442 | force, |
| 2443 | draft: Some(draft), |
| 2444 | }) = queued.action |
| 2445 | else { |
| 2446 | panic!("expected NewSession with candidate draft"); |
| 2447 | }; |
| 2448 | |
| 2449 | let initial_source = SessionSnapshotSource::control(app.session_sync_control()); |
| 2450 | let mut engine = codewhale_engine::core::engine::mock_engine_handle(); |
| 2451 | crate::tui::ui::begin_fresh_session(&mut app, &engine.handle, sync, force, Some(draft)) |
| 2452 | .unwrap(); |
| 2453 | app.input = "earlier composer draft".to_string(); |
| 2454 | app.cursor_position = app.input.chars().count(); |
| 2455 | |
| 2456 | assert!(!crate::tui::ui::poll_fresh_session( |
| 2457 | &mut app, |
| 2458 | &engine.handle |
| 2459 | )); |
| 2460 | match engine.rx_op.try_recv().expect("snapshot inspection op") { |
| 2461 | Op::GetSessionSnapshot { tx } => { |
| 2462 | let snapshot = fixture_snapshot(&app, "old-session", Some(initial_source)); |
| 2463 | let _ = tx.lock().unwrap().take().unwrap().send(snapshot); |
| 2464 | } |
| 2465 | other => panic!("unexpected op {other:?}"), |
| 2466 | } |
| 2467 | assert!(!crate::tui::ui::poll_fresh_session( |
| 2468 | &mut app, |
| 2469 | &engine.handle |
| 2470 | )); |
| 2471 | match engine.rx_op.try_recv().expect("sync session op") { |
| 2472 | Op::SyncSession { .. } => {} |
| 2473 | other => panic!("unexpected op {other:?}"), |
| 2474 | } |
| 2475 | match engine.rx_op.try_recv().expect("ack snapshot op") { |
| 2476 | Op::GetSessionSnapshot { tx } => { |
| 2477 | let mismatched = fixture_snapshot(&app, "mismatched-session", None); |
| 2478 | let _ = tx.lock().unwrap().take().unwrap().send(mismatched); |
| 2479 | } |
| 2480 | other => panic!("unexpected op {other:?}"), |
| 2481 | } |
| 2482 | |
| 2483 | assert!(!crate::tui::ui::poll_fresh_session( |
| 2484 | &mut app, |
| 2485 | &engine.handle |
| 2486 | )); |
| 2487 | assert!( |
| 2488 | app.pending_fresh_session |
| 2489 | .as_ref() |
| 2490 | .is_none_or(|p| p.draft.is_none()) |
| 2491 | ); |
| 2492 | assert_eq!(app.input, "earlier composer draft"); |
| 2493 | assert_ne!(app.input, "candidate draft"); |
| 2494 | assert_eq!(app.current_session_id.as_deref(), Some("old-session")); |
| 2495 | assert_eq!(app.conversation_mode, None); |
| 2496 | } |
| 2497 | |
| 2498 | #[test] |
| 2499 | fn plugin_show_lists_added_commands_and_profiles() { |
| 2500 | let _lock = crate::test_support::lock_test_env(); |
| 2501 | let root = TempDir::new().unwrap(); |
| 2502 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home")); |
| 2503 | let bundle = root.path().join(".codewhale/plugins/toolkit"); |
| 2504 | fs::create_dir_all(bundle.join("commands")).unwrap(); |
| 2505 | fs::create_dir_all(bundle.join("agents")).unwrap(); |
| 2506 | fs::write( |
| 2507 | bundle.join("plugin.toml"), |
| 2508 | "schema_version = 1\n[plugin]\nname = \"toolkit\"\nversion = \"1.0.0\"\n[commands]\npath = \"commands\"\n[agents]\npath = \"agents\"\n", |
| 2509 | ) |
| 2510 | .unwrap(); |
| 2511 | fs::write( |
| 2512 | bundle.join("commands/deploy.md"), |
| 2513 | "---\ndescription: Deploy release\n---\nDeploy\n", |
| 2514 | ) |
| 2515 | .unwrap(); |
| 2516 | fs::write( |
| 2517 | bundle.join("commands/custom_file.md"), |
| 2518 | "---\nname: ship-it\ndescription: Named command\n---\nShip\n", |
| 2519 | ) |
| 2520 | .unwrap(); |
| 2521 | fs::write( |
| 2522 | bundle.join("agents/reviewer.toml"), |
| 2523 | "name = \"security-reviewer\"\ndescription = \"Reviews changes\"\n", |
| 2524 | ) |
| 2525 | .unwrap(); |
| 2526 | fs::write( |
| 2527 | bundle.join("agents/scout.toml"), |
| 2528 | "description = \"Explores code\"\n", |
| 2529 | ) |
| 2530 | .unwrap(); |
| 2531 | |
| 2532 | let (mut app, _temp) = create_test_app(root.path()); |
| 2533 | let show = plugins_with_kimi_home_override(&mut app, Some("show toolkit"), None) |
| 2534 | .message |
| 2535 | .expect("show output"); |
| 2536 | assert!(show.contains("Commands: [/deploy, /ship\\-it]"), "{show}"); |
| 2537 | assert!( |
| 2538 | show.contains("Profiles: [scout, security\\-reviewer]"), |
| 2539 | "{show}" |
| 2540 | ); |
| 2541 | } |
| 2542 | |
| 2543 | fn write_native_service_bundle( |
| 2544 | root: &Path, |
| 2545 | name: &str, |
| 2546 | host_services: &[&str], |
| 2547 | ) -> std::path::PathBuf { |
| 2548 | let bundle = root.join(".codewhale/plugins").join(name); |
| 2549 | fs::create_dir_all(bundle.join("native")).unwrap(); |
| 2550 | fs::create_dir_all(bundle.join("skills/hello")).unwrap(); |
| 2551 | fs::write( |
| 2552 | bundle.join("native/index.mjs"), |
| 2553 | "export function apply() {}\n", |
| 2554 | ) |
| 2555 | .unwrap(); |
| 2556 | fs::write( |
| 2557 | bundle.join("skills/hello/SKILL.md"), |
| 2558 | "---\nname: hello\ndescription: hi\n---\nbody\n", |
| 2559 | ) |
| 2560 | .unwrap(); |
| 2561 | let asked = if host_services.is_empty() { |
| 2562 | String::new() |
| 2563 | } else { |
| 2564 | format!( |
| 2565 | "[capabilities]\nhost_services = [{}]\n", |
| 2566 | host_services |
| 2567 | .iter() |
| 2568 | .map(|service| format!("{service:?}")) |
| 2569 | .collect::<Vec<_>>() |
| 2570 | .join(", ") |
| 2571 | ) |
| 2572 | }; |
| 2573 | fs::write( |
| 2574 | bundle.join("plugin.toml"), |
| 2575 | format!( |
| 2576 | "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n[native]\npath = \"native/index.mjs\"\n{asked}" |
| 2577 | ), |
| 2578 | ) |
| 2579 | .unwrap(); |
| 2580 | bundle |
| 2581 | } |
| 2582 | |
| 2583 | #[test] |
| 2584 | fn plugin_list_and_show_name_the_approver_and_who_turned_it_on() { |
| 2585 | use codewhale_plugins::host_services::{ |
| 2586 | AGENT_PROCESS_NOTE, AgentApproval, AgentPosture, PersonVia, PluginApprover, ReviewApproval, |
| 2587 | }; |
| 2588 | |
| 2589 | let root = TempDir::new().unwrap(); |
| 2590 | let home = root.path().join("home"); |
| 2591 | let other_project = root.path().join("otherproject"); |
| 2592 | fs::create_dir_all(&home).unwrap(); |
| 2593 | fs::create_dir_all(&other_project).unwrap(); |
| 2594 | let sealed = crate::test_support::SealedHome::at(&home); |
| 2595 | |
| 2596 | write_native_service_bundle(root.path(), "agentsvc", &["workspace", "attachments"]); |
| 2597 | write_native_service_bundle(root.path(), "peer-plain", &[]); |
| 2598 | write_skill_bundle(root.path(), "personplug", ""); |
| 2599 | write_skill_bundle(root.path(), "preplug", ""); |
| 2600 | let other_bundle = sealed.codewhale_home().join("plugins/otherproj"); |
| 2601 | fs::create_dir_all(other_bundle.join("skills/hello")).unwrap(); |
| 2602 | #[cfg(unix)] |
| 2603 | { |
| 2604 | use std::os::unix::fs::PermissionsExt as _; |
| 2605 | fs::set_permissions( |
| 2606 | sealed.codewhale_home().join("plugins"), |
| 2607 | fs::Permissions::from_mode(0o700), |
| 2608 | ) |
| 2609 | .unwrap(); |
| 2610 | } |
| 2611 | fs::write( |
| 2612 | other_bundle.join("plugin.toml"), |
| 2613 | "schema_version = 1\n[plugin]\nname = \"otherproj\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n", |
| 2614 | ) |
| 2615 | .unwrap(); |
| 2616 | fs::write( |
| 2617 | other_bundle.join("skills/hello/SKILL.md"), |
| 2618 | "---\nname: hello\ndescription: hi\n---\nbody\n", |
| 2619 | ) |
| 2620 | .unwrap(); |
| 2621 | |
| 2622 | { |
| 2623 | let mut other_reg = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv() |
| 2624 | .registry_for_workspace(&other_project); |
| 2625 | let other_ws_str = other_reg.workspace().to_string_lossy().into_owned(); |
| 2626 | let agent_elsewhere = PluginApprover::Agent(AgentApproval { |
| 2627 | posture: AgentPosture::AutoReview, |
| 2628 | workspace: other_ws_str, |
| 2629 | thread_id: Some("th-other-1".to_string()), |
| 2630 | turn_id: Some("turn-other-1".to_string()), |
| 2631 | tool_call_id: Some("call-other-1".to_string()), |
| 2632 | }); |
| 2633 | let other_hs = other_reg |
| 2634 | .host_service_review_for("otherproj", &agent_elsewhere) |
| 2635 | .map(|review| review.token); |
| 2636 | std::sync::Arc::make_mut(&mut other_reg) |
| 2637 | .trust_and_enable_by( |
| 2638 | "otherproj", |
| 2639 | ReviewApproval { |
| 2640 | approved_by: agent_elsewhere.clone(), |
| 2641 | host_services: other_hs, |
| 2642 | }, |
| 2643 | agent_elsewhere, |
| 2644 | ) |
| 2645 | .unwrap(); |
| 2646 | } |
| 2647 | |
| 2648 | let (mut app, _temp) = create_test_app(root.path()); |
| 2649 | let ws_str = app |
| 2650 | .plugin_registry |
| 2651 | .workspace() |
| 2652 | .to_string_lossy() |
| 2653 | .into_owned(); |
| 2654 | |
| 2655 | let agent_full = PluginApprover::Agent(AgentApproval { |
| 2656 | posture: AgentPosture::FullAccess, |
| 2657 | workspace: ws_str, |
| 2658 | thread_id: Some("th-agent-1".to_string()), |
| 2659 | turn_id: Some("turn-agent-1".to_string()), |
| 2660 | tool_call_id: Some("call-agent-1".to_string()), |
| 2661 | }); |
| 2662 | let hs_token = app |
| 2663 | .plugin_registry |
| 2664 | .host_service_review_for("agentsvc", &agent_full) |
| 2665 | .map(|review| review.token); |
| 2666 | std::sync::Arc::make_mut(&mut app.plugin_registry) |
| 2667 | .trust_and_enable_by( |
| 2668 | "agentsvc", |
| 2669 | ReviewApproval { |
| 2670 | approved_by: agent_full.clone(), |
| 2671 | host_services: hs_token, |
| 2672 | }, |
| 2673 | agent_full, |
| 2674 | ) |
| 2675 | .unwrap(); |
| 2676 | { |
| 2677 | let reg = std::sync::Arc::make_mut(&mut app.plugin_registry); |
| 2678 | let person_term = PluginApprover::person(PersonVia::Terminal); |
| 2679 | reg.trust_and_enable_by( |
| 2680 | "personplug", |
| 2681 | ReviewApproval { |
| 2682 | approved_by: person_term.clone(), |
| 2683 | host_services: None, |
| 2684 | }, |
| 2685 | person_term.clone(), |
| 2686 | ) |
| 2687 | .unwrap(); |
| 2688 | reg.trust_and_enable_by( |
| 2689 | "preplug", |
| 2690 | ReviewApproval { |
| 2691 | approved_by: person_term.clone(), |
| 2692 | host_services: None, |
| 2693 | }, |
| 2694 | person_term, |
| 2695 | ) |
| 2696 | .unwrap(); |
| 2697 | } |
| 2698 | |
| 2699 | let state_path = app.plugin_registry.state_path().unwrap().to_path_buf(); |
| 2700 | let pre_id = app |
| 2701 | .plugin_registry |
| 2702 | .get("preplug") |
| 2703 | .unwrap() |
| 2704 | .id |
| 2705 | .as_str() |
| 2706 | .to_string(); |
| 2707 | let mut state: serde_json::Value = |
| 2708 | serde_json::from_slice(&fs::read(&state_path).unwrap()).unwrap(); |
| 2709 | if let Some(entry) = state["plugins"][&pre_id].as_object_mut() { |
| 2710 | entry.remove("enabled_by"); |
| 2711 | if let Some(trust) = entry.get_mut("trust").and_then(|v| v.as_object_mut()) { |
| 2712 | trust.remove("approved_by"); |
| 2713 | } |
| 2714 | if let Some(history) = entry |
| 2715 | .get_mut("review_history") |
| 2716 | .and_then(|v| v.as_array_mut()) |
| 2717 | { |
| 2718 | for item in history { |
| 2719 | if let Some(obj) = item.as_object_mut() { |
| 2720 | obj.remove("approved_by"); |
| 2721 | } |
| 2722 | } |
| 2723 | } |
| 2724 | } |
| 2725 | fs::write(&state_path, serde_json::to_vec_pretty(&state).unwrap()).unwrap(); |
| 2726 | let reloaded = plugins_with_kimi_home_override(&mut app, Some("reload"), None); |
| 2727 | assert!(!reloaded.is_error, "{:?}", reloaded.message); |
| 2728 | |
| 2729 | let show_before = plugins_with_kimi_home_override(&mut app, Some("show agentsvc"), None) |
| 2730 | .message |
| 2731 | .unwrap(); |
| 2732 | assert!(show_before.contains("Trust: not reviewed"), "{show_before}"); |
| 2733 | assert!( |
| 2734 | show_before.contains("Approval: approved by the agent in Full Access (approved "), |
| 2735 | "{show_before}" |
| 2736 | ); |
| 2737 | assert!( |
| 2738 | show_before.contains("Approval thread: th\\-agent\\-1"), |
| 2739 | "{show_before}" |
| 2740 | ); |
| 2741 | assert!( |
| 2742 | show_before.contains("Turned on by: turned on by the agent in Full Access"), |
| 2743 | "{show_before}" |
| 2744 | ); |
| 2745 | assert!( |
| 2746 | show_before.contains("Reach: this project ("), |
| 2747 | "{show_before}" |
| 2748 | ); |
| 2749 | assert!( |
| 2750 | show_before.contains(&format!("Process: {AGENT_PROCESS_NOTE}")), |
| 2751 | "{show_before}" |
| 2752 | ); |
| 2753 | assert!( |
| 2754 | show_before.contains("workspace (Workspace files and commands): can use"), |
| 2755 | "{show_before}" |
| 2756 | ); |
| 2757 | assert!( |
| 2758 | show_before.contains("attachments (Images in the conversation): can use"), |
| 2759 | "{show_before}" |
| 2760 | ); |
| 2761 | |
| 2762 | let peer_approver = PluginApprover::Agent(AgentApproval { |
| 2763 | posture: AgentPosture::AutoReview, |
| 2764 | workspace: app |
| 2765 | .plugin_registry |
| 2766 | .workspace() |
| 2767 | .to_string_lossy() |
| 2768 | .into_owned(), |
| 2769 | thread_id: Some("th-peer-1".to_string()), |
| 2770 | turn_id: Some("turn-peer-1".to_string()), |
| 2771 | tool_call_id: Some("call-peer-1".to_string()), |
| 2772 | }); |
| 2773 | let peer_hs = app |
| 2774 | .plugin_registry |
| 2775 | .host_service_review_for("peer-plain", &peer_approver) |
| 2776 | .map(|review| review.token); |
| 2777 | std::sync::Arc::make_mut(&mut app.plugin_registry) |
| 2778 | .trust_and_enable_by( |
| 2779 | "peer-plain", |
| 2780 | ReviewApproval { |
| 2781 | approved_by: peer_approver.clone(), |
| 2782 | host_services: peer_hs, |
| 2783 | }, |
| 2784 | peer_approver, |
| 2785 | ) |
| 2786 | .unwrap(); |
| 2787 | |
| 2788 | let list = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 2789 | .message |
| 2790 | .unwrap(); |
| 2791 | assert!( |
| 2792 | list.contains("agentsvc — active\n workspace · not reviewed"), |
| 2793 | "{list}" |
| 2794 | ); |
| 2795 | assert!( |
| 2796 | list.contains("approved by the agent in Full Access (approved "), |
| 2797 | "{list}" |
| 2798 | ); |
| 2799 | assert!( |
| 2800 | list.contains("turned on by the agent in Full Access"), |
| 2801 | "{list}" |
| 2802 | ); |
| 2803 | assert!( |
| 2804 | list.contains("approved by the agent in Auto-Review (approved "), |
| 2805 | "{list}" |
| 2806 | ); |
| 2807 | assert!( |
| 2808 | list.contains("personplug — active\n workspace · trusted"), |
| 2809 | "{list}" |
| 2810 | ); |
| 2811 | assert!(list.contains("approved by you (approved "), "{list}"); |
| 2812 | assert!(list.contains("turned on by you"), "{list}"); |
| 2813 | assert!(list.contains("otherproj — inactive"), "{list}"); |
| 2814 | assert!(list.contains("on only in otherproject"), "{list}"); |
| 2815 | assert!( |
| 2816 | list.contains("approver not recorded (reviewed before 0.10.3)"), |
| 2817 | "{list}" |
| 2818 | ); |
| 2819 | assert!( |
| 2820 | list.contains("who turned it on not recorded (enabled before 0.10.3)"), |
| 2821 | "{list}" |
| 2822 | ); |
| 2823 | |
| 2824 | let show_withheld = plugins_with_kimi_home_override(&mut app, Some("show agentsvc"), None) |
| 2825 | .message |
| 2826 | .unwrap(); |
| 2827 | assert!( |
| 2828 | show_withheld.contains( |
| 2829 | "workspace (Workspace files and commands): off for now: `peer-plain` is turned on and its review does not include it" |
| 2830 | ), |
| 2831 | "{show_withheld}" |
| 2832 | ); |
| 2833 | assert!( |
| 2834 | show_withheld.contains( |
| 2835 | "attachments (Images in the conversation): off for now: `peer-plain` is turned on and its review does not include it" |
| 2836 | ), |
| 2837 | "{show_withheld}" |
| 2838 | ); |
| 2839 | |
| 2840 | let show_other = plugins_with_kimi_home_override(&mut app, Some("show otherproj"), None) |
| 2841 | .message |
| 2842 | .unwrap(); |
| 2843 | assert!( |
| 2844 | show_other.contains("Reach: on only in otherproject"), |
| 2845 | "{show_other}" |
| 2846 | ); |
| 2847 | |
| 2848 | let show_pre = plugins_with_kimi_home_override(&mut app, Some("show preplug"), None) |
| 2849 | .message |
| 2850 | .unwrap(); |
| 2851 | assert!( |
| 2852 | show_pre.contains("Approval: approver not recorded (reviewed before 0.10.3)"), |
| 2853 | "{show_pre}" |
| 2854 | ); |
| 2855 | assert!( |
| 2856 | show_pre.contains("Turned on by: who turned it on not recorded (enabled before 0.10.3)"), |
| 2857 | "{show_pre}" |
| 2858 | ); |
| 2859 | |
| 2860 | let token = app.plugin_registry.get("agentsvc").unwrap().review_token(); |
| 2861 | let reviewed = |
| 2862 | plugins_with_kimi_home_override(&mut app, Some(&format!("trust agentsvc {token}")), None); |
| 2863 | assert!(!reviewed.is_error, "{:?}", reviewed.message); |
| 2864 | let show_after = plugins_with_kimi_home_override(&mut app, Some("show agentsvc"), None) |
| 2865 | .message |
| 2866 | .unwrap(); |
| 2867 | assert!(show_after.contains("Trust: trusted"), "{show_after}"); |
| 2868 | assert!( |
| 2869 | show_after.contains("Approval: approved by you (approved "), |
| 2870 | "{show_after}" |
| 2871 | ); |
| 2872 | assert!(!show_after.contains("Trust: not reviewed"), "{show_after}"); |
| 2873 | assert!(!show_after.contains("Approval thread:"), "{show_after}"); |
| 2874 | assert!(!show_after.contains("Turned on by:"), "{show_after}"); |
| 2875 | assert!(!show_after.contains(AGENT_PROCESS_NOTE), "{show_after}"); |
| 2876 | assert!( |
| 2877 | show_after.contains("Earlier reviews:") |
| 2878 | && show_after.contains("approved by the agent in Full Access"), |
| 2879 | "{show_after}" |
| 2880 | ); |
| 2881 | } |
| 2882 | |
| 2883 | #[test] |
| 2884 | fn command_line_trust_never_reads_as_reviewed_by_you() { |
| 2885 | let root = TempDir::new().unwrap(); |
| 2886 | let home = root.path().join("home"); |
| 2887 | fs::create_dir_all(&home).unwrap(); |
| 2888 | let _home = crate::test_support::SealedHome::at(&home); |
| 2889 | |
| 2890 | write_skill_bundle(root.path(), "cmdplug", ""); |
| 2891 | let (mut app, _temp) = create_test_app(root.path()); |
| 2892 | let mut reg_arc = app.plugin_registry.clone(); |
| 2893 | let mut console = ScriptedConsole::default(); |
| 2894 | let token = reg_arc.get("cmdplug").unwrap().review_token(); |
| 2895 | headless_trust_named( |
| 2896 | &mut reg_arc, |
| 2897 | "cmdplug", |
| 2898 | Some(&token), |
| 2899 | true, |
| 2900 | false, |
| 2901 | &mut console, |
| 2902 | ) |
| 2903 | .unwrap(); |
| 2904 | std::sync::Arc::make_mut(&mut reg_arc) |
| 2905 | .enable("cmdplug") |
| 2906 | .unwrap(); |
| 2907 | app.plugin_registry = reg_arc; |
| 2908 | |
| 2909 | let list = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 2910 | .message |
| 2911 | .unwrap(); |
| 2912 | assert!( |
| 2913 | list.contains("cmdplug — active\n workspace · not reviewed"), |
| 2914 | "{list}" |
| 2915 | ); |
| 2916 | assert!( |
| 2917 | list.contains("trusted from the command line with --yes; no review was shown there"), |
| 2918 | "{list}" |
| 2919 | ); |
| 2920 | assert!(!list.contains("reviewed by you"), "{list}"); |
| 2921 | |
| 2922 | let show = plugins_with_kimi_home_override(&mut app, Some("show cmdplug"), None) |
| 2923 | .message |
| 2924 | .unwrap(); |
| 2925 | assert!(show.contains("Trust: not reviewed"), "{show}"); |
| 2926 | assert!( |
| 2927 | show.contains( |
| 2928 | "Approval: trusted from the command line with --yes; no review was shown there" |
| 2929 | ), |
| 2930 | "{show}" |
| 2931 | ); |
| 2932 | assert!(show.contains("Turned on by: turned on by you"), "{show}"); |
| 2933 | assert!(!show.contains("reviewed by you"), "{show}"); |
| 2934 | } |
| 2935 | |
| 2936 | #[test] |
| 2937 | fn an_agent_approved_plugin_a_person_turned_on_still_reads_not_reviewed() { |
| 2938 | use codewhale_plugins::host_services::{ |
| 2939 | AGENT_PROCESS_NOTE, AgentApproval, AgentPosture, PersonVia, PluginApprover, ReviewApproval, |
| 2940 | }; |
| 2941 | |
| 2942 | let root = TempDir::new().unwrap(); |
| 2943 | let home = root.path().join("home"); |
| 2944 | fs::create_dir_all(&home).unwrap(); |
| 2945 | let _home = crate::test_support::SealedHome::at(&home); |
| 2946 | |
| 2947 | write_skill_bundle(root.path(), "hybridplug", ""); |
| 2948 | let (mut app, _temp) = create_test_app(root.path()); |
| 2949 | let ws = app |
| 2950 | .plugin_registry |
| 2951 | .workspace() |
| 2952 | .to_string_lossy() |
| 2953 | .into_owned(); |
| 2954 | { |
| 2955 | let agent_hybrid = PluginApprover::Agent(AgentApproval { |
| 2956 | posture: AgentPosture::AutoReview, |
| 2957 | workspace: ws, |
| 2958 | thread_id: Some("th-hybrid".to_string()), |
| 2959 | turn_id: Some("turn-hybrid".to_string()), |
| 2960 | tool_call_id: Some("call-hybrid".to_string()), |
| 2961 | }); |
| 2962 | let hybrid_hs = app |
| 2963 | .plugin_registry |
| 2964 | .host_service_review_for("hybridplug", &agent_hybrid) |
| 2965 | .map(|review| review.token); |
| 2966 | let reg = std::sync::Arc::make_mut(&mut app.plugin_registry); |
| 2967 | reg.trust_reviewed( |
| 2968 | "hybridplug", |
| 2969 | ReviewApproval { |
| 2970 | approved_by: agent_hybrid, |
| 2971 | host_services: hybrid_hs, |
| 2972 | }, |
| 2973 | ) |
| 2974 | .unwrap(); |
| 2975 | reg.enable_by("hybridplug", PluginApprover::person(PersonVia::App)) |
| 2976 | .unwrap(); |
| 2977 | } |
| 2978 | |
| 2979 | let list = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 2980 | .message |
| 2981 | .unwrap(); |
| 2982 | assert!( |
| 2983 | list.contains("hybridplug — active\n workspace · not reviewed"), |
| 2984 | "{list}" |
| 2985 | ); |
| 2986 | assert!( |
| 2987 | list.contains("approved by the agent in Auto-Review (approved "), |
| 2988 | "{list}" |
| 2989 | ); |
| 2990 | assert!(list.contains("turned on by you"), "{list}"); |
| 2991 | assert!(!list.contains("approved by you"), "{list}"); |
| 2992 | |
| 2993 | let show = plugins_with_kimi_home_override(&mut app, Some("show hybridplug"), None) |
| 2994 | .message |
| 2995 | .unwrap(); |
| 2996 | assert!(show.contains("Trust: not reviewed"), "{show}"); |
| 2997 | assert!( |
| 2998 | show.contains("Approval: approved by the agent in Auto-Review (approved "), |
| 2999 | "{show}" |
| 3000 | ); |
| 3001 | assert!(show.contains("Turned on by: turned on by you"), "{show}"); |
| 3002 | assert!( |
| 3003 | show.contains(&format!("Process: {AGENT_PROCESS_NOTE}")), |
| 3004 | "{show}" |
| 3005 | ); |
| 3006 | } |
| 3007 | |
| 3008 | #[test] |
| 3009 | fn the_approval_date_is_never_shown_as_the_turned_on_date() { |
| 3010 | use codewhale_plugins::host_services::{ |
| 3011 | AgentApproval, AgentPosture, PluginApprover, ReviewApproval, |
| 3012 | }; |
| 3013 | |
| 3014 | let root = TempDir::new().unwrap(); |
| 3015 | let home = root.path().join("home"); |
| 3016 | fs::create_dir_all(&home).unwrap(); |
| 3017 | let _home = crate::test_support::SealedHome::at(&home); |
| 3018 | |
| 3019 | write_skill_bundle(root.path(), "datedplug", ""); |
| 3020 | let (mut app, _temp) = create_test_app(root.path()); |
| 3021 | let ws = app |
| 3022 | .plugin_registry |
| 3023 | .workspace() |
| 3024 | .to_string_lossy() |
| 3025 | .into_owned(); |
| 3026 | let approver = PluginApprover::Agent(AgentApproval { |
| 3027 | posture: AgentPosture::FullAccess, |
| 3028 | workspace: ws, |
| 3029 | thread_id: Some("th-dated-1".to_string()), |
| 3030 | turn_id: Some("turn-dated-1".to_string()), |
| 3031 | tool_call_id: Some("call-dated-1".to_string()), |
| 3032 | }); |
| 3033 | let hs_token = app |
| 3034 | .plugin_registry |
| 3035 | .host_service_review_for("datedplug", &approver) |
| 3036 | .map(|review| review.token); |
| 3037 | std::sync::Arc::make_mut(&mut app.plugin_registry) |
| 3038 | .trust_and_enable_by( |
| 3039 | "datedplug", |
| 3040 | ReviewApproval { |
| 3041 | approved_by: approver.clone(), |
| 3042 | host_services: hs_token, |
| 3043 | }, |
| 3044 | approver, |
| 3045 | ) |
| 3046 | .unwrap(); |
| 3047 | |
| 3048 | let state_path = app.plugin_registry.state_path().unwrap().to_path_buf(); |
| 3049 | let id = app |
| 3050 | .plugin_registry |
| 3051 | .get("datedplug") |
| 3052 | .unwrap() |
| 3053 | .id |
| 3054 | .as_str() |
| 3055 | .to_string(); |
| 3056 | let mut state: serde_json::Value = |
| 3057 | serde_json::from_slice(&fs::read(&state_path).unwrap()).unwrap(); |
| 3058 | state["plugins"][&id]["trust"]["reviewed_at"] = serde_json::json!("2024-03-04T05:06:07Z"); |
| 3059 | if let Some(history) = state["plugins"][&id]["review_history"].as_array_mut() { |
| 3060 | for item in history { |
| 3061 | item["reviewed_at"] = serde_json::json!("2024-03-04T05:06:07Z"); |
| 3062 | } |
| 3063 | } |
| 3064 | fs::write(&state_path, serde_json::to_vec_pretty(&state).unwrap()).unwrap(); |
| 3065 | let reloaded = plugins_with_kimi_home_override(&mut app, Some("reload"), None); |
| 3066 | assert!(!reloaded.is_error, "{:?}", reloaded.message); |
| 3067 | |
| 3068 | let show = plugins_with_kimi_home_override(&mut app, Some("show datedplug"), None) |
| 3069 | .message |
| 3070 | .unwrap(); |
| 3071 | let approval_line = show |
| 3072 | .lines() |
| 3073 | .find(|line| line.starts_with("Approval:")) |
| 3074 | .expect("Approval line"); |
| 3075 | assert!( |
| 3076 | approval_line.contains("(approved 2024-03-04)"), |
| 3077 | "{approval_line}" |
| 3078 | ); |
| 3079 | let turned_on_line = show |
| 3080 | .lines() |
| 3081 | .find(|line| line.starts_with("Turned on by:")) |
| 3082 | .expect("Turned on by line"); |
| 3083 | assert!( |
| 3084 | turned_on_line.contains("turned on by the agent in Full Access"), |
| 3085 | "{turned_on_line}" |
| 3086 | ); |
| 3087 | assert!(!turned_on_line.contains("2024-03-04"), "{turned_on_line}"); |
| 3088 | assert!(!turned_on_line.contains("approved"), "{turned_on_line}"); |
| 3089 | |
| 3090 | let list = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 3091 | .message |
| 3092 | .unwrap(); |
| 3093 | let list_approval_line = list |
| 3094 | .lines() |
| 3095 | .find(|line| line.contains("approved by the agent in Full Access")) |
| 3096 | .expect("list approval line"); |
| 3097 | assert!( |
| 3098 | list_approval_line.contains("(approved 2024-03-04)"), |
| 3099 | "{list_approval_line}" |
| 3100 | ); |
| 3101 | let list_turned_on_line = list |
| 3102 | .lines() |
| 3103 | .find(|line| line.contains("turned on by the agent in Full Access")) |
| 3104 | .expect("list turned on line"); |
| 3105 | assert!( |
| 3106 | !list_turned_on_line.contains("2024-03-04"), |
| 3107 | "{list_turned_on_line}" |
| 3108 | ); |
| 3109 | } |
| 3110 | |
| 3111 | #[test] |
| 3112 | fn english_approver_strings_match_the_plugins_crate_labels() { |
| 3113 | use codewhale_plugins::host_services::{ |
| 3114 | AGENT_PROCESS_NOTE, AgentApproval, AgentPosture, PersonVia, PluginApprover, approver_label, |
| 3115 | }; |
| 3116 | |
| 3117 | let cases = [ |
| 3118 | ( |
| 3119 | Some(PluginApprover::person(PersonVia::Terminal)), |
| 3120 | MessageId::CmdPluginAuditApprovedByYou, |
| 3121 | ), |
| 3122 | ( |
| 3123 | Some(PluginApprover::person(PersonVia::App)), |
| 3124 | MessageId::CmdPluginAuditApprovedByYou, |
| 3125 | ), |
| 3126 | ( |
| 3127 | Some(PluginApprover::person(PersonVia::ApprovalCard)), |
| 3128 | MessageId::CmdPluginAuditApprovedByYou, |
| 3129 | ), |
| 3130 | ( |
| 3131 | Some(PluginApprover::Agent(AgentApproval { |
| 3132 | posture: AgentPosture::FullAccess, |
| 3133 | workspace: "/tmp/ws".to_string(), |
| 3134 | thread_id: None, |
| 3135 | turn_id: None, |
| 3136 | tool_call_id: None, |
| 3137 | })), |
| 3138 | MessageId::CmdPluginAuditApprovedByAgentFullAccess, |
| 3139 | ), |
| 3140 | ( |
| 3141 | Some(PluginApprover::Agent(AgentApproval { |
| 3142 | posture: AgentPosture::AutoReview, |
| 3143 | workspace: "/tmp/ws".to_string(), |
| 3144 | thread_id: None, |
| 3145 | turn_id: None, |
| 3146 | tool_call_id: None, |
| 3147 | })), |
| 3148 | MessageId::CmdPluginAuditApprovedByAgentAutoReview, |
| 3149 | ), |
| 3150 | ( |
| 3151 | Some(PluginApprover::Agent(AgentApproval { |
| 3152 | posture: AgentPosture::CommandLine, |
| 3153 | workspace: "/tmp/ws".to_string(), |
| 3154 | thread_id: None, |
| 3155 | turn_id: None, |
| 3156 | tool_call_id: None, |
| 3157 | })), |
| 3158 | MessageId::CmdPluginAuditApprovedByAgentShell, |
| 3159 | ), |
| 3160 | ( |
| 3161 | Some(PluginApprover::CommandLine), |
| 3162 | MessageId::CmdPluginAuditApprovedByCommandLine, |
| 3163 | ), |
| 3164 | (None, MessageId::CmdPluginAuditApprovedByUnknown), |
| 3165 | ]; |
| 3166 | for (approver, id) in cases { |
| 3167 | assert_eq!( |
| 3168 | codewhale_localization::tr(Locale::En, id).as_ref(), |
| 3169 | approver_label(approver.as_ref()), |
| 3170 | "{id:?}" |
| 3171 | ); |
| 3172 | } |
| 3173 | assert_eq!( |
| 3174 | codewhale_localization::tr(Locale::En, MessageId::CmdPluginAuditAgentProcessNote).as_ref(), |
| 3175 | AGENT_PROCESS_NOTE |
| 3176 | ); |
| 3177 | } |
| 3178 | |
| 3179 | #[test] |
| 3180 | fn a_manifest_cannot_forge_an_approver_line() { |
| 3181 | use codewhale_plugins::PluginRegistry; |
| 3182 | use codewhale_plugins::host_services::{ |
| 3183 | AgentApproval, AgentPosture, PluginApprover, ReviewApproval, |
| 3184 | }; |
| 3185 | |
| 3186 | let root = TempDir::new().unwrap(); |
| 3187 | let home = root.path().join("home"); |
| 3188 | fs::create_dir_all(&home).unwrap(); |
| 3189 | let _home = crate::test_support::SealedHome::at(&home); |
| 3190 | |
| 3191 | write_skill_bundle(root.path(), "forged", ""); |
| 3192 | let (base_app, _temp) = create_test_app(root.path()); |
| 3193 | let state_path = base_app.plugin_registry.state_path().unwrap().to_path_buf(); |
| 3194 | let workspace = base_app.plugin_registry.workspace().to_path_buf(); |
| 3195 | let mut forged_plugin = base_app.plugin_registry.get("forged").unwrap().clone(); |
| 3196 | let forged_id = forged_plugin.id.as_str().to_string(); |
| 3197 | |
| 3198 | let mut reg_for_state = base_app.plugin_registry.clone(); |
| 3199 | let agent = PluginApprover::Agent(AgentApproval { |
| 3200 | posture: AgentPosture::FullAccess, |
| 3201 | workspace: workspace.to_string_lossy().into_owned(), |
| 3202 | thread_id: Some("th-forged-1".to_string()), |
| 3203 | turn_id: Some("turn-forged-1".to_string()), |
| 3204 | tool_call_id: Some("call-forged-1".to_string()), |
| 3205 | }); |
| 3206 | let hs_token = reg_for_state |
| 3207 | .host_service_review_for("forged", &agent) |
| 3208 | .map(|review| review.token); |
| 3209 | std::sync::Arc::make_mut(&mut reg_for_state) |
| 3210 | .trust_and_enable_by( |
| 3211 | "forged", |
| 3212 | ReviewApproval { |
| 3213 | approved_by: agent.clone(), |
| 3214 | host_services: hs_token, |
| 3215 | }, |
| 3216 | agent, |
| 3217 | ) |
| 3218 | .unwrap(); |
| 3219 | |
| 3220 | forged_plugin.manifest.plugin.name = "x: approved by you\n\x1b[31m\u{202e}fake".to_string(); |
| 3221 | let registry = std::sync::Arc::new(PluginRegistry::from_discovery( |
| 3222 | vec![forged_plugin], |
| 3223 | Vec::new(), |
| 3224 | state_path, |
| 3225 | workspace.clone(), |
| 3226 | None, |
| 3227 | )); |
| 3228 | let mut app = crate::tui::app::App::new_with_plugin_registry( |
| 3229 | crate::tui::test_support::test_tui_options(&workspace), |
| 3230 | &codewhale_runtime::config::Config::default(), |
| 3231 | registry, |
| 3232 | ); |
| 3233 | |
| 3234 | let list = plugins_with_kimi_home_override(&mut app, Some("list"), None) |
| 3235 | .message |
| 3236 | .unwrap(); |
| 3237 | assert!(!list.contains('\x1b'), "{list}"); |
| 3238 | assert!(!list.contains('\u{202e}'), "{list}"); |
| 3239 | assert!(list.contains("\\u{a}"), "{list}"); |
| 3240 | assert!(list.contains("\\u{1b}"), "{list}"); |
| 3241 | assert!(list.contains("\\u{202e}"), "{list}"); |
| 3242 | assert!( |
| 3243 | !list |
| 3244 | .lines() |
| 3245 | .any(|line| line.trim_start() == "approved by you"), |
| 3246 | "{list}" |
| 3247 | ); |
| 3248 | |
| 3249 | let show = plugins_with_kimi_home_override(&mut app, Some(&format!("show {forged_id}")), None) |
| 3250 | .message |
| 3251 | .unwrap(); |
| 3252 | assert!(!show.contains('\x1b'), "{show}"); |
| 3253 | assert!(!show.contains('\u{202e}'), "{show}"); |
| 3254 | assert!(show.contains("\\u{a}"), "{show}"); |
| 3255 | assert!( |
| 3256 | show.lines() |
| 3257 | .any(|line| line.starts_with("Approval: approved by the agent in Full Access")), |
| 3258 | "{show}" |
| 3259 | ); |
| 3260 | |
| 3261 | let screen = crate::tui::views::extensions::ExtensionsView::new( |
| 3262 | &app, |
| 3263 | crate::tui::views::extensions::ExtensionsTab::Plugins, |
| 3264 | ) |
| 3265 | .render_text_for_test(160, 24); |
| 3266 | assert!(!screen.contains('\x1b'), "{screen}"); |
| 3267 | assert!(!screen.contains('\u{202e}'), "{screen}"); |
| 3268 | assert!(screen.contains("\\u{a}"), "{screen}"); |
| 3269 | |
| 3270 | let notice = app |
| 3271 | .status_toasts |
| 3272 | .iter() |
| 3273 | .find(|toast| { |
| 3274 | toast |
| 3275 | .text |
| 3276 | .contains("Agent-approved plugins active in this project") |
| 3277 | }) |
| 3278 | .expect("standing agent-approved plugins notice"); |
| 3279 | assert!(!notice.text.contains('\n'), "{}", notice.text); |
| 3280 | assert!(!notice.text.contains('\x1b'), "{}", notice.text); |
| 3281 | assert!(!notice.text.contains('\u{202e}'), "{}", notice.text); |
| 3282 | assert!(notice.text.contains("\\u{a}"), "{}", notice.text); |
| 3283 | } |
| 3284 |