supermaven.rs

  1mod messages;
  2mod supermaven_completion_provider;
  3
  4pub use supermaven_completion_provider::*;
  5
  6use anyhow::{Context as _, Result};
  7#[allow(unused_imports)]
  8use client::{proto, Client};
  9use collections::BTreeMap;
 10
 11use futures::{channel::mpsc, io::BufReader, AsyncBufReadExt, StreamExt};
 12use gpui::{
 13    actions, AppContext, AsyncAppContext, EntityId, Global, Model, ModelContext, Task, WeakModel,
 14};
 15use language::{
 16    language_settings::all_language_settings, Anchor, Buffer, BufferSnapshot, ToOffset,
 17};
 18use messages::*;
 19use postage::watch;
 20use serde::{Deserialize, Serialize};
 21use settings::SettingsStore;
 22use smol::{
 23    io::AsyncWriteExt,
 24    process::{Child, ChildStdin, ChildStdout, Command},
 25};
 26use std::{path::PathBuf, process::Stdio, sync::Arc};
 27use ui::prelude::*;
 28use util::ResultExt;
 29
 30actions!(supermaven, [SignOut]);
 31
 32pub fn init(client: Arc<Client>, cx: &mut AppContext) {
 33    let supermaven = cx.new_model(|_| Supermaven::Starting);
 34    Supermaven::set_global(supermaven.clone(), cx);
 35
 36    let mut provider = all_language_settings(None, cx).inline_completions.provider;
 37    if provider == language::language_settings::InlineCompletionProvider::Supermaven {
 38        supermaven.update(cx, |supermaven, cx| supermaven.start(client.clone(), cx));
 39    }
 40
 41    cx.observe_global::<SettingsStore>(move |cx| {
 42        let new_provider = all_language_settings(None, cx).inline_completions.provider;
 43        if new_provider != provider {
 44            provider = new_provider;
 45            if provider == language::language_settings::InlineCompletionProvider::Supermaven {
 46                supermaven.update(cx, |supermaven, cx| supermaven.start(client.clone(), cx));
 47            } else {
 48                supermaven.update(cx, |supermaven, _cx| supermaven.stop());
 49            }
 50        }
 51    })
 52    .detach();
 53
 54    cx.on_action(|_: &SignOut, cx| {
 55        if let Some(supermaven) = Supermaven::global(cx) {
 56            supermaven.update(cx, |supermaven, _cx| supermaven.sign_out());
 57        }
 58    });
 59}
 60
 61pub enum Supermaven {
 62    Starting,
 63    FailedDownload { error: anyhow::Error },
 64    Spawned(SupermavenAgent),
 65    Error { error: anyhow::Error },
 66}
 67
 68#[derive(Clone)]
 69pub enum AccountStatus {
 70    Unknown,
 71    NeedsActivation { activate_url: String },
 72    Ready,
 73}
 74
 75#[derive(Clone)]
 76struct SupermavenGlobal(Model<Supermaven>);
 77
 78impl Global for SupermavenGlobal {}
 79
 80impl Supermaven {
 81    pub fn global(cx: &AppContext) -> Option<Model<Self>> {
 82        cx.try_global::<SupermavenGlobal>()
 83            .map(|model| model.0.clone())
 84    }
 85
 86    pub fn set_global(supermaven: Model<Self>, cx: &mut AppContext) {
 87        cx.set_global(SupermavenGlobal(supermaven));
 88    }
 89
 90    pub fn start(&mut self, client: Arc<Client>, cx: &mut ModelContext<Self>) {
 91        if let Self::Starting = self {
 92            cx.spawn(|this, mut cx| async move {
 93                let binary_path =
 94                    supermaven_api::get_supermaven_agent_path(client.http_client()).await?;
 95
 96                this.update(&mut cx, |this, cx| {
 97                    if let Self::Starting = this {
 98                        *this =
 99                            Self::Spawned(SupermavenAgent::new(binary_path, client.clone(), cx)?);
100                    }
101                    anyhow::Ok(())
102                })
103            })
104            .detach_and_log_err(cx)
105        }
106    }
107
108    pub fn stop(&mut self) {
109        *self = Self::Starting;
110    }
111
112    pub fn is_enabled(&self) -> bool {
113        matches!(self, Self::Spawned { .. })
114    }
115
116    pub fn complete(
117        &mut self,
118        buffer: &Model<Buffer>,
119        cursor_position: Anchor,
120        cx: &AppContext,
121    ) -> Option<SupermavenCompletion> {
122        if let Self::Spawned(agent) = self {
123            let buffer_id = buffer.entity_id();
124            let buffer = buffer.read(cx);
125            let path = buffer
126                .file()
127                .and_then(|file| Some(file.as_local()?.abs_path(cx)))
128                .unwrap_or_else(|| PathBuf::from("untitled"))
129                .to_string_lossy()
130                .to_string();
131            let content = buffer.text();
132            let offset = cursor_position.to_offset(buffer);
133            let state_id = agent.next_state_id;
134            agent.next_state_id.0 += 1;
135
136            let (updates_tx, mut updates_rx) = watch::channel();
137            postage::stream::Stream::try_recv(&mut updates_rx).unwrap();
138
139            agent.states.insert(
140                state_id,
141                SupermavenCompletionState {
142                    buffer_id,
143                    prefix_anchor: cursor_position,
144                    text: String::new(),
145                    dedent: String::new(),
146                    updates_tx,
147                },
148            );
149            let _ = agent
150                .outgoing_tx
151                .unbounded_send(OutboundMessage::StateUpdate(StateUpdateMessage {
152                    new_id: state_id.0.to_string(),
153                    updates: vec![
154                        StateUpdate::FileUpdate(FileUpdateMessage {
155                            path: path.clone(),
156                            content,
157                        }),
158                        StateUpdate::CursorUpdate(CursorPositionUpdateMessage { path, offset }),
159                    ],
160                }));
161
162            Some(SupermavenCompletion {
163                id: state_id,
164                updates: updates_rx,
165            })
166        } else {
167            None
168        }
169    }
170
171    pub fn completion(
172        &self,
173        buffer: &Model<Buffer>,
174        cursor_position: Anchor,
175        cx: &AppContext,
176    ) -> Option<&str> {
177        if let Self::Spawned(agent) = self {
178            find_relevant_completion(
179                &agent.states,
180                buffer.entity_id(),
181                &buffer.read(cx).snapshot(),
182                cursor_position,
183            )
184        } else {
185            None
186        }
187    }
188
189    pub fn sign_out(&mut self) {
190        if let Self::Spawned(agent) = self {
191            agent
192                .outgoing_tx
193                .unbounded_send(OutboundMessage::Logout)
194                .ok();
195            // The account status will get set to RequiresActivation or Ready when the next
196            // message from the agent comes in. Until that happens, set the status to Unknown
197            // to disable the button.
198            agent.account_status = AccountStatus::Unknown;
199        }
200    }
201}
202
203fn find_relevant_completion<'a>(
204    states: &'a BTreeMap<SupermavenCompletionStateId, SupermavenCompletionState>,
205    buffer_id: EntityId,
206    buffer: &BufferSnapshot,
207    cursor_position: Anchor,
208) -> Option<&'a str> {
209    let mut best_completion: Option<&str> = None;
210    'completions: for state in states.values() {
211        if state.buffer_id != buffer_id {
212            continue;
213        }
214        let Some(state_completion) = state.text.strip_prefix(&state.dedent) else {
215            continue;
216        };
217
218        let current_cursor_offset = cursor_position.to_offset(buffer);
219        let original_cursor_offset = state.prefix_anchor.to_offset(buffer);
220        if current_cursor_offset < original_cursor_offset {
221            continue;
222        }
223
224        let text_inserted_since_completion_request =
225            buffer.text_for_range(original_cursor_offset..current_cursor_offset);
226        let mut trimmed_completion = state_completion;
227        for chunk in text_inserted_since_completion_request {
228            if let Some(suffix) = trimmed_completion.strip_prefix(chunk) {
229                trimmed_completion = suffix;
230            } else {
231                continue 'completions;
232            }
233        }
234
235        if best_completion.map_or(false, |best| best.len() > trimmed_completion.len()) {
236            continue;
237        }
238
239        best_completion = Some(trimmed_completion);
240    }
241    best_completion
242}
243
244pub struct SupermavenAgent {
245    _process: Child,
246    next_state_id: SupermavenCompletionStateId,
247    states: BTreeMap<SupermavenCompletionStateId, SupermavenCompletionState>,
248    outgoing_tx: mpsc::UnboundedSender<OutboundMessage>,
249    _handle_outgoing_messages: Task<Result<()>>,
250    _handle_incoming_messages: Task<Result<()>>,
251    pub account_status: AccountStatus,
252    service_tier: Option<ServiceTier>,
253    #[allow(dead_code)]
254    client: Arc<Client>,
255}
256
257impl SupermavenAgent {
258    fn new(
259        binary_path: PathBuf,
260        client: Arc<Client>,
261        cx: &mut ModelContext<Supermaven>,
262    ) -> Result<Self> {
263        let mut process = Command::new(&binary_path);
264        process
265            .arg("stdio")
266            .stdin(Stdio::piped())
267            .stdout(Stdio::piped())
268            .stderr(Stdio::piped())
269            .kill_on_drop(true);
270
271        #[cfg(target_os = "windows")]
272        {
273            use smol::process::windows::CommandExt;
274            process.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
275        }
276
277        let mut process = process.spawn().context("failed to start the binary")?;
278
279        let stdin = process
280            .stdin
281            .take()
282            .context("failed to get stdin for process")?;
283        let stdout = process
284            .stdout
285            .take()
286            .context("failed to get stdout for process")?;
287
288        let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
289
290        cx.spawn({
291            let client = client.clone();
292            let outgoing_tx = outgoing_tx.clone();
293            move |this, mut cx| async move {
294                let mut status = client.status();
295                while let Some(status) = status.next().await {
296                    if status.is_connected() {
297                        let api_key = client.request(proto::GetSupermavenApiKey {}).await?.api_key;
298                        outgoing_tx
299                            .unbounded_send(OutboundMessage::SetApiKey(SetApiKey { api_key }))
300                            .ok();
301                        this.update(&mut cx, |this, cx| {
302                            if let Supermaven::Spawned(this) = this {
303                                this.account_status = AccountStatus::Ready;
304                                cx.notify();
305                            }
306                        })?;
307                        break;
308                    }
309                }
310                return anyhow::Ok(());
311            }
312        })
313        .detach();
314
315        Ok(Self {
316            _process: process,
317            next_state_id: SupermavenCompletionStateId::default(),
318            states: BTreeMap::default(),
319            outgoing_tx,
320            _handle_outgoing_messages: cx
321                .spawn(|_, _cx| Self::handle_outgoing_messages(outgoing_rx, stdin)),
322            _handle_incoming_messages: cx
323                .spawn(|this, cx| Self::handle_incoming_messages(this, stdout, cx)),
324            account_status: AccountStatus::Unknown,
325            service_tier: None,
326            client,
327        })
328    }
329
330    async fn handle_outgoing_messages(
331        mut outgoing: mpsc::UnboundedReceiver<OutboundMessage>,
332        mut stdin: ChildStdin,
333    ) -> Result<()> {
334        while let Some(message) = outgoing.next().await {
335            let bytes = serde_json::to_vec(&message)?;
336            stdin.write_all(&bytes).await?;
337            stdin.write_all(&[b'\n']).await?;
338        }
339        Ok(())
340    }
341
342    async fn handle_incoming_messages(
343        this: WeakModel<Supermaven>,
344        stdout: ChildStdout,
345        mut cx: AsyncAppContext,
346    ) -> Result<()> {
347        const MESSAGE_PREFIX: &str = "SM-MESSAGE ";
348
349        let stdout = BufReader::new(stdout);
350        let mut lines = stdout.lines();
351        while let Some(line) = lines.next().await {
352            let Some(line) = line.context("failed to read line from stdout").log_err() else {
353                continue;
354            };
355            let Some(line) = line.strip_prefix(MESSAGE_PREFIX) else {
356                continue;
357            };
358            let Some(message) = serde_json::from_str::<SupermavenMessage>(&line)
359                .with_context(|| format!("failed to deserialize line from stdout: {:?}", line))
360                .log_err()
361            else {
362                continue;
363            };
364
365            this.update(&mut cx, |this, _cx| {
366                if let Supermaven::Spawned(this) = this {
367                    this.handle_message(message);
368                }
369                Task::ready(anyhow::Ok(()))
370            })?
371            .await?;
372        }
373
374        Ok(())
375    }
376
377    fn handle_message(&mut self, message: SupermavenMessage) {
378        match message {
379            SupermavenMessage::ActivationRequest(request) => {
380                self.account_status = match request.activate_url {
381                    Some(activate_url) => AccountStatus::NeedsActivation {
382                        activate_url: activate_url.clone(),
383                    },
384                    None => AccountStatus::Ready,
385                };
386            }
387            SupermavenMessage::ActivationSuccess => {
388                self.account_status = AccountStatus::Ready;
389            }
390            SupermavenMessage::ServiceTier { service_tier } => {
391                self.account_status = AccountStatus::Ready;
392                self.service_tier = Some(service_tier);
393            }
394            SupermavenMessage::Response(response) => {
395                let state_id = SupermavenCompletionStateId(response.state_id.parse().unwrap());
396                if let Some(state) = self.states.get_mut(&state_id) {
397                    for item in &response.items {
398                        match item {
399                            ResponseItem::Text { text } => state.text.push_str(text),
400                            ResponseItem::Dedent { text } => state.dedent.push_str(text),
401                            _ => {}
402                        }
403                    }
404                    *state.updates_tx.borrow_mut() = ();
405                }
406            }
407            SupermavenMessage::Passthrough { passthrough } => self.handle_message(*passthrough),
408            _ => {
409                log::warn!("unhandled message: {:?}", message);
410            }
411        }
412    }
413}
414
415#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
416pub struct SupermavenCompletionStateId(usize);
417
418#[allow(dead_code)]
419pub struct SupermavenCompletionState {
420    buffer_id: EntityId,
421    prefix_anchor: Anchor,
422    text: String,
423    dedent: String,
424    updates_tx: watch::Sender<()>,
425}
426
427pub struct SupermavenCompletion {
428    pub id: SupermavenCompletionStateId,
429    pub updates: watch::Receiver<()>,
430}