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::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 app_state = Arc::new(workspace::AppState {
274            client: client.clone(),
275            user_store: user_store.clone(),
276            workspace_store,
277            languages: language_registry,
278            fs: fs.clone(),
279            build_window_options: |_, _| Default::default(),
280            node_runtime: FakeNodeRuntime::new(),
281            session: Session::test(),
282        });
283
284        let os_keymap = "keymaps/default-macos.json";
285
286        cx.update(|cx| {
287            theme::init(theme::LoadThemes::JustBase, cx);
288            Project::init(&client, cx);
289            client::init(&client, cx);
290            language::init(cx);
291            editor::init(cx);
292            workspace::init(app_state.clone(), cx);
293            call::init(client.clone(), user_store.clone(), cx);
294            channel::init(&client, user_store.clone(), cx);
295            notifications::init(client.clone(), user_store, cx);
296            collab_ui::init(&app_state, cx);
297            file_finder::init(cx);
298            menu::init();
299            dev_server_projects::init(client.clone(), cx);
300            settings::KeymapFile::load_asset(os_keymap, cx).unwrap();
301            language_model::LanguageModelRegistry::test(cx);
302            completion::init(cx);
303            assistant::context_store::init(&client);
304        });
305
306        client
307            .authenticate_and_connect(false, &cx.to_async())
308            .await
309            .unwrap();
310
311        let client = TestClient {
312            app_state,
313            username: name.to_string(),
314            channel_store: cx.read(ChannelStore::global).clone(),
315            notification_store: cx.read(NotificationStore::global).clone(),
316            state: Default::default(),
317        };
318        client.wait_for_current_user(cx).await;
319        client
320    }
321
322    pub async fn create_dev_server(
323        &self,
324        access_token: String,
325        cx: &mut TestAppContext,
326    ) -> TestClient {
327        cx.update(|cx| {
328            if cx.has_global::<SettingsStore>() {
329                panic!("Same cx used to create two test clients")
330            }
331            let settings = SettingsStore::test(cx);
332            cx.set_global(settings);
333            release_channel::init(SemanticVersion::default(), cx);
334            client::init_settings(cx);
335        });
336        let (dev_server_id, _) = split_dev_server_token(&access_token).unwrap();
337
338        let clock = Arc::new(FakeSystemClock::default());
339        let http = FakeHttpClient::with_404_response();
340        let mut client = cx.update(|cx| Client::new(clock, http.clone(), cx));
341        let server = self.server.clone();
342        let db = self.app_state.db.clone();
343        let connection_killers = self.connection_killers.clone();
344        let forbid_connections = self.forbid_connections.clone();
345        Arc::get_mut(&mut client)
346            .unwrap()
347            .set_id(1)
348            .set_dev_server_token(client::DevServerToken(access_token.clone()))
349            .override_establish_connection(move |credentials, cx| {
350                assert_eq!(
351                    credentials,
352                    &Credentials::DevServer {
353                        token: client::DevServerToken(access_token.to_string())
354                    }
355                );
356
357                let server = server.clone();
358                let db = db.clone();
359                let connection_killers = connection_killers.clone();
360                let forbid_connections = forbid_connections.clone();
361                cx.spawn(move |cx| async move {
362                    if forbid_connections.load(SeqCst) {
363                        Err(EstablishConnectionError::other(anyhow!(
364                            "server is forbidding connections"
365                        )))
366                    } else {
367                        let (client_conn, server_conn, killed) =
368                            Connection::in_memory(cx.background_executor().clone());
369                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
370                        let dev_server = db
371                            .get_dev_server(dev_server_id)
372                            .await
373                            .expect("retrieving dev_server failed");
374                        cx.background_executor()
375                            .spawn(server.handle_connection(
376                                server_conn,
377                                "dev-server".to_string(),
378                                Principal::DevServer(dev_server),
379                                ZedVersion(SemanticVersion::new(1, 0, 0)),
380                                Some(connection_id_tx),
381                                Executor::Deterministic(cx.background_executor().clone()),
382                            ))
383                            .detach();
384                        let connection_id = connection_id_rx.await.map_err(|e| {
385                            EstablishConnectionError::Other(anyhow!(
386                                "{} (is server shutting down?)",
387                                e
388                            ))
389                        })?;
390                        connection_killers
391                            .lock()
392                            .insert(connection_id.into(), killed);
393                        Ok(client_conn)
394                    }
395                })
396            });
397
398        let fs = FakeFs::new(cx.executor());
399        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
400        let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
401        let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
402        let app_state = Arc::new(workspace::AppState {
403            client: client.clone(),
404            user_store: user_store.clone(),
405            workspace_store,
406            languages: language_registry,
407            fs: fs.clone(),
408            build_window_options: |_, _| Default::default(),
409            node_runtime: FakeNodeRuntime::new(),
410            session: Session::test(),
411        });
412
413        cx.update(|cx| {
414            theme::init(theme::LoadThemes::JustBase, cx);
415            Project::init(&client, cx);
416            client::init(&client, cx);
417            language::init(cx);
418            editor::init(cx);
419            workspace::init(app_state.clone(), cx);
420            call::init(client.clone(), user_store.clone(), cx);
421            channel::init(&client, user_store.clone(), cx);
422            notifications::init(client.clone(), user_store, cx);
423            collab_ui::init(&app_state, cx);
424            file_finder::init(cx);
425            menu::init();
426            headless::init(
427                client.clone(),
428                headless::AppState {
429                    languages: app_state.languages.clone(),
430                    user_store: app_state.user_store.clone(),
431                    fs: fs.clone(),
432                    node_runtime: app_state.node_runtime.clone(),
433                },
434                cx,
435            )
436        })
437        .await
438        .unwrap();
439
440        TestClient {
441            app_state,
442            username: "dev-server".to_string(),
443            channel_store: cx.read(ChannelStore::global).clone(),
444            notification_store: cx.read(NotificationStore::global).clone(),
445            state: Default::default(),
446        }
447    }
448
449    pub fn disconnect_client(&self, peer_id: PeerId) {
450        self.connection_killers
451            .lock()
452            .remove(&peer_id)
453            .unwrap()
454            .store(true, SeqCst);
455    }
456
457    pub fn simulate_long_connection_interruption(
458        &self,
459        peer_id: PeerId,
460        deterministic: BackgroundExecutor,
461    ) {
462        self.forbid_connections();
463        self.disconnect_client(peer_id);
464        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
465        self.allow_connections();
466        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
467        deterministic.run_until_parked();
468    }
469
470    pub fn forbid_connections(&self) {
471        self.forbid_connections.store(true, SeqCst);
472    }
473
474    pub fn allow_connections(&self) {
475        self.forbid_connections.store(false, SeqCst);
476    }
477
478    pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
479        for ix in 1..clients.len() {
480            let (left, right) = clients.split_at_mut(ix);
481            let (client_a, cx_a) = left.last_mut().unwrap();
482            for (client_b, cx_b) in right {
483                client_a
484                    .app_state
485                    .user_store
486                    .update(*cx_a, |store, cx| {
487                        store.request_contact(client_b.user_id().unwrap(), cx)
488                    })
489                    .await
490                    .unwrap();
491                cx_a.executor().run_until_parked();
492                client_b
493                    .app_state
494                    .user_store
495                    .update(*cx_b, |store, cx| {
496                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
497                    })
498                    .await
499                    .unwrap();
500            }
501        }
502    }
503
504    pub async fn make_channel(
505        &self,
506        channel: &str,
507        parent: Option<ChannelId>,
508        admin: (&TestClient, &mut TestAppContext),
509        members: &mut [(&TestClient, &mut TestAppContext)],
510    ) -> ChannelId {
511        let (_, admin_cx) = admin;
512        let channel_id = admin_cx
513            .read(ChannelStore::global)
514            .update(admin_cx, |channel_store, cx| {
515                channel_store.create_channel(channel, parent, cx)
516            })
517            .await
518            .unwrap();
519
520        for (member_client, member_cx) in members {
521            admin_cx
522                .read(ChannelStore::global)
523                .update(admin_cx, |channel_store, cx| {
524                    channel_store.invite_member(
525                        channel_id,
526                        member_client.user_id().unwrap(),
527                        ChannelRole::Member,
528                        cx,
529                    )
530                })
531                .await
532                .unwrap();
533
534            admin_cx.executor().run_until_parked();
535
536            member_cx
537                .read(ChannelStore::global)
538                .update(*member_cx, |channels, cx| {
539                    channels.respond_to_channel_invite(channel_id, true, cx)
540                })
541                .await
542                .unwrap();
543        }
544
545        channel_id
546    }
547
548    pub async fn make_public_channel(
549        &self,
550        channel: &str,
551        client: &TestClient,
552        cx: &mut TestAppContext,
553    ) -> ChannelId {
554        let channel_id = self
555            .make_channel(channel, None, (client, cx), &mut [])
556            .await;
557
558        client
559            .channel_store()
560            .update(cx, |channel_store, cx| {
561                channel_store.set_channel_visibility(
562                    channel_id,
563                    proto::ChannelVisibility::Public,
564                    cx,
565                )
566            })
567            .await
568            .unwrap();
569
570        channel_id
571    }
572
573    pub async fn make_channel_tree(
574        &self,
575        channels: &[(&str, Option<&str>)],
576        creator: (&TestClient, &mut TestAppContext),
577    ) -> Vec<ChannelId> {
578        let mut observed_channels = HashMap::default();
579        let mut result = Vec::new();
580        for (channel, parent) in channels {
581            let id;
582            if let Some(parent) = parent {
583                if let Some(parent_id) = observed_channels.get(parent) {
584                    id = self
585                        .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
586                        .await;
587                } else {
588                    panic!(
589                        "Edge {}->{} referenced before {} was created",
590                        parent, channel, parent
591                    )
592                }
593            } else {
594                id = self
595                    .make_channel(channel, None, (creator.0, creator.1), &mut [])
596                    .await;
597            }
598
599            observed_channels.insert(channel, id);
600            result.push(id);
601        }
602
603        result
604    }
605
606    pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
607        self.make_contacts(clients).await;
608
609        let (left, right) = clients.split_at_mut(1);
610        let (_client_a, cx_a) = &mut left[0];
611        let active_call_a = cx_a.read(ActiveCall::global);
612
613        for (client_b, cx_b) in right {
614            let user_id_b = client_b.current_user_id(cx_b).to_proto();
615            active_call_a
616                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
617                .await
618                .unwrap();
619
620            cx_b.executor().run_until_parked();
621            let active_call_b = cx_b.read(ActiveCall::global);
622            active_call_b
623                .update(*cx_b, |call, cx| call.accept_incoming(cx))
624                .await
625                .unwrap();
626        }
627    }
628
629    pub async fn build_app_state(
630        test_db: &TestDb,
631        live_kit_test_server: &live_kit_client::TestServer,
632        executor: Executor,
633    ) -> Arc<AppState> {
634        Arc::new(AppState {
635            db: test_db.db().clone(),
636            live_kit_client: Some(Arc::new(live_kit_test_server.create_api_client())),
637            blob_store_client: None,
638            rate_limiter: Arc::new(RateLimiter::new(test_db.db().clone())),
639            executor,
640            clickhouse_client: None,
641            config: Config {
642                http_port: 0,
643                database_url: "".into(),
644                database_max_connections: 0,
645                api_token: "".into(),
646                invite_link_prefix: "".into(),
647                live_kit_server: None,
648                live_kit_key: None,
649                live_kit_secret: None,
650                rust_log: None,
651                log_json: None,
652                zed_environment: "test".into(),
653                blob_store_url: None,
654                blob_store_region: None,
655                blob_store_access_key: None,
656                blob_store_secret_key: None,
657                blob_store_bucket: None,
658                openai_api_key: None,
659                google_ai_api_key: None,
660                anthropic_api_key: None,
661                clickhouse_url: None,
662                clickhouse_user: None,
663                clickhouse_password: None,
664                clickhouse_database: None,
665                zed_client_checksum_seed: None,
666                slack_panics_webhook: None,
667                auto_join_channel_id: None,
668                migrations_path: None,
669                seed_path: None,
670                supermaven_admin_api_key: None,
671            },
672        })
673    }
674}
675
676impl Deref for TestServer {
677    type Target = Server;
678
679    fn deref(&self) -> &Self::Target {
680        &self.server
681    }
682}
683
684impl Drop for TestServer {
685    fn drop(&mut self) {
686        self.server.teardown();
687        self.test_live_kit_server.teardown().unwrap();
688    }
689}
690
691impl Deref for TestClient {
692    type Target = Arc<Client>;
693
694    fn deref(&self) -> &Self::Target {
695        &self.app_state.client
696    }
697}
698
699impl TestClient {
700    pub fn fs(&self) -> &FakeFs {
701        self.app_state.fs.as_fake()
702    }
703
704    pub fn channel_store(&self) -> &Model<ChannelStore> {
705        &self.channel_store
706    }
707
708    pub fn notification_store(&self) -> &Model<NotificationStore> {
709        &self.notification_store
710    }
711
712    pub fn user_store(&self) -> &Model<UserStore> {
713        &self.app_state.user_store
714    }
715
716    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
717        &self.app_state.languages
718    }
719
720    pub fn client(&self) -> &Arc<Client> {
721        &self.app_state.client
722    }
723
724    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
725        UserId::from_proto(
726            self.app_state
727                .user_store
728                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
729        )
730    }
731
732    pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
733        let mut authed_user = self
734            .app_state
735            .user_store
736            .read_with(cx, |user_store, _| user_store.watch_current_user());
737        while authed_user.next().await.unwrap().is_none() {}
738    }
739
740    pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
741        self.app_state
742            .user_store
743            .update(cx, |store, _| store.clear_contacts())
744            .await;
745    }
746
747    pub fn local_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
748        Ref::map(self.state.borrow(), |state| &state.local_projects)
749    }
750
751    pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
752        Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
753    }
754
755    pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
756        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
757    }
758
759    pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
760        RefMut::map(self.state.borrow_mut(), |state| {
761            &mut state.dev_server_projects
762        })
763    }
764
765    pub fn buffers_for_project<'a>(
766        &'a self,
767        project: &Model<Project>,
768    ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
769        RefMut::map(self.state.borrow_mut(), |state| {
770            state.buffers.entry(project.clone()).or_default()
771        })
772    }
773
774    pub fn buffers(
775        &self,
776    ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + '_
777    {
778        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
779    }
780
781    pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + '_ {
782        RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
783    }
784
785    pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
786        self.app_state
787            .user_store
788            .read_with(cx, |store, _| ContactsSummary {
789                current: store
790                    .contacts()
791                    .iter()
792                    .map(|contact| contact.user.github_login.clone())
793                    .collect(),
794                outgoing_requests: store
795                    .outgoing_contact_requests()
796                    .iter()
797                    .map(|user| user.github_login.clone())
798                    .collect(),
799                incoming_requests: store
800                    .incoming_contact_requests()
801                    .iter()
802                    .map(|user| user.github_login.clone())
803                    .collect(),
804            })
805    }
806
807    pub async fn build_local_project(
808        &self,
809        root_path: impl AsRef<Path>,
810        cx: &mut TestAppContext,
811    ) -> (Model<Project>, WorktreeId) {
812        let project = self.build_empty_local_project(cx);
813        let (worktree, _) = project
814            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
815            .await
816            .unwrap();
817        worktree
818            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
819            .await;
820        (project, worktree.read_with(cx, |tree, _| tree.id()))
821    }
822
823    pub async fn build_ssh_project(
824        &self,
825        root_path: impl AsRef<Path>,
826        ssh: Arc<SshSession>,
827        cx: &mut TestAppContext,
828    ) -> (Model<Project>, WorktreeId) {
829        let project = cx.update(|cx| {
830            Project::ssh(
831                ssh,
832                self.client().clone(),
833                self.app_state.node_runtime.clone(),
834                self.app_state.user_store.clone(),
835                self.app_state.languages.clone(),
836                self.app_state.fs.clone(),
837                cx,
838            )
839        });
840        let (worktree, _) = project
841            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
842            .await
843            .unwrap();
844        (project, worktree.read_with(cx, |tree, _| tree.id()))
845    }
846
847    pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
848        self.fs()
849            .insert_tree(
850                "/a",
851                json!({
852                    "1.txt": "one\none\none",
853                    "2.js": "function two() { return 2; }",
854                    "3.rs": "mod test",
855                }),
856            )
857            .await;
858        self.build_local_project("/a", cx).await.0
859    }
860
861    pub async fn host_workspace(
862        &self,
863        workspace: &View<Workspace>,
864        channel_id: ChannelId,
865        cx: &mut VisualTestContext,
866    ) {
867        cx.update(|cx| {
868            let active_call = ActiveCall::global(cx);
869            active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
870        })
871        .await
872        .unwrap();
873        cx.update(|cx| {
874            let active_call = ActiveCall::global(cx);
875            let project = workspace.read(cx).project().clone();
876            active_call.update(cx, |call, cx| call.share_project(project, cx))
877        })
878        .await
879        .unwrap();
880        cx.executor().run_until_parked();
881    }
882
883    pub async fn join_workspace<'a>(
884        &'a self,
885        channel_id: ChannelId,
886        cx: &'a mut TestAppContext,
887    ) -> (View<Workspace>, &'a mut VisualTestContext) {
888        cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
889            .await
890            .unwrap();
891        cx.run_until_parked();
892
893        self.active_workspace(cx)
894    }
895
896    pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
897        cx.update(|cx| {
898            Project::local(
899                self.client().clone(),
900                self.app_state.node_runtime.clone(),
901                self.app_state.user_store.clone(),
902                self.app_state.languages.clone(),
903                self.app_state.fs.clone(),
904                cx,
905            )
906        })
907    }
908
909    pub async fn build_dev_server_project(
910        &self,
911        host_project_id: u64,
912        guest_cx: &mut TestAppContext,
913    ) -> Model<Project> {
914        let active_call = guest_cx.read(ActiveCall::global);
915        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
916        room.update(guest_cx, |room, cx| {
917            room.join_project(
918                host_project_id,
919                self.app_state.languages.clone(),
920                self.app_state.fs.clone(),
921                cx,
922            )
923        })
924        .await
925        .unwrap()
926    }
927
928    pub fn build_workspace<'a>(
929        &'a self,
930        project: &Model<Project>,
931        cx: &'a mut TestAppContext,
932    ) -> (View<Workspace>, &'a mut VisualTestContext) {
933        cx.add_window_view(|cx| {
934            cx.activate_window();
935            Workspace::new(None, project.clone(), self.app_state.clone(), cx)
936        })
937    }
938
939    pub async fn build_test_workspace<'a>(
940        &'a self,
941        cx: &'a mut TestAppContext,
942    ) -> (View<Workspace>, &'a mut VisualTestContext) {
943        let project = self.build_test_project(cx).await;
944        cx.add_window_view(|cx| {
945            cx.activate_window();
946            Workspace::new(None, project.clone(), self.app_state.clone(), cx)
947        })
948    }
949
950    pub fn active_workspace<'a>(
951        &'a self,
952        cx: &'a mut TestAppContext,
953    ) -> (View<Workspace>, &'a mut VisualTestContext) {
954        let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
955
956        let view = window.root_view(cx).unwrap();
957        let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
958        // it might be nice to try and cleanup these at the end of each test.
959        (view, cx)
960    }
961}
962
963pub fn open_channel_notes(
964    channel_id: ChannelId,
965    cx: &mut VisualTestContext,
966) -> Task<anyhow::Result<View<ChannelView>>> {
967    let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
968    let view = window.root_view(cx).unwrap();
969
970    cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
971}
972
973impl Drop for TestClient {
974    fn drop(&mut self) {
975        self.app_state.client.teardown();
976    }
977}