diff --git a/src/conversation.rs b/src/conversation.rs index 7d837f4..182d3f1 100644 --- a/src/conversation.rs +++ b/src/conversation.rs @@ -13,6 +13,7 @@ mod projects; mod queue; mod side_chat; mod sidebar; +mod skills; mod stash; mod suggestions; mod svg_preview; @@ -150,6 +151,8 @@ impl WorkspaceTab { pub struct Desktop { settings: Entity, show_settings: bool, + show_skills: bool, + skills: Option>, backlog: Backlog, #[cfg(unix)] remote_project: Option>, @@ -305,6 +308,8 @@ impl Desktop { let mut view = Self { settings, show_settings: false, + show_skills: false, + skills: None, backlog: Backlog::default(), #[cfg(unix)] remote_project: None, @@ -544,6 +549,7 @@ impl Desktop { cx: &mut Context, ) { self.show_settings = false; + self.show_skills = false; self.backlog.open = false; self.error = None; let key = (machine.environment.clone(), machine.project.clone()); @@ -563,8 +569,12 @@ impl Desktop { cx.notify(); } + fn showing_settings_or_skills(&self) -> bool { + self.show_settings || self.show_skills + } + fn local_workspace_visible(&self) -> bool { - !self.show_settings && !self.backlog.open && !self.remote_open() + !self.showing_settings_or_skills() && !self.backlog.open && !self.remote_open() } fn remote_open(&self) -> bool { @@ -584,6 +594,7 @@ impl Desktop { self.project_picker = None; self.checkout_browse = None; self.ensure_workspace(&id, window, cx)?; + self.show_skills = false; self.backlog.open = false; #[cfg(unix)] { @@ -892,18 +903,23 @@ impl Desktop { true } - fn open_settings( - &mut self, - target: SettingsTarget<'_>, - window: &mut Window, - cx: &mut Context, - ) { + fn dismiss_workspace_popovers(&mut self) { self.suggestions = Default::default(); self.model_picker = None; self.mcp_status = None; self.project_picker = None; self.checkout_browse = None; self.launch_workspace.close_picker(); + } + + fn open_settings( + &mut self, + target: SettingsTarget<'_>, + window: &mut Window, + cx: &mut Context, + ) { + self.dismiss_workspace_popovers(); + self.show_skills = false; self.show_settings = true; self.settings .update(cx, |settings, cx| settings.opened(target, window, cx)); @@ -916,6 +932,12 @@ impl Desktop { self.settings.read(cx).focus.focus(window); return; } + if self.show_skills { + if let Some(skills) = &self.skills { + skills.read(cx).focus(window, cx); + } + return; + } if self.backlog.open || self.remote_open() { self.focus.focus(window); return; @@ -940,7 +962,7 @@ impl Desktop { } pub(super) fn focus_message(&mut self, window: &mut Window, cx: &mut Context) { - if self.show_settings || self.backlog.open || self.launching.is_some() { + if self.showing_settings_or_skills() || self.backlog.open || self.launching.is_some() { return; } #[cfg(unix)] @@ -969,14 +991,10 @@ impl Desktop { if !self.leave_settings(cx) { return; } + self.show_skills = false; self.backlog.open = false; self.error = None; - self.suggestions = Default::default(); - self.model_picker = None; - self.mcp_status = None; - self.project_picker = None; - self.checkout_browse = None; - self.launch_workspace.close_picker(); + self.dismiss_workspace_popovers(); self.launch_setup = setup; #[cfg(unix)] { @@ -1292,7 +1310,7 @@ impl Desktop { .update(cx, |input, cx| input.set_value(message, w, cx)); } if still_open - && !v.show_settings + && !v.showing_settings_or_skills() && (v.backlog.open == saved_draft.is_some()) && (saved_draft.is_none() || sent.is_ok()) { @@ -2238,11 +2256,14 @@ impl Render for Desktop { }), |layout| layout.key_context(DOCUMENT_CONTEXT), ) - .when(!remote && !self.backlog.open, |layout| { - layout - .on_action(cx.listener(Self::close_active_document)) - .on_action(cx.listener(Self::save_active_document)) - }) + .when( + !remote && !self.backlog.open && !self.show_skills, + |layout| { + layout + .on_action(cx.listener(Self::close_active_document)) + .on_action(cx.listener(Self::save_active_document)) + }, + ) .on_action(cx.listener(|v, _: &crate::OpenSettings, w, cx| { v.open_settings(SettingsTarget::Overview, w, cx) })) @@ -2321,6 +2342,21 @@ impl Render for Desktop { ) })) )) + .child(control!( + "Skills", + Button::new("skills") + .small() + .compact() + .w_full() + .justify_start() + .ghost() + .icon(IconName::BookOpen) + .label("Skills") + .selected(self.show_skills) + .on_click(cx.listener(|view, _, w, cx| { + view.open_skills(w, cx) + })) + )) .child(control!( "Backlog", Button::new("backlog") @@ -2331,7 +2367,10 @@ impl Render for Desktop { .ghost() .icon(IconName::GalleryVerticalEnd) .label("Backlog") - .selected(self.backlog.open && !self.show_settings) + .selected( + self.backlog.open + && !self.showing_settings_or_skills() + ) .on_click(cx.listener(|view, _, w, cx| { view.open_backlog(w, cx) })) @@ -2397,19 +2436,24 @@ impl Render for Desktop { pane.child(self.workspace_header(navigation_open, right_open, cx)) .child(self.document_tab_strip(window, cx)) }) - .when(remote && !self.show_settings && !navigation_open, |pane| { - pane.child( - div() - .px_4() - .py_1() - .child(self.navigation_toggle(navigation_open, cx)), - ) - }) + .when( + remote && !self.showing_settings_or_skills() && !navigation_open, + |pane| { + pane.child( + div() + .px_4() + .py_1() + .child(self.navigation_toggle(navigation_open, cx)), + ) + }, + ) .child(if self.show_settings { let toggle = self.navigation_toggle(navigation_open, cx); self.settings .update(cx, |settings, cx| settings.panel(toggle, window, cx)) .into_any_element() + } else if self.show_skills { + self.skills_page(navigation_open, cx).into_any_element() } else if self.backlog.open { self.backlog_page(navigation_open, conversation_width, cx) .into_any_element() diff --git a/src/conversation/backlog.rs b/src/conversation/backlog.rs index d716e09..5f698f0 100644 --- a/src/conversation/backlog.rs +++ b/src/conversation/backlog.rs @@ -218,6 +218,7 @@ impl Desktop { self.backlog.expanded_details.clear(); self.backlog.scroll.set_offset(Point::default()); } + self.show_skills = false; self.backlog.open = true; self.error = self .load_backlog() diff --git a/src/conversation/document_tabs/editor.rs b/src/conversation/document_tabs/editor.rs index 220b61b..ec90d2b 100644 --- a/src/conversation/document_tabs/editor.rs +++ b/src/conversation/document_tabs/editor.rs @@ -179,7 +179,7 @@ impl Desktop { tab.mode == DocumentMode::Raw && tab.document.path() == Some(editor_path.as_ref()) }) - && !view.show_settings + && !view.showing_settings_or_skills() && !window.has_active_dialog(cx) { draft.input.focus_handle(cx).focus(window); diff --git a/src/conversation/skills.rs b/src/conversation/skills.rs new file mode 100644 index 0000000..2b13ea7 --- /dev/null +++ b/src/conversation/skills.rs @@ -0,0 +1,378 @@ +mod detail; + +use super::*; +use detail::SkillDetail; +use serde::Deserialize; +use std::time::Duration; +use url::Url; + +const CATALOG: &str = "https://skills.sh"; +const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024; + +async fn fetch_catalog_response(url: Url) -> anyhow::Result> { + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build()?; + let mut response = client.get(url).send().await?.error_for_status()?; + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await? { + anyhow::ensure!( + bytes.len() + chunk.len() <= MAX_RESPONSE_BYTES, + "skills.sh response is too large" + ); + bytes.extend_from_slice(&chunk); + } + Ok(bytes) +} + +#[derive(Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Skill { + source: String, + skill_id: String, + name: String, + installs: u64, +} + +impl Skill { + fn url(&self) -> Option { + let mut url = Url::parse(CATALOG).ok()?; + { + let mut path = url.path_segments_mut().ok()?; + if !self.source.contains('/') { + path.push("site"); + } + for segment in self.source.split('/').chain([self.skill_id.as_str()]) { + if segment.is_empty() || matches!(segment, "." | "..") { + return None; + } + path.push(&segment.to_ascii_lowercase()); + } + } + Some(url) + } + fn install_count(&self) -> String { + match self.installs { + count if count >= 1_000_000_000 => format!("{}B+", count / 1_000_000_000), + count if count >= 1_000_000 => format!("{}M+", count / 1_000_000), + count if count >= 1_000 => format!("{}K+", count / 1_000), + count => count.to_string(), + } + } + + fn row(&self, index: usize, cx: &Context) -> Div { + let skill = self.clone(); + let action = format!("Open {} on skills.sh", self.name); + h_flex() + .min_w_0() + .gap_3() + .py_2() + .border_t_1() + .border_color(cx.theme().border) + .child( + control!( + format!("View details for {} ({})", self.name, self.source), + Button::new(("skill-detail", index)) + .ghost() + .w_full() + .min_w_0() + .h_10() + .px_1() + .justify_start() + .overflow_hidden() + .child( + v_flex() + .min_w_0() + .items_start() + .child(label(self.name.clone()).w_full().truncate()) + .child(hint(self.source.clone(), cx).w_full().text_xs().truncate()), + ) + .on_click(cx.listener(move |view, _, window, cx| { + view.open_detail(skill.clone(), window, cx); + })) + ) + .flex_1() + .min_w_0(), + ) + .child(hint(format!("{} installs", self.install_count()), cx).text_xs()) + .when_some(self.url(), |row, url| { + row.child(control!( + action.clone(), + Button::new(("open-skill", index)) + .small() + .ghost() + .icon(IconName::ExternalLink) + .tooltip(action) + .on_click(move |_, _, cx| cx.open_url(url.as_str())) + )) + }) + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct CatalogPage { + skills: Vec, + #[serde(default)] + has_more: bool, +} + +#[derive(Clone)] +enum Request { + Browse(usize), + Search(String), +} + +impl Request { + async fn fetch(self) -> anyhow::Result { + // Use the public directory endpoints used by the skills.sh website. + // The documented v1 endpoints require a Vercel project token. + let mut url = match &self { + Self::Browse(page) => Url::parse(&format!("{CATALOG}/api/skills/all-time/{page}"))?, + Self::Search(_) => Url::parse(&format!("{CATALOG}/api/search"))?, + }; + if let Self::Search(query) = &self { + url.query_pairs_mut() + .append_pair("q", query) + .append_pair("limit", "50"); + } + Ok(serde_json::from_slice(&fetch_catalog_response(url).await?)?) + } +} + +pub(super) struct Skills { + input: Entity, + executor: tokio::runtime::Handle, + query: String, + rows: Vec, + next_page: Option, + failed: Option, + pending: Option>, + scroll: ScrollHandle, + detail: Option, +} + +impl Skills { + pub fn new( + executor: tokio::runtime::Handle, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search skills")); + cx.subscribe(&input, |view, input, event, cx| { + if matches!(event, InputEvent::Change) { + let value = input.read(cx).value(); + let query = value.trim(); + if view.query != query { + view.query = query.to_owned(); + view.rows.clear(); + view.next_page = None; + view.failed = None; + view.pending = None; + view.scroll.set_offset(Point::default()); + if query.is_empty() { + view.load(Request::Browse(0), cx); + } else if query.chars().count() >= 2 { + view.load(Request::Search(query.to_owned()), cx); + } + cx.notify(); + } + } + }) + .detach(); + Self { + input, + executor, + query: String::new(), + rows: Vec::new(), + next_page: None, + failed: None, + pending: None, + scroll: ScrollHandle::new(), + detail: None, + } + } + + fn load(&mut self, request: Request, cx: &mut Context) { + self.failed = None; + let executor = self.executor.clone(); + self.pending = Some(cx.spawn(async move |view, cx| { + if matches!(request, Request::Search(_)) { + smol::Timer::after(Duration::from_millis(300)).await; + } + let page = executor.spawn(request.clone().fetch()).await; + let _ = view.update(cx, |view, cx| { + match page { + Ok(Ok(page)) => { + view.next_page = match request { + Request::Browse(index) if page.has_more => Some(index + 1), + _ => None, + }; + view.rows.extend(page.skills); + } + _ => view.failed = Some(request), + } + view.pending = None; + cx.notify(); + }); + })); + cx.notify(); + } +} + +impl Render for Skills { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + if let Some(detail) = &self.detail { + return detail.render(window, cx); + } + let browse = self.query.is_empty(); + let status = if self.pending.is_some() { + Some(if browse { + "Loading skills…" + } else { + "Searching…" + }) + } else if self.failed.is_some() { + Some("Couldn’t load skills from skills.sh.") + } else if self.query.chars().count() == 1 { + Some("Enter at least two characters to search.") + } else if self.rows.is_empty() { + Some("No skills found.") + } else { + None + }; + + v_flex() + .flex_1() + .min_h_0() + .items_center() + .child( + v_flex() + .w_full() + .max_w(px(720.)) + .px_4() + .pt_5() + .pb_3() + .gap_3() + .child(control!( + "Search skills", + Input::new(&self.input) + .prefix(Icon::new(IconName::Search)) + .cleanable(true) + )) + .child(label(if browse { + "Popular skills" + } else { + "Search results" + })), + ) + .child( + crate::ui::keyboard_scroll_area("skills-list", &self.scroll, window, cx) + .w_full() + .flex_1() + .min_h_0() + .overflow_y_scroll() + .child( + v_flex().items_center().w_full().child( + v_flex() + .w_full() + .max_w(px(720.)) + .px_4() + .pb_5() + .children( + self.rows + .iter() + .enumerate() + .map(|(index, skill)| skill.row(index, cx)), + ) + .when_some(status, |list, message| { + list.child(control!(message, hint(message, cx).py_3())) + }) + .when_some(self.failed.clone(), |list, request| { + list.child( + Button::new("retry-skills") + .small() + .label("Retry") + .on_click(cx.listener(move |view, _, _, cx| { + view.load(request.clone(), cx) + })), + ) + }) + .when(self.pending.is_none() && self.failed.is_none(), |list| { + list.when_some(self.next_page, |list, page| { + list.child( + Button::new("more-skills") + .small() + .label("Load more") + .on_click(cx.listener(move |view, _, _, cx| { + view.load(Request::Browse(page), cx) + })), + ) + }) + }), + ), + ), + ) + } +} + +impl Desktop { + pub(super) fn skills_page(&self, navigation_open: bool, cx: &Context) -> Div { + v_flex() + .flex_1() + .min_h_0() + .child( + h_flex() + .h_10() + .flex_shrink_0() + .px_4() + .border_b_1() + .border_color(cx.theme().border) + .gap_2() + .child(self.navigation_toggle(navigation_open, cx)) + .child(label("Skills")), + ) + .children(self.skills.clone()) + } + + pub(super) fn open_skills(&mut self, window: &mut Window, cx: &mut Context) { + if !self.leave_settings(cx) { + return; + } + self.dismiss_workspace_popovers(); + let skills = self.skills.get_or_insert_with(|| { + cx.new(|cx| { + let mut skills = Skills::new(self.executor.clone(), window, cx); + skills.load(Request::Browse(0), cx); + skills + }) + }); + self.show_skills = true; + skills.read(cx).focus(window, cx); + cx.notify(); + } +} + +#[cfg(test)] +mod tests { + use super::Skill; + + #[test] + fn skill_urls_match_repository_and_domain_routes() { + let mut skill = Skill { + source: "Mintlify/Docs".into(), + skill_id: "mintlify".into(), + name: "Mintlify".into(), + installs: 0, + }; + assert_eq!( + skill.url().unwrap().as_str(), + "https://skills.sh/mintlify/docs/mintlify" + ); + skill.source = "Mintlify.com".into(); + assert_eq!( + skill.url().unwrap().as_str(), + "https://skills.sh/site/mintlify.com/mintlify" + ); + } +} diff --git a/src/conversation/skills/detail.rs b/src/conversation/skills/detail.rs new file mode 100644 index 0000000..594daa8 --- /dev/null +++ b/src/conversation/skills/detail.rs @@ -0,0 +1,249 @@ +use super::*; + +#[derive(Deserialize)] +struct SkillMetadata { + #[serde(rename = "@type")] + kind: String, + description: Option, +} + +fn description(html: &str) -> Option { + // Read the public page's structured metadata without rendering remote HTML. + html.split("").map(|(json, _)| json)) + .filter_map(|json| serde_json::from_str::(json).ok()) + .find(|metadata| metadata.kind == "SoftwareApplication") + .and_then(|metadata| metadata.description) + .filter(|description| !description.trim().is_empty()) + .or_else(|| preview_overview(html)) +} + +fn preview_overview(html: &str) -> Option { + // Domain-hosted skills have a SKILL.md preview in place of a JSON-LD overview. + let (_, preview) = html.split_once("SKILL.md")?; + let (preview, _) = preview.split_once("")?; + let (_, paragraph) = preview.split_once("

")?; + let (paragraph, _) = paragraph.split_once("

")?; + let fragment = format!("

{paragraph}

"); + let document = roxmltree::Document::parse(&fragment).ok()?; + let text = document + .descendants() + .filter(|node| node.is_text()) + .filter_map(|node| node.text()) + .collect::(); + let text = text.trim(); + (!text.is_empty()).then(|| text.to_owned()) +} + +async fn fetch_description(url: Url) -> anyhow::Result> { + let bytes = fetch_catalog_response(url).await?; + Ok(description(std::str::from_utf8(&bytes)?)) +} + +enum Overview { + Loading, + Available(String), + Missing, + Failed, +} + +pub(super) struct SkillDetail { + skill: Skill, + overview: Overview, + pending: Option>, + focus: FocusHandle, + scroll: ScrollHandle, +} + +impl Skills { + pub fn focus(&self, window: &mut Window, cx: &App) { + match &self.detail { + Some(detail) => detail.focus.focus(window), + None => self.input.focus_handle(cx).focus(window), + } + } + + pub(super) fn open_detail( + &mut self, + skill: Skill, + window: &mut Window, + cx: &mut Context, + ) { + self.detail = Some(SkillDetail { + skill, + overview: Overview::Missing, + pending: None, + focus: cx.focus_handle(), + scroll: ScrollHandle::new(), + }); + self.focus(window, cx); + self.load_overview(cx); + } + + fn close_detail(&mut self, window: &mut Window, cx: &mut Context) { + self.detail = None; + self.focus(window, cx); + cx.notify(); + } + + fn load_overview(&mut self, cx: &mut Context) { + let Some(detail) = &mut self.detail else { + return; + }; + if let Some(url) = detail.skill.url() { + detail.overview = Overview::Loading; + let job = self.executor.spawn(fetch_description(url)); + detail.pending = Some(cx.spawn(async move |view, cx| { + let result = job.await; + let _ = view.update(cx, |view, cx| { + if let Some(detail) = &mut view.detail { + detail.overview = match result { + Ok(Ok(Some(text))) => Overview::Available(text), + Ok(Ok(None)) => Overview::Missing, + _ => Overview::Failed, + }; + detail.pending = None; + cx.notify(); + } + }); + })); + } + cx.notify(); + } +} + +impl SkillDetail { + pub(super) fn render(&self, window: &mut Window, cx: &mut Context) -> Div { + let skill = &self.skill; + let border = cx.theme().border; + v_flex() + .track_focus(&self.focus) + .on_key_down(cx.listener(|view, event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "escape" { + cx.stop_propagation(); + view.close_detail(window, cx); + } + })) + .flex_1() + .min_h_0() + .items_center() + .child( + h_flex() + .w_full() + .max_w(px(720.)) + .px_4() + .pt_3() + .pb_2() + .child(control!( + "Back to skills", + Button::new("back-to-skills") + .ghost() + .small() + .compact() + .icon(IconName::ArrowLeft) + .label("Back to skills") + .on_click( + cx.listener(|view, _, window, cx| view.close_detail(window, cx)) + ) + )), + ) + .child( + crate::ui::keyboard_scroll_area("skill-detail", &self.scroll, window, cx) + .w_full() + .flex_1() + .min_h_0() + .overflow_y_scroll() + .child( + v_flex().items_center().w_full().child( + v_flex() + .w_full() + .min_w_0() + .max_w(px(720.)) + .px_4() + .pt_3() + .pb_6() + .gap_5() + .child( + v_flex() + .gap_1() + .child(heading(skill.name.clone())) + .child(hint(skill.source.clone(), cx)), + ) + .child( + h_flex() + .flex_wrap() + .gap_3() + .child(hint( + format!("{} installs", skill.install_count()), + cx, + )) + .when_some(skill.url(), |row, url| { + row.child( + Button::new("skill-website") + .small() + .outline() + .icon(IconName::ExternalLink) + .label("View on skills.sh") + .on_click(move |_, _, cx| { + cx.open_url(url.as_str()) + }), + ) + }), + ) + .child( + v_flex() + .border_t_1() + .border_color(border) + .pt_4() + .gap_2() + .child(label("Overview")) + .child(match &self.overview { + Overview::Loading => hint("Loading overview…", cx), + Overview::Available(description) => control!( + "Skill overview", + div() + .text_sm() + .line_height(relative(1.55)) + .child(description.clone()) + ), + Overview::Missing => { + hint("No overview is available on skills.sh.", cx) + } + Overview::Failed => { + hint("Couldn’t load the skill overview.", cx) + } + }) + .when( + matches!(self.overview, Overview::Failed), + |section| { + section.child( + Button::new("retry-skill") + .small() + .label("Retry") + .on_click(cx.listener(|view, _, _, cx| { + view.load_overview(cx) + })), + ) + }, + ), + ), + ), + ), + ) + } +} + +#[cfg(test)] +mod tests { + use super::description; + + #[test] + fn domain_skill_overview_uses_preview_text() { + let html = r#"

Site navigation.

SKILL.md

Reference

Read the guide for setup & examples.

Later section.

"#; + assert_eq!( + description(html).as_deref(), + Some("Read the guide for setup & examples.") + ); + } +}