| 1 | //! Unified inventory for Codewhale extensions. |
| 2 | //! |
| 3 | //! This is deliberately a projection over the existing owners of Hooks, |
| 4 | //! Plugins, Marketplace catalogs, Skills, and MCP. It has no registry, trust |
| 5 | //! database, installer, or network fetch of its own. Future actions emitted by |
| 6 | //! this view must delegate to the existing command/mutation controllers. |
| 7 | //! The skills mutation manager remains at `/skills manage`; MCP setup is a |
| 8 | //! read-only suggestions handoff, not an inline installer or credential editor. |
| 9 | |
| 10 | use codewhale_engine::mcp::McpServerConfigExt; |
| 11 | use std::borrow::Cow; |
| 12 | use std::cell::RefCell; |
| 13 | use std::collections::BTreeSet; |
| 14 | use std::fmt::Write as _; |
| 15 | |
| 16 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; |
| 17 | use ratatui::{ |
| 18 | buffer::Buffer, |
| 19 | layout::{Constraint, Direction, Layout, Rect}, |
| 20 | style::{Modifier, Style}, |
| 21 | text::{Line, Span}, |
| 22 | widgets::{Paragraph, Widget, Wrap}, |
| 23 | }; |
| 24 | use unicode_width::UnicodeWidthStr; |
| 25 | |
| 26 | use super::{ |
| 27 | CommandPaletteAction, ModalKind, ModalView, ViewAction, ViewEvent, render_modal_footer, |
| 28 | truncate_view_text, |
| 29 | }; |
| 30 | use crate::commands::contract::{localized_approver_label, localized_turned_on_by_label}; |
| 31 | use crate::commands::groups::plugins::render::{ReviewTextContext, escape_review_text}; |
| 32 | use crate::tui::app::App; |
| 33 | use crate::tui::views::rounded::{ |
| 34 | render_hairline, render_rounded_surface_themed, resolved_surface_bg, |
| 35 | }; |
| 36 | use codewhale_localization::{Locale, MessageId, tr}; |
| 37 | use codewhale_palette as palette; |
| 38 | use codewhale_tui_kit::menu_style; |
| 39 | |
| 40 | fn localize(locale: Locale, id: MessageId, replacements: &[(&str, &str)]) -> String { |
| 41 | let mut value = tr(locale, id).into_owned(); |
| 42 | for (name, replacement) in replacements { |
| 43 | value = value.replace(&format!("{{{name}}}"), replacement); |
| 44 | } |
| 45 | value |
| 46 | } |
| 47 | |
| 48 | /// All extension surfaces in display order. |
| 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 50 | pub enum ExtensionsTab { |
| 51 | Hooks, |
| 52 | Plugins, |
| 53 | Marketplace, |
| 54 | Skills, |
| 55 | Mcp, |
| 56 | Command, |
| 57 | } |
| 58 | |
| 59 | impl ExtensionsTab { |
| 60 | pub const ALL: [Self; 6] = [ |
| 61 | Self::Hooks, |
| 62 | Self::Plugins, |
| 63 | Self::Marketplace, |
| 64 | Self::Skills, |
| 65 | Self::Mcp, |
| 66 | Self::Command, |
| 67 | ]; |
| 68 | |
| 69 | #[must_use] |
| 70 | fn label(self, locale: Locale) -> String { |
| 71 | match self { |
| 72 | Self::Hooks => tr(locale, MessageId::ExtensionsTabHooks), |
| 73 | Self::Plugins => tr(locale, MessageId::ExtensionsTabInstalled), |
| 74 | Self::Marketplace => tr(locale, MessageId::ExtensionsTabMarketplace), |
| 75 | Self::Skills => tr(locale, MessageId::HelpSkills), |
| 76 | Self::Mcp => tr(locale, MessageId::ExtensionsTabConnectors), |
| 77 | Self::Command => tr(locale, MessageId::CommandPaletteTitle), |
| 78 | } |
| 79 | .into_owned() |
| 80 | } |
| 81 | |
| 82 | const fn index(self) -> usize { |
| 83 | match self { |
| 84 | Self::Hooks => 0, |
| 85 | Self::Plugins => 1, |
| 86 | Self::Marketplace => 2, |
| 87 | Self::Skills => 3, |
| 88 | Self::Mcp => 4, |
| 89 | Self::Command => 5, |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | const fn next(self) -> Self { |
| 94 | Self::ALL[(self.index() + 1) % Self::ALL.len()] |
| 95 | } |
| 96 | |
| 97 | const fn previous(self) -> Self { |
| 98 | Self::ALL[(self.index() + Self::ALL.len() - 1) % Self::ALL.len()] |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// A real capability contributed by one plugin product. |
| 103 | /// |
| 104 | /// Recommendations use the same component vocabulary as installed plugin |
| 105 | /// bundles: a component is an MCP server or a Skill, the two things this |
| 106 | /// panel can actually install and switch on. Kinds that named a runtime |
| 107 | /// nobody could install from here — a browser driver, a sandbox helper — |
| 108 | /// were removed rather than left advertising an unreachable action. |
| 109 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 110 | pub enum PluginProductComponentKind { |
| 111 | Mcp, |
| 112 | Skills, |
| 113 | } |
| 114 | |
| 115 | impl PluginProductComponentKind { |
| 116 | fn label(self, locale: Locale) -> String { |
| 117 | match self { |
| 118 | Self::Mcp => tr(locale, MessageId::ConfigSectionMcp), |
| 119 | Self::Skills => tr(locale, MessageId::HelpSkills), |
| 120 | } |
| 121 | .into_owned() |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 126 | pub struct PluginProductComponent { |
| 127 | pub kind: PluginProductComponentKind, |
| 128 | pub name: String, |
| 129 | } |
| 130 | |
| 131 | /// Marketplace-facing recommendation model. |
| 132 | /// |
| 133 | /// `source_reference` is display provenance only. It is intentionally not an |
| 134 | /// install command or executable plan; explicit installation still enters the |
| 135 | /// reviewed plugin installer and trust flow. |
| 136 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 137 | pub struct PluginProduct { |
| 138 | pub id: String, |
| 139 | pub name: String, |
| 140 | pub description: String, |
| 141 | pub publisher: String, |
| 142 | pub source_reference: String, |
| 143 | pub components: Vec<PluginProductComponent>, |
| 144 | pub maturity: String, |
| 145 | } |
| 146 | |
| 147 | impl PluginProduct { |
| 148 | fn into_row(self, locale: Locale) -> ExtensionItem { |
| 149 | let mut components = String::new(); |
| 150 | for (index, component) in self.components.iter().enumerate() { |
| 151 | if index > 0 { |
| 152 | components.push_str(", "); |
| 153 | } |
| 154 | let _ = write!( |
| 155 | components, |
| 156 | "{} ({})", |
| 157 | component.name, |
| 158 | component.kind.label(locale) |
| 159 | ); |
| 160 | } |
| 161 | ExtensionItem { |
| 162 | id: self.id, |
| 163 | label: self.name, |
| 164 | tone: ExtensionTone::Idle, |
| 165 | description: self.description, |
| 166 | state: self.maturity, |
| 167 | detail: localize( |
| 168 | locale, |
| 169 | MessageId::ExtensionsProductDetail, |
| 170 | &[ |
| 171 | ("publisher", &self.publisher), |
| 172 | ("components", &components), |
| 173 | ("source", &self.source_reference), |
| 174 | ], |
| 175 | ), |
| 176 | action: None, |
| 177 | toggle: None, |
| 178 | remove: None, |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// What a row's state *means*, independent of the words it uses to say it. |
| 184 | /// |
| 185 | /// Every row on this screen used to paint in one colour, so twenty servers, |
| 186 | /// four of them broken, read as one undifferentiated wall — "incredibly |
| 187 | /// boring, plain, and hard on the eyes because of the sameness". The tone is |
| 188 | /// typed rather than sniffed out of the localized state string, because a |
| 189 | /// screen that only colours correctly in English is not coloured. |
| 190 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 191 | pub enum ExtensionTone { |
| 192 | /// Working: connected, enabled, active. |
| 193 | Ready, |
| 194 | /// Wants a person: auth required, disconnected, not yet reviewed. |
| 195 | Attention, |
| 196 | /// Broken: an error or a rejected entry. |
| 197 | Failure, |
| 198 | /// Deliberately off, or simply not configured. |
| 199 | #[default] |
| 200 | Idle, |
| 201 | } |
| 202 | |
| 203 | impl ExtensionTone { |
| 204 | fn ink(self) -> codewhale_palette::ChromeInk { |
| 205 | use codewhale_palette::ChromeInk; |
| 206 | match self { |
| 207 | Self::Ready => ChromeInk::Outcome, |
| 208 | Self::Attention => ChromeInk::Attention, |
| 209 | Self::Failure => ChromeInk::Failure, |
| 210 | Self::Idle => ChromeInk::Metadata, |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 216 | pub struct ExtensionItem { |
| 217 | pub id: String, |
| 218 | pub label: String, |
| 219 | pub description: String, |
| 220 | pub state: String, |
| 221 | /// Semantic reading of `state`, resolved through the theme's ink grammar. |
| 222 | pub tone: ExtensionTone, |
| 223 | pub detail: String, |
| 224 | pub action: Option<ExtensionAction>, |
| 225 | /// Reversible on/off toggle for the row (`e`): enable or disable a |
| 226 | /// plugin or MCP server without leaving the panel. |
| 227 | pub toggle: Option<ExtensionAction>, |
| 228 | /// Destructive removal for the row (`d` / Delete, or the row's |
| 229 | /// right-click menu; confirmed in two steps either way). Only MCP servers |
| 230 | /// offer it today; plugins keep their reviewed uninstall flow. |
| 231 | pub remove: Option<ExtensionAction>, |
| 232 | } |
| 233 | |
| 234 | /// Where a row's command lands when the user activates it. |
| 235 | /// |
| 236 | /// Every row used to close the panel and drop a slash command into the |
| 237 | /// transcript — inspecting a plugin closed the list and pasted its detail |
| 238 | /// into chat, and a mutation left every other row reading open-time state. |
| 239 | /// Only the row knows which its command is, so the disposition lives on the |
| 240 | /// action: mutations and inspects act in place, and flows that own a |
| 241 | /// different surface (an editor, OAuth login, a composer-bound trust token) |
| 242 | /// still yield the panel to them. |
| 243 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 244 | pub enum RowActionDisposition { |
| 245 | /// Run the command with the panel open; the host refreshes the snapshot |
| 246 | /// afterwards so every row re-reads live state. |
| 247 | InPlace, |
| 248 | /// In place, and the command's text output renders in a pager stacked on |
| 249 | /// the panel — the inspect path that keeps detail out of the transcript. |
| 250 | InPlacePager, |
| 251 | /// The command owns a different surface; the panel yields to it. |
| 252 | LeavePanel, |
| 253 | } |
| 254 | |
| 255 | /// A row affordance. Executable actions route back through the existing slash |
| 256 | /// command controller; status-only actions explain why Enter will not mutate. |
| 257 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 258 | pub enum ExtensionAction { |
| 259 | Command { |
| 260 | label: String, |
| 261 | command: String, |
| 262 | disposition: RowActionDisposition, |
| 263 | }, |
| 264 | Status { |
| 265 | label: String, |
| 266 | }, |
| 267 | } |
| 268 | |
| 269 | impl ExtensionAction { |
| 270 | fn label(&self) -> &str { |
| 271 | match self { |
| 272 | Self::Command { label, .. } | Self::Status { label } => label, |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | fn command(&self) -> Option<&str> { |
| 277 | match self { |
| 278 | Self::Command { command, .. } => Some(command), |
| 279 | Self::Status { .. } => None, |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 285 | pub struct ExtensionGroup { |
| 286 | pub id: String, |
| 287 | pub label: String, |
| 288 | pub items: Vec<ExtensionItem>, |
| 289 | } |
| 290 | |
| 291 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 292 | pub struct ExtensionsTabModel { |
| 293 | pub groups: Vec<ExtensionGroup>, |
| 294 | pub problem: Option<String>, |
| 295 | } |
| 296 | |
| 297 | /// Read model captured when the modal opens. No source is contacted over the |
| 298 | /// network and no extension process is started while building it. |
| 299 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 300 | pub struct ExtensionsSnapshot { |
| 301 | tabs: [ExtensionsTabModel; 6], |
| 302 | /// MCP manager generation and initializing flag at capture time. The |
| 303 | /// open panel reports these on its bounded poll so the host rebuilds the |
| 304 | /// model only when live state actually moved. |
| 305 | pub mcp_generation: u64, |
| 306 | pub mcp_initializing: bool, |
| 307 | } |
| 308 | |
| 309 | impl ExtensionsSnapshot { |
| 310 | #[must_use] |
| 311 | pub fn from_app(app: &App) -> Self { |
| 312 | let mut snapshot = Self { |
| 313 | mcp_generation: app.mcp_snapshot_generation, |
| 314 | mcp_initializing: app.mcp_boot_initializing(), |
| 315 | ..Self::default() |
| 316 | }; |
| 317 | snapshot.tabs[ExtensionsTab::Hooks.index()] = hooks_model(app, app.ui_locale); |
| 318 | snapshot.tabs[ExtensionsTab::Plugins.index()] = plugins_model(app, app.ui_locale); |
| 319 | snapshot.tabs[ExtensionsTab::Marketplace.index()] = marketplace_model(app, app.ui_locale); |
| 320 | snapshot.tabs[ExtensionsTab::Skills.index()] = skills_model(app, app.ui_locale); |
| 321 | snapshot.tabs[ExtensionsTab::Mcp.index()] = mcp_model(app, app.ui_locale); |
| 322 | snapshot.tabs[ExtensionsTab::Command.index()] = commands_model(app, app.ui_locale); |
| 323 | snapshot |
| 324 | .with_recommendations(reviewed_product_catalog(app.ui_locale), app.ui_locale) |
| 325 | .with_recommended_actions(app) |
| 326 | } |
| 327 | |
| 328 | #[must_use] |
| 329 | pub fn with_recommendations(mut self, products: Vec<PluginProduct>, locale: Locale) -> Self { |
| 330 | if !products.is_empty() { |
| 331 | self.tabs[ExtensionsTab::Marketplace.index()].groups.insert( |
| 332 | 0, |
| 333 | ExtensionGroup { |
| 334 | id: "recommended".into(), |
| 335 | label: tr(locale, MessageId::ExtensionsGroupRecommended).into_owned(), |
| 336 | items: products |
| 337 | .into_iter() |
| 338 | .map(|product| product.into_row(locale)) |
| 339 | .collect(), |
| 340 | }, |
| 341 | ); |
| 342 | } |
| 343 | self |
| 344 | } |
| 345 | |
| 346 | fn with_recommended_actions(mut self, app: &App) -> Self { |
| 347 | let configured = codewhale_engine::mcp::load_config_with_workspace_and_plugins( |
| 348 | &app.mcp_config_path, |
| 349 | &app.workspace, |
| 350 | app.plugin_registry.as_ref(), |
| 351 | ) |
| 352 | .ok(); |
| 353 | let computer_use = self.tabs[ExtensionsTab::Marketplace.index()] |
| 354 | .groups |
| 355 | .iter() |
| 356 | .find(|group| group.id == "codewhale") |
| 357 | .and_then(|group| { |
| 358 | group |
| 359 | .items |
| 360 | .iter() |
| 361 | .find(|item| item.id == "codewhale:computer-use") |
| 362 | }) |
| 363 | .cloned(); |
| 364 | let Some(group) = self.tabs[ExtensionsTab::Marketplace.index()] |
| 365 | .groups |
| 366 | .iter_mut() |
| 367 | .find(|group| group.id == "recommended") |
| 368 | else { |
| 369 | return self; |
| 370 | }; |
| 371 | |
| 372 | if configured.is_none() { |
| 373 | for item in &mut group.items { |
| 374 | item.action = Some(ExtensionAction::Status { |
| 375 | label: tr(app.ui_locale, MessageId::PickerActionUnavailable).into_owned(), |
| 376 | }); |
| 377 | } |
| 378 | return self; |
| 379 | } |
| 380 | |
| 381 | for item in &mut group.items { |
| 382 | if item.id == "codewhale-computer-use" { |
| 383 | if let Some(catalog_item) = &computer_use { |
| 384 | item.state = catalog_item.state.clone(); |
| 385 | item.tone = catalog_item.tone; |
| 386 | item.action = catalog_item.action.clone(); |
| 387 | } else { |
| 388 | item.action = Some(ExtensionAction::Status { |
| 389 | label: tr(app.ui_locale, MessageId::PickerActionUnavailable).into_owned(), |
| 390 | }); |
| 391 | } |
| 392 | continue; |
| 393 | } |
| 394 | let recommendation = match item.id.as_str() { |
| 395 | "playwright-browser" => Some(("playwright", "playwright")), |
| 396 | "chrome-devtools" => Some(("chrome-devtools", "chrome-devtools")), |
| 397 | _ => None, |
| 398 | }; |
| 399 | if let Some((server_name, recommendation_id)) = recommendation { |
| 400 | match configured |
| 401 | .as_ref() |
| 402 | .and_then(|config| config.servers.get(server_name)) |
| 403 | { |
| 404 | None => { |
| 405 | item.state = |
| 406 | tr(app.ui_locale, MessageId::ExtensionsStateAvailable).into_owned(); |
| 407 | item.action = Some(ExtensionAction::Command { |
| 408 | label: tr(app.ui_locale, MessageId::ExtensionsActionAdd).into_owned(), |
| 409 | command: format!("/mcp add recommended {recommendation_id}"), |
| 410 | disposition: RowActionDisposition::InPlace, |
| 411 | }); |
| 412 | } |
| 413 | Some(server) if !server.is_enabled() => { |
| 414 | item.state = |
| 415 | tr(app.ui_locale, MessageId::HotbarSetupStatusDisabled).into_owned(); |
| 416 | item.action = Some(ExtensionAction::Command { |
| 417 | label: tr(app.ui_locale, MessageId::ExtensionsActionEnable) |
| 418 | .into_owned(), |
| 419 | command: format!("/mcp enable {server_name}"), |
| 420 | disposition: RowActionDisposition::InPlace, |
| 421 | }); |
| 422 | } |
| 423 | Some(_) => { |
| 424 | item.state = |
| 425 | tr(app.ui_locale, MessageId::PickerActionConfigured).into_owned(); |
| 426 | item.action = Some(ExtensionAction::Status { |
| 427 | label: tr(app.ui_locale, MessageId::PickerActionConfigured) |
| 428 | .into_owned(), |
| 429 | }); |
| 430 | } |
| 431 | } |
| 432 | } else { |
| 433 | item.action = Some(ExtensionAction::Status { |
| 434 | label: tr(app.ui_locale, MessageId::PickerActionUnavailable).into_owned(), |
| 435 | }); |
| 436 | } |
| 437 | } |
| 438 | self |
| 439 | } |
| 440 | |
| 441 | fn tab(&self, tab: ExtensionsTab) -> &ExtensionsTabModel { |
| 442 | &self.tabs[tab.index()] |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | /// Pinned review metadata only. These rows do not contain install commands, |
| 447 | /// do not fetch anything, and do not grant trust. The source-specific plugin |
| 448 | /// manifests produced by the packaging lane remain the installation authority. |
| 449 | /// |
| 450 | /// Every row here must resolve to a real action in |
| 451 | /// [`ExtensionsSnapshot::with_recommended_actions`]. Rows that could only |
| 452 | /// ever render `unavailable` — Browser Use, the sandbox runtime — were |
| 453 | /// removed: a recommendation a person cannot act on is an advertisement, and |
| 454 | /// it made the tab read as a list of things Codewhale would not do. |
| 455 | fn reviewed_product_catalog(locale: Locale) -> Vec<PluginProduct> { |
| 456 | vec![ |
| 457 | // First-party computer use. This is the only computer-use product |
| 458 | // row: third-party desktop-control MCPs are not recommended here. |
| 459 | PluginProduct { |
| 460 | id: "codewhale-computer-use".into(), |
| 461 | name: "Computer Use".into(), |
| 462 | description: tr( |
| 463 | locale, |
| 464 | MessageId::ExtensionsProductCodewhaleComputerUseDescription, |
| 465 | ) |
| 466 | .into_owned(), |
| 467 | publisher: "Codewhale".into(), |
| 468 | source_reference: "https://github.com/codewhale-hq/codewhale-cu-plugin".into(), |
| 469 | components: vec![ |
| 470 | PluginProductComponent { |
| 471 | kind: PluginProductComponentKind::Mcp, |
| 472 | name: "Computer Use MCP".into(), |
| 473 | }, |
| 474 | PluginProductComponent { |
| 475 | kind: PluginProductComponentKind::Skills, |
| 476 | name: "Computer Use Skill".into(), |
| 477 | }, |
| 478 | ], |
| 479 | maturity: tr(locale, MessageId::ExtensionsStateFirstParty).into_owned(), |
| 480 | }, |
| 481 | PluginProduct { |
| 482 | id: "playwright-browser".into(), |
| 483 | name: "Playwright Browser".into(), |
| 484 | description: tr(locale, MessageId::ExtensionsProductPlaywrightDescription).into_owned(), |
| 485 | publisher: "Microsoft".into(), |
| 486 | source_reference: "microsoft/playwright-mcp".into(), |
| 487 | components: vec![PluginProductComponent { |
| 488 | kind: PluginProductComponentKind::Mcp, |
| 489 | name: "Playwright MCP".into(), |
| 490 | }], |
| 491 | maturity: tr(locale, MessageId::ExtensionsStateReviewedCandidate).into_owned(), |
| 492 | }, |
| 493 | PluginProduct { |
| 494 | id: "chrome-devtools".into(), |
| 495 | name: "Chrome DevTools".into(), |
| 496 | description: tr(locale, MessageId::ExtensionsProductChromeDescription).into_owned(), |
| 497 | publisher: "Chrome DevTools".into(), |
| 498 | source_reference: "ChromeDevTools/chrome-devtools-mcp".into(), |
| 499 | components: vec![PluginProductComponent { |
| 500 | kind: PluginProductComponentKind::Mcp, |
| 501 | name: "Chrome DevTools MCP".into(), |
| 502 | }], |
| 503 | maturity: tr(locale, MessageId::ExtensionsStateReviewedCandidate).into_owned(), |
| 504 | }, |
| 505 | ] |
| 506 | } |
| 507 | |
| 508 | fn hooks_model(app: &App, locale: Locale) -> ExtensionsTabModel { |
| 509 | let config = app.hooks.config(); |
| 510 | let configured = config |
| 511 | .hooks |
| 512 | .iter() |
| 513 | .enumerate() |
| 514 | .map(|(index, hook)| ExtensionItem { |
| 515 | id: format!("hook-{index}"), |
| 516 | tone: if config.enabled { |
| 517 | ExtensionTone::Ready |
| 518 | } else { |
| 519 | ExtensionTone::Idle |
| 520 | }, |
| 521 | label: hook.name.clone().unwrap_or_else(|| { |
| 522 | localize( |
| 523 | locale, |
| 524 | MessageId::ExtensionsHookFallback, |
| 525 | &[("event", hook.event.as_str())], |
| 526 | ) |
| 527 | }), |
| 528 | description: hook.event.as_str().to_string(), |
| 529 | state: if config.enabled { |
| 530 | tr(locale, MessageId::ExtensionsStateEnabled) |
| 531 | } else { |
| 532 | tr(locale, MessageId::HotbarSetupStatusDisabled) |
| 533 | } |
| 534 | .into_owned(), |
| 535 | detail: localize( |
| 536 | locale, |
| 537 | MessageId::ExtensionsHookDetail, |
| 538 | &[ |
| 539 | ("timeout", &hook.timeout_secs.to_string()), |
| 540 | ("background", &localized_bool(locale, hook.background)), |
| 541 | ( |
| 542 | "continue_on_error", |
| 543 | &localized_bool(locale, hook.continue_on_error), |
| 544 | ), |
| 545 | ], |
| 546 | ), |
| 547 | action: Some(ExtensionAction::Command { |
| 548 | label: tr(locale, MessageId::ExtensionsActionEdit).into_owned(), |
| 549 | command: "/hooks edit".into(), |
| 550 | disposition: RowActionDisposition::LeavePanel, |
| 551 | }), |
| 552 | toggle: None, |
| 553 | remove: None, |
| 554 | }) |
| 555 | .collect::<Vec<_>>(); |
| 556 | let problems = config |
| 557 | .problems |
| 558 | .iter() |
| 559 | .enumerate() |
| 560 | .map(|(index, problem)| ExtensionItem { |
| 561 | id: format!("hook-problem-{index}"), |
| 562 | tone: if problem.rejected { |
| 563 | ExtensionTone::Failure |
| 564 | } else { |
| 565 | ExtensionTone::Attention |
| 566 | }, |
| 567 | label: problem.name.clone().unwrap_or_else(|| { |
| 568 | tr(locale, MessageId::ExtensionsHooksConfiguration).into_owned() |
| 569 | }), |
| 570 | description: problem.detail.clone(), |
| 571 | state: if problem.rejected { |
| 572 | tr(locale, MessageId::ExtensionsStateRejected) |
| 573 | } else { |
| 574 | tr(locale, MessageId::ExtensionsStateWarning) |
| 575 | } |
| 576 | .into_owned(), |
| 577 | detail: codewhale_engine::hooks::config::problem_summary(problem), |
| 578 | action: Some(ExtensionAction::Command { |
| 579 | label: tr(locale, MessageId::ExtensionsActionEdit).into_owned(), |
| 580 | command: "/hooks edit".into(), |
| 581 | disposition: RowActionDisposition::LeavePanel, |
| 582 | }), |
| 583 | toggle: None, |
| 584 | remove: None, |
| 585 | }) |
| 586 | .collect::<Vec<_>>(); |
| 587 | let mut groups = Vec::new(); |
| 588 | if !configured.is_empty() { |
| 589 | groups.push(ExtensionGroup { |
| 590 | id: "configured".into(), |
| 591 | label: tr(locale, MessageId::ExtensionsGroupConfigured).into_owned(), |
| 592 | items: configured, |
| 593 | }); |
| 594 | } |
| 595 | if !problems.is_empty() { |
| 596 | groups.push(ExtensionGroup { |
| 597 | id: "problems".into(), |
| 598 | label: tr(locale, MessageId::ExtensionsGroupProblems).into_owned(), |
| 599 | items: problems, |
| 600 | }); |
| 601 | } |
| 602 | // A screen with nothing on it and nothing to press is where "need to be |
| 603 | // able to add hooks!" comes from. The row that teaches the file is the |
| 604 | // row that opens it. |
| 605 | if groups.is_empty() { |
| 606 | groups.push(ExtensionGroup { |
| 607 | id: "start".into(), |
| 608 | label: tr(locale, MessageId::ExtensionsGroupConfigured).into_owned(), |
| 609 | items: vec![ExtensionItem { |
| 610 | id: "hooks-add".into(), |
| 611 | tone: ExtensionTone::Idle, |
| 612 | label: tr(locale, MessageId::ExtensionsHooksAddLabel).into_owned(), |
| 613 | description: tr(locale, MessageId::ExtensionsHooksAddDescription).into_owned(), |
| 614 | state: tr(locale, MessageId::ExtensionsStateAvailable).into_owned(), |
| 615 | detail: ".codewhale/hooks.toml".into(), |
| 616 | action: Some(ExtensionAction::Command { |
| 617 | label: tr(locale, MessageId::ExtensionsActionEdit).into_owned(), |
| 618 | command: "/hooks edit".into(), |
| 619 | disposition: RowActionDisposition::LeavePanel, |
| 620 | }), |
| 621 | toggle: None, |
| 622 | remove: None, |
| 623 | }], |
| 624 | }); |
| 625 | } |
| 626 | ExtensionsTabModel { |
| 627 | groups, |
| 628 | problem: None, |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | fn inventory_summary( |
| 633 | inventory: &codewhale_plugins::manifest::PluginInventory, |
| 634 | locale: Locale, |
| 635 | ) -> String { |
| 636 | let mut parts = Vec::new(); |
| 637 | if inventory.skills > 0 { |
| 638 | parts.push(localize( |
| 639 | locale, |
| 640 | MessageId::ExtensionsInventorySkills, |
| 641 | &[("count", &inventory.skills.to_string())], |
| 642 | )); |
| 643 | } |
| 644 | if inventory.mcp_servers > 0 { |
| 645 | parts.push(localize( |
| 646 | locale, |
| 647 | MessageId::ExtensionsInventoryMcp, |
| 648 | &[("count", &inventory.mcp_servers.to_string())], |
| 649 | )); |
| 650 | } |
| 651 | if inventory.hooks > 0 { |
| 652 | parts.push(localize( |
| 653 | locale, |
| 654 | MessageId::ExtensionsInventoryHooks, |
| 655 | &[("count", &inventory.hooks.to_string())], |
| 656 | )); |
| 657 | } |
| 658 | if inventory.commands > 0 { |
| 659 | parts.push(localize( |
| 660 | locale, |
| 661 | MessageId::ExtensionsInventoryCommands, |
| 662 | &[("count", &inventory.commands.to_string())], |
| 663 | )); |
| 664 | } |
| 665 | if inventory.agents > 0 { |
| 666 | parts.push(localize( |
| 667 | locale, |
| 668 | MessageId::ExtensionsInventoryAgents, |
| 669 | &[("count", &inventory.agents.to_string())], |
| 670 | )); |
| 671 | } |
| 672 | if parts.is_empty() { |
| 673 | tr(locale, MessageId::ExtensionsInventoryNone).into_owned() |
| 674 | } else { |
| 675 | parts.join(", ") |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | fn localized_bool(locale: Locale, value: bool) -> String { |
| 680 | tr( |
| 681 | locale, |
| 682 | if value { |
| 683 | MessageId::ExtensionsValueYes |
| 684 | } else { |
| 685 | MessageId::ExtensionsValueNo |
| 686 | }, |
| 687 | ) |
| 688 | .into_owned() |
| 689 | } |
| 690 | |
| 691 | /// Say what the row *is*, in the words a person already uses for a switch. |
| 692 | /// |
| 693 | /// "enabled, untrusted" named an internal pair of booleans and gave no hint |
| 694 | /// that anything could be done about it; a founder read the panel and said |
| 695 | /// "i don't know what untrusted means and i can't even do anything about |
| 696 | /// it". The switch now reads on/off and the review requirement reads |
| 697 | /// "needs review", which is both what it is and the verb `e`/Enter runs. |
| 698 | fn localized_plugin_state(locale: Locale, state: &str) -> String { |
| 699 | let id = match state { |
| 700 | "active" => MessageId::ExtensionsStateOn, |
| 701 | "disabled" | "inactive" => MessageId::ExtensionsStateOff, |
| 702 | "enabled-untrusted" => MessageId::ExtensionsStateNeedsReview, |
| 703 | "unstaged" => MessageId::ExtensionsStateUnstaged, |
| 704 | "inapplicable" => MessageId::ExtensionsStateInapplicable, |
| 705 | "unsupported" => MessageId::ExtensionsStateUnsupported, |
| 706 | _ => return state.to_string(), |
| 707 | }; |
| 708 | tr(locale, id).into_owned() |
| 709 | } |
| 710 | |
| 711 | /// The row's state line, which must answer both "is the switch on?" and |
| 712 | /// "is anything standing between this and running?" at once. |
| 713 | /// |
| 714 | /// A bundle that is switched off *and* never reviewed reads `off · needs |
| 715 | /// review`, so turning it on is visibly a two-part step rather than a dead |
| 716 | /// `disabled` with no explanation — the exact row (`computer-use`) the |
| 717 | /// founder could not enable. |
| 718 | fn plugin_row_state(locale: Locale, plugin: &codewhale_plugins::types::LoadedPlugin) -> String { |
| 719 | use codewhale_plugins::host_services::{PluginApprover, workspace_folder_name}; |
| 720 | let state = localized_plugin_state(locale, plugin.state_label()); |
| 721 | if !plugin.trusted() && plugin.approved_by.is_none() { |
| 722 | if plugin.enabled { |
| 723 | return state; |
| 724 | } |
| 725 | return format!( |
| 726 | "{state} · {}", |
| 727 | tr(locale, MessageId::ExtensionsStateNeedsReview) |
| 728 | ); |
| 729 | } |
| 730 | match plugin.approved_by.as_ref() { |
| 731 | Some(PluginApprover::Agent(agent)) => { |
| 732 | if plugin.outside_reach { |
| 733 | let folder = escape_review_text( |
| 734 | workspace_folder_name(&agent.workspace), |
| 735 | ReviewTextContext::Plain, |
| 736 | ); |
| 737 | let id = if plugin.enabled { |
| 738 | MessageId::CmdPluginAuditRowOnOnlyIn |
| 739 | } else { |
| 740 | MessageId::CmdPluginAuditRowOffOnlyIn |
| 741 | }; |
| 742 | return localize(locale, id, &[("folder", &folder)]); |
| 743 | } |
| 744 | if !plugin.enabled { |
| 745 | return tr(locale, MessageId::CmdPluginAuditRowAgentOff).into_owned(); |
| 746 | } |
| 747 | let id = if matches!(plugin.enabled_by, Some(PluginApprover::Person { .. })) { |
| 748 | MessageId::CmdPluginAuditRowPersonEnabledAgentApproved |
| 749 | } else { |
| 750 | MessageId::CmdPluginAuditRowTurnedOnByAgent |
| 751 | }; |
| 752 | tr(locale, id).into_owned() |
| 753 | } |
| 754 | Some(PluginApprover::CommandLine) => { |
| 755 | let id = if plugin.enabled { |
| 756 | MessageId::CmdPluginAuditRowCommandLineOn |
| 757 | } else { |
| 758 | MessageId::CmdPluginAuditRowCommandLineOff |
| 759 | }; |
| 760 | tr(locale, id).into_owned() |
| 761 | } |
| 762 | None => { |
| 763 | let id = if plugin.enabled { |
| 764 | MessageId::CmdPluginAuditRowUnknownOn |
| 765 | } else { |
| 766 | MessageId::CmdPluginAuditRowUnknownOff |
| 767 | }; |
| 768 | tr(locale, id).into_owned() |
| 769 | } |
| 770 | Some(PluginApprover::Person { .. }) => state, |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | fn plugin_attribution_parts( |
| 775 | locale: Locale, |
| 776 | plugin: &codewhale_plugins::types::LoadedPlugin, |
| 777 | ) -> Vec<String> { |
| 778 | use codewhale_plugins::host_services::{ |
| 779 | PluginApprover, PluginCohort, cohort_of, short_review_date, workspace_folder_name, |
| 780 | }; |
| 781 | let mut parts = Vec::new(); |
| 782 | if plugin.trusted() || plugin.approved_by.is_some() { |
| 783 | let approver = localized_approver_label(locale, plugin.approved_by.as_ref()); |
| 784 | if let Some(ts) = plugin.reviewed_at.as_deref() { |
| 785 | let date = escape_review_text(short_review_date(ts), ReviewTextContext::Plain); |
| 786 | let approved_date = localize( |
| 787 | locale, |
| 788 | MessageId::CmdPluginAuditApprovedDate, |
| 789 | &[("date", &date)], |
| 790 | ); |
| 791 | parts.push(format!("{approver} ({approved_date})")); |
| 792 | } else { |
| 793 | parts.push(approver); |
| 794 | } |
| 795 | } |
| 796 | if plugin.enabled { |
| 797 | parts.push(localized_turned_on_by_label( |
| 798 | locale, |
| 799 | plugin.enabled_by.as_ref(), |
| 800 | )); |
| 801 | } |
| 802 | if let Some(workspace) = plugin |
| 803 | .approved_by |
| 804 | .as_ref() |
| 805 | .and_then(PluginApprover::agent_workspace) |
| 806 | { |
| 807 | let folder = escape_review_text(workspace_folder_name(workspace), ReviewTextContext::Plain); |
| 808 | let id = if plugin.outside_reach { |
| 809 | MessageId::CmdPluginAuditReachOnlyIn |
| 810 | } else { |
| 811 | MessageId::CmdPluginAuditReachHere |
| 812 | }; |
| 813 | parts.push(localize(locale, id, &[("folder", &folder)])); |
| 814 | } |
| 815 | if plugin.trusted() |
| 816 | && matches!( |
| 817 | cohort_of(plugin.approved_by.as_ref()), |
| 818 | PluginCohort::Agent { .. } |
| 819 | ) |
| 820 | { |
| 821 | parts.push(tr(locale, MessageId::CmdPluginAuditAgentProcessNote).into_owned()); |
| 822 | } |
| 823 | parts |
| 824 | } |
| 825 | |
| 826 | fn localized_trust(locale: Locale, trust: &str) -> String { |
| 827 | let id = match trust { |
| 828 | "trusted" => MessageId::ExtensionsTrustTrusted, |
| 829 | "not-reviewed" => MessageId::ExtensionsTrustNotReviewed, |
| 830 | "content-changed" => MessageId::ExtensionsTrustContentChanged, |
| 831 | "capabilities-changed" => MessageId::ExtensionsTrustCapabilitiesChanged, |
| 832 | _ => return trust.to_string(), |
| 833 | }; |
| 834 | tr(locale, id).into_owned() |
| 835 | } |
| 836 | |
| 837 | fn localized_compatibility(locale: Locale, compatibility: &str) -> String { |
| 838 | let id = match compatibility { |
| 839 | "full" => MessageId::ExtensionsCompatibilityFull, |
| 840 | "partial" => MessageId::ExtensionsCompatibilityPartial, |
| 841 | "unsupported" => MessageId::ExtensionsStateUnsupported, |
| 842 | _ => return compatibility.to_string(), |
| 843 | }; |
| 844 | tr(locale, id).into_owned() |
| 845 | } |
| 846 | |
| 847 | fn localized_tier(locale: Locale, tier: &str) -> String { |
| 848 | let id = match tier { |
| 849 | "community" => MessageId::ExtensionsTierCommunity, |
| 850 | "official" => MessageId::ExtensionsTierOfficial, |
| 851 | "curated" => MessageId::ExtensionsTierCurated, |
| 852 | "partner" => MessageId::ExtensionsTierPartner, |
| 853 | _ => return tier.to_string(), |
| 854 | }; |
| 855 | tr(locale, id).into_owned() |
| 856 | } |
| 857 | |
| 858 | fn localized_skill_root(locale: Locale, kind: codewhale_skills::roots::SkillRootKind) -> String { |
| 859 | use codewhale_skills::roots::SkillRootKind; |
| 860 | |
| 861 | match kind { |
| 862 | SkillRootKind::CodeWhaleProject => { |
| 863 | tr(locale, MessageId::ExtensionsSkillRootProject).into_owned() |
| 864 | } |
| 865 | SkillRootKind::CodeWhaleGlobal => { |
| 866 | tr(locale, MessageId::ExtensionsSkillRootGlobal).into_owned() |
| 867 | } |
| 868 | SkillRootKind::CompatibleProject(harness) => localize( |
| 869 | locale, |
| 870 | MessageId::ExtensionsSkillRootCompatibleProject, |
| 871 | &[("harness", harness.label())], |
| 872 | ), |
| 873 | SkillRootKind::CompatibleGlobal(harness) => localize( |
| 874 | locale, |
| 875 | MessageId::ExtensionsSkillRootCompatibleGlobal, |
| 876 | &[("harness", harness.label())], |
| 877 | ), |
| 878 | SkillRootKind::Configured => { |
| 879 | tr(locale, MessageId::ExtensionsSkillRootConfigured).into_owned() |
| 880 | } |
| 881 | SkillRootKind::BuiltIn => tr(locale, MessageId::ExtensionsGroupBuiltIn).into_owned(), |
| 882 | SkillRootKind::ReviewedPluginSnapshot => { |
| 883 | tr(locale, MessageId::ExtensionsSkillRootReviewedPlugin).into_owned() |
| 884 | } |
| 885 | SkillRootKind::RegistryCache => { |
| 886 | tr(locale, MessageId::ExtensionsSkillRootRegistryCache).into_owned() |
| 887 | } |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | /// The one action a plugin row offers, wherever that row is drawn. |
| 892 | /// |
| 893 | /// The Plugins tab and the marketplace's first-party row both need "what does |
| 894 | /// this plugin want from me right now?", and a second copy of the ladder is |
| 895 | /// how the marketplace ends up offering `Enable` for something already active. |
| 896 | fn plugin_row_action( |
| 897 | locale: Locale, |
| 898 | plugin: &codewhale_plugins::types::LoadedPlugin, |
| 899 | ) -> ExtensionAction { |
| 900 | let has_error_diagnostics = plugin.diagnostics.iter().any(|diagnostic| { |
| 901 | diagnostic.level == codewhale_plugins::types::PluginDiagnosticLevel::Error |
| 902 | }); |
| 903 | if has_error_diagnostics { |
| 904 | ExtensionAction::Command { |
| 905 | label: tr(locale, MessageId::ExtensionsActionDiagnose).into_owned(), |
| 906 | command: format!("/plugin validate {}", plugin.name()), |
| 907 | disposition: RowActionDisposition::InPlacePager, |
| 908 | } |
| 909 | } else if plugin.active() { |
| 910 | ExtensionAction::Command { |
| 911 | label: tr(locale, MessageId::LaunchHintOpen).into_owned(), |
| 912 | command: format!("/plugin show {}", plugin.name()), |
| 913 | disposition: RowActionDisposition::InPlacePager, |
| 914 | } |
| 915 | } else if plugin.trusted() && !plugin.enabled { |
| 916 | ExtensionAction::Command { |
| 917 | label: tr(locale, MessageId::ExtensionsActionEnable).into_owned(), |
| 918 | command: format!("/plugin enable {}", plugin.name()), |
| 919 | disposition: RowActionDisposition::InPlace, |
| 920 | } |
| 921 | } else { |
| 922 | // The command opens the exact-content review with its confirmation |
| 923 | // control stacked on this panel. Confirming the digest runs the |
| 924 | // trust mutation and the host re-reads the inventory, so the row the |
| 925 | // person just reviewed reports its new state instead of the stale |
| 926 | // "not reviewed" it left with. |
| 927 | ExtensionAction::Command { |
| 928 | label: tr(locale, MessageId::ExtensionsActionReview).into_owned(), |
| 929 | command: format!("/plugin trust {}", plugin.name()), |
| 930 | disposition: RowActionDisposition::InPlace, |
| 931 | } |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | /// The reversible on/off control for a plugin row — offered on **every** |
| 936 | /// plugin, reviewed or not. |
| 937 | /// |
| 938 | /// Withholding the switch from an unreviewed bundle left `computer-use` |
| 939 | /// reading `disabled` with no way to enable it: the panel said what was |
| 940 | /// wrong and then refused the only gesture that could fix it. Nothing about |
| 941 | /// the trust boundary required that. `/plugin enable` already routes an |
| 942 | /// unreviewed bundle into the exact-capability review |
| 943 | /// (`mutate_bundle` in `commands::groups::plugins`) and only flips the |
| 944 | /// switch once the digest is confirmed, so handing `e` to every row widens |
| 945 | /// the affordance without widening what runs unreviewed. |
| 946 | fn plugin_row_toggle( |
| 947 | locale: Locale, |
| 948 | plugin: &codewhale_plugins::types::LoadedPlugin, |
| 949 | ) -> Option<ExtensionAction> { |
| 950 | Some(if plugin.enabled { |
| 951 | ExtensionAction::Command { |
| 952 | label: tr(locale, MessageId::ExtensionsActionDisable).into_owned(), |
| 953 | command: format!("/plugin disable {}", plugin.name()), |
| 954 | disposition: RowActionDisposition::InPlace, |
| 955 | } |
| 956 | } else { |
| 957 | ExtensionAction::Command { |
| 958 | label: tr(locale, MessageId::ExtensionsActionEnable).into_owned(), |
| 959 | command: format!("/plugin enable {}", plugin.name()), |
| 960 | disposition: RowActionDisposition::InPlace, |
| 961 | } |
| 962 | }) |
| 963 | } |
| 964 | |
| 965 | /// How a plugin row reads, using the same ladder as [`plugin_row_action`]. |
| 966 | fn plugin_row_tone(plugin: &codewhale_plugins::types::LoadedPlugin) -> ExtensionTone { |
| 967 | use codewhale_plugins::host_services::PluginApprover; |
| 968 | |
| 969 | let has_error_diagnostics = plugin.diagnostics.iter().any(|diagnostic| { |
| 970 | diagnostic.level == codewhale_plugins::types::PluginDiagnosticLevel::Error |
| 971 | }); |
| 972 | if has_error_diagnostics { |
| 973 | ExtensionTone::Failure |
| 974 | } else if plugin.active() { |
| 975 | if matches!( |
| 976 | plugin.approved_by, |
| 977 | Some(PluginApprover::Agent(_) | PluginApprover::CommandLine) |
| 978 | ) { |
| 979 | ExtensionTone::Attention |
| 980 | } else { |
| 981 | ExtensionTone::Ready |
| 982 | } |
| 983 | } else if plugin.trusted() { |
| 984 | ExtensionTone::Idle |
| 985 | } else { |
| 986 | ExtensionTone::Attention |
| 987 | } |
| 988 | } |
| 989 | |
| 990 | fn plugins_model(app: &App, locale: Locale) -> ExtensionsTabModel { |
| 991 | let mut by_scope = [Vec::new(), Vec::new(), Vec::new()]; |
| 992 | for plugin in app.plugin_registry.list() { |
| 993 | let scope = match plugin.scope { |
| 994 | codewhale_plugins::types::PluginScope::Builtin => 0, |
| 995 | codewhale_plugins::types::PluginScope::User => 1, |
| 996 | codewhale_plugins::types::PluginScope::Workspace => 2, |
| 997 | }; |
| 998 | let diagnostic_count = plugin.diagnostics.len(); |
| 999 | let action = plugin_row_action(locale, plugin); |
| 1000 | let toggle = plugin_row_toggle(locale, plugin); |
| 1001 | by_scope[scope].push(ExtensionItem { |
| 1002 | id: plugin.id.as_str().to_string(), |
| 1003 | tone: plugin_row_tone(plugin), |
| 1004 | label: escape_review_text(plugin.name(), ReviewTextContext::Plain), |
| 1005 | description: plugin |
| 1006 | .manifest |
| 1007 | .plugin |
| 1008 | .description |
| 1009 | .as_deref() |
| 1010 | .map(|description| escape_review_text(description, ReviewTextContext::Plain)) |
| 1011 | .unwrap_or_else(|| inventory_summary(&plugin.inventory, locale)), |
| 1012 | state: plugin_row_state(locale, plugin), |
| 1013 | // An unreviewed bundle's detail line is the one place with room |
| 1014 | // to say what the review *is*. `trust: not reviewed` restated |
| 1015 | // the state word and taught nobody anything; the sentence says |
| 1016 | // what Codewhale withholds and which key ends the wait. |
| 1017 | detail: if plugin.trusted() { |
| 1018 | let trust_key = if matches!( |
| 1019 | plugin.approved_by, |
| 1020 | Some( |
| 1021 | codewhale_plugins::host_services::PluginApprover::Agent(_) |
| 1022 | | codewhale_plugins::host_services::PluginApprover::CommandLine |
| 1023 | ) |
| 1024 | ) { |
| 1025 | "not-reviewed" |
| 1026 | } else { |
| 1027 | plugin.trust_status.as_str() |
| 1028 | }; |
| 1029 | let base_detail = localize( |
| 1030 | locale, |
| 1031 | MessageId::ExtensionsPluginDetail, |
| 1032 | &[ |
| 1033 | ("inventory", &inventory_summary(&plugin.inventory, locale)), |
| 1034 | ("trust", &localized_trust(locale, trust_key)), |
| 1035 | ( |
| 1036 | "compatibility", |
| 1037 | &localized_compatibility(locale, plugin.compatibility().as_str()), |
| 1038 | ), |
| 1039 | ("diagnostics", &diagnostic_count.to_string()), |
| 1040 | ], |
| 1041 | ); |
| 1042 | let extra = plugin_attribution_parts(locale, plugin); |
| 1043 | if extra.is_empty() { |
| 1044 | base_detail |
| 1045 | } else { |
| 1046 | format!("{base_detail} · {}", extra.join(" · ")) |
| 1047 | } |
| 1048 | } else { |
| 1049 | format!( |
| 1050 | "{} · Enter runs /plugin trust {} to confirm content hash · {}", |
| 1051 | tr(locale, MessageId::ExtensionsReviewExplainer), |
| 1052 | plugin.name(), |
| 1053 | inventory_summary(&plugin.inventory, locale) |
| 1054 | ) |
| 1055 | }, |
| 1056 | action: Some(action), |
| 1057 | toggle, |
| 1058 | remove: None, |
| 1059 | }); |
| 1060 | } |
| 1061 | let labels = [ |
| 1062 | ( |
| 1063 | "builtin", |
| 1064 | tr(locale, MessageId::ExtensionsGroupBuiltIn).into_owned(), |
| 1065 | ), |
| 1066 | ( |
| 1067 | "user", |
| 1068 | tr(locale, MessageId::ExtensionsGroupUser).into_owned(), |
| 1069 | ), |
| 1070 | ( |
| 1071 | "workspace", |
| 1072 | tr(locale, MessageId::ExtensionsGroupWorkspace).into_owned(), |
| 1073 | ), |
| 1074 | ]; |
| 1075 | let mut groups = labels |
| 1076 | .into_iter() |
| 1077 | .zip(by_scope) |
| 1078 | .filter(|(_, items)| !items.is_empty()) |
| 1079 | .map(|((id, label), items)| ExtensionGroup { |
| 1080 | id: id.into(), |
| 1081 | label, |
| 1082 | items, |
| 1083 | }) |
| 1084 | .collect::<Vec<_>>(); |
| 1085 | let problems = app |
| 1086 | .plugin_registry |
| 1087 | .diagnostics() |
| 1088 | .iter() |
| 1089 | .enumerate() |
| 1090 | .map(|(index, diagnostic)| ExtensionItem { |
| 1091 | id: format!("plugin-diagnostic-{index}"), |
| 1092 | tone: ExtensionTone::Failure, |
| 1093 | label: diagnostic.code.to_string(), |
| 1094 | description: diagnostic.message.clone(), |
| 1095 | state: if diagnostic.level == codewhale_plugins::types::PluginDiagnosticLevel::Error { |
| 1096 | tr(locale, MessageId::ExtensionsStateInvalid) |
| 1097 | } else { |
| 1098 | tr(locale, MessageId::ExtensionsStateWarning) |
| 1099 | } |
| 1100 | .into_owned(), |
| 1101 | detail: diagnostic |
| 1102 | .path |
| 1103 | .as_ref() |
| 1104 | .map(|path| path.display().to_string()) |
| 1105 | .unwrap_or_else(|| diagnostic.message.clone()), |
| 1106 | action: Some(ExtensionAction::Command { |
| 1107 | label: tr(locale, MessageId::ExtensionsActionDiagnose).into_owned(), |
| 1108 | command: "/plugin validate".into(), |
| 1109 | disposition: RowActionDisposition::InPlacePager, |
| 1110 | }), |
| 1111 | toggle: None, |
| 1112 | remove: None, |
| 1113 | }) |
| 1114 | .collect::<Vec<_>>(); |
| 1115 | if !problems.is_empty() { |
| 1116 | groups.push(ExtensionGroup { |
| 1117 | id: "problems".into(), |
| 1118 | label: tr(locale, MessageId::ExtensionsGroupProblems).into_owned(), |
| 1119 | items: problems, |
| 1120 | }); |
| 1121 | } |
| 1122 | ExtensionsTabModel { |
| 1123 | groups, |
| 1124 | problem: app.plugin_registry.state_error().map(ToString::to_string), |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | fn marketplace_model(app: &App, locale: Locale) -> ExtensionsTabModel { |
| 1129 | use codewhale_plugins::marketplace::document::{ |
| 1130 | CatalogInstallResolution, resolve_candidate_install, |
| 1131 | }; |
| 1132 | let Some(store) = codewhale_plugins::marketplace::store::MarketplaceStore::open( |
| 1133 | app.plugin_registry.state_path(), |
| 1134 | ) else { |
| 1135 | return ExtensionsTabModel { |
| 1136 | groups: Vec::new(), |
| 1137 | problem: Some(tr(locale, MessageId::ExtensionsMarketplaceUnavailable).into_owned()), |
| 1138 | }; |
| 1139 | }; |
| 1140 | let state = match store.load() { |
| 1141 | Ok(state) => state, |
| 1142 | Err(error) => { |
| 1143 | return ExtensionsTabModel { |
| 1144 | groups: Vec::new(), |
| 1145 | problem: Some(error), |
| 1146 | }; |
| 1147 | } |
| 1148 | }; |
| 1149 | let groups = state |
| 1150 | .catalogs() |
| 1151 | .values() |
| 1152 | .map(|stored| { |
| 1153 | let catalog = &stored.catalog; |
| 1154 | ExtensionGroup { |
| 1155 | id: catalog.id.as_str().to_string(), |
| 1156 | label: catalog |
| 1157 | .display_name |
| 1158 | .clone() |
| 1159 | .unwrap_or_else(|| catalog.name.clone()), |
| 1160 | items: catalog |
| 1161 | .candidates |
| 1162 | .iter() |
| 1163 | .map(|candidate| { |
| 1164 | let resolution = |
| 1165 | resolve_candidate_install(stored, candidate, &app.plugin_registry); |
| 1166 | if let CatalogInstallResolution::AlreadyPresent { plugin, .. } = &resolution |
| 1167 | { |
| 1168 | // A catalog name match is only occupancy. Show and |
| 1169 | // review the actual local bundle, not catalog claims. |
| 1170 | return ExtensionItem { |
| 1171 | id: candidate.id.as_str().to_string(), |
| 1172 | tone: plugin_row_tone(plugin), |
| 1173 | label: escape_review_text(plugin.name(), ReviewTextContext::Plain), |
| 1174 | description: plugin |
| 1175 | .manifest |
| 1176 | .plugin |
| 1177 | .description |
| 1178 | .as_deref() |
| 1179 | .map(|description| { |
| 1180 | escape_review_text(description, ReviewTextContext::Plain) |
| 1181 | }) |
| 1182 | .unwrap_or_default(), |
| 1183 | state: if plugin.scope |
| 1184 | == codewhale_plugins::types::PluginScope::Builtin |
| 1185 | { |
| 1186 | tr(locale, MessageId::ExtensionsStateFirstParty).into_owned() |
| 1187 | } else { |
| 1188 | plugin_row_state(locale, plugin) |
| 1189 | }, |
| 1190 | detail: { |
| 1191 | let path = escape_review_text( |
| 1192 | &plugin.canonical_root.display().to_string(), |
| 1193 | ReviewTextContext::Plain, |
| 1194 | ); |
| 1195 | let extra = plugin_attribution_parts(locale, plugin); |
| 1196 | let base = if !plugin.trusted() { |
| 1197 | format!( |
| 1198 | "Staged (disabled until trusted) · Enter runs /plugin trust {} to confirm content hash · {path}", |
| 1199 | plugin.name() |
| 1200 | ) |
| 1201 | } else { |
| 1202 | path |
| 1203 | }; |
| 1204 | if extra.is_empty() { |
| 1205 | base |
| 1206 | } else { |
| 1207 | format!("{base} · {}", extra.join(" · ")) |
| 1208 | } |
| 1209 | }, |
| 1210 | action: Some(plugin_row_action(locale, plugin)), |
| 1211 | toggle: None, |
| 1212 | remove: None, |
| 1213 | }; |
| 1214 | } |
| 1215 | let installable = |
| 1216 | matches!(resolution, CatalogInstallResolution::Supported { .. }); |
| 1217 | ExtensionItem { |
| 1218 | id: candidate.id.as_str().to_string(), |
| 1219 | tone: ExtensionTone::Attention, |
| 1220 | label: candidate |
| 1221 | .display_name |
| 1222 | .clone() |
| 1223 | .unwrap_or_else(|| candidate.name.clone()), |
| 1224 | description: candidate.description.clone().unwrap_or_default(), |
| 1225 | state: if candidate.has_errors() { |
| 1226 | tr(locale, MessageId::ExtensionsStateInvalid) |
| 1227 | } else if installable { |
| 1228 | tr(locale, MessageId::ExtensionsStateAvailable) |
| 1229 | } else { |
| 1230 | tr(locale, MessageId::AutomationActionInspect) |
| 1231 | } |
| 1232 | .into_owned(), |
| 1233 | detail: { |
| 1234 | let unknown = tr(locale, MessageId::CmdCostUnknownValue); |
| 1235 | let base = localize( |
| 1236 | locale, |
| 1237 | MessageId::ExtensionsMarketplaceDetail, |
| 1238 | &[ |
| 1239 | ( |
| 1240 | "publisher", |
| 1241 | candidate |
| 1242 | .provenance |
| 1243 | .publisher |
| 1244 | .as_deref() |
| 1245 | .unwrap_or(unknown.as_ref()), |
| 1246 | ), |
| 1247 | ( |
| 1248 | "tier", |
| 1249 | &localized_tier( |
| 1250 | locale, |
| 1251 | candidate.provenance.tier.as_str(), |
| 1252 | ), |
| 1253 | ), |
| 1254 | ("installable", &localized_bool(locale, installable)), |
| 1255 | ], |
| 1256 | ); |
| 1257 | if installable { |
| 1258 | format!( |
| 1259 | "{base} · Enter stages disabled; confirm content hash with /plugin trust {}", |
| 1260 | candidate.name |
| 1261 | ) |
| 1262 | } else { |
| 1263 | base |
| 1264 | } |
| 1265 | }, |
| 1266 | action: if installable { |
| 1267 | Some(ExtensionAction::Command { |
| 1268 | label: tr(locale, MessageId::ExtensionsActionAdd).into_owned(), |
| 1269 | command: format!( |
| 1270 | "/plugin marketplace install {} {}", |
| 1271 | catalog.id.as_str(), |
| 1272 | candidate.name |
| 1273 | ), |
| 1274 | disposition: RowActionDisposition::InPlace, |
| 1275 | }) |
| 1276 | } else { |
| 1277 | Some(ExtensionAction::Status { |
| 1278 | label: tr(locale, MessageId::PickerActionUnavailable) |
| 1279 | .into_owned(), |
| 1280 | }) |
| 1281 | }, |
| 1282 | toggle: None, |
| 1283 | remove: None, |
| 1284 | } |
| 1285 | }) |
| 1286 | .collect(), |
| 1287 | } |
| 1288 | }) |
| 1289 | .collect(); |
| 1290 | ExtensionsTabModel { |
| 1291 | groups, |
| 1292 | problem: None, |
| 1293 | } |
| 1294 | } |
| 1295 | |
| 1296 | fn skills_model(app: &App, locale: Locale) -> ExtensionsTabModel { |
| 1297 | use codewhale_skills::audit::{ParserState, SkillAuditMode, scan_with_configured}; |
| 1298 | |
| 1299 | let home = codewhale_paths::user_home(); |
| 1300 | let audit = scan_with_configured( |
| 1301 | &app.workspace, |
| 1302 | home.as_deref(), |
| 1303 | Some(&app.skills_dir), |
| 1304 | SkillAuditMode::OwnedOnly, |
| 1305 | None, |
| 1306 | ); |
| 1307 | let mut groups = Vec::<ExtensionGroup>::new(); |
| 1308 | for skill in audit.skills { |
| 1309 | let group_id = format!("{:?}", skill.root.kind); |
| 1310 | let position = groups.iter().position(|group| group.id == group_id); |
| 1311 | let item = ExtensionItem { |
| 1312 | id: format!("{}:{}", group_id, skill.id.canonical_name), |
| 1313 | tone: ExtensionTone::Ready, |
| 1314 | label: skill.name, |
| 1315 | description: skill.description.unwrap_or_default(), |
| 1316 | state: match skill.parser { |
| 1317 | ParserState::Valid => tr(locale, MessageId::HotbarSetupStatusReady), |
| 1318 | ParserState::Warning(_) => tr(locale, MessageId::ExtensionsStateWarning), |
| 1319 | ParserState::Broken(_) | ParserState::Oversized => { |
| 1320 | tr(locale, MessageId::ExtensionsStateInvalid) |
| 1321 | } |
| 1322 | } |
| 1323 | .into_owned(), |
| 1324 | detail: skill.safe_display_path, |
| 1325 | // Enter opens the skills manager, which is where install, update, |
| 1326 | // remove and trust already live (`views/skills_manager.rs`, 1,000 |
| 1327 | // lines, driving `codewhale_skills::mutation::SkillMutationRequest`). This |
| 1328 | // tab used to dead-end on `action: None` — founder live-test: |
| 1329 | // "skills - no way to delete them or edit or anything either" — |
| 1330 | // even though the manager it needed was one command away. Routing |
| 1331 | // rather than reimplementing: the mutation authority stays in one |
| 1332 | // place. |
| 1333 | action: Some(ExtensionAction::Command { |
| 1334 | label: tr(locale, MessageId::ExtensionsActionManage).into_owned(), |
| 1335 | command: "/skills manage".into(), |
| 1336 | disposition: RowActionDisposition::LeavePanel, |
| 1337 | }), |
| 1338 | toggle: None, |
| 1339 | remove: None, |
| 1340 | }; |
| 1341 | if let Some(position) = position { |
| 1342 | groups[position].items.push(item); |
| 1343 | } else { |
| 1344 | groups.push(ExtensionGroup { |
| 1345 | id: group_id.clone(), |
| 1346 | label: localized_skill_root(locale, skill.root.kind), |
| 1347 | items: vec![item], |
| 1348 | }); |
| 1349 | } |
| 1350 | } |
| 1351 | ExtensionsTabModel { |
| 1352 | groups, |
| 1353 | problem: None, |
| 1354 | } |
| 1355 | } |
| 1356 | |
| 1357 | /// Whether a listed MCP row belongs to the user's own config, and may |
| 1358 | /// therefore be removed or toggled from the Extensions panel. |
| 1359 | /// |
| 1360 | /// `owned` is the set of servers in the user's config without plugin |
| 1361 | /// contributions; `None` means that config could not be read, in which case |
| 1362 | /// ownership is unknown and the gestures are kept rather than silently |
| 1363 | /// withdrawn. Plugin-contributed servers are never in that set: their names are |
| 1364 | /// synthesized and `/mcp remove` resolves against the config file, so offering |
| 1365 | /// the gesture produced a guaranteed "server not found". |
| 1366 | fn mcp_row_is_mutable(owned: Option<&BTreeSet<String>>, name: &str) -> bool { |
| 1367 | owned.is_none_or(|owned| owned.contains(name)) |
| 1368 | } |
| 1369 | |
| 1370 | fn mcp_model(app: &App, locale: Locale) -> ExtensionsTabModel { |
| 1371 | let configured = codewhale_engine::mcp::load_config_with_workspace_and_plugins( |
| 1372 | &app.mcp_config_path, |
| 1373 | &app.workspace, |
| 1374 | app.plugin_registry.as_ref(), |
| 1375 | ) |
| 1376 | .ok(); |
| 1377 | // The rows above are the union of the user's config and every plugin's |
| 1378 | // contribution. Only the user's own servers can be removed or toggled: a |
| 1379 | // plugin server's name is synthesized (`plugin-{len}-{plugin}-{server}`) |
| 1380 | // and never appears in the config file `/mcp remove` resolves against, so |
| 1381 | // offering the gesture there was a guaranteed 404. Derive the set by |
| 1382 | // loading the same config without plugin contributions and taking the |
| 1383 | // difference, rather than parsing the shape of the synthesized name. |
| 1384 | let user_owned: Option<BTreeSet<String>> = |
| 1385 | codewhale_engine::mcp::load_config_with_workspace(&app.mcp_config_path, &app.workspace) |
| 1386 | .ok() |
| 1387 | .map(|config| config.servers.keys().cloned().collect()); |
| 1388 | // Where each row lives. A person asked to "say if they should be global |
| 1389 | // or in a certain project"; the panel could not answer because nothing |
| 1390 | // on the row carried its origin. Resolved once here, not per row. |
| 1391 | let project_owned = |
| 1392 | codewhale_engine::mcp::project_server_names(&app.mcp_config_path, &app.workspace); |
| 1393 | let snapshot = app.mcp_snapshot.as_ref(); |
| 1394 | // Configured names are the count authority used by the surrounding shell. |
| 1395 | // Snapshot data enriches those exact rows; it must never independently |
| 1396 | // filter the list down to only the last discovered subset. |
| 1397 | let names = configured.as_ref().map_or_else( |
| 1398 | || { |
| 1399 | snapshot |
| 1400 | .into_iter() |
| 1401 | .flat_map(|snapshot| snapshot.servers.iter().map(|server| server.name.clone())) |
| 1402 | .collect::<BTreeSet<_>>() |
| 1403 | }, |
| 1404 | |config| config.servers.keys().cloned().collect::<BTreeSet<_>>(), |
| 1405 | ); |
| 1406 | let total = names.len(); |
| 1407 | let items: Vec<_> = names |
| 1408 | .into_iter() |
| 1409 | .map(|name| { |
| 1410 | let observed = snapshot |
| 1411 | .and_then(|snapshot| snapshot.servers.iter().find(|server| server.name == name)); |
| 1412 | let config = configured |
| 1413 | .as_ref() |
| 1414 | .and_then(|configured| configured.servers.get(&name)); |
| 1415 | // The config file just read is the authority for on/off. The |
| 1416 | // snapshot is the live pool as of its last event, and a server |
| 1417 | // switched off (or on) since then used to keep its stale live row |
| 1418 | // — a disabled server offered "reconnect" instead of "enable". |
| 1419 | // When the two disagree, the observation belongs to a config the |
| 1420 | // user already changed, so it is not shown as this row's state. |
| 1421 | let config_enabled = config.map(codewhale_mcp::config::McpServerConfig::is_enabled); |
| 1422 | let stale = observed |
| 1423 | .zip(config_enabled) |
| 1424 | .is_some_and(|(server, enabled)| server.enabled != enabled); |
| 1425 | let observed = observed.filter(|_| !stale); |
| 1426 | let enabled = config_enabled |
| 1427 | .or_else(|| observed.map(|server| server.enabled)) |
| 1428 | .unwrap_or(true); |
| 1429 | // A `/mcp retry` the person already asked for: connecting now, or |
| 1430 | // queued behind the running turn. |
| 1431 | let retry = enabled |
| 1432 | .then(|| { |
| 1433 | app.mcp_retries |
| 1434 | .iter() |
| 1435 | .find(|pending| pending.server == name) |
| 1436 | }) |
| 1437 | .flatten(); |
| 1438 | // `connecting` is the engine's real in-flight set (#6033): under |
| 1439 | // lazy boot a configured-but-unstarted server reads "not connected", |
| 1440 | // never "connecting". |
| 1441 | let initializing = retry.is_some() |
| 1442 | || (enabled |
| 1443 | && app |
| 1444 | .mcp_connecting |
| 1445 | .iter() |
| 1446 | .any(|connecting| connecting == &name) |
| 1447 | && observed.is_none_or(|server| !server.connected && server.error.is_none())); |
| 1448 | let state = if !enabled { |
| 1449 | tr(locale, MessageId::HotbarSetupStatusDisabled) |
| 1450 | } else if retry.is_some_and(|pending| pending.queued) { |
| 1451 | tr(locale, MessageId::AutomationRunStatusQueued) |
| 1452 | } else if initializing { |
| 1453 | Cow::Borrowed("connecting") |
| 1454 | } else if observed.is_some_and(|server| server.connected) { |
| 1455 | tr(locale, MessageId::ExtensionsStateConnected) |
| 1456 | } else if observed.is_some_and(|server| server.auth_required) { |
| 1457 | Cow::Owned(crate::tui::session_boot::mcp_auth_required_state_label( |
| 1458 | locale, |
| 1459 | )) |
| 1460 | } else if observed.is_some_and(|server| server.error.is_some()) { |
| 1461 | tr(locale, MessageId::ExtensionsStateError) |
| 1462 | } else if stale { |
| 1463 | // Switched on in the file, still off in the live pool. |
| 1464 | tr(locale, MessageId::McpStateDisconnected) |
| 1465 | } else if observed.is_none() { |
| 1466 | tr(locale, MessageId::ExtensionsStateNotInspected) |
| 1467 | } else if observed.is_some_and(|server| !server.started()) { |
| 1468 | // Nothing in this session has needed it yet. "Not started" |
| 1469 | // read as a failure to someone whose `codewhale mcp tools` |
| 1470 | // had just listed its tools from the shell, which is a |
| 1471 | // separate process with its own connection. |
| 1472 | tr(locale, MessageId::McpStateDisconnected) |
| 1473 | } else { |
| 1474 | tr(locale, MessageId::ExtensionsStateDisconnected) |
| 1475 | } |
| 1476 | .into_owned(); |
| 1477 | let not_started = enabled |
| 1478 | && !initializing |
| 1479 | && (stale || observed.is_none_or(|server| !server.started())); |
| 1480 | // The live pool knows this server and has simply not needed it: |
| 1481 | // it has no tool counts to show, only what happens next. |
| 1482 | let waiting_for_first_use = enabled |
| 1483 | && !initializing |
| 1484 | && !stale |
| 1485 | && observed.is_some_and(|server| !server.started()); |
| 1486 | let oauth_capable = config.is_some_and(codewhale_engine::mcp::mcp_server_oauth_capable); |
| 1487 | let recovery = match observed { |
| 1488 | Some(server) => server.recovery_kind(oauth_capable), |
| 1489 | None => codewhale_engine::mcp::mcp_recovery_kind( |
| 1490 | enabled, |
| 1491 | false, |
| 1492 | false, |
| 1493 | None, |
| 1494 | oauth_capable, |
| 1495 | ), |
| 1496 | }; |
| 1497 | let action = match (initializing, recovery) { |
| 1498 | // Still connecting: the state is the whole story. |
| 1499 | (true, _) => ExtensionAction::Status { |
| 1500 | label: state.clone(), |
| 1501 | }, |
| 1502 | // The live pool still holds the pre-edit config, and a |
| 1503 | // single-server retry deliberately never re-reads it; only a |
| 1504 | // reload brings the newly enabled server into the pool. |
| 1505 | (false, Some(_)) if stale && enabled => ExtensionAction::Command { |
| 1506 | label: tr(locale, MessageId::ExtensionsActionConnect).into_owned(), |
| 1507 | command: "/mcp reload".into(), |
| 1508 | disposition: RowActionDisposition::InPlace, |
| 1509 | }, |
| 1510 | // Healthy. A row that needs nothing offers nothing — the |
| 1511 | // actionable rows are the ones worth finding in a list of 20. |
| 1512 | (false, None) => ExtensionAction::Status { |
| 1513 | label: state.clone(), |
| 1514 | }, |
| 1515 | (false, Some(recovery)) |
| 1516 | if codewhale_engine::mcp::mcp_name_is_command_safe(&name) |
| 1517 | || matches!( |
| 1518 | recovery, |
| 1519 | codewhale_engine::mcp::McpRecoveryKind::Connect |
| 1520 | | codewhale_engine::mcp::McpRecoveryKind::Reconnect |
| 1521 | | codewhale_engine::mcp::McpRecoveryKind::Diagnose |
| 1522 | | codewhale_engine::mcp::McpRecoveryKind::AwsLogin |
| 1523 | ) => |
| 1524 | { |
| 1525 | ExtensionAction::Command { |
| 1526 | label: tr(locale, recovery.label_key()).into_owned(), |
| 1527 | command: recovery.slash_command(&name), |
| 1528 | // Re-auth hands off to the OAuth login flow; every |
| 1529 | // other recovery runs against live state the panel |
| 1530 | // re-reads when it lands. |
| 1531 | disposition: match recovery { |
| 1532 | codewhale_engine::mcp::McpRecoveryKind::Reauth => { |
| 1533 | RowActionDisposition::LeavePanel |
| 1534 | } |
| 1535 | _ => RowActionDisposition::InPlace, |
| 1536 | }, |
| 1537 | } |
| 1538 | } |
| 1539 | (false, Some(_)) => ExtensionAction::Command { |
| 1540 | label: tr(locale, MessageId::ExtensionsActionDiagnose).into_owned(), |
| 1541 | command: "/mcp validate".into(), |
| 1542 | disposition: RowActionDisposition::InPlace, |
| 1543 | }, |
| 1544 | }; |
| 1545 | let scope = config |
| 1546 | .and_then(|server| server.reviewed_plugin_source()) |
| 1547 | .map(|source| { |
| 1548 | localize( |
| 1549 | locale, |
| 1550 | MessageId::ExtensionsScopePlugin, |
| 1551 | &[("plugin", source.plugin_name())], |
| 1552 | ) |
| 1553 | }) |
| 1554 | .unwrap_or_else(|| { |
| 1555 | tr( |
| 1556 | locale, |
| 1557 | if project_owned.contains(&name) { |
| 1558 | MessageId::ExtensionsScopeProject |
| 1559 | } else { |
| 1560 | MessageId::ExtensionsScopeGlobal |
| 1561 | }, |
| 1562 | ) |
| 1563 | .into_owned() |
| 1564 | }); |
| 1565 | let command_safe = codewhale_engine::mcp::mcp_name_is_command_safe(&name); |
| 1566 | let mutable = command_safe && mcp_row_is_mutable(user_owned.as_ref(), &name); |
| 1567 | let toggle = mutable.then(|| { |
| 1568 | if enabled { |
| 1569 | ExtensionAction::Command { |
| 1570 | label: tr(locale, MessageId::ExtensionsActionDisable).into_owned(), |
| 1571 | command: format!("/mcp disable {name}"), |
| 1572 | disposition: RowActionDisposition::InPlace, |
| 1573 | } |
| 1574 | } else { |
| 1575 | ExtensionAction::Command { |
| 1576 | label: tr(locale, MessageId::ExtensionsActionEnable).into_owned(), |
| 1577 | command: format!("/mcp enable {name}"), |
| 1578 | disposition: RowActionDisposition::InPlace, |
| 1579 | } |
| 1580 | } |
| 1581 | }); |
| 1582 | let remove = mutable.then(|| ExtensionAction::Command { |
| 1583 | label: tr(locale, MessageId::ExtensionsActionRemove).into_owned(), |
| 1584 | command: format!("/mcp remove {name}"), |
| 1585 | disposition: RowActionDisposition::InPlace, |
| 1586 | }); |
| 1587 | ExtensionItem { |
| 1588 | id: name.clone(), |
| 1589 | tone: match (enabled, initializing, recovery) { |
| 1590 | (false, ..) => ExtensionTone::Idle, |
| 1591 | // Lazy boot left it for later: nothing is wrong with it. |
| 1592 | _ if not_started => ExtensionTone::Idle, |
| 1593 | (true, true, _) => ExtensionTone::Attention, |
| 1594 | (true, false, None) => ExtensionTone::Ready, |
| 1595 | // A server that reports an error is broken; one that only |
| 1596 | // wants a login or a reconnect is waiting on a person. |
| 1597 | (true, false, Some(codewhale_engine::mcp::McpRecoveryKind::Diagnose)) => { |
| 1598 | ExtensionTone::Failure |
| 1599 | } |
| 1600 | (true, false, Some(_)) => ExtensionTone::Attention, |
| 1601 | }, |
| 1602 | // A plugin's server is shown as `plugin/server`, not as the |
| 1603 | // wire key `plugin-25-<plugin>-<server>`. The length-prefixed |
| 1604 | // form is how the config layer keeps the name unambiguous; it |
| 1605 | // was never meant to be read by a person. |
| 1606 | label: codewhale_engine::mcp::split_qualified_plugin_server_name(&name) |
| 1607 | .map_or_else( |
| 1608 | || name.clone(), |
| 1609 | |(plugin, server)| format!("{plugin}/{server}"), |
| 1610 | ), |
| 1611 | description: observed.map_or_else(String::new, |server| { |
| 1612 | if waiting_for_first_use { |
| 1613 | return server.transport.clone(); |
| 1614 | } |
| 1615 | localize( |
| 1616 | locale, |
| 1617 | MessageId::ExtensionsMcpSummary, |
| 1618 | &[ |
| 1619 | ("transport", &server.transport), |
| 1620 | ("tools", &server.tools.len().to_string()), |
| 1621 | ("resources", &server.resources.len().to_string()), |
| 1622 | ], |
| 1623 | ) |
| 1624 | }), |
| 1625 | state, |
| 1626 | // The passive snapshot can carry a command line or URL. Do |
| 1627 | // not mirror either into this broad inventory surface. |
| 1628 | detail: format!( |
| 1629 | "{scope} · {}", |
| 1630 | observed.map_or_else( |
| 1631 | || tr(locale, MessageId::ExtensionsMcpNotInspected).into_owned(), |
| 1632 | |server| { |
| 1633 | if waiting_for_first_use { |
| 1634 | return tr(locale, MessageId::ExtensionsMcpNotConnectedYet) |
| 1635 | .into_owned(); |
| 1636 | } |
| 1637 | server.error.clone().unwrap_or_else(|| { |
| 1638 | localize( |
| 1639 | locale, |
| 1640 | MessageId::ExtensionsMcpDetail, |
| 1641 | &[ |
| 1642 | ("tools", &server.tools.len().to_string()), |
| 1643 | ("resources", &server.resources.len().to_string()), |
| 1644 | ("prompts", &server.prompts.len().to_string()), |
| 1645 | ], |
| 1646 | ) |
| 1647 | }) |
| 1648 | }, |
| 1649 | ) |
| 1650 | ), |
| 1651 | action: Some(action), |
| 1652 | toggle, |
| 1653 | remove, |
| 1654 | } |
| 1655 | }) |
| 1656 | .collect(); |
| 1657 | let groups = if items.is_empty() && configured.is_some() { |
| 1658 | vec![ExtensionGroup { |
| 1659 | id: "mcp-start".into(), |
| 1660 | label: tr(locale, MessageId::ExtensionsMcpEmpty).into_owned(), |
| 1661 | items: vec![ExtensionItem { |
| 1662 | id: "mcp-suggestions".into(), |
| 1663 | tone: ExtensionTone::Idle, |
| 1664 | label: tr(locale, MessageId::ExtensionsMcpBrowse).into_owned(), |
| 1665 | description: tr(locale, MessageId::McpRecommendationsHeading).into_owned(), |
| 1666 | state: tr(locale, MessageId::ExtensionsStateAvailable).into_owned(), |
| 1667 | detail: localize( |
| 1668 | locale, |
| 1669 | MessageId::McpRecommendationsSafety, |
| 1670 | &[("restart_command", "/mcp restart")], |
| 1671 | ), |
| 1672 | action: Some(ExtensionAction::Command { |
| 1673 | label: tr(locale, MessageId::AutomationActionInspect).into_owned(), |
| 1674 | command: "/mcp recommendations".into(), |
| 1675 | disposition: RowActionDisposition::InPlacePager, |
| 1676 | }), |
| 1677 | toggle: None, |
| 1678 | remove: None, |
| 1679 | }], |
| 1680 | }] |
| 1681 | } else { |
| 1682 | mcp_groups(locale, items) |
| 1683 | }; |
| 1684 | ExtensionsTabModel { |
| 1685 | groups, |
| 1686 | problem: (configured.is_none() && app.mcp_configured_count > total).then(|| { |
| 1687 | localize( |
| 1688 | locale, |
| 1689 | MessageId::ExtensionsMcpRefresh, |
| 1690 | &[("count", &app.mcp_configured_count.to_string())], |
| 1691 | ) |
| 1692 | }), |
| 1693 | } |
| 1694 | } |
| 1695 | |
| 1696 | /// Group id of the `/mcp` rows whose one action is a login. |
| 1697 | const MCP_LOGIN_GROUP_ID: &str = "login"; |
| 1698 | |
| 1699 | /// Whether a row's one action is the login flow. |
| 1700 | fn mcp_item_needs_login(item: &ExtensionItem) -> bool { |
| 1701 | item.action |
| 1702 | .as_ref() |
| 1703 | .and_then(ExtensionAction::command) |
| 1704 | .is_some_and(|command| command.starts_with("/mcp login ")) |
| 1705 | } |
| 1706 | |
| 1707 | /// Order the `/mcp` rows by what a person has to do about them. Everything |
| 1708 | /// that needs a human leads: with twenty servers configured, the four that |
| 1709 | /// failed or want re-auth were impossible to pick out of a flat alphabetical |
| 1710 | /// list — founder live-test on the same screen. Within that, the servers |
| 1711 | /// that only need a login come first, as their own group, because "failed" |
| 1712 | /// is the wrong word for an expired login and the fix is one key (#5926): |
| 1713 | /// Enter on the row runs `/mcp login <server>`. Real failures follow with |
| 1714 | /// their reason in the detail line; a healthy server renders its state and |
| 1715 | /// sorts below. |
| 1716 | fn mcp_groups(locale: Locale, items: Vec<ExtensionItem>) -> Vec<ExtensionGroup> { |
| 1717 | let (login, rest): (Vec<_>, Vec<_>) = items.into_iter().partition(mcp_item_needs_login); |
| 1718 | // "Needs attention" is for rows that are broken or waiting on a person. |
| 1719 | // A switched-off server or one lazy boot has not started yet keeps its |
| 1720 | // `enable` / `connect` action but sorts with the rest: listing eight |
| 1721 | // servers as needing attention when six were simply idle buried the two |
| 1722 | // that were actually failing. |
| 1723 | let (attention, healthy): (Vec<_>, Vec<_>) = rest.into_iter().partition(|item| { |
| 1724 | matches!(item.tone, ExtensionTone::Attention | ExtensionTone::Failure) |
| 1725 | && item.action.as_ref().is_some_and(|a| a.command().is_some()) |
| 1726 | }); |
| 1727 | [ |
| 1728 | ( |
| 1729 | MCP_LOGIN_GROUP_ID, |
| 1730 | MessageId::ExtensionsGroupNeedsLogin, |
| 1731 | login, |
| 1732 | ), |
| 1733 | ( |
| 1734 | "attention", |
| 1735 | MessageId::ExtensionsGroupNeedsAttention, |
| 1736 | attention, |
| 1737 | ), |
| 1738 | ("servers", MessageId::ExtensionsGroupServers, healthy), |
| 1739 | ] |
| 1740 | .into_iter() |
| 1741 | .filter(|(_, _, items)| !items.is_empty()) |
| 1742 | .map(|(id, label, items)| ExtensionGroup { |
| 1743 | id: id.into(), |
| 1744 | label: tr(locale, label).into_owned(), |
| 1745 | items, |
| 1746 | }) |
| 1747 | .collect() |
| 1748 | } |
| 1749 | |
| 1750 | fn commands_model(app: &App, locale: Locale) -> ExtensionsTabModel { |
| 1751 | crate::commands::user_registry::with_registry_for_app(app, |registry| { |
| 1752 | let mut user = Vec::new(); |
| 1753 | let mut workspace = Vec::new(); |
| 1754 | let mut entries: Vec<_> = registry |
| 1755 | .iter() |
| 1756 | .filter(|metadata| { |
| 1757 | metadata.plugin_authority.is_none() |
| 1758 | && metadata.extension.is_none() |
| 1759 | && !metadata.hidden |
| 1760 | }) |
| 1761 | .collect(); |
| 1762 | entries.sort_by(|a, b| a.name.cmp(&b.name)); |
| 1763 | for metadata in entries { |
| 1764 | let error = registry.dispatch_error(&metadata.name); |
| 1765 | let scope = tr( |
| 1766 | locale, |
| 1767 | if metadata.workspace_sourced { |
| 1768 | MessageId::ExtensionsScopeProject |
| 1769 | } else { |
| 1770 | MessageId::ExtensionsScopeGlobal |
| 1771 | }, |
| 1772 | ); |
| 1773 | let mut detail_parts = vec![scope.into_owned()]; |
| 1774 | if let Some(usage) = metadata.display_usage() { |
| 1775 | detail_parts.push(usage.to_string()); |
| 1776 | } |
| 1777 | if !metadata.aliases.is_empty() { |
| 1778 | let aliases = metadata |
| 1779 | .aliases |
| 1780 | .iter() |
| 1781 | .map(|alias| format!("/{alias}")) |
| 1782 | .collect::<Vec<_>>() |
| 1783 | .join(", "); |
| 1784 | detail_parts.push(aliases); |
| 1785 | } |
| 1786 | if let Some(reason) = error.as_deref() { |
| 1787 | detail_parts.push(reason.to_string()); |
| 1788 | } |
| 1789 | let item = ExtensionItem { |
| 1790 | id: format!("command:{}", metadata.name), |
| 1791 | label: format!("/{}", metadata.name), |
| 1792 | description: metadata.description.clone().unwrap_or_default(), |
| 1793 | tone: if error.is_some() { |
| 1794 | ExtensionTone::Failure |
| 1795 | } else { |
| 1796 | ExtensionTone::Ready |
| 1797 | }, |
| 1798 | state: if error.is_some() { |
| 1799 | tr(locale, MessageId::ExtensionsStateInvalid) |
| 1800 | } else { |
| 1801 | tr(locale, MessageId::ExtensionsStateEnabled) |
| 1802 | } |
| 1803 | .into_owned(), |
| 1804 | detail: detail_parts.join(" · "), |
| 1805 | action: None, |
| 1806 | toggle: None, |
| 1807 | remove: None, |
| 1808 | }; |
| 1809 | if metadata.workspace_sourced { |
| 1810 | workspace.push(item); |
| 1811 | } else { |
| 1812 | user.push(item); |
| 1813 | } |
| 1814 | } |
| 1815 | let groups = [ |
| 1816 | ("user", MessageId::ExtensionsGroupUser, user), |
| 1817 | ("workspace", MessageId::ExtensionsGroupWorkspace, workspace), |
| 1818 | ] |
| 1819 | .into_iter() |
| 1820 | .filter(|(_, _, items)| !items.is_empty()) |
| 1821 | .map(|(id, label, items)| ExtensionGroup { |
| 1822 | id: id.into(), |
| 1823 | label: tr(locale, label).into_owned(), |
| 1824 | items, |
| 1825 | }) |
| 1826 | .collect(); |
| 1827 | ExtensionsTabModel { |
| 1828 | groups, |
| 1829 | problem: None, |
| 1830 | } |
| 1831 | }) |
| 1832 | } |
| 1833 | |
| 1834 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1835 | enum ExtensionsFocus { |
| 1836 | Tabs, |
| 1837 | Search, |
| 1838 | List, |
| 1839 | } |
| 1840 | |
| 1841 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1842 | enum VisibleEntry<'a> { |
| 1843 | Group(&'a ExtensionGroup), |
| 1844 | Item(&'a ExtensionGroup, &'a ExtensionItem), |
| 1845 | Problem(&'a str), |
| 1846 | Empty, |
| 1847 | } |
| 1848 | |
| 1849 | /// Stable identity of a visible row across snapshot refreshes. An item is |
| 1850 | /// keyed by its own id alone: a refresh may regroup it (MCP login-first). |
| 1851 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1852 | enum EntryKey { |
| 1853 | Group(String), |
| 1854 | Item(String), |
| 1855 | Problem, |
| 1856 | } |
| 1857 | |
| 1858 | impl EntryKey { |
| 1859 | fn of(entry: VisibleEntry<'_>) -> Option<Self> { |
| 1860 | match entry { |
| 1861 | VisibleEntry::Group(group) => Some(Self::Group(group.id.clone())), |
| 1862 | VisibleEntry::Item(_, item) => Some(Self::Item(item.id.clone())), |
| 1863 | VisibleEntry::Problem(_) => Some(Self::Problem), |
| 1864 | VisibleEntry::Empty => None, |
| 1865 | } |
| 1866 | } |
| 1867 | } |
| 1868 | |
| 1869 | #[derive(Default)] |
| 1870 | struct HitAreas { |
| 1871 | tabs: Vec<(Rect, ExtensionsTab)>, |
| 1872 | search: Option<Rect>, |
| 1873 | rows: Vec<(Rect, usize)>, |
| 1874 | } |
| 1875 | |
| 1876 | pub struct ExtensionsView { |
| 1877 | snapshot: ExtensionsSnapshot, |
| 1878 | locale: Locale, |
| 1879 | active_tab: ExtensionsTab, |
| 1880 | focus: ExtensionsFocus, |
| 1881 | query: String, |
| 1882 | selected: [usize; 6], |
| 1883 | scroll: [usize; 6], |
| 1884 | folded_groups: BTreeSet<String>, |
| 1885 | /// The live theme, captured at open so row ink resolves through the same |
| 1886 | /// grammar the rest of the chrome uses instead of raw palette constants. |
| 1887 | theme: codewhale_palette::UiTheme, |
| 1888 | hits: RefCell<HitAreas>, |
| 1889 | hovered_row: Option<usize>, |
| 1890 | hovered_tab: Option<ExtensionsTab>, |
| 1891 | /// Last time `tick` asked the host for a fresh snapshot. Bounds the poll |
| 1892 | /// so a per-frame tick cannot turn into a rebuild every frame. |
| 1893 | last_poll: std::time::Instant, |
| 1894 | /// Row id whose removal is armed. A second `d` / Delete on the same row |
| 1895 | /// confirms; any navigation or Esc disarms. |
| 1896 | pending_remove: Option<String>, |
| 1897 | } |
| 1898 | |
| 1899 | impl ExtensionsView { |
| 1900 | #[must_use] |
| 1901 | pub fn new(app: &App, tab: ExtensionsTab) -> Self { |
| 1902 | let mut view = |
| 1903 | Self::from_snapshot_with_locale(ExtensionsSnapshot::from_app(app), tab, app.ui_locale); |
| 1904 | view.theme = app.ui_theme; |
| 1905 | view |
| 1906 | } |
| 1907 | |
| 1908 | fn from_snapshot_with_locale( |
| 1909 | snapshot: ExtensionsSnapshot, |
| 1910 | tab: ExtensionsTab, |
| 1911 | locale: Locale, |
| 1912 | ) -> Self { |
| 1913 | let mut view = Self { |
| 1914 | snapshot, |
| 1915 | locale, |
| 1916 | active_tab: tab, |
| 1917 | focus: ExtensionsFocus::List, |
| 1918 | query: String::new(), |
| 1919 | selected: [0; 6], |
| 1920 | scroll: [0; 6], |
| 1921 | folded_groups: BTreeSet::new(), |
| 1922 | theme: codewhale_palette::UI_THEME, |
| 1923 | hits: RefCell::new(HitAreas::default()), |
| 1924 | hovered_row: None, |
| 1925 | hovered_tab: None, |
| 1926 | last_poll: std::time::Instant::now(), |
| 1927 | pending_remove: None, |
| 1928 | }; |
| 1929 | // Each tab lands on a real item, preserving login-first MCP sorting. |
| 1930 | // Group headings remain reachable for folding with Up. |
| 1931 | for initial_tab in ExtensionsTab::ALL { |
| 1932 | view.active_tab = initial_tab; |
| 1933 | if let Some(index) = view |
| 1934 | .visible_entries() |
| 1935 | .iter() |
| 1936 | .position(|entry| matches!(entry, VisibleEntry::Item(_, _))) |
| 1937 | { |
| 1938 | view.selected[initial_tab.index()] = index; |
| 1939 | } |
| 1940 | } |
| 1941 | view.active_tab = tab; |
| 1942 | view |
| 1943 | } |
| 1944 | |
| 1945 | fn fold_key(&self, group: &ExtensionGroup) -> String { |
| 1946 | format!("{}:{}", self.active_tab.index(), group.id) |
| 1947 | } |
| 1948 | |
| 1949 | fn group_matches(&self, group: &ExtensionGroup, query: &str) -> bool { |
| 1950 | group.label.to_lowercase().contains(query) |
| 1951 | || group.items.iter().any(|item| item_matches(item, query)) |
| 1952 | } |
| 1953 | |
| 1954 | fn visible_entries(&self) -> Vec<VisibleEntry<'_>> { |
| 1955 | let model = self.snapshot.tab(self.active_tab); |
| 1956 | let query = self.query.trim().to_lowercase(); |
| 1957 | let searching = !query.is_empty(); |
| 1958 | let mut entries = Vec::new(); |
| 1959 | if let Some(problem) = model.problem.as_deref() { |
| 1960 | entries.push(VisibleEntry::Problem(problem)); |
| 1961 | } |
| 1962 | for group in &model.groups { |
| 1963 | if searching && !self.group_matches(group, &query) { |
| 1964 | continue; |
| 1965 | } |
| 1966 | entries.push(VisibleEntry::Group(group)); |
| 1967 | let folded = !searching && self.folded_groups.contains(&self.fold_key(group)); |
| 1968 | if folded { |
| 1969 | continue; |
| 1970 | } |
| 1971 | let group_name_matches = searching && group.label.to_lowercase().contains(&query); |
| 1972 | entries.extend( |
| 1973 | group |
| 1974 | .items |
| 1975 | .iter() |
| 1976 | .filter(|item| !searching || group_name_matches || item_matches(item, &query)) |
| 1977 | .map(|item| VisibleEntry::Item(group, item)), |
| 1978 | ); |
| 1979 | } |
| 1980 | if entries.is_empty() { |
| 1981 | entries.push(VisibleEntry::Empty); |
| 1982 | } |
| 1983 | entries |
| 1984 | } |
| 1985 | |
| 1986 | fn clamp_selection(&mut self) { |
| 1987 | let len = self.visible_entries().len(); |
| 1988 | let index = self.active_tab.index(); |
| 1989 | self.selected[index] = self.selected[index].min(len.saturating_sub(1)); |
| 1990 | self.scroll[index] = self.scroll[index].min(self.selected[index]); |
| 1991 | } |
| 1992 | |
| 1993 | fn move_selection(&mut self, delta: isize) { |
| 1994 | self.pending_remove = None; |
| 1995 | let len = self.visible_entries().len(); |
| 1996 | if len == 0 { |
| 1997 | return; |
| 1998 | } |
| 1999 | let index = self.active_tab.index(); |
| 2000 | self.selected[index] = |
| 2001 | (self.selected[index] as isize + delta).rem_euclid(len as isize) as usize; |
| 2002 | } |
| 2003 | |
| 2004 | fn selected_item(&self) -> Option<&ExtensionItem> { |
| 2005 | let selected = self.selected[self.active_tab.index()]; |
| 2006 | match self.visible_entries().get(selected).copied() { |
| 2007 | Some(VisibleEntry::Item(_, item)) => Some(item), |
| 2008 | _ => None, |
| 2009 | } |
| 2010 | } |
| 2011 | |
| 2012 | #[cfg(test)] |
| 2013 | pub(crate) fn render_text_for_test(&self, width: u16, height: u16) -> String { |
| 2014 | let area = Rect::new(0, 0, width, height); |
| 2015 | let mut buf = Buffer::empty(area); |
| 2016 | self.render(area, &mut buf); |
| 2017 | let mut text = String::new(); |
| 2018 | for y in area.y..area.bottom() { |
| 2019 | for x in area.x..area.right() { |
| 2020 | text.push_str(buf[(x, y)].symbol()); |
| 2021 | } |
| 2022 | text.push('\n'); |
| 2023 | } |
| 2024 | text |
| 2025 | } |
| 2026 | |
| 2027 | /// `e`: run the row's reversible on/off command in place. |
| 2028 | fn toggle_selected(&mut self) -> ViewAction { |
| 2029 | self.pending_remove = None; |
| 2030 | match self.selected_item().and_then(|item| item.toggle.as_ref()) { |
| 2031 | Some(ExtensionAction::Command { command, .. }) => { |
| 2032 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 2033 | command: command.clone(), |
| 2034 | pager_title: None, |
| 2035 | }) |
| 2036 | } |
| 2037 | _ => ViewAction::None, |
| 2038 | } |
| 2039 | } |
| 2040 | |
| 2041 | /// `d` / Delete: arm removal on the first gesture, run the |
| 2042 | /// row's remove command on the second. Rows without a remove command |
| 2043 | /// ignore the gesture. |
| 2044 | fn remove_selected(&mut self) -> ViewAction { |
| 2045 | let Some((id, command)) = self.selected_item().and_then(|item| match &item.remove { |
| 2046 | Some(ExtensionAction::Command { command, .. }) => { |
| 2047 | Some((item.id.clone(), command.clone())) |
| 2048 | } |
| 2049 | _ => None, |
| 2050 | }) else { |
| 2051 | self.pending_remove = None; |
| 2052 | return ViewAction::None; |
| 2053 | }; |
| 2054 | if self.pending_remove.as_deref() == Some(id.as_str()) { |
| 2055 | self.pending_remove = None; |
| 2056 | return ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 2057 | command, |
| 2058 | pager_title: None, |
| 2059 | }); |
| 2060 | } |
| 2061 | self.pending_remove = Some(id); |
| 2062 | ViewAction::None |
| 2063 | } |
| 2064 | |
| 2065 | /// The selected row's context menu: its own action, details, its on/off |
| 2066 | /// switch and — last, behind an in-menu confirm — its removal. Only |
| 2067 | /// what the row actually offers is listed. |
| 2068 | fn row_menu(&self, column: u16, row: u16) -> Option<ViewEvent> { |
| 2069 | use crate::tui::context_menu::ContextMenuEntry; |
| 2070 | use crate::tui::views::{ContextMenuAction, ExtensionMenuVerb}; |
| 2071 | |
| 2072 | let item = self.selected_item()?; |
| 2073 | let entry = |label: String, verb: ExtensionMenuVerb| { |
| 2074 | ContextMenuEntry::new( |
| 2075 | label, |
| 2076 | String::new(), |
| 2077 | ContextMenuAction::Extension { |
| 2078 | item_id: item.id.clone(), |
| 2079 | verb, |
| 2080 | }, |
| 2081 | ) |
| 2082 | }; |
| 2083 | let details = tr(self.locale, MessageId::CtxMenuOpenDetails).into_owned(); |
| 2084 | let mut entries = Vec::new(); |
| 2085 | match &item.action { |
| 2086 | Some(ExtensionAction::Command { label, .. }) => { |
| 2087 | entries.push(entry(sentence_case(label), ExtensionMenuVerb::Activate).primary()); |
| 2088 | entries.push(entry(details, ExtensionMenuVerb::Details)); |
| 2089 | } |
| 2090 | _ => entries.push(entry(details, ExtensionMenuVerb::Details).primary()), |
| 2091 | } |
| 2092 | if let Some(ExtensionAction::Command { label, .. }) = &item.toggle { |
| 2093 | entries.push(entry(sentence_case(label), ExtensionMenuVerb::Toggle)); |
| 2094 | } |
| 2095 | if let Some(ExtensionAction::Command { label, .. }) = &item.remove { |
| 2096 | entries.push( |
| 2097 | entry( |
| 2098 | format!("{}…", sentence_case(label)), |
| 2099 | ExtensionMenuVerb::Remove, |
| 2100 | ) |
| 2101 | .confirm(tr(self.locale, MessageId::CtxMenuConfirmArmed)) |
| 2102 | .section_start(), |
| 2103 | ); |
| 2104 | } |
| 2105 | Some(ViewEvent::OpenContextMenu { |
| 2106 | title: item.label.clone(), |
| 2107 | entries, |
| 2108 | column, |
| 2109 | row, |
| 2110 | }) |
| 2111 | } |
| 2112 | |
| 2113 | /// Run a row-menu verb on the row with `item_id`. The menu closed before |
| 2114 | /// this runs and a poll may have rebuilt the list meanwhile, so the row |
| 2115 | /// is found again by id rather than by index. `None` when it is gone. |
| 2116 | pub(crate) fn run_menu_verb( |
| 2117 | &mut self, |
| 2118 | item_id: &str, |
| 2119 | verb: crate::tui::views::ExtensionMenuVerb, |
| 2120 | ) -> Option<ViewAction> { |
| 2121 | use crate::tui::views::ExtensionMenuVerb; |
| 2122 | |
| 2123 | let index = self |
| 2124 | .visible_entries() |
| 2125 | .iter() |
| 2126 | .position(|entry| matches!(entry, VisibleEntry::Item(_, item) if item.id == item_id))?; |
| 2127 | self.selected[self.active_tab.index()] = index; |
| 2128 | self.pending_remove = None; |
| 2129 | Some(match verb { |
| 2130 | ExtensionMenuVerb::Activate => self.activate_selected(), |
| 2131 | ExtensionMenuVerb::Toggle => self.toggle_selected(), |
| 2132 | ExtensionMenuVerb::Details => { |
| 2133 | let item = self.selected_item()?; |
| 2134 | ViewAction::Emit(ViewEvent::OpenTextPager { |
| 2135 | title: item.label.clone(), |
| 2136 | content: format!("{}\n\n{}\n\n{}", item.state, item.description, item.detail), |
| 2137 | }) |
| 2138 | } |
| 2139 | // Confirmed in the menu; the command's own result is the receipt. |
| 2140 | ExtensionMenuVerb::Remove => match &self.selected_item()?.remove { |
| 2141 | Some(ExtensionAction::Command { command, .. }) => { |
| 2142 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 2143 | command: command.clone(), |
| 2144 | pager_title: None, |
| 2145 | }) |
| 2146 | } |
| 2147 | _ => ViewAction::None, |
| 2148 | }, |
| 2149 | }) |
| 2150 | } |
| 2151 | |
| 2152 | fn activate_selected(&mut self) -> ViewAction { |
| 2153 | let selected = self.selected[self.active_tab.index()]; |
| 2154 | match self.visible_entries().get(selected).copied() { |
| 2155 | Some(VisibleEntry::Group(group)) => { |
| 2156 | let group = group.clone(); |
| 2157 | let key = self.fold_key(&group); |
| 2158 | if !self.folded_groups.remove(&key) { |
| 2159 | self.folded_groups.insert(key); |
| 2160 | } |
| 2161 | self.clamp_selection(); |
| 2162 | ViewAction::None |
| 2163 | } |
| 2164 | Some(VisibleEntry::Item(_, item)) => match item.action.as_ref() { |
| 2165 | Some(ExtensionAction::Command { |
| 2166 | command, |
| 2167 | disposition, |
| 2168 | .. |
| 2169 | }) => match disposition { |
| 2170 | RowActionDisposition::LeavePanel => { |
| 2171 | ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected { |
| 2172 | action: CommandPaletteAction::ExecuteCommand { |
| 2173 | command: command.clone(), |
| 2174 | }, |
| 2175 | }) |
| 2176 | } |
| 2177 | RowActionDisposition::InPlace => { |
| 2178 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 2179 | command: command.clone(), |
| 2180 | pager_title: None, |
| 2181 | }) |
| 2182 | } |
| 2183 | RowActionDisposition::InPlacePager => { |
| 2184 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 2185 | command: command.clone(), |
| 2186 | pager_title: Some(item.label.clone()), |
| 2187 | }) |
| 2188 | } |
| 2189 | }, |
| 2190 | _ => ViewAction::Emit(ViewEvent::OpenTextPager { |
| 2191 | title: item.label.clone(), |
| 2192 | content: format!("{}\n\n{}\n\n{}", item.state, item.description, item.detail), |
| 2193 | }), |
| 2194 | }, |
| 2195 | Some(VisibleEntry::Problem(problem)) => ViewAction::Emit(ViewEvent::OpenTextPager { |
| 2196 | title: self.active_tab.label(self.locale), |
| 2197 | content: problem.to_string(), |
| 2198 | }), |
| 2199 | _ => ViewAction::None, |
| 2200 | } |
| 2201 | } |
| 2202 | |
| 2203 | /// Swap in a fresh read model while keeping everything the user is doing: |
| 2204 | /// active tab, focus, search query, selection, scroll, and folded groups |
| 2205 | /// all survive. The selection follows its entity, not its row number: a |
| 2206 | /// refresh that reorders the list (a server logs in, a plugin is |
| 2207 | /// installed) keeps the same item selected, so a later `e`/`d` can never |
| 2208 | /// act on whatever row slid into the old index. It only moves when the |
| 2209 | /// selected entity is gone. |
| 2210 | pub fn refresh_snapshot(&mut self, snapshot: ExtensionsSnapshot) { |
| 2211 | let active = self.active_tab; |
| 2212 | let anchors = ExtensionsTab::ALL.map(|tab| { |
| 2213 | self.active_tab = tab; |
| 2214 | self.visible_entries() |
| 2215 | .get(self.selected[tab.index()]) |
| 2216 | .copied() |
| 2217 | .and_then(EntryKey::of) |
| 2218 | }); |
| 2219 | self.snapshot = snapshot; |
| 2220 | for (tab, anchor) in ExtensionsTab::ALL.into_iter().zip(anchors) { |
| 2221 | self.active_tab = tab; |
| 2222 | if let Some(index) = anchor.and_then(|anchor| { |
| 2223 | self.visible_entries() |
| 2224 | .iter() |
| 2225 | .position(|entry| EntryKey::of(*entry).as_ref() == Some(&anchor)) |
| 2226 | }) { |
| 2227 | self.selected[tab.index()] = index; |
| 2228 | } |
| 2229 | self.clamp_selection(); |
| 2230 | } |
| 2231 | self.active_tab = active; |
| 2232 | } |
| 2233 | |
| 2234 | fn set_tab(&mut self, tab: ExtensionsTab) { |
| 2235 | self.hovered_row = None; |
| 2236 | self.hovered_tab = None; |
| 2237 | self.pending_remove = None; |
| 2238 | self.active_tab = tab; |
| 2239 | self.clamp_selection(); |
| 2240 | } |
| 2241 | |
| 2242 | fn selected_status(&self) -> String { |
| 2243 | if let Some(item) = self.selected_item() |
| 2244 | && self.pending_remove.as_deref() == Some(item.id.as_str()) |
| 2245 | { |
| 2246 | return localize( |
| 2247 | self.locale, |
| 2248 | MessageId::ExtensionsRemoveArmed, |
| 2249 | &[("name", &item.label)], |
| 2250 | ); |
| 2251 | } |
| 2252 | let index = self.selected[self.active_tab.index()]; |
| 2253 | match self.visible_entries().get(index).copied() { |
| 2254 | Some(VisibleEntry::Group(group)) => localize( |
| 2255 | self.locale, |
| 2256 | MessageId::ExtensionsGroupStatus, |
| 2257 | &[("count", &group.items.len().to_string())], |
| 2258 | ), |
| 2259 | Some(VisibleEntry::Item(_, item)) => { |
| 2260 | let action = item |
| 2261 | .action |
| 2262 | .as_ref() |
| 2263 | .map(|action| format!(" · {}", action.label())) |
| 2264 | .unwrap_or_default(); |
| 2265 | format!("{} · {}{action} · {}", item.label, item.state, item.detail) |
| 2266 | } |
| 2267 | Some(VisibleEntry::Problem(problem)) => problem.to_string(), |
| 2268 | Some(VisibleEntry::Empty) | None => self.empty_message(), |
| 2269 | } |
| 2270 | } |
| 2271 | |
| 2272 | fn empty_message(&self) -> String { |
| 2273 | if self.query.is_empty() { |
| 2274 | tr(self.locale, MessageId::ExtensionsNoItems).into_owned() |
| 2275 | } else { |
| 2276 | localize( |
| 2277 | self.locale, |
| 2278 | MessageId::ExtensionsNoMatches, |
| 2279 | &[("query", &self.query)], |
| 2280 | ) |
| 2281 | } |
| 2282 | } |
| 2283 | } |
| 2284 | |
| 2285 | fn item_matches(item: &ExtensionItem, query: &str) -> bool { |
| 2286 | item.label.to_lowercase().contains(query) |
| 2287 | || item.description.to_lowercase().contains(query) |
| 2288 | || item.state.to_lowercase().contains(query) |
| 2289 | || item.detail.to_lowercase().contains(query) |
| 2290 | || item |
| 2291 | .action |
| 2292 | .as_ref() |
| 2293 | .is_some_and(|action| action.label().to_lowercase().contains(query)) |
| 2294 | } |
| 2295 | |
| 2296 | impl ModalView for ExtensionsView { |
| 2297 | fn kind(&self) -> ModalKind { |
| 2298 | ModalKind::Extensions |
| 2299 | } |
| 2300 | |
| 2301 | fn handle_paste(&mut self, text: &str) -> bool { |
| 2302 | if self.focus != ExtensionsFocus::Search { |
| 2303 | return false; |
| 2304 | } |
| 2305 | let sanitized = text |
| 2306 | .trim_end_matches(['\r', '\n']) |
| 2307 | .replace("\r\n", "\n") |
| 2308 | .replace(char::is_control, " "); |
| 2309 | if !sanitized.is_empty() { |
| 2310 | self.query.push_str(&sanitized); |
| 2311 | self.clamp_selection(); |
| 2312 | } |
| 2313 | true |
| 2314 | } |
| 2315 | |
| 2316 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 2317 | self.hovered_row = None; |
| 2318 | self.hovered_tab = None; |
| 2319 | // One navigation grammar (grokbuild, the stated authority): Tab and |
| 2320 | // Shift+Tab / BackTab move across the tab bar, always — even during |
| 2321 | // a search, which keeps its query on the new tab. `/` searches, Esc |
| 2322 | // backs out, ↑↓ move, Enter acts. Tab never cycles focus. |
| 2323 | if key.code == KeyCode::BackTab |
| 2324 | || (key.code == KeyCode::Tab && key.modifiers.contains(KeyModifiers::SHIFT)) |
| 2325 | { |
| 2326 | self.set_tab(self.active_tab.previous()); |
| 2327 | return ViewAction::None; |
| 2328 | } |
| 2329 | if key.code == KeyCode::Tab { |
| 2330 | self.set_tab(self.active_tab.next()); |
| 2331 | return ViewAction::None; |
| 2332 | } |
| 2333 | if self.focus == ExtensionsFocus::Search { |
| 2334 | match key.code { |
| 2335 | KeyCode::Esc => { |
| 2336 | if self.query.is_empty() { |
| 2337 | self.focus = ExtensionsFocus::List; |
| 2338 | } else { |
| 2339 | self.query.clear(); |
| 2340 | self.clamp_selection(); |
| 2341 | } |
| 2342 | } |
| 2343 | KeyCode::Backspace => { |
| 2344 | self.query.pop(); |
| 2345 | self.clamp_selection(); |
| 2346 | } |
| 2347 | KeyCode::Enter | KeyCode::Down => self.focus = ExtensionsFocus::List, |
| 2348 | KeyCode::Char(ch) |
| 2349 | if !key.modifiers.intersects( |
| 2350 | KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER, |
| 2351 | ) => |
| 2352 | { |
| 2353 | self.query.push(ch); |
| 2354 | self.clamp_selection(); |
| 2355 | } |
| 2356 | _ => {} |
| 2357 | } |
| 2358 | return ViewAction::None; |
| 2359 | } |
| 2360 | if self.pending_remove.is_some() |
| 2361 | && !matches!( |
| 2362 | key.code, |
| 2363 | KeyCode::Char('d') | KeyCode::Delete | KeyCode::Enter | KeyCode::Char('y') |
| 2364 | ) |
| 2365 | { |
| 2366 | // Anything but the confirming key disarms a pending removal. |
| 2367 | self.pending_remove = None; |
| 2368 | if key.code == KeyCode::Esc { |
| 2369 | return ViewAction::None; |
| 2370 | } |
| 2371 | } |
| 2372 | match key.code { |
| 2373 | KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close, |
| 2374 | KeyCode::Char('/') => { |
| 2375 | self.focus = ExtensionsFocus::Search; |
| 2376 | ViewAction::None |
| 2377 | } |
| 2378 | KeyCode::Char('e') => { |
| 2379 | self.focus = ExtensionsFocus::List; |
| 2380 | self.toggle_selected() |
| 2381 | } |
| 2382 | KeyCode::Char('d') | KeyCode::Delete => { |
| 2383 | self.focus = ExtensionsFocus::List; |
| 2384 | self.remove_selected() |
| 2385 | } |
| 2386 | KeyCode::Char('y') | KeyCode::Enter if self.pending_remove.is_some() => { |
| 2387 | self.remove_selected() |
| 2388 | } |
| 2389 | // Left/Right and `[`/`]` are the same move for hands that reach |
| 2390 | // for them; the advertised chord is Tab. |
| 2391 | KeyCode::Left | KeyCode::Char('[') | KeyCode::Char('h') => { |
| 2392 | self.set_tab(self.active_tab.previous()); |
| 2393 | ViewAction::None |
| 2394 | } |
| 2395 | KeyCode::Right | KeyCode::Char(']') | KeyCode::Char('l') => { |
| 2396 | self.set_tab(self.active_tab.next()); |
| 2397 | ViewAction::None |
| 2398 | } |
| 2399 | KeyCode::Up | KeyCode::Char('k') => { |
| 2400 | self.focus = ExtensionsFocus::List; |
| 2401 | self.move_selection(-1); |
| 2402 | ViewAction::None |
| 2403 | } |
| 2404 | KeyCode::Down | KeyCode::Char('j') => { |
| 2405 | self.focus = ExtensionsFocus::List; |
| 2406 | self.move_selection(1); |
| 2407 | ViewAction::None |
| 2408 | } |
| 2409 | // Space is the switch. Both references this panel follows bind |
| 2410 | // it that way — grokbuild's `space toggle` and Codex's |
| 2411 | // `space enable/disable` — and it is the gesture a person |
| 2412 | // reaches for on a list of things that are on or off. `e` stays |
| 2413 | // as an alias. A row with no switch (a group heading, a |
| 2414 | // marketplace candidate) keeps Space's old meaning rather than |
| 2415 | // swallowing the key. |
| 2416 | KeyCode::Char(' ') => { |
| 2417 | self.focus = ExtensionsFocus::List; |
| 2418 | match self.toggle_selected() { |
| 2419 | ViewAction::None => self.activate_selected(), |
| 2420 | action => action, |
| 2421 | } |
| 2422 | } |
| 2423 | KeyCode::Enter => { |
| 2424 | self.focus = ExtensionsFocus::List; |
| 2425 | self.activate_selected() |
| 2426 | } |
| 2427 | _ => ViewAction::None, |
| 2428 | } |
| 2429 | } |
| 2430 | |
| 2431 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 2432 | match mouse.kind { |
| 2433 | MouseEventKind::Moved => { |
| 2434 | let hits = self.hits.borrow(); |
| 2435 | let point = (mouse.column, mouse.row).into(); |
| 2436 | self.hovered_row = hits |
| 2437 | .rows |
| 2438 | .iter() |
| 2439 | .find_map(|(rect, row)| rect.contains(point).then_some(*row)); |
| 2440 | self.hovered_tab = hits |
| 2441 | .tabs |
| 2442 | .iter() |
| 2443 | .find_map(|(rect, tab)| rect.contains(point).then_some(*tab)); |
| 2444 | return ViewAction::None; |
| 2445 | } |
| 2446 | // The wheel moves this list, not the transcript behind it. |
| 2447 | MouseEventKind::ScrollUp => { |
| 2448 | self.pending_remove = None; |
| 2449 | self.focus = ExtensionsFocus::List; |
| 2450 | self.move_selection(-1); |
| 2451 | return ViewAction::None; |
| 2452 | } |
| 2453 | MouseEventKind::ScrollDown => { |
| 2454 | self.pending_remove = None; |
| 2455 | self.focus = ExtensionsFocus::List; |
| 2456 | self.move_selection(1); |
| 2457 | return ViewAction::None; |
| 2458 | } |
| 2459 | // Right-click on a row selects it and opens that row's menu. It |
| 2460 | // used to arm (then run) the row's removal, so two right-clicks |
| 2461 | // deleted an extension with no menu ever shown. |
| 2462 | MouseEventKind::Down(MouseButton::Right) => { |
| 2463 | self.pending_remove = None; |
| 2464 | let row = self |
| 2465 | .hits |
| 2466 | .borrow() |
| 2467 | .rows |
| 2468 | .iter() |
| 2469 | .find(|(rect, _)| rect.contains((mouse.column, mouse.row).into())) |
| 2470 | .map(|(_, row)| *row); |
| 2471 | let Some(row) = row else { |
| 2472 | return ViewAction::None; |
| 2473 | }; |
| 2474 | self.focus = ExtensionsFocus::List; |
| 2475 | self.selected[self.active_tab.index()] = row; |
| 2476 | return self |
| 2477 | .row_menu(mouse.column, mouse.row) |
| 2478 | .map_or(ViewAction::None, ViewAction::Emit); |
| 2479 | } |
| 2480 | MouseEventKind::Down(MouseButton::Left) => {} |
| 2481 | _ => return ViewAction::None, |
| 2482 | } |
| 2483 | let hits = self.hits.borrow(); |
| 2484 | if let Some((_, tab)) = hits |
| 2485 | .tabs |
| 2486 | .iter() |
| 2487 | .find(|(rect, _)| rect.contains((mouse.column, mouse.row).into())) |
| 2488 | .copied() |
| 2489 | { |
| 2490 | drop(hits); |
| 2491 | self.focus = ExtensionsFocus::Tabs; |
| 2492 | self.set_tab(tab); |
| 2493 | return ViewAction::None; |
| 2494 | } |
| 2495 | if hits |
| 2496 | .search |
| 2497 | .is_some_and(|rect| rect.contains((mouse.column, mouse.row).into())) |
| 2498 | { |
| 2499 | drop(hits); |
| 2500 | self.focus = ExtensionsFocus::Search; |
| 2501 | return ViewAction::None; |
| 2502 | } |
| 2503 | if let Some((_, row)) = hits |
| 2504 | .rows |
| 2505 | .iter() |
| 2506 | .find(|(rect, _)| rect.contains((mouse.column, mouse.row).into())) |
| 2507 | .copied() |
| 2508 | { |
| 2509 | drop(hits); |
| 2510 | self.focus = ExtensionsFocus::List; |
| 2511 | self.selected[self.active_tab.index()] = row; |
| 2512 | return self.activate_selected(); |
| 2513 | } |
| 2514 | ViewAction::None |
| 2515 | } |
| 2516 | |
| 2517 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 2518 | *self.hits.borrow_mut() = HitAreas::default(); |
| 2519 | let body = render_rounded_surface_themed( |
| 2520 | area, |
| 2521 | buf, |
| 2522 | tr(self.locale, MessageId::ExtensionsTitle).into_owned(), |
| 2523 | None, |
| 2524 | self.focus == ExtensionsFocus::Search, |
| 2525 | Some(&self.theme), |
| 2526 | ); |
| 2527 | if body.width == 0 || body.height < 5 { |
| 2528 | return; |
| 2529 | } |
| 2530 | let surface_bg = resolved_surface_bg(&self.theme); |
| 2531 | let border_color = if self.theme.border != ratatui::style::Color::Reset { |
| 2532 | self.theme.border |
| 2533 | } else { |
| 2534 | palette::BORDER_COLOR |
| 2535 | }; |
| 2536 | let spacious = body.height >= 16; |
| 2537 | let status_lines: Vec<Line<'static>> = if spacious && self.pending_remove.is_none() { |
| 2538 | match self.selected_item() { |
| 2539 | Some(item) => vec![ |
| 2540 | Line::from(vec![ |
| 2541 | Span::styled( |
| 2542 | item.label.clone(), |
| 2543 | Style::default() |
| 2544 | .fg(palette::TEXT_PRIMARY) |
| 2545 | .add_modifier(Modifier::BOLD), |
| 2546 | ), |
| 2547 | Span::styled(" · ", Style::default().fg(border_color)), |
| 2548 | Span::styled( |
| 2549 | item.state.clone(), |
| 2550 | Style::default().fg(item.tone.ink().color(&self.theme)), |
| 2551 | ), |
| 2552 | ]), |
| 2553 | Line::from(Span::styled( |
| 2554 | item.description.clone(), |
| 2555 | Style::default().fg(palette::TEXT_SOFT), |
| 2556 | )), |
| 2557 | Line::from(Span::styled( |
| 2558 | item.detail.clone(), |
| 2559 | Style::default().fg(palette::TEXT_MUTED), |
| 2560 | )), |
| 2561 | ], |
| 2562 | None => vec![Line::from(Span::styled( |
| 2563 | self.selected_status(), |
| 2564 | Style::default().fg(palette::TEXT_MUTED), |
| 2565 | ))], |
| 2566 | } |
| 2567 | } else { |
| 2568 | vec![Line::from(Span::styled( |
| 2569 | self.selected_status(), |
| 2570 | Style::default().fg(if self.pending_remove.is_some() { |
| 2571 | palette::STATUS_WARNING |
| 2572 | } else { |
| 2573 | palette::TEXT_MUTED |
| 2574 | }), |
| 2575 | ))] |
| 2576 | }; |
| 2577 | let status = Paragraph::new(status_lines).wrap(Wrap { trim: false }); |
| 2578 | let status_height = if spacious { |
| 2579 | u16::try_from(status.line_count(body.width)) |
| 2580 | .unwrap_or(u16::MAX) |
| 2581 | .saturating_add(1) |
| 2582 | .clamp(4, (body.height / 3).max(4)) |
| 2583 | } else { |
| 2584 | 1 |
| 2585 | }; |
| 2586 | let rows = Layout::default() |
| 2587 | .direction(Direction::Vertical) |
| 2588 | .constraints([ |
| 2589 | Constraint::Length(1), |
| 2590 | Constraint::Length(1), |
| 2591 | Constraint::Min(1), |
| 2592 | Constraint::Length(status_height), |
| 2593 | Constraint::Length(1), |
| 2594 | ]) |
| 2595 | .split(body); |
| 2596 | |
| 2597 | let mut hits = HitAreas::default(); |
| 2598 | let mut x = rows[0].x; |
| 2599 | let available = rows[0].right(); |
| 2600 | let cells = |label: &str| { |
| 2601 | u16::try_from(UnicodeWidthStr::width(label)) |
| 2602 | .unwrap_or(u16::MAX) |
| 2603 | .saturating_add(2) |
| 2604 | }; |
| 2605 | let mut labels: Vec<(ExtensionsTab, String)> = ExtensionsTab::ALL |
| 2606 | .iter() |
| 2607 | .map(|tab| (*tab, tab.label(self.locale))) |
| 2608 | .collect(); |
| 2609 | let row_cells = available.saturating_sub(x); |
| 2610 | let total = labels |
| 2611 | .iter() |
| 2612 | .fold(0u16, |sum, (_, label)| sum.saturating_add(cells(label))); |
| 2613 | if total > row_cells { |
| 2614 | for (tab, label) in &mut labels { |
| 2615 | if *tab == ExtensionsTab::Marketplace { |
| 2616 | *label = |
| 2617 | tr(self.locale, MessageId::ExtensionsTabMarketplaceCompact).into_owned(); |
| 2618 | } |
| 2619 | } |
| 2620 | } |
| 2621 | let mut first = 0; |
| 2622 | if let Some(active_index) = labels.iter().position(|(tab, _)| *tab == self.active_tab) { |
| 2623 | while first < active_index |
| 2624 | && labels[first..=active_index] |
| 2625 | .iter() |
| 2626 | .fold(0u16, |sum, (_, label)| sum.saturating_add(cells(label))) |
| 2627 | > row_cells |
| 2628 | { |
| 2629 | first += 1; |
| 2630 | } |
| 2631 | } |
| 2632 | for (tab, label) in labels.into_iter().skip(first) { |
| 2633 | let width = cells(&label); |
| 2634 | if width > available.saturating_sub(x) { |
| 2635 | break; |
| 2636 | } |
| 2637 | let tab_area = Rect::new(x, rows[0].y, width, 1); |
| 2638 | let active = tab == self.active_tab; |
| 2639 | let focused = active && self.focus == ExtensionsFocus::Tabs; |
| 2640 | let style = if focused { |
| 2641 | menu_style::selected_row_style() |
| 2642 | } else if self.hovered_tab == Some(tab) { |
| 2643 | menu_style::hovered_row_style().fg(palette::TEXT_PRIMARY) |
| 2644 | } else if active { |
| 2645 | Style::default() |
| 2646 | .fg(palette::WHALE_ACTION) |
| 2647 | .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) |
| 2648 | } else { |
| 2649 | Style::default().fg(palette::TEXT_MUTED) |
| 2650 | }; |
| 2651 | Paragraph::new(Line::from(Span::styled(format!(" {label} "), style))) |
| 2652 | .render(tab_area, buf); |
| 2653 | hits.tabs.push((tab_area, tab)); |
| 2654 | x = x.saturating_add(width); |
| 2655 | } |
| 2656 | |
| 2657 | let search_style = if self.focus == ExtensionsFocus::Search { |
| 2658 | Style::default() |
| 2659 | .fg(palette::WHALE_ACTION) |
| 2660 | .add_modifier(Modifier::BOLD) |
| 2661 | } else { |
| 2662 | Style::default().fg(palette::TEXT_MUTED) |
| 2663 | }; |
| 2664 | let cursor = if self.focus == ExtensionsFocus::Search { |
| 2665 | "_" |
| 2666 | } else { |
| 2667 | "" |
| 2668 | }; |
| 2669 | Paragraph::new(Line::from(vec![ |
| 2670 | Span::styled( |
| 2671 | tr(self.locale, MessageId::ExtensionsSearchLabel), |
| 2672 | search_style, |
| 2673 | ), |
| 2674 | Span::styled( |
| 2675 | format!("{}{cursor}", self.query), |
| 2676 | Style::default().fg(palette::TEXT_PRIMARY), |
| 2677 | ), |
| 2678 | ])) |
| 2679 | .render(rows[1], buf); |
| 2680 | hits.search = Some(rows[1]); |
| 2681 | |
| 2682 | let entries = self.visible_entries(); |
| 2683 | let list_height = usize::from(rows[2].height); |
| 2684 | let mut scroll = self.scroll[self.active_tab.index()]; |
| 2685 | let selected = self.selected[self.active_tab.index()]; |
| 2686 | if selected < scroll { |
| 2687 | scroll = selected; |
| 2688 | } else if selected >= scroll.saturating_add(list_height.max(1)) { |
| 2689 | scroll = selected.saturating_sub(list_height.saturating_sub(1)); |
| 2690 | } |
| 2691 | let ascii = crate::tui::color_compat::ascii_safe_enabled(); |
| 2692 | for (visible_offset, (entry_index, entry)) in entries |
| 2693 | .iter() |
| 2694 | .enumerate() |
| 2695 | .skip(scroll) |
| 2696 | .take(list_height) |
| 2697 | .enumerate() |
| 2698 | { |
| 2699 | let row_area = Rect::new( |
| 2700 | rows[2].x, |
| 2701 | rows[2].y.saturating_add(visible_offset as u16), |
| 2702 | rows[2].width, |
| 2703 | 1, |
| 2704 | ); |
| 2705 | let is_selected = entry_index == selected; |
| 2706 | let hovered = self.hovered_row == Some(entry_index); |
| 2707 | let style = if is_selected && self.focus == ExtensionsFocus::List { |
| 2708 | menu_style::selected_row_style() |
| 2709 | } else if hovered { |
| 2710 | menu_style::hovered_row_style().fg(palette::TEXT_PRIMARY) |
| 2711 | } else if is_selected { |
| 2712 | Style::default() |
| 2713 | .fg(palette::WHALE_ACTION) |
| 2714 | .add_modifier(Modifier::BOLD) |
| 2715 | } else { |
| 2716 | Style::default().fg(palette::TEXT_PRIMARY) |
| 2717 | }; |
| 2718 | let mut parts: Vec<(String, Option<codewhale_palette::ChromeInk>)> = Vec::new(); |
| 2719 | match entry { |
| 2720 | VisibleEntry::Group(group) => { |
| 2721 | let folded = self.folded_groups.contains(&self.fold_key(group)); |
| 2722 | let chevron = if folded { |
| 2723 | if ascii { ">" } else { "▸" } |
| 2724 | } else if ascii { |
| 2725 | "v" |
| 2726 | } else { |
| 2727 | "▾" |
| 2728 | }; |
| 2729 | parts.push(( |
| 2730 | format!("{chevron} {} ({})", group.label, group.items.len()), |
| 2731 | Some(codewhale_palette::ChromeInk::Identity), |
| 2732 | )); |
| 2733 | } |
| 2734 | VisibleEntry::Item(_, item) => { |
| 2735 | let dot = match item.tone { |
| 2736 | ExtensionTone::Ready => { |
| 2737 | if ascii { |
| 2738 | "*" |
| 2739 | } else { |
| 2740 | "●" |
| 2741 | } |
| 2742 | } |
| 2743 | ExtensionTone::Idle => { |
| 2744 | if ascii { |
| 2745 | "o" |
| 2746 | } else { |
| 2747 | "○" |
| 2748 | } |
| 2749 | } |
| 2750 | ExtensionTone::Attention => "!", |
| 2751 | ExtensionTone::Failure => { |
| 2752 | if ascii { |
| 2753 | "x" |
| 2754 | } else { |
| 2755 | "✗" |
| 2756 | } |
| 2757 | } |
| 2758 | }; |
| 2759 | parts.push((format!("{dot} "), Some(item.tone.ink()))); |
| 2760 | if let Some(action) = item.action.as_ref() { |
| 2761 | parts.push(( |
| 2762 | format!("{} · ", action.label()), |
| 2763 | Some(match action { |
| 2764 | ExtensionAction::Command { .. } => { |
| 2765 | codewhale_palette::ChromeInk::Identity |
| 2766 | } |
| 2767 | ExtensionAction::Status { .. } => item.tone.ink(), |
| 2768 | }), |
| 2769 | )); |
| 2770 | } |
| 2771 | parts.push((item.label.clone(), None)); |
| 2772 | parts.push((format!(" · {}", item.state), Some(item.tone.ink()))); |
| 2773 | } |
| 2774 | VisibleEntry::Problem(problem) => parts.push(( |
| 2775 | format!("! {problem}"), |
| 2776 | Some(codewhale_palette::ChromeInk::Failure), |
| 2777 | )), |
| 2778 | VisibleEntry::Empty => parts.push(( |
| 2779 | self.empty_message(), |
| 2780 | Some(codewhale_palette::ChromeInk::MetadataHint), |
| 2781 | )), |
| 2782 | } |
| 2783 | |
| 2784 | let joined = parts |
| 2785 | .iter() |
| 2786 | .map(|(text, _)| text.as_str()) |
| 2787 | .collect::<String>(); |
| 2788 | let clipped = truncate_view_text(&joined, usize::from(row_area.width)); |
| 2789 | let spans = if is_selected || hovered || clipped.len() != joined.len() { |
| 2790 | vec![Span::styled(clipped, style)] |
| 2791 | } else { |
| 2792 | parts |
| 2793 | .into_iter() |
| 2794 | .filter(|(text, _)| !text.is_empty()) |
| 2795 | .map(|(text, ink)| { |
| 2796 | let span_style = match ink { |
| 2797 | Some(ink) => Style::default().fg(ink.color(&self.theme)), |
| 2798 | None => style, |
| 2799 | }; |
| 2800 | Span::styled(text, span_style) |
| 2801 | }) |
| 2802 | .collect() |
| 2803 | }; |
| 2804 | Paragraph::new(Line::from(spans)) |
| 2805 | .style(style) |
| 2806 | .render(row_area, buf); |
| 2807 | hits.rows.push((row_area, entry_index)); |
| 2808 | } |
| 2809 | |
| 2810 | if spacious && rows[3].height > 1 { |
| 2811 | render_hairline(rows[3], buf, border_color, surface_bg); |
| 2812 | status.render( |
| 2813 | Rect::new( |
| 2814 | rows[3].x, |
| 2815 | rows[3].y.saturating_add(1), |
| 2816 | rows[3].width, |
| 2817 | rows[3].height.saturating_sub(1), |
| 2818 | ), |
| 2819 | buf, |
| 2820 | ); |
| 2821 | } else { |
| 2822 | status.render(rows[3], buf); |
| 2823 | } |
| 2824 | let enter_label = match entries.get(selected).copied() { |
| 2825 | Some(VisibleEntry::Item(_, item)) => Some( |
| 2826 | item.action |
| 2827 | .as_ref() |
| 2828 | .filter(|action| action.command().is_some()) |
| 2829 | .map_or_else( |
| 2830 | || tr(self.locale, MessageId::AutomationActionInspect).into_owned(), |
| 2831 | |action| action.label().to_string(), |
| 2832 | ), |
| 2833 | ), |
| 2834 | Some(VisibleEntry::Group(_)) => { |
| 2835 | Some(tr(self.locale, MessageId::ExtensionsActionFold).into_owned()) |
| 2836 | } |
| 2837 | Some(VisibleEntry::Problem(_)) => { |
| 2838 | Some(tr(self.locale, MessageId::AutomationActionInspect).into_owned()) |
| 2839 | } |
| 2840 | _ => None, |
| 2841 | }; |
| 2842 | let mut hints = vec![ |
| 2843 | ( |
| 2844 | 0u8, |
| 2845 | super::ActionHint::new("Tab", tr(self.locale, MessageId::ExtensionsActionTabs)), |
| 2846 | ), |
| 2847 | ( |
| 2848 | 3, |
| 2849 | super::ActionHint::new("↑↓", tr(self.locale, MessageId::LaunchHintMove)), |
| 2850 | ), |
| 2851 | ]; |
| 2852 | if let Some(label) = enter_label { |
| 2853 | hints.push((0, super::ActionHint::new("Enter", label))); |
| 2854 | } |
| 2855 | if let Some(item) = self.selected_item() { |
| 2856 | if let Some(toggle) = item.toggle.as_ref() { |
| 2857 | hints.push(( |
| 2858 | 1, |
| 2859 | super::ActionHint::new("Space", toggle.label().to_string()), |
| 2860 | )); |
| 2861 | } |
| 2862 | if let Some(remove) = item.remove.as_ref() { |
| 2863 | hints.push((2, super::ActionHint::new("d", remove.label().to_string()))); |
| 2864 | } |
| 2865 | } |
| 2866 | hints.push(( |
| 2867 | 0, |
| 2868 | super::ActionHint::new("/", tr(self.locale, MessageId::SessionsActionSearch)), |
| 2869 | )); |
| 2870 | hints.push(( |
| 2871 | 0, |
| 2872 | super::ActionHint::new("Esc", tr(self.locale, MessageId::SessionsActionClose)), |
| 2873 | )); |
| 2874 | let (mut ranks, mut hints): (Vec<u8>, Vec<super::ActionHint>) = hints.into_iter().unzip(); |
| 2875 | for shed in [3, 2, 1] { |
| 2876 | if super::action_footer_lines(&hints, rows[4].width).len() <= 1 { |
| 2877 | break; |
| 2878 | } |
| 2879 | let mut kept = ranks.iter().map(|rank| *rank != shed); |
| 2880 | hints.retain(|_| kept.next().unwrap_or(true)); |
| 2881 | ranks.retain(|rank| *rank != shed); |
| 2882 | } |
| 2883 | render_modal_footer(rows[4], buf, &hints); |
| 2884 | *self.hits.borrow_mut() = hits; |
| 2885 | } |
| 2886 | |
| 2887 | fn tick(&mut self) -> ViewAction { |
| 2888 | // MCP rows go live while the panel is open — a retry lands, a login |
| 2889 | // finishes, a diagnosis resolves — and the open-time capture would |
| 2890 | // read stale until reopen. Ask the host for a fresh model at a |
| 2891 | // bounded cadence; it rebuilds only when the generation or the |
| 2892 | // initializing flag actually moved. |
| 2893 | if self.last_poll.elapsed() < std::time::Duration::from_millis(750) { |
| 2894 | return ViewAction::None; |
| 2895 | } |
| 2896 | self.last_poll = std::time::Instant::now(); |
| 2897 | ViewAction::Emit(ViewEvent::RefreshExtensions { |
| 2898 | mcp_generation: self.snapshot.mcp_generation, |
| 2899 | mcp_initializing: self.snapshot.mcp_initializing, |
| 2900 | }) |
| 2901 | } |
| 2902 | |
| 2903 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 2904 | self |
| 2905 | } |
| 2906 | } |
| 2907 | |
| 2908 | /// Row action labels are lower-case verbs ("remove", "enable") written for |
| 2909 | /// the footer; a menu row starts with a capital. |
| 2910 | fn sentence_case(label: &str) -> String { |
| 2911 | let mut chars = label.chars(); |
| 2912 | match chars.next() { |
| 2913 | Some(first) => first.to_uppercase().chain(chars).collect(), |
| 2914 | None => String::new(), |
| 2915 | } |
| 2916 | } |
| 2917 | |
| 2918 | #[cfg(test)] |
| 2919 | mod tests { |
| 2920 | use super::*; |
| 2921 | use codewhale_engine::mcp::McpRecoveryKind; |
| 2922 | |
| 2923 | #[test] |
| 2924 | fn passive_rows_open_details_without_recovery_or_mutation() { |
| 2925 | let mut view = view_on_item(ExtensionAction::Status { |
| 2926 | label: "connected".into(), |
| 2927 | }); |
| 2928 | let ViewAction::Emit(ViewEvent::OpenTextPager { title, content }) = |
| 2929 | view.activate_selected() |
| 2930 | else { |
| 2931 | panic!("a passive inventory row must have useful details"); |
| 2932 | }; |
| 2933 | assert_eq!(title, "row"); |
| 2934 | assert!(content.contains("state")); |
| 2935 | assert!(view.pending_remove.is_none()); |
| 2936 | } |
| 2937 | |
| 2938 | fn observed_row( |
| 2939 | name: &str, |
| 2940 | enabled: bool, |
| 2941 | connected: bool, |
| 2942 | error: Option<&str>, |
| 2943 | auth_required: bool, |
| 2944 | ) -> codewhale_engine::mcp::McpServerSnapshot { |
| 2945 | codewhale_engine::mcp::McpServerSnapshot { |
| 2946 | name: name.into(), |
| 2947 | enabled, |
| 2948 | required: false, |
| 2949 | transport: "stdio".into(), |
| 2950 | command_or_url: format!("{name}-mcp"), |
| 2951 | connect_timeout: 5, |
| 2952 | execute_timeout: 5, |
| 2953 | read_timeout: 5, |
| 2954 | connected, |
| 2955 | error: error.map(str::to_string), |
| 2956 | auth_required, |
| 2957 | capability_metadata: if connected { |
| 2958 | codewhale_engine::mcp::McpServerCapabilityMetadata::LegacyFallback |
| 2959 | } else { |
| 2960 | codewhale_engine::mcp::McpServerCapabilityMetadata::NotObserved |
| 2961 | }, |
| 2962 | tools: Vec::new(), |
| 2963 | resources: Vec::new(), |
| 2964 | prompts: Vec::new(), |
| 2965 | } |
| 2966 | } |
| 2967 | |
| 2968 | /// The founder's Extensions > MCP screen listed eight servers under |
| 2969 | /// "Needs attention", six of them "reconnect · configured". Each row now |
| 2970 | /// reads the state the engine's pool actually has, offers the action |
| 2971 | /// that state needs, and only broken or waiting rows need attention. |
| 2972 | #[test] |
| 2973 | fn mcp_rows_show_real_state_with_the_action_that_state_needs() { |
| 2974 | let _env = crate::test_support::lock_test_env(); |
| 2975 | let root = tempfile::tempdir().unwrap(); |
| 2976 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path()); |
| 2977 | let registry = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv() |
| 2978 | .registry_for_workspace(root.path()); |
| 2979 | let mut app = App::new_with_plugin_registry( |
| 2980 | crate::tui::test_support::test_tui_options(root.path()), |
| 2981 | &codewhale_runtime::config::Config::default(), |
| 2982 | registry, |
| 2983 | ); |
| 2984 | app.mcp_config_path = root.path().join("mcp.json"); |
| 2985 | std::fs::write( |
| 2986 | &app.mcp_config_path, |
| 2987 | r#"{"servers":{ |
| 2988 | "github":{"command":"github-mcp"}, |
| 2989 | "playwright":{"command":"npx"}, |
| 2990 | "stripe":{"url":"https://mcp.stripe.com"}, |
| 2991 | "aws":{"command":"uvx"}, |
| 2992 | "linear":{"url":"https://mcp.linear.app/mcp","disabled":true,"enabled":false}, |
| 2993 | "chrome-devtools":{"command":"npx"} |
| 2994 | }}"#, |
| 2995 | ) |
| 2996 | .unwrap(); |
| 2997 | app.mcp_snapshot = Some(codewhale_engine::mcp::McpManagerSnapshot { |
| 2998 | config_path: app.mcp_config_path.clone(), |
| 2999 | config_exists: true, |
| 3000 | reload_required: false, |
| 3001 | servers: vec![ |
| 3002 | observed_row("github", true, true, None, false), |
| 3003 | // Lazy boot never started it. |
| 3004 | observed_row("playwright", true, false, None, false), |
| 3005 | observed_row("stripe", true, false, Some("HTTP 401 Unauthorized"), true), |
| 3006 | observed_row( |
| 3007 | "aws", |
| 3008 | true, |
| 3009 | false, |
| 3010 | Some("MCP server 'aws' rejected initialize (command `uvx`): -32602"), |
| 3011 | false, |
| 3012 | ), |
| 3013 | // Disabled in the file since this snapshot was taken. |
| 3014 | observed_row("linear", true, false, None, false), |
| 3015 | observed_row("chrome-devtools", true, false, None, false), |
| 3016 | ], |
| 3017 | }); |
| 3018 | app.mcp_retries.push(crate::tui::app::PendingMcpRetry { |
| 3019 | server: "chrome-devtools".into(), |
| 3020 | queued: true, |
| 3021 | result: std::sync::Arc::new(std::sync::Mutex::new(None)), |
| 3022 | }); |
| 3023 | |
| 3024 | let model = mcp_model(&app, Locale::En); |
| 3025 | let row = |name: &str| { |
| 3026 | model |
| 3027 | .groups |
| 3028 | .iter() |
| 3029 | .flat_map(|group| { |
| 3030 | group |
| 3031 | .items |
| 3032 | .iter() |
| 3033 | .map(move |item| (group.id.as_str(), item)) |
| 3034 | }) |
| 3035 | .find(|(_, item)| item.id == name) |
| 3036 | .unwrap_or_else(|| panic!("row {name}")) |
| 3037 | }; |
| 3038 | let command = |item: &ExtensionItem| { |
| 3039 | item.action |
| 3040 | .as_ref() |
| 3041 | .and_then(ExtensionAction::command) |
| 3042 | .map(str::to_string) |
| 3043 | }; |
| 3044 | |
| 3045 | let (group, github) = row("github"); |
| 3046 | assert_eq!((group, github.state.as_str()), ("servers", "connected")); |
| 3047 | assert_eq!(command(github), None); |
| 3048 | |
| 3049 | // Lazy boot has not needed it: the row says so and says what happens |
| 3050 | // next, not "not started" over a row of zero counts. |
| 3051 | let (group, playwright) = row("playwright"); |
| 3052 | assert_eq!( |
| 3053 | (group, playwright.state.as_str()), |
| 3054 | ("servers", "not connected") |
| 3055 | ); |
| 3056 | assert_eq!(playwright.description, "stdio"); |
| 3057 | assert!( |
| 3058 | playwright |
| 3059 | .detail |
| 3060 | .ends_with("Not connected in this session yet. Connects when a tool is needed, or connect it now."), |
| 3061 | "{}", |
| 3062 | playwright.detail |
| 3063 | ); |
| 3064 | assert!( |
| 3065 | !playwright.detail.contains("tools: 0"), |
| 3066 | "{}", |
| 3067 | playwright.detail |
| 3068 | ); |
| 3069 | assert_eq!(playwright.tone, ExtensionTone::Idle); |
| 3070 | assert_eq!( |
| 3071 | command(playwright).as_deref(), |
| 3072 | Some("/mcp retry playwright") |
| 3073 | ); |
| 3074 | assert_eq!( |
| 3075 | playwright.action.as_ref().map(ExtensionAction::label), |
| 3076 | Some("connect") |
| 3077 | ); |
| 3078 | |
| 3079 | let (group, stripe) = row("stripe"); |
| 3080 | assert_eq!(group, MCP_LOGIN_GROUP_ID); |
| 3081 | assert_eq!(command(stripe).as_deref(), Some("/mcp login stripe")); |
| 3082 | |
| 3083 | let (group, aws) = row("aws"); |
| 3084 | assert_eq!((group, aws.state.as_str()), ("attention", "error")); |
| 3085 | assert_eq!(aws.tone, ExtensionTone::Failure); |
| 3086 | assert!(aws.detail.contains("rejected initialize"), "{}", aws.detail); |
| 3087 | |
| 3088 | let (group, linear) = row("linear"); |
| 3089 | assert_eq!((group, linear.state.as_str()), ("servers", "disabled")); |
| 3090 | assert_eq!(command(linear).as_deref(), Some("/mcp enable linear")); |
| 3091 | |
| 3092 | let (_, chrome) = row("chrome-devtools"); |
| 3093 | assert_eq!(chrome.state, "queued"); |
| 3094 | assert_eq!( |
| 3095 | command(chrome), |
| 3096 | None, |
| 3097 | "a pending retry is not offered twice" |
| 3098 | ); |
| 3099 | } |
| 3100 | |
| 3101 | #[test] |
| 3102 | fn empty_mcp_opens_suggestions_without_installing_and_skills_manage_does_not_loop() { |
| 3103 | let _env = crate::test_support::lock_test_env(); |
| 3104 | let root = tempfile::tempdir().unwrap(); |
| 3105 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path()); |
| 3106 | let registry = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv() |
| 3107 | .registry_for_workspace(root.path()); |
| 3108 | let app = App::new_with_plugin_registry( |
| 3109 | crate::tui::test_support::test_tui_options(root.path()), |
| 3110 | &codewhale_runtime::config::Config::default(), |
| 3111 | registry, |
| 3112 | ); |
| 3113 | let model = mcp_model(&app, Locale::En); |
| 3114 | assert_eq!(model.groups.len(), 1); |
| 3115 | assert_eq!(model.groups[0].label, "No MCP servers configured"); |
| 3116 | let item = &model.groups[0].items[0]; |
| 3117 | assert!(item.toggle.is_none() && item.remove.is_none()); |
| 3118 | assert!( |
| 3119 | matches!(item.action.as_ref(), Some(ExtensionAction::Command { |
| 3120 | command, disposition: RowActionDisposition::InPlacePager, .. |
| 3121 | }) if command == "/mcp recommendations") |
| 3122 | ); |
| 3123 | let skills = skills_model(&app, Locale::En); |
| 3124 | for item in skills.groups.iter().flat_map(|group| &group.items) { |
| 3125 | assert_eq!( |
| 3126 | item.action.as_ref().and_then(ExtensionAction::command), |
| 3127 | Some("/skills manage") |
| 3128 | ); |
| 3129 | } |
| 3130 | let mut snapshot = ExtensionsSnapshot::default(); |
| 3131 | snapshot.tabs[ExtensionsTab::Mcp.index()] = model; |
| 3132 | let mut view = |
| 3133 | ExtensionsView::from_snapshot_with_locale(snapshot, ExtensionsTab::Mcp, Locale::En); |
| 3134 | assert_eq!(view.selected[ExtensionsTab::Mcp.index()], 1); |
| 3135 | assert!( |
| 3136 | matches!(view.activate_selected(), ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 3137 | command, pager_title: Some(_) |
| 3138 | }) if command == "/mcp recommendations") |
| 3139 | ); |
| 3140 | } |
| 3141 | |
| 3142 | /// Tab widths are display cells: a two-cell CJK label measured in chars |
| 3143 | /// clipped its own text and let the next tab paint over it, and the hit |
| 3144 | /// rect covered the wrong cells. |
| 3145 | #[test] |
| 3146 | fn wide_tab_labels_get_their_full_cell_width_and_matching_hit_rects() { |
| 3147 | let view = ExtensionsView::from_snapshot_with_locale( |
| 3148 | ExtensionsSnapshot::default(), |
| 3149 | ExtensionsTab::Hooks, |
| 3150 | Locale::ZhHans, |
| 3151 | ); |
| 3152 | let area = Rect::new(0, 0, 100, 24); |
| 3153 | let mut buf = Buffer::empty(area); |
| 3154 | view.render(area, &mut buf); |
| 3155 | let tabs = view.hits.borrow().tabs.clone(); |
| 3156 | assert_eq!(tabs.len(), ExtensionsTab::ALL.len()); |
| 3157 | let mut next_x = tabs[0].0.x; |
| 3158 | for (rect, tab) in tabs { |
| 3159 | let label = tab.label(Locale::ZhHans); |
| 3160 | assert_eq!( |
| 3161 | usize::from(rect.width), |
| 3162 | UnicodeWidthStr::width(label.as_str()) + 2, |
| 3163 | "{tab:?} hit rect must match its painted width" |
| 3164 | ); |
| 3165 | assert_eq!( |
| 3166 | rect.x, next_x, |
| 3167 | "{tab:?} must start where the previous tab ended" |
| 3168 | ); |
| 3169 | next_x = rect.right(); |
| 3170 | // Read the row as a terminal shows it: a wide glyph covers the |
| 3171 | // cell after it. |
| 3172 | let mut painted = String::new(); |
| 3173 | let mut x = rect.x; |
| 3174 | while x < rect.right() { |
| 3175 | let symbol = buf[(x, rect.y)].symbol(); |
| 3176 | painted.push_str(symbol); |
| 3177 | x += u16::try_from(UnicodeWidthStr::width(symbol).max(1)).unwrap_or(1); |
| 3178 | } |
| 3179 | assert!( |
| 3180 | painted.contains(label.as_str()), |
| 3181 | "{tab:?} label {label:?} clipped: {painted:?}" |
| 3182 | ); |
| 3183 | } |
| 3184 | } |
| 3185 | |
| 3186 | fn painted_text(buf: &Buffer, area: Rect) -> String { |
| 3187 | let mut text = String::new(); |
| 3188 | for y in area.y..area.bottom() { |
| 3189 | for x in area.x..area.right() { |
| 3190 | text.push_str(buf[(x, y)].symbol()); |
| 3191 | } |
| 3192 | text.push('\n'); |
| 3193 | } |
| 3194 | text |
| 3195 | } |
| 3196 | |
| 3197 | #[test] |
| 3198 | fn extensions_screen_is_titled_plugins_with_filter_labels() { |
| 3199 | for (width, height) in [(80, 24), (120, 32)] { |
| 3200 | let view = ExtensionsView::from_snapshot_with_locale( |
| 3201 | ExtensionsSnapshot::default(), |
| 3202 | ExtensionsTab::Plugins, |
| 3203 | Locale::En, |
| 3204 | ); |
| 3205 | let area = Rect::new(0, 0, width, height); |
| 3206 | let mut buf = Buffer::empty(area); |
| 3207 | view.render(area, &mut buf); |
| 3208 | let text = painted_text(&buf, area); |
| 3209 | assert!(text.contains("Plugins"), "{width}x{height}: {text}"); |
| 3210 | for label in [ |
| 3211 | "Hooks", |
| 3212 | "Installed", |
| 3213 | "Marketplace", |
| 3214 | "Skills", |
| 3215 | "Connectors", |
| 3216 | "Command", |
| 3217 | ] { |
| 3218 | assert!( |
| 3219 | text.contains(label), |
| 3220 | "{width}x{height} is missing the {label} filter: {text}" |
| 3221 | ); |
| 3222 | } |
| 3223 | assert!(!text.contains("Extensions"), "{width}x{height}: {text}"); |
| 3224 | } |
| 3225 | } |
| 3226 | |
| 3227 | #[test] |
| 3228 | fn every_pack_keeps_every_painted_filter_whole_and_the_active_one_in_view() { |
| 3229 | for locale in Locale::shipped_complete() { |
| 3230 | let compact = format!( |
| 3231 | " {} ", |
| 3232 | tr(*locale, MessageId::ExtensionsTabMarketplaceCompact) |
| 3233 | ); |
| 3234 | for width in [40u16, 60, 80] { |
| 3235 | for active in ExtensionsTab::ALL { |
| 3236 | let view = ExtensionsView::from_snapshot_with_locale( |
| 3237 | ExtensionsSnapshot::default(), |
| 3238 | active, |
| 3239 | *locale, |
| 3240 | ); |
| 3241 | let area = Rect::new(0, 0, width, 24); |
| 3242 | let mut buf = Buffer::empty(area); |
| 3243 | view.render(area, &mut buf); |
| 3244 | let tabs = view.hits.borrow().tabs.clone(); |
| 3245 | assert!( |
| 3246 | tabs.iter().any(|(_, tab)| *tab == active), |
| 3247 | "{} at {width}: the active {active:?} filter is not painted", |
| 3248 | locale.tag() |
| 3249 | ); |
| 3250 | if width == 80 { |
| 3251 | assert_eq!(tabs.len(), ExtensionsTab::ALL.len(), "{}", locale.tag()); |
| 3252 | } |
| 3253 | for (rect, tab) in tabs { |
| 3254 | let full = format!(" {} ", tab.label(*locale)); |
| 3255 | let mut painted = String::new(); |
| 3256 | let mut x = rect.x; |
| 3257 | while x < rect.right() { |
| 3258 | let symbol = buf[(x, rect.y)].symbol(); |
| 3259 | painted.push_str(symbol); |
| 3260 | x += u16::try_from(UnicodeWidthStr::width(symbol).max(1)).unwrap_or(1); |
| 3261 | } |
| 3262 | assert!( |
| 3263 | painted == full |
| 3264 | || (tab == ExtensionsTab::Marketplace && painted == compact), |
| 3265 | "{} at {width}: {tab:?} is clipped: {painted:?}", |
| 3266 | locale.tag() |
| 3267 | ); |
| 3268 | assert!(rect.right() < area.right(), "{} at {width}", locale.tag()); |
| 3269 | } |
| 3270 | } |
| 3271 | } |
| 3272 | } |
| 3273 | } |
| 3274 | |
| 3275 | #[test] |
| 3276 | fn workbench_extension_hover_preserves_selection_and_small_resize_clears_targets() { |
| 3277 | let mut view = view_on_item(ExtensionAction::Command { |
| 3278 | label: "enable".into(), |
| 3279 | command: "/plugin enable demo".into(), |
| 3280 | disposition: RowActionDisposition::InPlace, |
| 3281 | }); |
| 3282 | let area = Rect::new(0, 0, 80, 24); |
| 3283 | let mut buf = Buffer::empty(area); |
| 3284 | view.render(area, &mut buf); |
| 3285 | let (hit, row) = view.hits.borrow().rows[0]; |
| 3286 | let selected = view.selected; |
| 3287 | view.handle_mouse(MouseEvent { |
| 3288 | kind: MouseEventKind::Moved, |
| 3289 | column: hit.x, |
| 3290 | row: hit.y, |
| 3291 | modifiers: KeyModifiers::NONE, |
| 3292 | }); |
| 3293 | assert_eq!(view.hovered_row, Some(row)); |
| 3294 | assert_eq!(view.selected, selected); |
| 3295 | view.render(area, &mut buf); |
| 3296 | assert_eq!(buf[(hit.right() - 1, hit.y)].bg, palette::SURFACE_ELEVATED); |
| 3297 | let tiny = Rect::new(0, 0, 20, 4); |
| 3298 | view.render(tiny, &mut Buffer::empty(tiny)); |
| 3299 | assert!(view.hits.borrow().rows.is_empty()); |
| 3300 | assert!(view.hits.borrow().tabs.is_empty()); |
| 3301 | } |
| 3302 | |
| 3303 | #[test] |
| 3304 | fn a_plugin_contributed_server_is_not_mutable_from_this_panel() { |
| 3305 | // The row's name is synthesized and never appears in the config file |
| 3306 | // `/mcp remove` resolves against, so the gesture could only ever 404. |
| 3307 | let owned = BTreeSet::from(["github".to_string(), "playwright".to_string()]); |
| 3308 | assert!(mcp_row_is_mutable(Some(&owned), "github")); |
| 3309 | assert!(!mcp_row_is_mutable( |
| 3310 | Some(&owned), |
| 3311 | "plugin-25-codewhale-account-plugins-codewhale-plugins" |
| 3312 | )); |
| 3313 | } |
| 3314 | |
| 3315 | #[test] |
| 3316 | fn an_unreadable_config_keeps_the_gestures_rather_than_withdrawing_them() { |
| 3317 | assert!(mcp_row_is_mutable(None, "anything")); |
| 3318 | } |
| 3319 | |
| 3320 | /// The founder's report, as a test: `computer-use` is installed disabled and |
| 3321 | /// never reviewed, and the panel said `disabled` while offering no way |
| 3322 | /// to enable it — "computer use is disabled but i can't enable it. tf?". |
| 3323 | /// The row must now say what stands in the way and carry the switch. |
| 3324 | #[test] |
| 3325 | fn an_installed_bundle_says_what_it_needs_and_carries_a_switch() { |
| 3326 | let _env = crate::test_support::lock_test_env(); |
| 3327 | let root = tempfile::tempdir().unwrap(); |
| 3328 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path()); |
| 3329 | let plugin_dir = root.path().join("plugins/computer-use"); |
| 3330 | std::fs::create_dir_all(&plugin_dir).unwrap(); |
| 3331 | #[cfg(unix)] |
| 3332 | std::fs::set_permissions( |
| 3333 | root.path().join("plugins"), |
| 3334 | std::os::unix::fs::PermissionsExt::from_mode(0o700), |
| 3335 | ) |
| 3336 | .unwrap(); |
| 3337 | std::fs::write( |
| 3338 | plugin_dir.join("plugin.json"), |
| 3339 | r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"computer-use","version":"1.0.0","description":"Locally installed fixture"}"#, |
| 3340 | ) |
| 3341 | .unwrap(); |
| 3342 | let registry = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv() |
| 3343 | .registry_for_workspace(root.path()); |
| 3344 | let app = App::new_with_plugin_registry( |
| 3345 | crate::tui::test_support::test_tui_options(root.path()), |
| 3346 | &codewhale_runtime::config::Config::default(), |
| 3347 | registry, |
| 3348 | ); |
| 3349 | let plugin = app.plugin_registry.get("computer-use").unwrap(); |
| 3350 | assert!(!plugin.enabled && !plugin.trusted(), "fixture precondition"); |
| 3351 | |
| 3352 | let model = plugins_model(&app, Locale::En); |
| 3353 | let row = model |
| 3354 | .groups |
| 3355 | .iter() |
| 3356 | .flat_map(|group| group.items.iter()) |
| 3357 | .find(|row| row.label == "computer-use") |
| 3358 | .expect("installed row"); |
| 3359 | |
| 3360 | // Both halves of the truth, in words a person uses for a switch. |
| 3361 | assert_eq!(row.state, "off · needs review", "state: {}", row.state); |
| 3362 | // The switch is offered even though the bundle is unreviewed: |
| 3363 | // `/plugin enable` routes through the capability review itself. |
| 3364 | assert!( |
| 3365 | matches!( |
| 3366 | &row.toggle, |
| 3367 | Some(ExtensionAction::Command { command, .. }) |
| 3368 | if command == "/plugin enable computer-use" |
| 3369 | ), |
| 3370 | "toggle: {:?}", |
| 3371 | row.toggle |
| 3372 | ); |
| 3373 | // And the verb on Enter is a verb, not the noun "inspect". |
| 3374 | assert!( |
| 3375 | matches!( |
| 3376 | &row.action, |
| 3377 | Some(ExtensionAction::Command { label, command, .. }) |
| 3378 | if label == "review" && command == "/plugin trust computer-use" |
| 3379 | ), |
| 3380 | "action: {:?}", |
| 3381 | row.action |
| 3382 | ); |
| 3383 | assert!( |
| 3384 | row.detail |
| 3385 | .contains("only after you review exactly what it can do"), |
| 3386 | "detail must explain the review, got: {}", |
| 3387 | row.detail |
| 3388 | ); |
| 3389 | } |
| 3390 | |
| 3391 | /// Space is the switch, on the row the founder could not turn on. |
| 3392 | #[test] |
| 3393 | fn space_runs_the_selected_rows_switch() { |
| 3394 | let _env = crate::test_support::lock_test_env(); |
| 3395 | let root = tempfile::tempdir().unwrap(); |
| 3396 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path()); |
| 3397 | let plugin_dir = root.path().join("plugins/computer-use"); |
| 3398 | std::fs::create_dir_all(&plugin_dir).unwrap(); |
| 3399 | #[cfg(unix)] |
| 3400 | std::fs::set_permissions( |
| 3401 | root.path().join("plugins"), |
| 3402 | std::os::unix::fs::PermissionsExt::from_mode(0o700), |
| 3403 | ) |
| 3404 | .unwrap(); |
| 3405 | std::fs::write( |
| 3406 | plugin_dir.join("plugin.json"), |
| 3407 | r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"computer-use","version":"1.0.0","description":"Locally installed fixture"}"#, |
| 3408 | ) |
| 3409 | .unwrap(); |
| 3410 | let registry = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv() |
| 3411 | .registry_for_workspace(root.path()); |
| 3412 | let app = App::new_with_plugin_registry( |
| 3413 | crate::tui::test_support::test_tui_options(root.path()), |
| 3414 | &codewhale_runtime::config::Config::default(), |
| 3415 | registry, |
| 3416 | ); |
| 3417 | let mut view = ExtensionsView::new(&app, ExtensionsTab::Plugins); |
| 3418 | assert_eq!( |
| 3419 | view.selected_item().map(|item| item.label.as_str()), |
| 3420 | Some("agent-teams"), |
| 3421 | "the Plugins tab lists the bundled Agent Teams plugin first" |
| 3422 | ); |
| 3423 | for _ in 0..4 { |
| 3424 | if view.selected_item().map(|item| item.label.as_str()) == Some("computer-use") { |
| 3425 | break; |
| 3426 | } |
| 3427 | let _ = view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); |
| 3428 | } |
| 3429 | assert_eq!( |
| 3430 | view.selected_item().map(|item| item.label.as_str()), |
| 3431 | Some("computer-use"), |
| 3432 | "navigating down selects the installed row" |
| 3433 | ); |
| 3434 | let action = view.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE)); |
| 3435 | assert!( |
| 3436 | matches!( |
| 3437 | action, |
| 3438 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { ref command, .. }) |
| 3439 | if command == "/plugin enable computer-use" |
| 3440 | ), |
| 3441 | "Space must run the row's switch, got {action:?}" |
| 3442 | ); |
| 3443 | } |
| 3444 | |
| 3445 | #[test] |
| 3446 | fn marketplace_installed_bundle_uses_local_metadata_and_review_action() { |
| 3447 | let _env = crate::test_support::lock_test_env(); |
| 3448 | let root = tempfile::tempdir().unwrap(); |
| 3449 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path()); |
| 3450 | let plugin_dir = root.path().join("plugins/computer-use"); |
| 3451 | std::fs::create_dir_all(&plugin_dir).unwrap(); |
| 3452 | #[cfg(unix)] |
| 3453 | std::fs::set_permissions( |
| 3454 | root.path().join("plugins"), |
| 3455 | std::os::unix::fs::PermissionsExt::from_mode(0o700), |
| 3456 | ) |
| 3457 | .unwrap(); |
| 3458 | std::fs::write( |
| 3459 | plugin_dir.join("plugin.json"), |
| 3460 | r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"computer-use","version":"1.0.0","description":"Locally installed fixture"}"#, |
| 3461 | ) |
| 3462 | .unwrap(); |
| 3463 | let registry = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv() |
| 3464 | .registry_for_workspace(root.path()); |
| 3465 | let app = App::new_with_plugin_registry( |
| 3466 | crate::tui::test_support::test_tui_options(root.path()), |
| 3467 | &codewhale_runtime::config::Config::default(), |
| 3468 | registry, |
| 3469 | ); |
| 3470 | let model = marketplace_model(&app, Locale::En); |
| 3471 | let group = model |
| 3472 | .groups |
| 3473 | .iter() |
| 3474 | .find(|group| group.id == "codewhale") |
| 3475 | .unwrap(); |
| 3476 | let row = group |
| 3477 | .items |
| 3478 | .iter() |
| 3479 | .find(|row| row.label == "computer-use") |
| 3480 | .unwrap(); |
| 3481 | let installed = app.plugin_registry.get("computer-use").unwrap(); |
| 3482 | assert_eq!( |
| 3483 | row.description, |
| 3484 | installed |
| 3485 | .manifest |
| 3486 | .plugin |
| 3487 | .description |
| 3488 | .clone() |
| 3489 | .unwrap_or_default() |
| 3490 | ); |
| 3491 | assert_eq!(row.state, plugin_row_state(Locale::En, installed)); |
| 3492 | // The exact-content review stacks on the panel so the confirmed |
| 3493 | // digest lands on a row that then re-reads its trust state. |
| 3494 | assert!( |
| 3495 | matches!(&row.action, Some(ExtensionAction::Command { command, disposition: RowActionDisposition::InPlace, .. }) if command == "/plugin trust computer-use") |
| 3496 | ); |
| 3497 | assert!(!installed.trusted()); |
| 3498 | assert!(!installed.enabled); |
| 3499 | assert!( |
| 3500 | group.items.iter().any(|row| matches!( |
| 3501 | &row.action, |
| 3502 | Some(ExtensionAction::Command { command, .. }) |
| 3503 | if command == "/plugin marketplace install codewhale whalewiki" |
| 3504 | )), |
| 3505 | "an absent catalog bundle should still offer installation" |
| 3506 | ); |
| 3507 | assert!( |
| 3508 | row.detail.contains("Staged (disabled until trusted)") |
| 3509 | && row.detail.contains("/plugin trust computer-use") |
| 3510 | && row.detail.contains("content hash"), |
| 3511 | "staged untrusted marketplace row must surface /plugin trust hash confirmation: {}", |
| 3512 | row.detail |
| 3513 | ); |
| 3514 | let installable_row = group |
| 3515 | .items |
| 3516 | .iter() |
| 3517 | .find(|item| { |
| 3518 | matches!( |
| 3519 | &item.action, |
| 3520 | Some(ExtensionAction::Command { command, .. }) |
| 3521 | if command == "/plugin marketplace install codewhale whalewiki" |
| 3522 | ) |
| 3523 | }) |
| 3524 | .expect("installable marketplace row"); |
| 3525 | assert!( |
| 3526 | installable_row.detail.contains("Enter stages disabled") |
| 3527 | && installable_row.detail.contains("/plugin trust whalewiki"), |
| 3528 | "available marketplace row must explain staged install and /plugin trust hash step: {}", |
| 3529 | installable_row.detail |
| 3530 | ); |
| 3531 | let plugins_tab = plugins_model(&app, Locale::En); |
| 3532 | let untrusted_plugin_row = plugins_tab |
| 3533 | .groups |
| 3534 | .iter() |
| 3535 | .flat_map(|g| &g.items) |
| 3536 | .find(|item| item.label == "computer-use") |
| 3537 | .expect("untrusted plugin row"); |
| 3538 | assert!( |
| 3539 | untrusted_plugin_row |
| 3540 | .detail |
| 3541 | .contains("/plugin trust computer-use") |
| 3542 | && untrusted_plugin_row.detail.contains("content hash"), |
| 3543 | "untrusted plugin row must surface /plugin trust hash confirmation: {}", |
| 3544 | untrusted_plugin_row.detail |
| 3545 | ); |
| 3546 | } |
| 3547 | |
| 3548 | #[test] |
| 3549 | fn mcp_item_action_for_stale_oauth_is_login() { |
| 3550 | let recovery = codewhale_engine::mcp::mcp_recovery_kind( |
| 3551 | true, |
| 3552 | true, |
| 3553 | false, |
| 3554 | Some("401 Unauthorized"), |
| 3555 | true, |
| 3556 | ) |
| 3557 | .expect("stale oauth needs recovery"); |
| 3558 | assert_eq!(recovery, McpRecoveryKind::Reauth); |
| 3559 | assert_eq!(recovery.slash_command("github"), "/mcp login github"); |
| 3560 | assert_eq!(tr(Locale::En, recovery.label_key()).as_ref(), "re-auth"); |
| 3561 | } |
| 3562 | |
| 3563 | #[test] |
| 3564 | fn a_healthy_server_offers_no_recovery_action() { |
| 3565 | // Founder live-test: "even the ones that are connected say diagnose |
| 3566 | // lol". Enabled, inspected, connected and erroring on nothing is not |
| 3567 | // a state anything repairs. |
| 3568 | assert_eq!( |
| 3569 | codewhale_engine::mcp::mcp_recovery_kind(true, true, true, None, false), |
| 3570 | None |
| 3571 | ); |
| 3572 | } |
| 3573 | |
| 3574 | #[test] |
| 3575 | fn mcp_item_action_for_disconnected_server_is_reconnect() { |
| 3576 | let recovery = codewhale_engine::mcp::mcp_recovery_kind(true, true, false, None, false) |
| 3577 | .expect("a disconnected server needs recovery"); |
| 3578 | assert_eq!(recovery, McpRecoveryKind::Reconnect); |
| 3579 | // The row names one server, so the command it runs must name it too: |
| 3580 | // reloading all of them leaves the row the user aimed at still pending |
| 3581 | // when the list returns, which reads as the key doing nothing. |
| 3582 | assert_eq!( |
| 3583 | recovery.slash_command("playwright"), |
| 3584 | "/mcp retry playwright" |
| 3585 | ); |
| 3586 | assert_eq!(tr(Locale::En, recovery.label_key()).as_ref(), "reconnect"); |
| 3587 | } |
| 3588 | |
| 3589 | /// Four distinct tones, four distinct inks, and none of them read out of |
| 3590 | /// a localized string — a screen that only colours correctly in English |
| 3591 | /// is not coloured. |
| 3592 | #[test] |
| 3593 | fn every_tone_paints_a_distinct_ink() { |
| 3594 | use codewhale_palette::ChromeInk; |
| 3595 | let theme = codewhale_palette::ThemeId::Whale.ui_theme(); |
| 3596 | let inks: Vec<ChromeInk> = [ |
| 3597 | ExtensionTone::Ready, |
| 3598 | ExtensionTone::Attention, |
| 3599 | ExtensionTone::Failure, |
| 3600 | ExtensionTone::Idle, |
| 3601 | ] |
| 3602 | .into_iter() |
| 3603 | .map(ExtensionTone::ink) |
| 3604 | .collect(); |
| 3605 | let colors: std::collections::BTreeSet<String> = inks |
| 3606 | .iter() |
| 3607 | .map(|ink| format!("{:?}", ink.color(&theme))) |
| 3608 | .collect(); |
| 3609 | assert_eq!( |
| 3610 | colors.len(), |
| 3611 | 4, |
| 3612 | "each tone must be visually separable: {inks:?}" |
| 3613 | ); |
| 3614 | assert_eq!(ExtensionTone::default(), ExtensionTone::Idle); |
| 3615 | } |
| 3616 | |
| 3617 | #[test] |
| 3618 | fn extensions_search_consumes_paste_while_focused() { |
| 3619 | let mut stack = crate::tui::views::ViewStack::new(); |
| 3620 | stack.push(ExtensionsView::from_snapshot_with_locale( |
| 3621 | ExtensionsSnapshot::default(), |
| 3622 | ExtensionsTab::Skills, |
| 3623 | Locale::En, |
| 3624 | )); |
| 3625 | assert!(!stack.handle_paste("outside search")); |
| 3626 | |
| 3627 | let key = |code| KeyEvent::new(code, KeyModifiers::NONE); |
| 3628 | stack.handle_key(key(KeyCode::Char('/'))); |
| 3629 | stack.handle_key(key(KeyCode::Char('n'))); |
| 3630 | assert!(stack.handle_paste("eedle\r\n")); |
| 3631 | |
| 3632 | let mut modal = stack.pop().unwrap(); |
| 3633 | let view = modal.as_any_mut().downcast_mut::<ExtensionsView>().unwrap(); |
| 3634 | assert_eq!(view.query, "needle"); |
| 3635 | } |
| 3636 | |
| 3637 | /// The grokbuild grammar: Tab / Shift+Tab move across the tab bar, even |
| 3638 | /// mid-search, and the query rides along to the new tab. |
| 3639 | #[test] |
| 3640 | fn tab_switches_tabs_and_keeps_the_search_query() { |
| 3641 | use crate::tui::views::ModalView; |
| 3642 | let mut view = ExtensionsView::from_snapshot_with_locale( |
| 3643 | ExtensionsSnapshot::default(), |
| 3644 | ExtensionsTab::Plugins, |
| 3645 | Locale::En, |
| 3646 | ); |
| 3647 | let key = |code| KeyEvent::new(code, KeyModifiers::NONE); |
| 3648 | view.handle_key(key(KeyCode::Char('/'))); |
| 3649 | view.handle_key(key(KeyCode::Char('g'))); |
| 3650 | assert_eq!(view.focus, ExtensionsFocus::Search); |
| 3651 | |
| 3652 | view.handle_key(key(KeyCode::Tab)); |
| 3653 | assert_eq!(view.active_tab, ExtensionsTab::Marketplace); |
| 3654 | assert_eq!(view.query, "g", "the query carries over to the new tab"); |
| 3655 | |
| 3656 | view.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT)); |
| 3657 | assert_eq!(view.active_tab, ExtensionsTab::Plugins); |
| 3658 | view.handle_key(key(KeyCode::BackTab)); |
| 3659 | assert_eq!(view.active_tab, ExtensionsTab::Hooks); |
| 3660 | |
| 3661 | // Wraps: the last tab's next is the first. |
| 3662 | view.set_tab(ExtensionsTab::Mcp); |
| 3663 | view.handle_key(key(KeyCode::Tab)); |
| 3664 | assert_eq!(view.active_tab, ExtensionsTab::Command); |
| 3665 | view.handle_key(key(KeyCode::Tab)); |
| 3666 | assert_eq!(view.active_tab, ExtensionsTab::Hooks); |
| 3667 | } |
| 3668 | |
| 3669 | fn mcp_row(name: &str, state: &str, detail: &str, action: ExtensionAction) -> ExtensionItem { |
| 3670 | ExtensionItem { |
| 3671 | id: name.into(), |
| 3672 | label: name.into(), |
| 3673 | description: String::new(), |
| 3674 | state: state.into(), |
| 3675 | tone: ExtensionTone::Attention, |
| 3676 | detail: detail.into(), |
| 3677 | action: Some(action), |
| 3678 | toggle: None, |
| 3679 | remove: None, |
| 3680 | } |
| 3681 | } |
| 3682 | |
| 3683 | fn login_row(name: &str) -> ExtensionItem { |
| 3684 | mcp_row( |
| 3685 | name, |
| 3686 | &crate::tui::session_boot::mcp_auth_required_state_label(Locale::En), |
| 3687 | "401 Unauthorized: the session is no longer accepted", |
| 3688 | ExtensionAction::Command { |
| 3689 | label: "re-auth".into(), |
| 3690 | command: McpRecoveryKind::Reauth.slash_command(name), |
| 3691 | disposition: RowActionDisposition::LeavePanel, |
| 3692 | }, |
| 3693 | ) |
| 3694 | } |
| 3695 | |
| 3696 | /// The founder's receipt (#5926): seven OAuth servers whose login |
| 3697 | /// expired and one that really failed. The expired logins lead in their |
| 3698 | /// own group with the login command on the row; the real failure keeps |
| 3699 | /// its reason; the connected server sorts last. |
| 3700 | #[test] |
| 3701 | fn mcp_rows_list_expired_logins_first_then_failures_with_their_reason() { |
| 3702 | let rows = vec![ |
| 3703 | mcp_row( |
| 3704 | "alpha", |
| 3705 | "connected", |
| 3706 | "3 tools", |
| 3707 | ExtensionAction::Status { |
| 3708 | label: "connected".into(), |
| 3709 | }, |
| 3710 | ), |
| 3711 | mcp_row( |
| 3712 | "supabase", |
| 3713 | "error", |
| 3714 | "OAuth token refresh failed: Failed to parse server response", |
| 3715 | ExtensionAction::Command { |
| 3716 | label: "diagnose".into(), |
| 3717 | command: McpRecoveryKind::Diagnose.slash_command("supabase"), |
| 3718 | disposition: RowActionDisposition::InPlace, |
| 3719 | }, |
| 3720 | ), |
| 3721 | login_row("slack"), |
| 3722 | login_row("stripe"), |
| 3723 | ]; |
| 3724 | let groups = mcp_groups(Locale::En, rows); |
| 3725 | let shape: Vec<(&str, Vec<&str>)> = groups |
| 3726 | .iter() |
| 3727 | .map(|group| { |
| 3728 | ( |
| 3729 | group.id.as_str(), |
| 3730 | group.items.iter().map(|item| item.label.as_str()).collect(), |
| 3731 | ) |
| 3732 | }) |
| 3733 | .collect(); |
| 3734 | assert_eq!( |
| 3735 | shape, |
| 3736 | vec![ |
| 3737 | ("login", vec!["slack", "stripe"]), |
| 3738 | ("attention", vec!["supabase"]), |
| 3739 | ("servers", vec!["alpha"]), |
| 3740 | ] |
| 3741 | ); |
| 3742 | assert_eq!(groups[0].label, "Needs login"); |
| 3743 | assert_eq!(groups[1].label, "Needs attention"); |
| 3744 | let slack = &groups[0].items[0]; |
| 3745 | assert_eq!( |
| 3746 | slack.action.as_ref().and_then(ExtensionAction::command), |
| 3747 | Some("/mcp login slack") |
| 3748 | ); |
| 3749 | assert!(!slack.state.contains("failed"), "{}", slack.state); |
| 3750 | assert_eq!( |
| 3751 | groups[1].items[0].detail, |
| 3752 | "OAuth token refresh failed: Failed to parse server response" |
| 3753 | ); |
| 3754 | } |
| 3755 | |
| 3756 | /// Opening `/mcp` lands on the first server that needs a login, so Enter |
| 3757 | /// is the login key, not a fold of the group heading. A tab without a |
| 3758 | /// login group but no items keeps the empty-state selection. |
| 3759 | #[test] |
| 3760 | fn mcp_tab_opens_on_the_first_login_row() { |
| 3761 | let mut snapshot = ExtensionsSnapshot::default(); |
| 3762 | snapshot.tabs[ExtensionsTab::Mcp.index()] = ExtensionsTabModel { |
| 3763 | groups: mcp_groups(Locale::En, vec![login_row("slack"), login_row("stripe")]), |
| 3764 | problem: None, |
| 3765 | }; |
| 3766 | let view = ExtensionsView::from_snapshot_with_locale( |
| 3767 | snapshot.clone(), |
| 3768 | ExtensionsTab::Mcp, |
| 3769 | Locale::En, |
| 3770 | ); |
| 3771 | assert_eq!(view.selected[ExtensionsTab::Mcp.index()], 1); |
| 3772 | let entries = view.visible_entries(); |
| 3773 | match entries[1] { |
| 3774 | VisibleEntry::Item(group, item) => { |
| 3775 | assert_eq!(group.id, MCP_LOGIN_GROUP_ID); |
| 3776 | assert_eq!(item.label, "slack"); |
| 3777 | assert_eq!( |
| 3778 | item.action.as_ref().and_then(ExtensionAction::command), |
| 3779 | Some("/mcp login slack") |
| 3780 | ); |
| 3781 | } |
| 3782 | other => panic!("expected the first login row, got {other:?}"), |
| 3783 | } |
| 3784 | |
| 3785 | let plain = ExtensionsView::from_snapshot_with_locale( |
| 3786 | ExtensionsSnapshot::default(), |
| 3787 | ExtensionsTab::Mcp, |
| 3788 | Locale::En, |
| 3789 | ); |
| 3790 | assert_eq!(plain.selected[ExtensionsTab::Mcp.index()], 0); |
| 3791 | } |
| 3792 | |
| 3793 | fn item_with_action(action: ExtensionAction) -> ExtensionItem { |
| 3794 | ExtensionItem { |
| 3795 | id: "row".into(), |
| 3796 | label: "row".into(), |
| 3797 | description: String::new(), |
| 3798 | state: "state".into(), |
| 3799 | tone: ExtensionTone::Idle, |
| 3800 | detail: "detail".into(), |
| 3801 | action: Some(action), |
| 3802 | toggle: None, |
| 3803 | remove: None, |
| 3804 | } |
| 3805 | } |
| 3806 | |
| 3807 | fn view_on_item(action: ExtensionAction) -> ExtensionsView { |
| 3808 | let mut snapshot = ExtensionsSnapshot::default(); |
| 3809 | snapshot.tabs[ExtensionsTab::Plugins.index()] = ExtensionsTabModel { |
| 3810 | groups: vec![ExtensionGroup { |
| 3811 | id: "g".into(), |
| 3812 | label: "g".into(), |
| 3813 | items: vec![item_with_action(action)], |
| 3814 | }], |
| 3815 | problem: None, |
| 3816 | }; |
| 3817 | let mut view = |
| 3818 | ExtensionsView::from_snapshot_with_locale(snapshot, ExtensionsTab::Plugins, Locale::En); |
| 3819 | // Land on the item, not its group heading. |
| 3820 | view.selected[ExtensionsTab::Plugins.index()] = 1; |
| 3821 | view |
| 3822 | } |
| 3823 | |
| 3824 | #[test] |
| 3825 | fn the_footer_sheds_row_hints_before_esc_close_at_every_width() { |
| 3826 | let mut view = view_on_item(ExtensionAction::Command { |
| 3827 | label: "diagnose".into(), |
| 3828 | command: "/mcp diagnose demo".into(), |
| 3829 | disposition: RowActionDisposition::InPlace, |
| 3830 | }); |
| 3831 | { |
| 3832 | let item = &mut view.snapshot.tabs[ExtensionsTab::Plugins.index()].groups[0].items[0]; |
| 3833 | item.toggle = Some(ExtensionAction::Command { |
| 3834 | label: "disable".into(), |
| 3835 | command: "/mcp disable demo".into(), |
| 3836 | disposition: RowActionDisposition::InPlace, |
| 3837 | }); |
| 3838 | item.remove = Some(ExtensionAction::Command { |
| 3839 | label: "remove".into(), |
| 3840 | command: "/mcp remove demo".into(), |
| 3841 | disposition: RowActionDisposition::InPlace, |
| 3842 | }); |
| 3843 | } |
| 3844 | let footer = |width: u16| { |
| 3845 | let screen = view.render_text_for_test(width, 24); |
| 3846 | screen.lines().nth(22).unwrap_or_default().to_string() |
| 3847 | }; |
| 3848 | for width in 60..=120u16 { |
| 3849 | let footer = footer(width); |
| 3850 | assert!(footer.contains("Enter diagnose"), "{width}: {footer}"); |
| 3851 | assert!(footer.contains("Esc close"), "{width}: {footer}"); |
| 3852 | } |
| 3853 | assert_eq!( |
| 3854 | footer(80).trim_matches(['│', ' ']), |
| 3855 | "Tab filters · Enter diagnose · Space disable · / search · Esc close" |
| 3856 | ); |
| 3857 | assert!(footer(120).contains("↑↓ move") && footer(120).contains("d remove")); |
| 3858 | } |
| 3859 | |
| 3860 | /// T10: right-click used to arm the row's removal and a second one ran |
| 3861 | /// it, with no menu ever shown. It now opens the row's menu; removal is |
| 3862 | /// its last entry, behind the menu's own confirm, and only the confirmed |
| 3863 | /// entry emits the remove command. |
| 3864 | #[test] |
| 3865 | fn right_click_opens_a_row_menu_instead_of_removing() { |
| 3866 | let mut view = view_on_item(ExtensionAction::Command { |
| 3867 | label: "enable".into(), |
| 3868 | command: "/mcp enable demo".into(), |
| 3869 | disposition: RowActionDisposition::InPlace, |
| 3870 | }); |
| 3871 | { |
| 3872 | let item = &mut view.snapshot.tabs[ExtensionsTab::Plugins.index()].groups[0].items[0]; |
| 3873 | item.toggle = Some(ExtensionAction::Command { |
| 3874 | label: "disable".into(), |
| 3875 | command: "/mcp disable demo".into(), |
| 3876 | disposition: RowActionDisposition::InPlace, |
| 3877 | }); |
| 3878 | item.remove = Some(ExtensionAction::Command { |
| 3879 | label: "remove".into(), |
| 3880 | command: "/mcp remove demo".into(), |
| 3881 | disposition: RowActionDisposition::InPlace, |
| 3882 | }); |
| 3883 | } |
| 3884 | let area = Rect::new(0, 0, 100, 30); |
| 3885 | view.render(area, &mut Buffer::empty(area)); |
| 3886 | let hit = view |
| 3887 | .hits |
| 3888 | .borrow() |
| 3889 | .rows |
| 3890 | .iter() |
| 3891 | .find(|(_, row)| *row == 1) |
| 3892 | .map(|(rect, _)| *rect) |
| 3893 | .expect("the item row is painted"); |
| 3894 | let right_click = MouseEvent { |
| 3895 | kind: MouseEventKind::Down(MouseButton::Right), |
| 3896 | column: hit.x + 1, |
| 3897 | row: hit.y, |
| 3898 | modifiers: KeyModifiers::NONE, |
| 3899 | }; |
| 3900 | |
| 3901 | for _ in 0..2 { |
| 3902 | let ViewAction::Emit(ViewEvent::OpenContextMenu { title, entries, .. }) = |
| 3903 | view.handle_mouse(right_click) |
| 3904 | else { |
| 3905 | panic!("right-click must open the row menu"); |
| 3906 | }; |
| 3907 | assert_eq!(title, "row"); |
| 3908 | let labels: Vec<&str> = entries.iter().map(|e| e.label.as_str()).collect(); |
| 3909 | assert_eq!(labels, ["Enable", "Open details", "Disable", "Remove…"]); |
| 3910 | assert!(entries[0].primary); |
| 3911 | let remove = entries.last().unwrap(); |
| 3912 | assert!(remove.confirm_label.is_some(), "removal is confirmed"); |
| 3913 | assert!(view.pending_remove.is_none(), "right-click arms nothing"); |
| 3914 | } |
| 3915 | |
| 3916 | match view.run_menu_verb("row", crate::tui::views::ExtensionMenuVerb::Remove) { |
| 3917 | Some(ViewAction::Emit(ViewEvent::ExecutePanelCommand { command, .. })) => { |
| 3918 | assert_eq!(command, "/mcp remove demo"); |
| 3919 | } |
| 3920 | other => panic!("the confirmed entry removes the row, got {other:?}"), |
| 3921 | } |
| 3922 | assert!( |
| 3923 | view.run_menu_verb("gone", crate::tui::views::ExtensionMenuVerb::Remove) |
| 3924 | .is_none(), |
| 3925 | "a row that left the list is reported, not guessed at" |
| 3926 | ); |
| 3927 | } |
| 3928 | |
| 3929 | /// The defect: every row closed the panel and dropped its command into |
| 3930 | /// the transcript. A mutation runs in place — the event carries the |
| 3931 | /// command, and `Emit` (not `EmitAndClose`) is what keeps the panel. |
| 3932 | #[test] |
| 3933 | fn in_place_row_action_emits_without_closing() { |
| 3934 | let mut view = view_on_item(ExtensionAction::Command { |
| 3935 | label: "enable".into(), |
| 3936 | command: "/plugin enable demo".into(), |
| 3937 | disposition: RowActionDisposition::InPlace, |
| 3938 | }); |
| 3939 | match view.activate_selected() { |
| 3940 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 3941 | command, |
| 3942 | pager_title, |
| 3943 | }) => { |
| 3944 | assert_eq!(command, "/plugin enable demo"); |
| 3945 | assert_eq!(pager_title, None); |
| 3946 | } |
| 3947 | other => panic!("expected an in-place command, got {other:?}"), |
| 3948 | } |
| 3949 | } |
| 3950 | |
| 3951 | /// An inspect row keeps the panel open and asks for its text output in a |
| 3952 | /// pager stacked on the panel — the detail belongs to the row, not to a |
| 3953 | /// transcript dump behind the modal. |
| 3954 | #[test] |
| 3955 | fn inspect_row_action_pages_its_output_in_place() { |
| 3956 | let mut view = view_on_item(ExtensionAction::Command { |
| 3957 | label: "open".into(), |
| 3958 | command: "/plugin show demo".into(), |
| 3959 | disposition: RowActionDisposition::InPlacePager, |
| 3960 | }); |
| 3961 | match view.activate_selected() { |
| 3962 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { |
| 3963 | command, |
| 3964 | pager_title, |
| 3965 | }) => { |
| 3966 | assert_eq!(command, "/plugin show demo"); |
| 3967 | assert_eq!(pager_title.as_deref(), Some("row")); |
| 3968 | } |
| 3969 | other => panic!("expected a paged inspect, got {other:?}"), |
| 3970 | } |
| 3971 | } |
| 3972 | |
| 3973 | /// A flow that owns another surface — a login, an editor, the composer's |
| 3974 | /// trust token — still yields the panel. |
| 3975 | #[test] |
| 3976 | fn leave_panel_row_action_still_closes() { |
| 3977 | let mut view = view_on_item(ExtensionAction::Command { |
| 3978 | label: "re-auth".into(), |
| 3979 | command: "/mcp login github".into(), |
| 3980 | disposition: RowActionDisposition::LeavePanel, |
| 3981 | }); |
| 3982 | match view.activate_selected() { |
| 3983 | ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected { |
| 3984 | action: CommandPaletteAction::ExecuteCommand { command }, |
| 3985 | }) => assert_eq!(command, "/mcp login github"), |
| 3986 | other => panic!("expected the panel to yield, got {other:?}"), |
| 3987 | } |
| 3988 | } |
| 3989 | |
| 3990 | /// A refresh swaps the read model without disturbing the session: tab, |
| 3991 | /// query, selection, and folds all survive, and the new MCP generation |
| 3992 | /// the poll compares against rides along. |
| 3993 | #[test] |
| 3994 | fn refresh_preserves_view_state_and_tracks_generation() { |
| 3995 | let mut view = view_on_item(ExtensionAction::Command { |
| 3996 | label: "enable".into(), |
| 3997 | command: "/plugin enable demo".into(), |
| 3998 | disposition: RowActionDisposition::InPlace, |
| 3999 | }); |
| 4000 | view.query = "de".into(); |
| 4001 | let mut fresh = ExtensionsSnapshot { |
| 4002 | mcp_generation: 7, |
| 4003 | mcp_initializing: true, |
| 4004 | ..ExtensionsSnapshot::default() |
| 4005 | }; |
| 4006 | fresh.tabs[ExtensionsTab::Plugins.index()] = ExtensionsTabModel { |
| 4007 | groups: vec![ExtensionGroup { |
| 4008 | id: "g".into(), |
| 4009 | label: "g".into(), |
| 4010 | items: vec![item_with_action(ExtensionAction::Status { |
| 4011 | label: "enabled".into(), |
| 4012 | })], |
| 4013 | }], |
| 4014 | problem: None, |
| 4015 | }; |
| 4016 | view.refresh_snapshot(fresh); |
| 4017 | assert_eq!(view.active_tab, ExtensionsTab::Plugins); |
| 4018 | assert_eq!(view.query, "de"); |
| 4019 | assert_eq!(view.snapshot.mcp_generation, 7); |
| 4020 | assert!(view.snapshot.mcp_initializing); |
| 4021 | // The refreshed row's action is the new model's, not the stale one. |
| 4022 | let entries = view.visible_entries(); |
| 4023 | match entries[view.selected[ExtensionsTab::Plugins.index()]] { |
| 4024 | VisibleEntry::Item(_, item) => { |
| 4025 | assert!(matches!(item.action, Some(ExtensionAction::Status { .. }))); |
| 4026 | } |
| 4027 | other => panic!("expected the refreshed item, got {other:?}"), |
| 4028 | } |
| 4029 | } |
| 4030 | |
| 4031 | /// U09-05: a refresh that reorders the list keeps the selection on the |
| 4032 | /// same entity, so a later toggle acts on the row the user chose — never |
| 4033 | /// on whatever slid into the old index. |
| 4034 | #[test] |
| 4035 | fn refresh_keeps_selection_on_the_same_entity_when_rows_reorder() { |
| 4036 | fn row(id: &str) -> ExtensionItem { |
| 4037 | ExtensionItem { |
| 4038 | id: id.into(), |
| 4039 | label: id.into(), |
| 4040 | toggle: Some(ExtensionAction::Command { |
| 4041 | label: "disable".into(), |
| 4042 | command: format!("/plugin disable {id}"), |
| 4043 | disposition: RowActionDisposition::InPlace, |
| 4044 | }), |
| 4045 | ..item_with_action(ExtensionAction::Status { |
| 4046 | label: "enabled".into(), |
| 4047 | }) |
| 4048 | } |
| 4049 | } |
| 4050 | fn snapshot(order: &[&str]) -> ExtensionsSnapshot { |
| 4051 | let mut snapshot = ExtensionsSnapshot::default(); |
| 4052 | snapshot.tabs[ExtensionsTab::Plugins.index()] = ExtensionsTabModel { |
| 4053 | groups: vec![ExtensionGroup { |
| 4054 | id: "g".into(), |
| 4055 | label: "g".into(), |
| 4056 | items: order.iter().map(|id| row(id)).collect(), |
| 4057 | }], |
| 4058 | problem: None, |
| 4059 | }; |
| 4060 | snapshot |
| 4061 | } |
| 4062 | let mut view = ExtensionsView::from_snapshot_with_locale( |
| 4063 | snapshot(&["alpha", "beta"]), |
| 4064 | ExtensionsTab::Plugins, |
| 4065 | Locale::En, |
| 4066 | ); |
| 4067 | // Group heading, alpha, beta: select beta. |
| 4068 | view.selected[ExtensionsTab::Plugins.index()] = 2; |
| 4069 | assert_eq!( |
| 4070 | view.selected_item().map(|item| item.id.as_str()), |
| 4071 | Some("beta") |
| 4072 | ); |
| 4073 | |
| 4074 | view.refresh_snapshot(snapshot(&["beta", "alpha"])); |
| 4075 | assert_eq!( |
| 4076 | view.selected_item().map(|item| item.id.as_str()), |
| 4077 | Some("beta") |
| 4078 | ); |
| 4079 | match view.toggle_selected() { |
| 4080 | ViewAction::Emit(ViewEvent::ExecutePanelCommand { command, .. }) => { |
| 4081 | assert_eq!(command, "/plugin disable beta"); |
| 4082 | } |
| 4083 | other => panic!("expected the toggle command, got {other:?}"), |
| 4084 | } |
| 4085 | |
| 4086 | // A selected entity that is gone falls back to the clamped row. |
| 4087 | view.refresh_snapshot(snapshot(&["alpha"])); |
| 4088 | assert_eq!( |
| 4089 | view.selected_item().map(|item| item.id.as_str()), |
| 4090 | Some("alpha") |
| 4091 | ); |
| 4092 | } |
| 4093 | |
| 4094 | #[test] |
| 4095 | fn command_filter_lists_hand_written_commands_and_omits_plugin_commands() { |
| 4096 | let _env = crate::test_support::lock_test_env(); |
| 4097 | let root = tempfile::tempdir().unwrap(); |
| 4098 | let home = root.path().join("home"); |
| 4099 | let codewhale_home = home.join(".codewhale"); |
| 4100 | let workspace = root.path().join("workspace"); |
| 4101 | std::fs::create_dir_all(codewhale_home.join("commands")).unwrap(); |
| 4102 | std::fs::create_dir_all(workspace.join(".codewhale/commands")).unwrap(); |
| 4103 | let _home = crate::test_support::EnvVarGuard::set("HOME", &home); |
| 4104 | let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 4105 | let _cw_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 4106 | crate::test_support::trust_workspace(&workspace); |
| 4107 | |
| 4108 | std::fs::write( |
| 4109 | codewhale_home.join("commands/personal.md"), |
| 4110 | "---\ndescription: Personal checklist\nusage: /personal <target>\naliases: pcheck\n---\nCheck $ARGUMENTS\n", |
| 4111 | ) |
| 4112 | .unwrap(); |
| 4113 | std::fs::write( |
| 4114 | workspace.join(".codewhale/commands/deploy.md"), |
| 4115 | "---\ndescription: Project deploy helper\n---\nDeploy now\n", |
| 4116 | ) |
| 4117 | .unwrap(); |
| 4118 | std::fs::write( |
| 4119 | workspace.join(".codewhale/commands/secret.md"), |
| 4120 | "---\nhidden: true\n---\nHidden\n", |
| 4121 | ) |
| 4122 | .unwrap(); |
| 4123 | |
| 4124 | let plugin_dir = workspace.join(".codewhale/plugins/bundle"); |
| 4125 | std::fs::create_dir_all(plugin_dir.join("commands")).unwrap(); |
| 4126 | std::fs::write( |
| 4127 | plugin_dir.join("plugin.toml"), |
| 4128 | "schema_version = 1\n[plugin]\nname = \"bundle\"\nversion = \"1.0.0\"\n[commands]\npath = \"commands\"\n", |
| 4129 | ) |
| 4130 | .unwrap(); |
| 4131 | std::fs::write( |
| 4132 | plugin_dir.join("commands/ship.md"), |
| 4133 | "---\ndescription: Plugin command\n---\nShip it\n", |
| 4134 | ) |
| 4135 | .unwrap(); |
| 4136 | |
| 4137 | let mut registry = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv() |
| 4138 | .registry_for_workspace(&workspace); |
| 4139 | let registry_mut = std::sync::Arc::make_mut(&mut registry); |
| 4140 | registry_mut.trust("bundle").unwrap(); |
| 4141 | registry_mut.enable("bundle").unwrap(); |
| 4142 | crate::commands::user_registry::install_plugin_registry(&workspace, ®istry); |
| 4143 | |
| 4144 | let app = App::new_with_plugin_registry( |
| 4145 | crate::tui::test_support::test_tui_options(&workspace), |
| 4146 | &codewhale_runtime::config::Config::default(), |
| 4147 | registry, |
| 4148 | ); |
| 4149 | let mut view = ExtensionsView::new(&app, ExtensionsTab::Command); |
| 4150 | let model = view.snapshot.tab(ExtensionsTab::Command); |
| 4151 | assert_eq!(model.groups.len(), 2); |
| 4152 | assert_eq!(model.groups[0].id, "user"); |
| 4153 | assert_eq!(model.groups[0].items.len(), 1); |
| 4154 | assert_eq!(model.groups[0].items[0].label, "/personal"); |
| 4155 | assert_eq!(model.groups[0].items[0].description, "Personal checklist"); |
| 4156 | assert!( |
| 4157 | model.groups[0].items[0] |
| 4158 | .detail |
| 4159 | .contains("/personal <target>") |
| 4160 | ); |
| 4161 | assert!(model.groups[0].items[0].detail.contains("/pcheck")); |
| 4162 | |
| 4163 | assert_eq!(model.groups[1].id, "workspace"); |
| 4164 | assert_eq!(model.groups[1].items.len(), 1); |
| 4165 | assert_eq!(model.groups[1].items[0].label, "/deploy"); |
| 4166 | |
| 4167 | let all_labels: Vec<&str> = model |
| 4168 | .groups |
| 4169 | .iter() |
| 4170 | .flat_map(|group| group.items.iter().map(|item| item.label.as_str())) |
| 4171 | .collect(); |
| 4172 | assert!(!all_labels.contains(&"/ship")); |
| 4173 | assert!(!all_labels.contains(&"/secret")); |
| 4174 | |
| 4175 | let ViewAction::Emit(ViewEvent::OpenTextPager { title, content }) = |
| 4176 | view.activate_selected() |
| 4177 | else { |
| 4178 | panic!("activating a command row must open its details pager without running a turn"); |
| 4179 | }; |
| 4180 | assert_eq!(title, "/personal"); |
| 4181 | assert!(content.contains("Personal checklist")); |
| 4182 | } |
| 4183 | |
| 4184 | #[test] |
| 4185 | fn plugins_screen_row_says_turned_on_by_the_agent() { |
| 4186 | use codewhale_plugins::host_services::{ |
| 4187 | AgentApproval, AgentPosture, PersonVia, PluginApprover, ReviewApproval, |
| 4188 | }; |
| 4189 | |
| 4190 | let root = tempfile::tempdir().unwrap(); |
| 4191 | let home = root.path().join("home"); |
| 4192 | let workspace = root.path().join("project"); |
| 4193 | let other_workspace = root.path().join("otherproject"); |
| 4194 | for dir in [&home, &workspace, &other_workspace] { |
| 4195 | std::fs::create_dir_all(dir).unwrap(); |
| 4196 | } |
| 4197 | let _home = crate::test_support::SealedHome::at(&home); |
| 4198 | let ctx = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv(); |
| 4199 | for (dir_root, name) in [ |
| 4200 | (workspace.join(".codewhale/plugins"), "ag"), |
| 4201 | (workspace.join(".codewhale/plugins"), "cmd"), |
| 4202 | (workspace.join(".codewhale/plugins"), "pers"), |
| 4203 | (ctx.user_plugins_dir().to_path_buf(), "other"), |
| 4204 | ] { |
| 4205 | let skill = dir_root.join(name).join("skills/hello"); |
| 4206 | std::fs::create_dir_all(&skill).unwrap(); |
| 4207 | std::fs::write( |
| 4208 | dir_root.join(name).join("plugin.toml"), |
| 4209 | format!( |
| 4210 | "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n" |
| 4211 | ), |
| 4212 | ) |
| 4213 | .unwrap(); |
| 4214 | std::fs::write( |
| 4215 | skill.join("SKILL.md"), |
| 4216 | "---\nname: hello\ndescription: hi\n---\nbody\n", |
| 4217 | ) |
| 4218 | .unwrap(); |
| 4219 | } |
| 4220 | #[cfg(unix)] |
| 4221 | { |
| 4222 | use std::os::unix::fs::PermissionsExt as _; |
| 4223 | std::fs::set_permissions( |
| 4224 | ctx.user_plugins_dir(), |
| 4225 | std::fs::Permissions::from_mode(0o700), |
| 4226 | ) |
| 4227 | .unwrap(); |
| 4228 | } |
| 4229 | { |
| 4230 | let mut other_reg = ctx.registry_for_workspace(&other_workspace); |
| 4231 | let other_ws_str = other_reg.workspace().to_string_lossy().into_owned(); |
| 4232 | let agent_elsewhere = PluginApprover::Agent(AgentApproval { |
| 4233 | posture: AgentPosture::AutoReview, |
| 4234 | workspace: other_ws_str, |
| 4235 | thread_id: Some("th-other-screen-1".to_string()), |
| 4236 | turn_id: Some("turn-other-screen-1".to_string()), |
| 4237 | tool_call_id: Some("call-other-screen-1".to_string()), |
| 4238 | }); |
| 4239 | let other_hs = other_reg |
| 4240 | .host_service_review_for("other", &agent_elsewhere) |
| 4241 | .map(|review| review.token); |
| 4242 | std::sync::Arc::make_mut(&mut other_reg) |
| 4243 | .trust_and_enable_by( |
| 4244 | "other", |
| 4245 | ReviewApproval { |
| 4246 | approved_by: agent_elsewhere.clone(), |
| 4247 | host_services: other_hs, |
| 4248 | }, |
| 4249 | agent_elsewhere, |
| 4250 | ) |
| 4251 | .unwrap(); |
| 4252 | } |
| 4253 | let mut registry = ctx.registry_for_workspace(&workspace); |
| 4254 | let ws_str = registry.workspace().to_string_lossy().into_owned(); |
| 4255 | { |
| 4256 | let agent_here = PluginApprover::Agent(AgentApproval { |
| 4257 | posture: AgentPosture::FullAccess, |
| 4258 | workspace: ws_str, |
| 4259 | thread_id: Some("th-screen-1".to_string()), |
| 4260 | turn_id: Some("turn-screen-1".to_string()), |
| 4261 | tool_call_id: Some("call-screen-1".to_string()), |
| 4262 | }); |
| 4263 | let ag_hs = registry |
| 4264 | .host_service_review_for("ag", &agent_here) |
| 4265 | .map(|review| review.token); |
| 4266 | let agent_then_person = PluginApprover::Agent(AgentApproval { |
| 4267 | posture: AgentPosture::CommandLine, |
| 4268 | workspace: registry.workspace().to_string_lossy().into_owned(), |
| 4269 | thread_id: None, |
| 4270 | turn_id: None, |
| 4271 | tool_call_id: None, |
| 4272 | }); |
| 4273 | let pers_hs = registry |
| 4274 | .host_service_review_for("pers", &agent_then_person) |
| 4275 | .map(|review| review.token); |
| 4276 | let reg = std::sync::Arc::make_mut(&mut registry); |
| 4277 | reg.trust_and_enable_by( |
| 4278 | "ag", |
| 4279 | ReviewApproval { |
| 4280 | approved_by: agent_here.clone(), |
| 4281 | host_services: ag_hs, |
| 4282 | }, |
| 4283 | agent_here, |
| 4284 | ) |
| 4285 | .unwrap(); |
| 4286 | reg.trust_and_enable_by( |
| 4287 | "cmd", |
| 4288 | ReviewApproval { |
| 4289 | approved_by: PluginApprover::CommandLine, |
| 4290 | host_services: None, |
| 4291 | }, |
| 4292 | PluginApprover::CommandLine, |
| 4293 | ) |
| 4294 | .unwrap(); |
| 4295 | reg.trust_reviewed( |
| 4296 | "pers", |
| 4297 | ReviewApproval { |
| 4298 | approved_by: agent_then_person, |
| 4299 | host_services: pers_hs, |
| 4300 | }, |
| 4301 | ) |
| 4302 | .unwrap(); |
| 4303 | reg.enable_by("pers", PluginApprover::person(PersonVia::App)) |
| 4304 | .unwrap(); |
| 4305 | } |
| 4306 | let app = App::new_with_plugin_registry( |
| 4307 | crate::tui::test_support::test_tui_options(&workspace), |
| 4308 | &codewhale_runtime::config::Config::default(), |
| 4309 | registry, |
| 4310 | ); |
| 4311 | let model = plugins_model(&app, Locale::En); |
| 4312 | let find_item = |name: &str| { |
| 4313 | model |
| 4314 | .groups |
| 4315 | .iter() |
| 4316 | .flat_map(|group| &group.items) |
| 4317 | .find(|item| item.label == name) |
| 4318 | .unwrap_or_else(|| panic!("missing item {name}")) |
| 4319 | }; |
| 4320 | let ag = find_item("ag"); |
| 4321 | assert_eq!( |
| 4322 | ag.state, |
| 4323 | "on · turned on by the agent · not reviewed by you" |
| 4324 | ); |
| 4325 | assert_eq!(ag.tone, ExtensionTone::Attention); |
| 4326 | assert!(ag.detail.contains("not reviewed"), "{}", ag.detail); |
| 4327 | assert!( |
| 4328 | ag.detail.contains("approved by the agent in Full Access"), |
| 4329 | "{}", |
| 4330 | ag.detail |
| 4331 | ); |
| 4332 | assert!( |
| 4333 | ag.detail.contains("turned on by the agent in Full Access"), |
| 4334 | "{}", |
| 4335 | ag.detail |
| 4336 | ); |
| 4337 | assert!( |
| 4338 | ag.detail |
| 4339 | .contains(codewhale_plugins::host_services::AGENT_PROCESS_NOTE), |
| 4340 | "{}", |
| 4341 | ag.detail |
| 4342 | ); |
| 4343 | let other = find_item("other"); |
| 4344 | assert_eq!(other.state, "on only in otherproject"); |
| 4345 | assert_eq!(other.tone, ExtensionTone::Idle); |
| 4346 | let cmd = find_item("cmd"); |
| 4347 | assert_eq!(cmd.state, "on · command line (no review)"); |
| 4348 | assert_eq!(cmd.tone, ExtensionTone::Attention); |
| 4349 | let pers = find_item("pers"); |
| 4350 | assert_eq!(pers.state, "on · not reviewed by you · turned on by you"); |
| 4351 | assert_eq!(pers.tone, ExtensionTone::Attention); |
| 4352 | |
| 4353 | let view = ExtensionsView::new(&app, ExtensionsTab::Plugins); |
| 4354 | for width in [80, 120] { |
| 4355 | let screen = view.render_text_for_test(width, 24); |
| 4356 | assert!( |
| 4357 | screen.contains("on · turned on by the agent"), |
| 4358 | "{width} cols:\n{screen}" |
| 4359 | ); |
| 4360 | assert!( |
| 4361 | screen.contains("on only in otherproject"), |
| 4362 | "{width} cols:\n{screen}" |
| 4363 | ); |
| 4364 | assert!( |
| 4365 | screen.contains("on · command line (no review)"), |
| 4366 | "{width} cols:\n{screen}" |
| 4367 | ); |
| 4368 | assert!( |
| 4369 | screen.contains("on · not reviewed by you"), |
| 4370 | "{width} cols:\n{screen}" |
| 4371 | ); |
| 4372 | if width >= 120 { |
| 4373 | assert!( |
| 4374 | screen.contains("on · not reviewed by you · turned on by you"), |
| 4375 | "{width} cols:\n{screen}" |
| 4376 | ); |
| 4377 | } |
| 4378 | } |
| 4379 | } |
| 4380 | |
| 4381 | #[test] |
| 4382 | fn extensions_search_accepts_sanitized_paste_only_when_focused() { |
| 4383 | use crate::tui::views::ModalView; |
| 4384 | let mut view = ExtensionsView::from_snapshot_with_locale( |
| 4385 | ExtensionsSnapshot::default(), |
| 4386 | ExtensionsTab::Plugins, |
| 4387 | Locale::En, |
| 4388 | ); |
| 4389 | assert!(!view.handle_paste("git\r\n")); |
| 4390 | assert!(view.query.is_empty()); |
| 4391 | |
| 4392 | view.handle_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE)); |
| 4393 | assert!(view.handle_paste("git\thub\r\n")); |
| 4394 | assert_eq!(view.query, "git hub"); |
| 4395 | assert!(view.handle_paste("\n")); |
| 4396 | assert_eq!(view.query, "git hub"); |
| 4397 | } |
| 4398 | } |
| 4399 |