headless_project.rs

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