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