headless_project.rs

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