test_server.rs

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