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            .arg("stdio")
265            .stdin(Stdio::piped())
266            .stdout(Stdio::piped())
267            .stderr(Stdio::piped())
268            .kill_on_drop(true)
269            .spawn()
270            .context("failed to start the binary")?;
271
272        let stdin = process
273            .stdin
274            .take()
275            .context("failed to get stdin for process")?;
276        let stdout = process
277            .stdout
278            .take()
279            .context("failed to get stdout for process")?;
280
281        let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
282
283        cx.spawn({
284            let client = client.clone();
285            let outgoing_tx = outgoing_tx.clone();
286            move |this, mut cx| async move {
287                let mut status = client.status();
288                while let Some(status) = status.next().await {
289                    if status.is_connected() {
290                        let api_key = client.request(proto::GetSupermavenApiKey {}).await?.api_key;
291                        outgoing_tx
292                            .unbounded_send(OutboundMessage::SetApiKey(SetApiKey { api_key }))
293                            .ok();
294                        this.update(&mut cx, |this, cx| {
295                            if let Supermaven::Spawned(this) = this {
296                                this.account_status = AccountStatus::Ready;
297                                cx.notify();
298                            }
299                        })?;
300                        break;
301                    }
302                }
303                return anyhow::Ok(());
304            }
305        })
306        .detach();
307
308        Ok(Self {
309            _process: process,
310            next_state_id: SupermavenCompletionStateId::default(),
311            states: BTreeMap::default(),
312            outgoing_tx,
313            _handle_outgoing_messages: cx
314                .spawn(|_, _cx| Self::handle_outgoing_messages(outgoing_rx, stdin)),
315            _handle_incoming_messages: cx
316                .spawn(|this, cx| Self::handle_incoming_messages(this, stdout, cx)),
317            account_status: AccountStatus::Unknown,
318            service_tier: None,
319            client,
320        })
321    }
322
323    async fn handle_outgoing_messages(
324        mut outgoing: mpsc::UnboundedReceiver<OutboundMessage>,
325        mut stdin: ChildStdin,
326    ) -> Result<()> {
327        while let Some(message) = outgoing.next().await {
328            let bytes = serde_json::to_vec(&message)?;
329            stdin.write_all(&bytes).await?;
330            stdin.write_all(&[b'\n']).await?;
331        }
332        Ok(())
333    }
334
335    async fn handle_incoming_messages(
336        this: WeakModel<Supermaven>,
337        stdout: ChildStdout,
338        mut cx: AsyncAppContext,
339    ) -> Result<()> {
340        const MESSAGE_PREFIX: &str = "SM-MESSAGE ";
341
342        let stdout = BufReader::new(stdout);
343        let mut lines = stdout.lines();
344        while let Some(line) = lines.next().await {
345            let Some(line) = line.context("failed to read line from stdout").log_err() else {
346                continue;
347            };
348            let Some(line) = line.strip_prefix(MESSAGE_PREFIX) else {
349                continue;
350            };
351            let Some(message) = serde_json::from_str::<SupermavenMessage>(&line)
352                .with_context(|| format!("failed to deserialize line from stdout: {:?}", line))
353                .log_err()
354            else {
355                continue;
356            };
357
358            this.update(&mut cx, |this, _cx| {
359                if let Supermaven::Spawned(this) = this {
360                    this.handle_message(message);
361                }
362                Task::ready(anyhow::Ok(()))
363            })?
364            .await?;
365        }
366
367        Ok(())
368    }
369
370    fn handle_message(&mut self, message: SupermavenMessage) {
371        match message {
372            SupermavenMessage::ActivationRequest(request) => {
373                self.account_status = match request.activate_url {
374                    Some(activate_url) => AccountStatus::NeedsActivation {
375                        activate_url: activate_url.clone(),
376                    },
377                    None => AccountStatus::Ready,
378                };
379            }
380            SupermavenMessage::ActivationSuccess => {
381                self.account_status = AccountStatus::Ready;
382            }
383            SupermavenMessage::ServiceTier { service_tier } => {
384                self.account_status = AccountStatus::Ready;
385                self.service_tier = Some(service_tier);
386            }
387            SupermavenMessage::Response(response) => {
388                let state_id = SupermavenCompletionStateId(response.state_id.parse().unwrap());
389                if let Some(state) = self.states.get_mut(&state_id) {
390                    for item in &response.items {
391                        match item {
392                            ResponseItem::Text { text } => state.text.push_str(text),
393                            ResponseItem::Dedent { text } => state.dedent.push_str(text),
394                            _ => {}
395                        }
396                    }
397                    *state.updates_tx.borrow_mut() = ();
398                }
399            }
400            SupermavenMessage::Passthrough { passthrough } => self.handle_message(*passthrough),
401            _ => {
402                log::warn!("unhandled message: {:?}", message);
403            }
404        }
405    }
406}
407
408#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
409pub struct SupermavenCompletionStateId(usize);
410
411#[allow(dead_code)]
412pub struct SupermavenCompletionState {
413    buffer_id: EntityId,
414    prefix_anchor: Anchor,
415    text: String,
416    dedent: String,
417    updates_tx: watch::Sender<()>,
418}
419
420pub struct SupermavenCompletion {
421    pub id: SupermavenCompletionStateId,
422    pub updates: watch::Receiver<()>,
423}