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