| 1 | //! Portable config command handlers (FEAT-028 Phase 5). |
| 2 | //! |
| 3 | //! Every handler consumes only the `CONFIG`/`PET`/`TRUST` capability facets and |
| 4 | //! returns a contract-owned `CommandResult<ConfigAction>`. No handler names |
| 5 | //! `App`, `AppAction` or any concrete host type, so the whole group compiles |
| 6 | //! without `codewhale-tui` and can move into `codewhale-commands` without a |
| 7 | //! circular dependency. The concrete implementations live in |
| 8 | //! `crate::commands::config_main_host`, reached only through the host adapters. |
| 9 | |
| 10 | #[cfg(test)] |
| 11 | use codewhale_command_contract::config::CommandWorkflowSummary; |
| 12 | use codewhale_command_contract::config::{ |
| 13 | CommandAccountState, CommandPetContext, CommandPetLabel, CommandWorkSurfaceContext, |
| 14 | ConfigMessage, ConfigReply, TrustPathError, |
| 15 | }; |
| 16 | use codewhale_command_contract::facets::CommandModeSelection; |
| 17 | use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts}; |
| 18 | use codewhale_command_contract::outcome::{ConfigAction, ConfigCommandResult}; |
| 19 | use codewhale_command_contract::types::{ |
| 20 | CommandMode, CommandRailPanel, CommandWorkSurfacePlacement, |
| 21 | }; |
| 22 | use codewhale_command_contract::whale_identity::{normalize_whale_color, normalize_whale_name}; |
| 23 | use codewhale_command_contract::workflow::render_workflow_summary; |
| 24 | |
| 25 | /// `/config` only: config authority plus `PRESENTATION` for its keyed messages |
| 26 | /// and `PERMISSIONS` because `ask-rules` forwards to the permission-rules editor. |
| 27 | pub const CONFIG_CAPS: CommandCapabilities = CommandCapabilities::CONFIG |
| 28 | .union(CommandCapabilities::PRESENTATION) |
| 29 | .union(CommandCapabilities::PERMISSIONS); |
| 30 | /// Commands that observe config and render keyed messages (`/theme`). |
| 31 | pub const CONFIG_PRESENTATION_CAPS: CommandCapabilities = |
| 32 | CommandCapabilities::CONFIG.union(CommandCapabilities::PRESENTATION); |
| 33 | /// Commands that observe config and render only literals |
| 34 | /// (`/settings`, `/verbose`, `/import-claude`). |
| 35 | pub const CONFIG_ONLY_CAPS: CommandCapabilities = CommandCapabilities::CONFIG; |
| 36 | /// Capabilities declared by `/whale`. |
| 37 | pub const WHALE_CAPS: CommandCapabilities = CommandCapabilities::PET; |
| 38 | /// Capabilities declared by `/trust`. |
| 39 | pub const TRUST_CAPS: CommandCapabilities = CommandCapabilities::TRUST; |
| 40 | /// Capabilities declared by `/login` and `/logout`. |
| 41 | pub const LOGIN_CAPS: CommandCapabilities = CommandCapabilities::LOGIN; |
| 42 | /// Capabilities declared by `/mode` (reuses the mode-policy facet). |
| 43 | pub const MODE_CAPS: CommandCapabilities = CommandCapabilities::MODE_POLICY; |
| 44 | /// Capabilities declared by `/workbar`. |
| 45 | pub const WORK_SURFACE_CAPS: CommandCapabilities = CommandCapabilities::WORK_SURFACE; |
| 46 | |
| 47 | /// Resolve a host reply into a command result. |
| 48 | /// |
| 49 | /// Literal messages never require the presentation shape. A `Keyed` message |
| 50 | /// needs it, and a missing required capability fails loudly (it must not be |
| 51 | /// substituted while the reply keeps `is_error == false`). |
| 52 | fn to_result( |
| 53 | reply: ConfigReply, |
| 54 | parts: &mut codewhale_command_contract::handler::ContextParts<'_>, |
| 55 | prepared: &PreparedTemplates, |
| 56 | ) -> ConfigCommandResult { |
| 57 | let message = match reply.message { |
| 58 | None => None, |
| 59 | Some(message) => { |
| 60 | if message_needs_presentation(&message) { |
| 61 | match parts.presentation.as_deref_mut() { |
| 62 | Some(_) => match render_message(message, prepared) { |
| 63 | Ok(text) => Some(text), |
| 64 | Err(error) => { |
| 65 | return ConfigCommandResult { |
| 66 | message: Some(error), |
| 67 | action: None, |
| 68 | is_error: true, |
| 69 | }; |
| 70 | } |
| 71 | }, |
| 72 | None => { |
| 73 | return ConfigCommandResult { |
| 74 | message: Some( |
| 75 | "Error: Command capability unavailable: presentation".to_string(), |
| 76 | ), |
| 77 | action: None, |
| 78 | is_error: true, |
| 79 | }; |
| 80 | } |
| 81 | } |
| 82 | } else { |
| 83 | render_literals(message) |
| 84 | } |
| 85 | } |
| 86 | }; |
| 87 | let message = match (message, reply.is_error) { |
| 88 | (Some(text), true) if !text.starts_with("Error: ") => Some(format!("Error: {text}")), |
| 89 | (other, _) => other, |
| 90 | }; |
| 91 | ConfigCommandResult { |
| 92 | message, |
| 93 | action: reply.action, |
| 94 | is_error: reply.is_error, |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// Whether any part of the message needs the presentation shape. |
| 99 | fn message_needs_presentation(message: &ConfigMessage) -> bool { |
| 100 | match message { |
| 101 | ConfigMessage::Literal(_) => false, |
| 102 | ConfigMessage::Keyed { .. } => true, |
| 103 | ConfigMessage::Concat(parts) => parts.iter().any(message_needs_presentation), |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// Render a literal-only message without the presentation shape. |
| 108 | fn render_literals(message: ConfigMessage) -> Option<String> { |
| 109 | match message { |
| 110 | ConfigMessage::Literal(text) => Some(text), |
| 111 | ConfigMessage::Concat(parts) => { |
| 112 | let mut out = String::new(); |
| 113 | for part in parts { |
| 114 | out.push_str(&render_literals(part)?); |
| 115 | } |
| 116 | Some(out) |
| 117 | } |
| 118 | ConfigMessage::Keyed { .. } => None, |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// The parameter names left as sentinels in a prepared template. |
| 123 | fn sentinel_names(template: &str) -> Vec<String> { |
| 124 | let mut names = Vec::new(); |
| 125 | let mut rest = template; |
| 126 | while let Some(start) = rest.find('\u{1}') { |
| 127 | let after = &rest[start + 1..]; |
| 128 | let Some(end) = after.find('\u{1}') else { |
| 129 | break; |
| 130 | }; |
| 131 | names.push(after[..end].to_string()); |
| 132 | rest = &after[end + 1..]; |
| 133 | } |
| 134 | names |
| 135 | } |
| 136 | |
| 137 | /// Sentinel left in place of a template placeholder during preflight. |
| 138 | fn sentinel(name: &str) -> String { |
| 139 | format!("\u{1}{name}\u{1}") |
| 140 | } |
| 141 | |
| 142 | /// Localized templates validated before any effect, keyed by message key. |
| 143 | /// |
| 144 | /// Rendering never translates again. Replies outside the prepared key/parameter |
| 145 | /// contract fail without an action; inserted values remain literal. |
| 146 | #[derive(Default)] |
| 147 | struct PreparedTemplates { |
| 148 | templates: std::collections::HashMap<String, String>, |
| 149 | } |
| 150 | |
| 151 | impl PreparedTemplates { |
| 152 | fn get(&self, key: &str) -> Option<&str> { |
| 153 | self.templates.get(key).map(String::as_str) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /// Render a reply message, propagating any translation failure (including one |
| 158 | /// nested inside a parameter) instead of converting it into ordinary text. |
| 159 | fn render_message(message: ConfigMessage, prepared: &PreparedTemplates) -> Result<String, String> { |
| 160 | match message { |
| 161 | ConfigMessage::Literal(text) => Ok(text), |
| 162 | ConfigMessage::Concat(parts) => { |
| 163 | let mut out = String::new(); |
| 164 | for part in parts { |
| 165 | out.push_str(&render_message(part, prepared)?); |
| 166 | } |
| 167 | Ok(out) |
| 168 | } |
| 169 | ConfigMessage::Keyed { key, params } => { |
| 170 | let mut resolved: Vec<(String, String)> = Vec::with_capacity(params.len()); |
| 171 | for (name, param) in params { |
| 172 | resolved.push((name, render_message(param, prepared)?)); |
| 173 | } |
| 174 | match prepared.get(&key) { |
| 175 | // Validated before any effect: substitute the sentinel left by |
| 176 | // preflight, never re-translate. The reply's parameter names |
| 177 | // must match the prepared template exactly. |
| 178 | Some(template) => { |
| 179 | // The template may repeat a placeholder; only the *set* of |
| 180 | // names has to match, and the reply must not duplicate one. |
| 181 | let expected: std::collections::BTreeSet<String> = |
| 182 | sentinel_names(template).into_iter().collect(); |
| 183 | let mut seen = std::collections::BTreeSet::new(); |
| 184 | for (name, _) in &resolved { |
| 185 | if !seen.insert(name.clone()) { |
| 186 | return Err(format!( |
| 187 | "invalid translation replacement contract for {key}: duplicate {name}" |
| 188 | )); |
| 189 | } |
| 190 | } |
| 191 | if seen != expected { |
| 192 | return Err(format!( |
| 193 | "invalid translation replacement contract for {key}" |
| 194 | )); |
| 195 | } |
| 196 | let mut out = String::with_capacity(template.len()); |
| 197 | let mut rest = template; |
| 198 | while let Some(start) = rest.find('\u{1}') { |
| 199 | let after = &rest[start + 1..]; |
| 200 | let Some(end) = after.find('\u{1}') else { |
| 201 | break; |
| 202 | }; |
| 203 | out.push_str(&rest[..start]); |
| 204 | let name = &after[..end]; |
| 205 | if let Some((_, value)) = resolved.iter().find(|(key, _)| key == name) { |
| 206 | out.push_str(value); |
| 207 | } |
| 208 | rest = &after[end + 1..]; |
| 209 | } |
| 210 | out.push_str(rest); |
| 211 | Ok(out) |
| 212 | } |
| 213 | // The effect-reply contract is prepared before the mutation; an |
| 214 | // unprepared key is a host contract violation, never a reason to |
| 215 | // translate after the effect. |
| 216 | None => Err(format!("unprepared message key: {key}")), |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /// The complete effect-reply contract, validated before every mutation. |
| 223 | const REQUIRED_TEMPLATES: &[(&str, &[&str])] = |
| 224 | codewhale_command_contract::config::EFFECT_REPLY_TEMPLATES; |
| 225 | |
| 226 | /// Templates `/settings` renders through the presentation shape. |
| 227 | const SETTINGS_TEMPLATES: &[(&str, &[&str])] = |
| 228 | &[("settings_title", &[]), ("settings_config_file", &[])]; |
| 229 | |
| 230 | /// Keyed explanatory notes the `/config status` audit renders. |
| 231 | const AUDIT_TEMPLATES: &[(&str, &[&str])] = &[ |
| 232 | ("config_audit_search_provider", &[]), |
| 233 | ("config_audit_prompt_suggestion", &[]), |
| 234 | ("config_audit_notifications", &[]), |
| 235 | ]; |
| 236 | |
| 237 | /// Validate required capabilities and translation templates before any effect. |
| 238 | #[allow(clippy::result_large_err)] |
| 239 | fn preflight( |
| 240 | parts: &mut codewhale_command_contract::handler::ContextParts<'_>, |
| 241 | ) -> Result<PreparedTemplates, ConfigCommandResult> { |
| 242 | preflight_with(parts, REQUIRED_TEMPLATES) |
| 243 | } |
| 244 | |
| 245 | /// As [`preflight`], with a caller-supplied template set. Returns the |
| 246 | /// validated templates so rendering cannot translate again after an effect. |
| 247 | #[allow(clippy::result_large_err)] |
| 248 | fn preflight_with( |
| 249 | parts: &mut codewhale_command_contract::handler::ContextParts<'_>, |
| 250 | templates: &[(&str, &[&str])], |
| 251 | ) -> Result<PreparedTemplates, ConfigCommandResult> { |
| 252 | let Some(presentation) = parts.presentation.as_deref_mut() else { |
| 253 | return Err(missing("presentation")); |
| 254 | }; |
| 255 | let mut prepared = PreparedTemplates::default(); |
| 256 | for (key, params) in templates { |
| 257 | let dummies: Vec<String> = params.iter().map(|name| sentinel(name)).collect(); |
| 258 | let refs: Vec<(&str, &str)> = params |
| 259 | .iter() |
| 260 | .zip(&dummies) |
| 261 | .map(|(name, dummy)| (*name, dummy.as_str())) |
| 262 | .collect(); |
| 263 | let template = presentation |
| 264 | .translate(key, &refs) |
| 265 | .map_err(|error| ConfigCommandResult { |
| 266 | message: Some(error), |
| 267 | action: None, |
| 268 | is_error: true, |
| 269 | })?; |
| 270 | prepared.templates.insert((*key).to_string(), template); |
| 271 | } |
| 272 | Ok(prepared) |
| 273 | } |
| 274 | |
| 275 | fn missing(facet: &str) -> ConfigCommandResult { |
| 276 | ConfigCommandResult { |
| 277 | message: Some(format!("Command capability unavailable: {facet}")), |
| 278 | action: None, |
| 279 | is_error: true, |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /// `/config [ask-rules|status|<key> [value]|preset|workflow|...]`. |
| 284 | /// `/config [ask-rules|status|<key> [value]|preset|workflow|subagents|search|notifications|tui|web|native]`. |
| 285 | /// |
| 286 | /// The command owns the top-level subcommand routing, the `--save` parse and the |
| 287 | /// ask-rules forwarding; the facet performs the per-key work behind typed |
| 288 | /// operations. |
| 289 | pub fn config(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 290 | let raw = arg.map(str::trim).unwrap_or(""); |
| 291 | if raw.is_empty() { |
| 292 | return ConfigCommandResult::action(ConfigAction::OpenConfigView); |
| 293 | } |
| 294 | if matches!( |
| 295 | raw.to_ascii_lowercase().as_str(), |
| 296 | "audit" | "editability" | "editable" | "status" |
| 297 | ) { |
| 298 | let mut parts = contexts.into_parts(); |
| 299 | if parts.config.is_none() { |
| 300 | return missing("config"); |
| 301 | } |
| 302 | let prepared = match preflight_with(&mut parts, AUDIT_TEMPLATES) { |
| 303 | Ok(prepared) => prepared, |
| 304 | Err(result) => return result, |
| 305 | }; |
| 306 | let report = match parts.config.as_deref_mut() { |
| 307 | Some(facet) => match facet.audit() { |
| 308 | Ok(report) => report, |
| 309 | Err(error) => return ConfigCommandResult::error(error), |
| 310 | }, |
| 311 | None => return missing("config"), |
| 312 | }; |
| 313 | let mut message = vec![ConfigMessage::literal(format!( |
| 314 | "Config editability audit\nConfig path: {}\nKey | Current | Editability | Command / reason", |
| 315 | report.config_path |
| 316 | ))]; |
| 317 | for row in &report.rows { |
| 318 | message.push(ConfigMessage::literal(format!( |
| 319 | "\n{} | {} | {} | {}\n ", |
| 320 | row.key, row.current, row.editability, row.command |
| 321 | ))); |
| 322 | message.push(row.note.clone()); |
| 323 | } |
| 324 | return to_result( |
| 325 | ConfigReply::message(ConfigMessage::concat(message)), |
| 326 | &mut parts, |
| 327 | &prepared, |
| 328 | ); |
| 329 | } |
| 330 | let mut raw_words = raw.splitn(2, char::is_whitespace); |
| 331 | let first_word = raw_words.next(); |
| 332 | if first_word.is_some_and(is_ask_rules_config_token) { |
| 333 | let rest = raw_words.next().unwrap_or("").trim(); |
| 334 | return super::policy::permissions::execute(contexts, Some(rest)); |
| 335 | } |
| 336 | let is_workflow = first_word.is_some_and(|token| { |
| 337 | token.eq_ignore_ascii_case("workflow") || token.eq_ignore_ascii_case("goal") |
| 338 | }) && raw_words |
| 339 | .clone() |
| 340 | .next() |
| 341 | .is_none_or(|rest| rest.trim().is_empty()); |
| 342 | let is_subagents = first_word.is_some_and(|token| token.eq_ignore_ascii_case("subagents")); |
| 343 | let is_search = first_word.is_some_and(|token| token.eq_ignore_ascii_case("search")); |
| 344 | let is_notifications = first_word.is_some_and(|token| { |
| 345 | token.eq_ignore_ascii_case("notifications") || token.eq_ignore_ascii_case("notification") |
| 346 | }); |
| 347 | let is_preset = first_word.is_some_and(|token| token.eq_ignore_ascii_case("preset")); |
| 348 | |
| 349 | let mut parts = contexts.into_parts(); |
| 350 | if parts.config.is_none() { |
| 351 | return missing("config"); |
| 352 | } |
| 353 | let prepared = match preflight(&mut parts) { |
| 354 | Ok(prepared) => prepared, |
| 355 | Err(result) => return result, |
| 356 | }; |
| 357 | let Some(facet) = parts.config.as_deref_mut() else { |
| 358 | return missing("config"); |
| 359 | }; |
| 360 | if is_workflow { |
| 361 | return ConfigCommandResult::message(render_workflow_summary(facet.workflow_summary())); |
| 362 | } |
| 363 | if is_subagents { |
| 364 | let rest = raw_words.next().unwrap_or("").trim(); |
| 365 | let (op, persist) = parse_subagent_rest(rest); |
| 366 | let reply = match op { |
| 367 | SubagentOp::Status => { |
| 368 | return match facet.subagents_status() { |
| 369 | Ok(report) => { |
| 370 | let mut lines = vec![ |
| 371 | format!( |
| 372 | "Sub-agents: {}", |
| 373 | report.disabled_reason.as_deref().map_or_else( |
| 374 | || "enabled".to_string(), |
| 375 | |reason| format!("disabled ({reason})"), |
| 376 | ) |
| 377 | ), |
| 378 | format!("Config path: {}", report.config_path), |
| 379 | format!( |
| 380 | "Active provider: {} ({})", |
| 381 | report.provider_key, report.provider_label |
| 382 | ), |
| 383 | format!( |
| 384 | "subagents.enabled = {}", |
| 385 | report.explicit_enabled.map_or_else( |
| 386 | || "default true".to_string(), |
| 387 | |value| value.to_string() |
| 388 | ) |
| 389 | ), |
| 390 | ]; |
| 391 | for limit in &report.limits { |
| 392 | lines.push(format!( |
| 393 | "subagents.{} = {} (resolved global {}; active provider {})", |
| 394 | limit.key, limit.raw, limit.global, limit.provider |
| 395 | )); |
| 396 | } |
| 397 | match &report.provider_rows { |
| 398 | Some(rows) => { |
| 399 | for row in rows { |
| 400 | lines.push(format!( |
| 401 | "subagents.providers.{}.{} = {}", |
| 402 | report.provider_key, row.key, row.value |
| 403 | )); |
| 404 | } |
| 405 | } |
| 406 | None => lines.push(format!( |
| 407 | "subagents.providers.{} = inherits global", |
| 408 | report.provider_key |
| 409 | )), |
| 410 | } |
| 411 | ConfigCommandResult::message(lines.join("\n")) |
| 412 | } |
| 413 | Err(error) => ConfigCommandResult::error(error), |
| 414 | }; |
| 415 | } |
| 416 | SubagentOp::Get(key) => facet.subagent(key), |
| 417 | SubagentOp::Set { key, value } => facet.set_subagent(key, value, persist), |
| 418 | SubagentOp::Usage => { |
| 419 | return ConfigCommandResult::error( |
| 420 | "Usage: /config subagents [status|on|off|enabled|max_concurrent|max_depth|launch_concurrency|api_timeout_secs|heartbeat_timeout_secs <value>] [--save]", |
| 421 | ); |
| 422 | } |
| 423 | }; |
| 424 | return to_result(reply, &mut parts, &prepared); |
| 425 | } |
| 426 | if is_search { |
| 427 | let rest = raw_words.next().unwrap_or("").trim(); |
| 428 | let (op, persist) = parse_search_rest(rest); |
| 429 | let reply = match op { |
| 430 | SearchOp::Status => facet.search_provider_status(), |
| 431 | SearchOp::Set(value) => facet.set_search_provider(value, persist), |
| 432 | SearchOp::Usage => { |
| 433 | return to_result( |
| 434 | ConfigReply::error(ConfigMessage::concat(vec![ |
| 435 | ConfigMessage::keyed("help_usage_label"), |
| 436 | ConfigMessage::literal(format!( |
| 437 | " /config search.provider <{}> [--save]", |
| 438 | facet.search_provider_names(), |
| 439 | )), |
| 440 | ])), |
| 441 | &mut parts, |
| 442 | &prepared, |
| 443 | ); |
| 444 | } |
| 445 | }; |
| 446 | return to_result(reply, &mut parts, &prepared); |
| 447 | } |
| 448 | if is_notifications { |
| 449 | let rest = raw_words.next().unwrap_or("").trim(); |
| 450 | let (op, persist) = parse_notifications_rest(rest); |
| 451 | let reply = match op { |
| 452 | NotificationsOp::Status => facet.notifications_status(), |
| 453 | NotificationsOp::Get(key) => facet.notification(key), |
| 454 | NotificationsOp::Set { key, value } => facet.set_notification(key, value, persist), |
| 455 | }; |
| 456 | return to_result(reply, &mut parts, &prepared); |
| 457 | } |
| 458 | |
| 459 | if is_preset { |
| 460 | let rest = raw_words.next().unwrap_or("").trim(); |
| 461 | let tokens = rest.split_whitespace().collect::<Vec<_>>(); |
| 462 | let persist = matches!(tokens.last(), Some(&"--save") | Some(&"-s")); |
| 463 | let name = tokens.first().copied().unwrap_or(""); |
| 464 | return to_result(facet.apply_preset(name, persist), &mut parts, &prepared); |
| 465 | } |
| 466 | let key = first_word.unwrap_or(raw); |
| 467 | match raw_words.next() { |
| 468 | None => { |
| 469 | if matches!(key.to_ascii_lowercase().as_str(), "tui" | "web" | "native") { |
| 470 | return ConfigCommandResult::action(ConfigAction::OpenConfigView); |
| 471 | } |
| 472 | to_result(facet.get_value(key), &mut parts, &prepared) |
| 473 | } |
| 474 | Some(rest) => { |
| 475 | let (value, persist) = split_save_flag(rest); |
| 476 | to_result(facet.set_value(key, value, persist), &mut parts, &prepared) |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | /// Whether a `/config` token forwards to the permission-rules editor. |
| 482 | fn is_ask_rules_config_token(token: &str) -> bool { |
| 483 | matches!( |
| 484 | token.to_ascii_lowercase().as_str(), |
| 485 | "ask-rules" |
| 486 | | "ask_rules" |
| 487 | | "askrules" |
| 488 | | "rules" |
| 489 | | "permission-rules" |
| 490 | | "permission_rules" |
| 491 | | "permissions" |
| 492 | ) |
| 493 | } |
| 494 | |
| 495 | /// `/settings [text]`. |
| 496 | /// `/settings [text]`. The command owns the argument routing; the facet returns |
| 497 | /// the resolved settings text. |
| 498 | pub fn settings(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 499 | match arg.map(str::trim).filter(|value| !value.is_empty()) { |
| 500 | None => ConfigCommandResult::action(ConfigAction::OpenConfigView), |
| 501 | Some("text" | "show" | "diagnostic" | "diagnostics") => { |
| 502 | let mut parts = contexts.into_parts(); |
| 503 | if parts.config.is_none() { |
| 504 | return missing("config"); |
| 505 | } |
| 506 | let prepared = match preflight_with(&mut parts, SETTINGS_TEMPLATES) { |
| 507 | Ok(prepared) => prepared, |
| 508 | Err(result) => return result, |
| 509 | }; |
| 510 | let Some(facet) = parts.config.as_deref_mut() else { |
| 511 | return missing("config"); |
| 512 | }; |
| 513 | let reply = match facet.show_settings() { |
| 514 | Ok(report) => { |
| 515 | let mut message = vec![ |
| 516 | ConfigMessage::keyed("settings_title"), |
| 517 | ConfigMessage::literal("\n─────────────────────────────\n"), |
| 518 | ]; |
| 519 | let mut rows = String::new(); |
| 520 | for row in &report.rows { |
| 521 | rows.push_str(&format!( |
| 522 | " {:<width$}{}", |
| 523 | row.label, |
| 524 | row.value, |
| 525 | width = row.label_width |
| 526 | )); |
| 527 | rows.push('\n'); |
| 528 | } |
| 529 | message.push(ConfigMessage::literal(rows)); |
| 530 | message.push(ConfigMessage::literal("\n")); |
| 531 | message.push(ConfigMessage::keyed("settings_config_file")); |
| 532 | let mut tail = format!(" {}", report.config_file); |
| 533 | if !report.from_settings.is_empty() || !report.session_overrides.is_empty() { |
| 534 | tail.push_str("\n\n"); |
| 535 | if !report.from_settings.is_empty() { |
| 536 | tail.push_str(&format!( |
| 537 | " from settings.toml: {}", |
| 538 | report.from_settings.join(", ") |
| 539 | )); |
| 540 | } |
| 541 | if !report.session_overrides.is_empty() { |
| 542 | if !report.from_settings.is_empty() { |
| 543 | tail.push('\n'); |
| 544 | } |
| 545 | tail.push_str(&format!( |
| 546 | " session override: {}", |
| 547 | report.session_overrides.join(", ") |
| 548 | )); |
| 549 | } |
| 550 | } |
| 551 | message.push(ConfigMessage::literal(tail)); |
| 552 | ConfigReply::message(ConfigMessage::concat(message)) |
| 553 | } |
| 554 | Err(error) => ConfigReply::error(error), |
| 555 | }; |
| 556 | to_result(reply, &mut parts, &prepared) |
| 557 | } |
| 558 | Some(_) => ConfigCommandResult::error("Usage: /settings [text]"), |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | /// `/mode [work|plan|1|2]` (alias `/jihua`). A retired Operate |
| 563 | /// spelling selects Work and says so. |
| 564 | /// |
| 565 | /// The command owns the alias handling, parse and message composition; the |
| 566 | /// mode-policy facet applies the selection and reports the outcome. |
| 567 | pub fn mode(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 568 | let Some(arg) = arg.filter(|value| !value.trim().is_empty()) else { |
| 569 | return ConfigCommandResult::action(ConfigAction::OpenModePicker); |
| 570 | }; |
| 571 | if let Some(plan_result) = parse_mode_plan_artifact_action(arg) { |
| 572 | return plan_result; |
| 573 | } |
| 574 | let mut parts = contexts.into_parts(); |
| 575 | let Some(facet) = parts.mode_policy.as_deref_mut() else { |
| 576 | return missing("mode_policy"); |
| 577 | }; |
| 578 | if CommandMode::is_legacy_bypass_alias(arg) { |
| 579 | return ConfigCommandResult::message( |
| 580 | "Full Access is a permission posture, not a mode. Press Shift+Tab to choose Full Access (or use /auto for Auto-Review).", |
| 581 | ); |
| 582 | } |
| 583 | let retired = if CommandMode::is_retired_operate_alias(arg) { |
| 584 | " Operate mode was retired; /fleet runs parallel agents." |
| 585 | } else { |
| 586 | "" |
| 587 | }; |
| 588 | match CommandMode::parse(arg) { |
| 589 | Some(mode) => { |
| 590 | let selection = facet.select_mode(mode); |
| 591 | let label = facet.mode_label(mode); |
| 592 | match selection { |
| 593 | CommandModeSelection::Changed => ConfigCommandResult::with_message_and_action( |
| 594 | format!("Switched to {label} mode.{retired}"), |
| 595 | ConfigAction::ModeChanged(mode), |
| 596 | ), |
| 597 | CommandModeSelection::PersistedSame => ConfigCommandResult::message(format!( |
| 598 | "{}{retired}", |
| 599 | facet.mode_startup_default_receipt(mode) |
| 600 | )), |
| 601 | CommandModeSelection::Refused => { |
| 602 | ConfigCommandResult::message(facet.setting_locked_mode_message()) |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | None if is_conversation_mode_word(arg) => { |
| 607 | ConfigCommandResult::action(ConfigAction::SetConversationMode { |
| 608 | id: arg.trim().to_ascii_lowercase(), |
| 609 | }) |
| 610 | } |
| 611 | None => ConfigCommandResult::error(format!("Usage: {MODE_USAGE}")), |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | pub(super) fn view_plan(arg: Option<&str>) -> ConfigCommandResult { |
| 616 | ConfigCommandResult::action(ConfigAction::OpenPlanArtifact { |
| 617 | arg: arg.map(str::to_owned), |
| 618 | }) |
| 619 | } |
| 620 | |
| 621 | fn parse_mode_plan_artifact_action(arg: &str) -> Option<ConfigCommandResult> { |
| 622 | let tokens: Vec<&str> = arg.split_whitespace().collect(); |
| 623 | if tokens.len() < 2 || !tokens[0].eq_ignore_ascii_case("plan") { |
| 624 | return None; |
| 625 | } |
| 626 | if tokens.len() > 2 { |
| 627 | return Some(ConfigCommandResult::error( |
| 628 | "Usage: /mode plan [view|save|edit|build]", |
| 629 | )); |
| 630 | } |
| 631 | let normalized = match tokens[1].to_ascii_lowercase().as_str() { |
| 632 | "view" | "show" | "open" => "view", |
| 633 | "save" => "save", |
| 634 | "edit" => "edit", |
| 635 | "build" | "run" | "exec" => "build", |
| 636 | _ => { |
| 637 | return Some(ConfigCommandResult::error( |
| 638 | "Usage: /mode plan [view|save|edit|build]", |
| 639 | )); |
| 640 | } |
| 641 | }; |
| 642 | Some(view_plan(Some(normalized))) |
| 643 | } |
| 644 | |
| 645 | fn is_conversation_mode_word(arg: &str) -> bool { |
| 646 | let arg = arg.trim(); |
| 647 | !arg.is_empty() |
| 648 | && arg.len() <= 64 |
| 649 | && !arg.chars().all(|c| c.is_ascii_digit()) |
| 650 | && arg |
| 651 | .chars() |
| 652 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) |
| 653 | } |
| 654 | |
| 655 | /// `/mode` usage, shared with the registration metadata. |
| 656 | pub(super) const MODE_USAGE: &str = |
| 657 | "/mode [work|plan [view|save|edit|build]|1|2|<conversation mode>]"; |
| 658 | |
| 659 | /// `/whale` usage, shared with the registration metadata. |
| 660 | pub const WHALE_USAGE: &str = "/whale [full|still|name <text>|color <name|#rrggbb|default>]"; |
| 661 | |
| 662 | pub fn connect(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 663 | let raw = arg.map(str::trim).unwrap_or(""); |
| 664 | if raw.split_whitespace().count() > 1 { |
| 665 | return ConfigCommandResult::error("Usage: /connect [account|<provider>]"); |
| 666 | } |
| 667 | let mut parts = contexts.into_parts(); |
| 668 | let Some(facet) = parts.login.as_deref_mut() else { |
| 669 | return missing("login"); |
| 670 | }; |
| 671 | if raw.is_empty() { |
| 672 | return ConfigCommandResult::action(ConfigAction::OpenModelConnectionSetup); |
| 673 | } |
| 674 | if matches!(raw, "account" | "codewhale") { |
| 675 | return ConfigCommandResult::action(ConfigAction::StartAccountConnect); |
| 676 | } |
| 677 | let provider = (!raw.is_empty()).then_some(raw); |
| 678 | let reply = facet.connect(provider); |
| 679 | to_result(reply, &mut parts, &PreparedTemplates::default()) |
| 680 | } |
| 681 | |
| 682 | /// `/disconnect <provider>` — sign out of an enabled plugin provider. |
| 683 | pub fn disconnect(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 684 | let raw = arg.map(str::trim).unwrap_or(""); |
| 685 | if raw.is_empty() || raw.split_whitespace().count() > 1 { |
| 686 | return ConfigCommandResult::error("Usage: /disconnect <provider>"); |
| 687 | } |
| 688 | let mut parts = contexts.into_parts(); |
| 689 | let Some(facet) = parts.login.as_deref_mut() else { |
| 690 | return missing("login"); |
| 691 | }; |
| 692 | let reply = facet.disconnect(raw); |
| 693 | to_result(reply, &mut parts, &PreparedTemplates::default()) |
| 694 | } |
| 695 | |
| 696 | /// `/theme [name|underwater|custom:<name>|schema|path]`. |
| 697 | /// `/theme [name|underwater|custom:<name>|schema|path]`. |
| 698 | pub fn theme(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 699 | let mut parts = contexts.into_parts(); |
| 700 | if parts.config.is_none() { |
| 701 | return missing("config"); |
| 702 | } |
| 703 | match arg.map(str::trim).filter(|s| !s.is_empty()) { |
| 704 | // `schema`/`path`/no-arg render no config message, so they do not |
| 705 | // depend on the config translation templates. |
| 706 | None => ConfigCommandResult::action(ConfigAction::OpenThemePicker), |
| 707 | Some("schema") => match parts.config.as_deref_mut() { |
| 708 | Some(facet) => ConfigCommandResult::message(facet.theme_schema()), |
| 709 | None => missing("config"), |
| 710 | }, |
| 711 | Some("path") => { |
| 712 | let Some(facet) = parts.config.as_deref_mut() else { |
| 713 | return missing("config"); |
| 714 | }; |
| 715 | match facet.themes_dir() { |
| 716 | Ok(path) => ConfigCommandResult::message(format!( |
| 717 | "User themes: {path}\nSelect with: /theme custom:<name>" |
| 718 | )), |
| 719 | Err(error) => ConfigCommandResult::error(error), |
| 720 | } |
| 721 | } |
| 722 | Some(name) => { |
| 723 | let prepared = match preflight(&mut parts) { |
| 724 | Ok(prepared) => prepared, |
| 725 | Err(result) => return result, |
| 726 | }; |
| 727 | let Some(facet) = parts.config.as_deref_mut() else { |
| 728 | return missing("config"); |
| 729 | }; |
| 730 | to_result(facet.set_value("theme", name, true), &mut parts, &prepared) |
| 731 | } |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | /// `/verbose [on|off]`. |
| 736 | /// |
| 737 | /// The command keeps its own parsing and message composition; the facet only |
| 738 | /// reads and writes the flag (FEAT-028: keep logic in the command, replace only |
| 739 | /// the surgical host touch). |
| 740 | pub fn verbose(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 741 | let mut parts = contexts.into_parts(); |
| 742 | if parts.config.is_none() { |
| 743 | return missing("config"); |
| 744 | } |
| 745 | let Some(facet) = parts.config.as_deref_mut() else { |
| 746 | return missing("config"); |
| 747 | }; |
| 748 | let next = match arg.map(str::trim).filter(|s| !s.is_empty()) { |
| 749 | None => !facet.verbose_enabled(), |
| 750 | Some(raw) => match raw.to_ascii_lowercase().as_str() { |
| 751 | "on" | "true" | "1" | "yes" => true, |
| 752 | "off" | "false" | "0" | "no" => false, |
| 753 | "toggle" => !facet.verbose_enabled(), |
| 754 | _ => { |
| 755 | return ConfigCommandResult { |
| 756 | message: Some( |
| 757 | "Usage: /verbose [on|off]. Compact thinking remains available when verbose is off." |
| 758 | .to_string(), |
| 759 | ), |
| 760 | action: None, |
| 761 | is_error: true, |
| 762 | }; |
| 763 | } |
| 764 | }, |
| 765 | }; |
| 766 | facet.set_verbose_enabled(next); |
| 767 | ConfigCommandResult::message(if next { |
| 768 | "Verbose transcript on: live thinking renders in full." |
| 769 | } else { |
| 770 | "Verbose transcript off: live thinking stays compact." |
| 771 | }) |
| 772 | } |
| 773 | |
| 774 | /// `/statusline` — pure: it only opens the statusline picker, so it declares no |
| 775 | /// capability and needs no host facet. |
| 776 | pub fn statusline(_arg: Option<&str>) -> ConfigCommandResult { |
| 777 | ConfigCommandResult { |
| 778 | message: None, |
| 779 | action: Some(ConfigAction::OpenStatusPicker), |
| 780 | is_error: false, |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | pub(super) const WORKBAR_USAGE: &str = |
| 785 | "/workbar [bottom|top|left|right|off|tasks|agents|terminal|context|pinned] [--save]"; |
| 786 | |
| 787 | /// `/workbar` (aliases `/rail`, `/sidebar`). |
| 788 | /// `/workbar [bottom|top|left|right|off|panel] [--save]` (aliases `/rail`, |
| 789 | /// `/sidebar`). The command owns token parsing and the status line; the facet |
| 790 | /// observes and applies the work-surface state. |
| 791 | pub fn workbar(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 792 | let usage_error = || ConfigCommandResult::error(format!("Usage: {WORKBAR_USAGE}")); |
| 793 | let raw = arg.map(str::trim).unwrap_or(""); |
| 794 | let mut tokens = raw.split_whitespace().collect::<Vec<_>>(); |
| 795 | let persist = matches!(tokens.last(), Some(&"--save" | &"-s")); |
| 796 | if persist { |
| 797 | tokens.pop(); |
| 798 | } |
| 799 | let mut parts = contexts.into_parts(); |
| 800 | // `/workbar` status and its setter errors are literal, so it needs no |
| 801 | // presentation and must not depend on the config translation templates. |
| 802 | let prepared = PreparedTemplates::default(); |
| 803 | let Some(facet) = parts.work_surface.as_deref_mut() else { |
| 804 | return missing("work_surface"); |
| 805 | }; |
| 806 | match tokens.as_slice() { |
| 807 | [] => return ConfigCommandResult::message(rail_status(facet)), |
| 808 | [value] => { |
| 809 | let value = value.to_ascii_lowercase(); |
| 810 | let placement = match value.as_str() { |
| 811 | "top" => Some(CommandWorkSurfacePlacement::Top), |
| 812 | "bottom" | "on" | "show" | "visible" => Some(CommandWorkSurfacePlacement::Bottom), |
| 813 | "left" => Some(CommandWorkSurfacePlacement::Left), |
| 814 | "right" => Some(CommandWorkSurfacePlacement::Right), |
| 815 | "off" | "hide" | "hidden" | "closed" | "none" => { |
| 816 | Some(CommandWorkSurfacePlacement::Off) |
| 817 | } |
| 818 | _ => None, |
| 819 | }; |
| 820 | let panel = match value.as_str() { |
| 821 | "tasks" | "activity" | "live" | "running" | "pinned" | "work" | "plan" |
| 822 | | "todos" => Some(CommandRailPanel::Tasks), |
| 823 | "agents" | "subagents" | "sub-agents" => Some(CommandRailPanel::Agents), |
| 824 | "background" | "shells" | "jobs" => Some(CommandRailPanel::Background), |
| 825 | "files" | "changes" => Some(CommandRailPanel::Files), |
| 826 | "terminal" | "terminals" => Some(CommandRailPanel::Terminal), |
| 827 | "notepad" | "notes" => Some(CommandRailPanel::Notepad), |
| 828 | "context" | "session" => Some(CommandRailPanel::Context), |
| 829 | "git" | "branch" => Some(CommandRailPanel::Git), |
| 830 | "price" | "cost" => Some(CommandRailPanel::Price), |
| 831 | _ => None, |
| 832 | }; |
| 833 | match (placement, panel) { |
| 834 | (Some(placement), None) => { |
| 835 | // Surface a setter error whether or not `--save` was given; |
| 836 | // discarding it would report a success that did not happen. |
| 837 | let reply = facet.set_placement(placement, persist); |
| 838 | if reply.is_error { |
| 839 | return to_result(reply, &mut parts, &prepared); |
| 840 | } |
| 841 | } |
| 842 | (None, Some(panel)) => { |
| 843 | let reply = facet.set_panel(panel, persist); |
| 844 | if reply.is_error { |
| 845 | return to_result(reply, &mut parts, &prepared); |
| 846 | } |
| 847 | } |
| 848 | _ => return usage_error(), |
| 849 | } |
| 850 | } |
| 851 | _ => return usage_error(), |
| 852 | } |
| 853 | facet.mark_redraw(); |
| 854 | ConfigCommandResult::message(rail_status(facet)) |
| 855 | } |
| 856 | |
| 857 | fn rail_status(facet: &dyn CommandWorkSurfaceContext) -> String { |
| 858 | let placement = facet.placement(); |
| 859 | if placement == CommandWorkSurfacePlacement::Off { |
| 860 | return "Workbar is off — no panel renders (/workbar bottom|top|left|right to show it)" |
| 861 | .to_string(); |
| 862 | } |
| 863 | let panel = facet.panel(); |
| 864 | let mut message = format!( |
| 865 | "Workbar: {} placement, {} panel", |
| 866 | placement.as_setting(), |
| 867 | facet.panel_title(panel) |
| 868 | ); |
| 869 | let effective = facet.effective_placement(); |
| 870 | if effective != placement && effective == CommandWorkSurfacePlacement::Top { |
| 871 | message.push_str(" — side placements need a wider terminal, showing top for now"); |
| 872 | } |
| 873 | if !facet.area_present() { |
| 874 | if panel == CommandRailPanel::Tasks { |
| 875 | message.push_str(" (currently hidden — no work to show)"); |
| 876 | } else { |
| 877 | message.push_str(" (renders next frame)"); |
| 878 | } |
| 879 | } |
| 880 | message |
| 881 | } |
| 882 | |
| 883 | /// `/login [status|account|key]`. |
| 884 | pub fn login(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 885 | let raw = arg.map(str::trim).unwrap_or(""); |
| 886 | let token = raw.split_whitespace().next().unwrap_or(""); |
| 887 | let mut parts = contexts.into_parts(); |
| 888 | let Some(facet) = parts.login.as_deref_mut() else { |
| 889 | return missing("login"); |
| 890 | }; |
| 891 | match token { |
| 892 | "" | "account" => ConfigCommandResult::action(ConfigAction::StartAccountLogin), |
| 893 | "status" => { |
| 894 | let status = facet.login_status(); |
| 895 | let account = match status.account { |
| 896 | CommandAccountState::SignedOut => { |
| 897 | format!("not signed in (api {})", status.api_base) |
| 898 | } |
| 899 | CommandAccountState::Authenticated => { |
| 900 | format!("signed in (api {})", status.api_base) |
| 901 | } |
| 902 | CommandAccountState::OfflineCached => { |
| 903 | format!("offline cached (api {})", status.api_base) |
| 904 | } |
| 905 | CommandAccountState::Expired => format!("expired (api {})", status.api_base), |
| 906 | CommandAccountState::Revoked => format!("revoked (api {})", status.api_base), |
| 907 | CommandAccountState::Unavailable(error) => format!("unavailable ({error})"), |
| 908 | }; |
| 909 | let sign_in = if status.sign_in_open { |
| 910 | "Sign in: `codewhale login`\n" |
| 911 | } else { |
| 912 | "" |
| 913 | }; |
| 914 | ConfigCommandResult::message(format!( |
| 915 | "Codewhale login\nAccount: {account}\nActive provider: {}\n\n\ |
| 916 | {sign_in}\ |
| 917 | Provider key: `codewhale auth set --provider <id>` or `/provider`\n\ |
| 918 | Sign out: `/logout` or `codewhale logout`", |
| 919 | status.provider |
| 920 | )) |
| 921 | } |
| 922 | "key" | "provider" => ConfigCommandResult::action(ConfigAction::OpenProviderPicker), |
| 923 | other => ConfigCommandResult::error(format!( |
| 924 | "Usage: /login [status|account|key]\nUnknown argument: {other}\n\ |
| 925 | To sign in to a plugin provider, use `/connect <provider>`." |
| 926 | )), |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | pub fn logout(contexts: CommandContexts<'_>, _arg: Option<&str>) -> ConfigCommandResult { |
| 931 | if contexts.into_parts().login.is_none() { |
| 932 | return missing("login"); |
| 933 | } |
| 934 | ConfigCommandResult::action(ConfigAction::StartAccountLogout) |
| 935 | } |
| 936 | |
| 937 | /// `/import-claude [--apply]`. |
| 938 | /// `/import-claude [--apply]`. The command owns the flow and messages; the facet |
| 939 | /// builds the plan, writes the artifacts and carries over the standing |
| 940 | /// instructions. |
| 941 | pub fn import_claude(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 942 | let apply = arg.map(str::trim).is_some_and(|arg| { |
| 943 | arg.eq_ignore_ascii_case("--apply") || arg.eq_ignore_ascii_case("apply") |
| 944 | }); |
| 945 | let mut parts = contexts.into_parts(); |
| 946 | if parts.config.is_none() { |
| 947 | return missing("config"); |
| 948 | } |
| 949 | let Some(facet) = parts.config.as_deref_mut() else { |
| 950 | return missing("config"); |
| 951 | }; |
| 952 | let Some(plan) = facet.build_plan() else { |
| 953 | return ConfigCommandResult::message( |
| 954 | "No Claude configuration found to import (looked for ~/.claude.json and ~/.claude/settings.json).", |
| 955 | ); |
| 956 | }; |
| 957 | let report = super::import_claude::report_markdown(&plan, &|path| facet.display_path(path)); |
| 958 | let bundle = if plan.env_safe.is_empty() { |
| 959 | None |
| 960 | } else { |
| 961 | Some(super::import_claude::portable_bundle_json(&plan)) |
| 962 | }; |
| 963 | let artifacts = facet.write_artifacts(&report, bundle.as_deref()); |
| 964 | if apply { |
| 965 | let outcome = facet.apply_import(&plan, &artifacts.report_path, artifacts.wrote_report); |
| 966 | let mut message = String::new(); |
| 967 | if outcome.done.is_empty() { |
| 968 | message.push_str("Nothing was applied.\n"); |
| 969 | } else { |
| 970 | message.push_str("Applied:\n"); |
| 971 | for item in &outcome.done { |
| 972 | message.push_str(&format!(" · {}\n", render_follow_up(item))); |
| 973 | } |
| 974 | } |
| 975 | if !outcome.manual.is_empty() { |
| 976 | message.push_str("\nStill yours to do:\n"); |
| 977 | for item in &outcome.manual { |
| 978 | message.push_str(&format!(" · {}\n", render_follow_up(item))); |
| 979 | } |
| 980 | } |
| 981 | if !outcome.done.is_empty() { |
| 982 | message.push_str( |
| 983 | "\nRun /mcp reload to connect the imported servers after reviewing them.", |
| 984 | ); |
| 985 | } |
| 986 | if outcome.wrote_report { |
| 987 | message.push_str(&format!( |
| 988 | "\nFull report: {}", |
| 989 | facet.display_path(&outcome.report_path) |
| 990 | )); |
| 991 | } else { |
| 992 | if !plan.sources.is_empty() { |
| 993 | message.push_str("\nSources:\n"); |
| 994 | for (path, status) in &plan.sources { |
| 995 | message.push_str(&format!( |
| 996 | " · {}\n", |
| 997 | status.describe(&facet.display_path(path)) |
| 998 | )); |
| 999 | } |
| 1000 | } |
| 1001 | message.push_str("\n(the report could not be written; the summary above is complete)"); |
| 1002 | } |
| 1003 | if bundle.is_some() && !artifacts.wrote_bundle { |
| 1004 | message.push_str("\n(the portable bundle could not be written)"); |
| 1005 | } |
| 1006 | return ConfigCommandResult::message(message); |
| 1007 | } |
| 1008 | let mut message = super::import_claude::render_plan(&plan, &|path| facet.display_path(path)); |
| 1009 | message.push_str( |
| 1010 | "\n\nNothing above is applied yet. `/import-claude --apply` carries over the \ |
| 1011 | standing instructions. Review MCP servers individually with `/mcp import`; hooks and \ |
| 1012 | permission rules stay manual because they run code.", |
| 1013 | ); |
| 1014 | if artifacts.wrote_report { |
| 1015 | message.push_str(&format!( |
| 1016 | "\nFull report: {}", |
| 1017 | facet.display_path(&artifacts.report_path) |
| 1018 | )); |
| 1019 | } else { |
| 1020 | message.push_str("\n(the report could not be written; the plan above is complete)"); |
| 1021 | } |
| 1022 | if artifacts.wrote_bundle { |
| 1023 | message.push_str(&format!( |
| 1024 | "\nPortable bundle (review, then `codewhale config import {}`): apply it there for the consent/rollback path.", |
| 1025 | facet.display_path(&artifacts.bundle_path) |
| 1026 | )); |
| 1027 | } else if bundle.is_some() { |
| 1028 | message.push_str("\n(the portable bundle could not be written)"); |
| 1029 | } |
| 1030 | ConfigCommandResult::message(message) |
| 1031 | } |
| 1032 | |
| 1033 | /// `/whale [full|still|name <text>|color <#rrggbb|default>]`. |
| 1034 | /// Bare `/whale` and `full` toggle the whale view; `on` and `off` set it. |
| 1035 | /// The command owns the verb parsing and message composition; the whale facet |
| 1036 | /// observes and mutates the whale state and resolves the localized labels. |
| 1037 | pub fn whale(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 1038 | let raw = arg.map(str::trim).unwrap_or(""); |
| 1039 | let (verb, rest) = match raw.split_once(char::is_whitespace) { |
| 1040 | Some((verb, rest)) => (verb, rest.trim()), |
| 1041 | None => (raw, ""), |
| 1042 | }; |
| 1043 | let verb = verb.to_ascii_lowercase(); |
| 1044 | let mut parts = contexts.into_parts(); |
| 1045 | let Some(facet) = parts.pet.as_deref_mut() else { |
| 1046 | return missing("whale"); |
| 1047 | }; |
| 1048 | let usage = || ConfigCommandResult::error(format!("Usage: {WHALE_USAGE}")); |
| 1049 | let view = |facet: &mut dyn CommandPetContext, enabled: bool| -> ConfigCommandResult { |
| 1050 | facet.set_enabled(enabled, true); |
| 1051 | ConfigCommandResult::message(facet.label(if enabled { |
| 1052 | CommandPetLabel::ModeOn |
| 1053 | } else { |
| 1054 | CommandPetLabel::ModeOff |
| 1055 | })) |
| 1056 | }; |
| 1057 | match (verb.as_str(), rest) { |
| 1058 | ("" | "full", "") => { |
| 1059 | let enabled = !facet.enabled(); |
| 1060 | view(facet, enabled) |
| 1061 | } |
| 1062 | ("on", "") => view(facet, true), |
| 1063 | ("off", "") => view(facet, false), |
| 1064 | ("still", "") => { |
| 1065 | let still = !facet.still(); |
| 1066 | facet.set_still(still); |
| 1067 | ConfigCommandResult::message(facet.label(if still { |
| 1068 | CommandPetLabel::StillOn |
| 1069 | } else { |
| 1070 | CommandPetLabel::StillOff |
| 1071 | })) |
| 1072 | } |
| 1073 | ("name" | "color" | "colour", "") => usage(), |
| 1074 | ("name", text) => { |
| 1075 | let name = match normalize_whale_name(text) { |
| 1076 | Ok(Some(name)) => name, |
| 1077 | Ok(None) => return usage(), |
| 1078 | Err(error) => return ConfigCommandResult::error(error), |
| 1079 | }; |
| 1080 | facet.set_name(&name); |
| 1081 | ConfigCommandResult::message( |
| 1082 | facet.label(CommandPetLabel::Named).replace("{name}", &name), |
| 1083 | ) |
| 1084 | } |
| 1085 | ("color" | "colour", value) => { |
| 1086 | let color = match normalize_whale_color(value) { |
| 1087 | Ok(color) => color, |
| 1088 | Err(error) => return ConfigCommandResult::error(error), |
| 1089 | }; |
| 1090 | facet.set_color(color.as_deref()); |
| 1091 | ConfigCommandResult::message(match color { |
| 1092 | Some(color) => facet |
| 1093 | .label(CommandPetLabel::Colored) |
| 1094 | .replace("{color}", &color), |
| 1095 | None => facet.label(CommandPetLabel::ColorReset), |
| 1096 | }) |
| 1097 | } |
| 1098 | _ => usage(), |
| 1099 | } |
| 1100 | } |
| 1101 | |
| 1102 | /// `/trust [on|off|add|remove|list]` (alias `/xinren`). |
| 1103 | /// |
| 1104 | /// The command owns subcommand parsing and message composition; the facet only |
| 1105 | /// reads and mutates the trust state and the allow-list. |
| 1106 | pub fn trust(contexts: CommandContexts<'_>, arg: Option<&str>) -> ConfigCommandResult { |
| 1107 | let raw = arg.map(str::trim).unwrap_or(""); |
| 1108 | let mut split = raw.splitn(2, char::is_whitespace); |
| 1109 | let sub = split.next().unwrap_or("").to_lowercase(); |
| 1110 | let rest = split.next().map(str::trim).unwrap_or(""); |
| 1111 | |
| 1112 | let mut parts = contexts.into_parts(); |
| 1113 | let Some(facet) = parts.trust.as_deref_mut() else { |
| 1114 | return missing("trust"); |
| 1115 | }; |
| 1116 | |
| 1117 | match sub.as_str() { |
| 1118 | "" | "status" | "list" => { |
| 1119 | let force_paths = sub == "list"; |
| 1120 | let mut lines = Vec::new(); |
| 1121 | lines.push(format!( |
| 1122 | "Workspace trust mode: {}", |
| 1123 | if facet.trust_mode() { |
| 1124 | "enabled" |
| 1125 | } else { |
| 1126 | "disabled" |
| 1127 | } |
| 1128 | )); |
| 1129 | let paths = facet.trusted_paths(); |
| 1130 | if paths.is_empty() { |
| 1131 | lines.push(if force_paths { |
| 1132 | "No external paths trusted from this workspace.".to_string() |
| 1133 | } else { |
| 1134 | "No external paths trusted yet. Use `/trust add <path>` to allow a directory." |
| 1135 | .to_string() |
| 1136 | }); |
| 1137 | } else { |
| 1138 | lines.push(format!("Trusted external paths ({}):", paths.len())); |
| 1139 | for path in paths { |
| 1140 | lines.push(format!(" • {}", path.display())); |
| 1141 | } |
| 1142 | } |
| 1143 | ConfigCommandResult::message(lines.join("\n")) |
| 1144 | } |
| 1145 | "on" | "enable" | "yes" | "y" | "off" | "disable" | "no" | "n" => { |
| 1146 | if !matches!(rest, "" | "--save") { |
| 1147 | return ConfigCommandResult::error(format!( |
| 1148 | "{} /trust on|off [--save]", |
| 1149 | facet.usage_label() |
| 1150 | )); |
| 1151 | } |
| 1152 | ConfigCommandResult::action(ConfigAction::SetWorkspaceTrust { |
| 1153 | trusted: matches!(sub.as_str(), "on" | "enable" | "yes" | "y"), |
| 1154 | save: rest == "--save", |
| 1155 | }) |
| 1156 | } |
| 1157 | "add" => { |
| 1158 | if rest.is_empty() { |
| 1159 | return ConfigCommandResult::error( |
| 1160 | "Usage: /trust add <path>. Supply an absolute path or a path relative to the workspace.", |
| 1161 | ); |
| 1162 | } |
| 1163 | match facet.add_trusted_path(rest) { |
| 1164 | Ok(stored) => ConfigCommandResult::message(format!( |
| 1165 | "Added to trust list for this workspace: {}", |
| 1166 | stored.display() |
| 1167 | )), |
| 1168 | Err(TrustPathError::NotFound(path)) => ConfigCommandResult::error(format!( |
| 1169 | "Path not found: {} — supply an existing directory or file.", |
| 1170 | path.display() |
| 1171 | )), |
| 1172 | Err(TrustPathError::UpdateFailed(err)) => { |
| 1173 | ConfigCommandResult::error(format!("Failed to update trust list: {err}")) |
| 1174 | } |
| 1175 | } |
| 1176 | } |
| 1177 | "remove" | "rm" | "del" | "delete" => { |
| 1178 | if rest.is_empty() { |
| 1179 | return ConfigCommandResult::error("Usage: /trust remove <path>"); |
| 1180 | } |
| 1181 | match facet.remove_trusted_path(rest) { |
| 1182 | Ok((path, true)) => ConfigCommandResult::message(format!( |
| 1183 | "Removed from trust list: {}", |
| 1184 | path.display() |
| 1185 | )), |
| 1186 | Ok((path, false)) => { |
| 1187 | ConfigCommandResult::message(format!("Not in trust list: {}", path.display())) |
| 1188 | } |
| 1189 | Err(TrustPathError::UpdateFailed(err)) => { |
| 1190 | ConfigCommandResult::error(format!("Failed to update trust list: {err}")) |
| 1191 | } |
| 1192 | Err(TrustPathError::NotFound(_)) => { |
| 1193 | ConfigCommandResult::error("Usage: /trust remove <path>") |
| 1194 | } |
| 1195 | } |
| 1196 | } |
| 1197 | other => ConfigCommandResult::error(format!( |
| 1198 | "Unknown /trust action `{other}`. Use `/trust`, `/trust on|off [--save]`, `/trust add <path>`, or `/trust remove <path>`." |
| 1199 | )), |
| 1200 | } |
| 1201 | } |
| 1202 | |
| 1203 | /// `/auth xai-device|chatgpt|chatgpt-revoke|orcarouter|orcarouter-revoke`. |
| 1204 | /// Pure: selects a capability-launch action, no host observation. |
| 1205 | pub fn auth(arg: Option<&str>) -> ConfigCommandResult { |
| 1206 | let action = match arg.map(str::trim) { |
| 1207 | Some("xai-device") | Some("xai_device") => ConfigAction::StartXaiDeviceLogin, |
| 1208 | Some("claude") | Some("anthropic") | Some("claude-revoke") => { |
| 1209 | return ConfigCommandResult::error( |
| 1210 | "Claude subscription sign-in was removed in 0.10.3. Use an Anthropic API key: /provider setup anthropic", |
| 1211 | ); |
| 1212 | } |
| 1213 | Some("chatgpt") | Some("openai-codex") | Some("openai_codex") => { |
| 1214 | ConfigAction::StartChatgptPkceLogin |
| 1215 | } |
| 1216 | Some("chatgpt-revoke") | Some("chatgpt_revoke") => ConfigAction::StartChatgptRevoke, |
| 1217 | Some("orcarouter") | Some("orca") => ConfigAction::StartOrcarouterPkceLogin, |
| 1218 | Some("orcarouter-revoke") | Some("orcarouter_revoke") | Some("orca-revoke") => { |
| 1219 | ConfigAction::StartOrcarouterRevoke |
| 1220 | } |
| 1221 | _ => { |
| 1222 | return ConfigCommandResult { |
| 1223 | message: Some( |
| 1224 | "Usage: /auth xai-device|chatgpt|chatgpt-revoke|orcarouter|orcarouter-revoke" |
| 1225 | .to_string(), |
| 1226 | ), |
| 1227 | action: None, |
| 1228 | is_error: true, |
| 1229 | }; |
| 1230 | } |
| 1231 | }; |
| 1232 | ConfigCommandResult { |
| 1233 | message: None, |
| 1234 | action: Some(action), |
| 1235 | is_error: false, |
| 1236 | } |
| 1237 | } |
| 1238 | |
| 1239 | /// Compose the `/import-claude --apply` follow-up sentence for a typed fact. |
| 1240 | fn render_follow_up(item: &codewhale_command_contract::config::CommandImportFollowUp) -> String { |
| 1241 | use codewhale_command_contract::config::CommandImportFollowUp as FollowUp; |
| 1242 | match item { |
| 1243 | FollowUp::InstructionsCopied { destination } => { |
| 1244 | format!("Standing instructions copied to {destination}.") |
| 1245 | } |
| 1246 | FollowUp::InstructionsKeptExisting { |
| 1247 | destination, |
| 1248 | source, |
| 1249 | } => format!( |
| 1250 | "{destination} already exists — left untouched; merge from {source} by hand if you want both." |
| 1251 | ), |
| 1252 | FollowUp::InstructionsCopyFailed { |
| 1253 | source, |
| 1254 | destination, |
| 1255 | } => format!("Could not copy {source} — copy it to {destination} by hand."), |
| 1256 | FollowUp::HomeUnresolved => { |
| 1257 | "Could not resolve the Codewhale home, so standing instructions were not copied." |
| 1258 | .to_string() |
| 1259 | } |
| 1260 | FollowUp::McpBlocked { name } => { |
| 1261 | format!("MCP `{name}` is disabled at its source and was not imported.") |
| 1262 | } |
| 1263 | FollowUp::McpNeedsReview { name } => format!( |
| 1264 | "MCP `{name}` needs a separate review: run /mcp import, then use its displayed approval command. It will be imported OFF." |
| 1265 | ), |
| 1266 | FollowUp::HookEvents { count } => format!( |
| 1267 | "{count} hook event(s) still need mapping with /hooks — hooks run code, so they are never imported for you." |
| 1268 | ), |
| 1269 | FollowUp::PermissionRules => { |
| 1270 | "Permission rules are listed in the report; apply the ones you want with /permissions." |
| 1271 | .to_string() |
| 1272 | } |
| 1273 | } |
| 1274 | } |
| 1275 | |
| 1276 | /// A parsed `/config subagents` tail. |
| 1277 | #[derive(Debug, PartialEq, Eq)] |
| 1278 | enum SubagentOp<'a> { |
| 1279 | Status, |
| 1280 | Get(&'a str), |
| 1281 | Set { key: &'a str, value: &'a str }, |
| 1282 | Usage, |
| 1283 | } |
| 1284 | |
| 1285 | /// Parse the `/config subagents …` grammar in the command. |
| 1286 | fn parse_subagent_rest(rest: &str) -> (SubagentOp<'_>, bool) { |
| 1287 | let mut tokens = rest.split_whitespace().collect::<Vec<_>>(); |
| 1288 | let persist = matches!(tokens.last(), Some(&"--save" | &"-s")); |
| 1289 | if persist { |
| 1290 | tokens.pop(); |
| 1291 | } |
| 1292 | let op = match tokens.as_slice() { |
| 1293 | [] | ["status"] => SubagentOp::Status, |
| 1294 | ["on"] | ["enable"] | ["enabled"] => SubagentOp::Set { |
| 1295 | key: "enabled", |
| 1296 | value: "true", |
| 1297 | }, |
| 1298 | ["off"] | ["disable"] | ["disabled"] => SubagentOp::Set { |
| 1299 | key: "enabled", |
| 1300 | value: "false", |
| 1301 | }, |
| 1302 | [key] => SubagentOp::Get(key), |
| 1303 | [key, value] => SubagentOp::Set { key, value }, |
| 1304 | _ => SubagentOp::Usage, |
| 1305 | }; |
| 1306 | (op, persist) |
| 1307 | } |
| 1308 | |
| 1309 | /// A parsed `/config search…` tail. |
| 1310 | #[derive(Debug, PartialEq, Eq)] |
| 1311 | enum SearchOp<'a> { |
| 1312 | Status, |
| 1313 | Set(&'a str), |
| 1314 | Usage, |
| 1315 | } |
| 1316 | |
| 1317 | /// Parse the `/config search[.provider] …` grammar in the command. |
| 1318 | fn parse_search_rest(rest: &str) -> (SearchOp<'_>, bool) { |
| 1319 | let mut tokens = rest.split_whitespace().collect::<Vec<_>>(); |
| 1320 | let persist = matches!(tokens.last(), Some(&"--save" | &"-s")); |
| 1321 | if persist { |
| 1322 | tokens.pop(); |
| 1323 | } |
| 1324 | let op = match tokens.as_slice() { |
| 1325 | [] | ["status"] | ["provider"] => SearchOp::Status, |
| 1326 | ["provider", value] | [value] => SearchOp::Set(value), |
| 1327 | _ => SearchOp::Usage, |
| 1328 | }; |
| 1329 | (op, persist) |
| 1330 | } |
| 1331 | |
| 1332 | fn split_save_flag(rest: &str) -> (&str, bool) { |
| 1333 | let rest = rest.trim(); |
| 1334 | match rest.rsplit_once(char::is_whitespace) { |
| 1335 | Some((value, "--save" | "-s")) => (value.trim_end(), true), |
| 1336 | _ => (rest, false), |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | /// A parsed `/config notifications…` tail. |
| 1341 | #[derive(Debug, PartialEq, Eq)] |
| 1342 | enum NotificationsOp<'a> { |
| 1343 | Status, |
| 1344 | Get(&'a str), |
| 1345 | Set { key: &'a str, value: &'a str }, |
| 1346 | } |
| 1347 | |
| 1348 | /// Parse the `/config notifications …` grammar in the command. |
| 1349 | fn parse_notifications_rest(rest: &str) -> (NotificationsOp<'_>, bool) { |
| 1350 | let (rest, persist) = split_save_flag(rest); |
| 1351 | let op = if rest.is_empty() || rest == "status" { |
| 1352 | NotificationsOp::Status |
| 1353 | } else { |
| 1354 | match rest.split_once(char::is_whitespace) { |
| 1355 | Some((key, value)) => NotificationsOp::Set { |
| 1356 | key, |
| 1357 | value: value.trim(), |
| 1358 | }, |
| 1359 | None => NotificationsOp::Get(rest), |
| 1360 | } |
| 1361 | }; |
| 1362 | (op, persist) |
| 1363 | } |
| 1364 | |
| 1365 | #[cfg(test)] |
| 1366 | mod tests { |
| 1367 | use super::*; |
| 1368 | use codewhale_command_contract::config::{ |
| 1369 | CommandClaudeApplyOutcome, CommandClaudeArtifacts, CommandClaudePlan, CommandConfigContext, |
| 1370 | }; |
| 1371 | use codewhale_command_contract::facets::CommandPresentationContext; |
| 1372 | |
| 1373 | #[test] |
| 1374 | fn missing_facets_fail_safely_with_the_inherited_error_contract() { |
| 1375 | for (name, result) in [ |
| 1376 | ("config", config(CommandContexts::empty(), Some("model"))), |
| 1377 | ("whale", whale(CommandContexts::empty(), None)), |
| 1378 | ("trust", trust(CommandContexts::empty(), None)), |
| 1379 | ] { |
| 1380 | assert!(result.is_error, "{name} must fail without its facet"); |
| 1381 | assert_eq!( |
| 1382 | result.message.as_deref(), |
| 1383 | Some(format!("Command capability unavailable: {name}").as_str()) |
| 1384 | ); |
| 1385 | assert!(result.action.is_none(), "no action may cross on failure"); |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | #[derive(Default)] |
| 1390 | struct Whale { |
| 1391 | enabled: bool, |
| 1392 | saved: Vec<bool>, |
| 1393 | still: bool, |
| 1394 | name: Option<String>, |
| 1395 | color: Option<String>, |
| 1396 | } |
| 1397 | |
| 1398 | impl CommandPetContext for Whale { |
| 1399 | fn enabled(&self) -> bool { |
| 1400 | self.enabled |
| 1401 | } |
| 1402 | fn set_enabled(&mut self, enabled: bool, persist: bool) { |
| 1403 | self.enabled = enabled; |
| 1404 | if persist { |
| 1405 | self.saved.push(enabled); |
| 1406 | } |
| 1407 | } |
| 1408 | fn still(&self) -> bool { |
| 1409 | self.still |
| 1410 | } |
| 1411 | fn set_still(&mut self, still: bool) { |
| 1412 | self.still = still; |
| 1413 | } |
| 1414 | fn set_name(&mut self, name: &str) { |
| 1415 | self.name = Some(name.to_owned()); |
| 1416 | } |
| 1417 | fn set_color(&mut self, color: Option<&str>) { |
| 1418 | self.color = color.map(str::to_owned); |
| 1419 | } |
| 1420 | fn label(&self, which: CommandPetLabel) -> String { |
| 1421 | match which { |
| 1422 | CommandPetLabel::Named => "named {name}".into(), |
| 1423 | CommandPetLabel::Colored => "colored {color}".into(), |
| 1424 | other => format!("{other:?}"), |
| 1425 | } |
| 1426 | } |
| 1427 | } |
| 1428 | |
| 1429 | fn run_whale(facet: &mut Whale, arg: Option<&str>) -> ConfigCommandResult { |
| 1430 | whale(CommandContexts::empty().with_pet(facet), arg) |
| 1431 | } |
| 1432 | |
| 1433 | #[test] |
| 1434 | fn whale_toggles_the_view_and_takes_only_its_four_subcommands() { |
| 1435 | let mut facet = Whale::default(); |
| 1436 | assert_eq!( |
| 1437 | run_whale(&mut facet, None).message.as_deref(), |
| 1438 | Some("ModeOn") |
| 1439 | ); |
| 1440 | assert_eq!( |
| 1441 | run_whale(&mut facet, Some(" FULL ")).message.as_deref(), |
| 1442 | Some("ModeOff") |
| 1443 | ); |
| 1444 | assert!(!run_whale(&mut facet, Some("on")).is_error); |
| 1445 | assert!(!run_whale(&mut facet, Some("on")).is_error); |
| 1446 | assert!(facet.enabled); |
| 1447 | assert!(!run_whale(&mut facet, Some("off")).is_error); |
| 1448 | assert_eq!(facet.saved, [true, false, true, true, false]); |
| 1449 | |
| 1450 | assert_eq!( |
| 1451 | run_whale(&mut facet, Some("still")).message.as_deref(), |
| 1452 | Some("StillOn") |
| 1453 | ); |
| 1454 | assert!(facet.still); |
| 1455 | assert_eq!( |
| 1456 | run_whale(&mut facet, Some("still")).message.as_deref(), |
| 1457 | Some("StillOff") |
| 1458 | ); |
| 1459 | |
| 1460 | for removed in [ |
| 1461 | "inspect", |
| 1462 | "status", |
| 1463 | "appearance", |
| 1464 | "style pixel", |
| 1465 | "source", |
| 1466 | "export", |
| 1467 | "sound on", |
| 1468 | "avatar", |
| 1469 | "avatar cove", |
| 1470 | "action greet", |
| 1471 | "view live", |
| 1472 | "on extra", |
| 1473 | "still on", |
| 1474 | "bogus", |
| 1475 | ] { |
| 1476 | let result = run_whale(&mut facet, Some(removed)); |
| 1477 | assert!(result.is_error, "{removed}"); |
| 1478 | assert_eq!( |
| 1479 | result.message.as_deref(), |
| 1480 | Some(format!("Error: Usage: {WHALE_USAGE}").as_str()) |
| 1481 | ); |
| 1482 | } |
| 1483 | assert!(!facet.enabled && !facet.still); |
| 1484 | } |
| 1485 | |
| 1486 | #[test] |
| 1487 | fn whale_name_and_colour_validate_before_they_reach_the_host() { |
| 1488 | let mut facet = Whale::default(); |
| 1489 | assert_eq!( |
| 1490 | run_whale(&mut facet, Some("name Moby Dick ")) |
| 1491 | .message |
| 1492 | .as_deref(), |
| 1493 | Some("named Moby Dick") |
| 1494 | ); |
| 1495 | assert_eq!(facet.name.as_deref(), Some("Moby Dick")); |
| 1496 | let too_long = format!("name {}", "x".repeat(33)); |
| 1497 | for rejected in [ |
| 1498 | "name", |
| 1499 | "name \u{1b}[31m", |
| 1500 | "name a\u{202e}b", |
| 1501 | too_long.as_str(), |
| 1502 | ] { |
| 1503 | assert!( |
| 1504 | run_whale(&mut facet, Some(rejected)).is_error, |
| 1505 | "{rejected:?}" |
| 1506 | ); |
| 1507 | } |
| 1508 | assert_eq!(facet.name.as_deref(), Some("Moby Dick")); |
| 1509 | let longest = format!("name {}", "鲸".repeat(32)); |
| 1510 | assert!(!run_whale(&mut facet, Some(longest.as_str())).is_error); |
| 1511 | |
| 1512 | assert_eq!( |
| 1513 | run_whale(&mut facet, Some("color #7FB2E0")) |
| 1514 | .message |
| 1515 | .as_deref(), |
| 1516 | Some("colored #7fb2e0") |
| 1517 | ); |
| 1518 | assert_eq!(facet.color.as_deref(), Some("#7fb2e0")); |
| 1519 | assert_eq!( |
| 1520 | run_whale(&mut facet, Some("colour Harbor")) |
| 1521 | .message |
| 1522 | .as_deref(), |
| 1523 | Some("colored harbor") |
| 1524 | ); |
| 1525 | assert!(!run_whale(&mut facet, Some("colour 000000")).is_error); |
| 1526 | assert_eq!(facet.color.as_deref(), Some("#000000")); |
| 1527 | for rejected in [ |
| 1528 | "color", |
| 1529 | "color blue", |
| 1530 | "color #12345", |
| 1531 | "color #12345g", |
| 1532 | "color #1234567", |
| 1533 | "color +12345", |
| 1534 | ] { |
| 1535 | assert!(run_whale(&mut facet, Some(rejected)).is_error, "{rejected}"); |
| 1536 | assert_eq!(facet.color.as_deref(), Some("#000000")); |
| 1537 | } |
| 1538 | assert!( |
| 1539 | run_whale(&mut facet, Some("color blue")) |
| 1540 | .message |
| 1541 | .is_some_and(|message| message.contains("scout, patch, harbor")) |
| 1542 | ); |
| 1543 | assert_eq!( |
| 1544 | run_whale(&mut facet, Some("color DEFAULT")) |
| 1545 | .message |
| 1546 | .as_deref(), |
| 1547 | Some("ColorReset") |
| 1548 | ); |
| 1549 | assert_eq!(facet.color, None); |
| 1550 | } |
| 1551 | |
| 1552 | #[test] |
| 1553 | fn capability_declarations_are_exact() { |
| 1554 | assert!(CONFIG_CAPS.contains(CommandCapabilities::CONFIG)); |
| 1555 | assert!(CONFIG_CAPS.contains(CommandCapabilities::PRESENTATION)); |
| 1556 | assert!(CONFIG_CAPS.contains(CommandCapabilities::PERMISSIONS)); |
| 1557 | // Commands that never consume permission authority must not expose it. |
| 1558 | assert!(CONFIG_ONLY_CAPS.contains(CommandCapabilities::CONFIG)); |
| 1559 | assert!(!CONFIG_ONLY_CAPS.contains(CommandCapabilities::PRESENTATION)); |
| 1560 | assert!(!CONFIG_ONLY_CAPS.contains(CommandCapabilities::PERMISSIONS)); |
| 1561 | assert!(CONFIG_PRESENTATION_CAPS.contains(CommandCapabilities::PRESENTATION)); |
| 1562 | assert!(!CONFIG_PRESENTATION_CAPS.contains(CommandCapabilities::PERMISSIONS)); |
| 1563 | assert!(WHALE_CAPS.contains(CommandCapabilities::PET)); |
| 1564 | assert!(!WHALE_CAPS.contains(CommandCapabilities::CONFIG)); |
| 1565 | assert!(TRUST_CAPS.contains(CommandCapabilities::TRUST)); |
| 1566 | assert!(!TRUST_CAPS.contains(CommandCapabilities::WORKSPACE)); |
| 1567 | assert!(!TRUST_CAPS.contains(CommandCapabilities::PRESENTATION)); |
| 1568 | assert!(!TRUST_CAPS.contains(CommandCapabilities::CONFIG)); |
| 1569 | } |
| 1570 | |
| 1571 | #[test] |
| 1572 | fn literal_error_needs_no_presentation_capability() { |
| 1573 | // `/workbar` declares only WORK_SURFACE, but its save-error message is a |
| 1574 | // literal: it must render without the presentation facet. |
| 1575 | let mut parts = CommandContexts::empty().into_parts(); |
| 1576 | let prepared = PreparedTemplates::default(); |
| 1577 | let reply = ConfigReply { |
| 1578 | message: Some(ConfigMessage::literal("Failed to save: permission denied")), |
| 1579 | action: None, |
| 1580 | is_error: true, |
| 1581 | }; |
| 1582 | let result = to_result(reply, &mut parts, &prepared); |
| 1583 | assert!(result.is_error); |
| 1584 | assert_eq!( |
| 1585 | result.message.as_deref(), |
| 1586 | Some("Error: Failed to save: permission denied") |
| 1587 | ); |
| 1588 | } |
| 1589 | |
| 1590 | #[test] |
| 1591 | fn keyed_message_without_presentation_fails_loudly() { |
| 1592 | let mut parts = CommandContexts::empty().into_parts(); |
| 1593 | let prepared = PreparedTemplates::default(); |
| 1594 | let reply = ConfigReply { |
| 1595 | message: Some(ConfigMessage::keyed("config_scope_session")), |
| 1596 | action: Some(ConfigAction::OpenConfigView), |
| 1597 | is_error: false, |
| 1598 | }; |
| 1599 | let result = to_result(reply, &mut parts, &prepared); |
| 1600 | assert!(result.is_error, "a missing required capability must fail"); |
| 1601 | assert!(result.action.is_none(), "no action on a failed capability"); |
| 1602 | assert_eq!( |
| 1603 | result.message.as_deref(), |
| 1604 | Some("Error: Command capability unavailable: presentation") |
| 1605 | ); |
| 1606 | } |
| 1607 | |
| 1608 | /// A config facet that panics the moment any method is touched, so a test |
| 1609 | /// can prove the command validated capabilities before any effect. |
| 1610 | struct PanicConfig; |
| 1611 | |
| 1612 | impl CommandConfigContext for PanicConfig { |
| 1613 | fn mcp_config_path(&self) -> std::path::PathBuf { |
| 1614 | panic!("config facet touched") |
| 1615 | } |
| 1616 | fn hugging_face_mcp_server_name(&self) -> Result<Option<String>, String> { |
| 1617 | panic!("config facet touched") |
| 1618 | } |
| 1619 | fn translation_enabled(&self) -> bool { |
| 1620 | panic!("config facet touched") |
| 1621 | } |
| 1622 | fn set_translation_enabled(&mut self, _: bool) { |
| 1623 | panic!("config facet touched") |
| 1624 | } |
| 1625 | fn config_path(&self) -> Option<std::path::PathBuf> { |
| 1626 | panic!("config facet touched") |
| 1627 | } |
| 1628 | fn audit( |
| 1629 | &mut self, |
| 1630 | ) -> Result<codewhale_command_contract::config::CommandConfigAuditReport, String> { |
| 1631 | panic!("config facet touched") |
| 1632 | } |
| 1633 | fn workflow_summary(&mut self) -> CommandWorkflowSummary { |
| 1634 | panic!("config facet touched") |
| 1635 | } |
| 1636 | fn subagents_status( |
| 1637 | &mut self, |
| 1638 | ) -> Result<codewhale_command_contract::config::CommandSubagentsReport, String> { |
| 1639 | panic!("config facet touched") |
| 1640 | } |
| 1641 | fn subagent(&mut self, _key: &str) -> ConfigReply { |
| 1642 | panic!("config facet touched") |
| 1643 | } |
| 1644 | fn set_subagent(&mut self, _key: &str, _value: &str, _persist: bool) -> ConfigReply { |
| 1645 | panic!("config facet touched") |
| 1646 | } |
| 1647 | fn search_provider_status(&mut self) -> ConfigReply { |
| 1648 | panic!("config facet touched") |
| 1649 | } |
| 1650 | fn search_provider_names(&self) -> &'static str { |
| 1651 | panic!("config facet touched") |
| 1652 | } |
| 1653 | fn set_search_provider(&mut self, _value: &str, _persist: bool) -> ConfigReply { |
| 1654 | panic!("config facet touched") |
| 1655 | } |
| 1656 | fn notifications_status(&mut self) -> ConfigReply { |
| 1657 | panic!("config facet touched") |
| 1658 | } |
| 1659 | fn notification(&mut self, _key: &str) -> ConfigReply { |
| 1660 | panic!("config facet touched") |
| 1661 | } |
| 1662 | fn set_notification(&mut self, _key: &str, _value: &str, _persist: bool) -> ConfigReply { |
| 1663 | panic!("config facet touched") |
| 1664 | } |
| 1665 | fn apply_preset(&mut self, _name: &str, _persist: bool) -> ConfigReply { |
| 1666 | panic!("config facet touched") |
| 1667 | } |
| 1668 | fn get_value(&mut self, _key: &str) -> ConfigReply { |
| 1669 | panic!("config facet touched") |
| 1670 | } |
| 1671 | fn set_value(&mut self, _key: &str, _value: &str, _persist: bool) -> ConfigReply { |
| 1672 | panic!("config facet touched") |
| 1673 | } |
| 1674 | fn show_settings( |
| 1675 | &mut self, |
| 1676 | ) -> Result<codewhale_command_contract::config::CommandSettingsReport, String> { |
| 1677 | panic!("config facet touched") |
| 1678 | } |
| 1679 | fn theme_schema(&self) -> String { |
| 1680 | panic!("config facet touched") |
| 1681 | } |
| 1682 | fn themes_dir(&self) -> Result<String, String> { |
| 1683 | panic!("config facet touched") |
| 1684 | } |
| 1685 | fn verbose_enabled(&self) -> bool { |
| 1686 | panic!("config facet touched") |
| 1687 | } |
| 1688 | fn set_verbose_enabled(&mut self, _enabled: bool) { |
| 1689 | panic!("config facet touched") |
| 1690 | } |
| 1691 | fn build_plan(&mut self) -> Option<CommandClaudePlan> { |
| 1692 | panic!("config facet touched") |
| 1693 | } |
| 1694 | fn write_artifacts( |
| 1695 | &mut self, |
| 1696 | _report: &str, |
| 1697 | _bundle: Option<&str>, |
| 1698 | ) -> CommandClaudeArtifacts { |
| 1699 | panic!("config facet touched") |
| 1700 | } |
| 1701 | fn apply_import( |
| 1702 | &mut self, |
| 1703 | _plan: &CommandClaudePlan, |
| 1704 | _report_path: &std::path::Path, |
| 1705 | _wrote_report: bool, |
| 1706 | ) -> CommandClaudeApplyOutcome { |
| 1707 | panic!("config facet touched") |
| 1708 | } |
| 1709 | fn display_path(&self, _path: &std::path::Path) -> String { |
| 1710 | panic!("config facet touched") |
| 1711 | } |
| 1712 | } |
| 1713 | |
| 1714 | /// Presentation that resolves every template except `failing`. |
| 1715 | struct OneMissingTemplate(&'static str); |
| 1716 | |
| 1717 | impl CommandPresentationContext for OneMissingTemplate { |
| 1718 | fn translate(&self, key: &str, _r: &[(&str, &str)]) -> Result<String, String> { |
| 1719 | if key == self.0 { |
| 1720 | Err(format!("{key}: unknown translation key")) |
| 1721 | } else { |
| 1722 | Ok(key.to_string()) |
| 1723 | } |
| 1724 | } |
| 1725 | } |
| 1726 | |
| 1727 | /// Presentation that succeeds once per key and fails on any second call, |
| 1728 | /// proving prepared rendering never re-translates after an effect. |
| 1729 | #[derive(Default)] |
| 1730 | struct OncePerKey(std::cell::RefCell<std::collections::HashSet<String>>); |
| 1731 | |
| 1732 | impl CommandPresentationContext for OncePerKey { |
| 1733 | fn translate(&self, key: &str, r: &[(&str, &str)]) -> Result<String, String> { |
| 1734 | if !self.0.borrow_mut().insert(key.to_string()) { |
| 1735 | return Err(format!("{key} translated twice")); |
| 1736 | } |
| 1737 | // Echo the replacement values so the preflight sentinels survive. |
| 1738 | Ok(r.iter().map(|(_, value)| *value).collect()) |
| 1739 | } |
| 1740 | } |
| 1741 | |
| 1742 | #[test] |
| 1743 | fn prepared_rendering_never_translates_again_after_preflight() { |
| 1744 | let mut presentation = OncePerKey::default(); |
| 1745 | let contexts = CommandContexts::empty().with_presentation(&mut presentation); |
| 1746 | let mut parts = contexts.into_parts(); |
| 1747 | let prepared = preflight(&mut parts).expect("preflight validates every template once"); |
| 1748 | let reply = ConfigReply::message(ConfigMessage::keyed_with( |
| 1749 | "config_search_updated", |
| 1750 | vec![ |
| 1751 | ("value".to_string(), ConfigMessage::literal("duckduckgo")), |
| 1752 | ( |
| 1753 | "scope".to_string(), |
| 1754 | ConfigMessage::keyed("config_scope_saved"), |
| 1755 | ), |
| 1756 | ], |
| 1757 | )); |
| 1758 | let result = to_result(reply, &mut parts, &prepared); |
| 1759 | assert!(!result.is_error, "{:?}", result.message); |
| 1760 | assert_eq!(result.message.as_deref(), Some("duckduckgo")); |
| 1761 | } |
| 1762 | |
| 1763 | /// Presentation that echoes replacement values and counts translations. |
| 1764 | #[derive(Default)] |
| 1765 | struct EchoWithCount(std::cell::Cell<usize>); |
| 1766 | |
| 1767 | impl CommandPresentationContext for EchoWithCount { |
| 1768 | fn translate(&self, _key: &str, r: &[(&str, &str)]) -> Result<String, String> { |
| 1769 | self.0.set(self.0.get() + 1); |
| 1770 | Ok(r.iter().map(|(_, value)| *value).collect()) |
| 1771 | } |
| 1772 | } |
| 1773 | |
| 1774 | #[test] |
| 1775 | fn prepared_rendering_rejects_missing_duplicate_and_extra_parameters() { |
| 1776 | for (name, params) in [ |
| 1777 | ( |
| 1778 | "missing scope", |
| 1779 | vec![("value".to_string(), ConfigMessage::literal("duckduckgo"))], |
| 1780 | ), |
| 1781 | ( |
| 1782 | "duplicate value", |
| 1783 | vec![ |
| 1784 | ("value".to_string(), ConfigMessage::literal("a")), |
| 1785 | ("value".to_string(), ConfigMessage::literal("b")), |
| 1786 | ( |
| 1787 | "scope".to_string(), |
| 1788 | ConfigMessage::keyed("config_scope_saved"), |
| 1789 | ), |
| 1790 | ], |
| 1791 | ), |
| 1792 | ( |
| 1793 | "extra parameter", |
| 1794 | vec![ |
| 1795 | ("value".to_string(), ConfigMessage::literal("duckduckgo")), |
| 1796 | ( |
| 1797 | "scope".to_string(), |
| 1798 | ConfigMessage::keyed("config_scope_saved"), |
| 1799 | ), |
| 1800 | ("extra".to_string(), ConfigMessage::literal("x")), |
| 1801 | ], |
| 1802 | ), |
| 1803 | ] { |
| 1804 | let mut presentation = EchoWithCount::default(); |
| 1805 | let contexts = CommandContexts::empty().with_presentation(&mut presentation); |
| 1806 | let mut parts = contexts.into_parts(); |
| 1807 | let prepared = preflight(&mut parts).expect("preflight"); |
| 1808 | let reply = ConfigReply::with_message_and_action( |
| 1809 | ConfigMessage::keyed_with("config_search_updated", params), |
| 1810 | ConfigAction::OpenConfigView, |
| 1811 | ); |
| 1812 | let result = to_result(reply, &mut parts, &prepared); |
| 1813 | assert!(result.is_error, "{name} must fail"); |
| 1814 | assert!(result.action.is_none(), "{name} must not keep the action"); |
| 1815 | assert!( |
| 1816 | result |
| 1817 | .message |
| 1818 | .as_deref() |
| 1819 | .is_some_and(|m| m.contains("invalid translation replacement contract")), |
| 1820 | "{name}: {:?}", |
| 1821 | result.message |
| 1822 | ); |
| 1823 | } |
| 1824 | } |
| 1825 | |
| 1826 | /// Work-surface facet that rejects every setter. |
| 1827 | struct RejectingWorkSurface; |
| 1828 | |
| 1829 | impl codewhale_command_contract::config::CommandWorkSurfaceContext for RejectingWorkSurface { |
| 1830 | fn placement(&self) -> codewhale_command_contract::types::CommandWorkSurfacePlacement { |
| 1831 | codewhale_command_contract::types::CommandWorkSurfacePlacement::Bottom |
| 1832 | } |
| 1833 | fn panel(&self) -> codewhale_command_contract::types::CommandRailPanel { |
| 1834 | codewhale_command_contract::types::CommandRailPanel::Tasks |
| 1835 | } |
| 1836 | fn effective_placement( |
| 1837 | &self, |
| 1838 | ) -> codewhale_command_contract::types::CommandWorkSurfacePlacement { |
| 1839 | codewhale_command_contract::types::CommandWorkSurfacePlacement::Bottom |
| 1840 | } |
| 1841 | fn area_present(&self) -> bool { |
| 1842 | true |
| 1843 | } |
| 1844 | fn panel_title( |
| 1845 | &self, |
| 1846 | _panel: codewhale_command_contract::types::CommandRailPanel, |
| 1847 | ) -> String { |
| 1848 | "Tasks".to_string() |
| 1849 | } |
| 1850 | fn set_placement( |
| 1851 | &mut self, |
| 1852 | _placement: codewhale_command_contract::types::CommandWorkSurfacePlacement, |
| 1853 | _persist: bool, |
| 1854 | ) -> ConfigReply { |
| 1855 | ConfigReply::error("workbar placement rejected") |
| 1856 | } |
| 1857 | fn set_panel( |
| 1858 | &mut self, |
| 1859 | _panel: codewhale_command_contract::types::CommandRailPanel, |
| 1860 | _persist: bool, |
| 1861 | ) -> ConfigReply { |
| 1862 | ConfigReply::error("workbar panel rejected") |
| 1863 | } |
| 1864 | fn mark_redraw(&mut self) {} |
| 1865 | } |
| 1866 | |
| 1867 | #[test] |
| 1868 | fn workbar_surfaces_setter_errors_without_save() { |
| 1869 | // No presentation facet: the setter error is literal, so `/workbar` |
| 1870 | // must not depend on the config templates. |
| 1871 | let mut work_surface = RejectingWorkSurface; |
| 1872 | let contexts = CommandContexts::empty().with_work_surface(&mut work_surface); |
| 1873 | // No `--save`: the setter error must still surface. |
| 1874 | let result = workbar(contexts, Some("left")); |
| 1875 | assert!(result.is_error, "{:?}", result.message); |
| 1876 | assert_eq!( |
| 1877 | result.message.as_deref(), |
| 1878 | Some("Error: workbar placement rejected") |
| 1879 | ); |
| 1880 | } |
| 1881 | |
| 1882 | #[test] |
| 1883 | fn workbar_status_needs_no_presentation() { |
| 1884 | let mut work_surface = RejectingWorkSurface; |
| 1885 | let contexts = CommandContexts::empty().with_work_surface(&mut work_surface); |
| 1886 | let result = workbar(contexts, None); |
| 1887 | assert!(!result.is_error, "{:?}", result.message); |
| 1888 | assert!(result.message.is_some()); |
| 1889 | } |
| 1890 | |
| 1891 | /// Presentation whose `config_search_updated` template repeats `{value}`. |
| 1892 | struct RepeatedPlaceholder; |
| 1893 | |
| 1894 | impl CommandPresentationContext for RepeatedPlaceholder { |
| 1895 | fn translate(&self, key: &str, r: &[(&str, &str)]) -> Result<String, String> { |
| 1896 | if key == "config_search_updated" && r.len() == 2 { |
| 1897 | return Ok(format!("{} {} {}", r[0].1, r[0].1, r[1].1)); |
| 1898 | } |
| 1899 | Ok(r.iter().map(|(_, value)| *value).collect()) |
| 1900 | } |
| 1901 | } |
| 1902 | |
| 1903 | #[test] |
| 1904 | fn prepared_rendering_allows_a_repeated_placeholder() { |
| 1905 | let mut presentation = RepeatedPlaceholder; |
| 1906 | let contexts = CommandContexts::empty().with_presentation(&mut presentation); |
| 1907 | let mut parts = contexts.into_parts(); |
| 1908 | let prepared = preflight(&mut parts).expect("preflight"); |
| 1909 | let reply = ConfigReply::with_message_and_action( |
| 1910 | ConfigMessage::keyed_with( |
| 1911 | "config_search_updated", |
| 1912 | vec![ |
| 1913 | ("value".to_string(), ConfigMessage::literal("duckduckgo")), |
| 1914 | ( |
| 1915 | "scope".to_string(), |
| 1916 | ConfigMessage::keyed("config_scope_saved"), |
| 1917 | ), |
| 1918 | ], |
| 1919 | ), |
| 1920 | ConfigAction::OpenConfigView, |
| 1921 | ); |
| 1922 | let result = to_result(reply, &mut parts, &prepared); |
| 1923 | assert!(!result.is_error, "{:?}", result.message); |
| 1924 | assert_eq!(result.action, Some(ConfigAction::OpenConfigView)); |
| 1925 | assert_eq!(result.message.as_deref(), Some("duckduckgo duckduckgo ")); |
| 1926 | } |
| 1927 | |
| 1928 | #[test] |
| 1929 | fn unprepared_key_errors_without_translating_after_an_effect() { |
| 1930 | let mut presentation = EchoWithCount::default(); |
| 1931 | let contexts = CommandContexts::empty().with_presentation(&mut presentation); |
| 1932 | let mut parts = contexts.into_parts(); |
| 1933 | // No preflight: an unprepared key must never reach the facet. |
| 1934 | let prepared = PreparedTemplates::default(); |
| 1935 | let reply = ConfigReply::with_message_and_action( |
| 1936 | ConfigMessage::keyed("not_a_prepared_key"), |
| 1937 | ConfigAction::OpenConfigView, |
| 1938 | ); |
| 1939 | let result = to_result(reply, &mut parts, &prepared); |
| 1940 | assert!(result.is_error); |
| 1941 | assert!(result.action.is_none()); |
| 1942 | assert!( |
| 1943 | result |
| 1944 | .message |
| 1945 | .as_deref() |
| 1946 | .is_some_and(|m| m.contains("unprepared message key")), |
| 1947 | "{:?}", |
| 1948 | result.message |
| 1949 | ); |
| 1950 | assert_eq!( |
| 1951 | presentation.0.get(), |
| 1952 | 0, |
| 1953 | "an unprepared key must not translate after the effect" |
| 1954 | ); |
| 1955 | } |
| 1956 | |
| 1957 | #[test] |
| 1958 | fn preflight_rejects_missing_presentation_before_effects() { |
| 1959 | let mut parts = CommandContexts::empty().into_parts(); |
| 1960 | let Err(result) = preflight(&mut parts) else { |
| 1961 | panic!("a missing presentation capability must fail preflight"); |
| 1962 | }; |
| 1963 | assert!(result.is_error); |
| 1964 | assert!(result.action.is_none()); |
| 1965 | assert_eq!( |
| 1966 | result.message.as_deref(), |
| 1967 | Some("Command capability unavailable: presentation") |
| 1968 | ); |
| 1969 | } |
| 1970 | |
| 1971 | #[test] |
| 1972 | fn config_fails_before_touching_the_facet_when_presentation_is_missing() { |
| 1973 | // `PanicConfig` panics on any call: passing proves no effect ran. |
| 1974 | let mut facet = PanicConfig; |
| 1975 | let contexts = CommandContexts::empty().with_config(&mut facet); |
| 1976 | let result = config(contexts, Some("search duckduckgo --save")); |
| 1977 | assert!(result.is_error); |
| 1978 | assert!(result.action.is_none()); |
| 1979 | assert_eq!( |
| 1980 | result.message.as_deref(), |
| 1981 | Some("Command capability unavailable: presentation") |
| 1982 | ); |
| 1983 | } |
| 1984 | |
| 1985 | #[test] |
| 1986 | fn config_fails_before_mutating_when_a_required_template_is_missing() { |
| 1987 | let mut facet = PanicConfig; |
| 1988 | let mut presentation = OneMissingTemplate("config_search_updated"); |
| 1989 | let contexts = CommandContexts::empty() |
| 1990 | .with_config(&mut facet) |
| 1991 | .with_presentation(&mut presentation); |
| 1992 | let result = config(contexts, Some("search duckduckgo --save")); |
| 1993 | assert!(result.is_error); |
| 1994 | assert!(result.action.is_none()); |
| 1995 | assert!( |
| 1996 | result |
| 1997 | .message |
| 1998 | .as_deref() |
| 1999 | .is_some_and(|m| m.contains("config_search_updated")) |
| 2000 | ); |
| 2001 | } |
| 2002 | |
| 2003 | #[test] |
| 2004 | fn translation_failure_inside_a_nested_parameter_propagates() { |
| 2005 | let mut presentation = OneMissingTemplate("config_scope_saved"); |
| 2006 | let contexts = CommandContexts::empty().with_presentation(&mut presentation); |
| 2007 | let mut parts = contexts.into_parts(); |
| 2008 | let prepared = PreparedTemplates::default(); |
| 2009 | let reply = ConfigReply::with_message_and_action( |
| 2010 | ConfigMessage::keyed_with( |
| 2011 | "config_search_updated", |
| 2012 | vec![ |
| 2013 | ("value".to_string(), ConfigMessage::literal("duckduckgo")), |
| 2014 | ( |
| 2015 | "scope".to_string(), |
| 2016 | ConfigMessage::keyed("config_scope_saved"), |
| 2017 | ), |
| 2018 | ], |
| 2019 | ), |
| 2020 | ConfigAction::OpenConfigView, |
| 2021 | ); |
| 2022 | let result = to_result(reply, &mut parts, &prepared); |
| 2023 | assert!(result.is_error, "a nested translation failure must fail"); |
| 2024 | assert!(result.action.is_none(), "no action on a failed translation"); |
| 2025 | assert!( |
| 2026 | result |
| 2027 | .message |
| 2028 | .as_deref() |
| 2029 | .is_some_and(|m| m.contains("config_scope_saved")) |
| 2030 | ); |
| 2031 | } |
| 2032 | |
| 2033 | #[test] |
| 2034 | fn subagent_grammar_lives_in_the_command() { |
| 2035 | assert_eq!(parse_subagent_rest(""), (SubagentOp::Status, false)); |
| 2036 | assert_eq!(parse_subagent_rest("status"), (SubagentOp::Status, false)); |
| 2037 | assert_eq!( |
| 2038 | parse_subagent_rest("on"), |
| 2039 | ( |
| 2040 | SubagentOp::Set { |
| 2041 | key: "enabled", |
| 2042 | value: "true", |
| 2043 | }, |
| 2044 | false, |
| 2045 | ) |
| 2046 | ); |
| 2047 | assert_eq!( |
| 2048 | parse_subagent_rest("off --save"), |
| 2049 | ( |
| 2050 | SubagentOp::Set { |
| 2051 | key: "enabled", |
| 2052 | value: "false", |
| 2053 | }, |
| 2054 | true, |
| 2055 | ) |
| 2056 | ); |
| 2057 | assert_eq!( |
| 2058 | parse_subagent_rest("max_depth"), |
| 2059 | (SubagentOp::Get("max_depth"), false) |
| 2060 | ); |
| 2061 | assert_eq!( |
| 2062 | parse_subagent_rest("max_depth 4 -s"), |
| 2063 | ( |
| 2064 | SubagentOp::Set { |
| 2065 | key: "max_depth", |
| 2066 | value: "4", |
| 2067 | }, |
| 2068 | true, |
| 2069 | ) |
| 2070 | ); |
| 2071 | assert_eq!(parse_subagent_rest("a b c"), (SubagentOp::Usage, false)); |
| 2072 | } |
| 2073 | |
| 2074 | #[test] |
| 2075 | fn search_grammar_lives_in_the_command() { |
| 2076 | assert_eq!(parse_search_rest(""), (SearchOp::Status, false)); |
| 2077 | assert_eq!(parse_search_rest("status"), (SearchOp::Status, false)); |
| 2078 | assert_eq!(parse_search_rest("provider"), (SearchOp::Status, false)); |
| 2079 | assert_eq!( |
| 2080 | parse_search_rest("duckduckgo"), |
| 2081 | (SearchOp::Set("duckduckgo"), false) |
| 2082 | ); |
| 2083 | assert_eq!( |
| 2084 | parse_search_rest("provider tavily --save"), |
| 2085 | (SearchOp::Set("tavily"), true) |
| 2086 | ); |
| 2087 | assert_eq!(parse_search_rest("a b"), (SearchOp::Usage, false)); |
| 2088 | } |
| 2089 | |
| 2090 | #[test] |
| 2091 | fn save_flag_splits_on_any_whitespace() { |
| 2092 | assert_eq!( |
| 2093 | split_save_flag("deepseek-v4\u{3000}--save"), |
| 2094 | ("deepseek-v4", true) |
| 2095 | ); |
| 2096 | assert_eq!(split_save_flag("on\t-s"), ("on", true)); |
| 2097 | assert_eq!(split_save_flag("--save"), ("--save", false)); |
| 2098 | assert_eq!( |
| 2099 | parse_notifications_rest("method\u{3000}sound\u{3000}--save"), |
| 2100 | ( |
| 2101 | NotificationsOp::Set { |
| 2102 | key: "method", |
| 2103 | value: "sound", |
| 2104 | }, |
| 2105 | true, |
| 2106 | ) |
| 2107 | ); |
| 2108 | } |
| 2109 | |
| 2110 | #[test] |
| 2111 | fn notifications_grammar_lives_in_the_command() { |
| 2112 | assert_eq!( |
| 2113 | parse_notifications_rest(""), |
| 2114 | (NotificationsOp::Status, false) |
| 2115 | ); |
| 2116 | assert_eq!( |
| 2117 | parse_notifications_rest("status"), |
| 2118 | (NotificationsOp::Status, false) |
| 2119 | ); |
| 2120 | assert_eq!( |
| 2121 | parse_notifications_rest("method"), |
| 2122 | (NotificationsOp::Get("method"), false) |
| 2123 | ); |
| 2124 | assert_eq!( |
| 2125 | parse_notifications_rest("method sound --save"), |
| 2126 | ( |
| 2127 | NotificationsOp::Set { |
| 2128 | key: "method", |
| 2129 | value: "sound", |
| 2130 | }, |
| 2131 | true, |
| 2132 | ) |
| 2133 | ); |
| 2134 | assert_eq!( |
| 2135 | parse_notifications_rest("threshold_secs 30 -s"), |
| 2136 | ( |
| 2137 | NotificationsOp::Set { |
| 2138 | key: "threshold_secs", |
| 2139 | value: "30", |
| 2140 | }, |
| 2141 | true, |
| 2142 | ) |
| 2143 | ); |
| 2144 | } |
| 2145 | } |
| 2146 |