BlueGit

ict rusty-teams

Files

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

actions.rs

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