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