headless_project.rs

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