BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / actions.rs

actions.rs

084d8c43 History
actions.rs 83.2 KiB Download Raw
1use std::time::{Duration, Instant};
2
3use calling::meeting::LiveMeeting;
4use calling::{
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
7};
8use gpui_kit::*;
9
10use super::background::{
11 BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds,
12};
13use super::demo::{
14 DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15 start_demo_scene_call,
16};
17use super::features::room_closed_move;
18use super::media::CallMedia;
19use super::mic::save_mic;
20use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
21use super::prejoin::{DemoMeeting, MeetingJoin};
22use super::ring::{MissedCall, RingOutcome};
23use super::target::{is_organizer, plan_for_chat};
24use crate::app_state::{AppEvent, AppState, Selection, chat_title};
25use crate::notify::selection_for;
26
27const TIMER_REFRESH: Duration = Duration::from_millis(500);
28const SHARE_SOURCES_EVERY_TICKS: u32 = 10;
29pub(super) const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";
30const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";
31const NOT_CALLABLE_NOTICE: &str = "This chat cannot be called";
32pub(super) const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";
33const ANSWER_FAILED_NOTICE: &str = "Could not answer the call";
34const MEETING_KIND: &str = "meeting";
35const DEMO_LOBBY_MEETING: &str = "demo-chat-meeting-retro";
36const DEMO_CROWD: usize = 11;
37const DEMO_SMALL_MEETING: usize = 4;
38const DEMO_LIVE_MINUTES: i64 = 60;
39const ORGID_PREFIX: &str = "8:orgid:";
40pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
41const CAMERA_META_KEY: &str = "call_camera";
42const EFFECTS_META_KEY: &str = "call_camera_effects";
43const DEFAULT_CAMERA_META: &str = "default";
44
45pub fn load_share_sound(store: &store::Store) -> bool {
46 store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
47}
48
49pub fn load_camera(store: &store::Store) -> DeviceChoice {
50 match store.meta(CAMERA_META_KEY).ok().flatten() {
51 Some(key) if !key.is_empty() && key != DEFAULT_CAMERA_META => DeviceChoice::Device(key),
52 _ => DeviceChoice::SystemDefault,
53 }
54}
55
56pub fn load_camera_effects(store: &store::Store) -> CameraEffects {
57 store
58 .meta(EFFECTS_META_KEY)
59 .ok()
60 .flatten()
61 .map_or_else(CameraEffects::default, |value| {
62 CameraEffects::from_meta(&value)
63 })
64}
65
66fn camera_meta(choice: &DeviceChoice) -> &str {
67 match choice {
68 DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,
69 DeviceChoice::Device(key) => key,
70 }
71}
72
73fn now_unix() -> i64 {
74 chrono::Utc::now().timestamp()
75}
76
77impl AppState {
78 pub fn start_test_call(&mut self, cx: &mut Context<Self>) {
79 if self.call.is_some() {
80 self.show_call(true, cx);
81 return;
82 }
83 let Some(handle) = self.place_call(CallSpec::Echo, DemoCall::Test, false, cx) else {
84 return;
85 };
86 self.begin_call(handle, CallModel::test(), None, cx);
87 }
88
89 pub fn start_chat_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
90 self.start_chat_call_with(conversation_id, false, cx);
91 }
92
93 pub fn start_chat_video_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
94 self.start_chat_call_with(conversation_id, true, cx);
95 }
96
97 fn start_chat_call_with(
98 &mut self,
99 conversation_id: &str,
100 with_video: bool,
101 cx: &mut Context<Self>,
102 ) {
103 if self.call.is_some() {
104 self.show_call(true, cx);
105 return;
106 }
107 let plan = self
108 .sidebar
109 .chats
110 .iter()
111 .find(|chat| chat.id == conversation_id)
112 .and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
113 let Some(plan) = plan else {
114 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
115 return;
116 };
117 let spec = CallSpec::People {
118 callees: plan
119 .callees
120 .iter()
121 .map(|(mri, name)| Callee {
122 mri: mri.clone(),
123 display_name: name.clone(),
124 })
125 .collect(),
126 thread_id: conversation_id.to_owned(),
127 };
128 let Some(handle) =
129 self.place_call(spec, DemoCall::People(plan.callees.clone()), with_video, cx)
130 else {
131 return;
132 };
133 let user_ids = plan
134 .callees
135 .iter()
136 .filter_map(|(mri, _)| mri.strip_prefix(ORGID_PREFIX).map(str::to_owned))
137 .collect();
138 self.request_avatars(user_ids, cx);
139 let model = CallModel::people(&plan.title, &plan.callees);
140 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
141 if with_video && self.mode.demo {
142 self.send_call_command(CallCommand::SetCamera(true));
143 }
144 }
145
146 pub fn join_meeting_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
147 if self.call.is_some() {
148 self.show_call(true, cx);
149 return;
150 }
151 let Some(meeting) = self.running_meeting(conversation_id).cloned() else {
152 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
153 return;
154 };
155 let Some(target) = meeting.target() else {
156 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
157 return;
158 };
159 let demo = DemoMeeting {
160 guests: if conversation_id == DEMO_LOBBY_MEETING {
161 DEMO_SMALL_MEETING
162 } else {
163 DEMO_CROWD
164 },
165 lobby: conversation_id == DEMO_LOBBY_MEETING,
166 organizer: conversation_id != DEMO_LOBBY_MEETING,
167 };
168 let title = selection_for(&self.sidebar, conversation_id)
169 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
170 .unwrap_or_else(|| "Meeting".to_owned());
171 let join = MeetingJoin {
172 organizer: is_organizer(&meeting, self.directory.me.as_ref()),
173 conversation_id: Some(conversation_id.to_owned()),
174 target,
175 title,
176 demo,
177 };
178 self.stage_meeting_join(join, cx);
179 }
180
181 pub(super) fn place_call(
182 &mut self,
183 spec: CallSpec,
184 demo: DemoCall,
185 with_video: bool,
186 cx: &mut Context<Self>,
187 ) -> Option<CallHandle> {
188 if self.mode.demo {
189 return Some(start_demo_call(demo));
190 }
191 if self.mode.read_only {
192 self.raise_notice(READ_ONLY_NOTICE.to_owned(), None, cx);
193 return None;
194 }
195 match self.call_launcher.clone() {
196 Some(launcher) if with_video => Some(launcher.start_video_call(spec)),
197 Some(launcher) => Some(launcher.start_call(spec)),
198 None => {
199 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
200 None
201 }
202 }
203 }
204
205 pub(super) fn begin_call(
206 &mut self,
207 handle: CallHandle,
208 model: CallModel,
209 conversation_id: Option<String>,
210 cx: &mut Context<Self>,
211 ) {
212 self.call_count += 1;
213 let call_id = self.call_count;
214 let CallHandle {
215 commands,
216 updates,
217 video,
218 } = handle;
219 self.call = Some(ActiveCall::new(
220 call_id,
221 model,
222 commands,
223 conversation_id,
224 video,
225 ));
226 if self.call_share_sound {
227 self.send_call_command(CallCommand::SetShareSound(true));
228 }
229 if self.call_share_motion {
230 self.send_call_command(CallCommand::SetShareMotion(true));
231 }
232 if self.call_share_standout {
233 self.send_call_command(CallCommand::SetShareStandout(true));
234 }
235 if self.call_mic != MicSettings::default() {
236 self.send_call_command(CallCommand::SetMicSettings(self.call_mic));
237 }
238 if let Some(call) = self.call.as_mut() {
239 call.model.background = self.call_background.clone();
240 call.model.camera = self.call_camera.clone();
241 call.model.view = self.call_view;
242 call.model.refresh_layout(Instant::now());
243 }
244 if self.call_camera != DeviceChoice::SystemDefault {
245 self.send_call_command(CallCommand::SelectCamera(self.call_camera.clone()));
246 }
247 if self.call_background != BackgroundPick::None {
248 self.send_background_command(cx);
249 }
250 self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));
251 self.refresh_call_backgrounds(cx);
252 self.new_chat = false;
253 self.follow_call(call_id, updates, cx);
254 cx.emit(AppEvent::Call);
255 cx.notify();
256 }
257
258 fn follow_call(
259 &mut self,
260 call_id: u64,
261 mut updates: tokio::sync::mpsc::UnboundedReceiver<CallUpdate>,
262 cx: &mut Context<Self>,
263 ) {
264 cx.spawn(async move |this, cx| {
265 while let Some(update) = updates.recv().await {
266 let alive =
267 this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));
268 if alive.is_err() {
269 return;
270 }
271 }
272 let _ = this.update(cx, |state, cx| state.end_orphaned_call(call_id, cx));
273 })
274 .detach();
275 cx.spawn(async move |this, cx| {
276 let mut ticks = 0u32;
277 loop {
278 cx.background_executor().timer(TIMER_REFRESH).await;
279 ticks += 1;
280 let running = this.update(cx, |state, cx| {
281 let running = state.call.as_ref().is_some_and(|call| call.id == call_id);
282 if running {
283 if ticks.is_multiple_of(SHARE_SOURCES_EVERY_TICKS) {
284 state.refresh_share_sources();
285 }
286 state.tick_call_layout(cx);
287 CallMedia::changed(&state.call_media, cx);
288 }
289 running
290 });
291 if !running.unwrap_or(false) {
292 return;
293 }
294 }
295 })
296 .detach();
297 }
298
299 fn end_orphaned_call(&mut self, call_id: u64, cx: &mut Context<Self>) {
300 let still_open = self
301 .call
302 .as_ref()
303 .is_some_and(|call| call.id == call_id && call.model.is_active());
304 if still_open {
305 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
306 self.apply_call_update(call_id, CallUpdate::State(CallState::Ended { reason }), cx);
307 }
308 }
309
310 pub(super) fn apply_call_update(
311 &mut self,
312 call_id: u64,
313 update: CallUpdate,
314 cx: &mut Context<Self>,
315 ) {
316 let media = self.call_media.clone();
317 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
318 return;
319 };
320 match update {
321 CallUpdate::VideoReady => {
322 call.pictures.apply(&call.video, cx);
323 CallMedia::changed(&media, cx);
324 return;
325 }
326 CallUpdate::Stats { .. } => return,
327 CallUpdate::Levels { local, remote } => {
328 let before = (call.model.local_speaking, call.model.remote_speaking);
329 call.model.apply(CallUpdate::Levels { local, remote });
330 if before != (call.model.local_speaking, call.model.remote_speaking) {
331 CallMedia::changed(&media, cx);
332 }
333 return;
334 }
335 CallUpdate::Notice(text) => {
336 self.raise_notice(text, None, cx);
337 return;
338 }
339 CallUpdate::WhiteboardUrl(url) => {
340 cx.open_url(&url);
341 return;
342 }
343 CallUpdate::BreakoutMove(moved) => {
344 self.begin_breakout_move(moved, cx);
345 return;
346 }
347 CallUpdate::MeetingOptions(result) => {
348 if let Some(dialog) = call.options_dialog.as_mut() {
349 dialog.loaded(result);
350 }
351 cx.notify();
352 return;
353 }
354 CallUpdate::MeetingOptionsSaved(result) => {
355 if call.options_dialog.as_mut().is_some_and(|dialog| dialog.saved(result)) {
356 call.options_dialog = None;
357 }
358 cx.notify();
359 return;
360 }
361 _ => {}
362 }
363 if let (CallUpdate::Caption(entry), Some(thread)) = (&update, call.chat_thread()) {
364 let speaker = if entry.display_name.is_empty() {
365 "Someone"
366 } else {
367 &entry.display_name
368 };
369 crate::agent_api::note_caption(thread, &entry.id, speaker, &entry.text, cx);
370 }
371 call.model.apply(update);
372 if let Some(language) = call.model.take_ready_caption_language() {
373 let _ = call.commands.send(CallCommand::SetCaptionLanguage(language));
374 }
375 if call.model.screen_sharer.is_none() {
376 call.stage_fullscreen = false;
377 call.share_stage.end();
378 call.pictures.forget(&VideoKey::Screen, cx);
379 }
380 if !call.model.camera_on {
381 call.pictures.forget(&VideoKey::LocalCamera, cx);
382 }
383 let Some(reason) = call.model.ended_reason().cloned() else {
384 cx.emit(AppEvent::Call);
385 cx.notify();
386 return;
387 };
388 let elapsed = call.model.elapsed(Instant::now());
389 let notice = ended_notice(&reason, elapsed, &call.model.peer_name);
390 let next_move = call
391 .pending_move
392 .take()
393 .or_else(|| room_closed_move(call, &reason));
394 let consult = call.consult.take();
395 call.pictures.clear(cx);
396 if let Some(thread) = call.chat_thread() {
397 crate::agent_api::clear_captions(thread, cx);
398 }
399 self.call = None;
400 self.transcript_panel = None;
401 if let Some(consult) = consult {
402 let _ = consult.commands.send(CallCommand::Hangup);
403 }
404 match next_move {
405 Some(next_move) => self.join_moved_call(next_move, cx),
406 None => self.raise_notice(notice, None, cx),
407 }
408 self.refresh_call_history_after_call(cx);
409 cx.emit(AppEvent::Call);
410 cx.notify();
411 }
412
413 pub(super) fn send_call_command(&self, command: CallCommand) {
414 if let Some(call) = &self.call {
415 let _ = call.commands.send(command);
416 }
417 }
418
419 pub fn toggle_call_mute(&mut self, _cx: &mut Context<Self>) {
420 let can_toggle = self
421 .call
422 .as_ref()
423 .is_some_and(|call| call.model.can_unmute());
424 if can_toggle {
425 self.send_call_command(CallCommand::Mute(MuteCommand::Toggle));
426 }
427 }
428
429 pub fn toggle_call_camera(&mut self, _cx: &mut Context<Self>) {
430 let Some(call) = self
431 .call
432 .as_ref()
433 .filter(|call| call.model.can_use_camera())
434 else {
435 return;
436 };
437 let on = !call.model.camera_on;
438 self.send_call_command(CallCommand::SetCamera(on));
439 }
440
441 pub fn set_call_mic(&mut self, settings: MicSettings, cx: &mut Context<Self>) {
442 self.call_mic = settings;
443 save_mic(&self.store, settings);
444 self.send_call_command(CallCommand::SetMicSettings(settings));
445 cx.notify();
446 }
447
448 pub fn press_push_to_talk(&mut self, _cx: &mut Context<Self>) {
449 let Some(call) = self.call.as_mut() else {
450 return;
451 };
452 let command = call
453 .push_to_talk
454 .press(call.model.muted, call.model.can_unmute());
455 if let Some(command) = command {
456 self.send_call_command(CallCommand::Mute(command));
457 }
458 }
459
460 pub fn release_push_to_talk(&mut self, _cx: &mut Context<Self>) {
461 let command = self
462 .call
463 .as_mut()
464 .and_then(|call| call.push_to_talk.release());
465 if let Some(command) = command {
466 self.send_call_command(CallCommand::Mute(command));
467 }
468 }
469
470 pub fn select_call_camera(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
471 let _ = self.store.set_meta(CAMERA_META_KEY, camera_meta(&choice));
472 self.call_camera = choice.clone();
473 if let Some(launcher) = &self.call_launcher {
474 launcher.set_default_camera(choice.clone());
475 }
476 if let Some(call) = self.call.as_mut() {
477 call.model.camera = choice.clone();
478 }
479 self.send_call_command(CallCommand::SelectCamera(choice));
480 }
481
482 pub fn start_call_share(&mut self, source: ShareSource, _cx: &mut Context<Self>) {
483 self.send_call_command(CallCommand::StartShare(source));
484 }
485
486 pub fn stop_call_share(&mut self, _cx: &mut Context<Self>) {
487 self.send_call_command(CallCommand::StopShare);
488 }
489
490 pub fn refresh_share_sources(&self) {
491 let idle = self
492 .call
493 .as_ref()
494 .is_some_and(|call| call.model.local_share.is_none());
495 if idle {
496 self.send_call_command(CallCommand::RefreshShareSources);
497 }
498 }
499
500 pub fn leave_call(&mut self, _cx: &mut Context<Self>) {
501 self.send_call_command(CallCommand::Hangup);
502 }
503
504 pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {
505 let allowed = self
506 .call
507 .as_ref()
508 .is_some_and(|call| call.model.can_end_meeting);
509 if allowed {
510 self.send_call_command(CallCommand::EndMeeting);
511 }
512 }
513
514 pub fn select_call_input(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
515 self.send_call_command(CallCommand::SelectInput(choice));
516 }
517
518 pub fn select_call_output(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
519 self.send_call_command(CallCommand::SelectOutput(choice));
520 }
521
522 pub fn show_call(&mut self, viewing: bool, cx: &mut Context<Self>) {
523 let Some(call) = self.call.as_mut().filter(|call| call.viewing != viewing) else {
524 return;
525 };
526 call.viewing = viewing;
527 if viewing {
528 self.new_chat = false;
529 }
530 cx.emit(AppEvent::Call);
531 cx.notify();
532 }
533
534 pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {
535 let Some(call) = self
536 .call
537 .as_mut()
538 .filter(|call| call.chat_thread().is_some())
539 else {
540 return;
541 };
542 call.chat_open = !call.chat_open;
543 if call.chat_open {
544 call.transcript_open = false;
545 self.transcript_panel = None;
546 call.people_open = false;
547 }
548 cx.emit(AppEvent::Call);
549 cx.notify();
550 }
551
552 pub fn call_chat_thread(&self) -> Option<String> {
553 let call = self.call.as_ref().filter(|call| call.chat_open)?;
554 call.chat_thread().map(str::to_owned)
555 }
556
557 pub fn call_chat_unread(&self) -> u32 {
558 let Some(thread) = self
559 .call
560 .as_ref()
561 .filter(|call| !call.chat_open)
562 .and_then(|call| call.chat_thread())
563 else {
564 return 0;
565 };
566 let counted = self.directory.unread_counts.get(thread).copied();
567 counted.unwrap_or_else(|| {
568 u32::from(
569 self.sidebar
570 .chats
571 .iter()
572 .any(|chat| chat.id == thread && chat.unread),
573 )
574 })
575 }
576
577 pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {
578 let Some(call) = self
579 .call
580 .as_mut()
581 .filter(|call| call.model.is_active() && call.model.has_reaction_controls())
582 else {
583 return;
584 };
585 let raised = call.model.own_hand.is_none();
586 call.model.own_hand = raised.then_some(u64::MAX);
587 self.send_call_command(CallCommand::SetHand(raised));
588 if raised {
589 self.raise_notice("Your hand is raised".to_owned(), None, cx);
590 }
591 cx.emit(AppEvent::Call);
592 cx.notify();
593 }
594
595 pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {
596 let allowed = self
597 .call
598 .as_ref()
599 .is_some_and(|call| call.model.can_lower_hands());
600 if allowed {
601 self.send_call_command(CallCommand::LowerHand { mri });
602 }
603 }
604
605 pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {
606 let allowed = self
607 .call
608 .as_ref()
609 .is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());
610 if allowed {
611 self.send_call_command(CallCommand::LowerAllHands);
612 }
613 }
614
615 pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {
616 let Some(call) = self
617 .call
618 .as_mut()
619 .filter(|call| call.model.is_active() && call.model.has_reaction_controls())
620 else {
621 return;
622 };
623 if let Some(own_mri) = call.model.own_mri.clone() {
624 call.model.note_reaction(own_mri, reaction, Instant::now());
625 }
626 self.send_call_command(CallCommand::SendReaction(reaction));
627 cx.emit(AppEvent::Call);
628 cx.notify();
629 }
630
631 pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {
632 self.call_share_sound = on;
633 let _ = self
634 .store
635 .set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });
636 self.send_call_command(CallCommand::SetShareSound(on));
637 cx.notify();
638 }
639
640 pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
641 if self
642 .call
643 .as_ref()
644 .is_some_and(|call| call.model.can_admit())
645 {
646 self.send_call_command(CallCommand::Admit { mri });
647 }
648 }
649
650 pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {
651 if self
652 .call
653 .as_ref()
654 .is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty())
655 {
656 self.send_call_command(CallCommand::AdmitAll);
657 }
658 }
659
660 pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
661 if self
662 .call
663 .as_ref()
664 .is_some_and(|call| call.model.can_admit())
665 {
666 self.send_call_command(CallCommand::Deny { mri });
667 }
668 }
669
670 pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
671 if self
672 .call
673 .as_ref()
674 .is_some_and(|call| call.model.can_manage())
675 {
676 self.send_call_command(CallCommand::MuteParticipant { mri });
677 }
678 }
679
680 pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {
681 if self
682 .call
683 .as_ref()
684 .is_some_and(|call| call.model.can_manage())
685 {
686 self.send_call_command(CallCommand::MuteAll);
687 }
688 }
689
690 pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
691 if self
692 .call
693 .as_ref()
694 .is_some_and(|call| call.model.can_manage())
695 {
696 self.send_call_command(CallCommand::RemoveParticipant { mri });
697 }
698 }
699
700 pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {
701 let Some(call) = self
702 .call
703 .as_ref()
704 .filter(|call| call.model.can_manage() && call.model.is_active())
705 else {
706 return;
707 };
708 let command = if call.model.is_spotlighted(&mri) {
709 CallCommand::StopSpotlight { mri }
710 } else {
711 CallCommand::Spotlight { mri }
712 };
713 self.send_call_command(command);
714 }
715
716 pub fn toggle_call_pin(&mut self, mri: &str, cx: &mut Context<Self>) {
717 if let Some(call) = self.call.as_mut() {
718 call.model.toggle_pin(mri);
719 cx.notify();
720 }
721 }
722
723 pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {
724 let Some(call) = self
725 .call
726 .as_ref()
727 .filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting)
728 else {
729 return;
730 };
731 let on = !call.model.captions_on();
732 self.send_call_command(CallCommand::SetCaptions(on));
733 }
734
735 pub fn set_call_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {
736 let _ = self.store.set_meta(EFFECTS_META_KEY, &effects.to_meta());
737 self.call_effects = effects;
738 self.send_call_command(CallCommand::SetCameraEffects(effects));
739 cx.notify();
740 }
741
742 pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
743 let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
744 self.call_background = pick.clone();
745 if let Some(call) = self.call.as_mut() {
746 call.model.background = pick;
747 }
748 self.send_background_command(cx);
749 cx.notify();
750 }
751
752 pub(super) fn send_background_command(&mut self, cx: &mut Context<Self>) {
753 let pick = self.call_background.clone();
754 if let Some(choice) = self.call_backgrounds.choice_for(&pick) {
755 self.send_call_command(CallCommand::SetBackground(choice));
756 return;
757 }
758 let BackgroundPick::Default(id) = pick else {
759 return;
760 };
761 let Some(image) = self.call_backgrounds.find(&id).cloned() else {
762 return;
763 };
764 let Some(launcher) = self.call_launcher.clone() else {
765 return;
766 };
767 let cache = self.call_backgrounds.cache.clone();
768 let receiver =
769 crate::runtime::spawn(
770 async move { launcher.download_background(&cache, &image).await },
771 );
772 cx.spawn(async move |this, cx| {
773 let path = receiver.await.ok().flatten();
774 this.update(cx, |state, cx| match path {
775 Some(path) if state.call_background == BackgroundPick::Default(id) => {
776 state.send_call_command(CallCommand::SetBackground(
777 calling::BackgroundChoice::Image(path),
778 ));
779 }
780 Some(_) => {}
781 None => state.raise_notice(
782 "That background could not be downloaded".to_owned(),
783 None,
784 cx,
785 ),
786 })
787 .ok();
788 })
789 .detach();
790 }
791
792 pub fn refresh_call_backgrounds(&mut self, cx: &mut Context<Self>) {
793 if self.mode.demo || !self.call_backgrounds.needs_refresh() {
794 return;
795 }
796 let Some(launcher) = self.call_launcher.clone() else {
797 return;
798 };
799 self.call_backgrounds.refreshing = true;
800 let cache = self.call_backgrounds.cache.clone();
801 let wanted = SHOWN_IMAGES;
802 let receiver =
803 crate::runtime::spawn(
804 async move { launcher.refresh_backgrounds(&cache, wanted).await },
805 );
806 cx.spawn(async move |this, cx| {
807 let catalog = receiver.await.ok().flatten();
808 this.update(cx, |state, cx| {
809 state.call_backgrounds.refreshing = false;
810 if let Some(catalog) = catalog {
811 state.call_backgrounds.images = catalog;
812 }
813 cx.notify();
814 })
815 .ok();
816 })
817 .detach();
818 }
819
820 pub fn add_call_background(&mut self, cx: &mut Context<Self>) {
821 let receiver = cx.prompt_for_paths(PathPromptOptions {
822 files: true,
823 directories: false,
824 multiple: false,
825 prompt: None,
826 });
827 cx.spawn(async move |this, cx| {
828 let Some(path) = receiver
829 .await
830 .ok()
831 .and_then(Result::ok)
832 .flatten()
833 .and_then(|paths| paths.into_iter().next())
834 else {
835 return;
836 };
837 this.update(cx, |state, cx| {
838 if !is_image_file(&path) {
839 state.raise_notice("Pick a JPG or PNG picture".to_owned(), None, cx);
840 return;
841 }
842 state.call_backgrounds.add_custom(path.clone());
843 save_custom_backgrounds(&state.store, &state.call_backgrounds.customs);
844 state.set_call_background(BackgroundPick::Custom(path), cx);
845 })
846 .ok();
847 })
848 .detach();
849 }
850
851 pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
852 let Some(call) = self
853 .call
854 .as_mut()
855 .filter(|call| call.model.screen_sharer.is_some())
856 else {
857 return;
858 };
859 call.stage_fullscreen = !call.stage_fullscreen;
860 cx.emit(AppEvent::Call);
861 cx.notify();
862 }
863
864 pub fn leave_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
865 let Some(call) = self.call.as_mut().filter(|call| call.stage_fullscreen) else {
866 return;
867 };
868 call.stage_fullscreen = false;
869 cx.emit(AppEvent::Call);
870 cx.notify();
871 }
872
873 pub fn stage_fullscreen(&self) -> bool {
874 self.call
875 .as_ref()
876 .is_some_and(|call| call.stage_fullscreen && call.model.screen_sharer.is_some())
877 }
878
879 pub fn viewing_call(&self) -> bool {
880 self.call.as_ref().is_some_and(|call| call.viewing)
881 }
882}
883
884impl AppState {
885 pub fn on_engine_event(&mut self, event: EngineEvent, cx: &mut Context<Self>) {
886 match event {
887 EngineEvent::Incoming(ring) => self.push_ring(ring, false, cx),
888 EngineEvent::RingEnded { ring_id, kind, .. } => {
889 self.signal_ring(ring_id, RingSignal::Remote(kind), cx);
890 }
891 }
892 }
893
894 fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {
895 let caller_user_id = ring
896 .caller
897 .mri
898 .strip_prefix(ORGID_PREFIX)
899 .map(str::to_owned);
900 self.rings.push(ring, demo, Instant::now());
901 if let Some(user_id) = caller_user_id {
902 self.request_avatars(vec![user_id], cx);
903 }
904 cx.emit(AppEvent::Ring);
905 cx.notify();
906 }
907
908 pub fn demo_incoming_ring(&mut self, cx: &mut Context<Self>) {
909 self.push_ring(demo_ring(), true, cx);
910 }
911
912 pub fn demo_incoming_video_ring(&mut self, cx: &mut Context<Self>) {
913 self.push_ring(demo_video_ring(), true, cx);
914 }
915
916 pub fn start_demo_scene(&mut self, scene: DemoScene, cx: &mut Context<Self>) {
917 if self.call.is_some() {
918 return;
919 }
920 let (script, model, conversation_id) = if scene.is_one_to_one() {
921 (
922 DemoCall::People(vec![demo_caller()]),
923 CallModel::people("Mara Lindqvist", &[demo_caller()]),
924 "demo-chat-mara",
925 )
926 } else {
927 let script = DemoCall::Meeting {
928 guests: demo_guests(scene.guests().unwrap_or(DEMO_SMALL_MEETING)),
929 lobby: false,
930 organizer: true,
931 };
932 (
933 script,
934 CallModel::meeting("Standup", true),
935 "demo-chat-meeting-standup",
936 )
937 };
938 let handle = start_demo_scene_call(script, scene);
939 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
940 if let Some(call) = self.call.as_mut().filter(|_| !scene.is_one_to_one()) {
941 call.meeting_target = Some(calling::MeetingTarget {
942 thread_id: conversation_id.to_owned(),
943 tenant_id: "demo-tenant".to_owned(),
944 organizer_id: "demo-me".to_owned(),
945 meeting_data: None,
946 });
947 }
948 if scene == DemoScene::Gallery {
949 self.queue_demo_bubbles(conversation_id, cx);
950 }
951 }
952
953 fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {
954 if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {
955 self.finish_ring(ring_id, outcome, cx);
956 }
957 }
958
959 fn finish_ring(&mut self, ring_id: u64, outcome: RingOutcome, cx: &mut Context<Self>) {
960 if let RingOutcome::Missed(missed) = outcome {
961 if let Some(launcher) = &self.call_launcher {
962 launcher.drop_ring(ring_id);
963 }
964 cx.emit(AppEvent::MissedCall(missed));
965 }
966 cx.emit(AppEvent::Ring);
967 cx.notify();
968 }
969
970 pub fn tick_rings(&mut self, cx: &mut Context<Self>) {
971 if self.rings.is_empty() {
972 return;
973 }
974 for (ring_id, outcome) in self.rings.tick(Instant::now()) {
975 self.finish_ring(ring_id, outcome, cx);
976 }
977 }
978
979 pub fn accept_ringing_call(&mut self, cx: &mut Context<Self>) {
980 if let Some(ring_id) = self.rings.first_ringing_id() {
981 self.accept_ring(ring_id, AcceptMode::Audio, cx);
982 }
983 }
984
985 pub fn decline_ringing_call(&mut self, cx: &mut Context<Self>) {
986 if let Some(ring_id) = self.rings.first_ringing_id() {
987 self.decline_ring(ring_id, cx);
988 }
989 }
990
991 pub fn accept_ring(&mut self, ring_id: u64, mode: AcceptMode, cx: &mut Context<Self>) {
992 let Some(entry) = self.rings.get(ring_id).cloned() else {
993 return;
994 };
995 if self.call.is_some() {
996 self.leave_call(cx);
997 }
998 self.signal_ring(ring_id, RingSignal::Accept, cx);
999 let conversation_id = entry.ring.thread_id.clone();
1000 let title = conversation_id
1001 .as_deref()
1002 .and_then(|id| self.sidebar.chats.iter().find(|chat| chat.id == id))
1003 .filter(|_| entry.ring.is_group)
1004 .map(chat_title)
1005 .unwrap_or_else(|| entry.caller_name().to_owned());
1006 let model = CallModel::incoming(&title, &entry.ring.caller.mri, entry.caller_name());
1007 if entry.demo {
1008 let handle = start_demo_call(DemoCall::Incoming(demo_caller()));
1009 self.begin_call(handle, model, conversation_id, cx);
1010 if mode == AcceptMode::Video {
1011 self.send_call_command(CallCommand::SetCamera(true));
1012 }
1013 return;
1014 }
1015 let Some(launcher) = self.call_launcher.clone() else {
1016 self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
1017 return;
1018 };
1019 let receiver =
1020 crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });
1021 cx.spawn(async move |this, cx| {
1022 let handle = receiver.await.ok().flatten();
1023 this.update(cx, |state, cx| match handle {
1024 Some(handle) => state.begin_call(handle, model, conversation_id, cx),
1025 None => state.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx),
1026 })
1027 .ok();
1028 })
1029 .detach();
1030 }
1031
1032 pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
1033 let Some(entry) = self.rings.get(ring_id) else {
1034 return;
1035 };
1036 let demo = entry.demo;
1037 if !demo && let Some(launcher) = &self.call_launcher {
1038 launcher.decline_ring(ring_id);
1039 }
1040 self.signal_ring(ring_id, RingSignal::Decline, cx);
1041 }
1042
1043 pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {
1044 if let Some(thread_id) = missed
1045 .thread_id
1046 .as_ref()
1047 .filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id))
1048 {
1049 return Some(thread_id.clone());
1050 }
1051 let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;
1052 self.sidebar
1053 .chats
1054 .iter()
1055 .find(|chat| {
1056 crate::data::is_one_on_one(chat)
1057 && chat
1058 .members
1059 .iter()
1060 .any(|member| member.user_id.as_deref() == Some(user_id))
1061 })
1062 .map(|chat| chat.id.clone())
1063 }
1064}
1065
1066impl AppState {
1067 pub fn running_meeting(&self, conversation_id: &str) -> Option<&LiveMeeting> {
1068 self.live_meetings
1069 .get(conversation_id)
1070 .filter(|meeting| meeting.is_running(now_unix()) && meeting.target().is_some())
1071 }
1072
1073 pub fn demo_live_meetings(&mut self) {
1074 for conversation_id in ["demo-chat-meeting-standup", DEMO_LOBBY_MEETING] {
1075 self.live_meetings.insert(
1076 conversation_id.to_owned(),
1077 LiveMeeting {
1078 thread_id: conversation_id.to_owned(),
1079 conversation_url: None,
1080 expiration: Some(now_unix() + DEMO_LIVE_MINUTES * 60),
1081 organizer_id: Some("demo-jonas".to_owned()),
1082 tenant_id: Some("demo-tenant".to_owned()),
1083 meeting_code: None,
1084 passcode: None,
1085 },
1086 );
1087 }
1088 }
1089
1090 pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {
1091 let meeting_chat =
1092 self.sidebar.chats.iter().any(|chat| {
1093 chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND)
1094 });
1095 meeting_chat
1096 || matches!(
1097 selection_for(&self.sidebar, conversation_id),
1098 Some(Selection::Channel(_))
1099 )
1100 }
1101
1102 pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1103 if self.mode.demo || !self.watches_live_meeting(conversation_id) {
1104 return;
1105 }
1106 let Some(launcher) = self.call_launcher.clone() else {
1107 return;
1108 };
1109 if !self.live_refreshing.insert(conversation_id.to_owned()) {
1110 return;
1111 }
1112 let thread_id = conversation_id.to_owned();
1113 let receiver =
1114 crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
1115 let conversation_id = conversation_id.to_owned();
1116 cx.spawn(async move |this, cx| {
1117 let meeting = receiver.await.ok().flatten();
1118 this.update(cx, |state, cx| {
1119 state.apply_live_meeting(conversation_id, meeting, cx)
1120 })
1121 .ok();
1122 })
1123 .detach();
1124 }
1125
1126 pub fn apply_live_meeting(
1127 &mut self,
1128 conversation_id: String,
1129 meeting: Option<LiveMeeting>,
1130 cx: &mut Context<Self>,
1131 ) {
1132 self.live_refreshing.remove(&conversation_id);
1133 let changed = match meeting {
1134 Some(meeting) => {
1135 self.live_meetings
1136 .insert(conversation_id.clone(), meeting.clone())
1137 != Some(meeting)
1138 }
1139 None => self.live_meetings.remove(&conversation_id).is_some(),
1140 };
1141 if changed {
1142 cx.emit(AppEvent::LiveMeeting);
1143 cx.notify();
1144 }
1145 }
1146
1147 pub fn on_thread_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1148 self.refresh_live_meeting(conversation_id, cx);
1149 }
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154 use std::sync::Arc;
1155 use std::time::{Duration, Instant};
1156
1157 use std::path::PathBuf;
1158
1159 use calling::{
1160 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1161 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, RecordingKind,
1162 StopScope, call_channel,
1163 };
1164 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1165 use store::{ChatRecord, MemberRecord, Store};
1166
1167 use super::{ActiveCall, CallModel, load_camera, load_camera_effects};
1168 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1169 use crate::call::TransferCandidate;
1170 use crate::call::background::BackgroundPick;
1171 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1172 use crate::call::demo::demo_ring;
1173 use crate::call::features::room_closed_move;
1174 use crate::call::model::{BreakoutState, ConsultCall};
1175 use crate::data::Person;
1176
1177 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1178 cx.update(gpui_kit::init);
1179 let store = Arc::new(Store::open_in_memory().unwrap());
1180 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1181 let (handle, _control) = call_channel();
1182 cx.update(|cx| {
1183 app.update(cx, |state, _| {
1184 state.call = Some(ActiveCall::new(
1185 7,
1186 CallModel::test(),
1187 handle.commands,
1188 None,
1189 handle.video,
1190 ));
1191 })
1192 });
1193 app
1194 }
1195
1196 fn app_with_commands(
1197 cx: &mut TestAppContext,
1198 model: CallModel,
1199 conversation_id: Option<&str>,
1200 ) -> (Entity<AppState>, CallControl) {
1201 cx.update(gpui_kit::init);
1202 let store = Arc::new(Store::open_in_memory().unwrap());
1203 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1204 let (handle, control) = call_channel();
1205 let conversation_id = conversation_id.map(str::to_owned);
1206 cx.update(|cx| {
1207 app.update(cx, |state, _| {
1208 state.call = Some(ActiveCall::new(
1209 7,
1210 model,
1211 handle.commands,
1212 conversation_id,
1213 handle.video,
1214 ));
1215 })
1216 });
1217 (app, control)
1218 }
1219
1220 fn live_meeting(can_end: bool) -> CallModel {
1221 let mut model = CallModel::meeting("Standup", can_end);
1222 model.apply(CallUpdate::State(CallState::Connected {
1223 since: Instant::now(),
1224 }));
1225 model.apply(CallUpdate::OwnIdentity {
1226 mri: "8:orgid:me".into(),
1227 });
1228 model
1229 }
1230
1231 #[gpui_kit::test]
1232 fn high_rate_updates_do_not_emit_call_events(cx: &mut TestAppContext) {
1233 let app = app_with_call(cx);
1234 let emitted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1235 let counter = emitted.clone();
1236 cx.update(|cx| {
1237 cx.subscribe(&app, move |_, event: &AppEvent, _| {
1238 if matches!(event, AppEvent::Call) {
1239 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1240 }
1241 })
1242 .detach();
1243 app.update(cx, |state, cx| {
1244 state.apply_call_update(7, CallUpdate::VideoReady, cx);
1245 state.apply_call_update(
1246 7,
1247 CallUpdate::Levels {
1248 local: 0.5,
1249 remote: 0.5,
1250 },
1251 cx,
1252 );
1253 state.apply_call_update(
1254 7,
1255 CallUpdate::Stats {
1256 inbound_packets: 1,
1257 outbound_packets: 1,
1258 },
1259 cx,
1260 );
1261 });
1262 });
1263 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);
1264 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));
1265 cx.update(|cx| {
1266 app.update(cx, |state, cx| {
1267 state.apply_call_update(7, CallUpdate::Muted(true), cx)
1268 })
1269 });
1270 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);
1271 }
1272
1273 #[gpui_kit::test]
1274 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1275 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1276 let store = cx.update(|cx| app.read(cx).store.clone());
1277 assert!(!cx.update(|cx| app.read(cx).call_share_sound));
1278 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));
1279 assert_eq!(
1280 control.try_recv_command(),
1281 Some(CallCommand::SetShareSound(true))
1282 );
1283 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1284 assert!(cx.update(|cx| reopened.read(cx).call_share_sound));
1285 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));
1286 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1287 assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));
1288 }
1289
1290 #[gpui_kit::test]
1291 fn the_camera_pick_is_remembered_and_the_next_call_starts_with_it(cx: &mut TestAppContext) {
1292 let (app, _control) = app_with_commands(cx, live_meeting(false), None);
1293 let store = cx.update(|cx| app.read(cx).store.clone());
1294 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1295 cx.update(|cx| {
1296 app.update(cx, |state, cx| {
1297 state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)
1298 })
1299 });
1300 assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));
1301 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1302 assert_eq!(
1303 cx.update(|cx| reopened.read(cx).call_camera.clone()),
1304 DeviceChoice::Device("cam-2".into())
1305 );
1306 cx.update(|cx| {
1307 app.update(cx, |state, cx| {
1308 state.select_call_camera(DeviceChoice::SystemDefault, cx)
1309 })
1310 });
1311 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1312 }
1313
1314 #[gpui_kit::test]
1315 fn the_camera_effects_are_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1316 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1317 let store = cx.update(|cx| app.read(cx).store.clone());
1318 assert_eq!(load_camera_effects(&store), CameraEffects::default());
1319 let effects = CameraEffects {
1320 mirror: false,
1321 auto_framing: true,
1322 soft_focus: true,
1323 soft_focus_strength: 75,
1324 ..CameraEffects::default()
1325 };
1326 cx.update(|cx| app.update(cx, |state, cx| state.set_call_effects(effects, cx)));
1327 assert_eq!(
1328 control.try_recv_command(),
1329 Some(CallCommand::SetCameraEffects(effects))
1330 );
1331 assert_eq!(load_camera_effects(&store), effects);
1332 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1333 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1334 }
1335
1336 #[gpui_kit::test]
1337 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1338 cx: &mut TestAppContext,
1339 ) {
1340 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1341 cx.update(|cx| {
1342 app.update(cx, |state, cx| {
1343 state.toggle_call_hand(cx);
1344 state.send_call_reaction(Reaction::Heart, cx);
1345 state.lower_call_hand("8:orgid:a".into(), cx);
1346 state.lower_all_call_hands(cx);
1347 })
1348 });
1349 assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));
1350 assert_eq!(
1351 control.try_recv_command(),
1352 Some(CallCommand::SendReaction(Reaction::Heart))
1353 );
1354 assert_eq!(control.try_recv_command(), None);
1355 let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);
1356 cx.update(|cx| {
1357 organizer.update(cx, |state, cx| {
1358 state.apply_call_update(
1359 7,
1360 CallUpdate::Roster(vec![calling::RosterEntry {
1361 mri: "8:orgid:a".into(),
1362 display_name: "Ana".into(),
1363 muted: false,
1364 in_lobby: false,
1365 has_video: false,
1366 sharing: false,
1367 hand: Some(calling::RaisedHand {
1368 state_id: "s".into(),
1369 rank: 1,
1370 }),
1371 spotlight: None,
1372 organizer: false,
1373 ..Default::default()
1374 }]),
1375 cx,
1376 );
1377 state.lower_call_hand("8:orgid:a".into(), cx);
1378 state.lower_all_call_hands(cx);
1379 })
1380 });
1381 assert_eq!(
1382 organizer_control.try_recv_command(),
1383 Some(CallCommand::LowerHand {
1384 mri: "8:orgid:a".into()
1385 })
1386 );
1387 assert_eq!(
1388 organizer_control.try_recv_command(),
1389 Some(CallCommand::LowerAllHands)
1390 );
1391 }
1392
1393 fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {
1394 calling::RosterEntry {
1395 mri: mri.into(),
1396 display_name: name.into(),
1397 muted: false,
1398 in_lobby,
1399 has_video: false,
1400 sharing: false,
1401 hand: None,
1402 spotlight: spotlit.then(|| calling::Spotlight {
1403 state_id: "sp".into(),
1404 rank: 1,
1405 }),
1406 organizer: false,
1407 ..Default::default()
1408 }
1409 }
1410
1411 #[gpui_kit::test]
1412 fn organizer_controls_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {
1413 let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1414 cx.update(|cx| {
1415 attendee.update(cx, |state, cx| {
1416 state.admit_call_guest("8:orgid:g".into(), cx);
1417 state.admit_all_call_guests(cx);
1418 state.deny_call_guest("8:orgid:g".into(), cx);
1419 state.mute_call_participant("8:orgid:a".into(), cx);
1420 state.mute_all_call(cx);
1421 state.remove_call_participant("8:orgid:a".into(), cx);
1422 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1423 })
1424 });
1425 assert_eq!(attendee_control.try_recv_command(), None);
1426 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1427 cx.update(|cx| {
1428 organizer.update(cx, |state, cx| {
1429 state.apply_call_update(
1430 7,
1431 CallUpdate::Roster(vec![
1432 guest("8:orgid:a", "Ana", false, false),
1433 guest("8:orgid:g", "Gast", true, false),
1434 ]),
1435 cx,
1436 );
1437 state.admit_call_guest("8:orgid:g".into(), cx);
1438 state.admit_all_call_guests(cx);
1439 state.deny_call_guest("8:orgid:g".into(), cx);
1440 state.mute_call_participant("8:orgid:a".into(), cx);
1441 state.mute_all_call(cx);
1442 state.remove_call_participant("8:orgid:a".into(), cx);
1443 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1444 })
1445 });
1446 assert_eq!(
1447 control.try_recv_command(),
1448 Some(CallCommand::Admit {
1449 mri: "8:orgid:g".into()
1450 })
1451 );
1452 assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));
1453 assert_eq!(
1454 control.try_recv_command(),
1455 Some(CallCommand::Deny {
1456 mri: "8:orgid:g".into()
1457 })
1458 );
1459 assert_eq!(
1460 control.try_recv_command(),
1461 Some(CallCommand::MuteParticipant {
1462 mri: "8:orgid:a".into()
1463 })
1464 );
1465 assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));
1466 assert_eq!(
1467 control.try_recv_command(),
1468 Some(CallCommand::RemoveParticipant {
1469 mri: "8:orgid:a".into()
1470 })
1471 );
1472 assert_eq!(
1473 control.try_recv_command(),
1474 Some(CallCommand::Spotlight {
1475 mri: "8:orgid:a".into()
1476 })
1477 );
1478 }
1479
1480 #[gpui_kit::test]
1481 fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(
1482 cx: &mut TestAppContext,
1483 ) {
1484 let (app, mut control) = app_with_commands(cx, live_meeting(true), None);
1485 cx.update(|cx| {
1486 app.update(cx, |state, cx| {
1487 state.apply_call_update(
1488 7,
1489 CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]),
1490 cx,
1491 );
1492 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1493 state.toggle_call_pin("8:orgid:a", cx);
1494 assert_eq!(
1495 state.call.as_ref().unwrap().model.pinned.as_deref(),
1496 Some("8:orgid:a")
1497 );
1498 state.toggle_call_pin("8:orgid:a", cx);
1499 assert_eq!(state.call.as_ref().unwrap().model.pinned, None);
1500 })
1501 });
1502 assert_eq!(
1503 control.try_recv_command(),
1504 Some(CallCommand::StopSpotlight {
1505 mri: "8:orgid:a".into()
1506 })
1507 );
1508 assert_eq!(control.try_recv_command(), None);
1509 }
1510
1511 #[gpui_kit::test]
1512 fn captions_toggle_between_on_and_off_and_only_in_meetings(cx: &mut TestAppContext) {
1513 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1514 cx.update(|cx| {
1515 app.update(cx, |state, cx| {
1516 state.toggle_call_captions(cx);
1517 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1518 state.toggle_call_captions(cx);
1519 })
1520 });
1521 assert_eq!(
1522 control.try_recv_command(),
1523 Some(CallCommand::SetCaptions(true))
1524 );
1525 assert_eq!(
1526 control.try_recv_command(),
1527 Some(CallCommand::SetCaptions(false))
1528 );
1529 let app = app_with_call(cx);
1530 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));
1531 }
1532
1533 #[gpui_kit::test]
1534 fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1535 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1536 let store = cx.update(|cx| app.read(cx).store.clone());
1537 assert_eq!(
1538 cx.update(|cx| app.read(cx).call_background.clone()),
1539 BackgroundPick::None
1540 );
1541 cx.update(|cx| {
1542 app.update(cx, |state, cx| {
1543 state.set_call_background(BackgroundPick::Blur, cx)
1544 })
1545 });
1546 assert_eq!(
1547 control.try_recv_command(),
1548 Some(CallCommand::SetBackground(BackgroundChoice::Blur))
1549 );
1550 assert_eq!(
1551 cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()),
1552 BackgroundPick::Blur
1553 );
1554 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1555 assert_eq!(
1556 cx.update(|cx| reopened.read(cx).call_background.clone()),
1557 BackgroundPick::Blur
1558 );
1559 let picture = PathBuf::from("/pictures/wall.jpg");
1560 cx.update(|cx| {
1561 app.update(cx, |state, cx| {
1562 state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)
1563 })
1564 });
1565 assert_eq!(
1566 control.try_recv_command(),
1567 Some(CallCommand::SetBackground(BackgroundChoice::Image(
1568 picture.clone()
1569 )))
1570 );
1571 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1572 assert_eq!(
1573 cx.update(|cx| reopened.read(cx).call_background.clone()),
1574 BackgroundPick::Custom(picture)
1575 );
1576 cx.update(|cx| {
1577 app.update(cx, |state, cx| {
1578 state.set_call_background(BackgroundPick::None, cx)
1579 })
1580 });
1581 assert_eq!(
1582 control.try_recv_command(),
1583 Some(CallCommand::SetBackground(BackgroundChoice::None))
1584 );
1585 }
1586
1587 #[gpui_kit::test]
1588 fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {
1589 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1590 cx.update(|cx| {
1591 app.update(cx, |state, cx| {
1592 state.set_call_background(BackgroundPick::Default("office_01".into()), cx)
1593 })
1594 });
1595 assert_eq!(control.try_recv_command(), None);
1596 }
1597
1598 #[gpui_kit::test]
1599 fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(
1600 cx: &mut TestAppContext,
1601 ) {
1602 let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1603 cx.update(|cx| {
1604 attendee.update(cx, |state, cx| {
1605 state.run_call_record_action(RecordAction::Start(RecordingKind::Video), cx);
1606 state.accept_recording_notice(cx);
1607 })
1608 });
1609 assert_eq!(attendee_control.try_recv_command(), None);
1610 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1611 cx.update(|cx| {
1612 organizer.update(cx, |state, cx| {
1613 state.run_call_record_action(RecordAction::Start(RecordingKind::Video), cx);
1614 state.apply_call_update(7, CallUpdate::Recording(true), cx);
1615 state.run_call_record_action(RecordAction::Stop(StopScope::Both), cx);
1616 state.accept_recording_notice(cx);
1617 state.apply_call_update(7, CallUpdate::ConsentRequired(true), cx);
1618 state.accept_recording_notice(cx);
1619 })
1620 });
1621 assert_eq!(
1622 control.try_recv_command(),
1623 Some(CallCommand::StartRecording {
1624 kind: RecordingKind::Video,
1625 title: "Standup".into()
1626 })
1627 );
1628 assert_eq!(
1629 control.try_recv_command(),
1630 Some(CallCommand::StopRecording {
1631 scope: StopScope::Both
1632 })
1633 );
1634 assert_eq!(
1635 control.try_recv_command(),
1636 Some(CallCommand::ConsentToRecording)
1637 );
1638 assert_eq!(control.try_recv_command(), None);
1639 }
1640
1641 #[gpui_kit::test]
1642 fn every_record_action_becomes_its_own_command_for_the_organizer(cx: &mut TestAppContext) {
1643 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1644 cx.update(|cx| {
1645 organizer.update(cx, |state, cx| {
1646 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
1647 state.run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
1648 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
1649 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
1650 })
1651 });
1652 let title = "Standup".to_owned();
1653 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::AudioOnly, title: title.clone() }));
1654 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::TranscriptOnly, title }));
1655 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::RecordingOnly }));
1656 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::TranscriptionOnly }));
1657 assert_eq!(control.try_recv_command(), None);
1658 }
1659
1660 #[gpui_kit::test]
1661 fn the_transcript_turns_captions_on_and_excludes_the_chat_panel(cx: &mut TestAppContext) {
1662 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1663 cx.update(|cx| {
1664 app.update(cx, |state, cx| {
1665 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
1666 state.toggle_call_chat(cx);
1667 state.show_call_transcript(cx);
1668 })
1669 });
1670 let (chat_open, transcript_open) = cx.update(|cx| {
1671 let call = app.read(cx).call.as_ref().unwrap();
1672 (call.chat_open, call.transcript_open)
1673 });
1674 assert!(!chat_open && transcript_open);
1675 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
1676 cx.update(|cx| {
1677 app.update(cx, |state, cx| {
1678 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1679 state.show_call_transcript(cx);
1680 state.toggle_call_chat(cx);
1681 })
1682 });
1683 let (chat_open, transcript_open) = cx.update(|cx| {
1684 let call = app.read(cx).call.as_ref().unwrap();
1685 (call.chat_open, call.transcript_open)
1686 });
1687 assert!(chat_open && !transcript_open);
1688 assert_eq!(control.try_recv_command(), None);
1689 }
1690
1691 #[gpui_kit::test]
1692 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(cx: &mut TestAppContext) {
1693 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1694 cx.update(|cx| {
1695 app.update(cx, |state, cx| {
1696 state.choose_call_caption_language("de-DE", cx);
1697 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::Starting), cx);
1698 })
1699 });
1700 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
1701 assert_eq!(control.try_recv_command(), None);
1702 cx.update(|cx| {
1703 app.update(cx, |state, cx| {
1704 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1705 state.choose_call_caption_language("fr-FR", cx);
1706 })
1707 });
1708 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("de-DE".into())));
1709 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("fr-FR".into())));
1710 assert_eq!(control.try_recv_command(), None);
1711 }
1712
1713 #[gpui_kit::test]
1714 fn caption_size_and_position_are_stored_and_reach_the_call_model(cx: &mut TestAppContext) {
1715 let (app, _control) = app_with_commands(cx, live_meeting(false), None);
1716 cx.update(|cx| {
1717 app.update(cx, |state, cx| {
1718 state.set_call_caption_size(CaptionSize::Large, cx);
1719 state.set_call_caption_position(CaptionPosition::Top, cx);
1720 })
1721 });
1722 let (view, stored) = cx.update(|cx| {
1723 let state = app.read(cx);
1724 (state.call.as_ref().unwrap().model.view, ViewSettings::load(&state.store))
1725 });
1726 assert_eq!((view.caption_size, view.caption_position), (CaptionSize::Large, CaptionPosition::Top));
1727 assert_eq!((stored.caption_size, stored.caption_position), (CaptionSize::Large, CaptionPosition::Top));
1728 }
1729
1730 fn live_one_to_one() -> CallModel {
1731 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1732 model.apply(CallUpdate::State(CallState::Connected {
1733 since: Instant::now(),
1734 }));
1735 model
1736 }
1737
1738 #[gpui_kit::test]
1739 fn hold_and_resume_alternate_and_stop_while_the_other_side_holds(cx: &mut TestAppContext) {
1740 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1741 cx.update(|cx| {
1742 app.update(cx, |state, cx| {
1743 state.toggle_call_hold(cx);
1744 state.apply_call_update(7, CallUpdate::Hold(HoldState::Local), cx);
1745 state.toggle_call_hold(cx);
1746 state.apply_call_update(7, CallUpdate::Hold(HoldState::Remote), cx);
1747 state.toggle_call_hold(cx);
1748 })
1749 });
1750 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(true)));
1751 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(false)));
1752 assert_eq!(control.try_recv_command(), None);
1753 let (meeting, mut meeting_control) = app_with_commands(cx, live_meeting(true), None);
1754 cx.update(|cx| meeting.update(cx, |state, cx| state.toggle_call_hold(cx)));
1755 assert_eq!(meeting_control.try_recv_command(), None);
1756 }
1757
1758 fn candidate(name: &str) -> TransferCandidate {
1759 TransferCandidate {
1760 mri: format!("8:orgid:{name}"),
1761 name: name.into(),
1762 user_id: Some(name.into()),
1763 chat_id: format!("19:{name}"),
1764 }
1765 }
1766
1767 #[gpui_kit::test]
1768 fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(
1769 cx: &mut TestAppContext,
1770 ) {
1771 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1772 cx.update(|cx| {
1773 app.update(cx, |state, cx| {
1774 state.transfer_call_blind(candidate("ana"), cx)
1775 })
1776 });
1777 assert_eq!(
1778 control.try_recv_command(),
1779 Some(CallCommand::Transfer {
1780 target: calling::Callee {
1781 mri: "8:orgid:ana".into(),
1782 display_name: "ana".into()
1783 },
1784 replaces: None
1785 })
1786 );
1787 let (consulting, mut consult_control) = app_with_commands(cx, live_one_to_one(), None);
1788 let (consult_handle, _consult_updates) = call_channel();
1789 cx.update(|cx| {
1790 consulting.update(cx, |state, cx| {
1791 state.call.as_mut().unwrap().consult = Some(ConsultCall {
1792 id: 8,
1793 target: ("8:orgid:ana".into(), "Ana".into()),
1794 commands: consult_handle.commands,
1795 state: CallState::Connecting,
1796 replacement: Some("https://cc.skype.com/replacement".into()),
1797 transferring: false,
1798 });
1799 state.transfer_consulted(cx);
1800 state.call.as_mut().unwrap().consult.as_mut().unwrap().state =
1801 CallState::Connected {
1802 since: Instant::now(),
1803 };
1804 state.transfer_consulted(cx);
1805 })
1806 });
1807 assert_eq!(
1808 consult_control.try_recv_command(),
1809 Some(CallCommand::Transfer {
1810 target: calling::Callee {
1811 mri: "8:orgid:ana".into(),
1812 display_name: "Ana".into()
1813 },
1814 replaces: Some("https://cc.skype.com/replacement".into()),
1815 })
1816 );
1817 assert_eq!(consult_control.try_recv_command(), None);
1818 }
1819
1820 #[gpui_kit::test]
1821 fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(
1822 cx: &mut TestAppContext,
1823 ) {
1824 let app = app_with_chats(cx);
1825 cx.update(|cx| {
1826 app.update(cx, |state, cx| {
1827 let names: Vec<String> = state
1828 .transfer_candidates()
1829 .into_iter()
1830 .map(|candidate| candidate.name)
1831 .collect();
1832 assert_eq!(names, vec!["Bea".to_owned()]);
1833 let (handle, _control) = call_channel();
1834 let mut on_the_call =
1835 CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);
1836 on_the_call.apply(CallUpdate::State(CallState::Connected {
1837 since: Instant::now(),
1838 }));
1839 state.call = Some(ActiveCall::new(
1840 9,
1841 on_the_call,
1842 handle.commands,
1843 None,
1844 handle.video,
1845 ));
1846 assert!(state.transfer_candidates().is_empty());
1847 cx.notify();
1848 })
1849 });
1850 }
1851
1852 fn room_move(returning: bool) -> calling::BreakoutMove {
1853 calling::BreakoutMove {
1854 room_name: "Room 1".into(),
1855 target: calling::MeetingTarget {
1856 thread_id: "19:meeting_room@thread.v2".into(),
1857 tenant_id: "t".into(),
1858 organizer_id: "o".into(),
1859 meeting_data: None,
1860 },
1861 returning,
1862 }
1863 }
1864
1865 fn main_target() -> calling::MeetingTarget {
1866 calling::MeetingTarget {
1867 thread_id: "19:meeting_main@thread.v2".into(),
1868 tenant_id: "t".into(),
1869 organizer_id: "o".into(),
1870 meeting_data: None,
1871 }
1872 }
1873
1874 #[gpui_kit::test]
1875 fn being_moved_to_a_room_leaves_the_call_and_remembers_the_way_back(cx: &mut TestAppContext) {
1876 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1877 cx.update(|cx| {
1878 app.update(cx, |state, cx| {
1879 state.call.as_mut().unwrap().meeting_target = Some(main_target());
1880 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1881 let pending = state
1882 .call
1883 .as_ref()
1884 .unwrap()
1885 .pending_move
1886 .clone()
1887 .expect("a move is pending");
1888 assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");
1889 assert_eq!(pending.title, "Room 1");
1890 let room = pending.breakout.expect("a room");
1891 assert_eq!(room.main, Some(main_target()));
1892 assert_eq!(room.main_title, "Standup");
1893 assert_eq!(
1894 state.notice.as_ref().map(|notice| notice.text.as_str()),
1895 Some("Moving you to Room 1")
1896 );
1897 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1898 })
1899 });
1900 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
1901 assert_eq!(control.try_recv_command(), None);
1902 }
1903
1904 #[gpui_kit::test]
1905 fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(
1906 cx: &mut TestAppContext,
1907 ) {
1908 let mut room = live_meeting(false);
1909 room.breakout = Some(BreakoutState {
1910 room_name: "Room 1".into(),
1911 main: Some(main_target()),
1912 main_title: "Standup".into(),
1913 });
1914 let (app, mut control) = app_with_commands(cx, room.clone(), None);
1915 cx.update(|cx| {
1916 app.update(cx, |state, cx| {
1917 state.return_to_main_meeting(cx);
1918 let pending = state
1919 .call
1920 .as_ref()
1921 .unwrap()
1922 .pending_move
1923 .clone()
1924 .expect("a move is pending");
1925 assert_eq!(pending.target, main_target());
1926 assert_eq!(pending.title, "Standup");
1927 assert!(pending.breakout.is_none());
1928 })
1929 });
1930 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
1931 let (closed, _control) = app_with_commands(cx, room, None);
1932 cx.update(|cx| {
1933 closed.update(cx, |state, _| {
1934 let call = state.call.as_ref().unwrap();
1935 let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed))
1936 .expect("goes back");
1937 assert_eq!(moved.target, main_target());
1938 assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());
1939 assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());
1940 })
1941 });
1942 let (plain, _control) = app_with_commands(cx, live_meeting(false), None);
1943 cx.update(|cx| {
1944 plain.update(cx, |state, _| {
1945 assert!(
1946 room_closed_move(
1947 state.call.as_ref().unwrap(),
1948 &EndReason::Remote(EndKind::RoomClosed)
1949 )
1950 .is_none()
1951 )
1952 })
1953 });
1954 }
1955
1956 #[gpui_kit::test]
1957 fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(
1958 cx: &mut TestAppContext,
1959 ) {
1960 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1961 cx.update(|cx| {
1962 app.update(cx, |state, cx| {
1963 state.open_call_whiteboard(cx);
1964 state.apply_call_update(
1965 7,
1966 CallUpdate::Whiteboard(Some(calling::ContentShare {
1967 session_id: "s".into(),
1968 presenter: Some("8:orgid:ana".into()),
1969 subject: "Whiteboard".into(),
1970 url: Some("https://app.whiteboard.microsoft.com/x".into()),
1971 whiteboard: true,
1972 })),
1973 cx,
1974 );
1975 state.open_call_whiteboard(cx);
1976 })
1977 });
1978 assert_eq!(
1979 control.try_recv_command(),
1980 Some(CallCommand::OpenWhiteboard {
1981 title: "Standup".into()
1982 })
1983 );
1984 assert_eq!(control.try_recv_command(), None);
1985 }
1986
1987 #[gpui_kit::test]
1988 fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(
1989 cx: &mut TestAppContext,
1990 ) {
1991 let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
1992 cx.update(|cx| {
1993 app.update(cx, |state, cx| {
1994 state
1995 .directory
1996 .unread_counts
1997 .insert("19:meeting_x@thread.v2".into(), 3);
1998 assert_eq!(state.call_chat_thread(), None);
1999 assert_eq!(state.call_chat_unread(), 0);
2000 state.apply_call_update(
2001 7,
2002 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2003 cx,
2004 );
2005 assert_eq!(state.call_chat_unread(), 3);
2006 state.toggle_call_chat(cx);
2007 assert_eq!(
2008 state.call_chat_thread().as_deref(),
2009 Some("19:meeting_x@thread.v2")
2010 );
2011 assert_eq!(state.call_chat_unread(), 0);
2012 state.toggle_call_chat(cx);
2013 assert_eq!(state.call_chat_thread(), None);
2014 })
2015 });
2016 }
2017
2018 #[gpui_kit::test]
2019 fn a_call_without_a_chat_has_no_panel(cx: &mut TestAppContext) {
2020 let app = app_with_call(cx);
2021 cx.update(|cx| {
2022 app.update(cx, |state, cx| {
2023 state.toggle_call_chat(cx);
2024 assert!(!state.call.as_ref().unwrap().chat_open);
2025 })
2026 });
2027 }
2028
2029 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
2030 cx.update(gpui_kit::init);
2031 let store = Arc::new(Store::open_in_memory().unwrap());
2032 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
2033 cx.update(|cx| {
2034 app.update(cx, |state, _| {
2035 state.directory.me = Some(Person {
2036 user_id: "me-id".into(),
2037 display_name: "Me".into(),
2038 });
2039 state.sidebar.chats = vec![
2040 ChatRecord {
2041 id: "19:meeting@thread.v2".into(),
2042 kind: "meeting".into(),
2043 members: vec![MemberRecord {
2044 user_id: Some("bea-id".into()),
2045 display_name: "Bea".into(),
2046 }],
2047 ..Default::default()
2048 },
2049 ChatRecord {
2050 id: "19:dm@unq.gbl.spaces".into(),
2051 kind: "oneOnOne".into(),
2052 members: vec![
2053 MemberRecord {
2054 user_id: Some("me-id".into()),
2055 display_name: "Me".into(),
2056 },
2057 MemberRecord {
2058 user_id: Some("bea-id".into()),
2059 display_name: "Bea".into(),
2060 },
2061 ],
2062 ..Default::default()
2063 },
2064 ];
2065 })
2066 });
2067 app
2068 }
2069
2070 #[gpui_kit::test]
2071 fn declining_by_shortcut_only_acts_while_a_ring_shows(cx: &mut TestAppContext) {
2072 let app = app_with_chats(cx);
2073 cx.update(|cx| {
2074 app.update(cx, |state, cx| {
2075 state.decline_ringing_call(cx);
2076 assert!(!state.rings.is_ringing());
2077 state.demo_incoming_ring(cx);
2078 assert!(state.rings.is_ringing());
2079 state.decline_ringing_call(cx);
2080 assert!(!state.rings.is_ringing());
2081 })
2082 });
2083 }
2084
2085 #[gpui_kit::test]
2086 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
2087 let app = app_with_call(cx);
2088 cx.update(|cx| {
2089 app.update(cx, |state, cx| {
2090 assert!(state.viewing_call());
2091 state.select(Selection::Chat("c1".into()), cx);
2092 assert!(!state.viewing_call());
2093 state.show_call(true, cx);
2094 assert!(state.viewing_call());
2095 })
2096 });
2097 }
2098
2099 #[gpui_kit::test]
2100 fn an_ended_call_closes_the_view_and_raises_a_notice(cx: &mut TestAppContext) {
2101 let app = app_with_call(cx);
2102 let since = Instant::now() - Duration::from_secs(42);
2103 cx.update(|cx| {
2104 app.update(cx, |state, cx| {
2105 state.apply_call_update(7, CallUpdate::State(CallState::Connected { since }), cx);
2106 assert!(state.call.is_some());
2107 state.apply_call_update(
2108 7,
2109 CallUpdate::State(CallState::Ended {
2110 reason: EndReason::LocalHangup,
2111 }),
2112 cx,
2113 );
2114 assert!(state.call.is_none());
2115 let notice = state.notice.as_ref().expect("notice");
2116 assert_eq!(notice.text, "Call ended 00:42");
2117 })
2118 });
2119 }
2120
2121 #[gpui_kit::test]
2122 fn full_window_exists_only_while_someone_shares_and_escape_leaves_it(cx: &mut TestAppContext) {
2123 let app = app_with_call(cx);
2124 cx.update(|cx| {
2125 app.update(cx, |state, cx| {
2126 state.toggle_stage_fullscreen(cx);
2127 assert!(!state.stage_fullscreen());
2128 state.apply_call_update(7, CallUpdate::ScreenShare(Some("8:orgid:a".into())), cx);
2129 state.toggle_stage_fullscreen(cx);
2130 assert!(state.stage_fullscreen());
2131 state.leave_stage_fullscreen(cx);
2132 assert!(!state.stage_fullscreen());
2133 state.toggle_stage_fullscreen(cx);
2134 state.apply_call_update(7, CallUpdate::ScreenShare(None), cx);
2135 assert!(!state.stage_fullscreen());
2136 })
2137 });
2138 }
2139
2140 #[gpui_kit::test]
2141 fn a_declined_call_names_who_declined(cx: &mut TestAppContext) {
2142 let app = app_with_call(cx);
2143 cx.update(|cx| {
2144 app.update(cx, |state, cx| {
2145 state.call.as_mut().unwrap().model.peer_name = "Bea".into();
2146 state.apply_call_update(
2147 7,
2148 CallUpdate::State(CallState::Ended {
2149 reason: EndReason::Remote(EndKind::Declined),
2150 }),
2151 cx,
2152 );
2153 assert_eq!(state.notice.as_ref().unwrap().text, "Bea declined");
2154 })
2155 });
2156 }
2157
2158 #[gpui_kit::test]
2159 fn updates_of_an_older_call_are_ignored(cx: &mut TestAppContext) {
2160 let app = app_with_call(cx);
2161 cx.update(|cx| {
2162 app.update(cx, |state, cx| {
2163 state.apply_call_update(
2164 6,
2165 CallUpdate::State(CallState::Ended {
2166 reason: EndReason::Dropped,
2167 }),
2168 cx,
2169 );
2170 assert!(state.call.is_some());
2171 assert!(state.notice.is_none());
2172 })
2173 });
2174 }
2175
2176 #[gpui_kit::test]
2177 fn a_ring_that_times_out_becomes_a_missed_call_event(cx: &mut TestAppContext) {
2178 cx.update(gpui_kit::init);
2179 let store = Arc::new(Store::open_in_memory().unwrap());
2180 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
2181 cx.update(|cx| {
2182 app.update(cx, |state, cx| {
2183 state.on_engine_event(EngineEvent::Incoming(demo_ring()), cx);
2184 assert!(state.rings.is_ringing());
2185 state.tick_rings(cx);
2186 assert!(state.rings.is_ringing());
2187 state.on_engine_event(
2188 EngineEvent::RingEnded {
2189 ring_id: demo_ring().ring_id,
2190 kind: EndKind::Cancelled,
2191 answered_by: None,
2192 },
2193 cx,
2194 );
2195 assert!(!state.rings.is_ringing());
2196 })
2197 });
2198 }
2199
2200 #[gpui_kit::test]
2201 fn calls_are_refused_for_meeting_chats_and_missing_chats(cx: &mut TestAppContext) {
2202 let app = app_with_chats(cx);
2203 cx.update(|cx| {
2204 app.update(cx, |state, cx| {
2205 state.start_chat_call("19:meeting@thread.v2", cx);
2206 assert!(state.call.is_none());
2207 assert_eq!(
2208 state.notice.as_ref().unwrap().text,
2209 "This chat cannot be called"
2210 );
2211 state.start_chat_call("19:unknown", cx);
2212 assert!(state.call.is_none());
2213 })
2214 });
2215 }
2216
2217 #[gpui_kit::test]
2218 fn a_missed_call_finds_the_one_on_one_chat_of_the_caller(cx: &mut TestAppContext) {
2219 let app = app_with_chats(cx);
2220 cx.update(|cx| {
2221 app.update(cx, |state, _| {
2222 let missed = super::MissedCall {
2223 caller_mri: "8:orgid:bea-id".into(),
2224 caller_name: "Bea".into(),
2225 thread_id: None,
2226 at: chrono::Utc::now(),
2227 };
2228 assert_eq!(
2229 state.conversation_of_missed_call(&missed).as_deref(),
2230 Some("19:dm@unq.gbl.spaces")
2231 );
2232 let direct = super::MissedCall {
2233 thread_id: Some("19:dm@unq.gbl.spaces".into()),
2234 ..missed.clone()
2235 };
2236 assert_eq!(
2237 state.conversation_of_missed_call(&direct).as_deref(),
2238 Some("19:dm@unq.gbl.spaces")
2239 );
2240 })
2241 });
2242 }
2243
2244 #[gpui_kit::test]
2245 fn only_meeting_chats_and_channels_watch_for_a_running_meeting(cx: &mut TestAppContext) {
2246 let app = app_with_chats(cx);
2247 cx.update(|cx| {
2248 app.update(cx, |state, _| {
2249 assert!(state.watches_live_meeting("19:meeting@thread.v2"));
2250 assert!(!state.watches_live_meeting("19:dm@unq.gbl.spaces"));
2251 assert!(!state.watches_live_meeting("19:unknown"));
2252 })
2253 });
2254 }
2255
2256 #[gpui_kit::test]
2257 fn a_live_meeting_shows_until_it_ends(cx: &mut TestAppContext) {
2258 let app = app_with_chats(cx);
2259 let meeting = calling::meeting::LiveMeeting {
2260 thread_id: "19:meeting@thread.v2".into(),
2261 conversation_url: None,
2262 expiration: Some(chrono::Utc::now().timestamp() + 600),
2263 organizer_id: Some("org".into()),
2264 tenant_id: Some("tenant".into()),
2265 meeting_code: None,
2266 passcode: None,
2267 };
2268 cx.update(|cx| {
2269 app.update(cx, |state, cx| {
2270 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
2271 state.apply_live_meeting("19:meeting@thread.v2".into(), Some(meeting), cx);
2272 assert!(state.running_meeting("19:meeting@thread.v2").is_some());
2273 state.apply_live_meeting("19:meeting@thread.v2".into(), None, cx);
2274 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
2275 })
2276 });
2277 }
2278}