test_server.rs

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