返回 CodeWhale
skills_manager.rs
根目录 / crates / tui / src / tui / views / skills_manager.rs
1 //! Dedicated `/skills manage` manager — audit inventory + mutation actions.
2 //!
3 //! This view never writes files. Keys emit [`ViewEvent::SkillMutationRequested`];
4 //! the host runs [`codewhale_skills::mutation`] and rebuilds the view.
5
6 use std::cell::Cell;
7
8 use crossterm::event::{KeyCode, KeyEvent};
9 use ratatui::{
10 buffer::Buffer,
11 layout::Rect,
12 style::{Modifier, Style},
13 text::{Line, Span},
14 widgets::{Block, Borders, Clear, Paragraph, Widget, Wrap},
15 };
16 use unicode_segmentation::UnicodeSegmentation;
17
18 use super::{
19 ActionHint, EmptyState, ListDetailLayout, ModalKind, ModalView, ViewAction, ViewEvent,
20 render_modal_footer, render_underwater_surface, truncate_view_text,
21 };
22 use crate::tui::app::App;
23 use codewhale_localization::{Locale, MessageId, tr};
24 use codewhale_palette as palette;
25 use codewhale_skills::audit::{
26 AuditedSkill, AuditedSkillId, DigestState, IntegrityState, ParserState, PrecedenceState,
27 ProvenanceState, SkillActionKind, SkillAuditMode, SkillAuditSnapshot, SkillSourceKind,
28 TrustState, expand_owned_scan_to_compatible, scan_with_configured,
29 };
30 use codewhale_skills::mutation::{ConflictPolicy, SkillMutationRequest, SkillTargetScope};
31 use codewhale_skills::roots::SkillRootKind;
32 use codewhale_tui_kit::menu_style;
33
34 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
35 enum ManagerMode {
36 OwnedOnly,
37 Compatible,
38 }
39
40 impl ManagerMode {
41 fn audit_mode(self) -> SkillAuditMode {
42 match self {
43 Self::OwnedOnly => SkillAuditMode::OwnedOnly,
44 Self::Compatible => SkillAuditMode::Compatible,
45 }
46 }
47
48 fn label(self) -> &'static str {
49 match self {
50 Self::OwnedOnly => "owned",
51 Self::Compatible => "compatible",
52 }
53 }
54 }
55
56 #[derive(Debug, Clone, PartialEq, Eq)]
57 enum PendingConfirm {
58 Remove {
59 skill_id: AuditedSkillId,
60 digest: Option<String>,
61 },
62 ImportReplace {
63 skill_id: AuditedSkillId,
64 digest: String,
65 },
66 }
67
68 pub struct SkillsManagerView {
69 mode: ManagerMode,
70 skills: Vec<AuditedSkill>,
71 selected: usize,
72 detail_scroll: usize,
73 detail_max_scroll: Cell<usize>,
74 import_scope: SkillTargetScope,
75 pending: Option<PendingConfirm>,
76 status: Option<String>,
77 locale: Locale,
78 }
79
80 impl SkillsManagerView {
81 #[must_use]
82 pub fn new(app: &App) -> Self {
83 Self::from_scan(
84 app,
85 ManagerMode::OwnedOnly,
86 SkillTargetScope::Global,
87 None,
88 None,
89 )
90 }
91
92 #[must_use]
93 pub fn rebuild_preserving(
94 app: &App,
95 previous: &Self,
96 status: Option<String>,
97 focus: Option<&AuditedSkillId>,
98 ) -> Self {
99 let mut view = Self::from_scan(
100 app,
101 previous.mode,
102 previous.import_scope,
103 status,
104 focus.or_else(|| previous.selected_skill().map(|s| &s.id)),
105 );
106 view.detail_scroll = 0;
107 view
108 }
109
110 fn from_scan(
111 app: &App,
112 mode: ManagerMode,
113 import_scope: SkillTargetScope,
114 status: Option<String>,
115 focus: Option<&AuditedSkillId>,
116 ) -> Self {
117 let snap = scan_snapshot(app, mode);
118 let mut view = Self {
119 mode,
120 skills: snap.skills,
121 selected: 0,
122 detail_scroll: 0,
123 detail_max_scroll: Cell::new(usize::MAX),
124 import_scope,
125 pending: None,
126 status,
127 locale: app.ui_locale,
128 };
129 if let Some(id) = focus
130 && let Some(idx) = view.skills.iter().position(|s| &s.id == id)
131 {
132 view.selected = idx;
133 }
134 view.clamp_selection();
135 view
136 }
137
138 fn selected_skill(&self) -> Option<&AuditedSkill> {
139 self.skills.get(self.selected)
140 }
141
142 fn clamp_selection(&mut self) {
143 if self.skills.is_empty() {
144 self.selected = 0;
145 return;
146 }
147 self.selected = self.selected.min(self.skills.len() - 1);
148 }
149
150 fn move_sel(&mut self, delta: isize) {
151 if self.skills.is_empty() {
152 return;
153 }
154 let len = self.skills.len() as isize;
155 let next = (self.selected as isize + delta).rem_euclid(len) as usize;
156 self.selected = next;
157 self.detail_scroll = 0;
158 self.pending = None;
159 }
160
161 fn toggle_mode(&mut self, app: &App) {
162 let next_mode = match self.mode {
163 ManagerMode::OwnedOnly => ManagerMode::Compatible,
164 ManagerMode::Compatible => ManagerMode::OwnedOnly,
165 };
166 let focus = self.selected_skill().map(|s| s.id.clone());
167 let home = codewhale_paths::user_home();
168 let snap = if self.mode == ManagerMode::OwnedOnly {
169 expand_owned_scan_to_compatible(
170 &app.workspace,
171 home.as_deref(),
172 Some(&app.skills_dir),
173 &self.skills,
174 None,
175 )
176 } else {
177 scan_with_configured(
178 &app.workspace,
179 home.as_deref(),
180 Some(&app.skills_dir),
181 next_mode.audit_mode(),
182 None,
183 )
184 };
185 self.mode = next_mode;
186 self.skills = snap.skills;
187 self.pending = None;
188 self.detail_scroll = 0;
189 self.status = Some(format!("Scan mode: {}", self.mode.label()));
190 if let Some(id) = focus {
191 if let Some(idx) = self.skills.iter().position(|s| s.id == id) {
192 self.selected = idx;
193 } else {
194 self.selected = 0;
195 }
196 } else {
197 self.selected = 0;
198 }
199 self.clamp_selection();
200 }
201
202 fn cycle_import_scope(&mut self) {
203 self.import_scope = match self.import_scope {
204 SkillTargetScope::Global => SkillTargetScope::Project,
205 SkillTargetScope::Project => SkillTargetScope::Global,
206 };
207 self.status = Some(format!("Import target: {}", scope_label(self.import_scope)));
208 }
209
210 fn emit_action(&mut self, kind: SkillActionKind) -> ViewAction {
211 let Some(skill) = self.selected_skill().cloned() else {
212 return ViewAction::None;
213 };
214 if !skill.available_actions.contains(&kind) {
215 self.status = Some(format!(
216 "{} is not available for '{}'",
217 action_label(kind),
218 skill.name
219 ));
220 return ViewAction::None;
221 }
222
223 match kind {
224 SkillActionKind::Remove => {
225 let digest = match &skill.digest {
226 DigestState::Known(d) => Some(d.clone()),
227 DigestState::Unknown(_) => None,
228 };
229 self.pending = Some(PendingConfirm::Remove {
230 skill_id: skill.id.clone(),
231 digest,
232 });
233 self.status = Some(format!(
234 "Remove '{}'? Press Enter to confirm, Esc to cancel.",
235 skill.name
236 ));
237 ViewAction::None
238 }
239 SkillActionKind::Import => {
240 let DigestState::Known(digest) = &skill.digest else {
241 self.status = Some("Import requires a known package digest".into());
242 return ViewAction::None;
243 };
244 let want_kind = match self.import_scope {
245 SkillTargetScope::Project => SkillRootKind::CodeWhaleProject,
246 SkillTargetScope::Global => SkillRootKind::CodeWhaleGlobal,
247 };
248 // Only treat same-scope owned peers as replace conflicts — the
249 // mutation controller replaces inside `import_scope` alone.
250 let owned_conflict = self.skills.iter().any(|peer| {
251 peer.id.canonical_name == skill.id.canonical_name
252 && peer.root.is_writable_owned()
253 && peer.root.kind == want_kind
254 && peer.id != skill.id
255 && match &peer.digest {
256 DigestState::Known(other) => other != digest,
257 DigestState::Unknown(_) => true,
258 }
259 });
260 if owned_conflict {
261 self.pending = Some(PendingConfirm::ImportReplace {
262 skill_id: skill.id.clone(),
263 digest: digest.clone(),
264 });
265 self.status = Some(format!(
266 "'{}' conflicts with {} owned copy. Enter = replace, Esc = cancel.",
267 skill.name,
268 scope_label(self.import_scope)
269 ));
270 return ViewAction::None;
271 }
272 ViewAction::Emit(ViewEvent::SkillMutationRequested {
273 request: SkillMutationRequest::ImportExternal {
274 source_id: skill.id.clone(),
275 expected_digest: digest.clone(),
276 target: self.import_scope,
277 conflict_policy: ConflictPolicy::Reject,
278 },
279 })
280 }
281 SkillActionKind::Update => ViewAction::Emit(ViewEvent::SkillMutationRequested {
282 request: SkillMutationRequest::Update {
283 skill_id: skill.id.clone(),
284 expected_digest: known_digest(&skill),
285 },
286 }),
287 SkillActionKind::Trust => {
288 let Some(digest) = known_digest(&skill) else {
289 self.status = Some("Trust requires a known package digest".into());
290 return ViewAction::None;
291 };
292 ViewAction::Emit(ViewEvent::SkillMutationRequested {
293 request: SkillMutationRequest::Trust {
294 skill_id: skill.id.clone(),
295 expected_digest: digest,
296 },
297 })
298 }
299 SkillActionKind::Install => {
300 self.status = Some(
301 "Install from registry: /skill install [--project|--global] <spec>".into(),
302 );
303 ViewAction::None
304 }
305 }
306 }
307
308 fn confirm_pending(&mut self) -> ViewAction {
309 match self.pending.take() {
310 Some(PendingConfirm::Remove { skill_id, digest }) => {
311 ViewAction::Emit(ViewEvent::SkillMutationRequested {
312 request: SkillMutationRequest::Remove {
313 skill_id,
314 expected_digest: digest,
315 },
316 })
317 }
318 Some(PendingConfirm::ImportReplace { skill_id, digest }) => {
319 ViewAction::Emit(ViewEvent::SkillMutationRequested {
320 request: SkillMutationRequest::ImportExternal {
321 source_id: skill_id,
322 expected_digest: digest,
323 target: self.import_scope,
324 conflict_policy: ConflictPolicy::ReplaceConfirmed,
325 },
326 })
327 }
328 None => {
329 // Primary action for selection.
330 let Some(skill) = self.selected_skill() else {
331 return ViewAction::None;
332 };
333 let Some(kind) = skill.available_actions.first().copied() else {
334 self.status = Some(format!("No actions available for '{}'", skill.name));
335 return ViewAction::None;
336 };
337 self.emit_action(kind)
338 }
339 }
340 }
341
342 fn footer_hints(&self) -> Vec<ActionHint> {
343 if self.pending.is_some() {
344 return vec![
345 ActionHint::new("Enter", "confirm"),
346 ActionHint::new("Esc", "cancel"),
347 ];
348 }
349 let mut hints = vec![
350 ActionHint::new("↑/↓", "move"),
351 ActionHint::new("Enter", "action"),
352 ActionHint::new("c", "scan mode"),
353 ActionHint::new("s", "import scope"),
354 ActionHint::new("Esc", "close"),
355 ];
356 if let Some(skill) = self.selected_skill() {
357 for action in &skill.available_actions {
358 match action {
359 SkillActionKind::Import => hints.insert(2, ActionHint::new("i", "import")),
360 SkillActionKind::Update => hints.insert(2, ActionHint::new("u", "update")),
361 SkillActionKind::Remove => hints.insert(2, ActionHint::new("r", "remove")),
362 SkillActionKind::Trust => hints.insert(2, ActionHint::new("t", "trust")),
363 SkillActionKind::Install => {}
364 }
365 }
366 }
367 hints
368 }
369
370 fn render_list(&self, area: Rect, buf: &mut Buffer) {
371 let block = Block::default()
372 .title(Line::from(Span::styled(
373 format!(" Skills ({}) ", self.skills.len()),
374 Style::default()
375 .fg(palette::WHALE_ACTION)
376 .add_modifier(Modifier::BOLD),
377 )))
378 .borders(Borders::ALL)
379 .border_style(Style::default().fg(palette::BORDER_COLOR))
380 .style(Style::default().bg(palette::WHALE_BG));
381 let inner = block.inner(area);
382 block.render(area, buf);
383
384 if self.skills.is_empty() {
385 let hint = tr(self.locale, MessageId::SkillsManagerEmptyHint)
386 .replace("{key}", "c")
387 .replace("{command}", "/skill install <spec>");
388 EmptyState::new(tr(self.locale, MessageId::SkillsManagerEmptyTitle), hint)
389 .render(inner, buf);
390 return;
391 }
392
393 let visible = usize::from(inner.height).max(1);
394 let offset = self.selected.saturating_add(1).saturating_sub(visible);
395 let end = (offset + visible).min(self.skills.len());
396
397 for (row, idx) in (offset..end).enumerate() {
398 let skill = &self.skills[idx];
399 let y = inner.y + row as u16;
400 if y >= inner.y + inner.height {
401 break;
402 }
403 let selected = idx == self.selected;
404 let style = if selected {
405 menu_style::selected_row_style()
406 } else {
407 Style::default().fg(palette::TEXT_PRIMARY)
408 };
409 let mark = codewhale_tui_kit::glyphs::selection_marker(selected);
410 let line = format!(
411 "{mark} {:<6} {} {} {}",
412 skill_tier_label(skill),
413 truncate_view_text(&skill.name, 15),
414 precedence_label(&skill.precedence),
415 source_label(skill.source_kind),
416 );
417 buf.set_stringn(inner.x, y, line, usize::from(inner.width), style);
418 }
419 }
420
421 fn render_detail(&self, area: Rect, buf: &mut Buffer) {
422 let block = Block::default()
423 .title(Line::from(Span::styled(
424 " Details ",
425 Style::default()
426 .fg(palette::WHALE_ACTION)
427 .add_modifier(Modifier::BOLD),
428 )))
429 .borders(Borders::ALL)
430 .border_style(Style::default().fg(palette::BORDER_COLOR))
431 .style(Style::default().bg(palette::WHALE_BG));
432 let inner = block.inner(area);
433 block.render(area, buf);
434
435 let Some(skill) = self.selected_skill() else {
436 self.detail_max_scroll.set(0);
437 EmptyState::new(
438 "Nothing selected",
439 "Install or import a skill to get started.",
440 )
441 .render(inner, buf);
442 return;
443 };
444
445 let mut lines = vec![
446 Line::from(Span::styled(
447 skill.name.clone(),
448 Style::default()
449 .fg(palette::WHALE_ACTION)
450 .add_modifier(Modifier::BOLD),
451 )),
452 Line::from(""),
453 kv_line("Path", &skill.safe_display_path),
454 kv_line("Tier", skill_tier_label(skill)),
455 kv_line("Source", source_label(skill.source_kind)),
456 kv_line("Status", &precedence_label(&skill.precedence)),
457 kv_line("Integrity", integrity_label(&skill.integrity)),
458 kv_line("Trust", trust_label(&skill.trust)),
459 kv_line("Parser", &parser_label(&skill.parser)),
460 kv_line("Digest", &digest_label(&skill.digest)),
461 kv_line("Provenance", &provenance_label(&skill.provenance)),
462 kv_line("Readiness", "unknown"),
463 kv_line("Import to", scope_label(self.import_scope)),
464 kv_line("Scan", self.mode.label()),
465 ];
466
467 if let Some(desc) = skill.description.as_deref() {
468 lines.push(Line::from(""));
469 lines.push(Line::from(Span::styled(
470 "Description",
471 Style::default().fg(palette::TEXT_MUTED),
472 )));
473 lines.push(Line::from(truncate_view_text(desc, 240)));
474 }
475
476 lines.push(Line::from(""));
477 lines.push(Line::from(Span::styled(
478 "Actions",
479 Style::default().fg(palette::TEXT_MUTED),
480 )));
481 if skill.available_actions.is_empty() {
482 lines.push(Line::from(Span::styled(
483 "(none — read-only or not managed)",
484 Style::default().fg(palette::TEXT_MUTED),
485 )));
486 } else {
487 let labels: Vec<&str> = skill
488 .available_actions
489 .iter()
490 .map(|a| action_label(*a))
491 .collect();
492 lines.push(Line::from(labels.join(", ")));
493 }
494
495 if !skill.warnings.is_empty() {
496 lines.push(Line::from(""));
497 lines.push(Line::from(Span::styled(
498 "Warnings",
499 Style::default().fg(palette::STATUS_WARNING),
500 )));
501 for w in &skill.warnings {
502 match w {
503 codewhale_skills::audit::SkillAuditWarning::Message(msg) => {
504 lines.push(Line::from(format!("• {msg}")));
505 }
506 }
507 }
508 }
509
510 if let Some(status) = &self.status {
511 lines.push(Line::from(""));
512 lines.push(Line::from(Span::styled(
513 status.clone(),
514 Style::default().fg(palette::WHALE_ACTION),
515 )));
516 }
517
518 let max_scroll = lines.len().saturating_sub(1);
519 self.detail_max_scroll.set(max_scroll);
520 let scroll = self.detail_scroll.min(max_scroll);
521 let visible: Vec<Line> = lines.into_iter().skip(scroll).collect();
522 Paragraph::new(visible)
523 .wrap(Wrap { trim: false })
524 .style(Style::default().fg(palette::TEXT_PRIMARY))
525 .render(inner, buf);
526 }
527 }
528
529 fn scan_snapshot(app: &App, mode: ManagerMode) -> SkillAuditSnapshot {
530 scan_with_configured(
531 &app.workspace,
532 codewhale_paths::user_home().as_deref(),
533 Some(&app.skills_dir),
534 mode.audit_mode(),
535 None,
536 )
537 }
538
539 fn known_digest(skill: &AuditedSkill) -> Option<String> {
540 match &skill.digest {
541 DigestState::Known(d) => Some(d.clone()),
542 DigestState::Unknown(_) => None,
543 }
544 }
545
546 fn scope_label(scope: SkillTargetScope) -> &'static str {
547 match scope {
548 SkillTargetScope::Project => "project",
549 SkillTargetScope::Global => "global",
550 }
551 }
552
553 fn action_label(kind: SkillActionKind) -> &'static str {
554 match kind {
555 SkillActionKind::Install => "install",
556 SkillActionKind::Import => "import",
557 SkillActionKind::Update => "update",
558 SkillActionKind::Remove => "remove",
559 SkillActionKind::Trust => "trust",
560 }
561 }
562
563 fn source_label(kind: SkillSourceKind) -> &'static str {
564 match kind {
565 SkillSourceKind::CodeWhaleManaged => "managed",
566 SkillSourceKind::CodeWhaleManual => "manual",
567 SkillSourceKind::CompatibleExternal => "external",
568 SkillSourceKind::BuiltIn => "built-in",
569 SkillSourceKind::ReviewedPluginSnapshot => "plugin",
570 SkillSourceKind::RegistryCache => "cache",
571 }
572 }
573
574 fn skill_tier_label(skill: &AuditedSkill) -> &'static str {
575 if skill.source_kind != SkillSourceKind::BuiltIn {
576 return "custom";
577 }
578 codewhale_skills::bundled_skill_tier(&skill.name)
579 .map_or("custom", codewhale_skills::BundledSkillTier::label)
580 }
581
582 fn precedence_label(state: &PrecedenceState) -> String {
583 match state {
584 PrecedenceState::Active => "active".into(),
585 PrecedenceState::ShadowedBy(id) => format!("shadowed:{}", id.canonical_name),
586 PrecedenceState::InactiveSource => "inactive".into(),
587 PrecedenceState::Unknown => "unknown".into(),
588 }
589 }
590
591 fn integrity_label(state: &IntegrityState) -> &'static str {
592 match state {
593 IntegrityState::Healthy => "healthy",
594 IntegrityState::LocalContentDrift => "drift",
595 IntegrityState::BrokenManagedInstall => "broken",
596 IntegrityState::LegacyMetadataUnknown => "legacy",
597 IntegrityState::Unknown => "unknown",
598 }
599 }
600
601 fn trust_label(state: &TrustState) -> &'static str {
602 match state {
603 TrustState::TrustedForDigest(_) => "trusted",
604 TrustState::TrustStale => "stale",
605 TrustState::LegacyAdvisory => "legacy",
606 TrustState::Untrusted => "untrusted",
607 TrustState::NotApplicable => "n/a",
608 TrustState::Unknown => "unknown",
609 }
610 }
611
612 fn parser_label(state: &ParserState) -> String {
613 match state {
614 ParserState::Valid => "valid".into(),
615 ParserState::Warning(ws) => format!("warning({})", ws.len()),
616 ParserState::Broken(msg) => format!("broken:{msg}"),
617 ParserState::Oversized => "oversized".into(),
618 }
619 }
620
621 fn digest_label(state: &DigestState) -> String {
622 match state {
623 DigestState::Known(d) => {
624 let mut graphemes = UnicodeSegmentation::graphemes(d.as_str(), true);
625 let prefix: String = graphemes.by_ref().take(12).collect();
626 if graphemes.next().is_some() {
627 format!("{prefix}…")
628 } else {
629 d.clone()
630 }
631 }
632 DigestState::Unknown(reason) => format!("unknown:{reason:?}"),
633 }
634 }
635
636 fn provenance_label(state: &ProvenanceState) -> String {
637 match state {
638 ProvenanceState::Managed { spec, .. } => spec.clone().unwrap_or_else(|| "managed".into()),
639 ProvenanceState::Manual => "manual".into(),
640 ProvenanceState::External => "external".into(),
641 ProvenanceState::BuiltIn => "built-in".into(),
642 ProvenanceState::Plugin => "plugin".into(),
643 ProvenanceState::Cache => "cache".into(),
644 ProvenanceState::Unknown => "unknown".into(),
645 }
646 }
647
648 fn kv_line(key: &str, value: &str) -> Line<'static> {
649 Line::from(vec![
650 Span::styled(
651 format!("{key:<11}"),
652 Style::default().fg(palette::TEXT_MUTED),
653 ),
654 Span::raw(value.to_string()),
655 ])
656 }
657
658 impl ModalView for SkillsManagerView {
659 fn kind(&self) -> ModalKind {
660 ModalKind::SkillsManager
661 }
662
663 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
664 self
665 }
666
667 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
668 if self.pending.is_some() {
669 return match key.code {
670 KeyCode::Esc => {
671 self.pending = None;
672 self.status = Some("Cancelled.".into());
673 ViewAction::None
674 }
675 KeyCode::Enter => self.confirm_pending(),
676 _ => ViewAction::None,
677 };
678 }
679
680 match key.code {
681 KeyCode::Esc => ViewAction::Close,
682 KeyCode::Char('q') | KeyCode::Char('Q') if key.modifiers.is_empty() => {
683 ViewAction::Close
684 }
685 KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
686 self.move_sel(-1);
687 ViewAction::None
688 }
689 KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {
690 self.move_sel(1);
691 ViewAction::None
692 }
693 KeyCode::PageUp => {
694 self.detail_scroll = self.detail_scroll.saturating_sub(8);
695 ViewAction::None
696 }
697 KeyCode::PageDown => {
698 self.detail_scroll = self
699 .detail_scroll
700 .saturating_add(8)
701 .min(self.detail_max_scroll.get());
702 ViewAction::None
703 }
704 KeyCode::Home => {
705 self.detail_scroll = 0;
706 ViewAction::None
707 }
708 KeyCode::Enter => self.confirm_pending(),
709 KeyCode::Char('i') | KeyCode::Char('I') if key.modifiers.is_empty() => {
710 self.emit_action(SkillActionKind::Import)
711 }
712 KeyCode::Char('u') | KeyCode::Char('U') if key.modifiers.is_empty() => {
713 self.emit_action(SkillActionKind::Update)
714 }
715 KeyCode::Char('r') | KeyCode::Char('R') if key.modifiers.is_empty() => {
716 self.emit_action(SkillActionKind::Remove)
717 }
718 KeyCode::Char('t') | KeyCode::Char('T') if key.modifiers.is_empty() => {
719 self.emit_action(SkillActionKind::Trust)
720 }
721 KeyCode::Char('c') | KeyCode::Char('C') if key.modifiers.is_empty() => {
722 ViewAction::Emit(ViewEvent::SkillsManagerToggleCompatible)
723 }
724 KeyCode::Char('s') | KeyCode::Char('S') if key.modifiers.is_empty() => {
725 self.cycle_import_scope();
726 ViewAction::None
727 }
728 _ => ViewAction::None,
729 }
730 }
731
732 fn render(&self, area: Rect, buf: &mut Buffer) {
733 Clear.render(area, buf);
734 let body = render_underwater_surface(area, buf, "Skills Manager");
735 let hints = self.footer_hints();
736 let content = render_modal_footer(body, buf, &hints);
737
738 let header_h = 2u16.min(content.height);
739 let header = Rect {
740 x: content.x,
741 y: content.y,
742 width: content.width,
743 height: header_h,
744 };
745 let mode_line = format!(
746 " scan={} import-target={} {}",
747 self.mode.label(),
748 scope_label(self.import_scope),
749 self.status.as_deref().unwrap_or("idle")
750 );
751 buf.set_stringn(
752 header.x,
753 header.y,
754 truncate_view_text(&mode_line, usize::from(header.width)),
755 usize::from(header.width),
756 Style::default().fg(palette::TEXT_SECONDARY),
757 );
758
759 let panel = Rect {
760 x: content.x,
761 y: content.y.saturating_add(header_h),
762 width: content.width,
763 height: content.height.saturating_sub(header_h),
764 };
765 let layout = ListDetailLayout::split(panel, 34);
766 self.render_list(layout.list, buf);
767 self.render_detail(layout.detail, buf);
768 }
769 }
770
771 /// Apply scan-mode toggle using the live app workspace (host-driven).
772 pub fn apply_toggle_compatible(view: &mut SkillsManagerView, app: &App) {
773 view.toggle_mode(app);
774 }
775
776 #[cfg(test)]
777 mod tests {
778 use super::*;
779 use crate::tui::app::{App, TuiOptions};
780 use codewhale_runtime::config::Config;
781 use crossterm::event::{KeyEventKind, KeyModifiers};
782 use std::fs;
783 use tempfile::TempDir;
784
785 fn key(code: KeyCode) -> KeyEvent {
786 KeyEvent {
787 code,
788 modifiers: KeyModifiers::NONE,
789 kind: KeyEventKind::Press,
790 state: crossterm::event::KeyEventState::NONE,
791 }
792 }
793
794 struct IsolatedHome {
795 _home: crate::test_support::EnvVarGuard,
796 _userprofile: crate::test_support::EnvVarGuard,
797 _codewhale_home: crate::test_support::EnvVarGuard,
798 _lock: crate::test_support::TestEnvLock,
799 }
800
801 impl IsolatedHome {
802 fn new(tmpdir: &TempDir) -> Self {
803 let lock = crate::test_support::lock_test_env();
804 let home = tmpdir.path().join("home");
805 fs::create_dir_all(&home).unwrap();
806 Self {
807 _home: crate::test_support::EnvVarGuard::set("HOME", &home),
808 _userprofile: crate::test_support::EnvVarGuard::set("USERPROFILE", &home),
809 _codewhale_home: crate::test_support::EnvVarGuard::set(
810 "CODEWHALE_HOME",
811 home.join(".codewhale"),
812 ),
813 _lock: lock,
814 }
815 }
816 }
817
818 fn app_in(tmp: &TempDir) -> App {
819 let workspace = tmp.path().join("ws");
820 fs::create_dir_all(&workspace).unwrap();
821 let options = TuiOptions {
822 skills_dir: tmp.path().join("skills"),
823 memory_path: tmp.path().join("memory.md"),
824 mcp_config_path: tmp.path().join("mcp.json"),
825 ..crate::tui::test_support::test_tui_options(workspace)
826 };
827 App::new(options, &Config::default())
828 }
829
830 #[test]
831 fn opens_owned_scan_and_closes_on_esc() {
832 let tmp = TempDir::new().unwrap();
833 let _home = IsolatedHome::new(&tmp);
834 let app = app_in(&tmp);
835 let mut view = SkillsManagerView::new(&app);
836 assert_eq!(view.mode, ManagerMode::OwnedOnly);
837 assert_eq!(view.kind(), ModalKind::SkillsManager);
838 assert!(matches!(
839 view.handle_key(key(KeyCode::Esc)),
840 ViewAction::Close
841 ));
842 }
843
844 #[test]
845 fn remove_requires_confirm_then_emits() {
846 let tmp = TempDir::new().unwrap();
847 let _home = IsolatedHome::new(&tmp);
848 let workspace = tmp.path().join("ws");
849 let skill_dir = workspace.join(".codewhale").join("skills").join("demo");
850 fs::create_dir_all(&skill_dir).unwrap();
851 fs::write(
852 skill_dir.join("SKILL.md"),
853 "---\nname: demo\ndescription: d\n---\nbody\n",
854 )
855 .unwrap();
856 let digest = codewhale_skills::audit::compute_package_digest(&skill_dir).unwrap();
857 codewhale_skill_install::install::write_installed_from_v2(
858 &skill_dir,
859 "github:o/r",
860 None,
861 "src",
862 &digest,
863 "demo",
864 )
865 .unwrap();
866
867 let mut app = app_in(&tmp);
868 app.workspace = workspace;
869 let mut view = SkillsManagerView::new(&app);
870 assert!(!view.skills.is_empty());
871 let action = view.handle_key(key(KeyCode::Char('r')));
872 assert!(matches!(action, ViewAction::None));
873 assert!(view.pending.is_some());
874 let action = view.handle_key(key(KeyCode::Enter));
875 assert!(matches!(
876 action,
877 ViewAction::Emit(ViewEvent::SkillMutationRequested {
878 request: SkillMutationRequest::Remove { .. },
879 })
880 ));
881 }
882
883 #[test]
884 fn render_fits_narrow_terminal() {
885 let tmp = TempDir::new().unwrap();
886 let _home = IsolatedHome::new(&tmp);
887 let app = app_in(&tmp);
888 let view = SkillsManagerView::new(&app);
889 let area = Rect::new(0, 0, 80, 24);
890 let mut buf = Buffer::empty(area);
891 view.render(area, &mut buf);
892 let mut found = false;
893 for y in 0..area.height {
894 let mut row = String::new();
895 for x in 0..area.width {
896 row.push(
897 buf.cell((x, y))
898 .map(|c| c.symbol().chars().next().unwrap_or(' '))
899 .unwrap_or(' '),
900 );
901 }
902 if row.contains("Skills") {
903 found = true;
904 break;
905 }
906 }
907 assert!(found, "expected Skills title on 80x24 surface");
908 }
909
910 #[test]
911 fn empty_state_follows_the_ui_locale() {
912 let tmp = TempDir::new().unwrap();
913 let _home = IsolatedHome::new(&tmp);
914 let app = app_in(&tmp);
915 let mut view = SkillsManagerView::new(&app);
916 view.skills.clear();
917 view.locale = Locale::Fr;
918 let area = Rect::new(0, 0, 80, 24);
919 let mut buf = Buffer::empty(area);
920 view.render(area, &mut buf);
921 let text: String = (0..area.height)
922 .flat_map(|y| (0..area.width).map(move |x| (x, y)))
923 .map(|(x, y)| buf.cell((x, y)).map_or(" ", |c| c.symbol()).to_string())
924 .collect();
925 assert!(!text.contains("No skills in this scan"), "{text}");
926 assert!(text.contains("Aucune"), "{text}");
927 }
928
929 #[test]
930 fn selected_skill_row_uses_charter_pointer_and_selection_bg() {
931 let tmp = TempDir::new().unwrap();
932 let _home = IsolatedHome::new(&tmp);
933 let mut app = app_in(&tmp);
934 app.skills_dir = tmp.path().join("home").join(".codewhale").join("skills");
935 codewhale_skills::install_system_skills(&app.skills_dir, &app.skills_config.bundled)
936 .unwrap();
937
938 let view = SkillsManagerView::new(&app);
939 assert!(!view.skills.is_empty());
940 let area = Rect::new(0, 0, 100, 24);
941 let mut buf = Buffer::empty(area);
942 view.render(area, &mut buf);
943
944 let selected_row_painted = area
945 .positions()
946 .any(|position| buf[position].bg == palette::SELECTION_BG);
947 assert!(
948 selected_row_painted,
949 "selected skill row must use the shared selection highlight"
950 );
951 let text = area
952 .positions()
953 .map(|position| buf[position].symbol())
954 .collect::<String>();
955 assert!(
956 text.contains(codewhale_tui_kit::glyphs::SELECTION),
957 "selected skill row must carry the charter pointer: {text}"
958 );
959 }
960
961 #[test]
962 fn manager_labels_exact_built_ins_by_tier_and_user_skills_as_custom() {
963 let tmp = TempDir::new().unwrap();
964 let _home = IsolatedHome::new(&tmp);
965 let mut app = app_in(&tmp);
966 app.skills_dir = tmp.path().join("home").join(".codewhale").join("skills");
967 codewhale_skills::install_system_skills(&app.skills_dir, &app.skills_config.bundled)
968 .unwrap();
969 write_skill_pkg(&app.skills_dir.join("my-workflow"), "my-workflow", "mine");
970
971 let view = SkillsManagerView::new(&app);
972 let review = view
973 .skills
974 .iter()
975 .find(|skill| skill.name == "review")
976 .expect("review row");
977 let help = view
978 .skills
979 .iter()
980 .find(|skill| skill.name == "help")
981 .expect("help row");
982 let custom = view
983 .skills
984 .iter()
985 .find(|skill| skill.name == "my-workflow")
986 .expect("custom row");
987
988 assert_eq!(skill_tier_label(review), "core");
989 assert_eq!(skill_tier_label(help), "tools");
990 assert_eq!(skill_tier_label(custom), "custom");
991 }
992
993 #[test]
994 fn import_replace_confirm_is_scoped_to_import_target() {
995 let tmp = TempDir::new().unwrap();
996 let _home = IsolatedHome::new(&tmp);
997 let workspace = tmp.path().join("ws");
998 let home = tmp.path().join("home");
999 fs::create_dir_all(&home).unwrap();
1000
1001 // Project-owned conflict only — Global import must not prompt replace.
1002 write_skill_pkg(
1003 &workspace.join(".codewhale").join("skills").join("shared"),
1004 "shared",
1005 "owned-project",
1006 );
1007 write_skill_pkg(
1008 &workspace.join(".claude").join("skills").join("shared"),
1009 "shared",
1010 "external-different",
1011 );
1012
1013 let mut app = app_in(&tmp);
1014 app.workspace = workspace;
1015 // Force HOME for scan so global root is the isolated home.
1016 let mut view = SkillsManagerView::from_scan(
1017 &app,
1018 ManagerMode::Compatible,
1019 SkillTargetScope::Global,
1020 None,
1021 None,
1022 );
1023 // Select the external row.
1024 let ext_idx = view
1025 .skills
1026 .iter()
1027 .position(|s| s.source_kind == SkillSourceKind::CompatibleExternal)
1028 .expect("external skill");
1029 view.selected = ext_idx;
1030
1031 let action = view.handle_key(key(KeyCode::Char('i')));
1032 assert!(
1033 matches!(
1034 action,
1035 ViewAction::Emit(ViewEvent::SkillMutationRequested {
1036 request: SkillMutationRequest::ImportExternal {
1037 conflict_policy: ConflictPolicy::Reject,
1038 ..
1039 },
1040 })
1041 ),
1042 "global import must not treat project-owned peer as replace: {action:?}"
1043 );
1044 assert!(view.pending.is_none());
1045
1046 view.import_scope = SkillTargetScope::Project;
1047 let action = view.handle_key(key(KeyCode::Char('i')));
1048 assert!(matches!(action, ViewAction::None));
1049 assert!(
1050 matches!(view.pending, Some(PendingConfirm::ImportReplace { .. })),
1051 "project import should confirm replace against project-owned peer"
1052 );
1053 assert!(home.exists());
1054 }
1055
1056 #[test]
1057 fn compatible_scan_includes_configured_skills_dir() {
1058 let tmp = TempDir::new().unwrap();
1059 let _home = IsolatedHome::new(&tmp);
1060 let workspace = tmp.path().join("ws");
1061 let configured = tmp.path().join("custom-skills");
1062 write_skill_pkg(&configured.join("custom-one"), "custom-one", "from-config");
1063
1064 let mut app = app_in(&tmp);
1065 app.workspace = workspace;
1066 app.skills_dir = configured;
1067
1068 let view = SkillsManagerView::from_scan(
1069 &app,
1070 ManagerMode::Compatible,
1071 SkillTargetScope::Global,
1072 None,
1073 None,
1074 );
1075 assert!(
1076 view.skills.iter().any(|s| s.name == "custom-one"),
1077 "configured skills_dir rows must appear in compatible scan"
1078 );
1079 }
1080
1081 #[test]
1082 fn digest_label_truncates_multibyte_utf8_by_grapheme_without_panicking() {
1083 let family = "👨‍👩‍👧‍👦";
1084 let multibyte = family.repeat(14);
1085 assert_eq!(
1086 digest_label(&DigestState::Known(multibyte)),
1087 format!("{}…", family.repeat(12))
1088 );
1089 assert_eq!(
1090 digest_label(&DigestState::Known("abcdef1234567890".into())),
1091 "abcdef123456…"
1092 );
1093 assert_eq!(digest_label(&DigestState::Known("short".into())), "short");
1094 }
1095
1096 #[test]
1097 fn detail_scroll_clamps_to_rendered_ceiling() {
1098 let tmp = TempDir::new().unwrap();
1099 let _home = IsolatedHome::new(&tmp);
1100 let configured = tmp.path().join("custom-skills");
1101 write_skill_pkg(&configured.join("scroll-one"), "scroll-one", "body");
1102
1103 let mut app = app_in(&tmp);
1104 app.skills_dir = configured;
1105 let mut view = SkillsManagerView::from_scan(
1106 &app,
1107 ManagerMode::Compatible,
1108 SkillTargetScope::Global,
1109 None,
1110 None,
1111 );
1112 let area = Rect::new(0, 0, 80, 20);
1113 let mut buf = Buffer::empty(area);
1114 view.render(area, &mut buf);
1115
1116 let ceiling = view.detail_max_scroll.get();
1117 assert!(ceiling > 0 && ceiling < usize::MAX);
1118 for _ in 0..20 {
1119 view.handle_key(key(KeyCode::PageDown));
1120 }
1121 assert_eq!(view.detail_scroll, ceiling);
1122 view.handle_key(key(KeyCode::PageUp));
1123 assert_eq!(view.detail_scroll, ceiling.saturating_sub(8));
1124 }
1125
1126 fn write_skill_pkg(dir: &std::path::Path, name: &str, body: &str) {
1127 fs::create_dir_all(dir).unwrap();
1128 fs::write(
1129 dir.join("SKILL.md"),
1130 format!("---\nname: {name}\ndescription: d\n---\n{body}\n"),
1131 )
1132 .unwrap();
1133 }
1134 }
1135
1135 lines RUST