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    // Used mostly to keep alive the toolchain store for RPC handlers.
 54    // Local variant is used within LSP store, but that's a separate entity.
 55    pub _toolchain_store: Entity<ToolchainStore>,
 56}
 57
 58pub struct HeadlessAppState {
 59    pub session: AnyProtoClient,
 60    pub fs: Arc<dyn Fs>,
 61    pub http_client: Arc<dyn HttpClient>,
 62    pub node_runtime: NodeRuntime,
 63    pub languages: Arc<LanguageRegistry>,
 64    pub extension_host_proxy: Arc<ExtensionHostProxy>,
 65}
 66
 67impl HeadlessProject {
 68    pub fn init(cx: &mut App) {
 69        settings::init(cx);
 70        language::init(cx);
 71        project::Project::init_settings(cx);
 72        extension_host::ExtensionSettings::register(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(), fs.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                true,
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,
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_message_handler(Self::handle_toggle_lsp_logs);
259
260        session.add_entity_request_handler(BufferStore::handle_update_buffer);
261        session.add_entity_message_handler(BufferStore::handle_close_buffer);
262
263        session.add_request_handler(
264            extensions.downgrade(),
265            HeadlessExtensionStore::handle_sync_extensions,
266        );
267        session.add_request_handler(
268            extensions.downgrade(),
269            HeadlessExtensionStore::handle_install_extension,
270        );
271
272        BufferStore::init(&session);
273        WorktreeStore::init(&session);
274        SettingsObserver::init(&session);
275        LspStore::init(&session);
276        TaskStore::init(Some(&session));
277        ToolchainStore::init(&session);
278        DapStore::init(&session, cx);
279        // todo(debugger): Re init breakpoint store when we set it up for collab
280        // BreakpointStore::init(&client);
281        GitStore::init(&session);
282        AgentServerStore::init_headless(&session);
283
284        HeadlessProject {
285            next_entry_id: Default::default(),
286            session,
287            settings_observer,
288            fs,
289            worktree_store,
290            buffer_store,
291            lsp_store,
292            task_store,
293            dap_store,
294            agent_server_store,
295            languages,
296            extensions,
297            git_store,
298            _toolchain_store: toolchain_store,
299        }
300    }
301
302    fn on_buffer_event(
303        &mut self,
304        buffer: Entity<Buffer>,
305        event: &BufferEvent,
306        cx: &mut Context<Self>,
307    ) {
308        if let BufferEvent::Operation {
309            operation,
310            is_local: true,
311        } = event
312        {
313            cx.background_spawn(self.session.request(proto::UpdateBuffer {
314                project_id: REMOTE_SERVER_PROJECT_ID,
315                buffer_id: buffer.read(cx).remote_id().to_proto(),
316                operations: vec![serialize_operation(operation)],
317            }))
318            .detach()
319        }
320    }
321
322    fn on_lsp_store_event(
323        &mut self,
324        lsp_store: Entity<LspStore>,
325        event: &LspStoreEvent,
326        cx: &mut Context<Self>,
327    ) {
328        match event {
329            LspStoreEvent::LanguageServerAdded(id, name, worktree_id) => {
330                let log_store = cx
331                    .try_global::<GlobalLogStore>()
332                    .map(|lsp_logs| lsp_logs.0.clone());
333                if let Some(log_store) = log_store {
334                    log_store.update(cx, |log_store, cx| {
335                        log_store.add_language_server(
336                            LanguageServerKind::LocalSsh {
337                                lsp_store: self.lsp_store.downgrade(),
338                            },
339                            *id,
340                            Some(name.clone()),
341                            *worktree_id,
342                            lsp_store.read(cx).language_server_for_id(*id),
343                            cx,
344                        );
345                    });
346                }
347            }
348            LspStoreEvent::LanguageServerRemoved(id) => {
349                let log_store = cx
350                    .try_global::<GlobalLogStore>()
351                    .map(|lsp_logs| lsp_logs.0.clone());
352                if let Some(log_store) = log_store {
353                    log_store.update(cx, |log_store, cx| {
354                        log_store.remove_language_server(*id, cx);
355                    });
356                }
357            }
358            LspStoreEvent::LanguageServerUpdate {
359                language_server_id,
360                name,
361                message,
362            } => {
363                self.session
364                    .send(proto::UpdateLanguageServer {
365                        project_id: REMOTE_SERVER_PROJECT_ID,
366                        server_name: name.as_ref().map(|name| name.to_string()),
367                        language_server_id: language_server_id.to_proto(),
368                        variant: Some(message.clone()),
369                    })
370                    .log_err();
371            }
372            LspStoreEvent::Notification(message) => {
373                self.session
374                    .send(proto::Toast {
375                        project_id: REMOTE_SERVER_PROJECT_ID,
376                        notification_id: "lsp".to_string(),
377                        message: message.clone(),
378                    })
379                    .log_err();
380            }
381            LspStoreEvent::LanguageServerPrompt(prompt) => {
382                let request = self.session.request(proto::LanguageServerPromptRequest {
383                    project_id: REMOTE_SERVER_PROJECT_ID,
384                    actions: prompt
385                        .actions
386                        .iter()
387                        .map(|action| action.title.to_string())
388                        .collect(),
389                    level: Some(prompt_to_proto(prompt)),
390                    lsp_name: prompt.lsp_name.clone(),
391                    message: prompt.message.clone(),
392                });
393                let prompt = prompt.clone();
394                cx.background_spawn(async move {
395                    let response = request.await?;
396                    if let Some(action_response) = response.action_response {
397                        prompt.respond(action_response as usize).await;
398                    }
399                    anyhow::Ok(())
400                })
401                .detach();
402            }
403            _ => {}
404        }
405    }
406
407    pub async fn handle_add_worktree(
408        this: Entity<Self>,
409        message: TypedEnvelope<proto::AddWorktree>,
410        mut cx: AsyncApp,
411    ) -> Result<proto::AddWorktreeResponse> {
412        use client::ErrorCodeExt;
413        let fs = this.read_with(&cx, |this, _| this.fs.clone())?;
414        let path = PathBuf::from(shellexpand::tilde(&message.payload.path).to_string());
415
416        let canonicalized = match fs.canonicalize(&path).await {
417            Ok(path) => path,
418            Err(e) => {
419                let mut parent = path
420                    .parent()
421                    .ok_or(e)
422                    .with_context(|| format!("{path:?} does not exist"))?;
423                if parent == Path::new("") {
424                    parent = util::paths::home_dir();
425                }
426                let parent = fs.canonicalize(parent).await.map_err(|_| {
427                    anyhow!(
428                        proto::ErrorCode::DevServerProjectPathDoesNotExist
429                            .with_tag("path", path.to_string_lossy().as_ref())
430                    )
431                })?;
432                parent.join(path.file_name().unwrap())
433            }
434        };
435
436        let worktree = this
437            .read_with(&cx.clone(), |this, _| {
438                Worktree::local(
439                    Arc::from(canonicalized.as_path()),
440                    message.payload.visible,
441                    this.fs.clone(),
442                    this.next_entry_id.clone(),
443                    &mut cx,
444                )
445            })?
446            .await?;
447
448        let response = this.read_with(&cx, |_, cx| {
449            let worktree = worktree.read(cx);
450            proto::AddWorktreeResponse {
451                worktree_id: worktree.id().to_proto(),
452                canonicalized_path: canonicalized.to_string_lossy().into_owned(),
453            }
454        })?;
455
456        // We spawn this asynchronously, so that we can send the response back
457        // *before* `worktree_store.add()` can send out UpdateProject requests
458        // to the client about the new worktree.
459        //
460        // That lets the client manage the reference/handles of the newly-added
461        // worktree, before getting interrupted by an UpdateProject request.
462        //
463        // This fixes the problem of the client sending the AddWorktree request,
464        // headless project sending out a project update, client receiving it
465        // and immediately dropping the reference of the new client, causing it
466        // to be dropped on the headless project, and the client only then
467        // receiving a response to AddWorktree.
468        cx.spawn(async move |cx| {
469            this.update(cx, |this, cx| {
470                this.worktree_store.update(cx, |worktree_store, cx| {
471                    worktree_store.add(&worktree, cx);
472                });
473            })
474            .log_err();
475        })
476        .detach();
477
478        Ok(response)
479    }
480
481    pub async fn handle_remove_worktree(
482        this: Entity<Self>,
483        envelope: TypedEnvelope<proto::RemoveWorktree>,
484        mut cx: AsyncApp,
485    ) -> Result<proto::Ack> {
486        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
487        this.update(&mut cx, |this, cx| {
488            this.worktree_store.update(cx, |worktree_store, cx| {
489                worktree_store.remove_worktree(worktree_id, cx);
490            });
491        })?;
492        Ok(proto::Ack {})
493    }
494
495    pub async fn handle_open_buffer_by_path(
496        this: Entity<Self>,
497        message: TypedEnvelope<proto::OpenBufferByPath>,
498        mut cx: AsyncApp,
499    ) -> Result<proto::OpenBufferResponse> {
500        let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
501        let path = RelPath::from_proto(&message.payload.path)?;
502        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
503            let buffer_store = this.buffer_store.clone();
504            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
505                buffer_store.open_buffer(ProjectPath { worktree_id, path }, cx)
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,
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(
635            message.query.context("missing query field")?,
636            PathStyle::local(),
637        )?;
638        let results = this.update(&mut cx, |this, cx| {
639            this.buffer_store.update(cx, |buffer_store, cx| {
640                buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
641            })
642        })?;
643
644        let mut response = proto::FindSearchCandidatesResponse {
645            buffer_ids: Vec::new(),
646        };
647
648        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
649
650        while let Ok(buffer) = results.recv().await {
651            let buffer_id = buffer.read_with(&cx, |this, _| this.remote_id())?;
652            response.buffer_ids.push(buffer_id.to_proto());
653            buffer_store
654                .update(&mut cx, |buffer_store, cx| {
655                    buffer_store.create_buffer_for_peer(&buffer, REMOTE_SERVER_PEER_ID, cx)
656                })?
657                .await?;
658        }
659
660        Ok(response)
661    }
662
663    async fn handle_list_remote_directory(
664        this: Entity<Self>,
665        envelope: TypedEnvelope<proto::ListRemoteDirectory>,
666        cx: AsyncApp,
667    ) -> Result<proto::ListRemoteDirectoryResponse> {
668        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
669        let expanded = PathBuf::from(shellexpand::tilde(&envelope.payload.path).to_string());
670        let check_info = envelope
671            .payload
672            .config
673            .as_ref()
674            .is_some_and(|config| config.is_dir);
675
676        let mut entries = Vec::new();
677        let mut entry_info = Vec::new();
678        let mut response = fs.read_dir(&expanded).await?;
679        while let Some(path) = response.next().await {
680            let path = path?;
681            if let Some(file_name) = path.file_name() {
682                entries.push(file_name.to_string_lossy().into_owned());
683                if check_info {
684                    let is_dir = fs.is_dir(&path).await;
685                    entry_info.push(proto::EntryInfo { is_dir });
686                }
687            }
688        }
689        Ok(proto::ListRemoteDirectoryResponse {
690            entries,
691            entry_info,
692        })
693    }
694
695    async fn handle_get_path_metadata(
696        this: Entity<Self>,
697        envelope: TypedEnvelope<proto::GetPathMetadata>,
698        cx: AsyncApp,
699    ) -> Result<proto::GetPathMetadataResponse> {
700        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
701        let expanded = PathBuf::from(shellexpand::tilde(&envelope.payload.path).to_string());
702
703        let metadata = fs.metadata(&expanded).await?;
704        let is_dir = metadata.map(|metadata| metadata.is_dir).unwrap_or(false);
705
706        Ok(proto::GetPathMetadataResponse {
707            exists: metadata.is_some(),
708            is_dir,
709            path: expanded.to_string_lossy().into_owned(),
710        })
711    }
712
713    async fn handle_shutdown_remote_server(
714        _this: Entity<Self>,
715        _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
716        cx: AsyncApp,
717    ) -> Result<proto::Ack> {
718        cx.spawn(async move |cx| {
719            cx.update(|cx| {
720                // TODO: This is a hack, because in a headless project, shutdown isn't executed
721                // when calling quit, but it should be.
722                cx.shutdown();
723                cx.quit();
724            })
725        })
726        .detach();
727
728        Ok(proto::Ack {})
729    }
730
731    pub async fn handle_ping(
732        _this: Entity<Self>,
733        _envelope: TypedEnvelope<proto::Ping>,
734        _cx: AsyncApp,
735    ) -> Result<proto::Ack> {
736        log::debug!("Received ping from client");
737        Ok(proto::Ack {})
738    }
739
740    async fn handle_get_processes(
741        _this: Entity<Self>,
742        _envelope: TypedEnvelope<proto::GetProcesses>,
743        _cx: AsyncApp,
744    ) -> Result<proto::GetProcessesResponse> {
745        let mut processes = Vec::new();
746        let system = System::new_all();
747
748        for (_pid, process) in system.processes() {
749            let name = process.name().to_string_lossy().into_owned();
750            let command = process
751                .cmd()
752                .iter()
753                .map(|s| s.to_string_lossy().into_owned())
754                .collect::<Vec<_>>();
755
756            processes.push(proto::ProcessInfo {
757                pid: process.pid().as_u32(),
758                name,
759                command,
760            });
761        }
762
763        processes.sort_by_key(|p| p.name.clone());
764
765        Ok(proto::GetProcessesResponse { processes })
766    }
767}
768
769fn prompt_to_proto(
770    prompt: &project::LanguageServerPromptRequest,
771) -> proto::language_server_prompt_request::Level {
772    match prompt.level {
773        PromptLevel::Info => proto::language_server_prompt_request::Level::Info(
774            proto::language_server_prompt_request::Info {},
775        ),
776        PromptLevel::Warning => proto::language_server_prompt_request::Level::Warning(
777            proto::language_server_prompt_request::Warning {},
778        ),
779        PromptLevel::Critical => proto::language_server_prompt_request::Level::Critical(
780            proto::language_server_prompt_request::Critical {},
781        ),
782    }
783}