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