headless_project.rs

  1use anyhow::{Context as _, Result, anyhow};
  2use client::ProjectId;
  3use collections::HashSet;
  4use language::File;
  5use lsp::LanguageServerId;
  6
  7use extension::ExtensionHostProxy;
  8use extension_host::headless_host::HeadlessExtensionStore;
  9use fs::Fs;
 10use gpui::{App, AppContext as _, AsyncApp, Context, Entity, PromptLevel};
 11use http_client::HttpClient;
 12use language::{Buffer, BufferEvent, LanguageRegistry, proto::serialize_operation};
 13use node_runtime::NodeRuntime;
 14use project::{
 15    LspStore, LspStoreEvent, ManifestTree, PrettierStore, ProjectEnvironment, ProjectPath,
 16    ToolchainStore, WorktreeId,
 17    agent_server_store::AgentServerStore,
 18    buffer_store::{BufferStore, BufferStoreEvent},
 19    debugger::{breakpoint_store::BreakpointStore, dap_store::DapStore},
 20    git_store::GitStore,
 21    image_store::ImageId,
 22    lsp_store::log_store::{self, GlobalLogStore, LanguageServerKind, LogKind},
 23    project_settings::SettingsObserver,
 24    search::SearchQuery,
 25    task_store::TaskStore,
 26    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
 27    worktree_store::WorktreeStore,
 28};
 29use rpc::{
 30    AnyProtoClient, TypedEnvelope,
 31    proto::{self, REMOTE_SERVER_PEER_ID, REMOTE_SERVER_PROJECT_ID},
 32};
 33
 34use settings::initial_server_settings_content;
 35use smol::stream::StreamExt;
 36use std::{
 37    num::NonZeroU64,
 38    path::{Path, PathBuf},
 39    sync::{
 40        Arc,
 41        atomic::{AtomicU64, AtomicUsize, Ordering},
 42    },
 43};
 44use sysinfo::{ProcessRefreshKind, RefreshKind, System, UpdateKind};
 45use util::{ResultExt, paths::PathStyle, rel_path::RelPath};
 46use worktree::Worktree;
 47
 48pub struct HeadlessProject {
 49    pub fs: Arc<dyn Fs>,
 50    pub session: AnyProtoClient,
 51    pub worktree_store: Entity<WorktreeStore>,
 52    pub buffer_store: Entity<BufferStore>,
 53    pub lsp_store: Entity<LspStore>,
 54    pub task_store: Entity<TaskStore>,
 55    pub dap_store: Entity<DapStore>,
 56    pub breakpoint_store: Entity<BreakpointStore>,
 57    pub agent_server_store: Entity<AgentServerStore>,
 58    pub settings_observer: Entity<SettingsObserver>,
 59    pub next_entry_id: Arc<AtomicUsize>,
 60    pub languages: Arc<LanguageRegistry>,
 61    pub extensions: Entity<HeadlessExtensionStore>,
 62    pub git_store: Entity<GitStore>,
 63    pub environment: Entity<ProjectEnvironment>,
 64    // Used mostly to keep alive the toolchain store for RPC handlers.
 65    // Local variant is used within LSP store, but that's a separate entity.
 66    pub _toolchain_store: Entity<ToolchainStore>,
 67}
 68
 69pub struct HeadlessAppState {
 70    pub session: AnyProtoClient,
 71    pub fs: Arc<dyn Fs>,
 72    pub http_client: Arc<dyn HttpClient>,
 73    pub node_runtime: NodeRuntime,
 74    pub languages: Arc<LanguageRegistry>,
 75    pub extension_host_proxy: Arc<ExtensionHostProxy>,
 76}
 77
 78impl HeadlessProject {
 79    pub fn init(cx: &mut App) {
 80        settings::init(cx);
 81        log_store::init(true, cx);
 82    }
 83
 84    pub fn new(
 85        HeadlessAppState {
 86            session,
 87            fs,
 88            http_client,
 89            node_runtime,
 90            languages,
 91            extension_host_proxy: proxy,
 92        }: HeadlessAppState,
 93        init_worktree_trust: bool,
 94        cx: &mut Context<Self>,
 95    ) -> Self {
 96        debug_adapter_extension::init(proxy.clone(), cx);
 97        languages::init(languages.clone(), fs.clone(), node_runtime.clone(), cx);
 98
 99        let worktree_store = cx.new(|cx| {
100            let mut store = WorktreeStore::local(true, fs.clone());
101            store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
102            store
103        });
104
105        if init_worktree_trust {
106            project::trusted_worktrees::track_worktree_trust(
107                worktree_store.clone(),
108                None::<RemoteHostLocation>,
109                Some((session.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))),
110                None,
111                cx,
112            );
113        }
114
115        let environment =
116            cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx));
117        let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
118        let toolchain_store = cx.new(|cx| {
119            ToolchainStore::local(
120                languages.clone(),
121                worktree_store.clone(),
122                environment.clone(),
123                manifest_tree.clone(),
124                fs.clone(),
125                cx,
126            )
127        });
128
129        let buffer_store = cx.new(|cx| {
130            let mut buffer_store = BufferStore::local(worktree_store.clone(), cx);
131            buffer_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
132            buffer_store
133        });
134
135        let breakpoint_store = cx.new(|_| {
136            let mut breakpoint_store =
137                BreakpointStore::local(worktree_store.clone(), buffer_store.clone());
138            breakpoint_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone());
139
140            breakpoint_store
141        });
142
143        let dap_store = cx.new(|cx| {
144            let mut dap_store = DapStore::new_local(
145                http_client.clone(),
146                node_runtime.clone(),
147                fs.clone(),
148                environment.clone(),
149                toolchain_store.read(cx).as_language_toolchain_store(),
150                worktree_store.clone(),
151                breakpoint_store.clone(),
152                true,
153                cx,
154            );
155            dap_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
156            dap_store
157        });
158
159        let git_store = cx.new(|cx| {
160            let mut store = GitStore::local(
161                &worktree_store,
162                buffer_store.clone(),
163                environment.clone(),
164                fs.clone(),
165                cx,
166            );
167            store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
168            store
169        });
170
171        let prettier_store = cx.new(|cx| {
172            PrettierStore::new(
173                node_runtime.clone(),
174                fs.clone(),
175                languages.clone(),
176                worktree_store.clone(),
177                cx,
178            )
179        });
180
181        let task_store = cx.new(|cx| {
182            let mut task_store = TaskStore::local(
183                buffer_store.downgrade(),
184                worktree_store.clone(),
185                toolchain_store.read(cx).as_language_toolchain_store(),
186                environment.clone(),
187                cx,
188            );
189            task_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
190            task_store
191        });
192        let settings_observer = cx.new(|cx| {
193            let mut observer = SettingsObserver::new_local(
194                fs.clone(),
195                worktree_store.clone(),
196                task_store.clone(),
197                cx,
198            );
199            observer.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
200            observer
201        });
202
203        let lsp_store = cx.new(|cx| {
204            let mut lsp_store = LspStore::new_local(
205                buffer_store.clone(),
206                worktree_store.clone(),
207                prettier_store.clone(),
208                toolchain_store
209                    .read(cx)
210                    .as_local_store()
211                    .expect("Toolchain store to be local")
212                    .clone(),
213                environment.clone(),
214                manifest_tree,
215                languages.clone(),
216                http_client.clone(),
217                fs.clone(),
218                cx,
219            );
220            lsp_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
221            lsp_store
222        });
223
224        let agent_server_store = cx.new(|cx| {
225            let mut agent_server_store = AgentServerStore::local(
226                node_runtime.clone(),
227                fs.clone(),
228                environment.clone(),
229                http_client.clone(),
230                cx,
231            );
232            agent_server_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);
233            agent_server_store
234        });
235
236        cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
237        language_extension::init(
238            language_extension::LspAccess::ViaLspStore(lsp_store.clone()),
239            proxy.clone(),
240            languages.clone(),
241        );
242
243        cx.subscribe(&buffer_store, |_this, _buffer_store, event, cx| {
244            if let BufferStoreEvent::BufferAdded(buffer) = event {
245                cx.subscribe(buffer, Self::on_buffer_event).detach();
246            }
247        })
248        .detach();
249
250        let extensions = HeadlessExtensionStore::new(
251            fs.clone(),
252            http_client.clone(),
253            paths::remote_extensions_dir().to_path_buf(),
254            proxy,
255            node_runtime,
256            cx,
257        );
258
259        // local_machine -> ssh handlers
260        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &worktree_store);
261        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &buffer_store);
262        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());
263        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &lsp_store);
264        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &task_store);
265        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &toolchain_store);
266        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &dap_store);
267        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &breakpoint_store);
268        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &settings_observer);
269        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &git_store);
270        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &agent_server_store);
271
272        session.add_request_handler(cx.weak_entity(), Self::handle_list_remote_directory);
273        session.add_request_handler(cx.weak_entity(), Self::handle_get_path_metadata);
274        session.add_request_handler(cx.weak_entity(), Self::handle_shutdown_remote_server);
275        session.add_request_handler(cx.weak_entity(), Self::handle_ping);
276        session.add_request_handler(cx.weak_entity(), Self::handle_get_processes);
277
278        session.add_entity_request_handler(Self::handle_add_worktree);
279        session.add_request_handler(cx.weak_entity(), Self::handle_remove_worktree);
280
281        session.add_entity_request_handler(Self::handle_open_buffer_by_path);
282        session.add_entity_request_handler(Self::handle_open_new_buffer);
283        session.add_entity_request_handler(Self::handle_find_search_candidates);
284        session.add_entity_request_handler(Self::handle_open_server_settings);
285        session.add_entity_request_handler(Self::handle_get_directory_environment);
286        session.add_entity_message_handler(Self::handle_toggle_lsp_logs);
287        session.add_entity_request_handler(Self::handle_open_image_by_path);
288        session.add_entity_request_handler(Self::handle_trust_worktrees);
289        session.add_entity_request_handler(Self::handle_restrict_worktrees);
290
291        session.add_entity_request_handler(BufferStore::handle_update_buffer);
292        session.add_entity_message_handler(BufferStore::handle_close_buffer);
293
294        session.add_request_handler(
295            extensions.downgrade(),
296            HeadlessExtensionStore::handle_sync_extensions,
297        );
298        session.add_request_handler(
299            extensions.downgrade(),
300            HeadlessExtensionStore::handle_install_extension,
301        );
302
303        BufferStore::init(&session);
304        WorktreeStore::init(&session);
305        SettingsObserver::init(&session);
306        LspStore::init(&session);
307        TaskStore::init(Some(&session));
308        ToolchainStore::init(&session);
309        DapStore::init(&session, cx);
310        // todo(debugger): Re init breakpoint store when we set it up for collab
311        BreakpointStore::init(&session);
312        GitStore::init(&session);
313        AgentServerStore::init_headless(&session);
314
315        HeadlessProject {
316            next_entry_id: Default::default(),
317            session,
318            settings_observer,
319            fs,
320            worktree_store,
321            buffer_store,
322            lsp_store,
323            task_store,
324            dap_store,
325            breakpoint_store,
326            agent_server_store,
327            languages,
328            extensions,
329            git_store,
330            environment,
331            _toolchain_store: toolchain_store,
332        }
333    }
334
335    fn on_buffer_event(
336        &mut self,
337        buffer: Entity<Buffer>,
338        event: &BufferEvent,
339        cx: &mut Context<Self>,
340    ) {
341        if let BufferEvent::Operation {
342            operation,
343            is_local: true,
344        } = event
345        {
346            cx.background_spawn(self.session.request(proto::UpdateBuffer {
347                project_id: REMOTE_SERVER_PROJECT_ID,
348                buffer_id: buffer.read(cx).remote_id().to_proto(),
349                operations: vec![serialize_operation(operation)],
350            }))
351            .detach()
352        }
353    }
354
355    fn on_lsp_store_event(
356        &mut self,
357        lsp_store: Entity<LspStore>,
358        event: &LspStoreEvent,
359        cx: &mut Context<Self>,
360    ) {
361        match event {
362            LspStoreEvent::LanguageServerAdded(id, name, worktree_id) => {
363                let log_store = cx
364                    .try_global::<GlobalLogStore>()
365                    .map(|lsp_logs| lsp_logs.0.clone());
366                if let Some(log_store) = log_store {
367                    log_store.update(cx, |log_store, cx| {
368                        log_store.add_language_server(
369                            LanguageServerKind::LocalSsh {
370                                lsp_store: self.lsp_store.downgrade(),
371                            },
372                            *id,
373                            Some(name.clone()),
374                            *worktree_id,
375                            lsp_store.read(cx).language_server_for_id(*id),
376                            cx,
377                        );
378                    });
379                }
380            }
381            LspStoreEvent::LanguageServerRemoved(id) => {
382                let log_store = cx
383                    .try_global::<GlobalLogStore>()
384                    .map(|lsp_logs| lsp_logs.0.clone());
385                if let Some(log_store) = log_store {
386                    log_store.update(cx, |log_store, cx| {
387                        log_store.remove_language_server(*id, cx);
388                    });
389                }
390            }
391            LspStoreEvent::LanguageServerUpdate {
392                language_server_id,
393                name,
394                message,
395            } => {
396                self.session
397                    .send(proto::UpdateLanguageServer {
398                        project_id: REMOTE_SERVER_PROJECT_ID,
399                        server_name: name.as_ref().map(|name| name.to_string()),
400                        language_server_id: language_server_id.to_proto(),
401                        variant: Some(message.clone()),
402                    })
403                    .log_err();
404            }
405            LspStoreEvent::Notification(message) => {
406                self.session
407                    .send(proto::Toast {
408                        project_id: REMOTE_SERVER_PROJECT_ID,
409                        notification_id: "lsp".to_string(),
410                        message: message.clone(),
411                    })
412                    .log_err();
413            }
414            LspStoreEvent::LanguageServerPrompt(prompt) => {
415                let request = self.session.request(proto::LanguageServerPromptRequest {
416                    project_id: REMOTE_SERVER_PROJECT_ID,
417                    actions: prompt
418                        .actions
419                        .iter()
420                        .map(|action| action.title.to_string())
421                        .collect(),
422                    level: Some(prompt_to_proto(prompt)),
423                    lsp_name: prompt.lsp_name.clone(),
424                    message: prompt.message.clone(),
425                });
426                let prompt = prompt.clone();
427                cx.background_spawn(async move {
428                    let response = request.await?;
429                    if let Some(action_response) = response.action_response {
430                        prompt.respond(action_response as usize).await;
431                    }
432                    anyhow::Ok(())
433                })
434                .detach();
435            }
436            _ => {}
437        }
438    }
439
440    pub async fn handle_add_worktree(
441        this: Entity<Self>,
442        message: TypedEnvelope<proto::AddWorktree>,
443        mut cx: AsyncApp,
444    ) -> Result<proto::AddWorktreeResponse> {
445        use client::ErrorCodeExt;
446        let fs = this.read_with(&cx, |this, _| this.fs.clone())?;
447        let path = PathBuf::from(shellexpand::tilde(&message.payload.path).to_string());
448
449        let canonicalized = match fs.canonicalize(&path).await {
450            Ok(path) => path,
451            Err(e) => {
452                let mut parent = path
453                    .parent()
454                    .ok_or(e)
455                    .with_context(|| format!("{path:?} does not exist"))?;
456                if parent == Path::new("") {
457                    parent = util::paths::home_dir();
458                }
459                let parent = fs.canonicalize(parent).await.map_err(|_| {
460                    anyhow!(
461                        proto::ErrorCode::DevServerProjectPathDoesNotExist
462                            .with_tag("path", path.to_string_lossy().as_ref())
463                    )
464                })?;
465                parent.join(path.file_name().unwrap())
466            }
467        };
468
469        let worktree = this
470            .read_with(&cx.clone(), |this, _| {
471                Worktree::local(
472                    Arc::from(canonicalized.as_path()),
473                    message.payload.visible,
474                    this.fs.clone(),
475                    this.next_entry_id.clone(),
476                    true,
477                    &mut cx,
478                )
479            })?
480            .await?;
481
482        let response = this.read_with(&cx, |_, cx| {
483            let worktree = worktree.read(cx);
484            proto::AddWorktreeResponse {
485                worktree_id: worktree.id().to_proto(),
486                canonicalized_path: canonicalized.to_string_lossy().into_owned(),
487            }
488        })?;
489
490        // We spawn this asynchronously, so that we can send the response back
491        // *before* `worktree_store.add()` can send out UpdateProject requests
492        // to the client about the new worktree.
493        //
494        // That lets the client manage the reference/handles of the newly-added
495        // worktree, before getting interrupted by an UpdateProject request.
496        //
497        // This fixes the problem of the client sending the AddWorktree request,
498        // headless project sending out a project update, client receiving it
499        // and immediately dropping the reference of the new client, causing it
500        // to be dropped on the headless project, and the client only then
501        // receiving a response to AddWorktree.
502        cx.spawn(async move |cx| {
503            this.update(cx, |this, cx| {
504                this.worktree_store.update(cx, |worktree_store, cx| {
505                    worktree_store.add(&worktree, cx);
506                });
507            })
508            .log_err();
509        })
510        .detach();
511
512        Ok(response)
513    }
514
515    pub async fn handle_remove_worktree(
516        this: Entity<Self>,
517        envelope: TypedEnvelope<proto::RemoveWorktree>,
518        mut cx: AsyncApp,
519    ) -> Result<proto::Ack> {
520        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
521        this.update(&mut cx, |this, cx| {
522            this.worktree_store.update(cx, |worktree_store, cx| {
523                worktree_store.remove_worktree(worktree_id, cx);
524            });
525        })?;
526        Ok(proto::Ack {})
527    }
528
529    pub async fn handle_open_buffer_by_path(
530        this: Entity<Self>,
531        message: TypedEnvelope<proto::OpenBufferByPath>,
532        mut cx: AsyncApp,
533    ) -> Result<proto::OpenBufferResponse> {
534        let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
535        let path = RelPath::from_proto(&message.payload.path)?;
536        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
537            let buffer_store = this.buffer_store.clone();
538            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
539                buffer_store.open_buffer(ProjectPath { worktree_id, path }, cx)
540            });
541            anyhow::Ok((buffer_store, buffer))
542        })??;
543
544        let buffer = buffer.await?;
545        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
546        buffer_store.update(&mut cx, |buffer_store, cx| {
547            buffer_store
548                .create_buffer_for_peer(&buffer, REMOTE_SERVER_PEER_ID, cx)
549                .detach_and_log_err(cx);
550        })?;
551
552        Ok(proto::OpenBufferResponse {
553            buffer_id: buffer_id.to_proto(),
554        })
555    }
556
557    pub async fn handle_open_image_by_path(
558        this: Entity<Self>,
559        message: TypedEnvelope<proto::OpenImageByPath>,
560        mut cx: AsyncApp,
561    ) -> Result<proto::OpenImageResponse> {
562        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
563        let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
564        let path = RelPath::from_proto(&message.payload.path)?;
565        let project_id = message.payload.project_id;
566        use proto::create_image_for_peer::Variant;
567
568        let (worktree_store, session) = this.read_with(&cx, |this, _| {
569            (this.worktree_store.clone(), this.session.clone())
570        })?;
571
572        let worktree = worktree_store
573            .read_with(&cx, |store, cx| store.worktree_for_id(worktree_id, cx))?
574            .context("worktree not found")?;
575
576        let load_task = worktree.update(&mut cx, |worktree, cx| {
577            worktree.load_binary_file(path.as_ref(), cx)
578        })?;
579
580        let loaded_file = load_task.await?;
581        let content = loaded_file.content;
582        let file = loaded_file.file;
583
584        let proto_file = worktree.read_with(&cx, |_worktree, cx| file.to_proto(cx))?;
585        let image_id =
586            ImageId::from(NonZeroU64::new(NEXT_ID.fetch_add(1, Ordering::Relaxed)).unwrap());
587
588        let format = image::guess_format(&content)
589            .map(|f| format!("{:?}", f).to_lowercase())
590            .unwrap_or_else(|_| "unknown".to_string());
591
592        let state = proto::ImageState {
593            id: image_id.to_proto(),
594            file: Some(proto_file),
595            content_size: content.len() as u64,
596            format,
597        };
598
599        session.send(proto::CreateImageForPeer {
600            project_id,
601            peer_id: Some(REMOTE_SERVER_PEER_ID),
602            variant: Some(Variant::State(state)),
603        })?;
604
605        const CHUNK_SIZE: usize = 1024 * 1024; // 1MB chunks
606        for chunk in content.chunks(CHUNK_SIZE) {
607            session.send(proto::CreateImageForPeer {
608                project_id,
609                peer_id: Some(REMOTE_SERVER_PEER_ID),
610                variant: Some(Variant::Chunk(proto::ImageChunk {
611                    image_id: image_id.to_proto(),
612                    data: chunk.to_vec(),
613                })),
614            })?;
615        }
616
617        Ok(proto::OpenImageResponse {
618            image_id: image_id.to_proto(),
619        })
620    }
621
622    pub async fn handle_trust_worktrees(
623        this: Entity<Self>,
624        envelope: TypedEnvelope<proto::TrustWorktrees>,
625        mut cx: AsyncApp,
626    ) -> Result<proto::Ack> {
627        let trusted_worktrees = cx
628            .update(|cx| TrustedWorktrees::try_get_global(cx))?
629            .context("missing trusted worktrees")?;
630        let worktree_store = this.read_with(&cx, |project, _| project.worktree_store.clone())?;
631        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
632            trusted_worktrees.trust(
633                &worktree_store,
634                envelope
635                    .payload
636                    .trusted_paths
637                    .into_iter()
638                    .filter_map(PathTrust::from_proto)
639                    .collect(),
640                cx,
641            );
642        })?;
643        Ok(proto::Ack {})
644    }
645
646    pub async fn handle_restrict_worktrees(
647        this: Entity<Self>,
648        envelope: TypedEnvelope<proto::RestrictWorktrees>,
649        mut cx: AsyncApp,
650    ) -> Result<proto::Ack> {
651        let trusted_worktrees = cx
652            .update(|cx| TrustedWorktrees::try_get_global(cx))?
653            .context("missing trusted worktrees")?;
654        let worktree_store =
655            this.read_with(&cx, |project, _| project.worktree_store.downgrade())?;
656        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
657            let restricted_paths = envelope
658                .payload
659                .worktree_ids
660                .into_iter()
661                .map(WorktreeId::from_proto)
662                .map(PathTrust::Worktree)
663                .collect::<HashSet<_>>();
664            trusted_worktrees.restrict(worktree_store, restricted_paths, cx);
665        })?;
666        Ok(proto::Ack {})
667    }
668
669    pub async fn handle_open_new_buffer(
670        this: Entity<Self>,
671        _message: TypedEnvelope<proto::OpenNewBuffer>,
672        mut cx: AsyncApp,
673    ) -> Result<proto::OpenBufferResponse> {
674        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
675            let buffer_store = this.buffer_store.clone();
676            let buffer = this
677                .buffer_store
678                .update(cx, |buffer_store, cx| buffer_store.create_buffer(true, cx));
679            anyhow::Ok((buffer_store, buffer))
680        })??;
681
682        let buffer = buffer.await?;
683        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
684        buffer_store.update(&mut cx, |buffer_store, cx| {
685            buffer_store
686                .create_buffer_for_peer(&buffer, REMOTE_SERVER_PEER_ID, cx)
687                .detach_and_log_err(cx);
688        })?;
689
690        Ok(proto::OpenBufferResponse {
691            buffer_id: buffer_id.to_proto(),
692        })
693    }
694
695    async fn handle_toggle_lsp_logs(
696        _: Entity<Self>,
697        envelope: TypedEnvelope<proto::ToggleLspLogs>,
698        cx: AsyncApp,
699    ) -> Result<()> {
700        let server_id = LanguageServerId::from_proto(envelope.payload.server_id);
701        cx.update(|cx| {
702            let log_store = cx
703                .try_global::<GlobalLogStore>()
704                .map(|global_log_store| global_log_store.0.clone())
705                .context("lsp logs store is missing")?;
706            let toggled_log_kind =
707                match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
708                    .context("invalid log type")?
709                {
710                    proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
711                    proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
712                    proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
713                };
714            log_store.update(cx, |log_store, _| {
715                log_store.toggle_lsp_logs(server_id, envelope.payload.enabled, toggled_log_kind);
716            });
717            anyhow::Ok(())
718        })??;
719
720        Ok(())
721    }
722
723    async fn handle_open_server_settings(
724        this: Entity<Self>,
725        _: TypedEnvelope<proto::OpenServerSettings>,
726        mut cx: AsyncApp,
727    ) -> Result<proto::OpenBufferResponse> {
728        let settings_path = paths::settings_file();
729        let (worktree, path) = this
730            .update(&mut cx, |this, cx| {
731                this.worktree_store.update(cx, |worktree_store, cx| {
732                    worktree_store.find_or_create_worktree(settings_path, false, cx)
733                })
734            })?
735            .await?;
736
737        let (buffer, buffer_store) = this.update(&mut cx, |this, cx| {
738            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
739                buffer_store.open_buffer(
740                    ProjectPath {
741                        worktree_id: worktree.read(cx).id(),
742                        path: path,
743                    },
744                    cx,
745                )
746            });
747
748            (buffer, this.buffer_store.clone())
749        })?;
750
751        let buffer = buffer.await?;
752
753        let buffer_id = cx.update(|cx| {
754            if buffer.read(cx).is_empty() {
755                buffer.update(cx, |buffer, cx| {
756                    buffer.edit([(0..0, initial_server_settings_content())], None, cx)
757                });
758            }
759
760            let buffer_id = buffer.read(cx).remote_id();
761
762            buffer_store.update(cx, |buffer_store, cx| {
763                buffer_store
764                    .create_buffer_for_peer(&buffer, REMOTE_SERVER_PEER_ID, cx)
765                    .detach_and_log_err(cx);
766            });
767
768            buffer_id
769        })?;
770
771        Ok(proto::OpenBufferResponse {
772            buffer_id: buffer_id.to_proto(),
773        })
774    }
775
776    async fn handle_find_search_candidates(
777        this: Entity<Self>,
778        envelope: TypedEnvelope<proto::FindSearchCandidates>,
779        mut cx: AsyncApp,
780    ) -> Result<proto::FindSearchCandidatesResponse> {
781        let message = envelope.payload;
782        let query = SearchQuery::from_proto(
783            message.query.context("missing query field")?,
784            PathStyle::local(),
785        )?;
786        let results = this.update(&mut cx, |this, cx| {
787            project::Search::local(
788                this.fs.clone(),
789                this.buffer_store.clone(),
790                this.worktree_store.clone(),
791                message.limit as _,
792                cx,
793            )
794            .into_handle(query, cx)
795            .matching_buffers(cx)
796        })?;
797
798        let mut response = proto::FindSearchCandidatesResponse {
799            buffer_ids: Vec::new(),
800        };
801
802        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
803
804        while let Ok(buffer) = results.rx.recv().await {
805            let buffer_id = buffer.read_with(&cx, |this, _| this.remote_id())?;
806            response.buffer_ids.push(buffer_id.to_proto());
807            buffer_store
808                .update(&mut cx, |buffer_store, cx| {
809                    buffer_store.create_buffer_for_peer(&buffer, REMOTE_SERVER_PEER_ID, cx)
810                })?
811                .await?;
812        }
813
814        Ok(response)
815    }
816
817    async fn handle_list_remote_directory(
818        this: Entity<Self>,
819        envelope: TypedEnvelope<proto::ListRemoteDirectory>,
820        cx: AsyncApp,
821    ) -> Result<proto::ListRemoteDirectoryResponse> {
822        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
823        let expanded = PathBuf::from(shellexpand::tilde(&envelope.payload.path).to_string());
824        let check_info = envelope
825            .payload
826            .config
827            .as_ref()
828            .is_some_and(|config| config.is_dir);
829
830        let mut entries = Vec::new();
831        let mut entry_info = Vec::new();
832        let mut response = fs.read_dir(&expanded).await?;
833        while let Some(path) = response.next().await {
834            let path = path?;
835            if let Some(file_name) = path.file_name() {
836                entries.push(file_name.to_string_lossy().into_owned());
837                if check_info {
838                    let is_dir = fs.is_dir(&path).await;
839                    entry_info.push(proto::EntryInfo { is_dir });
840                }
841            }
842        }
843        Ok(proto::ListRemoteDirectoryResponse {
844            entries,
845            entry_info,
846        })
847    }
848
849    async fn handle_get_path_metadata(
850        this: Entity<Self>,
851        envelope: TypedEnvelope<proto::GetPathMetadata>,
852        cx: AsyncApp,
853    ) -> Result<proto::GetPathMetadataResponse> {
854        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
855        let expanded = PathBuf::from(shellexpand::tilde(&envelope.payload.path).to_string());
856
857        let metadata = fs.metadata(&expanded).await?;
858        let is_dir = metadata.map(|metadata| metadata.is_dir).unwrap_or(false);
859
860        Ok(proto::GetPathMetadataResponse {
861            exists: metadata.is_some(),
862            is_dir,
863            path: expanded.to_string_lossy().into_owned(),
864        })
865    }
866
867    async fn handle_shutdown_remote_server(
868        _this: Entity<Self>,
869        _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
870        cx: AsyncApp,
871    ) -> Result<proto::Ack> {
872        cx.spawn(async move |cx| {
873            cx.update(|cx| {
874                // TODO: This is a hack, because in a headless project, shutdown isn't executed
875                // when calling quit, but it should be.
876                cx.shutdown();
877                cx.quit();
878            })
879        })
880        .detach();
881
882        Ok(proto::Ack {})
883    }
884
885    pub async fn handle_ping(
886        _this: Entity<Self>,
887        _envelope: TypedEnvelope<proto::Ping>,
888        _cx: AsyncApp,
889    ) -> Result<proto::Ack> {
890        log::debug!("Received ping from client");
891        Ok(proto::Ack {})
892    }
893
894    async fn handle_get_processes(
895        _this: Entity<Self>,
896        _envelope: TypedEnvelope<proto::GetProcesses>,
897        _cx: AsyncApp,
898    ) -> Result<proto::GetProcessesResponse> {
899        let mut processes = Vec::new();
900        let refresh_kind = RefreshKind::nothing().with_processes(
901            ProcessRefreshKind::nothing()
902                .without_tasks()
903                .with_cmd(UpdateKind::Always),
904        );
905
906        for process in System::new_with_specifics(refresh_kind)
907            .processes()
908            .values()
909        {
910            let name = process.name().to_string_lossy().into_owned();
911            let command = process
912                .cmd()
913                .iter()
914                .map(|s| s.to_string_lossy().into_owned())
915                .collect::<Vec<_>>();
916
917            processes.push(proto::ProcessInfo {
918                pid: process.pid().as_u32(),
919                name,
920                command,
921            });
922        }
923
924        processes.sort_by_key(|p| p.name.clone());
925
926        Ok(proto::GetProcessesResponse { processes })
927    }
928
929    async fn handle_get_directory_environment(
930        this: Entity<Self>,
931        envelope: TypedEnvelope<proto::GetDirectoryEnvironment>,
932        mut cx: AsyncApp,
933    ) -> Result<proto::DirectoryEnvironment> {
934        let shell = task::shell_from_proto(envelope.payload.shell.context("missing shell")?)?;
935        let directory = PathBuf::from(envelope.payload.directory);
936        let environment = this
937            .update(&mut cx, |this, cx| {
938                this.environment.update(cx, |environment, cx| {
939                    environment.local_directory_environment(&shell, directory.into(), cx)
940                })
941            })?
942            .await
943            .context("failed to get directory environment")?
944            .into_iter()
945            .collect();
946        Ok(proto::DirectoryEnvironment { environment })
947    }
948}
949
950fn prompt_to_proto(
951    prompt: &project::LanguageServerPromptRequest,
952) -> proto::language_server_prompt_request::Level {
953    match prompt.level {
954        PromptLevel::Info => proto::language_server_prompt_request::Level::Info(
955            proto::language_server_prompt_request::Info {},
956        ),
957        PromptLevel::Warning => proto::language_server_prompt_request::Level::Warning(
958            proto::language_server_prompt_request::Warning {},
959        ),
960        PromptLevel::Critical => proto::language_server_prompt_request::Level::Critical(
961            proto::language_server_prompt_request::Critical {},
962        ),
963    }
964}