test_server.rs

  1use crate::stripe_client::FakeStripeClient;
  2use crate::{
  3    AppState, Config,
  4    db::{NewUserParams, UserId, tests::TestDb},
  5    executor::Executor,
  6    rpc::{CLEANUP_TIMEOUT, Principal, RECONNECT_TIMEOUT, Server, ZedVersion},
  7};
  8use anyhow::anyhow;
  9use call::ActiveCall;
 10use channel::{ChannelBuffer, ChannelStore};
 11use client::test::{make_get_authenticated_user_response, parse_authorization_header};
 12use client::{
 13    self, ChannelId, Client, Connection, Credentials, EstablishConnectionError, UserStore,
 14    proto::PeerId,
 15};
 16use clock::FakeSystemClock;
 17use collab_ui::channel_view::ChannelView;
 18use collections::{HashMap, HashSet};
 19
 20use fs::FakeFs;
 21use futures::{StreamExt as _, channel::oneshot};
 22use git::GitHostingProviderRegistry;
 23use gpui::{AppContext as _, BackgroundExecutor, Entity, Task, TestAppContext, VisualTestContext};
 24use http_client::{FakeHttpClient, Method};
 25use language::LanguageRegistry;
 26use node_runtime::NodeRuntime;
 27use notifications::NotificationStore;
 28use parking_lot::Mutex;
 29use project::{Project, WorktreeId};
 30use remote::SshRemoteClient;
 31use rpc::{
 32    RECEIVE_TIMEOUT,
 33    proto::{self, ChannelRole},
 34};
 35use semantic_version::SemanticVersion;
 36use serde_json::json;
 37use session::{AppSession, Session};
 38use settings::SettingsStore;
 39use std::{
 40    cell::{Ref, RefCell, RefMut},
 41    env,
 42    ops::{Deref, DerefMut},
 43    path::Path,
 44    sync::{
 45        Arc,
 46        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 47    },
 48};
 49use util::path;
 50use workspace::{Workspace, WorkspaceStore};
 51
 52use livekit_client::test::TestServer as LivekitTestServer;
 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            release_channel::init(SemanticVersion::default(), cx);
177            client::init_settings(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 mut 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        Arc::get_mut(&mut client)
252            .unwrap()
253            .set_id(user_id.to_proto())
254            .override_authenticate(move |cx| {
255                cx.spawn(async move |_| {
256                    Ok(Credentials {
257                        user_id: user_id.to_proto(),
258                        access_token: ACCESS_TOKEN.into(),
259                    })
260                })
261            })
262            .override_establish_connection(move |credentials, cx| {
263                assert_eq!(
264                    credentials,
265                    &Credentials {
266                        user_id: user_id.0 as u64,
267                        access_token: ACCESS_TOKEN.into(),
268                    }
269                );
270
271                let server = server.clone();
272                let db = db.clone();
273                let connection_killers = connection_killers.clone();
274                let forbid_connections = forbid_connections.clone();
275                let client_name = client_name.clone();
276                cx.spawn(async move |cx| {
277                    if forbid_connections.load(SeqCst) {
278                        Err(EstablishConnectionError::other(anyhow!(
279                            "server is forbidding connections"
280                        )))
281                    } else {
282                        let (client_conn, server_conn, killed) =
283                            Connection::in_memory(cx.background_executor().clone());
284                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
285                        let user = db
286                            .get_user_by_id(user_id)
287                            .await
288                            .map_err(|e| {
289                                EstablishConnectionError::Other(anyhow!(
290                                    "retrieving user failed: {}",
291                                    e
292                                ))
293                            })?
294                            .unwrap();
295                        cx.background_spawn(server.handle_connection(
296                            server_conn,
297                            client_name,
298                            Principal::User(user),
299                            ZedVersion(SemanticVersion::new(1, 0, 0)),
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            language::init(cx);
348            editor::init(cx);
349            workspace::init(app_state.clone(), cx);
350            call::init(client.clone(), user_store.clone(), cx);
351            channel::init(&client, user_store.clone(), cx);
352            notifications::init(client.clone(), user_store, cx);
353            collab_ui::init(&app_state, cx);
354            file_finder::init(cx);
355            menu::init();
356            cx.bind_keys(
357                settings::KeymapFile::load_asset_allow_partial_failure(os_keymap, cx).unwrap(),
358            );
359            language_model::LanguageModelRegistry::test(cx);
360            assistant_context::init(client.clone(), cx);
361            agent_settings::init(cx);
362        });
363
364        client
365            .connect(false, &cx.to_async())
366            .await
367            .into_response()
368            .unwrap();
369
370        let client = TestClient {
371            app_state,
372            username: name.to_string(),
373            channel_store: cx.read(ChannelStore::global).clone(),
374            notification_store: cx.read(NotificationStore::global).clone(),
375            state: Default::default(),
376        };
377        client.wait_for_current_user(cx).await;
378        client
379    }
380
381    pub fn disconnect_client(&self, peer_id: PeerId) {
382        self.connection_killers
383            .lock()
384            .remove(&peer_id)
385            .unwrap()
386            .store(true, SeqCst);
387    }
388
389    pub fn simulate_long_connection_interruption(
390        &self,
391        peer_id: PeerId,
392        deterministic: BackgroundExecutor,
393    ) {
394        self.forbid_connections();
395        self.disconnect_client(peer_id);
396        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
397        self.allow_connections();
398        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
399        deterministic.run_until_parked();
400    }
401
402    pub fn forbid_connections(&self) {
403        self.forbid_connections.store(true, SeqCst);
404    }
405
406    pub fn allow_connections(&self) {
407        self.forbid_connections.store(false, SeqCst);
408    }
409
410    pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
411        for ix in 1..clients.len() {
412            let (left, right) = clients.split_at_mut(ix);
413            let (client_a, cx_a) = left.last_mut().unwrap();
414            for (client_b, cx_b) in right {
415                client_a
416                    .app_state
417                    .user_store
418                    .update(*cx_a, |store, cx| {
419                        store.request_contact(client_b.user_id().unwrap(), cx)
420                    })
421                    .await
422                    .unwrap();
423                cx_a.executor().run_until_parked();
424                client_b
425                    .app_state
426                    .user_store
427                    .update(*cx_b, |store, cx| {
428                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
429                    })
430                    .await
431                    .unwrap();
432            }
433        }
434    }
435
436    pub async fn make_channel(
437        &self,
438        channel: &str,
439        parent: Option<ChannelId>,
440        admin: (&TestClient, &mut TestAppContext),
441        members: &mut [(&TestClient, &mut TestAppContext)],
442    ) -> ChannelId {
443        let (_, admin_cx) = admin;
444        let channel_id = admin_cx
445            .read(ChannelStore::global)
446            .update(admin_cx, |channel_store, cx| {
447                channel_store.create_channel(channel, parent, cx)
448            })
449            .await
450            .unwrap();
451
452        for (member_client, member_cx) in members {
453            admin_cx
454                .read(ChannelStore::global)
455                .update(admin_cx, |channel_store, cx| {
456                    channel_store.invite_member(
457                        channel_id,
458                        member_client.user_id().unwrap(),
459                        ChannelRole::Member,
460                        cx,
461                    )
462                })
463                .await
464                .unwrap();
465
466            admin_cx.executor().run_until_parked();
467
468            member_cx
469                .read(ChannelStore::global)
470                .update(*member_cx, |channels, cx| {
471                    channels.respond_to_channel_invite(channel_id, true, cx)
472                })
473                .await
474                .unwrap();
475        }
476
477        channel_id
478    }
479
480    pub async fn make_public_channel(
481        &self,
482        channel: &str,
483        client: &TestClient,
484        cx: &mut TestAppContext,
485    ) -> ChannelId {
486        let channel_id = self
487            .make_channel(channel, None, (client, cx), &mut [])
488            .await;
489
490        client
491            .channel_store()
492            .update(cx, |channel_store, cx| {
493                channel_store.set_channel_visibility(
494                    channel_id,
495                    proto::ChannelVisibility::Public,
496                    cx,
497                )
498            })
499            .await
500            .unwrap();
501
502        channel_id
503    }
504
505    pub async fn make_channel_tree(
506        &self,
507        channels: &[(&str, Option<&str>)],
508        creator: (&TestClient, &mut TestAppContext),
509    ) -> Vec<ChannelId> {
510        let mut observed_channels = HashMap::default();
511        let mut result = Vec::new();
512        for (channel, parent) in channels {
513            let id;
514            if let Some(parent) = parent {
515                if let Some(parent_id) = observed_channels.get(parent) {
516                    id = self
517                        .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
518                        .await;
519                } else {
520                    panic!(
521                        "Edge {}->{} referenced before {} was created",
522                        parent, channel, parent
523                    )
524                }
525            } else {
526                id = self
527                    .make_channel(channel, None, (creator.0, creator.1), &mut [])
528                    .await;
529            }
530
531            observed_channels.insert(channel, id);
532            result.push(id);
533        }
534
535        result
536    }
537
538    pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
539        self.make_contacts(clients).await;
540
541        let (left, right) = clients.split_at_mut(1);
542        let (_client_a, cx_a) = &mut left[0];
543        let active_call_a = cx_a.read(ActiveCall::global);
544
545        for (client_b, cx_b) in right {
546            let user_id_b = client_b.current_user_id(cx_b).to_proto();
547            active_call_a
548                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
549                .await
550                .unwrap();
551
552            cx_b.executor().run_until_parked();
553            let active_call_b = cx_b.read(ActiveCall::global);
554            active_call_b
555                .update(*cx_b, |call, cx| call.accept_incoming(cx))
556                .await
557                .unwrap();
558        }
559    }
560
561    pub async fn build_app_state(
562        test_db: &TestDb,
563        livekit_test_server: &LivekitTestServer,
564        executor: Executor,
565    ) -> Arc<AppState> {
566        Arc::new(AppState {
567            db: test_db.db().clone(),
568            llm_db: None,
569            livekit_client: Some(Arc::new(livekit_test_server.create_api_client())),
570            blob_store_client: None,
571            real_stripe_client: None,
572            stripe_client: Some(Arc::new(FakeStripeClient::new())),
573            stripe_billing: None,
574            executor,
575            kinesis_client: None,
576            config: Config {
577                http_port: 0,
578                database_url: "".into(),
579                database_max_connections: 0,
580                api_token: "".into(),
581                invite_link_prefix: "".into(),
582                livekit_server: None,
583                livekit_key: None,
584                livekit_secret: None,
585                llm_database_url: None,
586                llm_database_max_connections: None,
587                llm_database_migrations_path: None,
588                llm_api_secret: None,
589                rust_log: None,
590                log_json: None,
591                zed_environment: "test".into(),
592                blob_store_url: None,
593                blob_store_region: None,
594                blob_store_access_key: None,
595                blob_store_secret_key: None,
596                blob_store_bucket: None,
597                openai_api_key: None,
598                google_ai_api_key: None,
599                anthropic_api_key: None,
600                anthropic_staff_api_key: None,
601                llm_closed_beta_model_name: None,
602                prediction_api_url: None,
603                prediction_api_key: None,
604                prediction_model: None,
605                zed_client_checksum_seed: None,
606                slack_panics_webhook: None,
607                auto_join_channel_id: None,
608                migrations_path: None,
609                seed_path: None,
610                stripe_api_key: None,
611                supermaven_admin_api_key: None,
612                user_backfiller_github_access_token: None,
613                kinesis_region: None,
614                kinesis_stream: None,
615                kinesis_access_key: None,
616                kinesis_secret_key: None,
617            },
618        })
619    }
620}
621
622impl Deref for TestServer {
623    type Target = Server;
624
625    fn deref(&self) -> &Self::Target {
626        &self.server
627    }
628}
629
630impl Drop for TestServer {
631    fn drop(&mut self) {
632        self.server.teardown();
633        self.test_livekit_server.teardown().unwrap();
634    }
635}
636
637impl Deref for TestClient {
638    type Target = Arc<Client>;
639
640    fn deref(&self) -> &Self::Target {
641        &self.app_state.client
642    }
643}
644
645impl TestClient {
646    pub fn fs(&self) -> Arc<FakeFs> {
647        self.app_state.fs.as_fake()
648    }
649
650    pub fn channel_store(&self) -> &Entity<ChannelStore> {
651        &self.channel_store
652    }
653
654    pub fn notification_store(&self) -> &Entity<NotificationStore> {
655        &self.notification_store
656    }
657
658    pub fn user_store(&self) -> &Entity<UserStore> {
659        &self.app_state.user_store
660    }
661
662    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
663        &self.app_state.languages
664    }
665
666    pub fn client(&self) -> &Arc<Client> {
667        &self.app_state.client
668    }
669
670    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
671        UserId::from_proto(
672            self.app_state
673                .user_store
674                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
675        )
676    }
677
678    pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
679        let mut authed_user = self
680            .app_state
681            .user_store
682            .read_with(cx, |user_store, _| user_store.watch_current_user());
683        while authed_user.next().await.unwrap().is_none() {}
684    }
685
686    pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
687        self.app_state
688            .user_store
689            .update(cx, |store, _| store.clear_contacts())
690            .await;
691    }
692
693    pub fn local_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
694        Ref::map(self.state.borrow(), |state| &state.local_projects)
695    }
696
697    pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
698        Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
699    }
700
701    pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
702        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
703    }
704
705    pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
706        RefMut::map(self.state.borrow_mut(), |state| {
707            &mut state.dev_server_projects
708        })
709    }
710
711    pub fn buffers_for_project<'a>(
712        &'a self,
713        project: &Entity<Project>,
714    ) -> impl DerefMut<Target = HashSet<Entity<language::Buffer>>> + 'a {
715        RefMut::map(self.state.borrow_mut(), |state| {
716            state.buffers.entry(project.clone()).or_default()
717        })
718    }
719
720    pub fn buffers(
721        &self,
722    ) -> impl DerefMut<Target = HashMap<Entity<Project>, HashSet<Entity<language::Buffer>>>> + '_
723    {
724        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
725    }
726
727    pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Entity<ChannelBuffer>>> + '_ {
728        RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
729    }
730
731    pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
732        self.app_state
733            .user_store
734            .read_with(cx, |store, _| ContactsSummary {
735                current: store
736                    .contacts()
737                    .iter()
738                    .map(|contact| contact.user.github_login.clone().to_string())
739                    .collect(),
740                outgoing_requests: store
741                    .outgoing_contact_requests()
742                    .iter()
743                    .map(|user| user.github_login.clone().to_string())
744                    .collect(),
745                incoming_requests: store
746                    .incoming_contact_requests()
747                    .iter()
748                    .map(|user| user.github_login.clone().to_string())
749                    .collect(),
750            })
751    }
752
753    pub async fn build_local_project(
754        &self,
755        root_path: impl AsRef<Path>,
756        cx: &mut TestAppContext,
757    ) -> (Entity<Project>, WorktreeId) {
758        let project = self.build_empty_local_project(cx);
759        let (worktree, _) = project
760            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
761            .await
762            .unwrap();
763        worktree
764            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
765            .await;
766        cx.run_until_parked();
767        (project, worktree.read_with(cx, |tree, _| tree.id()))
768    }
769
770    pub async fn build_ssh_project(
771        &self,
772        root_path: impl AsRef<Path>,
773        ssh: Entity<SshRemoteClient>,
774        cx: &mut TestAppContext,
775    ) -> (Entity<Project>, WorktreeId) {
776        let project = cx.update(|cx| {
777            Project::ssh(
778                ssh,
779                self.client().clone(),
780                self.app_state.node_runtime.clone(),
781                self.app_state.user_store.clone(),
782                self.app_state.languages.clone(),
783                self.app_state.fs.clone(),
784                cx,
785            )
786        });
787        let (worktree, _) = project
788            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
789            .await
790            .unwrap();
791        (project, worktree.read_with(cx, |tree, _| tree.id()))
792    }
793
794    pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Entity<Project> {
795        self.fs()
796            .insert_tree(
797                path!("/a"),
798                json!({
799                    "1.txt": "one\none\none",
800                    "2.js": "function two() { return 2; }",
801                    "3.rs": "mod test",
802                }),
803            )
804            .await;
805        self.build_local_project(path!("/a"), cx).await.0
806    }
807
808    pub async fn host_workspace(
809        &self,
810        workspace: &Entity<Workspace>,
811        channel_id: ChannelId,
812        cx: &mut VisualTestContext,
813    ) {
814        cx.update(|_, cx| {
815            let active_call = ActiveCall::global(cx);
816            active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
817        })
818        .await
819        .unwrap();
820        cx.update(|_, cx| {
821            let active_call = ActiveCall::global(cx);
822            let project = workspace.read(cx).project().clone();
823            active_call.update(cx, |call, cx| call.share_project(project, cx))
824        })
825        .await
826        .unwrap();
827        cx.executor().run_until_parked();
828    }
829
830    pub async fn join_workspace<'a>(
831        &'a self,
832        channel_id: ChannelId,
833        cx: &'a mut TestAppContext,
834    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
835        cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
836            .await
837            .unwrap();
838        cx.run_until_parked();
839
840        self.active_workspace(cx)
841    }
842
843    pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Entity<Project> {
844        cx.update(|cx| {
845            Project::local(
846                self.client().clone(),
847                self.app_state.node_runtime.clone(),
848                self.app_state.user_store.clone(),
849                self.app_state.languages.clone(),
850                self.app_state.fs.clone(),
851                None,
852                cx,
853            )
854        })
855    }
856
857    pub async fn join_remote_project(
858        &self,
859        host_project_id: u64,
860        guest_cx: &mut TestAppContext,
861    ) -> Entity<Project> {
862        let active_call = guest_cx.read(ActiveCall::global);
863        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
864        room.update(guest_cx, |room, cx| {
865            room.join_project(
866                host_project_id,
867                self.app_state.languages.clone(),
868                self.app_state.fs.clone(),
869                cx,
870            )
871        })
872        .await
873        .unwrap()
874    }
875
876    pub fn build_workspace<'a>(
877        &'a self,
878        project: &Entity<Project>,
879        cx: &'a mut TestAppContext,
880    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
881        cx.add_window_view(|window, cx| {
882            window.activate_window();
883            Workspace::new(None, project.clone(), self.app_state.clone(), window, cx)
884        })
885    }
886
887    pub async fn build_test_workspace<'a>(
888        &'a self,
889        cx: &'a mut TestAppContext,
890    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
891        let project = self.build_test_project(cx).await;
892        cx.add_window_view(|window, cx| {
893            window.activate_window();
894            Workspace::new(None, project.clone(), self.app_state.clone(), window, cx)
895        })
896    }
897
898    pub fn active_workspace<'a>(
899        &'a self,
900        cx: &'a mut TestAppContext,
901    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
902        let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
903
904        let entity = window.root(cx).unwrap();
905        let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
906        // it might be nice to try and cleanup these at the end of each test.
907        (entity, cx)
908    }
909}
910
911pub fn open_channel_notes(
912    channel_id: ChannelId,
913    cx: &mut VisualTestContext,
914) -> Task<anyhow::Result<Entity<ChannelView>>> {
915    let window = cx.update(|_, cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
916    let entity = window.root(cx).unwrap();
917
918    cx.update(|window, cx| ChannelView::open(channel_id, None, entity.clone(), window, cx))
919}
920
921impl Drop for TestClient {
922    fn drop(&mut self) {
923        self.app_state.client.teardown();
924    }
925}