headless_project.rs

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