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