test_server.rs

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