返回 CodeWhale
plugin_suggestions.rs
根目录 / crates / tui / src / tui / plugin_suggestions.rs
1 //! In-context plugin reminders: the send-time toast, the model-requested
2 //! review row, and idle catalog polling.
3 //!
4 //! 0.10.1 plugin offering policy ("helpful, not pushy"):
5 //! - The only unprompted surface is the send-time toast. There is no live
6 //! as-you-type matching.
7 //! - The review row appears only when the model calls `request_plugin_install`
8 //! (once per session), and only while contextual tips are on and the shared
9 //! per-session guidance budget has room.
10 //! - The row offers Review. Only that button opens the existing Extensions
11 //! inventory: installed bundles on Plugins, other suggestions on Marketplace.
12 //! Install, exact-content trust, and enable remain explicit row actions.
13 //! - Esc hides the row for this session only. "Don't suggest again" is the
14 //! explicit, persisted dismissal.
15
16 use std::collections::BTreeSet;
17 use std::time::{Duration, Instant};
18
19 use ratatui::buffer::Buffer;
20 use ratatui::layout::Rect;
21 use ratatui::style::Style;
22 use ratatui::text::{Line, Span};
23 use ratatui::widgets::{Block, Widget};
24 use unicode_width::UnicodeWidthStr;
25
26 use crate::tui::app::{App, StatusToast, StatusToastKind, StatusToastLevel};
27 use codewhale_localization::{MessageId, tr};
28 use codewhale_plugins::recommend::{
29 PluginNextStep, load_marketplace_candidates, match_plugin_for_draft,
30 };
31
32 const CATALOG_POLL_INTERVAL: Duration = Duration::from_secs(2);
33
34 pub const MCP_CONFIG_NUDGE: &str =
35 "MCP servers changed on disk. They apply when the session is idle, or run /mcp reload.";
36
37 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38 pub struct ExternalCatalogChange {
39 pub plugins: bool,
40 pub mcp: bool,
41 }
42
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub struct McpConfigWatch {
45 pub digest: Option<[u8; 32]>,
46 pub generation: u64,
47 pub notified: bool,
48 }
49
50 #[derive(Debug, Clone, PartialEq, Eq)]
51 pub enum PluginCtaPhase {
52 Hidden,
53 Matched { name: String },
54 }
55
56 impl PluginCtaPhase {
57 #[must_use]
58 pub fn is_visible(&self) -> bool {
59 matches!(self, Self::Matched { .. })
60 }
61
62 #[must_use]
63 pub fn matched_name(&self) -> Option<&str> {
64 match self {
65 Self::Hidden => None,
66 Self::Matched { name, .. } => Some(name.as_str()),
67 }
68 }
69 }
70
71 #[derive(Debug, Clone)]
72 pub struct PluginCtaState {
73 pub phase: PluginCtaPhase,
74 /// Lowercased names hidden from every proactive path: persisted "Don't
75 /// suggest again" choices plus this session's Esc dismissals.
76 pub dismissed: BTreeSet<String>,
77 }
78
79 impl Default for PluginCtaState {
80 fn default() -> Self {
81 Self {
82 phase: PluginCtaPhase::Hidden,
83 dismissed: BTreeSet::new(),
84 }
85 }
86 }
87
88 impl PluginCtaState {
89 pub(crate) fn from_settings(settings: &codewhale_runtime::settings::Settings) -> Self {
90 Self {
91 dismissed: settings
92 .dismissed_plugin_suggestions
93 .iter()
94 .map(|name| name.to_ascii_lowercase())
95 .collect(),
96 ..Self::default()
97 }
98 }
99 }
100
101 impl App {
102 /// When the user sends a task that matches an installed-but-idle plugin
103 /// or a locally added marketplace candidate, toast the next review step
104 /// once. Never installs, trusts, or enables anything.
105 pub fn maybe_nudge_plugin_for_prompt(&mut self, input: &str) -> bool {
106 if !self.behavioral_tips.guidance_available() {
107 return false;
108 }
109 let marketplace = load_marketplace_candidates(self.plugin_registry.state_path());
110 let Some(recommendation) = match_plugin_for_draft(
111 input,
112 self.plugin_registry.as_ref(),
113 &marketplace,
114 &self.plugin_cta.dismissed,
115 ) else {
116 return false;
117 };
118 let message_id = match recommendation.next_step {
119 PluginNextStep::Trust => MessageId::PluginPromptSuggestTrust,
120 PluginNextStep::Enable => MessageId::PluginPromptSuggestEnable,
121 PluginNextStep::MarketplaceInstall { .. } => MessageId::PluginPromptSuggestMarketplace,
122 PluginNextStep::AlreadyActive
123 | PluginNextStep::Inspect
124 | PluginNextStep::SourceInstall { .. } => return false,
125 };
126 let mut message = tr(self.ui_locale, message_id).replace("{name}", &recommendation.name);
127 if let PluginNextStep::MarketplaceInstall { catalog_id } = &recommendation.next_step {
128 message = message.replace("{catalog}", catalog_id);
129 }
130 if let Some(term) = recommendation.matched_term {
131 message.push_str(" · ");
132 message.push_str(
133 &tr(self.ui_locale, MessageId::PluginSuggestionReason).replace("{trigger}", &term),
134 );
135 }
136 self.behavioral_tips.record_guidance_impression();
137 let mut toast = StatusToast::new(message, StatusToastLevel::Info, Some(8_000));
138 toast.kind = StatusToastKind::PluginSuggestion;
139 self.push_status_toast_record(toast);
140 true
141 }
142
143 pub fn poll_external_catalog_changes(
144 &mut self,
145 engine_busy: bool,
146 ) -> Option<ExternalCatalogChange> {
147 let now = Instant::now();
148 if self
149 .last_plugin_catalog_poll
150 .is_some_and(|seen| now.duration_since(seen) < CATALOG_POLL_INTERVAL)
151 {
152 return None;
153 }
154 self.last_plugin_catalog_poll = Some(now);
155 let digest = codewhale_plugins::discovery::file_content_digest(&self.mcp_config_path);
156 let generation = self.mcp_snapshot_generation;
157 let watch = self.mcp_config_watch.get_or_insert(McpConfigWatch {
158 digest,
159 generation,
160 notified: false,
161 });
162 if watch.generation != generation {
163 *watch = McpConfigWatch {
164 digest,
165 generation,
166 notified: false,
167 };
168 }
169 let mcp = watch.digest != digest;
170 let mcp_unannounced = mcp && !std::mem::replace(&mut watch.notified, true);
171 let plugins = self.plugin_registry.on_disk_catalog_changed();
172 if !plugins && !mcp {
173 return None;
174 }
175 if engine_busy || self.pending_fresh_session.is_some() {
176 if plugins
177 && let Some(message) = codewhale_plugins::plugin_reload_nudge(
178 self.plugin_registry.as_ref(),
179 &mut self.plugin_reload_nudge_stamp,
180 )
181 {
182 self.push_status_toast(message, StatusToastLevel::Warning, Some(8_000));
183 self.needs_redraw = true;
184 }
185 if mcp_unannounced {
186 self.push_status_toast(MCP_CONFIG_NUDGE, StatusToastLevel::Warning, Some(8_000));
187 self.needs_redraw = true;
188 }
189 return None;
190 }
191 Some(ExternalCatalogChange { plugins, mcp })
192 }
193
194 pub fn mark_external_catalog_applied(&mut self) {
195 self.mcp_config_watch = Some(McpConfigWatch {
196 digest: codewhale_plugins::discovery::file_content_digest(&self.mcp_config_path),
197 generation: self.mcp_snapshot_generation,
198 notified: false,
199 });
200 }
201
202 #[must_use]
203 pub fn plugin_cta_row_height(&self) -> u16 {
204 u16::from(self.plugin_cta.phase.is_visible())
205 }
206
207 /// Esc: hide the row and skip this plugin for the rest of the session.
208 /// Persists nothing, so the next session may offer it again.
209 pub fn dismiss_plugin_cta_for_session(&mut self) -> bool {
210 let Some(name) = self
211 .plugin_cta
212 .phase
213 .matched_name()
214 .map(str::to_ascii_lowercase)
215 else {
216 return false;
217 };
218 self.plugin_cta.dismissed.insert(name);
219 self.plugin_cta.phase = PluginCtaPhase::Hidden;
220 self.needs_redraw = true;
221 true
222 }
223
224 /// "Don't suggest again": the explicit, persisted dismissal. Also hides
225 /// the row immediately for this session, even if saving fails.
226 pub fn dismiss_plugin_cta(&mut self) -> bool {
227 let Some(name) = self.plugin_cta.phase.matched_name().map(str::to_string) else {
228 return false;
229 };
230 let name = name.to_ascii_lowercase();
231 self.plugin_cta.dismissed.insert(name.clone());
232 self.plugin_cta.phase = PluginCtaPhase::Hidden;
233 self.needs_redraw = true;
234 if let Err(error) = codewhale_runtime::settings::Settings::transact_opt(|settings| {
235 Ok(settings
236 .dismissed_plugin_suggestions
237 .insert(name)
238 .then_some(()))
239 }) {
240 tracing::warn!(%error, "could not persist plugin suggestion dismissal");
241 self.push_status_toast(
242 tr(self.ui_locale, MessageId::PluginCtaDismissSaveFailed).into_owned(),
243 StatusToastLevel::Warning,
244 Some(8_000),
245 );
246 }
247 true
248 }
249
250 /// Human-initiated navigation to the existing inventory. Resolve the tab
251 /// from current installed facts, never from the model-returned command.
252 /// The inventory retains its own explicit install/review/enable actions.
253 #[must_use]
254 pub fn accept_plugin_cta_review(
255 &mut self,
256 ) -> Option<crate::tui::views::extensions::ExtensionsTab> {
257 let name = match &self.plugin_cta.phase {
258 PluginCtaPhase::Matched { name } => name.clone(),
259 PluginCtaPhase::Hidden => return None,
260 };
261 let tab = if self.plugin_registry.get(&name).is_some() {
262 crate::tui::views::extensions::ExtensionsTab::Plugins
263 } else {
264 crate::tui::views::extensions::ExtensionsTab::Marketplace
265 };
266 self.plugin_cta.dismissed.insert(name.to_ascii_lowercase());
267 self.plugin_cta.phase = PluginCtaPhase::Hidden;
268 self.needs_redraw = true;
269 Some(tab)
270 }
271
272 /// Model-requested review: show the review row and a toast naming the
273 /// command. Does not run it, so nothing is installed, trusted, or
274 /// enabled. Obeys the tips switch and draws from the shared per-session
275 /// guidance budget like every other proactive offer.
276 pub fn surface_plugin_review_request(&mut self, name: &str, command: &str) {
277 if name.trim().is_empty()
278 || command.trim().is_empty()
279 || !self.behavioral_tips.guidance_available()
280 || self
281 .plugin_cta
282 .dismissed
283 .contains(&name.to_ascii_lowercase())
284 {
285 return;
286 }
287 self.behavioral_tips.record_guidance_impression();
288 self.plugin_cta.phase = PluginCtaPhase::Matched {
289 name: name.to_string(),
290 };
291 let mut toast = StatusToast::new(command.to_string(), StatusToastLevel::Info, Some(8_000));
292 toast.kind = StatusToastKind::PluginSuggestion;
293 self.push_status_toast_record(toast);
294 self.needs_redraw = true;
295 }
296 }
297
298 /// Draw the one-line review row above the composer. No-op when hidden.
299 pub fn draw_plugin_cta(app: &mut App, area: Rect, buf: &mut Buffer) {
300 app.viewport.last_plugin_cta_area = None;
301 app.viewport.last_plugin_cta_review_area = None;
302 app.viewport.last_plugin_cta_dismiss_area = None;
303 let PluginCtaPhase::Matched { name } = &app.plugin_cta.phase else {
304 return;
305 };
306 let name = name.clone();
307 if area.height == 0 || area.width == 0 {
308 return;
309 }
310 let prompt = tr(app.ui_locale, MessageId::PluginCtaInstallPrompt).replace("{name}", &name);
311 let review = tr(app.ui_locale, MessageId::PluginCtaReview);
312 let dismiss = tr(app.ui_locale, MessageId::PluginCtaDismiss);
313 let review_label = format!("[{review}]");
314 let dismiss_label = format!("[{dismiss}]");
315 let review_w = review_label.width() as u16;
316 let dismiss_w = dismiss_label.width() as u16;
317 let gap = 1u16;
318 let right_w = review_w.saturating_add(gap).saturating_add(dismiss_w);
319 let bg = Style::default().bg(app.ui_theme.composer_bg);
320 Block::default().style(bg).render(area, buf);
321 let left_budget = if area.width > right_w.saturating_add(1) {
322 area.width - right_w - 1
323 } else {
324 area.width
325 };
326 let left = Line::from(vec![Span::styled(
327 prompt,
328 Style::default().fg(app.ui_theme.text_hint),
329 )]);
330 buf.set_line(area.x, area.y, &left, left_budget);
331 if area.width <= right_w {
332 app.viewport.last_plugin_cta_area = Some(area);
333 return;
334 }
335 let review_x = area.x + area.width - right_w;
336 let dismiss_x = review_x + review_w + gap;
337 buf.set_stringn(
338 review_x,
339 area.y,
340 &review_label,
341 usize::from(review_w),
342 Style::default().fg(app.ui_theme.accent_action),
343 );
344 buf.set_stringn(
345 dismiss_x,
346 area.y,
347 &dismiss_label,
348 usize::from(dismiss_w),
349 Style::default().fg(app.ui_theme.text_hint),
350 );
351 app.viewport.last_plugin_cta_area = Some(area);
352 app.viewport.last_plugin_cta_review_area = Some(Rect::new(review_x, area.y, review_w, 1));
353 app.viewport.last_plugin_cta_dismiss_area = Some(Rect::new(dismiss_x, area.y, dismiss_w, 1));
354 }
355
356 #[cfg(test)]
357 mod tests {
358 use super::*;
359 use crate::tui::app::TuiOptions;
360 use codewhale_localization::Locale;
361 use codewhale_runtime::config::Config;
362 use std::fs;
363 use tempfile::TempDir;
364
365 fn app_with_supabase_plugin() -> (App, TempDir, crate::test_support::EnvVarGuard) {
366 let root = TempDir::new().unwrap();
367 let home =
368 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home"));
369 let bundle = root.path().join(".codewhale/plugins/supabase");
370 fs::create_dir_all(&bundle).unwrap();
371 fs::write(
372 bundle.join("plugin.toml"),
373 "schema_version = 1\n[plugin]\nname = \"supabase\"\nversion = \"1.0.0\"\ndescription = \"Hosted Postgres and auth\"\nkeywords = [\"supabase\"]\n",
374 )
375 .unwrap();
376 let app_dir = root.path().join("app");
377 fs::create_dir_all(&app_dir).unwrap();
378 let options = TuiOptions {
379 config_path: Some(app_dir.join("config.toml")),
380 skills_dir: app_dir.join("skills"),
381 memory_path: app_dir.join("memory.md"),
382 mcp_config_path: app_dir.join("mcp.json"),
383 ..crate::tui::test_support::test_tui_options(root.path())
384 };
385 let discovery = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv();
386 let registry = discovery.registry_for_workspace(root.path());
387 let mut app = App::new_with_plugin_registry(options, &Config::default(), registry);
388 app.ui_locale = Locale::En;
389 (app, root, home)
390 }
391
392 #[test]
393 fn sending_a_supabase_prompt_toasts_trust_for_an_installed_idle_plugin() {
394 let _lock = crate::test_support::lock_test_env();
395 let (mut app, _root, _home) = app_with_supabase_plugin();
396
397 assert!(app.maybe_nudge_plugin_for_prompt("add supabase auth to login"));
398 assert_eq!(app.status_toasts.len(), 1);
399 assert!(
400 app.status_toasts[0].text.contains("/plugin trust supabase"),
401 "{}",
402 app.status_toasts[0].text
403 );
404 assert!(!app.maybe_nudge_plugin_for_prompt("add supabase auth to login"));
405 }
406
407 #[test]
408 fn optional_plugin_and_behavioral_guidance_share_one_session_budget() {
409 use crate::tui::behavioral_tips::BehavioralTip;
410 let _lock = crate::test_support::lock_test_env();
411 for plugin_first in [true, false] {
412 let (mut app, _root, _home) = app_with_supabase_plugin();
413 if plugin_first {
414 assert!(app.maybe_nudge_plugin_for_prompt("add supabase auth"));
415 assert!(!app.maybe_show_behavioral_tip(BehavioralTip::McpValidation));
416 } else {
417 assert!(app.maybe_show_behavioral_tip(BehavioralTip::McpValidation));
418 assert!(!app.maybe_nudge_plugin_for_prompt("add supabase auth"));
419 }
420 assert_eq!(app.status_toasts.len(), 1);
421 }
422 }
423
424 #[test]
425 fn tips_off_removes_every_plugin_offer_but_preserves_required_notices() {
426 let _lock = crate::test_support::lock_test_env();
427 let (mut app, _root, _home) = app_with_supabase_plugin();
428 app.set_contextual_tips_enabled(false);
429 assert!(!app.maybe_nudge_plugin_for_prompt("add supabase auth"));
430 app.surface_plugin_review_request("supabase", "/plugin trust supabase");
431 assert!(
432 !app.plugin_cta.phase.is_visible(),
433 "tips off: no review row, even when the model asks"
434 );
435 assert_eq!(app.plugin_cta_row_height(), 0);
436 assert!(app.status_toasts.is_empty());
437
438 app.set_contextual_tips_enabled(true);
439 app.surface_plugin_review_request("supabase", "/plugin trust supabase");
440 assert!(app.plugin_cta.phase.is_visible());
441 app.push_status_toast_record(
442 StatusToast::new("Review required", StatusToastLevel::Warning, None).for_action("a"),
443 );
444 app.push_status_toast("Keep this error", StatusToastLevel::Error, None);
445 app.set_contextual_tips_enabled(false);
446 assert!(
447 !app.plugin_cta.phase.is_visible(),
448 "turning tips off hides the row"
449 );
450 assert_eq!(app.status_toasts.len(), 2);
451 assert!(
452 app.status_toasts
453 .iter()
454 .all(|toast| toast.kind != StatusToastKind::PluginSuggestion)
455 );
456 app.set_contextual_tips_enabled(true);
457 assert!(
458 !app.maybe_nudge_plugin_for_prompt("add supabase auth"),
459 "reenabling must not reset the shared cap"
460 );
461 }
462
463 #[test]
464 fn model_requested_review_draws_from_the_shared_budget() {
465 let _lock = crate::test_support::lock_test_env();
466 let (mut app, _root, _home) = app_with_supabase_plugin();
467 assert!(app.maybe_nudge_plugin_for_prompt("add supabase auth"));
468 app.surface_plugin_review_request("supabase", "/plugin trust supabase");
469 assert!(
470 !app.plugin_cta.phase.is_visible(),
471 "the send-time toast already spent this session's budget"
472 );
473 }
474
475 #[test]
476 fn external_state_and_mcp_writes_apply_when_idle_and_toast_while_busy() {
477 let _lock = crate::test_support::lock_test_env();
478 let (mut app, _root, _home) = app_with_supabase_plugin();
479 assert_eq!(app.poll_external_catalog_changes(false), None);
480
481 let state_path = app.plugin_registry.state_path().unwrap().to_path_buf();
482 fs::create_dir_all(state_path.parent().unwrap()).unwrap();
483 fs::write(&state_path, "{\"version\":1,\"plugins\":{}}").unwrap();
484 fs::write(&app.mcp_config_path, "{\"servers\":{}}").unwrap();
485
486 app.last_plugin_catalog_poll = None;
487 assert_eq!(app.poll_external_catalog_changes(true), None);
488 let toasts = app
489 .status_toasts
490 .iter()
491 .map(|toast| toast.text.to_string())
492 .collect::<Vec<_>>();
493 assert!(toasts.iter().any(|text| text.contains("Plugins changed")));
494 assert!(
495 toasts
496 .iter()
497 .any(|text| text.contains("MCP servers changed"))
498 );
499
500 app.last_plugin_catalog_poll = None;
501 assert_eq!(
502 app.poll_external_catalog_changes(false),
503 Some(ExternalCatalogChange {
504 plugins: true,
505 mcp: true
506 })
507 );
508 app.mark_external_catalog_applied();
509 app.plugin_registry = app
510 .plugin_registry
511 .rediscover_for_workspace(&app.workspace.clone());
512 app.last_plugin_catalog_poll = None;
513 assert_eq!(app.poll_external_catalog_changes(false), None);
514 }
515
516 #[test]
517 fn typing_a_matching_draft_never_shows_a_row() {
518 let _lock = crate::test_support::lock_test_env();
519 let (mut app, _root, _home) = app_with_supabase_plugin();
520 app.input = "add supabase auth to login".to_string();
521 let _ = app.poll_external_catalog_changes(false);
522 assert!(!app.plugin_cta.phase.is_visible());
523 assert_eq!(app.plugin_cta_row_height(), 0);
524 }
525
526 #[test]
527 fn review_row_opens_installed_inventory_without_running_suggested_commands() {
528 let _lock = crate::test_support::lock_test_env();
529 for command in [
530 "/plugin trust supabase",
531 "/plugin enable supabase",
532 "/plugin marketplace install official supabase",
533 ] {
534 let (mut app, _root, _home) = app_with_supabase_plugin();
535 let before = app.plugin_registry.get("supabase").unwrap().clone();
536 app.surface_plugin_review_request("supabase", command);
537 assert_eq!(
538 app.plugin_cta.phase,
539 PluginCtaPhase::Matched {
540 name: "supabase".into(),
541 }
542 );
543 let area = Rect::new(0, 0, 140, 1);
544 let mut buffer = Buffer::empty(area);
545 draw_plugin_cta(&mut app, area, &mut buffer);
546 let row = buffer
547 .content
548 .iter()
549 .map(|cell| cell.symbol())
550 .collect::<String>();
551 assert!(row.contains("supabase"), "{row}");
552 assert!(row.contains("[Review]"), "{row}");
553 assert!(row.contains("[Don't suggest again]"), "{row}");
554 assert_eq!(
555 app.accept_plugin_cta_review(),
556 Some(crate::tui::views::extensions::ExtensionsTab::Plugins),
557 "accepting opens the installed inventory, never {command}"
558 );
559 let after = app.plugin_registry.get("supabase").unwrap();
560 assert_eq!(after.trust_status, before.trust_status);
561 assert_eq!(after.enabled, before.enabled);
562 assert_eq!(after.active(), before.active());
563 assert!(!app.plugin_cta.phase.is_visible());
564 }
565 }
566
567 #[test]
568 fn uninstalled_review_opens_marketplace_without_installing_or_running_commands() {
569 let _lock = crate::test_support::lock_test_env();
570 let (mut app, _root, _home) = app_with_supabase_plugin();
571 let before = app.plugin_registry.list().len();
572 app.surface_plugin_review_request("catalog-only", "/plugin enable supabase");
573 assert!(app.plugin_registry.get("catalog-only").is_none());
574 assert_eq!(
575 app.accept_plugin_cta_review(),
576 Some(crate::tui::views::extensions::ExtensionsTab::Marketplace)
577 );
578 assert!(app.plugin_registry.get("catalog-only").is_none());
579 assert_eq!(app.plugin_registry.list().len(), before);
580 assert!(!app.plugin_registry.get("supabase").unwrap().enabled);
581 assert_eq!(app.accept_plugin_cta_review(), None);
582 }
583
584 #[test]
585 fn esc_clears_a_draft_first_then_dismisses_for_the_session_only() {
586 use crate::tui::composer_ui::{EscapeAction, next_escape_action};
587 use codewhale_runtime::settings::Settings;
588 let _lock = crate::test_support::lock_test_env();
589 let (mut app, root, _home) = app_with_supabase_plugin();
590 app.surface_plugin_review_request("supabase", "/plugin trust supabase");
591 app.input = "half-written draft".into();
592 assert_eq!(next_escape_action(&app, false), EscapeAction::ClearInput);
593 app.input.clear();
594 assert_eq!(
595 next_escape_action(&app, false),
596 EscapeAction::DismissPluginCta
597 );
598
599 assert!(app.dismiss_plugin_cta_for_session());
600 assert!(!app.plugin_cta.phase.is_visible());
601 assert!(!app.maybe_nudge_plugin_for_prompt("add supabase auth"));
602 let saved = Settings::load_read_only().unwrap_or_default();
603 assert!(
604 saved.dismissed_plugin_suggestions.is_empty(),
605 "Esc persists nothing"
606 );
607 let restarted = App::new_with_plugin_registry(
608 crate::tui::test_support::test_tui_options(root.path()),
609 &Config::default(),
610 app.plugin_registry.clone(),
611 );
612 assert!(!restarted.plugin_cta.dismissed.contains("supabase"));
613 }
614
615 #[test]
616 fn dismissal_survives_restart_and_all_proactive_paths_preserving_settings() {
617 use codewhale_runtime::settings::Settings;
618 let _lock = crate::test_support::lock_test_env();
619 let (mut app, root, _home) = app_with_supabase_plugin();
620 Settings::transact(|settings| settings.set("max_history", "321")).unwrap();
621 app.surface_plugin_review_request("supabase", "/plugin trust supabase");
622 assert!(app.dismiss_plugin_cta());
623 let saved = Settings::load_read_only().unwrap();
624 assert_eq!(saved.max_input_history, 321);
625 assert!(saved.dismissed_plugin_suggestions.contains("supabase"));
626 // A freshly initialized App must hydrate the persisted preference.
627 let mut restarted = App::new_with_plugin_registry(
628 crate::tui::test_support::test_tui_options(root.path()),
629 &Config::default(),
630 app.plugin_registry.clone(),
631 );
632 assert!(!restarted.maybe_nudge_plugin_for_prompt("add supabase auth to login"));
633 restarted.surface_plugin_review_request("supabase", "/plugin trust supabase");
634 assert!(!restarted.plugin_cta.phase.is_visible());
635 assert!(
636 codewhale_plugins::recommend::lookup_reviewable_plugin(
637 "supabase",
638 restarted.plugin_registry.as_ref(),
639 &[],
640 )
641 .is_some(),
642 "manual plugin commands remain available"
643 );
644 }
645
646 #[test]
647 fn failed_dismissal_save_preserves_malformed_preferences_and_hides_this_session() {
648 let _lock = crate::test_support::lock_test_env();
649 let (mut app, root, _home) = app_with_supabase_plugin();
650 app.surface_plugin_review_request("supabase", "/plugin trust supabase");
651 let path = codewhale_runtime::settings::Settings::path().unwrap();
652 assert!(path.starts_with(root.path()));
653 fs::create_dir_all(path.parent().unwrap()).unwrap();
654 let malformed = "theme = [private_fixture_payload\n";
655 fs::write(&path, malformed).unwrap();
656 assert!(app.dismiss_plugin_cta());
657 assert_eq!(fs::read_to_string(&path).unwrap(), malformed);
658 assert!(!app.plugin_cta.phase.is_visible());
659 let toast = app.status_toasts.back().expect("save failure receipt");
660 assert!(toast.text.contains("could not save"));
661 assert!(!toast.text.contains("private_fixture_payload"));
662 }
663 }
664
664 lines RUST