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
175                    .read(cx)
176                    .as_local_store()
177                    .expect("Toolchain store to be local")
178                    .clone(),
179                environment,
180                manifest_tree,
181                languages.clone(),
182                http_client.clone(),
183                fs.clone(),
184                cx,
185            );
186            lsp_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
187            lsp_store
188        });
189
190        cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
191        language_extension::init(
192            language_extension::LspAccess::ViaLspStore(lsp_store.clone()),
193            proxy.clone(),
194            languages.clone(),
195        );
196
197        cx.subscribe(&buffer_store, |_this, _buffer_store, event, cx| {
198            if let BufferStoreEvent::BufferAdded(buffer) = event {
199                cx.subscribe(buffer, Self::on_buffer_event).detach();
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        if let BufferEvent::Operation {
285            operation,
286            is_local: true,
287        } = event
288        {
289            cx.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    fn on_lsp_store_event(
299        &mut self,
300        _lsp_store: Entity<LspStore>,
301        event: &LspStoreEvent,
302        cx: &mut Context<Self>,
303    ) {
304        match event {
305            LspStoreEvent::LanguageServerUpdate {
306                language_server_id,
307                name,
308                message,
309            } => {
310                self.session
311                    .send(proto::UpdateLanguageServer {
312                        project_id: SSH_PROJECT_ID,
313                        server_name: name.as_ref().map(|name| name.to_string()),
314                        language_server_id: language_server_id.to_proto(),
315                        variant: Some(message.clone()),
316                    })
317                    .log_err();
318            }
319            LspStoreEvent::Notification(message) => {
320                self.session
321                    .send(proto::Toast {
322                        project_id: SSH_PROJECT_ID,
323                        notification_id: "lsp".to_string(),
324                        message: message.clone(),
325                    })
326                    .log_err();
327            }
328            LspStoreEvent::LanguageServerLog(language_server_id, log_type, message) => {
329                self.session
330                    .send(proto::LanguageServerLog {
331                        project_id: SSH_PROJECT_ID,
332                        language_server_id: language_server_id.to_proto(),
333                        message: message.clone(),
334                        log_type: Some(log_type.to_proto()),
335                    })
336                    .log_err();
337            }
338            LspStoreEvent::LanguageServerPrompt(prompt) => {
339                let request = self.session.request(proto::LanguageServerPromptRequest {
340                    project_id: SSH_PROJECT_ID,
341                    actions: prompt
342                        .actions
343                        .iter()
344                        .map(|action| action.title.to_string())
345                        .collect(),
346                    level: Some(prompt_to_proto(prompt)),
347                    lsp_name: prompt.lsp_name.clone(),
348                    message: prompt.message.clone(),
349                });
350                let prompt = prompt.clone();
351                cx.background_spawn(async move {
352                    let response = request.await?;
353                    if let Some(action_response) = response.action_response {
354                        prompt.respond(action_response as usize).await;
355                    }
356                    anyhow::Ok(())
357                })
358                .detach();
359            }
360            _ => {}
361        }
362    }
363
364    pub async fn handle_add_worktree(
365        this: Entity<Self>,
366        message: TypedEnvelope<proto::AddWorktree>,
367        mut cx: AsyncApp,
368    ) -> Result<proto::AddWorktreeResponse> {
369        use client::ErrorCodeExt;
370        let fs = this.read_with(&cx, |this, _| this.fs.clone())?;
371        let path = PathBuf::from_proto(shellexpand::tilde(&message.payload.path).to_string());
372
373        let canonicalized = match fs.canonicalize(&path).await {
374            Ok(path) => path,
375            Err(e) => {
376                let mut parent = path
377                    .parent()
378                    .ok_or(e)
379                    .with_context(|| format!("{path:?} does not exist"))?;
380                if parent == Path::new("") {
381                    parent = util::paths::home_dir();
382                }
383                let parent = fs.canonicalize(parent).await.map_err(|_| {
384                    anyhow!(
385                        proto::ErrorCode::DevServerProjectPathDoesNotExist
386                            .with_tag("path", path.to_string_lossy().as_ref())
387                    )
388                })?;
389                parent.join(path.file_name().unwrap())
390            }
391        };
392
393        let worktree = this
394            .read_with(&cx.clone(), |this, _| {
395                Worktree::local(
396                    Arc::from(canonicalized.as_path()),
397                    message.payload.visible,
398                    this.fs.clone(),
399                    this.next_entry_id.clone(),
400                    &mut cx,
401                )
402            })?
403            .await?;
404
405        let response = this.read_with(&cx, |_, cx| {
406            let worktree = worktree.read(cx);
407            proto::AddWorktreeResponse {
408                worktree_id: worktree.id().to_proto(),
409                canonicalized_path: canonicalized.to_proto(),
410            }
411        })?;
412
413        // We spawn this asynchronously, so that we can send the response back
414        // *before* `worktree_store.add()` can send out UpdateProject requests
415        // to the client about the new worktree.
416        //
417        // That lets the client manage the reference/handles of the newly-added
418        // worktree, before getting interrupted by an UpdateProject request.
419        //
420        // This fixes the problem of the client sending the AddWorktree request,
421        // headless project sending out a project update, client receiving it
422        // and immediately dropping the reference of the new client, causing it
423        // to be dropped on the headless project, and the client only then
424        // receiving a response to AddWorktree.
425        cx.spawn(async move |cx| {
426            this.update(cx, |this, cx| {
427                this.worktree_store.update(cx, |worktree_store, cx| {
428                    worktree_store.add(&worktree, cx);
429                });
430            })
431            .log_err();
432        })
433        .detach();
434
435        Ok(response)
436    }
437
438    pub async fn handle_remove_worktree(
439        this: Entity<Self>,
440        envelope: TypedEnvelope<proto::RemoveWorktree>,
441        mut cx: AsyncApp,
442    ) -> Result<proto::Ack> {
443        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
444        this.update(&mut cx, |this, cx| {
445            this.worktree_store.update(cx, |worktree_store, cx| {
446                worktree_store.remove_worktree(worktree_id, cx);
447            });
448        })?;
449        Ok(proto::Ack {})
450    }
451
452    pub async fn handle_open_buffer_by_path(
453        this: Entity<Self>,
454        message: TypedEnvelope<proto::OpenBufferByPath>,
455        mut cx: AsyncApp,
456    ) -> Result<proto::OpenBufferResponse> {
457        let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
458        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
459            let buffer_store = this.buffer_store.clone();
460            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
461                buffer_store.open_buffer(
462                    ProjectPath {
463                        worktree_id,
464                        path: Arc::<Path>::from_proto(message.payload.path),
465                    },
466                    cx,
467                )
468            });
469            anyhow::Ok((buffer_store, buffer))
470        })??;
471
472        let buffer = buffer.await?;
473        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
474        buffer_store.update(&mut cx, |buffer_store, cx| {
475            buffer_store
476                .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
477                .detach_and_log_err(cx);
478        })?;
479
480        Ok(proto::OpenBufferResponse {
481            buffer_id: buffer_id.to_proto(),
482        })
483    }
484
485    pub async fn handle_open_new_buffer(
486        this: Entity<Self>,
487        _message: TypedEnvelope<proto::OpenNewBuffer>,
488        mut cx: AsyncApp,
489    ) -> Result<proto::OpenBufferResponse> {
490        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
491            let buffer_store = this.buffer_store.clone();
492            let buffer = this
493                .buffer_store
494                .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx));
495            anyhow::Ok((buffer_store, buffer))
496        })??;
497
498        let buffer = buffer.await?;
499        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
500        buffer_store.update(&mut cx, |buffer_store, cx| {
501            buffer_store
502                .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
503                .detach_and_log_err(cx);
504        })?;
505
506        Ok(proto::OpenBufferResponse {
507            buffer_id: buffer_id.to_proto(),
508        })
509    }
510
511    pub async fn handle_open_server_settings(
512        this: Entity<Self>,
513        _: TypedEnvelope<proto::OpenServerSettings>,
514        mut cx: AsyncApp,
515    ) -> Result<proto::OpenBufferResponse> {
516        let settings_path = paths::settings_file();
517        let (worktree, path) = this
518            .update(&mut cx, |this, cx| {
519                this.worktree_store.update(cx, |worktree_store, cx| {
520                    worktree_store.find_or_create_worktree(settings_path, false, cx)
521                })
522            })?
523            .await?;
524
525        let (buffer, buffer_store) = this.update(&mut cx, |this, cx| {
526            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
527                buffer_store.open_buffer(
528                    ProjectPath {
529                        worktree_id: worktree.read(cx).id(),
530                        path: path.into(),
531                    },
532                    cx,
533                )
534            });
535
536            (buffer, this.buffer_store.clone())
537        })?;
538
539        let buffer = buffer.await?;
540
541        let buffer_id = cx.update(|cx| {
542            if buffer.read(cx).is_empty() {
543                buffer.update(cx, |buffer, cx| {
544                    buffer.edit([(0..0, initial_server_settings_content())], None, cx)
545                });
546            }
547
548            let buffer_id = buffer.read(cx).remote_id();
549
550            buffer_store.update(cx, |buffer_store, cx| {
551                buffer_store
552                    .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
553                    .detach_and_log_err(cx);
554            });
555
556            buffer_id
557        })?;
558
559        Ok(proto::OpenBufferResponse {
560            buffer_id: buffer_id.to_proto(),
561        })
562    }
563
564    pub async fn handle_find_search_candidates(
565        this: Entity<Self>,
566        envelope: TypedEnvelope<proto::FindSearchCandidates>,
567        mut cx: AsyncApp,
568    ) -> Result<proto::FindSearchCandidatesResponse> {
569        let message = envelope.payload;
570        let query = SearchQuery::from_proto(message.query.context("missing query field")?)?;
571        let results = this.update(&mut cx, |this, cx| {
572            this.buffer_store.update(cx, |buffer_store, cx| {
573                buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
574            })
575        })?;
576
577        let mut response = proto::FindSearchCandidatesResponse {
578            buffer_ids: Vec::new(),
579        };
580
581        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
582
583        while let Ok(buffer) = results.recv().await {
584            let buffer_id = buffer.read_with(&cx, |this, _| this.remote_id())?;
585            response.buffer_ids.push(buffer_id.to_proto());
586            buffer_store
587                .update(&mut cx, |buffer_store, cx| {
588                    buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
589                })?
590                .await?;
591        }
592
593        Ok(response)
594    }
595
596    pub async fn handle_list_remote_directory(
597        this: Entity<Self>,
598        envelope: TypedEnvelope<proto::ListRemoteDirectory>,
599        cx: AsyncApp,
600    ) -> Result<proto::ListRemoteDirectoryResponse> {
601        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
602        let expanded = PathBuf::from_proto(shellexpand::tilde(&envelope.payload.path).to_string());
603        let check_info = envelope
604            .payload
605            .config
606            .as_ref()
607            .is_some_and(|config| config.is_dir);
608
609        let mut entries = Vec::new();
610        let mut entry_info = Vec::new();
611        let mut response = fs.read_dir(&expanded).await?;
612        while let Some(path) = response.next().await {
613            let path = path?;
614            if let Some(file_name) = path.file_name() {
615                entries.push(file_name.to_string_lossy().to_string());
616                if check_info {
617                    let is_dir = fs.is_dir(&path).await;
618                    entry_info.push(proto::EntryInfo { is_dir });
619                }
620            }
621        }
622        Ok(proto::ListRemoteDirectoryResponse {
623            entries,
624            entry_info,
625        })
626    }
627
628    pub async fn handle_get_path_metadata(
629        this: Entity<Self>,
630        envelope: TypedEnvelope<proto::GetPathMetadata>,
631        cx: AsyncApp,
632    ) -> Result<proto::GetPathMetadataResponse> {
633        let fs = cx.read_entity(&this, |this, _| this.fs.clone())?;
634        let expanded = PathBuf::from_proto(shellexpand::tilde(&envelope.payload.path).to_string());
635
636        let metadata = fs.metadata(&expanded).await?;
637        let is_dir = metadata.map(|metadata| metadata.is_dir).unwrap_or(false);
638
639        Ok(proto::GetPathMetadataResponse {
640            exists: metadata.is_some(),
641            is_dir,
642            path: expanded.to_proto(),
643        })
644    }
645
646    pub async fn handle_shutdown_remote_server(
647        _this: Entity<Self>,
648        _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
649        cx: AsyncApp,
650    ) -> Result<proto::Ack> {
651        cx.spawn(async move |cx| {
652            cx.update(|cx| {
653                // TODO: This is a hack, because in a headless project, shutdown isn't executed
654                // when calling quit, but it should be.
655                cx.shutdown();
656                cx.quit();
657            })
658        })
659        .detach();
660
661        Ok(proto::Ack {})
662    }
663
664    pub async fn handle_ping(
665        _this: Entity<Self>,
666        _envelope: TypedEnvelope<proto::Ping>,
667        _cx: AsyncApp,
668    ) -> Result<proto::Ack> {
669        log::debug!("Received ping from client");
670        Ok(proto::Ack {})
671    }
672}
673
674fn prompt_to_proto(
675    prompt: &project::LanguageServerPromptRequest,
676) -> proto::language_server_prompt_request::Level {
677    match prompt.level {
678        PromptLevel::Info => proto::language_server_prompt_request::Level::Info(
679            proto::language_server_prompt_request::Info {},
680        ),
681        PromptLevel::Warning => proto::language_server_prompt_request::Level::Warning(
682            proto::language_server_prompt_request::Warning {},
683        ),
684        PromptLevel::Critical => proto::language_server_prompt_request::Level::Critical(
685            proto::language_server_prompt_request::Critical {},
686        ),
687    }
688}