fetch_command.rs

  1use std::sync::atomic::AtomicBool;
  2use std::sync::Arc;
  3
  4use anyhow::{anyhow, bail, Context, Result};
  5use assistant_slash_command::{SlashCommand, SlashCommandOutput, SlashCommandOutputSection};
  6use futures::AsyncReadExt;
  7use gpui::{AppContext, Task, WeakView};
  8use html_to_markdown::{convert_html_to_markdown, markdown, HandleTag};
  9use http::{AsyncBody, HttpClient, HttpClientWithUrl};
 10use language::LspAdapterDelegate;
 11use ui::{prelude::*, ButtonLike, ElevationIndex};
 12use workspace::Workspace;
 13
 14pub(crate) struct FetchSlashCommand;
 15
 16impl FetchSlashCommand {
 17    async fn build_message(http_client: Arc<HttpClientWithUrl>, url: &str) -> Result<String> {
 18        let mut url = url.to_owned();
 19        if !url.starts_with("https://") {
 20            url = format!("https://{url}");
 21        }
 22
 23        let mut response = http_client.get(&url, AsyncBody::default(), true).await?;
 24
 25        let mut body = Vec::new();
 26        response
 27            .body_mut()
 28            .read_to_end(&mut body)
 29            .await
 30            .context("error reading response body")?;
 31
 32        if response.status().is_client_error() {
 33            let text = String::from_utf8_lossy(body.as_slice());
 34            bail!(
 35                "status error {}, response: {text:?}",
 36                response.status().as_u16()
 37            );
 38        }
 39
 40        let mut handlers: Vec<Box<dyn HandleTag>> = vec![
 41            Box::new(markdown::ParagraphHandler),
 42            Box::new(markdown::HeadingHandler),
 43            Box::new(markdown::ListHandler),
 44            Box::new(markdown::TableHandler::new()),
 45            Box::new(markdown::StyledTextHandler),
 46            Box::new(markdown::CodeHandler),
 47        ];
 48        if url.contains("wikipedia.org") {
 49            use html_to_markdown::structure::wikipedia;
 50
 51            handlers.push(Box::new(wikipedia::WikipediaChromeRemover));
 52        }
 53
 54        convert_html_to_markdown(&body[..], handlers)
 55    }
 56}
 57
 58impl SlashCommand for FetchSlashCommand {
 59    fn name(&self) -> String {
 60        "fetch".into()
 61    }
 62
 63    fn description(&self) -> String {
 64        "insert URL contents".into()
 65    }
 66
 67    fn menu_text(&self) -> String {
 68        "Insert fetched URL contents".into()
 69    }
 70
 71    fn requires_argument(&self) -> bool {
 72        true
 73    }
 74
 75    fn complete_argument(
 76        &self,
 77        _query: String,
 78        _cancel: Arc<AtomicBool>,
 79        _workspace: Option<WeakView<Workspace>>,
 80        _cx: &mut AppContext,
 81    ) -> Task<Result<Vec<String>>> {
 82        Task::ready(Ok(Vec::new()))
 83    }
 84
 85    fn run(
 86        self: Arc<Self>,
 87        argument: Option<&str>,
 88        workspace: WeakView<Workspace>,
 89        _delegate: Arc<dyn LspAdapterDelegate>,
 90        cx: &mut WindowContext,
 91    ) -> Task<Result<SlashCommandOutput>> {
 92        let Some(argument) = argument else {
 93            return Task::ready(Err(anyhow!("missing URL")));
 94        };
 95        let Some(workspace) = workspace.upgrade() else {
 96            return Task::ready(Err(anyhow!("workspace was dropped")));
 97        };
 98
 99        let http_client = workspace.read(cx).client().http_client();
100        let url = argument.to_string();
101
102        let text = cx.background_executor().spawn({
103            let url = url.clone();
104            async move { Self::build_message(http_client, &url).await }
105        });
106
107        let url = SharedString::from(url);
108        cx.foreground_executor().spawn(async move {
109            let text = text.await?;
110            let range = 0..text.len();
111            Ok(SlashCommandOutput {
112                text,
113                sections: vec![SlashCommandOutputSection {
114                    range,
115                    render_placeholder: Arc::new(move |id, unfold, _cx| {
116                        FetchPlaceholder {
117                            id,
118                            unfold,
119                            url: url.clone(),
120                        }
121                        .into_any_element()
122                    }),
123                }],
124                run_commands_in_text: false,
125            })
126        })
127    }
128}
129
130#[derive(IntoElement)]
131struct FetchPlaceholder {
132    pub id: ElementId,
133    pub unfold: Arc<dyn Fn(&mut WindowContext)>,
134    pub url: SharedString,
135}
136
137impl RenderOnce for FetchPlaceholder {
138    fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
139        let unfold = self.unfold;
140
141        ButtonLike::new(self.id)
142            .style(ButtonStyle::Filled)
143            .layer(ElevationIndex::ElevatedSurface)
144            .child(Icon::new(IconName::AtSign))
145            .child(Label::new(format!("fetch {url}", url = self.url)))
146            .on_click(move |_, cx| unfold(cx))
147    }
148}