Skip to main content

agent_hub_runtime/commands/
skill_groups.rs

1pub mod membership;
2pub use membership::set_skill_group_skills_internal;
3
4use serde::{Deserialize, Serialize};
5use std::sync::atomic::AtomicBool;
6use std::sync::Arc;
7use std::time::Instant;
8use tauri::State;
9
10use crate::core::{
11    error::AppError,
12    scenario_service::{self, BatchApplyMode},
13    skill_store::{ScenarioRecord, SkillStore},
14    sync_metadata,
15    timing::should_log_first_or_slow,
16    tool_adapters,
17};
18
19fn refresh_tray_menu_best_effort(app: &tauri::AppHandle) {
20    if let Err(err) = crate::refresh_tray_menu(app) {
21        log::warn!("Failed to refresh tray menu after skill group mutation: {err}");
22    }
23}
24
25/// Sync a skill's files to all enabled tool adapter directories for the given skill_group.
26/// Only performs sync if the skill group is the currently active one.
27pub(crate) fn sync_skill_to_active_skill_group(
28    store: &SkillStore,
29    scenario_id: &str,
30    skill_id: &str,
31) -> Result<(), AppError> {
32    scenario_service::sync_skill_to_active_scenario(store, scenario_id, skill_id)
33}
34
35#[derive(Debug, Serialize)]
36pub struct SkillGroupDto {
37    pub id: String,
38    pub name: String,
39    pub description: Option<String>,
40    pub icon: Option<String>,
41    pub sort_order: i32,
42    pub skill_count: i64,
43    pub created_at: i64,
44    pub updated_at: i64,
45}
46
47static GET_SKILL_GROUPS_FIRST_CALL: AtomicBool = AtomicBool::new(true);
48
49fn skill_group_dto(store: &SkillStore, scenario: ScenarioRecord) -> SkillGroupDto {
50    let skill_count = store.count_skills_for_scenario(&scenario.id).unwrap_or(0);
51    SkillGroupDto {
52        id: scenario.id,
53        name: scenario.name,
54        description: scenario.description,
55        icon: scenario.icon,
56        sort_order: scenario.sort_order,
57        skill_count,
58        created_at: scenario.created_at,
59        updated_at: scenario.updated_at,
60    }
61}
62
63#[tauri::command]
64pub async fn get_skill_groups(
65    store: State<'_, Arc<SkillStore>>,
66) -> Result<Vec<SkillGroupDto>, AppError> {
67    let store = store.inner().clone();
68    tauri::async_runtime::spawn_blocking(move || {
69        let start = Instant::now();
70        let scenarios = store.get_all_scenarios().map_err(AppError::db)?;
71        let count = scenarios.len();
72        let mut result = Vec::new();
73        for s in scenarios {
74            result.push(skill_group_dto(&store, s));
75        }
76        let elapsed_ms = start.elapsed().as_millis();
77        if should_log_first_or_slow(&GET_SKILL_GROUPS_FIRST_CALL, elapsed_ms, 100) {
78            log::info!("get_skill_groups: {count} skill groups in {elapsed_ms} ms");
79        }
80        Ok(result)
81    })
82    .await?
83}
84
85#[tauri::command]
86pub async fn get_active_skill_group(
87    store: State<'_, Arc<SkillStore>>,
88) -> Result<Option<SkillGroupDto>, AppError> {
89    let store = store.inner().clone();
90    tauri::async_runtime::spawn_blocking(move || {
91        let active_id = store.get_active_scenario_id().map_err(AppError::db)?;
92
93        if let Some(id) = active_id {
94            let scenarios = store.get_all_scenarios().map_err(AppError::db)?;
95            if let Some(s) = scenarios.into_iter().find(|s| s.id == id) {
96                return Ok(Some(skill_group_dto(&store, s)));
97            }
98        }
99        Ok(None)
100    })
101    .await?
102}
103
104#[tauri::command]
105pub async fn create_skill_group(
106    app: tauri::AppHandle,
107    name: String,
108    description: Option<String>,
109    icon: Option<String>,
110    store: State<'_, Arc<SkillStore>>,
111) -> Result<SkillGroupDto, AppError> {
112    let store = store.inner().clone();
113    let result = tauri::async_runtime::spawn_blocking(move || {
114        create_and_activate_skill_group_internal(
115            &store,
116            &name,
117            description.as_deref(),
118            icon.as_deref(),
119        )
120        .map(|scenario| skill_group_dto(&store, scenario))
121    })
122    .await?;
123    if result.is_ok() {
124        refresh_tray_menu_best_effort(&app);
125    }
126    result
127}
128
129pub fn create_skill_group_internal(
130    store: &SkillStore,
131    name: &str,
132    description: Option<&str>,
133    icon: Option<&str>,
134) -> Result<ScenarioRecord, AppError> {
135    let name = name.trim();
136    if name.is_empty() {
137        return Err(AppError::invalid_input("Skill group name cannot be empty"));
138    }
139
140    let now = chrono::Utc::now().timestamp_millis();
141    let id = uuid::Uuid::new_v4().to_string();
142    let record = ScenarioRecord {
143        id: id.clone(),
144        name: name.to_string(),
145        description: description
146            .map(str::trim)
147            .filter(|value| !value.is_empty())
148            .map(str::to_string),
149        icon: icon
150            .map(str::trim)
151            .filter(|value| !value.is_empty())
152            .map(str::to_string),
153        sort_order: 999,
154        created_at: now,
155        updated_at: now,
156    };
157
158    sync_metadata::with_repo_lock("create skill group", || {
159        store.insert_scenario(&record)?;
160        sync_metadata::write_all_from_db_unlocked(store)
161    })
162    .map_err(AppError::db)?;
163    Ok(record)
164}
165
166/// Preserve the desktop app's legacy create-and-select behavior while the CLI
167/// uses [`create_skill_group_internal`] as a pure organization operation.
168fn create_and_activate_skill_group_internal(
169    store: &SkillStore,
170    name: &str,
171    description: Option<&str>,
172    icon: Option<&str>,
173) -> Result<ScenarioRecord, AppError> {
174    let previous_active_id = store.get_active_scenario_id().map_err(AppError::db)?;
175    let record = create_skill_group_internal(store, name, description, icon)?;
176    if let Some(previous_id) = previous_active_id.as_deref() {
177        unsync_scenario_skills(store, previous_id)?;
178    }
179    store
180        .set_active_scenario(&record.id)
181        .map_err(AppError::db)?;
182    Ok(record)
183}
184
185#[tauri::command]
186pub async fn update_skill_group(
187    app: tauri::AppHandle,
188    id: String,
189    name: String,
190    description: Option<String>,
191    icon: Option<String>,
192    store: State<'_, Arc<SkillStore>>,
193) -> Result<(), AppError> {
194    let store = store.inner().clone();
195    let result = tauri::async_runtime::spawn_blocking(move || {
196        update_skill_group_internal(&store, &id, &name, description.as_deref(), icon.as_deref())
197    })
198    .await?;
199    if result.is_ok() {
200        refresh_tray_menu_best_effort(&app);
201    }
202    result
203}
204
205pub fn update_skill_group_internal(
206    store: &SkillStore,
207    id: &str,
208    name: &str,
209    description: Option<&str>,
210    icon: Option<&str>,
211) -> Result<(), AppError> {
212    scenario_service::ensure_scenario_exists(store, id)?;
213    let name = name.trim();
214    if name.is_empty() {
215        return Err(AppError::invalid_input("Skill group name cannot be empty"));
216    }
217    let description = description.map(str::trim).filter(|value| !value.is_empty());
218    let icon = icon.map(str::trim).filter(|value| !value.is_empty());
219    sync_metadata::with_repo_lock("update skill group", || {
220        store.update_scenario(id, name, description, icon)?;
221        sync_metadata::write_all_from_db_unlocked(store)
222    })
223    .map_err(AppError::db)
224}
225
226#[tauri::command]
227pub async fn delete_skill_group(
228    app: tauri::AppHandle,
229    id: String,
230    store: State<'_, Arc<SkillStore>>,
231) -> Result<(), AppError> {
232    let store = store.inner().clone();
233    let result = tauri::async_runtime::spawn_blocking(move || {
234        delete_skill_group_with_active_fallback_internal(&store, &id)
235    })
236    .await?;
237    if result.is_ok() {
238        refresh_tray_menu_best_effort(&app);
239    }
240    result
241}
242
243pub fn delete_skill_group_internal(store: &SkillStore, id: &str) -> Result<(), AppError> {
244    scenario_service::ensure_scenario_exists(store, id)?;
245    let was_active = store
246        .get_active_scenario_id()
247        .map_err(AppError::db)?
248        .as_deref()
249        == Some(id);
250
251    sync_metadata::with_repo_lock("delete skill group", || {
252        if was_active {
253            store.clear_active_scenario()?;
254        }
255        store.delete_scenario(id)?;
256        sync_metadata::remove_scenario_metadata(id)
257    })
258    .map_err(AppError::db)
259}
260
261/// Preserve the desktop app's legacy active-skill-group transition. The CLI calls
262/// [`delete_skill_group_internal`] directly so deleting an organization object does
263/// not implicitly undeploy skills.
264fn delete_skill_group_with_active_fallback_internal(
265    store: &SkillStore,
266    id: &str,
267) -> Result<(), AppError> {
268    scenario_service::ensure_scenario_exists(store, id)?;
269    let was_active = store
270        .get_active_scenario_id()
271        .map_err(AppError::db)?
272        .as_deref()
273        == Some(id);
274
275    if was_active {
276        unsync_scenario_skills(store, id)?;
277    }
278
279    delete_skill_group_internal(store, id)?;
280
281    if was_active {
282        let remaining = store.get_all_scenarios().map_err(AppError::db)?;
283        if let Some(first) = remaining.first() {
284            store.set_active_scenario(&first.id).map_err(AppError::db)?;
285            // The skill group is already deleted and the fallback already active, so
286            // a refusal here cannot undo any of that — report it, don't fail.
287            for refusal in sync_scenario_skills(store, &first.id, false)? {
288                log::warn!("fallback skill group sync skipped a target: {refusal}");
289            }
290        }
291    }
292
293    Ok(())
294}
295
296/// Apply a skill group to the default targets (all enabled agent globals).
297///
298/// This is the explicit user-initiated action introduced in v1.16. It performs
299/// the same disk-writing work as the legacy [`switch_skill_group`] command but is
300/// only invoked when the user clicks "Apply to Default" — sidebar/command-palette
301/// skill group clicks no longer call this.
302#[tauri::command]
303pub async fn apply_skill_group_to_default(
304    app: tauri::AppHandle,
305    id: String,
306    force: Option<bool>,
307    store: State<'_, Arc<SkillStore>>,
308) -> Result<(), AppError> {
309    apply_skill_group_to_default_impl(app, id, force.unwrap_or(false), store.inner().clone()).await
310}
311
312/// Legacy command kept for the CLI and backward compatibility. New callers
313/// should use [`apply_skill_group_to_default`] (or [`apply_skill_group_to_coding_agents`]
314/// for the workspace-scoped variant the tray now uses).
315#[tauri::command]
316pub async fn switch_skill_group(
317    app: tauri::AppHandle,
318    id: String,
319    force: Option<bool>,
320    store: State<'_, Arc<SkillStore>>,
321) -> Result<(), AppError> {
322    apply_skill_group_to_default_impl(app, id, force.unwrap_or(false), store.inner().clone()).await
323}
324
325async fn apply_skill_group_to_default_impl(
326    app: tauri::AppHandle,
327    id: String,
328    force: bool,
329    store: Arc<SkillStore>,
330) -> Result<(), AppError> {
331    let result = tauri::async_runtime::spawn_blocking(move || {
332        scenario_service::apply_scenario_to_default(&store, &id, force)
333    })
334    .await?;
335    // Refresh even on failure. `apply_scenario_to_default` commits the active
336    // skill group before syncing, and syncing now reports ownership refusals as an
337    // error (#363) — so an error here still means the skill group switched and most
338    // skills deployed. Gating the refresh on success would leave the tray
339    // showing the old skill_group while the app is on the new one. Failures that
340    // happen before the switch make this a harmless no-op refresh.
341    refresh_tray_menu_best_effort(&app);
342    result.and_then(scenario_service::refusals_to_error)
343}
344
345#[tauri::command]
346pub async fn reorder_skill_groups(
347    app: tauri::AppHandle,
348    ids: Vec<String>,
349    store: State<'_, Arc<SkillStore>>,
350) -> Result<(), AppError> {
351    let store = store.inner().clone();
352    let result = tauri::async_runtime::spawn_blocking(move || {
353        sync_metadata::with_repo_lock("reorder scenarios", || {
354            store.reorder_scenarios(&ids)?;
355            sync_metadata::write_all_from_db_unlocked(&store)
356        })
357        .map_err(AppError::db)
358    })
359    .await?;
360    if result.is_ok() {
361        refresh_tray_menu_best_effort(&app);
362    }
363    result
364}
365
366#[tauri::command]
367pub async fn get_skill_group_skill_order(
368    skill_group_id: String,
369    store: State<'_, Arc<SkillStore>>,
370) -> Result<Vec<String>, AppError> {
371    let store = store.inner().clone();
372    tauri::async_runtime::spawn_blocking(move || {
373        store
374            .get_skill_ids_for_scenario(&skill_group_id)
375            .map_err(AppError::db)
376    })
377    .await?
378}
379
380#[tauri::command]
381pub async fn reorder_skill_group_skills(
382    skill_group_id: String,
383    skill_ids: Vec<String>,
384    store: State<'_, Arc<SkillStore>>,
385) -> Result<(), AppError> {
386    let store = store.inner().clone();
387    tauri::async_runtime::spawn_blocking(move || {
388        sync_metadata::with_repo_lock("reorder scenario skills", || {
389            store.reorder_scenario_skills(&skill_group_id, &skill_ids)?;
390            sync_metadata::write_all_from_db_unlocked(&store)
391        })
392        .map_err(AppError::db)
393    })
394    .await?
395}
396
397// ── Internal helpers ──
398
399pub(crate) fn sync_scenario_skills(
400    store: &SkillStore,
401    scenario_id: &str,
402    force: bool,
403) -> Result<Vec<scenario_service::TargetConflict>, AppError> {
404    scenario_service::sync_scenario_skills(store, scenario_id, force)
405}
406
407pub(crate) fn unsync_scenario_skills(
408    store: &SkillStore,
409    scenario_id: &str,
410) -> Result<(), AppError> {
411    scenario_service::unsync_scenario_skills(store, scenario_id)
412}
413
414#[derive(Debug, Clone, Copy, Deserialize)]
415#[serde(rename_all = "lowercase")]
416pub enum SkillGroupApplyMode {
417    Add,
418    Remove,
419}
420
421impl From<SkillGroupApplyMode> for BatchApplyMode {
422    fn from(value: SkillGroupApplyMode) -> Self {
423        match value {
424            SkillGroupApplyMode::Add => BatchApplyMode::Add,
425            SkillGroupApplyMode::Remove => BatchApplyMode::Remove,
426        }
427    }
428}
429
430/// Apply (or remove) every skill in `skill_group_id` against every enabled coding
431/// agent (`ToolCategory::Coding`). Mirrors the SkillGroupBar behavior in the
432/// global workspace view but covers all enabled coding agents at once.
433///
434/// Lobster agents are intentionally excluded — they have their own workspace
435/// and their own skill group bar.
436#[tauri::command]
437pub async fn apply_skill_group_to_coding_agents(
438    app: tauri::AppHandle,
439    skill_group_id: String,
440    mode: SkillGroupApplyMode,
441    store: State<'_, Arc<SkillStore>>,
442) -> Result<(), AppError> {
443    let store = store.inner().clone();
444    let result = tauri::async_runtime::spawn_blocking(move || {
445        scenario_service::ensure_scenario_exists(&store, &skill_group_id)?;
446        let skill_ids = store
447            .get_skill_ids_for_scenario(&skill_group_id)
448            .map_err(AppError::db)?;
449        if skill_ids.is_empty() {
450            return Ok(());
451        }
452        let tool_keys: Vec<String> = tool_adapters::enabled_deployable_adapters(&store)
453            .into_iter()
454            .filter(|adapter| matches!(adapter.category, tool_adapters::ToolCategory::Coding))
455            .map(|adapter| adapter.key)
456            .collect();
457        if tool_keys.is_empty() {
458            return Ok(());
459        }
460        scenario_service::apply_skills_to_tools(&store, &skill_ids, &tool_keys, mode.into(), false)
461    })
462    .await?;
463    if result.is_ok() {
464        refresh_tray_menu_best_effort(&app);
465    }
466    result
467}
468
469#[cfg(test)]
470mod tests;