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