1139 lines · 41.5 KB · Rust
RawDownload
use anyhow::{Context as _, Result, anyhow};use client::ProjectId;use collections::HashSet;use language::File;use lsp::LanguageServerId; use extension::ExtensionHostProxy;use extension_host::headless_host::HeadlessExtensionStore;use fs::Fs;use gpui::{App, AppContext as _, AsyncApp, Context, Entity, PromptLevel};use http_client::HttpClient;use language::{Buffer, BufferEvent, LanguageRegistry, proto::serialize_operation};use node_runtime::NodeRuntime;use project::{    AgentRegistryStore, LspStore, LspStoreEvent, ManifestTree, PrettierStore, ProjectEnvironment,    ProjectPath, ToolchainStore, WorktreeId,    agent_server_store::AgentServerStore,    buffer_store::{BufferStore, BufferStoreEvent},    context_server_store::ContextServerStore,    debugger::{breakpoint_store::BreakpointStore, dap_store::DapStore},    git_store::GitStore,    image_store::ImageId,    lsp_store::log_store::{self, GlobalLogStore, LanguageServerKind, LogKind},    project_settings::SettingsObserver,    search::SearchQuery,    task_store::TaskStore,    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},    worktree_store::{WorktreeIdCounter, WorktreeStore},};use rpc::{    AnyProtoClient, TypedEnvelope,    proto::{self, REMOTE_SERVER_PEER_ID, REMOTE_SERVER_PROJECT_ID},}; use settings::initial_server_settings_content;use std::{    num::NonZeroU64,    path::{Path, PathBuf},    sync::{        Arc,        atomic::{AtomicU64, AtomicUsize, Ordering},    },};use sysinfo::{ProcessRefreshKind, RefreshKind, System, UpdateKind};use util::{ResultExt, paths::PathStyle, rel_path::RelPath};use worktree::Worktree; pub struct HeadlessProject {    pub fs: Arc<dyn Fs>,    pub session: AnyProtoClient,    pub worktree_store: Entity<WorktreeStore>,    pub buffer_store: Entity<BufferStore>,    pub lsp_store: Entity<LspStore>,    pub task_store: Entity<TaskStore>,    pub dap_store: Entity<DapStore>,    pub breakpoint_store: Entity<BreakpointStore>,    pub agent_server_store: Entity<AgentServerStore>,    pub context_server_store: Entity<ContextServerStore>,    pub settings_observer: Entity<SettingsObserver>,    pub next_entry_id: Arc<AtomicUsize>,    pub languages: Arc<LanguageRegistry>,    pub extensions: Entity<HeadlessExtensionStore>,    pub git_store: Entity<GitStore>,    pub environment: Entity<ProjectEnvironment>,    // Used mostly to keep alive the toolchain store for RPC handlers.    // Local variant is used within LSP store, but that's a separate entity.    pub _toolchain_store: Entity<ToolchainStore>,} pub struct HeadlessAppState {    pub session: AnyProtoClient,    pub fs: Arc<dyn Fs>,    pub http_client: Arc<dyn HttpClient>,    pub node_runtime: NodeRuntime,    pub languages: Arc<LanguageRegistry>,    pub extension_host_proxy: Arc<ExtensionHostProxy>,} impl HeadlessProject {    pub fn init(cx: &mut App) {        settings::init(cx);        log_store::init(true, cx);    }     pub fn new(        HeadlessAppState {            session,            fs,            http_client,            node_runtime,            languages,            extension_host_proxy: proxy,        }: HeadlessAppState,        init_worktree_trust: bool,        cx: &mut Context<Self>,    ) -> Self {        debug_adapter_extension::init(proxy.clone(), cx);        languages::init(languages.clone(), fs.clone(), node_runtime.clone(), cx);         let worktree_store = cx.new(|cx| {            let mut store = WorktreeStore::local(true, fs.clone(), WorktreeIdCounter::get(cx));            store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            store        });         if init_worktree_trust {            project::trusted_worktrees::track_worktree_trust(                worktree_store.clone(),                None::<RemoteHostLocation>,                Some((session.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))),                None,                cx,            );        }         let environment =            cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx));        let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);        let toolchain_store = cx.new(|cx| {            ToolchainStore::local(                languages.clone(),                worktree_store.clone(),                environment.clone(),                manifest_tree.clone(),                fs.clone(),                cx,            )        });         let buffer_store = cx.new(|cx| {            let mut buffer_store = BufferStore::local(worktree_store.clone(), cx);            buffer_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            buffer_store        });         let breakpoint_store = cx.new(|_| {            let mut breakpoint_store =                BreakpointStore::local(worktree_store.clone(), buffer_store.clone());            breakpoint_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone());             breakpoint_store        });         let dap_store = cx.new(|cx| {            let mut dap_store = DapStore::new_local(                http_client.clone(),                node_runtime.clone(),                fs.clone(),                environment.clone(),                toolchain_store.read(cx).as_language_toolchain_store(),                worktree_store.clone(),                breakpoint_store.clone(),                true,                cx,            );            dap_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            dap_store        });         let git_store = cx.new(|cx| {            let mut store = GitStore::local(                &worktree_store,                buffer_store.clone(),                environment.clone(),                fs.clone(),                cx,            );            store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            store        });         let prettier_store = cx.new(|cx| {            PrettierStore::new(                node_runtime.clone(),                fs.clone(),                languages.clone(),                worktree_store.clone(),                cx,            )        });         let task_store = cx.new(|cx| {            let mut task_store = TaskStore::local(                buffer_store.downgrade(),                worktree_store.clone(),                toolchain_store.read(cx).as_language_toolchain_store(),                environment.clone(),                cx,            );            task_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            task_store        });        let settings_observer = cx.new(|cx| {            let mut observer = SettingsObserver::new_local(                fs.clone(),                worktree_store.clone(),                task_store.clone(),                true,                cx,            );            observer.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            observer        });         let lsp_store = cx.new(|cx| {            let mut lsp_store = LspStore::new_local(                buffer_store.clone(),                worktree_store.clone(),                prettier_store.clone(),                toolchain_store                    .read(cx)                    .as_local_store()                    .expect("Toolchain store to be local")                    .clone(),                environment.clone(),                manifest_tree,                languages.clone(),                http_client.clone(),                fs.clone(),                cx,            );            lsp_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            lsp_store        });         AgentRegistryStore::init_global(cx, fs.clone(), http_client.clone());         let agent_server_store = cx.new(|cx| {            let mut agent_server_store = AgentServerStore::local(                node_runtime.clone(),                fs.clone(),                environment.clone(),                http_client.clone(),                cx,            );            agent_server_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone(), cx);            agent_server_store        });         let context_server_store = cx.new(|cx| {            let mut context_server_store =                ContextServerStore::local(worktree_store.clone(), None, true, cx);            context_server_store.shared(REMOTE_SERVER_PROJECT_ID, session.clone());            context_server_store        });         cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();        language_extension::init(            language_extension::LspAccess::ViaLspStore(lsp_store.clone()),            proxy.clone(),            languages.clone(),        );         cx.subscribe(&buffer_store, |_this, _buffer_store, event, cx| {            if let BufferStoreEvent::BufferAdded(buffer) = event {                cx.subscribe(buffer, Self::on_buffer_event).detach();            }        })        .detach();         let extensions = HeadlessExtensionStore::new(            fs.clone(),            http_client.clone(),            paths::remote_extensions_dir().to_path_buf(),            proxy,            node_runtime,            cx,        );         // local_machine -> ssh handlers        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &worktree_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &buffer_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &lsp_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &task_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &toolchain_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &dap_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &breakpoint_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &settings_observer);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &git_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &agent_server_store);        session.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &context_server_store);         session.add_request_handler(cx.weak_entity(), Self::handle_list_remote_directory);        session.add_request_handler(cx.weak_entity(), Self::handle_get_path_metadata);        session.add_request_handler(cx.weak_entity(), Self::handle_shutdown_remote_server);        session.add_request_handler(cx.weak_entity(), Self::handle_ping);        session.add_request_handler(cx.weak_entity(), Self::handle_get_processes);         session.add_entity_request_handler(Self::handle_add_worktree);        session.add_request_handler(cx.weak_entity(), Self::handle_remove_worktree);         session.add_entity_request_handler(Self::handle_open_buffer_by_path);        session.add_entity_request_handler(Self::handle_open_new_buffer);        session.add_entity_request_handler(Self::handle_find_search_candidates);        session.add_entity_request_handler(Self::handle_open_server_settings);        session.add_entity_request_handler(Self::handle_get_directory_environment);        session.add_entity_message_handler(Self::handle_toggle_lsp_logs);        session.add_entity_request_handler(Self::handle_open_image_by_path);        session.add_entity_request_handler(Self::handle_trust_worktrees);        session.add_entity_request_handler(Self::handle_restrict_worktrees);        session.add_entity_request_handler(Self::handle_download_file_by_path);         session.add_entity_message_handler(Self::handle_find_search_candidates_cancel);        session.add_entity_request_handler(BufferStore::handle_update_buffer);        session.add_entity_message_handler(BufferStore::handle_close_buffer);         session.add_request_handler(            extensions.downgrade(),            HeadlessExtensionStore::handle_sync_extensions,        );        session.add_request_handler(            extensions.downgrade(),            HeadlessExtensionStore::handle_install_extension,        );         BufferStore::init(&session);        WorktreeStore::init(&session);        SettingsObserver::init(&session);        LspStore::init(&session);        TaskStore::init(Some(&session));        ToolchainStore::init(&session);        DapStore::init(&session, cx);        // todo(debugger): Re init breakpoint store when we set it up for collab        BreakpointStore::init(&session);        GitStore::init(&session);        AgentServerStore::init_headless(&session);        ContextServerStore::init_headless(&session);         HeadlessProject {            next_entry_id: Default::default(),            session,            settings_observer,            fs,            worktree_store,            buffer_store,            lsp_store,            task_store,            dap_store,            breakpoint_store,            agent_server_store,            context_server_store,            languages,            extensions,            git_store,            environment,            _toolchain_store: toolchain_store,        }    }     fn on_buffer_event(        &mut self,        buffer: Entity<Buffer>,        event: &BufferEvent,        cx: &mut Context<Self>,    ) {        if let BufferEvent::Operation {            operation,            is_local: true,        } = event        {            cx.background_spawn(self.session.request(proto::UpdateBuffer {                project_id: REMOTE_SERVER_PROJECT_ID,                buffer_id: buffer.read(cx).remote_id().to_proto(),                operations: vec![serialize_operation(operation)],            }))            .detach()        }    }     fn on_lsp_store_event(        &mut self,        lsp_store: Entity<LspStore>,        event: &LspStoreEvent,        cx: &mut Context<Self>,    ) {        match event {            LspStoreEvent::LanguageServerAdded(id, name, worktree_id) => {                let log_store = cx                    .try_global::<GlobalLogStore>()                    .map(|lsp_logs| lsp_logs.0.clone());                if let Some(log_store) = log_store {                    log_store.update(cx, |log_store, cx| {                        log_store.add_language_server(                            LanguageServerKind::LocalSsh {                                lsp_store: self.lsp_store.downgrade(),                            },                            *id,                            Some(name.clone()),                            *worktree_id,                            lsp_store.read(cx).language_server_for_id(*id),                            cx,                        );                    });                }            }            LspStoreEvent::LanguageServerRemoved(id) => {                let log_store = cx                    .try_global::<GlobalLogStore>()                    .map(|lsp_logs| lsp_logs.0.clone());                if let Some(log_store) = log_store {                    log_store.update(cx, |log_store, cx| {                        log_store.remove_language_server(*id, cx);                    });                }            }            LspStoreEvent::LanguageServerUpdate {                language_server_id,                name,                message,            } => {                self.session                    .send(proto::UpdateLanguageServer {                        project_id: REMOTE_SERVER_PROJECT_ID,                        server_name: name.as_ref().map(|name| name.to_string()),                        language_server_id: language_server_id.to_proto(),                        variant: Some(message.clone()),                    })                    .log_err();            }            LspStoreEvent::Notification(message) => {                self.session                    .send(proto::Toast {                        project_id: REMOTE_SERVER_PROJECT_ID,                        notification_id: "lsp".to_string(),                        message: message.clone(),                    })                    .log_err();            }            LspStoreEvent::LanguageServerPrompt(prompt) => {                let request = self.session.request(proto::LanguageServerPromptRequest {                    project_id: REMOTE_SERVER_PROJECT_ID,                    actions: prompt                        .actions                        .iter()                        .map(|action| action.title.to_string())                        .collect(),                    level: Some(prompt_to_proto(prompt)),                    lsp_name: prompt.lsp_name.clone(),                    message: prompt.message.clone(),                });                let prompt = prompt.clone();                cx.background_spawn(async move {                    let response = request.await?;                    if let Some(action_response) = response.action_response {                        prompt.respond(action_response as usize).await;                    }                    anyhow::Ok(())                })                .detach();            }            _ => {}        }    }     pub async fn handle_add_worktree(        this: Entity<Self>,        message: TypedEnvelope<proto::AddWorktree>,        mut cx: AsyncApp,    ) -> Result<proto::AddWorktreeResponse> {        use client::ErrorCodeExt;        let fs = this.read_with(&cx, |this, _| this.fs.clone());        let path = PathBuf::from(shellexpand::tilde(&message.payload.path).to_string());         let canonicalized = match fs.canonicalize(&path).await {            Ok(path) => path,            Err(e) => {                let mut parent = path                    .parent()                    .ok_or(e)                    .with_context(|| format!("{path:?} does not exist"))?;                if parent == Path::new("") {                    parent = util::paths::home_dir();                }                let parent = fs.canonicalize(parent).await.map_err(|_| {                    anyhow!(                        proto::ErrorCode::DevServerProjectPathDoesNotExist                            .with_tag("path", path.to_string_lossy().as_ref())                    )                })?;                if let Some(file_name) = path.file_name() {                    parent.join(file_name)                } else {                    parent                }            }        };        let next_worktree_id = this            .update(&mut cx, |this, cx| {                this.worktree_store                    .update(cx, |worktree_store, _| worktree_store.next_worktree_id())            })            .await?;        let worktree = this            .read_with(&cx.clone(), |this, _| {                Worktree::local(                    Arc::from(canonicalized.as_path()),                    message.payload.visible,                    this.fs.clone(),                    this.next_entry_id.clone(),

Lines 1–500 of 1139.