room.rs

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