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