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