test_server.rs

  1use crate::{
  2    AppState, Config,
  3    db::{NewUserParams, UserId, tests::TestDb},
  4    executor::Executor,
  5    rpc::{CLEANUP_TIMEOUT, Principal, RECONNECT_TIMEOUT, Server, ZedVersion},
  6};
  7use anyhow::anyhow;
  8use call::ActiveCall;
  9use channel::{ChannelBuffer, ChannelStore};
 10use client::test::{make_get_authenticated_user_response, parse_authorization_header};
 11use client::{
 12    self, ChannelId, Client, Connection, Credentials, EstablishConnectionError, UserStore,
 13    proto::PeerId,
 14};
 15use clock::FakeSystemClock;
 16use collab_ui::channel_view::ChannelView;
 17use collections::{HashMap, HashSet};
 18
 19use fs::FakeFs;
 20use futures::{StreamExt as _, channel::oneshot};
 21use git::GitHostingProviderRegistry;
 22use gpui::{AppContext as _, BackgroundExecutor, Entity, Task, TestAppContext, VisualTestContext};
 23use http_client::{FakeHttpClient, Method};
 24use language::LanguageRegistry;
 25use node_runtime::NodeRuntime;
 26use notifications::NotificationStore;
 27use parking_lot::Mutex;
 28use project::{Project, WorktreeId};
 29use remote::RemoteClient;
 30use rpc::{
 31    RECEIVE_TIMEOUT,
 32    proto::{self, ChannelRole},
 33};
 34use serde_json::json;
 35use session::{AppSession, Session};
 36use settings::SettingsStore;
 37use std::{
 38    cell::{Ref, RefCell, RefMut},
 39    env,
 40    ops::{Deref, DerefMut},
 41    path::Path,
 42    sync::{
 43        Arc,
 44        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 45    },
 46};
 47use util::path;
 48use workspace::{Workspace, WorkspaceStore};
 49
 50use livekit_client::test::TestServer as LivekitTestServer;
 51
 52pub struct TestServer {
 53    pub app_state: Arc<AppState>,
 54    pub test_livekit_server: Arc<LivekitTestServer>,
 55    pub test_db: TestDb,
 56    server: Arc<Server>,
 57    next_github_user_id: i32,
 58    connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
 59    forbid_connections: Arc<AtomicBool>,
 60}
 61
 62pub struct TestClient {
 63    pub username: String,
 64    pub app_state: Arc<workspace::AppState>,
 65    channel_store: Entity<ChannelStore>,
 66    notification_store: Entity<NotificationStore>,
 67    state: RefCell<TestClientState>,
 68}
 69
 70#[derive(Default)]
 71struct TestClientState {
 72    local_projects: Vec<Entity<Project>>,
 73    dev_server_projects: Vec<Entity<Project>>,
 74    buffers: HashMap<Entity<Project>, HashSet<Entity<language::Buffer>>>,
 75    channel_buffers: HashSet<Entity<ChannelBuffer>>,
 76}
 77
 78pub struct ContactsSummary {
 79    pub current: Vec<String>,
 80    pub outgoing_requests: Vec<String>,
 81    pub incoming_requests: Vec<String>,
 82}
 83
 84impl TestServer {
 85    pub async fn start(deterministic: BackgroundExecutor) -> Self {
 86        static NEXT_LIVEKIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
 87
 88        let use_postgres = env::var("USE_POSTGRES").ok();
 89        let use_postgres = use_postgres.as_deref();
 90        let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
 91            TestDb::postgres(deterministic.clone())
 92        } else {
 93            TestDb::sqlite(deterministic.clone())
 94        };
 95        let livekit_server_id = NEXT_LIVEKIT_SERVER_ID.fetch_add(1, SeqCst);
 96        let livekit_server = LivekitTestServer::create(
 97            format!("http://livekit.{}.test", livekit_server_id),
 98            format!("devkey-{}", livekit_server_id),
 99            format!("secret-{}", livekit_server_id),
100            deterministic.clone(),
101        )
102        .unwrap();
103        let executor = Executor::Deterministic(deterministic.clone());
104        let app_state = Self::build_app_state(&test_db, &livekit_server, executor.clone()).await;
105        let epoch = app_state
106            .db
107            .create_server(&app_state.config.zed_environment)
108            .await
109            .unwrap();
110        let server = Server::new(epoch, app_state.clone());
111        server.start().await.unwrap();
112        // Advance clock to ensure the server's cleanup task is finished.
113        deterministic.advance_clock(CLEANUP_TIMEOUT);
114        Self {
115            app_state,
116            server,
117            connection_killers: Default::default(),
118            forbid_connections: Default::default(),
119            next_github_user_id: 0,
120            test_db,
121            test_livekit_server: livekit_server,
122        }
123    }
124
125    pub async fn start2(
126        cx_a: &mut TestAppContext,
127        cx_b: &mut TestAppContext,
128    ) -> (TestServer, TestClient, TestClient, ChannelId) {
129        let mut server = Self::start(cx_a.executor()).await;
130        let client_a = server.create_client(cx_a, "user_a").await;
131        let client_b = server.create_client(cx_b, "user_b").await;
132        let channel_id = server
133            .make_channel(
134                "test-channel",
135                None,
136                (&client_a, cx_a),
137                &mut [(&client_b, cx_b)],
138            )
139            .await;
140        cx_a.run_until_parked();
141
142        (server, client_a, client_b, channel_id)
143    }
144
145    pub async fn start1(cx: &mut TestAppContext) -> (TestServer, TestClient) {
146        let mut server = Self::start(cx.executor().clone()).await;
147        let client = server.create_client(cx, "user_a").await;
148        (server, client)
149    }
150
151    pub async fn reset(&self) {
152        self.app_state.db.reset();
153        let epoch = self
154            .app_state
155            .db
156            .create_server(&self.app_state.config.zed_environment)
157            .await
158            .unwrap();
159        self.server.reset(epoch);
160    }
161
162    pub async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
163        const ACCESS_TOKEN: &str = "the-token";
164
165        let fs = FakeFs::new(cx.executor());
166
167        cx.update(|cx| {
168            gpui_tokio::init(cx);
169            if cx.has_global::<SettingsStore>() {
170                panic!("Same cx used to create two test clients")
171            }
172            let settings = SettingsStore::test(cx);
173            cx.set_global(settings);
174            theme::init(theme::LoadThemes::JustBase, cx);
175            release_channel::init(semver::Version::new(0, 0, 0), cx);
176        });
177
178        let clock = Arc::new(FakeSystemClock::new());
179
180        let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
181        {
182            user.id
183        } else {
184            let github_user_id = self.next_github_user_id;
185            self.next_github_user_id += 1;
186            self.app_state
187                .db
188                .create_user(
189                    &format!("{name}@example.com"),
190                    None,
191                    false,
192                    NewUserParams {
193                        github_login: name.into(),
194                        github_user_id,
195                    },
196                )
197                .await
198                .expect("creating user failed")
199                .user_id
200        };
201
202        let http = FakeHttpClient::create({
203            let name = name.to_string();
204            move |req| {
205                let name = name.clone();
206                async move {
207                    match (req.method(), req.uri().path()) {
208                        (&Method::GET, "/client/users/me") => {
209                            let credentials = parse_authorization_header(&req);
210                            if credentials
211                                != Some(Credentials {
212                                    user_id: user_id.to_proto(),
213                                    access_token: ACCESS_TOKEN.into(),
214                                })
215                            {
216                                return Ok(http_client::Response::builder()
217                                    .status(401)
218                                    .body("Unauthorized".into())
219                                    .unwrap());
220                            }
221
222                            Ok(http_client::Response::builder()
223                                .status(200)
224                                .body(
225                                    serde_json::to_string(&make_get_authenticated_user_response(
226                                        user_id.0, name,
227                                    ))
228                                    .unwrap()
229                                    .into(),
230                                )
231                                .unwrap())
232                        }
233                        _ => Ok(http_client::Response::builder()
234                            .status(404)
235                            .body("Not Found".into())
236                            .unwrap()),
237                    }
238                }
239            }
240        });
241
242        let client_name = name.to_string();
243        let mut client = cx.update(|cx| Client::new(clock, http.clone(), cx));
244        let server = self.server.clone();
245        let db = self.app_state.db.clone();
246        let connection_killers = self.connection_killers.clone();
247        let forbid_connections = self.forbid_connections.clone();
248
249        Arc::get_mut(&mut client)
250            .unwrap()
251            .set_id(user_id.to_proto())
252            .override_authenticate(move |cx| {
253                cx.spawn(async move |_| {
254                    Ok(Credentials {
255                        user_id: user_id.to_proto(),
256                        access_token: ACCESS_TOKEN.into(),
257                    })
258                })
259            })
260            .override_establish_connection(move |credentials, cx| {
261                assert_eq!(
262                    credentials,
263                    &Credentials {
264                        user_id: user_id.0 as u64,
265                        access_token: ACCESS_TOKEN.into(),
266                    }
267                );
268
269                let server = server.clone();
270                let db = db.clone();
271                let connection_killers = connection_killers.clone();
272                let forbid_connections = forbid_connections.clone();
273                let client_name = client_name.clone();
274                cx.spawn(async move |cx| {
275                    if forbid_connections.load(SeqCst) {
276                        Err(EstablishConnectionError::other(anyhow!(
277                            "server is forbidding connections"
278                        )))
279                    } else {
280                        let (client_conn, server_conn, killed) =
281                            Connection::in_memory(cx.background_executor().clone());
282                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
283                        let user = db
284                            .get_user_by_id(user_id)
285                            .await
286                            .map_err(|e| {
287                                EstablishConnectionError::Other(anyhow!(
288                                    "retrieving user failed: {}",
289                                    e
290                                ))
291                            })?
292                            .unwrap();
293                        cx.background_spawn(server.handle_connection(
294                            server_conn,
295                            client_name,
296                            Principal::User(user),
297                            ZedVersion(semver::Version::new(1, 0, 0)),
298                            Some("test".to_string()),
299                            None,
300                            None,
301                            None,
302                            Some(connection_id_tx),
303                            Executor::Deterministic(cx.background_executor().clone()),
304                            None,
305                        ))
306                        .detach();
307                        let connection_id = connection_id_rx.await.map_err(|e| {
308                            EstablishConnectionError::Other(anyhow!(
309                                "{} (is server shutting down?)",
310                                e
311                            ))
312                        })?;
313                        connection_killers
314                            .lock()
315                            .insert(connection_id.into(), killed);
316                        Ok(client_conn)
317                    }
318                })
319            });
320
321        let git_hosting_provider_registry = cx.update(GitHostingProviderRegistry::default_global);
322        git_hosting_provider_registry
323            .register_hosting_provider(Arc::new(git_hosting_providers::Github::public_instance()));
324
325        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
326        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
327        let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
328        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
329        let app_state = Arc::new(workspace::AppState {
330            client: client.clone(),
331            user_store: user_store.clone(),
332            workspace_store,
333            languages: language_registry,
334            fs: fs.clone(),
335            build_window_options: |_, _| Default::default(),
336            node_runtime: NodeRuntime::unavailable(),
337            session,
338        });
339
340        let os_keymap = "keymaps/default-macos.json";
341
342        cx.update(|cx| {
343            theme::init(theme::LoadThemes::JustBase, cx);
344            Project::init(&client, cx);
345            client::init(&client, cx);
346            editor::init(cx);
347            workspace::init(app_state.clone(), cx);
348            call::init(client.clone(), user_store.clone(), cx);
349            channel::init(&client, user_store.clone(), cx);
350            notifications::init(client.clone(), user_store, cx);
351            collab_ui::init(&app_state, cx);
352            file_finder::init(cx);
353            menu::init();
354            cx.bind_keys(
355                settings::KeymapFile::load_asset_allow_partial_failure(os_keymap, cx).unwrap(),
356            );
357            language_model::LanguageModelRegistry::test(cx);
358            assistant_text_thread::init(client.clone(), cx);
359        });
360
361        client
362            .connect(false, &cx.to_async())
363            .await
364            .into_response()
365            .unwrap();
366
367        let client = TestClient {
368            app_state,
369            username: name.to_string(),
370            channel_store: cx.read(ChannelStore::global),
371            notification_store: cx.read(NotificationStore::global),
372            state: Default::default(),
373        };
374        client.wait_for_current_user(cx).await;
375        client
376    }
377
378    pub fn disconnect_client(&self, peer_id: PeerId) {
379        self.connection_killers
380            .lock()
381            .remove(&peer_id)
382            .unwrap()
383            .store(true, SeqCst);
384    }
385
386    pub fn simulate_long_connection_interruption(
387        &self,
388        peer_id: PeerId,
389        deterministic: BackgroundExecutor,
390    ) {
391        self.forbid_connections();
392        self.disconnect_client(peer_id);
393        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
394        self.allow_connections();
395        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
396        deterministic.run_until_parked();
397    }
398
399    pub fn forbid_connections(&self) {
400        self.forbid_connections.store(true, SeqCst);
401    }
402
403    pub fn allow_connections(&self) {
404        self.forbid_connections.store(false, SeqCst);
405    }
406
407    pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
408        for ix in 1..clients.len() {
409            let (left, right) = clients.split_at_mut(ix);
410            let (client_a, cx_a) = left.last_mut().unwrap();
411            for (client_b, cx_b) in right {
412                client_a
413                    .app_state
414                    .user_store
415                    .update(*cx_a, |store, cx| {
416                        store.request_contact(client_b.user_id().unwrap(), cx)
417                    })
418                    .await
419                    .unwrap();
420                cx_a.executor().run_until_parked();
421                client_b
422                    .app_state
423                    .user_store
424                    .update(*cx_b, |store, cx| {
425                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
426                    })
427                    .await
428                    .unwrap();
429            }
430        }
431    }
432
433    pub async fn make_channel(
434        &self,
435        channel: &str,
436        parent: Option<ChannelId>,
437        admin: (&TestClient, &mut TestAppContext),
438        members: &mut [(&TestClient, &mut TestAppContext)],
439    ) -> ChannelId {
440        let (_, admin_cx) = admin;
441        let channel_id = admin_cx
442            .read(ChannelStore::global)
443            .update(admin_cx, |channel_store, cx| {
444                channel_store.create_channel(channel, parent, cx)
445            })
446            .await
447            .unwrap();
448
449        for (member_client, member_cx) in members {
450            admin_cx
451                .read(ChannelStore::global)
452                .update(admin_cx, |channel_store, cx| {
453                    channel_store.invite_member(
454                        channel_id,
455                        member_client.user_id().unwrap(),
456                        ChannelRole::Member,
457                        cx,
458                    )
459                })
460                .await
461                .unwrap();
462
463            admin_cx.executor().run_until_parked();
464
465            member_cx
466                .read(ChannelStore::global)
467                .update(*member_cx, |channels, cx| {
468                    channels.respond_to_channel_invite(channel_id, true, cx)
469                })
470                .await
471                .unwrap();
472        }
473
474        channel_id
475    }
476
477    pub async fn make_public_channel(
478        &self,
479        channel: &str,
480        client: &TestClient,
481        cx: &mut TestAppContext,
482    ) -> ChannelId {
483        let channel_id = self
484            .make_channel(channel, None, (client, cx), &mut [])
485            .await;
486
487        client
488            .channel_store()
489            .update(cx, |channel_store, cx| {
490                channel_store.set_channel_visibility(
491                    channel_id,
492                    proto::ChannelVisibility::Public,
493                    cx,
494                )
495            })
496            .await
497            .unwrap();
498
499        channel_id
500    }
501
502    pub async fn make_channel_tree(
503        &self,
504        channels: &[(&str, Option<&str>)],
505        creator: (&TestClient, &mut TestAppContext),
506    ) -> Vec<ChannelId> {
507        let mut observed_channels = HashMap::default();
508        let mut result = Vec::new();
509        for (channel, parent) in channels {
510            let id;
511            if let Some(parent) = parent {
512                if let Some(parent_id) = observed_channels.get(parent) {
513                    id = self
514                        .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
515                        .await;
516                } else {
517                    panic!(
518                        "Edge {}->{} referenced before {} was created",
519                        parent, channel, parent
520                    )
521                }
522            } else {
523                id = self
524                    .make_channel(channel, None, (creator.0, creator.1), &mut [])
525                    .await;
526            }
527
528            observed_channels.insert(channel, id);
529            result.push(id);
530        }
531
532        result
533    }
534
535    pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
536        self.make_contacts(clients).await;
537
538        let (left, right) = clients.split_at_mut(1);
539        let (_client_a, cx_a) = &mut left[0];
540        let active_call_a = cx_a.read(ActiveCall::global);
541
542        for (client_b, cx_b) in right {
543            let user_id_b = client_b.current_user_id(cx_b).to_proto();
544            active_call_a
545                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
546                .await
547                .unwrap();
548
549            cx_b.executor().run_until_parked();
550            let active_call_b = cx_b.read(ActiveCall::global);
551            active_call_b
552                .update(*cx_b, |call, cx| call.accept_incoming(cx))
553                .await
554                .unwrap();
555        }
556    }
557
558    pub async fn build_app_state(
559        test_db: &TestDb,
560        livekit_test_server: &LivekitTestServer,
561        executor: Executor,
562    ) -> Arc<AppState> {
563        Arc::new(AppState {
564            db: test_db.db().clone(),
565            livekit_client: Some(Arc::new(livekit_test_server.create_api_client())),
566            blob_store_client: None,
567            executor,
568            kinesis_client: None,
569            config: Config {
570                http_port: 0,
571                database_url: "".into(),
572                database_max_connections: 0,
573                api_token: "".into(),
574                invite_link_prefix: "".into(),
575                livekit_server: None,
576                livekit_key: None,
577                livekit_secret: None,
578                llm_database_url: None,
579                llm_database_max_connections: None,
580                llm_database_migrations_path: None,
581                llm_api_secret: None,
582                rust_log: None,
583                log_json: None,
584                zed_environment: "test".into(),
585                blob_store_url: None,
586                blob_store_region: None,
587                blob_store_access_key: None,
588                blob_store_secret_key: None,
589                blob_store_bucket: None,
590                openai_api_key: None,
591                google_ai_api_key: None,
592                anthropic_api_key: None,
593                anthropic_staff_api_key: None,
594                llm_closed_beta_model_name: None,
595                prediction_api_url: None,
596                prediction_api_key: None,
597                prediction_model: None,
598                zed_client_checksum_seed: None,
599                auto_join_channel_id: None,
600                migrations_path: None,
601                seed_path: None,
602                supermaven_admin_api_key: None,
603                kinesis_region: None,
604                kinesis_stream: None,
605                kinesis_access_key: None,
606                kinesis_secret_key: None,
607            },
608        })
609    }
610}
611
612impl Deref for TestServer {
613    type Target = Server;
614
615    fn deref(&self) -> &Self::Target {
616        &self.server
617    }
618}
619
620impl Drop for TestServer {
621    fn drop(&mut self) {
622        self.server.teardown();
623        self.test_livekit_server.teardown().unwrap();
624    }
625}
626
627impl Deref for TestClient {
628    type Target = Arc<Client>;
629
630    fn deref(&self) -> &Self::Target {
631        &self.app_state.client
632    }
633}
634
635impl TestClient {
636    pub fn fs(&self) -> Arc<FakeFs> {
637        self.app_state.fs.as_fake()
638    }
639
640    pub fn channel_store(&self) -> &Entity<ChannelStore> {
641        &self.channel_store
642    }
643
644    pub fn notification_store(&self) -> &Entity<NotificationStore> {
645        &self.notification_store
646    }
647
648    pub fn user_store(&self) -> &Entity<UserStore> {
649        &self.app_state.user_store
650    }
651
652    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
653        &self.app_state.languages
654    }
655
656    pub fn client(&self) -> &Arc<Client> {
657        &self.app_state.client
658    }
659
660    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
661        UserId::from_proto(
662            self.app_state
663                .user_store
664                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
665        )
666    }
667
668    pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
669        let mut authed_user = self
670            .app_state
671            .user_store
672            .read_with(cx, |user_store, _| user_store.watch_current_user());
673        while authed_user.next().await.unwrap().is_none() {}
674    }
675
676    pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
677        self.app_state
678            .user_store
679            .update(cx, |store, _| store.clear_contacts())
680            .await;
681    }
682
683    pub fn local_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
684        Ref::map(self.state.borrow(), |state| &state.local_projects)
685    }
686
687    pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
688        Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
689    }
690
691    pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
692        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
693    }
694
695    pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
696        RefMut::map(self.state.borrow_mut(), |state| {
697            &mut state.dev_server_projects
698        })
699    }
700
701    pub fn buffers_for_project<'a>(
702        &'a self,
703        project: &Entity<Project>,
704    ) -> impl DerefMut<Target = HashSet<Entity<language::Buffer>>> + 'a {
705        RefMut::map(self.state.borrow_mut(), |state| {
706            state.buffers.entry(project.clone()).or_default()
707        })
708    }
709
710    pub fn buffers(
711        &self,
712    ) -> impl DerefMut<Target = HashMap<Entity<Project>, HashSet<Entity<language::Buffer>>>> + '_
713    {
714        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
715    }
716
717    pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Entity<ChannelBuffer>>> + '_ {
718        RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
719    }
720
721    pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
722        self.app_state
723            .user_store
724            .read_with(cx, |store, _| ContactsSummary {
725                current: store
726                    .contacts()
727                    .iter()
728                    .map(|contact| contact.user.github_login.clone().to_string())
729                    .collect(),
730                outgoing_requests: store
731                    .outgoing_contact_requests()
732                    .iter()
733                    .map(|user| user.github_login.clone().to_string())
734                    .collect(),
735                incoming_requests: store
736                    .incoming_contact_requests()
737                    .iter()
738                    .map(|user| user.github_login.clone().to_string())
739                    .collect(),
740            })
741    }
742
743    pub async fn build_local_project(
744        &self,
745        root_path: impl AsRef<Path>,
746        cx: &mut TestAppContext,
747    ) -> (Entity<Project>, WorktreeId) {
748        let project = self.build_empty_local_project(cx);
749        let (worktree, _) = project
750            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
751            .await
752            .unwrap();
753        worktree
754            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
755            .await;
756        cx.run_until_parked();
757        (project, worktree.read_with(cx, |tree, _| tree.id()))
758    }
759
760    pub async fn build_ssh_project(
761        &self,
762        root_path: impl AsRef<Path>,
763        ssh: Entity<RemoteClient>,
764        cx: &mut TestAppContext,
765    ) -> (Entity<Project>, WorktreeId) {
766        let project = cx.update(|cx| {
767            Project::remote(
768                ssh,
769                self.client().clone(),
770                self.app_state.node_runtime.clone(),
771                self.app_state.user_store.clone(),
772                self.app_state.languages.clone(),
773                self.app_state.fs.clone(),
774                cx,
775            )
776        });
777        let (worktree, _) = project
778            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
779            .await
780            .unwrap();
781        (project, worktree.read_with(cx, |tree, _| tree.id()))
782    }
783
784    pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Entity<Project> {
785        self.fs()
786            .insert_tree(
787                path!("/a"),
788                json!({
789                    "1.txt": "one\none\none",
790                    "2.js": "function two() { return 2; }",
791                    "3.rs": "mod test",
792                }),
793            )
794            .await;
795        self.build_local_project(path!("/a"), cx).await.0
796    }
797
798    pub async fn host_workspace(
799        &self,
800        workspace: &Entity<Workspace>,
801        channel_id: ChannelId,
802        cx: &mut VisualTestContext,
803    ) {
804        cx.update(|_, cx| {
805            let active_call = ActiveCall::global(cx);
806            active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
807        })
808        .await
809        .unwrap();
810        cx.update(|_, cx| {
811            let active_call = ActiveCall::global(cx);
812            let project = workspace.read(cx).project().clone();
813            active_call.update(cx, |call, cx| call.share_project(project, cx))
814        })
815        .await
816        .unwrap();
817        cx.executor().run_until_parked();
818    }
819
820    pub async fn join_workspace<'a>(
821        &'a self,
822        channel_id: ChannelId,
823        cx: &'a mut TestAppContext,
824    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
825        cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
826            .await
827            .unwrap();
828        cx.run_until_parked();
829
830        self.active_workspace(cx)
831    }
832
833    pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Entity<Project> {
834        cx.update(|cx| {
835            Project::local(
836                self.client().clone(),
837                self.app_state.node_runtime.clone(),
838                self.app_state.user_store.clone(),
839                self.app_state.languages.clone(),
840                self.app_state.fs.clone(),
841                None,
842                cx,
843            )
844        })
845    }
846
847    pub async fn join_remote_project(
848        &self,
849        host_project_id: u64,
850        guest_cx: &mut TestAppContext,
851    ) -> Entity<Project> {
852        let active_call = guest_cx.read(ActiveCall::global);
853        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
854        room.update(guest_cx, |room, cx| {
855            room.join_project(
856                host_project_id,
857                self.app_state.languages.clone(),
858                self.app_state.fs.clone(),
859                cx,
860            )
861        })
862        .await
863        .unwrap()
864    }
865
866    pub fn build_workspace<'a>(
867        &'a self,
868        project: &Entity<Project>,
869        cx: &'a mut TestAppContext,
870    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
871        cx.add_window_view(|window, cx| {
872            window.activate_window();
873            Workspace::new(None, project.clone(), self.app_state.clone(), window, cx)
874        })
875    }
876
877    pub async fn build_test_workspace<'a>(
878        &'a self,
879        cx: &'a mut TestAppContext,
880    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
881        let project = self.build_test_project(cx).await;
882        cx.add_window_view(|window, cx| {
883            window.activate_window();
884            Workspace::new(None, project.clone(), self.app_state.clone(), window, cx)
885        })
886    }
887
888    pub fn active_workspace<'a>(
889        &'a self,
890        cx: &'a mut TestAppContext,
891    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
892        let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
893
894        let entity = window.root(cx).unwrap();
895        let cx = VisualTestContext::from_window(*window.deref(), cx).into_mut();
896        // it might be nice to try and cleanup these at the end of each test.
897        (entity, cx)
898    }
899}
900
901pub fn open_channel_notes(
902    channel_id: ChannelId,
903    cx: &mut VisualTestContext,
904) -> Task<anyhow::Result<Entity<ChannelView>>> {
905    let window = cx.update(|_, cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
906    let entity = window.root(cx).unwrap();
907
908    cx.update(|window, cx| ChannelView::open(channel_id, None, entity.clone(), window, cx))
909}
910
911impl Drop for TestClient {
912    fn drop(&mut self) {
913        self.app_state.client.teardown();
914    }
915}