room.rs

   1use crate::{
   2    call_settings::CallSettings,
   3    participant::{LocalParticipant, ParticipantLocation, RemoteParticipant},
   4};
   5use anyhow::{Context as _, Result, anyhow};
   6use audio::{Audio, Sound};
   7use client::{
   8    ChannelId, Client, ParticipantIndex, TypedEnvelope, User, UserStore,
   9    proto::{self, PeerId},
  10};
  11use collections::{BTreeMap, HashMap, HashSet};
  12use feature_flags::FeatureFlagAppExt;
  13use fs::Fs;
  14use futures::StreamExt;
  15use gpui::{
  16    App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FutureExt as _,
  17    ScreenCaptureSource, ScreenCaptureStream, Task, Timeout, WeakEntity,
  18};
  19use gpui_tokio::Tokio;
  20use language::LanguageRegistry;
  21use livekit::{LocalTrackPublication, ParticipantIdentity, RoomEvent};
  22use livekit_client::{self as livekit, AudioStream, TrackSid};
  23use postage::{sink::Sink, stream::Stream, watch};
  24use project::Project;
  25use settings::Settings as _;
  26use std::{future::Future, mem, rc::Rc, sync::Arc, time::Duration, time::Instant};
  27use util::{ResultExt, TryFutureExt, paths::PathStyle, post_inc};
  28
  29pub const RECONNECT_TIMEOUT: Duration = Duration::from_secs(30);
  30
  31#[derive(Clone, Debug, PartialEq, Eq)]
  32pub enum Event {
  33    RoomJoined {
  34        channel_id: Option<ChannelId>,
  35    },
  36    ParticipantLocationChanged {
  37        participant_id: proto::PeerId,
  38    },
  39    RemoteVideoTracksChanged {
  40        participant_id: proto::PeerId,
  41    },
  42    RemoteVideoTrackUnsubscribed {
  43        sid: TrackSid,
  44    },
  45    RemoteAudioTracksChanged {
  46        participant_id: proto::PeerId,
  47    },
  48    RemoteProjectShared {
  49        owner: Arc<User>,
  50        project_id: u64,
  51        worktree_root_names: Vec<String>,
  52    },
  53    RemoteProjectUnshared {
  54        project_id: u64,
  55    },
  56    RemoteProjectJoined {
  57        project_id: u64,
  58    },
  59    RemoteProjectInvitationDiscarded {
  60        project_id: u64,
  61    },
  62    RoomLeft {
  63        channel_id: Option<ChannelId>,
  64    },
  65}
  66
  67pub struct Room {
  68    id: u64,
  69    channel_id: Option<ChannelId>,
  70    live_kit: Option<LiveKitRoom>,
  71    status: RoomStatus,
  72    shared_projects: HashSet<WeakEntity<Project>>,
  73    joined_projects: HashSet<WeakEntity<Project>>,
  74    local_participant: LocalParticipant,
  75    remote_participants: BTreeMap<u64, RemoteParticipant>,
  76    pending_participants: Vec<Arc<User>>,
  77    participant_user_ids: HashSet<u64>,
  78    pending_call_count: usize,
  79    leave_when_empty: bool,
  80    client: Arc<Client>,
  81    user_store: Entity<UserStore>,
  82    follows_by_leader_id_project_id: HashMap<(PeerId, u64), Vec<PeerId>>,
  83    client_subscriptions: Vec<client::Subscription>,
  84    _subscriptions: Vec<gpui::Subscription>,
  85    room_update_completed_tx: watch::Sender<Option<()>>,
  86    room_update_completed_rx: watch::Receiver<Option<()>>,
  87    pending_room_update: Option<Task<()>>,
  88    maintain_connection: Option<Task<Option<()>>>,
  89    created: Instant,
  90}
  91
  92impl EventEmitter<Event> for Room {}
  93
  94impl Room {
  95    pub fn channel_id(&self) -> Option<ChannelId> {
  96        self.channel_id
  97    }
  98
  99    pub fn is_sharing_project(&self) -> bool {
 100        !self.shared_projects.is_empty()
 101    }
 102
 103    pub fn is_connected(&self, _: &App) -> bool {
 104        if let Some(live_kit) = self.live_kit.as_ref() {
 105            live_kit.room.connection_state() == livekit::ConnectionState::Connected
 106        } else {
 107            false
 108        }
 109    }
 110
 111    fn new(
 112        id: u64,
 113        channel_id: Option<ChannelId>,
 114        livekit_connection_info: Option<proto::LiveKitConnectionInfo>,
 115        client: Arc<Client>,
 116        user_store: Entity<UserStore>,
 117        cx: &mut Context<Self>,
 118    ) -> Self {
 119        spawn_room_connection(livekit_connection_info, cx);
 120
 121        let maintain_connection = cx.spawn({
 122            let client = client.clone();
 123            async move |this, cx| {
 124                Self::maintain_connection(this, client.clone(), cx)
 125                    .log_err()
 126                    .await
 127            }
 128        });
 129
 130        Audio::play_sound(Sound::Joined, cx);
 131
 132        let (room_update_completed_tx, room_update_completed_rx) = watch::channel();
 133
 134        Self {
 135            id,
 136            channel_id,
 137            live_kit: None,
 138            status: RoomStatus::Online,
 139            shared_projects: Default::default(),
 140            joined_projects: Default::default(),
 141            participant_user_ids: Default::default(),
 142            local_participant: Default::default(),
 143            remote_participants: Default::default(),
 144            pending_participants: Default::default(),
 145            pending_call_count: 0,
 146            client_subscriptions: vec![
 147                client.add_message_handler(cx.weak_entity(), Self::handle_room_updated),
 148            ],
 149            _subscriptions: vec![
 150                cx.on_release(Self::released),
 151                cx.on_app_quit(Self::app_will_quit),
 152            ],
 153            leave_when_empty: false,
 154            pending_room_update: None,
 155            client,
 156            user_store,
 157            follows_by_leader_id_project_id: Default::default(),
 158            maintain_connection: Some(maintain_connection),
 159            room_update_completed_tx,
 160            room_update_completed_rx,
 161            created: cx.background_executor().now(),
 162        }
 163    }
 164
 165    pub(crate) fn create(
 166        called_user_id: u64,
 167        initial_project: Option<Entity<Project>>,
 168        client: Arc<Client>,
 169        user_store: Entity<UserStore>,
 170        cx: &mut App,
 171    ) -> Task<Result<Entity<Self>>> {
 172        cx.spawn(async move |cx| {
 173            let response = client.request(proto::CreateRoom {}).await?;
 174            let room_proto = response.room.context("invalid room")?;
 175            let room = cx.new(|cx| {
 176                let mut room = Self::new(
 177                    room_proto.id,
 178                    None,
 179                    response.live_kit_connection_info,
 180                    client,
 181                    user_store,
 182                    cx,
 183                );
 184                if let Some(participant) = room_proto.participants.first() {
 185                    room.local_participant.role = participant.role()
 186                }
 187                room
 188            })?;
 189
 190            let initial_project_id = if let Some(initial_project) = initial_project {
 191                let initial_project_id = room
 192                    .update(cx, |room, cx| {
 193                        room.share_project(initial_project.clone(), cx)
 194                    })?
 195                    .await?;
 196                Some(initial_project_id)
 197            } else {
 198                None
 199            };
 200
 201            let did_join = room
 202                .update(cx, |room, cx| {
 203                    room.leave_when_empty = true;
 204                    room.call(called_user_id, initial_project_id, cx)
 205                })?
 206                .await;
 207            match did_join {
 208                Ok(()) => Ok(room),
 209                Err(error) => Err(error.context("room creation failed")),
 210            }
 211        })
 212    }
 213
 214    pub(crate) async fn join_channel(
 215        channel_id: ChannelId,
 216        client: Arc<Client>,
 217        user_store: Entity<UserStore>,
 218        cx: AsyncApp,
 219    ) -> Result<Entity<Self>> {
 220        Self::from_join_response(
 221            client
 222                .request(proto::JoinChannel {
 223                    channel_id: channel_id.0,
 224                })
 225                .await?,
 226            client,
 227            user_store,
 228            cx,
 229        )
 230    }
 231
 232    pub(crate) async fn join(
 233        room_id: u64,
 234        client: Arc<Client>,
 235        user_store: Entity<UserStore>,
 236        cx: AsyncApp,
 237    ) -> Result<Entity<Self>> {
 238        Self::from_join_response(
 239            client.request(proto::JoinRoom { id: room_id }).await?,
 240            client,
 241            user_store,
 242            cx,
 243        )
 244    }
 245
 246    fn released(&mut self, cx: &mut App) {
 247        if self.status.is_online() {
 248            self.leave_internal(cx).detach_and_log_err(cx);
 249        }
 250    }
 251
 252    fn app_will_quit(&mut self, cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
 253        let task = if self.status.is_online() {
 254            let leave = self.leave_internal(cx);
 255            Some(cx.background_spawn(async move {
 256                leave.await.log_err();
 257            }))
 258        } else {
 259            None
 260        };
 261
 262        async move {
 263            if let Some(task) = task {
 264                task.await;
 265            }
 266        }
 267    }
 268
 269    pub fn mute_on_join(cx: &App) -> bool {
 270        CallSettings::get_global(cx).mute_on_join || client::IMPERSONATE_LOGIN.is_some()
 271    }
 272
 273    fn from_join_response(
 274        response: proto::JoinRoomResponse,
 275        client: Arc<Client>,
 276        user_store: Entity<UserStore>,
 277        mut cx: AsyncApp,
 278    ) -> Result<Entity<Self>> {
 279        let room_proto = response.room.context("invalid room")?;
 280        let room = cx.new(|cx| {
 281            Self::new(
 282                room_proto.id,
 283                response.channel_id.map(ChannelId),
 284                response.live_kit_connection_info,
 285                client,
 286                user_store,
 287                cx,
 288            )
 289        })?;
 290        room.update(&mut cx, |room, cx| {
 291            room.leave_when_empty = room.channel_id.is_none();
 292            room.apply_room_update(room_proto, cx)?;
 293            anyhow::Ok(())
 294        })??;
 295        Ok(room)
 296    }
 297
 298    fn should_leave(&self) -> bool {
 299        self.leave_when_empty
 300            && self.pending_room_update.is_none()
 301            && self.pending_participants.is_empty()
 302            && self.remote_participants.is_empty()
 303            && self.pending_call_count == 0
 304    }
 305
 306    pub(crate) fn leave(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 307        cx.notify();
 308        self.leave_internal(cx)
 309    }
 310
 311    fn leave_internal(&mut self, cx: &mut App) -> Task<Result<()>> {
 312        if self.status.is_offline() {
 313            return Task::ready(Err(anyhow!("room is offline")));
 314        }
 315
 316        log::info!("leaving room");
 317        Audio::play_sound(Sound::Leave, cx);
 318
 319        self.clear_state(cx);
 320
 321        let leave_room = self.client.request(proto::LeaveRoom {});
 322        cx.background_spawn(async move {
 323            leave_room.await?;
 324            anyhow::Ok(())
 325        })
 326    }
 327
 328    pub(crate) fn clear_state(&mut self, cx: &mut App) {
 329        for project in self.shared_projects.drain() {
 330            if let Some(project) = project.upgrade() {
 331                project.update(cx, |project, cx| {
 332                    project.unshare(cx).log_err();
 333                });
 334            }
 335        }
 336        for project in self.joined_projects.drain() {
 337            if let Some(project) = project.upgrade() {
 338                project.update(cx, |project, cx| {
 339                    project.disconnected_from_host(cx);
 340                    project.close(cx);
 341                });
 342            }
 343        }
 344
 345        self.status = RoomStatus::Offline;
 346        self.remote_participants.clear();
 347        self.pending_participants.clear();
 348        self.participant_user_ids.clear();
 349        self.client_subscriptions.clear();
 350        self.live_kit.take();
 351        self.pending_room_update.take();
 352        self.maintain_connection.take();
 353    }
 354
 355    async fn maintain_connection(
 356        this: WeakEntity<Self>,
 357        client: Arc<Client>,
 358        cx: &mut AsyncApp,
 359    ) -> Result<()> {
 360        let mut client_status = client.status();
 361        loop {
 362            let _ = client_status.try_recv();
 363            let is_connected = client_status.borrow().is_connected();
 364            // Even if we're initially connected, any future change of the status means we momentarily disconnected.
 365            if !is_connected || client_status.next().await.is_some() {
 366                log::info!("detected client disconnection");
 367
 368                this.upgrade()
 369                    .context("room was dropped")?
 370                    .update(cx, |this, cx| {
 371                        this.status = RoomStatus::Rejoining;
 372                        cx.notify();
 373                    })?;
 374
 375                // Wait for client to re-establish a connection to the server.
 376                let executor = cx.background_executor().clone();
 377                let client_reconnection = async {
 378                    let mut remaining_attempts = 3;
 379                    while remaining_attempts > 0 {
 380                        if client_status.borrow().is_connected() {
 381                            log::info!("client reconnected, attempting to rejoin room");
 382
 383                            let Some(this) = this.upgrade() else { break };
 384                            match this.update(cx, |this, cx| this.rejoin(cx)) {
 385                                Ok(task) => {
 386                                    if task.await.log_err().is_some() {
 387                                        return true;
 388                                    } else {
 389                                        remaining_attempts -= 1;
 390                                    }
 391                                }
 392                                Err(_app_dropped) => return false,
 393                            }
 394                        } else if client_status.borrow().is_signed_out() {
 395                            return false;
 396                        }
 397
 398                        log::info!(
 399                            "waiting for client status change, remaining attempts {}",
 400                            remaining_attempts
 401                        );
 402                        client_status.next().await;
 403                    }
 404                    false
 405                };
 406
 407                match client_reconnection
 408                    .with_timeout(RECONNECT_TIMEOUT, &executor)
 409                    .await
 410                {
 411                    Ok(true) => {
 412                        log::info!("successfully reconnected to room");
 413                        // If we successfully joined the room, go back around the loop
 414                        // waiting for future connection status changes.
 415                        continue;
 416                    }
 417                    Ok(false) => break,
 418                    Err(Timeout) => {
 419                        log::info!("room reconnection timeout expired");
 420                        break;
 421                    }
 422                }
 423            }
 424        }
 425
 426        // The client failed to re-establish a connection to the server
 427        // or an error occurred while trying to re-join the room. Either way
 428        // we leave the room and return an error.
 429        if let Some(this) = this.upgrade() {
 430            log::info!("reconnection failed, leaving room");
 431            this.update(cx, |this, cx| this.leave(cx))?.await?;
 432        }
 433        anyhow::bail!("can't reconnect to room: client failed to re-establish connection");
 434    }
 435
 436    fn rejoin(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 437        let mut projects = HashMap::default();
 438        let mut reshared_projects = Vec::new();
 439        let mut rejoined_projects = Vec::new();
 440        self.shared_projects.retain(|project| {
 441            if let Some(handle) = project.upgrade() {
 442                let project = handle.read(cx);
 443                if let Some(project_id) = project.remote_id() {
 444                    projects.insert(project_id, handle.clone());
 445                    reshared_projects.push(proto::UpdateProject {
 446                        project_id,
 447                        worktrees: project.worktree_metadata_protos(cx),
 448                    });
 449                    return true;
 450                }
 451            }
 452            false
 453        });
 454        self.joined_projects.retain(|project| {
 455            if let Some(handle) = project.upgrade() {
 456                let project = handle.read(cx);
 457                if let Some(project_id) = project.remote_id() {
 458                    projects.insert(project_id, handle.clone());
 459                    let mut worktrees = Vec::new();
 460                    let mut repositories = Vec::new();
 461                    for worktree in project.worktrees(cx) {
 462                        let worktree = worktree.read(cx);
 463                        worktrees.push(proto::RejoinWorktree {
 464                            id: worktree.id().to_proto(),
 465                            scan_id: worktree.completed_scan_id() as u64,
 466                        });
 467                    }
 468                    for (entry_id, repository) in project.repositories(cx) {
 469                        let repository = repository.read(cx);
 470                        repositories.push(proto::RejoinRepository {
 471                            id: entry_id.to_proto(),
 472                            scan_id: repository.scan_id,
 473                        });
 474                    }
 475
 476                    rejoined_projects.push(proto::RejoinProject {
 477                        id: project_id,
 478                        worktrees,
 479                        repositories,
 480                    });
 481                }
 482                return true;
 483            }
 484            false
 485        });
 486
 487        let response = self.client.request_envelope(proto::RejoinRoom {
 488            id: self.id,
 489            reshared_projects,
 490            rejoined_projects,
 491        });
 492
 493        cx.spawn(async move |this, cx| {
 494            let response = response.await?;
 495            let message_id = response.message_id;
 496            let response = response.payload;
 497            let room_proto = response.room.context("invalid room")?;
 498            this.update(cx, |this, cx| {
 499                this.status = RoomStatus::Online;
 500                this.apply_room_update(room_proto, cx)?;
 501
 502                for reshared_project in response.reshared_projects {
 503                    if let Some(project) = projects.get(&reshared_project.id) {
 504                        project.update(cx, |project, cx| {
 505                            project.reshared(reshared_project, cx).log_err();
 506                        });
 507                    }
 508                }
 509
 510                for rejoined_project in response.rejoined_projects {
 511                    if let Some(project) = projects.get(&rejoined_project.id) {
 512                        project.update(cx, |project, cx| {
 513                            project.rejoined(rejoined_project, message_id, cx).log_err();
 514                        });
 515                    }
 516                }
 517
 518                anyhow::Ok(())
 519            })?
 520        })
 521    }
 522
 523    pub fn id(&self) -> u64 {
 524        self.id
 525    }
 526
 527    pub fn status(&self) -> RoomStatus {
 528        self.status
 529    }
 530
 531    pub fn local_participant(&self) -> &LocalParticipant {
 532        &self.local_participant
 533    }
 534
 535    pub fn local_participant_user(&self, cx: &App) -> Option<Arc<User>> {
 536        self.user_store.read(cx).current_user()
 537    }
 538
 539    pub fn remote_participants(&self) -> &BTreeMap<u64, RemoteParticipant> {
 540        &self.remote_participants
 541    }
 542
 543    pub fn remote_participant_for_peer_id(&self, peer_id: PeerId) -> Option<&RemoteParticipant> {
 544        self.remote_participants
 545            .values()
 546            .find(|p| p.peer_id == peer_id)
 547    }
 548
 549    pub fn role_for_user(&self, user_id: u64) -> Option<proto::ChannelRole> {
 550        self.remote_participants
 551            .get(&user_id)
 552            .map(|participant| participant.role)
 553    }
 554
 555    pub fn contains_guests(&self) -> bool {
 556        self.local_participant.role == proto::ChannelRole::Guest
 557            || self
 558                .remote_participants
 559                .values()
 560                .any(|p| p.role == proto::ChannelRole::Guest)
 561    }
 562
 563    pub fn local_participant_is_admin(&self) -> bool {
 564        self.local_participant.role == proto::ChannelRole::Admin
 565    }
 566
 567    pub fn local_participant_is_guest(&self) -> bool {
 568        self.local_participant.role == proto::ChannelRole::Guest
 569    }
 570
 571    pub fn set_participant_role(
 572        &mut self,
 573        user_id: u64,
 574        role: proto::ChannelRole,
 575        cx: &Context<Self>,
 576    ) -> Task<Result<()>> {
 577        let client = self.client.clone();
 578        let room_id = self.id;
 579        let role = role.into();
 580        cx.spawn(async move |_, _| {
 581            client
 582                .request(proto::SetRoomParticipantRole {
 583                    room_id,
 584                    user_id,
 585                    role,
 586                })
 587                .await
 588                .map(|_| ())
 589        })
 590    }
 591
 592    pub fn pending_participants(&self) -> &[Arc<User>] {
 593        &self.pending_participants
 594    }
 595
 596    pub fn contains_participant(&self, user_id: u64) -> bool {
 597        self.participant_user_ids.contains(&user_id)
 598    }
 599
 600    pub fn followers_for(&self, leader_id: PeerId, project_id: u64) -> &[PeerId] {
 601        self.follows_by_leader_id_project_id
 602            .get(&(leader_id, project_id))
 603            .map_or(&[], |v| v.as_slice())
 604    }
 605
 606    /// Returns the most 'active' projects, defined as most people in the project
 607    pub fn most_active_project(&self, cx: &App) -> Option<(u64, u64)> {
 608        let mut project_hosts_and_guest_counts = HashMap::<u64, (Option<u64>, u32)>::default();
 609        for participant in self.remote_participants.values() {
 610            match participant.location {
 611                ParticipantLocation::SharedProject { project_id } => {
 612                    project_hosts_and_guest_counts
 613                        .entry(project_id)
 614                        .or_default()
 615                        .1 += 1;
 616                }
 617                ParticipantLocation::External | ParticipantLocation::UnsharedProject => {}
 618            }
 619            for project in &participant.projects {
 620                project_hosts_and_guest_counts
 621                    .entry(project.id)
 622                    .or_default()
 623                    .0 = Some(participant.user.id);
 624            }
 625        }
 626
 627        if let Some(user) = self.user_store.read(cx).current_user() {
 628            for project in &self.local_participant.projects {
 629                project_hosts_and_guest_counts
 630                    .entry(project.id)
 631                    .or_default()
 632                    .0 = Some(user.id);
 633            }
 634        }
 635
 636        project_hosts_and_guest_counts
 637            .into_iter()
 638            .filter_map(|(id, (host, guest_count))| Some((id, host?, guest_count)))
 639            .max_by_key(|(_, _, guest_count)| *guest_count)
 640            .map(|(id, host, _)| (id, host))
 641    }
 642
 643    async fn handle_room_updated(
 644        this: Entity<Self>,
 645        envelope: TypedEnvelope<proto::RoomUpdated>,
 646        mut cx: AsyncApp,
 647    ) -> Result<()> {
 648        let room = envelope.payload.room.context("invalid room")?;
 649        this.update(&mut cx, |this, cx| this.apply_room_update(room, cx))?
 650    }
 651
 652    fn apply_room_update(&mut self, room: proto::Room, cx: &mut Context<Self>) -> Result<()> {
 653        log::trace!(
 654            "client {:?}. room update: {:?}",
 655            self.client.user_id(),
 656            &room
 657        );
 658
 659        self.pending_room_update = Some(self.start_room_connection(room, cx));
 660
 661        cx.notify();
 662        Ok(())
 663    }
 664
 665    pub fn room_update_completed(&mut self) -> impl Future<Output = ()> + use<> {
 666        let mut done_rx = self.room_update_completed_rx.clone();
 667        async move {
 668            while let Some(result) = done_rx.next().await {
 669                if result.is_some() {
 670                    break;
 671                }
 672            }
 673        }
 674    }
 675
 676    fn start_room_connection(&self, mut room: proto::Room, cx: &mut Context<Self>) -> Task<()> {
 677        // Filter ourselves out from the room's participants.
 678        let local_participant_ix = room
 679            .participants
 680            .iter()
 681            .position(|participant| Some(participant.user_id) == self.client.user_id());
 682        let local_participant = local_participant_ix.map(|ix| room.participants.swap_remove(ix));
 683
 684        let pending_participant_user_ids = room
 685            .pending_participants
 686            .iter()
 687            .map(|p| p.user_id)
 688            .collect::<Vec<_>>();
 689
 690        let remote_participant_user_ids = room
 691            .participants
 692            .iter()
 693            .map(|p| p.user_id)
 694            .collect::<Vec<_>>();
 695
 696        let (remote_participants, pending_participants) =
 697            self.user_store.update(cx, move |user_store, cx| {
 698                (
 699                    user_store.get_users(remote_participant_user_ids, cx),
 700                    user_store.get_users(pending_participant_user_ids, cx),
 701                )
 702            });
 703        cx.spawn(async move |this, cx| {
 704            let (remote_participants, pending_participants) =
 705                futures::join!(remote_participants, pending_participants);
 706
 707            this.update(cx, |this, cx| {
 708                this.participant_user_ids.clear();
 709
 710                if let Some(participant) = local_participant {
 711                    let role = participant.role();
 712                    this.local_participant.projects = participant.projects;
 713                    if this.local_participant.role != role {
 714                        this.local_participant.role = role;
 715
 716                        if role == proto::ChannelRole::Guest {
 717                            for project in mem::take(&mut this.shared_projects) {
 718                                if let Some(project) = project.upgrade() {
 719                                    this.unshare_project(project, cx).log_err();
 720                                }
 721                            }
 722                            this.local_participant.projects.clear();
 723                            if let Some(livekit_room) = &mut this.live_kit {
 724                                livekit_room.stop_publishing(cx);
 725                            }
 726                        }
 727
 728                        this.joined_projects.retain(|project| {
 729                            if let Some(project) = project.upgrade() {
 730                                project.update(cx, |project, cx| project.set_role(role, cx));
 731                                true
 732                            } else {
 733                                false
 734                            }
 735                        });
 736                    }
 737                } else {
 738                    this.local_participant.projects.clear();
 739                }
 740
 741                let livekit_participants = this
 742                    .live_kit
 743                    .as_ref()
 744                    .map(|live_kit| live_kit.room.remote_participants());
 745
 746                if let Some(participants) = remote_participants.log_err() {
 747                    for (participant, user) in room.participants.into_iter().zip(participants) {
 748                        let Some(peer_id) = participant.peer_id else {
 749                            continue;
 750                        };
 751                        let participant_index = ParticipantIndex(participant.participant_index);
 752                        this.participant_user_ids.insert(participant.user_id);
 753
 754                        let old_projects = this
 755                            .remote_participants
 756                            .get(&participant.user_id)
 757                            .into_iter()
 758                            .flat_map(|existing| &existing.projects)
 759                            .map(|project| project.id)
 760                            .collect::<HashSet<_>>();
 761                        let new_projects = participant
 762                            .projects
 763                            .iter()
 764                            .map(|project| project.id)
 765                            .collect::<HashSet<_>>();
 766
 767                        for project in &participant.projects {
 768                            if !old_projects.contains(&project.id) {
 769                                cx.emit(Event::RemoteProjectShared {
 770                                    owner: user.clone(),
 771                                    project_id: project.id,
 772                                    worktree_root_names: project.worktree_root_names.clone(),
 773                                });
 774                            }
 775                        }
 776
 777                        for unshared_project_id in old_projects.difference(&new_projects) {
 778                            this.joined_projects.retain(|project| {
 779                                if let Some(project) = project.upgrade() {
 780                                    project.update(cx, |project, cx| {
 781                                        if project.remote_id() == Some(*unshared_project_id) {
 782                                            project.disconnected_from_host(cx);
 783                                            false
 784                                        } else {
 785                                            true
 786                                        }
 787                                    })
 788                                } else {
 789                                    false
 790                                }
 791                            });
 792                            cx.emit(Event::RemoteProjectUnshared {
 793                                project_id: *unshared_project_id,
 794                            });
 795                        }
 796
 797                        let role = participant.role();
 798                        let location = ParticipantLocation::from_proto(participant.location)
 799                            .unwrap_or(ParticipantLocation::External);
 800                        if let Some(remote_participant) =
 801                            this.remote_participants.get_mut(&participant.user_id)
 802                        {
 803                            remote_participant.peer_id = peer_id;
 804                            remote_participant.projects = participant.projects;
 805                            remote_participant.participant_index = participant_index;
 806                            if location != remote_participant.location
 807                                || role != remote_participant.role
 808                            {
 809                                remote_participant.location = location;
 810                                remote_participant.role = role;
 811                                cx.emit(Event::ParticipantLocationChanged {
 812                                    participant_id: peer_id,
 813                                });
 814                            }
 815                        } else {
 816                            this.remote_participants.insert(
 817                                participant.user_id,
 818                                RemoteParticipant {
 819                                    user: user.clone(),
 820                                    participant_index,
 821                                    peer_id,
 822                                    projects: participant.projects,
 823                                    location,
 824                                    role,
 825                                    muted: true,
 826                                    speaking: false,
 827                                    video_tracks: Default::default(),
 828                                    audio_tracks: Default::default(),
 829                                },
 830                            );
 831
 832                            // When joining a room start_room_connection gets
 833                            // called but we have already played the join sound.
 834                            // Dont play extra sounds over that.
 835                            if this.created.elapsed() > Duration::from_millis(100) {
 836                                if let proto::ChannelRole::Guest = role {
 837                                    Audio::play_sound(Sound::GuestJoined, cx);
 838                                } else {
 839                                    Audio::play_sound(Sound::Joined, cx);
 840                                }
 841                            }
 842
 843                            if let Some(livekit_participants) = &livekit_participants
 844                                && let Some(livekit_participant) = livekit_participants
 845                                    .get(&ParticipantIdentity(user.id.to_string()))
 846                            {
 847                                for publication in
 848                                    livekit_participant.track_publications().into_values()
 849                                {
 850                                    if let Some(track) = publication.track() {
 851                                        this.livekit_room_updated(
 852                                            RoomEvent::TrackSubscribed {
 853                                                track,
 854                                                publication,
 855                                                participant: livekit_participant.clone(),
 856                                            },
 857                                            cx,
 858                                        )
 859                                        .warn_on_err();
 860                                    }
 861                                }
 862                            }
 863                        }
 864                    }
 865
 866                    this.remote_participants.retain(|user_id, participant| {
 867                        if this.participant_user_ids.contains(user_id) {
 868                            true
 869                        } else {
 870                            for project in &participant.projects {
 871                                cx.emit(Event::RemoteProjectUnshared {
 872                                    project_id: project.id,
 873                                });
 874                            }
 875                            false
 876                        }
 877                    });
 878                }
 879
 880                if let Some(pending_participants) = pending_participants.log_err() {
 881                    this.pending_participants = pending_participants;
 882                    for participant in &this.pending_participants {
 883                        this.participant_user_ids.insert(participant.id);
 884                    }
 885                }
 886
 887                this.follows_by_leader_id_project_id.clear();
 888                for follower in room.followers {
 889                    let project_id = follower.project_id;
 890                    let (leader, follower) = match (follower.leader_id, follower.follower_id) {
 891                        (Some(leader), Some(follower)) => (leader, follower),
 892
 893                        _ => {
 894                            log::error!("Follower message {follower:?} missing some state");
 895                            continue;
 896                        }
 897                    };
 898
 899                    let list = this
 900                        .follows_by_leader_id_project_id
 901                        .entry((leader, project_id))
 902                        .or_default();
 903                    if !list.contains(&follower) {
 904                        list.push(follower);
 905                    }
 906                }
 907
 908                this.pending_room_update.take();
 909                if this.should_leave() {
 910                    log::info!("room is empty, leaving");
 911                    this.leave(cx).detach();
 912                }
 913
 914                this.user_store.update(cx, |user_store, cx| {
 915                    let participant_indices_by_user_id = this
 916                        .remote_participants
 917                        .iter()
 918                        .map(|(user_id, participant)| (*user_id, participant.participant_index))
 919                        .collect();
 920                    user_store.set_participant_indices(participant_indices_by_user_id, cx);
 921                });
 922
 923                this.check_invariants();
 924                this.room_update_completed_tx.try_send(Some(())).ok();
 925                cx.notify();
 926            })
 927            .ok();
 928        })
 929    }
 930
 931    fn livekit_room_updated(&mut self, event: RoomEvent, cx: &mut Context<Self>) -> Result<()> {
 932        log::trace!(
 933            "client {:?}. livekit event: {:?}",
 934            self.client.user_id(),
 935            &event
 936        );
 937
 938        match event {
 939            RoomEvent::TrackSubscribed {
 940                track,
 941                participant,
 942                publication,
 943            } => {
 944                let user_id = participant.identity().0.parse()?;
 945                let track_id = track.sid();
 946                let participant =
 947                    self.remote_participants
 948                        .get_mut(&user_id)
 949                        .with_context(|| {
 950                            format!(
 951                                "{:?} subscribed to track by unknown participant {user_id}",
 952                                self.client.user_id()
 953                            )
 954                        })?;
 955                if self.live_kit.as_ref().is_none_or(|kit| kit.deafened) && publication.is_audio() {
 956                    publication.set_enabled(false, cx);
 957                }
 958                match track {
 959                    livekit_client::RemoteTrack::Audio(track) => {
 960                        cx.emit(Event::RemoteAudioTracksChanged {
 961                            participant_id: participant.peer_id,
 962                        });
 963                        if let Some(live_kit) = self.live_kit.as_ref() {
 964                            let stream = live_kit.room.play_remote_audio_track(&track, cx)?;
 965                            participant.audio_tracks.insert(track_id, (track, stream));
 966                            participant.muted = publication.is_muted();
 967                        }
 968                    }
 969                    livekit_client::RemoteTrack::Video(track) => {
 970                        cx.emit(Event::RemoteVideoTracksChanged {
 971                            participant_id: participant.peer_id,
 972                        });
 973                        participant.video_tracks.insert(track_id, track);
 974                    }
 975                }
 976            }
 977
 978            RoomEvent::TrackUnsubscribed {
 979                track, participant, ..
 980            } => {
 981                let user_id = participant.identity().0.parse()?;
 982                let participant =
 983                    self.remote_participants
 984                        .get_mut(&user_id)
 985                        .with_context(|| {
 986                            format!(
 987                                "{:?}, unsubscribed from track by unknown participant {user_id}",
 988                                self.client.user_id()
 989                            )
 990                        })?;
 991                match track {
 992                    livekit_client::RemoteTrack::Audio(track) => {
 993                        participant.audio_tracks.remove(&track.sid());
 994                        participant.muted = true;
 995                        cx.emit(Event::RemoteAudioTracksChanged {
 996                            participant_id: participant.peer_id,
 997                        });
 998                    }
 999                    livekit_client::RemoteTrack::Video(track) => {
1000                        participant.video_tracks.remove(&track.sid());
1001                        cx.emit(Event::RemoteVideoTracksChanged {
1002                            participant_id: participant.peer_id,
1003                        });
1004                        cx.emit(Event::RemoteVideoTrackUnsubscribed { sid: track.sid() });
1005                    }
1006                }
1007            }
1008
1009            RoomEvent::ActiveSpeakersChanged { speakers } => {
1010                let mut speaker_ids = speakers
1011                    .into_iter()
1012                    .filter_map(|speaker| speaker.identity().0.parse().ok())
1013                    .collect::<Vec<u64>>();
1014                speaker_ids.sort_unstable();
1015                for (sid, participant) in &mut self.remote_participants {
1016                    participant.speaking = speaker_ids.binary_search(sid).is_ok();
1017                }
1018                if let Some(id) = self.client.user_id()
1019                    && let Some(room) = &mut self.live_kit
1020                {
1021                    room.speaking = speaker_ids.binary_search(&id).is_ok();
1022                }
1023            }
1024
1025            RoomEvent::TrackMuted {
1026                participant,
1027                publication,
1028            }
1029            | RoomEvent::TrackUnmuted {
1030                participant,
1031                publication,
1032            } => {
1033                let mut found = false;
1034                let user_id = participant.identity().0.parse()?;
1035                let track_id = publication.sid();
1036                if let Some(participant) = self.remote_participants.get_mut(&user_id) {
1037                    for (track, _) in participant.audio_tracks.values() {
1038                        if track.sid() == track_id {
1039                            found = true;
1040                            break;
1041                        }
1042                    }
1043                    if found {
1044                        participant.muted = publication.is_muted();
1045                    }
1046                }
1047            }
1048
1049            RoomEvent::LocalTrackUnpublished { publication, .. } => {
1050                log::info!("unpublished track {}", publication.sid());
1051                if let Some(room) = &mut self.live_kit {
1052                    if let LocalTrack::Published {
1053                        track_publication, ..
1054                    } = &room.microphone_track
1055                        && track_publication.sid() == publication.sid()
1056                    {
1057                        room.microphone_track = LocalTrack::None;
1058                    }
1059                    if let LocalTrack::Published {
1060                        track_publication, ..
1061                    } = &room.screen_track
1062                        && track_publication.sid() == publication.sid()
1063                    {
1064                        room.screen_track = LocalTrack::None;
1065                    }
1066                }
1067            }
1068
1069            RoomEvent::LocalTrackPublished { publication, .. } => {
1070                log::info!("published track {:?}", publication.sid());
1071            }
1072
1073            RoomEvent::Disconnected { reason } => {
1074                log::info!("disconnected from room: {reason:?}");
1075                self.leave(cx).detach_and_log_err(cx);
1076            }
1077            _ => {}
1078        }
1079
1080        cx.notify();
1081        Ok(())
1082    }
1083
1084    fn check_invariants(&self) {
1085        #[cfg(any(test, feature = "test-support"))]
1086        {
1087            for participant in self.remote_participants.values() {
1088                assert!(self.participant_user_ids.contains(&participant.user.id));
1089                assert_ne!(participant.user.id, self.client.user_id().unwrap());
1090            }
1091
1092            for participant in &self.pending_participants {
1093                assert!(self.participant_user_ids.contains(&participant.id));
1094                assert_ne!(participant.id, self.client.user_id().unwrap());
1095            }
1096
1097            assert_eq!(
1098                self.participant_user_ids.len(),
1099                self.remote_participants.len() + self.pending_participants.len()
1100            );
1101        }
1102    }
1103
1104    pub(crate) fn call(
1105        &mut self,
1106        called_user_id: u64,
1107        initial_project_id: Option<u64>,
1108        cx: &mut Context<Self>,
1109    ) -> Task<Result<()>> {
1110        if self.status.is_offline() {
1111            return Task::ready(Err(anyhow!("room is offline")));
1112        }
1113
1114        cx.notify();
1115        let client = self.client.clone();
1116        let room_id = self.id;
1117        self.pending_call_count += 1;
1118        cx.spawn(async move |this, cx| {
1119            let result = client
1120                .request(proto::Call {
1121                    room_id,
1122                    called_user_id,
1123                    initial_project_id,
1124                })
1125                .await;
1126            this.update(cx, |this, cx| {
1127                this.pending_call_count -= 1;
1128                if this.should_leave() {
1129                    this.leave(cx).detach_and_log_err(cx);
1130                }
1131            })?;
1132            result?;
1133            Ok(())
1134        })
1135    }
1136
1137    pub fn join_project(
1138        &mut self,
1139        id: u64,
1140        language_registry: Arc<LanguageRegistry>,
1141        fs: Arc<dyn Fs>,
1142        cx: &mut Context<Self>,
1143    ) -> Task<Result<Entity<Project>>> {
1144        let client = self.client.clone();
1145        let user_store = self.user_store.clone();
1146        cx.emit(Event::RemoteProjectJoined { project_id: id });
1147        cx.spawn(async move |this, cx| {
1148            let project =
1149                Project::in_room(id, client, user_store, language_registry, fs, cx.clone()).await?;
1150
1151            this.update(cx, |this, cx| {
1152                this.joined_projects.retain(|project| {
1153                    if let Some(project) = project.upgrade() {
1154                        !project.read(cx).is_disconnected(cx)
1155                    } else {
1156                        false
1157                    }
1158                });
1159                this.joined_projects.insert(project.downgrade());
1160            })?;
1161            Ok(project)
1162        })
1163    }
1164
1165    pub fn share_project(
1166        &mut self,
1167        project: Entity<Project>,
1168        cx: &mut Context<Self>,
1169    ) -> Task<Result<u64>> {
1170        if let Some(project_id) = project.read(cx).remote_id() {
1171            return Task::ready(Ok(project_id));
1172        }
1173
1174        let request = self.client.request(proto::ShareProject {
1175            room_id: self.id(),
1176            worktrees: project.read(cx).worktree_metadata_protos(cx),
1177            is_ssh_project: project.read(cx).is_via_remote_server(),
1178            windows_paths: Some(project.read(cx).path_style(cx) == PathStyle::Windows),
1179        });
1180
1181        cx.spawn(async move |this, cx| {
1182            let response = request.await?;
1183
1184            project.update(cx, |project, cx| project.shared(response.project_id, cx))??;
1185
1186            // If the user's location is in this project, it changes from UnsharedProject to SharedProject.
1187            this.update(cx, |this, cx| {
1188                this.shared_projects.insert(project.downgrade());
1189                let active_project = this.local_participant.active_project.as_ref();
1190                if active_project.is_some_and(|location| *location == project) {
1191                    this.set_location(Some(&project), cx)
1192                } else {
1193                    Task::ready(Ok(()))
1194                }
1195            })?
1196            .await?;
1197
1198            Ok(response.project_id)
1199        })
1200    }
1201
1202    pub(crate) fn unshare_project(
1203        &mut self,
1204        project: Entity<Project>,
1205        cx: &mut Context<Self>,
1206    ) -> Result<()> {
1207        let project_id = match project.read(cx).remote_id() {
1208            Some(project_id) => project_id,
1209            None => return Ok(()),
1210        };
1211
1212        self.client.send(proto::UnshareProject { project_id })?;
1213        project.update(cx, |this, cx| this.unshare(cx))?;
1214
1215        if self.local_participant.active_project == Some(project.downgrade()) {
1216            self.set_location(Some(&project), cx).detach_and_log_err(cx);
1217        }
1218        Ok(())
1219    }
1220
1221    pub(crate) fn set_location(
1222        &mut self,
1223        project: Option<&Entity<Project>>,
1224        cx: &mut Context<Self>,
1225    ) -> Task<Result<()>> {
1226        if self.status.is_offline() {
1227            return Task::ready(Err(anyhow!("room is offline")));
1228        }
1229
1230        let client = self.client.clone();
1231        let room_id = self.id;
1232        let location = if let Some(project) = project {
1233            self.local_participant.active_project = Some(project.downgrade());
1234            if let Some(project_id) = project.read(cx).remote_id() {
1235                proto::participant_location::Variant::SharedProject(
1236                    proto::participant_location::SharedProject { id: project_id },
1237                )
1238            } else {
1239                proto::participant_location::Variant::UnsharedProject(
1240                    proto::participant_location::UnsharedProject {},
1241                )
1242            }
1243        } else {
1244            self.local_participant.active_project = None;
1245            proto::participant_location::Variant::External(proto::participant_location::External {})
1246        };
1247
1248        cx.notify();
1249        cx.background_spawn(async move {
1250            client
1251                .request(proto::UpdateParticipantLocation {
1252                    room_id,
1253                    location: Some(proto::ParticipantLocation {
1254                        variant: Some(location),
1255                    }),
1256                })
1257                .await?;
1258            Ok(())
1259        })
1260    }
1261
1262    pub fn is_sharing_screen(&self) -> bool {
1263        self.live_kit
1264            .as_ref()
1265            .is_some_and(|live_kit| !matches!(live_kit.screen_track, LocalTrack::None))
1266    }
1267
1268    pub fn shared_screen_id(&self) -> Option<u64> {
1269        self.live_kit.as_ref().and_then(|lk| match lk.screen_track {
1270            LocalTrack::Published { ref _stream, .. } => {
1271                _stream.metadata().ok().map(|meta| meta.id)
1272            }
1273            _ => None,
1274        })
1275    }
1276
1277    pub fn is_sharing_mic(&self) -> bool {
1278        self.live_kit
1279            .as_ref()
1280            .is_some_and(|live_kit| !matches!(live_kit.microphone_track, LocalTrack::None))
1281    }
1282
1283    pub fn is_muted(&self) -> bool {
1284        self.live_kit.as_ref().is_some_and(|live_kit| {
1285            matches!(live_kit.microphone_track, LocalTrack::None)
1286                || live_kit.muted_by_user
1287                || live_kit.deafened
1288        })
1289    }
1290
1291    pub fn muted_by_user(&self) -> bool {
1292        self.live_kit
1293            .as_ref()
1294            .is_some_and(|live_kit| live_kit.muted_by_user)
1295    }
1296
1297    pub fn is_speaking(&self) -> bool {
1298        self.live_kit
1299            .as_ref()
1300            .is_some_and(|live_kit| live_kit.speaking)
1301    }
1302
1303    pub fn is_deafened(&self) -> Option<bool> {
1304        self.live_kit.as_ref().map(|live_kit| live_kit.deafened)
1305    }
1306
1307    pub fn can_use_microphone(&self) -> bool {
1308        use proto::ChannelRole::*;
1309
1310        match self.local_participant.role {
1311            Admin | Member | Talker => true,
1312            Guest | Banned => false,
1313        }
1314    }
1315
1316    pub fn can_share_projects(&self) -> bool {
1317        use proto::ChannelRole::*;
1318        match self.local_participant.role {
1319            Admin | Member => true,
1320            Guest | Banned | Talker => false,
1321        }
1322    }
1323
1324    #[track_caller]
1325    pub fn share_microphone(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
1326        if self.status.is_offline() {
1327            return Task::ready(Err(anyhow!("room is offline")));
1328        }
1329
1330        let (room, publish_id) = if let Some(live_kit) = self.live_kit.as_mut() {
1331            let publish_id = post_inc(&mut live_kit.next_publish_id);
1332            live_kit.microphone_track = LocalTrack::Pending { publish_id };
1333            cx.notify();
1334            (live_kit.room.clone(), publish_id)
1335        } else {
1336            return Task::ready(Err(anyhow!("live-kit was not initialized")));
1337        };
1338
1339        let is_staff = cx.is_staff();
1340        let user_name = self
1341            .user_store
1342            .read(cx)
1343            .current_user()
1344            .and_then(|user| user.name.clone())
1345            .unwrap_or_else(|| "unknown".to_string());
1346
1347        cx.spawn(async move |this, cx| {
1348            let publication = room
1349                .publish_local_microphone_track(user_name, is_staff, cx)
1350                .await;
1351            this.update(cx, |this, cx| {
1352                let live_kit = this
1353                    .live_kit
1354                    .as_mut()
1355                    .context("live-kit was not initialized")?;
1356
1357                let canceled = if let LocalTrack::Pending {
1358                    publish_id: cur_publish_id,
1359                } = &live_kit.microphone_track
1360                {
1361                    *cur_publish_id != publish_id
1362                } else {
1363                    true
1364                };
1365
1366                match publication {
1367                    Ok((publication, stream)) => {
1368                        if canceled {
1369                            cx.spawn(async move |_, cx| {
1370                                room.unpublish_local_track(publication.sid(), cx).await
1371                            })
1372                            .detach_and_log_err(cx)
1373                        } else {
1374                            if live_kit.muted_by_user || live_kit.deafened {
1375                                publication.mute(cx);
1376                            }
1377                            live_kit.microphone_track = LocalTrack::Published {
1378                                track_publication: publication,
1379                                _stream: Box::new(stream),
1380                            };
1381                            cx.notify();
1382                        }
1383                        Ok(())
1384                    }
1385                    Err(error) => {
1386                        if canceled {
1387                            Ok(())
1388                        } else {
1389                            live_kit.microphone_track = LocalTrack::None;
1390                            cx.notify();
1391                            Err(error)
1392                        }
1393                    }
1394                }
1395            })?
1396        })
1397    }
1398
1399    pub fn share_screen(
1400        &mut self,
1401        source: Rc<dyn ScreenCaptureSource>,
1402        cx: &mut Context<Self>,
1403    ) -> Task<Result<()>> {
1404        if self.status.is_offline() {
1405            return Task::ready(Err(anyhow!("room is offline")));
1406        }
1407        if self.is_sharing_screen() {
1408            return Task::ready(Err(anyhow!("screen was already shared")));
1409        }
1410
1411        let (participant, publish_id) = if let Some(live_kit) = self.live_kit.as_mut() {
1412            let publish_id = post_inc(&mut live_kit.next_publish_id);
1413            live_kit.screen_track = LocalTrack::Pending { publish_id };
1414            cx.notify();
1415            (live_kit.room.local_participant(), publish_id)
1416        } else {
1417            return Task::ready(Err(anyhow!("live-kit was not initialized")));
1418        };
1419
1420        cx.spawn(async move |this, cx| {
1421            let publication = participant.publish_screenshare_track(&*source, cx).await;
1422
1423            this.update(cx, |this, cx| {
1424                let live_kit = this
1425                    .live_kit
1426                    .as_mut()
1427                    .context("live-kit was not initialized")?;
1428
1429                let canceled = if let LocalTrack::Pending {
1430                    publish_id: cur_publish_id,
1431                } = &live_kit.screen_track
1432                {
1433                    *cur_publish_id != publish_id
1434                } else {
1435                    true
1436                };
1437
1438                match publication {
1439                    Ok((publication, stream)) => {
1440                        if canceled {
1441                            cx.spawn(async move |_, cx| {
1442                                participant.unpublish_track(publication.sid(), cx).await
1443                            })
1444                            .detach()
1445                        } else {
1446                            live_kit.screen_track = LocalTrack::Published {
1447                                track_publication: publication,
1448                                _stream: stream,
1449                            };
1450                            cx.notify();
1451                        }
1452
1453                        Audio::play_sound(Sound::StartScreenshare, cx);
1454                        Ok(())
1455                    }
1456                    Err(error) => {
1457                        if canceled {
1458                            Ok(())
1459                        } else {
1460                            live_kit.screen_track = LocalTrack::None;
1461                            cx.notify();
1462                            Err(error)
1463                        }
1464                    }
1465                }
1466            })?
1467        })
1468    }
1469
1470    pub fn toggle_mute(&mut self, cx: &mut Context<Self>) {
1471        if let Some(live_kit) = self.live_kit.as_mut() {
1472            // When unmuting, undeafen if the user was deafened before.
1473            let was_deafened = live_kit.deafened;
1474            if live_kit.muted_by_user
1475                || live_kit.deafened
1476                || matches!(live_kit.microphone_track, LocalTrack::None)
1477            {
1478                live_kit.muted_by_user = false;
1479                live_kit.deafened = false;
1480            } else {
1481                live_kit.muted_by_user = true;
1482            }
1483            let muted = live_kit.muted_by_user;
1484            let should_undeafen = was_deafened && !live_kit.deafened;
1485
1486            if let Some(task) = self.set_mute(muted, cx) {
1487                task.detach_and_log_err(cx);
1488            }
1489
1490            if should_undeafen {
1491                self.set_deafened(false, cx);
1492            }
1493        }
1494    }
1495
1496    pub fn toggle_deafen(&mut self, cx: &mut Context<Self>) {
1497        if let Some(live_kit) = self.live_kit.as_mut() {
1498            // When deafening, mute the microphone if it was not already muted.
1499            // When un-deafening, unmute the microphone, unless it was explicitly muted.
1500            let deafened = !live_kit.deafened;
1501            live_kit.deafened = deafened;
1502            let should_change_mute = !live_kit.muted_by_user;
1503
1504            self.set_deafened(deafened, cx);
1505
1506            if should_change_mute && let Some(task) = self.set_mute(deafened, cx) {
1507                task.detach_and_log_err(cx);
1508            }
1509        }
1510    }
1511
1512    pub fn unshare_screen(&mut self, play_sound: bool, cx: &mut Context<Self>) -> Result<()> {
1513        anyhow::ensure!(!self.status.is_offline(), "room is offline");
1514
1515        let live_kit = self
1516            .live_kit
1517            .as_mut()
1518            .context("live-kit was not initialized")?;
1519        match mem::take(&mut live_kit.screen_track) {
1520            LocalTrack::None => anyhow::bail!("screen was not shared"),
1521            LocalTrack::Pending { .. } => {
1522                cx.notify();
1523                Ok(())
1524            }
1525            LocalTrack::Published {
1526                track_publication, ..
1527            } => {
1528                {
1529                    let local_participant = live_kit.room.local_participant();
1530                    let sid = track_publication.sid();
1531                    cx.spawn(async move |_, cx| local_participant.unpublish_track(sid, cx).await)
1532                        .detach_and_log_err(cx);
1533                    cx.notify();
1534                }
1535
1536                if play_sound {
1537                    Audio::play_sound(Sound::StopScreenshare, cx);
1538                }
1539
1540                Ok(())
1541            }
1542        }
1543    }
1544
1545    fn set_deafened(&mut self, deafened: bool, cx: &mut Context<Self>) -> Option<()> {
1546        {
1547            let live_kit = self.live_kit.as_mut()?;
1548            cx.notify();
1549            for (_, participant) in live_kit.room.remote_participants() {
1550                for (_, publication) in participant.track_publications() {
1551                    if publication.is_audio() {
1552                        publication.set_enabled(!deafened, cx);
1553                    }
1554                }
1555            }
1556        }
1557
1558        None
1559    }
1560
1561    fn set_mute(&mut self, should_mute: bool, cx: &mut Context<Room>) -> Option<Task<Result<()>>> {
1562        let live_kit = self.live_kit.as_mut()?;
1563        cx.notify();
1564
1565        if should_mute {
1566            Audio::play_sound(Sound::Mute, cx);
1567        } else {
1568            Audio::play_sound(Sound::Unmute, cx);
1569        }
1570
1571        match &mut live_kit.microphone_track {
1572            LocalTrack::None => {
1573                if should_mute {
1574                    None
1575                } else {
1576                    Some(self.share_microphone(cx))
1577                }
1578            }
1579            LocalTrack::Pending { .. } => None,
1580            LocalTrack::Published {
1581                track_publication, ..
1582            } => {
1583                let guard = Tokio::handle(cx);
1584                if should_mute {
1585                    track_publication.mute(cx)
1586                } else {
1587                    track_publication.unmute(cx)
1588                }
1589                drop(guard);
1590
1591                None
1592            }
1593        }
1594    }
1595}
1596
1597fn spawn_room_connection(
1598    livekit_connection_info: Option<proto::LiveKitConnectionInfo>,
1599    cx: &mut Context<Room>,
1600) {
1601    if let Some(connection_info) = livekit_connection_info {
1602        cx.spawn(async move |this, cx| {
1603            let (room, mut events) =
1604                livekit::Room::connect(connection_info.server_url, connection_info.token, cx)
1605                    .await?;
1606
1607            this.update(cx, |this, cx| {
1608                let _handle_updates = cx.spawn(async move |this, cx| {
1609                    while let Some(event) = events.next().await {
1610                        if this
1611                            .update(cx, |this, cx| {
1612                                this.livekit_room_updated(event, cx).warn_on_err();
1613                            })
1614                            .is_err()
1615                        {
1616                            break;
1617                        }
1618                    }
1619                });
1620
1621                let muted_by_user = Room::mute_on_join(cx);
1622                this.live_kit = Some(LiveKitRoom {
1623                    room: Rc::new(room),
1624                    screen_track: LocalTrack::None,
1625                    microphone_track: LocalTrack::None,
1626                    next_publish_id: 0,
1627                    muted_by_user,
1628                    deafened: false,
1629                    speaking: false,
1630                    _handle_updates,
1631                });
1632
1633                if !muted_by_user && this.can_use_microphone() {
1634                    this.share_microphone(cx)
1635                } else {
1636                    Task::ready(Ok(()))
1637                }
1638            })?
1639            .await
1640        })
1641        .detach_and_log_err(cx);
1642    }
1643}
1644
1645struct LiveKitRoom {
1646    room: Rc<livekit::Room>,
1647    screen_track: LocalTrack<dyn ScreenCaptureStream>,
1648    microphone_track: LocalTrack<AudioStream>,
1649    /// Tracks whether we're currently in a muted state due to auto-mute from deafening or manual mute performed by user.
1650    muted_by_user: bool,
1651    deafened: bool,
1652    speaking: bool,
1653    next_publish_id: usize,
1654    _handle_updates: Task<()>,
1655}
1656
1657impl LiveKitRoom {
1658    fn stop_publishing(&mut self, cx: &mut Context<Room>) {
1659        let mut tracks_to_unpublish = Vec::new();
1660        if let LocalTrack::Published {
1661            track_publication, ..
1662        } = mem::replace(&mut self.microphone_track, LocalTrack::None)
1663        {
1664            tracks_to_unpublish.push(track_publication.sid());
1665            cx.notify();
1666        }
1667
1668        if let LocalTrack::Published {
1669            track_publication, ..
1670        } = mem::replace(&mut self.screen_track, LocalTrack::None)
1671        {
1672            tracks_to_unpublish.push(track_publication.sid());
1673            cx.notify();
1674        }
1675
1676        let participant = self.room.local_participant();
1677        cx.spawn(async move |_, cx| {
1678            for sid in tracks_to_unpublish {
1679                participant.unpublish_track(sid, cx).await.log_err();
1680            }
1681        })
1682        .detach();
1683    }
1684}
1685
1686enum LocalTrack<Stream: ?Sized> {
1687    None,
1688    Pending {
1689        publish_id: usize,
1690    },
1691    Published {
1692        track_publication: LocalTrackPublication,
1693        _stream: Box<Stream>,
1694    },
1695}
1696
1697impl<T: ?Sized> Default for LocalTrack<T> {
1698    fn default() -> Self {
1699        Self::None
1700    }
1701}
1702
1703#[derive(Copy, Clone, PartialEq, Eq)]
1704pub enum RoomStatus {
1705    Online,
1706    Rejoining,
1707    Offline,
1708}
1709
1710impl RoomStatus {
1711    pub fn is_offline(&self) -> bool {
1712        matches!(self, RoomStatus::Offline)
1713    }
1714
1715    pub fn is_online(&self) -> bool {
1716        matches!(self, RoomStatus::Online)
1717    }
1718}