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 prefix_offset: offset,
145 text: String::new(),
146 dedent: String::new(),
147 updates_tx,
148 },
149 );
150 let _ = agent
151 .outgoing_tx
152 .unbounded_send(OutboundMessage::StateUpdate(StateUpdateMessage {
153 new_id: state_id.0.to_string(),
154 updates: vec![
155 StateUpdate::FileUpdate(FileUpdateMessage {
156 path: path.clone(),
157 content,
158 }),
159 StateUpdate::CursorUpdate(CursorPositionUpdateMessage { path, offset }),
160 ],
161 }));
162
163 Some(SupermavenCompletion {
164 id: state_id,
165 updates: updates_rx,
166 })
167 } else {
168 None
169 }
170 }
171
172 pub fn completion(
173 &self,
174 buffer: &Model<Buffer>,
175 cursor_position: Anchor,
176 cx: &AppContext,
177 ) -> Option<&str> {
178 if let Self::Spawned(agent) = self {
179 find_relevant_completion(
180 &agent.states,
181 buffer.entity_id(),
182 &buffer.read(cx).snapshot(),
183 cursor_position,
184 )
185 } else {
186 None
187 }
188 }
189
190 pub fn sign_out(&mut self) {
191 if let Self::Spawned(agent) = self {
192 agent
193 .outgoing_tx
194 .unbounded_send(OutboundMessage::Logout)
195 .ok();
196 // The account status will get set to RequiresActivation or Ready when the next
197 // message from the agent comes in. Until that happens, set the status to Unknown
198 // to disable the button.
199 agent.account_status = AccountStatus::Unknown;
200 }
201 }
202}
203
204fn find_relevant_completion<'a>(
205 states: &'a BTreeMap<SupermavenCompletionStateId, SupermavenCompletionState>,
206 buffer_id: EntityId,
207 buffer: &BufferSnapshot,
208 cursor_position: Anchor,
209) -> Option<&'a str> {
210 let mut best_completion: Option<&str> = None;
211 'completions: for state in states.values() {
212 if state.buffer_id != buffer_id {
213 continue;
214 }
215 let Some(state_completion) = state.text.strip_prefix(&state.dedent) else {
216 continue;
217 };
218
219 let current_cursor_offset = cursor_position.to_offset(buffer);
220 if current_cursor_offset < state.prefix_offset {
221 continue;
222 }
223
224 let original_cursor_offset = buffer.clip_offset(state.prefix_offset, text::Bias::Left);
225 let text_inserted_since_completion_request =
226 buffer.text_for_range(original_cursor_offset..current_cursor_offset);
227 let mut trimmed_completion = state_completion;
228 for chunk in text_inserted_since_completion_request {
229 if let Some(suffix) = trimmed_completion.strip_prefix(chunk) {
230 trimmed_completion = suffix;
231 } else {
232 continue 'completions;
233 }
234 }
235
236 if best_completion.map_or(false, |best| best.len() > trimmed_completion.len()) {
237 continue;
238 }
239
240 best_completion = Some(trimmed_completion);
241 }
242 best_completion
243}
244
245pub struct SupermavenAgent {
246 _process: Child,
247 next_state_id: SupermavenCompletionStateId,
248 states: BTreeMap<SupermavenCompletionStateId, SupermavenCompletionState>,
249 outgoing_tx: mpsc::UnboundedSender<OutboundMessage>,
250 _handle_outgoing_messages: Task<Result<()>>,
251 _handle_incoming_messages: Task<Result<()>>,
252 pub account_status: AccountStatus,
253 service_tier: Option<ServiceTier>,
254 #[allow(dead_code)]
255 client: Arc<Client>,
256}
257
258impl SupermavenAgent {
259 fn new(
260 binary_path: PathBuf,
261 client: Arc<Client>,
262 cx: &mut ModelContext<Supermaven>,
263 ) -> Result<Self> {
264 let mut process = Command::new(&binary_path);
265 process
266 .arg("stdio")
267 .stdin(Stdio::piped())
268 .stdout(Stdio::piped())
269 .stderr(Stdio::piped())
270 .kill_on_drop(true);
271
272 #[cfg(target_os = "windows")]
273 {
274 use smol::process::windows::CommandExt;
275 process.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
276 }
277
278 let mut process = process.spawn().context("failed to start the binary")?;
279
280 let stdin = process
281 .stdin
282 .take()
283 .context("failed to get stdin for process")?;
284 let stdout = process
285 .stdout
286 .take()
287 .context("failed to get stdout for process")?;
288
289 let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
290
291 cx.spawn({
292 let client = client.clone();
293 let outgoing_tx = outgoing_tx.clone();
294 move |this, mut cx| async move {
295 let mut status = client.status();
296 while let Some(status) = status.next().await {
297 if status.is_connected() {
298 let api_key = client.request(proto::GetSupermavenApiKey {}).await?.api_key;
299 outgoing_tx
300 .unbounded_send(OutboundMessage::SetApiKey(SetApiKey { api_key }))
301 .ok();
302 this.update(&mut cx, |this, cx| {
303 if let Supermaven::Spawned(this) = this {
304 this.account_status = AccountStatus::Ready;
305 cx.notify();
306 }
307 })?;
308 break;
309 }
310 }
311 anyhow::Ok(())
312 }
313 })
314 .detach();
315
316 Ok(Self {
317 _process: process,
318 next_state_id: SupermavenCompletionStateId::default(),
319 states: BTreeMap::default(),
320 outgoing_tx,
321 _handle_outgoing_messages: cx
322 .spawn(|_, _cx| Self::handle_outgoing_messages(outgoing_rx, stdin)),
323 _handle_incoming_messages: cx
324 .spawn(|this, cx| Self::handle_incoming_messages(this, stdout, cx)),
325 account_status: AccountStatus::Unknown,
326 service_tier: None,
327 client,
328 })
329 }
330
331 async fn handle_outgoing_messages(
332 mut outgoing: mpsc::UnboundedReceiver<OutboundMessage>,
333 mut stdin: ChildStdin,
334 ) -> Result<()> {
335 while let Some(message) = outgoing.next().await {
336 let bytes = serde_json::to_vec(&message)?;
337 stdin.write_all(&bytes).await?;
338 stdin.write_all(&[b'\n']).await?;
339 }
340 Ok(())
341 }
342
343 async fn handle_incoming_messages(
344 this: WeakModel<Supermaven>,
345 stdout: ChildStdout,
346 mut cx: AsyncAppContext,
347 ) -> Result<()> {
348 const MESSAGE_PREFIX: &str = "SM-MESSAGE ";
349
350 let stdout = BufReader::new(stdout);
351 let mut lines = stdout.lines();
352 while let Some(line) = lines.next().await {
353 let Some(line) = line.context("failed to read line from stdout").log_err() else {
354 continue;
355 };
356 let Some(line) = line.strip_prefix(MESSAGE_PREFIX) else {
357 continue;
358 };
359 let Some(message) = serde_json::from_str::<SupermavenMessage>(line)
360 .with_context(|| format!("failed to deserialize line from stdout: {:?}", line))
361 .log_err()
362 else {
363 continue;
364 };
365
366 this.update(&mut cx, |this, _cx| {
367 if let Supermaven::Spawned(this) = this {
368 this.handle_message(message);
369 }
370 Task::ready(anyhow::Ok(()))
371 })?
372 .await?;
373 }
374
375 Ok(())
376 }
377
378 fn handle_message(&mut self, message: SupermavenMessage) {
379 match message {
380 SupermavenMessage::ActivationRequest(request) => {
381 self.account_status = match request.activate_url {
382 Some(activate_url) => AccountStatus::NeedsActivation {
383 activate_url: activate_url.clone(),
384 },
385 None => AccountStatus::Ready,
386 };
387 }
388 SupermavenMessage::ActivationSuccess => {
389 self.account_status = AccountStatus::Ready;
390 }
391 SupermavenMessage::ServiceTier { service_tier } => {
392 self.account_status = AccountStatus::Ready;
393 self.service_tier = Some(service_tier);
394 }
395 SupermavenMessage::Response(response) => {
396 let state_id = SupermavenCompletionStateId(response.state_id.parse().unwrap());
397 if let Some(state) = self.states.get_mut(&state_id) {
398 for item in &response.items {
399 match item {
400 ResponseItem::Text { text } => state.text.push_str(text),
401 ResponseItem::Dedent { text } => state.dedent.push_str(text),
402 _ => {}
403 }
404 }
405 *state.updates_tx.borrow_mut() = ();
406 }
407 }
408 SupermavenMessage::Passthrough { passthrough } => self.handle_message(*passthrough),
409 _ => {
410 log::warn!("unhandled message: {:?}", message);
411 }
412 }
413 }
414}
415
416#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
417pub struct SupermavenCompletionStateId(usize);
418
419#[allow(dead_code)]
420pub struct SupermavenCompletionState {
421 buffer_id: EntityId,
422 prefix_anchor: Anchor,
423 // prefix_offset is tracked independently because the anchor biases left which
424 // doesn't allow us to determine if the prior text has been deleted.
425 prefix_offset: usize,
426 text: String,
427 dedent: String,
428 updates_tx: watch::Sender<()>,
429}
430
431pub struct SupermavenCompletion {
432 pub id: SupermavenCompletionStateId,
433 pub updates: watch::Receiver<()>,
434}