BlueGit

ict rusty-teams

Files

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

actions.rs

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