headless_project.rs

  1use ::proto::{FromProto, ToProto};
  2use anyhow::{anyhow, Context as _, Result};
  3use extension::ExtensionHostProxy;
  4use extension_host::headless_host::HeadlessExtensionStore;
  5use fs::Fs;
  6use git::repository::RepoPath;
  7use gpui::{App, AppContext as _, AsyncApp, Context, Entity, PromptLevel, SharedString};
  8use http_client::HttpClient;
  9use language::{proto::serialize_operation, Buffer, BufferEvent, LanguageRegistry};
 10use node_runtime::NodeRuntime;
 11use project::{
 12    buffer_store::{BufferStore, BufferStoreEvent},
 13    git::{GitState, Repository},
 14    project_settings::SettingsObserver,
 15    search::SearchQuery,
 16    task_store::TaskStore,
 17    worktree_store::WorktreeStore,
 18    LspStore, LspStoreEvent, PrettierStore, ProjectEntryId, ProjectPath, ToolchainStore,
 19    WorktreeId,
 20};
 21use remote::ssh_session::ChannelClient;
 22use rpc::{
 23    proto::{self, SSH_PEER_ID, SSH_PROJECT_ID},
 24    AnyProtoClient, TypedEnvelope,
 25};
 26
 27use settings::initial_server_settings_content;
 28use smol::stream::StreamExt;
 29use std::{
 30    path::{Path, PathBuf},
 31    sync::{atomic::AtomicUsize, Arc},
 32};
 33use util::ResultExt;
 34use worktree::Worktree;
 35
 36pub struct HeadlessProject {
 37    pub fs: Arc<dyn Fs>,
 38    pub session: AnyProtoClient,
 39    pub worktree_store: Entity<WorktreeStore>,
 40    pub buffer_store: Entity<BufferStore>,
 41    pub lsp_store: Entity<LspStore>,
 42    pub task_store: Entity<TaskStore>,
 43    pub settings_observer: Entity<SettingsObserver>,
 44    pub next_entry_id: Arc<AtomicUsize>,
 45    pub languages: Arc<LanguageRegistry>,
 46    pub extensions: Entity<HeadlessExtensionStore>,
 47    pub git_state: Entity<GitState>,
 48}
 49
 50pub struct HeadlessAppState {
 51    pub session: Arc<ChannelClient>,
 52    pub fs: Arc<dyn Fs>,
 53    pub http_client: Arc<dyn HttpClient>,
 54    pub node_runtime: NodeRuntime,
 55    pub languages: Arc<LanguageRegistry>,
 56    pub extension_host_proxy: Arc<ExtensionHostProxy>,
 57}
 58
 59impl HeadlessProject {
 60    pub fn init(cx: &mut App) {
 61        settings::init(cx);
 62        language::init(cx);
 63        project::Project::init_settings(cx);
 64    }
 65
 66    pub fn new(
 67        HeadlessAppState {
 68            session,
 69            fs,
 70            http_client,
 71            node_runtime,
 72            languages,
 73            extension_host_proxy: proxy,
 74        }: HeadlessAppState,
 75        cx: &mut Context<Self>,
 76    ) -> Self {
 77        language_extension::init(proxy.clone(), languages.clone());
 78        languages::init(languages.clone(), node_runtime.clone(), cx);
 79
 80        let worktree_store = cx.new(|cx| {
 81            let mut store = WorktreeStore::local(true, fs.clone());
 82            store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 83            store
 84        });
 85
 86        let git_state = cx.new(|cx| GitState::new(&worktree_store, None, None, cx));
 87
 88        let buffer_store = cx.new(|cx| {
 89            let mut buffer_store = BufferStore::local(worktree_store.clone(), cx);
 90            buffer_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 91            buffer_store
 92        });
 93        let prettier_store = cx.new(|cx| {
 94            PrettierStore::new(
 95                node_runtime.clone(),
 96                fs.clone(),
 97                languages.clone(),
 98                worktree_store.clone(),
 99                cx,
100            )
101        });
102        let environment = project::ProjectEnvironment::new(&worktree_store, None, cx);
103        let toolchain_store = cx.new(|cx| {
104            ToolchainStore::local(
105                languages.clone(),
106                worktree_store.clone(),
107                environment.clone(),
108                cx,
109            )
110        });
111
112        let task_store = cx.new(|cx| {
113            let mut task_store = TaskStore::local(
114                fs.clone(),
115                buffer_store.downgrade(),
116                worktree_store.clone(),
117                toolchain_store.read(cx).as_language_toolchain_store(),
118                environment.clone(),
119                cx,
120            );
121            task_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
122            task_store
123        });
124        let settings_observer = cx.new(|cx| {
125            let mut observer = SettingsObserver::new_local(
126                fs.clone(),
127                worktree_store.clone(),
128                task_store.clone(),
129                cx,
130            );
131            observer.shared(SSH_PROJECT_ID, session.clone().into(), cx);
132            observer
133        });
134
135        let lsp_store = cx.new(|cx| {
136            let mut lsp_store = LspStore::new_local(
137                buffer_store.clone(),
138                worktree_store.clone(),
139                prettier_store.clone(),
140                toolchain_store.clone(),
141                environment,
142                languages.clone(),
143                http_client.clone(),
144                fs.clone(),
145                cx,
146            );
147            lsp_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
148            lsp_store
149        });
150
151        cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
152
153        cx.subscribe(
154            &buffer_store,
155            |_this, _buffer_store, event, cx| match event {
156                BufferStoreEvent::BufferAdded(buffer) => {
157                    cx.subscribe(buffer, Self::on_buffer_event).detach();
158                }
159                _ => {}
160            },
161        )
162        .detach();
163
164        let extensions = HeadlessExtensionStore::new(
165            fs.clone(),
166            http_client.clone(),
167            paths::remote_extensions_dir().to_path_buf(),
168            proxy,
169            node_runtime,
170            cx,
171        );
172
173        let client: AnyProtoClient = session.clone().into();
174
175        // local_machine -> ssh handlers
176        session.subscribe_to_entity(SSH_PROJECT_ID, &worktree_store);
177        session.subscribe_to_entity(SSH_PROJECT_ID, &buffer_store);
178        session.subscribe_to_entity(SSH_PROJECT_ID, &cx.entity());
179        session.subscribe_to_entity(SSH_PROJECT_ID, &lsp_store);
180        session.subscribe_to_entity(SSH_PROJECT_ID, &task_store);
181        session.subscribe_to_entity(SSH_PROJECT_ID, &toolchain_store);
182        session.subscribe_to_entity(SSH_PROJECT_ID, &settings_observer);
183
184        client.add_request_handler(cx.weak_entity(), Self::handle_list_remote_directory);
185        client.add_request_handler(cx.weak_entity(), Self::handle_get_path_metadata);
186        client.add_request_handler(cx.weak_entity(), Self::handle_shutdown_remote_server);
187        client.add_request_handler(cx.weak_entity(), Self::handle_ping);
188
189        client.add_entity_request_handler(Self::handle_add_worktree);
190        client.add_request_handler(cx.weak_entity(), Self::handle_remove_worktree);
191
192        client.add_entity_request_handler(Self::handle_open_buffer_by_path);
193        client.add_entity_request_handler(Self::handle_open_new_buffer);
194        client.add_entity_request_handler(Self::handle_find_search_candidates);
195        client.add_entity_request_handler(Self::handle_open_server_settings);
196
197        client.add_entity_request_handler(BufferStore::handle_update_buffer);
198        client.add_entity_message_handler(BufferStore::handle_close_buffer);
199
200        client.add_entity_request_handler(Self::handle_stage);
201        client.add_entity_request_handler(Self::handle_unstage);
202        client.add_entity_request_handler(Self::handle_commit);
203        client.add_entity_request_handler(Self::handle_open_commit_message_buffer);
204
205        client.add_request_handler(
206            extensions.clone().downgrade(),
207            HeadlessExtensionStore::handle_sync_extensions,
208        );
209        client.add_request_handler(
210            extensions.clone().downgrade(),
211            HeadlessExtensionStore::handle_install_extension,
212        );
213
214        BufferStore::init(&client);
215        WorktreeStore::init(&client);
216        SettingsObserver::init(&client);
217        LspStore::init(&client);
218        TaskStore::init(Some(&client));
219        ToolchainStore::init(&client);
220
221        HeadlessProject {
222            session: client,
223            settings_observer,
224            fs,
225            worktree_store,
226            buffer_store,
227            lsp_store,
228            task_store,
229            next_entry_id: Default::default(),
230            languages,
231            extensions,
232            git_state,
233        }
234    }
235
236    fn on_buffer_event(
237        &mut self,
238        buffer: Entity<Buffer>,
239        event: &BufferEvent,
240        cx: &mut Context<Self>,
241    ) {
242        match event {
243            BufferEvent::Operation {
244                operation,
245                is_local: true,
246            } => cx
247                .background_executor()
248                .spawn(self.session.request(proto::UpdateBuffer {
249                    project_id: SSH_PROJECT_ID,
250                    buffer_id: buffer.read(cx).remote_id().to_proto(),
251                    operations: vec![serialize_operation(operation)],
252                }))
253                .detach(),
254            _ => {}
255        }
256    }
257
258    fn on_lsp_store_event(
259        &mut self,
260        _lsp_store: Entity<LspStore>,
261        event: &LspStoreEvent,
262        cx: &mut Context<Self>,
263    ) {
264        match event {
265            LspStoreEvent::LanguageServerUpdate {
266                language_server_id,
267                message,
268            } => {
269                self.session
270                    .send(proto::UpdateLanguageServer {
271                        project_id: SSH_PROJECT_ID,
272                        language_server_id: language_server_id.to_proto(),
273                        variant: Some(message.clone()),
274                    })
275                    .log_err();
276            }
277            LspStoreEvent::Notification(message) => {
278                self.session
279                    .send(proto::Toast {
280                        project_id: SSH_PROJECT_ID,
281                        notification_id: "lsp".to_string(),
282                        message: message.clone(),
283                    })
284                    .log_err();
285            }
286            LspStoreEvent::LanguageServerLog(language_server_id, log_type, message) => {
287                self.session
288                    .send(proto::LanguageServerLog {
289                        project_id: SSH_PROJECT_ID,
290                        language_server_id: language_server_id.to_proto(),
291                        message: message.clone(),
292                        log_type: Some(log_type.to_proto()),
293                    })
294                    .log_err();
295            }
296            LspStoreEvent::LanguageServerPrompt(prompt) => {
297                let request = self.session.request(proto::LanguageServerPromptRequest {
298                    project_id: SSH_PROJECT_ID,
299                    actions: prompt
300                        .actions
301                        .iter()
302                        .map(|action| action.title.to_string())
303                        .collect(),
304                    level: Some(prompt_to_proto(&prompt)),
305                    lsp_name: prompt.lsp_name.clone(),
306                    message: prompt.message.clone(),
307                });
308                let prompt = prompt.clone();
309                cx.background_executor()
310                    .spawn(async move {
311                        let response = request.await?;
312                        if let Some(action_response) = response.action_response {
313                            prompt.respond(action_response as usize).await;
314                        }
315                        anyhow::Ok(())
316                    })
317                    .detach();
318            }
319            _ => {}
320        }
321    }
322
323    pub async fn handle_add_worktree(
324        this: Entity<Self>,
325        message: TypedEnvelope<proto::AddWorktree>,
326        mut cx: AsyncApp,
327    ) -> Result<proto::AddWorktreeResponse> {
328        use client::ErrorCodeExt;
329        let fs = this.read_with(&mut cx, |this, _| this.fs.clone())?;
330        let path = PathBuf::from_proto(shellexpand::tilde(&message.payload.path).to_string());
331
332        let canonicalized = match fs.canonicalize(&path).await {
333            Ok(path) => path,
334            Err(e) => {
335                let mut parent = path
336                    .parent()
337                    .ok_or(e)
338                    .map_err(|_| anyhow!("{:?} does not exist", path))?;
339                if parent == Path::new("") {
340                    parent = util::paths::home_dir();
341                }
342                let parent = fs.canonicalize(parent).await.map_err(|_| {
343                    anyhow!(proto::ErrorCode::DevServerProjectPathDoesNotExist
344                        .with_tag("path", &path.to_string_lossy().as_ref()))
345                })?;
346                parent.join(path.file_name().unwrap())
347            }
348        };
349
350        let worktree = this
351            .update(&mut cx.clone(), |this, _| {
352                Worktree::local(
353                    Arc::from(canonicalized.as_path()),
354                    message.payload.visible,
355                    this.fs.clone(),
356                    this.next_entry_id.clone(),
357                    &mut cx,
358                )
359            })?
360            .await?;
361
362        let response = this.update(&mut cx, |_, cx| {
363            worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
364                worktree_id: worktree.id().to_proto(),
365                canonicalized_path: canonicalized.to_proto(),
366            })
367        })?;
368
369        // We spawn this asynchronously, so that we can send the response back
370        // *before* `worktree_store.add()` can send out UpdateProject requests
371        // to the client about the new worktree.
372        //
373        // That lets the client manage the reference/handles of the newly-added
374        // worktree, before getting interrupted by an UpdateProject request.
375        //
376        // This fixes the problem of the client sending the AddWorktree request,
377        // headless project sending out a project update, client receiving it
378        // and immediately dropping the reference of the new client, causing it
379        // to be dropped on the headless project, and the client only then
380        // receiving a response to AddWorktree.
381        cx.spawn(|mut cx| async move {
382            this.update(&mut cx, |this, cx| {
383                this.worktree_store.update(cx, |worktree_store, cx| {
384                    worktree_store.add(&worktree, cx);
385                });
386            })
387            .log_err();
388        })
389        .detach();
390
391        Ok(response)
392    }
393
394    pub async fn handle_remove_worktree(
395        this: Entity<Self>,
396        envelope: TypedEnvelope<proto::RemoveWorktree>,
397        mut cx: AsyncApp,
398    ) -> Result<proto::Ack> {
399        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
400        this.update(&mut cx, |this, cx| {
401            this.worktree_store.update(cx, |worktree_store, cx| {
402                worktree_store.remove_worktree(worktree_id, cx);
403            });
404        })?;
405        Ok(proto::Ack {})
406    }
407
408    pub async fn handle_open_buffer_by_path(
409        this: Entity<Self>,
410        message: TypedEnvelope<proto::OpenBufferByPath>,
411        mut cx: AsyncApp,
412    ) -> Result<proto::OpenBufferResponse> {
413        let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
414        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
415            let buffer_store = this.buffer_store.clone();
416            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
417                buffer_store.open_buffer(
418                    ProjectPath {
419                        worktree_id,
420                        path: Arc::<Path>::from_proto(message.payload.path),
421                    },
422                    cx,
423                )
424            });
425            anyhow::Ok((buffer_store, buffer))
426        })??;
427
428        let buffer = buffer.await?;
429        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
430        buffer_store.update(&mut cx, |buffer_store, cx| {
431            buffer_store
432                .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
433                .detach_and_log_err(cx);
434        })?;
435
436        Ok(proto::OpenBufferResponse {
437            buffer_id: buffer_id.to_proto(),
438        })
439    }
440
441    pub async fn handle_open_new_buffer(
442        this: Entity<Self>,
443        _message: TypedEnvelope<proto::OpenNewBuffer>,
444        mut cx: AsyncApp,
445    ) -> Result<proto::OpenBufferResponse> {
446        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
447            let buffer_store = this.buffer_store.clone();
448            let buffer = this
449                .buffer_store
450                .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx));
451            anyhow::Ok((buffer_store, buffer))
452        })??;
453
454        let buffer = buffer.await?;
455        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
456        buffer_store.update(&mut cx, |buffer_store, cx| {
457            buffer_store
458                .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
459                .detach_and_log_err(cx);
460        })?;
461
462        Ok(proto::OpenBufferResponse {
463            buffer_id: buffer_id.to_proto(),
464        })
465    }
466
467    pub async fn handle_open_server_settings(
468        this: Entity<Self>,
469        _: TypedEnvelope<proto::OpenServerSettings>,
470        mut cx: AsyncApp,
471    ) -> Result<proto::OpenBufferResponse> {
472        let settings_path = paths::settings_file();
473        let (worktree, path) = this
474            .update(&mut cx, |this, cx| {
475                this.worktree_store.update(cx, |worktree_store, cx| {
476                    worktree_store.find_or_create_worktree(settings_path, false, cx)
477                })
478            })?
479            .await?;
480
481        let (buffer, buffer_store) = this.update(&mut cx, |this, cx| {
482            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
483                buffer_store.open_buffer(
484                    ProjectPath {
485                        worktree_id: worktree.read(cx).id(),
486                        path: path.into(),
487                    },
488                    cx,
489                )
490            });
491
492            (buffer, this.buffer_store.clone())
493        })?;
494
495        let buffer = buffer.await?;
496
497        let buffer_id = cx.update(|cx| {
498            if buffer.read(cx).is_empty() {
499                buffer.update(cx, |buffer, cx| {
500                    buffer.edit([(0..0, initial_server_settings_content())], None, cx)
501                });
502            }
503
504            let buffer_id = buffer.read_with(cx, |b, _| b.remote_id());
505
506            buffer_store.update(cx, |buffer_store, cx| {
507                buffer_store
508                    .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
509                    .detach_and_log_err(cx);
510            });
511
512            buffer_id
513        })?;
514
515        Ok(proto::OpenBufferResponse {
516            buffer_id: buffer_id.to_proto(),
517        })
518    }
519
520    pub async fn handle_find_search_candidates(
521        this: Entity<Self>,
522        envelope: TypedEnvelope<proto::FindSearchCandidates>,
523        mut cx: AsyncApp,
524    ) -> Result<proto::FindSearchCandidatesResponse> {
525        let message = envelope.payload;
526        let query = SearchQuery::from_proto(
527            message
528                .query
529                .ok_or_else(|| anyhow!("missing query field"))?,
530        )?;
531        let results = this.update(&mut cx, |this, cx| {
532            this.buffer_store.update(cx, |buffer_store, cx| {
533                buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
534            })
535        })?;
536
537        let mut response = proto::FindSearchCandidatesResponse {
538            buffer_ids: Vec::new(),
539        };
540
541        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
542
543        while let Ok(buffer) = results.recv().await {
544            let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
545            response.buffer_ids.push(buffer_id.to_proto());
546            buffer_store
547                .update(&mut cx, |buffer_store, cx| {
548                    buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
549                })?
550                .await?;
551        }
552
553        Ok(response)
554    }
555
556    pub async fn handle_list_remote_directory(
557        this: Entity<Self>,
558        envelope: TypedEnvelope<proto::ListRemoteDirectory>,
559        cx: AsyncApp,
560    ) -> Result<proto::ListRemoteDirectoryResponse> {
561        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
562        let expanded = PathBuf::from_proto(shellexpand::tilde(&envelope.payload.path).to_string());
563
564        let mut entries = Vec::new();
565        let mut response = fs.read_dir(&expanded).await?;
566        while let Some(path) = response.next().await {
567            if let Some(file_name) = path?.file_name() {
568                entries.push(file_name.to_string_lossy().to_string());
569            }
570        }
571        Ok(proto::ListRemoteDirectoryResponse { entries })
572    }
573
574    pub async fn handle_get_path_metadata(
575        this: Entity<Self>,
576        envelope: TypedEnvelope<proto::GetPathMetadata>,
577        cx: AsyncApp,
578    ) -> Result<proto::GetPathMetadataResponse> {
579        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
580        let expanded = PathBuf::from_proto(shellexpand::tilde(&envelope.payload.path).to_string());
581
582        let metadata = fs.metadata(&expanded).await?;
583        let is_dir = metadata.map(|metadata| metadata.is_dir).unwrap_or(false);
584
585        Ok(proto::GetPathMetadataResponse {
586            exists: metadata.is_some(),
587            is_dir,
588            path: expanded.to_proto(),
589        })
590    }
591
592    pub async fn handle_shutdown_remote_server(
593        _this: Entity<Self>,
594        _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
595        cx: AsyncApp,
596    ) -> Result<proto::Ack> {
597        cx.spawn(|cx| async move {
598            cx.update(|cx| {
599                // TODO: This is a hack, because in a headless project, shutdown isn't executed
600                // when calling quit, but it should be.
601                cx.shutdown();
602                cx.quit();
603            })
604        })
605        .detach();
606
607        Ok(proto::Ack {})
608    }
609
610    pub async fn handle_ping(
611        _this: Entity<Self>,
612        _envelope: TypedEnvelope<proto::Ping>,
613        _cx: AsyncApp,
614    ) -> Result<proto::Ack> {
615        log::debug!("Received ping from client");
616        Ok(proto::Ack {})
617    }
618
619    async fn handle_stage(
620        this: Entity<Self>,
621        envelope: TypedEnvelope<proto::Stage>,
622        mut cx: AsyncApp,
623    ) -> Result<proto::Ack> {
624        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
625        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
626        let repository_handle =
627            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
628
629        let entries = envelope
630            .payload
631            .paths
632            .into_iter()
633            .map(PathBuf::from)
634            .map(RepoPath::new)
635            .collect();
636
637        repository_handle
638            .update(&mut cx, |repository_handle, _| {
639                repository_handle.stage_entries(entries)
640            })?
641            .await??;
642        Ok(proto::Ack {})
643    }
644
645    async fn handle_unstage(
646        this: Entity<Self>,
647        envelope: TypedEnvelope<proto::Unstage>,
648        mut cx: AsyncApp,
649    ) -> Result<proto::Ack> {
650        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
651        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
652        let repository_handle =
653            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
654
655        let entries = envelope
656            .payload
657            .paths
658            .into_iter()
659            .map(PathBuf::from)
660            .map(RepoPath::new)
661            .collect();
662
663        repository_handle
664            .update(&mut cx, |repository_handle, _| {
665                repository_handle.unstage_entries(entries)
666            })?
667            .await??;
668
669        Ok(proto::Ack {})
670    }
671
672    async fn handle_commit(
673        this: Entity<Self>,
674        envelope: TypedEnvelope<proto::Commit>,
675        mut cx: AsyncApp,
676    ) -> Result<proto::Ack> {
677        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
678        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
679        let repository_handle =
680            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
681
682        let message = SharedString::from(envelope.payload.message);
683        let name = envelope.payload.name.map(SharedString::from);
684        let email = envelope.payload.email.map(SharedString::from);
685
686        repository_handle
687            .update(&mut cx, |repository_handle, _| {
688                repository_handle.commit(message, name.zip(email))
689            })?
690            .await??;
691        Ok(proto::Ack {})
692    }
693
694    async fn handle_open_commit_message_buffer(
695        this: Entity<Self>,
696        envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,
697        mut cx: AsyncApp,
698    ) -> Result<proto::OpenBufferResponse> {
699        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
700        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
701        let repository =
702            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
703        let buffer = repository
704            .update(&mut cx, |repository, cx| {
705                repository.open_commit_buffer(None, this.read(cx).buffer_store.clone(), cx)
706            })?
707            .await?;
708
709        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id())?;
710        this.update(&mut cx, |headless_project, cx| {
711            headless_project
712                .buffer_store
713                .update(cx, |buffer_store, cx| {
714                    buffer_store
715                        .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
716                        .detach_and_log_err(cx);
717                })
718        })?;
719
720        Ok(proto::OpenBufferResponse {
721            buffer_id: buffer_id.to_proto(),
722        })
723    }
724
725    fn repository_for_request(
726        this: &Entity<Self>,
727        worktree_id: WorktreeId,
728        work_directory_id: ProjectEntryId,
729        cx: &mut AsyncApp,
730    ) -> Result<Entity<Repository>> {
731        this.update(cx, |project, cx| {
732            let repository_handle = project
733                .git_state
734                .read(cx)
735                .all_repositories()
736                .into_iter()
737                .find(|repository_handle| {
738                    repository_handle.read(cx).worktree_id == worktree_id
739                        && repository_handle
740                            .read(cx)
741                            .repository_entry
742                            .work_directory_id()
743                            == work_directory_id
744                })
745                .context("missing repository handle")?;
746            anyhow::Ok(repository_handle)
747        })?
748    }
749}
750
751fn prompt_to_proto(
752    prompt: &project::LanguageServerPromptRequest,
753) -> proto::language_server_prompt_request::Level {
754    match prompt.level {
755        PromptLevel::Info => proto::language_server_prompt_request::Level::Info(
756            proto::language_server_prompt_request::Info {},
757        ),
758        PromptLevel::Warning => proto::language_server_prompt_request::Level::Warning(
759            proto::language_server_prompt_request::Warning {},
760        ),
761        PromptLevel::Critical => proto::language_server_prompt_request::Level::Critical(
762            proto::language_server_prompt_request::Critical {},
763        ),
764    }
765}