BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 102.2 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 if let Some(launcher) = &self.call_launcher {
719 launcher.set_default_mic(settings);
720 }
721 self.send_call_command(CallCommand::SetMicSettings(settings));
722 cx.notify();
723 }
724
725 pub fn set_call_video_quality(
726 &mut self,
727 quality: calling::VideoQuality,
728 cx: &mut Context<Self>,
729 ) {
730 self.call_video_quality = quality;
731 save_video_quality(&self.store, quality);
732 self.send_call_command(CallCommand::SetVideoQuality(quality));
733 cx.notify();
734 }
735
736 pub fn press_push_to_talk(&mut self, _cx: &mut Context<Self>) {
737 let Some(call) = self.call.as_mut() else {
738 return;
739 };
740 let command = call
741 .push_to_talk
742 .press(call.model.muted, call.model.can_unmute());
743 if let Some(command) = command {
744 self.send_call_command(CallCommand::Mute(command));
745 }
746 }
747
748 pub fn release_push_to_talk(&mut self, _cx: &mut Context<Self>) {
749 let command = self
750 .call
751 .as_mut()
752 .and_then(|call| call.push_to_talk.release());
753 if let Some(command) = command {
754 self.send_call_command(CallCommand::Mute(command));
755 }
756 }
757
758 pub fn select_call_camera(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
759 let _ = self.store.set_meta(CAMERA_META_KEY, device_meta(&choice));
760 self.call_camera = choice.clone();
761 if let Some(launcher) = &self.call_launcher {
762 launcher.set_default_camera(choice.clone());
763 }
764 if let Some(call) = self.call.as_mut() {
765 call.model.camera = choice.clone();
766 }
767 self.send_call_command(CallCommand::SelectCamera(choice));
768 }
769
770 pub fn start_call_share(&mut self, source: ShareSource, _cx: &mut Context<Self>) {
771 self.send_call_command(CallCommand::StartShare(source));
772 }
773
774 pub fn start_portal_share(&mut self, kind: ShareKind, _cx: &mut Context<Self>) {
775 self.send_call_command(CallCommand::StartPortalShare(kind));
776 }
777
778 pub fn stop_call_share(&mut self, _cx: &mut Context<Self>) {
779 self.send_call_command(CallCommand::StopShare);
780 }
781
782 pub fn refresh_share_sources(&self) {
783 let idle = self
784 .call
785 .as_ref()
786 .is_some_and(|call| call.model.local_share.is_none());
787 if idle {
788 self.send_call_command(CallCommand::RefreshShareSources);
789 }
790 }
791
792 pub fn leave_call(&mut self, _cx: &mut Context<Self>) {
793 self.send_call_command(CallCommand::Hangup);
794 }
795
796 pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {
797 let allowed = self
798 .call
799 .as_ref()
800 .is_some_and(|call| call.model.can_end_meeting);
801 if allowed {
802 self.send_call_command(CallCommand::EndMeeting);
803 }
804 }
805
806 pub fn select_call_input(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
807 let _ = self.store.set_meta(INPUT_META_KEY, device_meta(&choice));
808 self.call_input = choice.clone();
809 self.send_call_command(CallCommand::SelectInput(choice));
810 }
811
812 pub fn select_call_output(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
813 let _ = self.store.set_meta(OUTPUT_META_KEY, device_meta(&choice));
814 self.call_output = choice.clone();
815 apply_sound_output(&choice);
816 self.send_call_command(CallCommand::SelectOutput(choice));
817 }
818
819 pub fn show_call(&mut self, viewing: bool, cx: &mut Context<Self>) {
820 let Some(call) = self.call.as_mut().filter(|call| call.viewing != viewing) else {
821 return;
822 };
823 call.viewing = viewing;
824 if viewing {
825 self.new_chat = false;
826 }
827 cx.emit(AppEvent::Call);
828 cx.notify();
829 }
830
831 pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {
832 let Some(call) = self
833 .call
834 .as_mut()
835 .filter(|call| call.chat_thread().is_some())
836 else {
837 return;
838 };
839 call.chat_open = !call.chat_open;
840 let chat_state = if call.chat_open { "open" } else { "close" };
841 if call.chat_open {
842 call.transcript_open = false;
843 self.transcript_panel = None;
844 call.people_open = false;
845 }
846 self.note_call_feature("chat", chat_state.to_owned());
847 cx.emit(AppEvent::Call);
848 cx.notify();
849 }
850
851 pub fn call_chat_thread(&self) -> Option<String> {
852 let call = self.call.as_ref().filter(|call| call.chat_open)?;
853 call.chat_thread().map(str::to_owned)
854 }
855
856 pub fn call_chat_unread(&self) -> u32 {
857 let Some(thread) = self
858 .call
859 .as_ref()
860 .filter(|call| !call.chat_open)
861 .and_then(|call| call.chat_thread())
862 else {
863 return 0;
864 };
865 let counted = self.directory.unread_counts.get(thread).copied();
866 counted.unwrap_or_else(|| {
867 u32::from(
868 self.sidebar
869 .chats
870 .iter()
871 .any(|chat| chat.id == thread && chat.unread),
872 )
873 })
874 }
875
876 pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {
877 let Some(call) = self
878 .call
879 .as_mut()
880 .filter(|call| call.model.is_active() && call.model.has_reaction_controls())
881 else {
882 return;
883 };
884 let raised = call.model.own_hand.is_none();
885 call.model.own_hand = raised.then_some(u64::MAX);
886 self.send_call_command(CallCommand::SetHand(raised));
887 if raised {
888 self.raise_notice("Your hand is raised".to_owned(), None, cx);
889 }
890 cx.emit(AppEvent::Call);
891 cx.notify();
892 }
893
894 pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {
895 let allowed = self
896 .call
897 .as_ref()
898 .is_some_and(|call| call.model.can_lower_hands());
899 if allowed {
900 self.send_call_command(CallCommand::LowerHand { mri });
901 }
902 }
903
904 pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {
905 let allowed = self
906 .call
907 .as_ref()
908 .is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());
909 if allowed {
910 self.send_call_command(CallCommand::LowerAllHands);
911 }
912 }
913
914 pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {
915 let Some(call) = self
916 .call
917 .as_mut()
918 .filter(|call| call.model.is_active() && call.model.has_reaction_controls())
919 else {
920 return;
921 };
922 if let Some(own_mri) = call.model.own_mri.clone() {
923 call.model
924 .note_reaction(own_mri, reaction.clone(), Instant::now());
925 }
926 self.send_call_command(CallCommand::SendReaction(reaction));
927 cx.emit(AppEvent::Call);
928 cx.notify();
929 }
930
931 pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {
932 self.call_share_sound = on;
933 let _ = self
934 .store
935 .set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });
936 self.send_call_command(CallCommand::SetShareSound(on));
937 cx.notify();
938 }
939
940 pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
941 if self
942 .call
943 .as_ref()
944 .is_some_and(|call| call.model.can_admit())
945 {
946 self.send_call_command(CallCommand::Admit { mri });
947 }
948 }
949
950 pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {
951 if self
952 .call
953 .as_ref()
954 .is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty())
955 {
956 self.send_call_command(CallCommand::AdmitAll);
957 }
958 }
959
960 pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
961 if self
962 .call
963 .as_ref()
964 .is_some_and(|call| call.model.can_admit())
965 {
966 self.send_call_command(CallCommand::Deny { mri });
967 }
968 }
969
970 pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
971 if self
972 .call
973 .as_ref()
974 .is_some_and(|call| call.model.can_manage())
975 {
976 self.send_call_command(CallCommand::MuteParticipant { mri });
977 }
978 }
979
980 pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {
981 if self
982 .call
983 .as_ref()
984 .is_some_and(|call| call.model.can_manage())
985 {
986 self.send_call_command(CallCommand::MuteAll);
987 }
988 }
989
990 pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
991 if self
992 .call
993 .as_ref()
994 .is_some_and(|call| call.model.can_manage())
995 {
996 self.send_call_command(CallCommand::RemoveParticipant { mri });
997 }
998 }
999
1000 pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {
1001 let Some(call) = self
1002 .call
1003 .as_ref()
1004 .filter(|call| call.model.can_manage() && call.model.is_active())
1005 else {
1006 return;
1007 };
1008 let command = if call.model.is_spotlighted(&mri) {
1009 CallCommand::StopSpotlight { mri }
1010 } else {
1011 CallCommand::Spotlight { mri }
1012 };
1013 self.send_call_command(command);
1014 }
1015
1016 pub fn toggle_call_pin(&mut self, mri: &str, cx: &mut Context<Self>) {
1017 if let Some(call) = self.call.as_mut() {
1018 call.model.toggle_pin(mri);
1019 cx.notify();
1020 }
1021 }
1022
1023 pub fn toggle_call_fit(&mut self, mri: &str, cx: &mut Context<Self>) {
1024 if let Some(call) = self.call.as_mut() {
1025 call.model.toggle_fit(mri);
1026 cx.notify();
1027 }
1028 }
1029
1030 pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {
1031 let Some(call) = self
1032 .call
1033 .as_ref()
1034 .filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting)
1035 else {
1036 return;
1037 };
1038 let on = !call.model.captions_on();
1039 self.send_call_command(CallCommand::SetCaptions(on));
1040 }
1041
1042 pub fn set_call_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {
1043 let _ = self.store.set_meta(EFFECTS_META_KEY, &effects.to_meta());
1044 self.call_effects = effects;
1045 self.send_call_command(CallCommand::SetCameraEffects(effects));
1046 cx.notify();
1047 }
1048
1049 pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
1050 let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
1051 self.call_background = pick.clone();
1052 if let Some(call) = self.call.as_mut() {
1053 call.model.background = pick;
1054 }
1055 self.send_background_command(cx);
1056 cx.notify();
1057 }
1058
1059 pub fn toggle_call_background_blur(&mut self, cx: &mut Context<Self>) {
1060 if self.call.is_none() {
1061 return;
1062 }
1063 let pick = if self.call_background == BackgroundPick::Blur {
1064 BackgroundPick::None
1065 } else {
1066 BackgroundPick::Blur
1067 };
1068 self.set_call_background(pick, cx);
1069 }
1070
1071 pub(super) fn send_background_command(&mut self, cx: &mut Context<Self>) {
1072 let pick = self.call_background.clone();
1073 if let Some(choice) = self.call_backgrounds.choice_for(&pick) {
1074 self.send_call_command(CallCommand::SetBackground(choice));
1075 return;
1076 }
1077 let BackgroundPick::Default(id) = pick else {
1078 return;
1079 };
1080 let Some(image) = self.call_backgrounds.find(&id).cloned() else {
1081 return;
1082 };
1083 let Some(launcher) = self.call_launcher.clone() else {
1084 return;
1085 };
1086 let cache = self.call_backgrounds.cache.clone();
1087 let receiver =
1088 crate::runtime::spawn(
1089 async move { launcher.download_background(&cache, &image).await },
1090 );
1091 cx.spawn(async move |this, cx| {
1092 let path = receiver.await.ok().flatten();
1093 this.update(cx, |state, cx| match path {
1094 Some(path) if state.call_background == BackgroundPick::Default(id) => {
1095 state.send_call_command(CallCommand::SetBackground(
1096 calling::BackgroundChoice::Image(path),
1097 ));
1098 }
1099 Some(_) => {}
1100 None => state.raise_notice(
1101 "That background could not be downloaded".to_owned(),
1102 None,
1103 cx,
1104 ),
1105 })
1106 .ok();
1107 })
1108 .detach();
1109 }
1110
1111 pub fn refresh_call_backgrounds(&mut self, cx: &mut Context<Self>) {
1112 if self.mode.demo || !self.call_backgrounds.needs_refresh() {
1113 return;
1114 }
1115 let Some(launcher) = self.call_launcher.clone() else {
1116 return;
1117 };
1118 self.call_backgrounds.refreshing = true;
1119 let cache = self.call_backgrounds.cache.clone();
1120 let wanted = SHOWN_IMAGES;
1121 let receiver =
1122 crate::runtime::spawn(
1123 async move { launcher.refresh_backgrounds(&cache, wanted).await },
1124 );
1125 cx.spawn(async move |this, cx| {
1126 let catalog = receiver.await.ok().flatten();
1127 this.update(cx, |state, cx| {
1128 state.call_backgrounds.refreshing = false;
1129 if let Some(catalog) = catalog {
1130 state.call_backgrounds.images = catalog;
1131 }
1132 cx.notify();
1133 })
1134 .ok();
1135 })
1136 .detach();
1137 }
1138
1139 pub fn add_call_background(&mut self, cx: &mut Context<Self>) {
1140 let receiver = cx.prompt_for_paths(PathPromptOptions {
1141 files: true,
1142 directories: false,
1143 multiple: false,
1144 prompt: None,
1145 });
1146 cx.spawn(async move |this, cx| {
1147 let Some(path) = receiver
1148 .await
1149 .ok()
1150 .and_then(Result::ok)
1151 .flatten()
1152 .and_then(|paths| paths.into_iter().next())
1153 else {
1154 return;
1155 };
1156 this.update(cx, |state, cx| {
1157 if !is_image_file(&path) {
1158 state.raise_notice("Pick a JPG or PNG picture".to_owned(), None, cx);
1159 return;
1160 }
1161 state.call_backgrounds.add_custom(path.clone());
1162 save_custom_backgrounds(&state.store, &state.call_backgrounds.customs);
1163 state.set_call_background(BackgroundPick::Custom(path), cx);
1164 })
1165 .ok();
1166 })
1167 .detach();
1168 }
1169
1170 pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
1171 let Some(call) = self
1172 .call
1173 .as_mut()
1174 .filter(|call| call.model.screen_sharer.is_some())
1175 else {
1176 return;
1177 };
1178 call.stage_fullscreen = !call.stage_fullscreen;
1179 cx.emit(AppEvent::Call);
1180 cx.notify();
1181 }
1182
1183 pub fn leave_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
1184 let Some(call) = self.call.as_mut().filter(|call| call.stage_fullscreen) else {
1185 return;
1186 };
1187 call.stage_fullscreen = false;
1188 cx.emit(AppEvent::Call);
1189 cx.notify();
1190 }
1191
1192 pub fn stage_fullscreen(&self) -> bool {
1193 self.call
1194 .as_ref()
1195 .is_some_and(|call| call.stage_fullscreen && call.model.screen_sharer.is_some())
1196 }
1197
1198 pub fn viewing_call(&self) -> bool {
1199 self.call.as_ref().is_some_and(|call| call.viewing)
1200 }
1201}
1202
1203impl AppState {
1204 pub fn on_engine_event(&mut self, event: EngineEvent, cx: &mut Context<Self>) {
1205 match event {
1206 EngineEvent::Incoming(ring) => self.push_ring(ring, false, cx),
1207 EngineEvent::RingEnded { ring_id, kind, .. } => {
1208 self.signal_ring(ring_id, RingSignal::Remote(kind), cx);
1209 }
1210 }
1211 }
1212
1213 fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {
1214 let caller_user_id = ring
1215 .caller
1216 .mri
1217 .strip_prefix(ORGID_PREFIX)
1218 .map(str::to_owned);
1219 self.rings.push(ring, demo, Instant::now());
1220 if let Some(user_id) = caller_user_id {
1221 self.request_avatars(vec![user_id], cx);
1222 }
1223 cx.emit(AppEvent::Ring);
1224 cx.notify();
1225 }
1226
1227 pub fn demo_incoming_ring(&mut self, cx: &mut Context<Self>) {
1228 self.push_ring(demo_ring(), true, cx);
1229 }
1230
1231 pub fn demo_incoming_video_ring(&mut self, cx: &mut Context<Self>) {
1232 self.push_ring(demo_video_ring(), true, cx);
1233 }
1234
1235 pub fn start_demo_scene(&mut self, scene: DemoScene, cx: &mut Context<Self>) {
1236 if self.call.is_some() {
1237 return;
1238 }
1239 if let Some(cause) = scene.end_cause() {
1240 self.demo_call_end(cause, cx);
1241 return;
1242 }
1243 let (script, model, conversation_id) = if scene.is_one_to_one() {
1244 (
1245 DemoCall::People(vec![demo_caller()]),
1246 CallModel::people("Mara Lindqvist", &[demo_caller()]),
1247 "demo-chat-mara",
1248 )
1249 } else {
1250 let script = DemoCall::Meeting {
1251 guests: demo_guests(scene.guests().unwrap_or(DEMO_SMALL_MEETING)),
1252 lobby: false,
1253 organizer: true,
1254 };
1255 (
1256 script,
1257 CallModel::meeting("Standup", true),
1258 "demo-chat-meeting-standup",
1259 )
1260 };
1261 let handle = start_demo_scene_call(script, scene);
1262 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
1263 if let Some(call) = self.call.as_mut().filter(|_| !scene.is_one_to_one()) {
1264 call.meeting_target = Some(calling::MeetingTarget {
1265 thread_id: conversation_id.to_owned(),
1266 tenant_id: "demo-tenant".to_owned(),
1267 organizer_id: "demo-me".to_owned(),
1268 meeting_data: None,
1269 });
1270 }
1271 if scene.minimized() {
1272 self.show_call(false, cx);
1273 }
1274 if let Some(call) = self.call.as_mut().filter(|_| scene == DemoScene::Blocked) {
1275 call.model.recording_policy.call_recording = false;
1276 call.model.recording_policy.call_transcription = false;
1277 }
1278 if scene == DemoScene::Gallery {
1279 self.queue_demo_bubbles(conversation_id, cx);
1280 }
1281 if scene == DemoScene::Consult {
1282 if let Some(call) = self.call.as_mut() {
1283 call.model.apply(CallUpdate::State(CallState::Connected {
1284 since: Instant::now(),
1285 }));
1286 }
1287 self.start_consult(demo_consult_target(), cx);
1288 }
1289 }
1290
1291 fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {
1292 if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {
1293 self.finish_ring(ring_id, outcome, cx);
1294 }
1295 }
1296
1297 fn finish_ring(&mut self, ring_id: u64, outcome: RingOutcome, cx: &mut Context<Self>) {
1298 if let RingOutcome::Missed(missed) = outcome {
1299 if let Some(launcher) = &self.call_launcher {
1300 launcher.drop_ring(ring_id);
1301 }
1302 cx.emit(AppEvent::MissedCall(missed));
1303 }
1304 cx.emit(AppEvent::Ring);
1305 cx.notify();
1306 }
1307
1308 pub fn tick_rings(&mut self, cx: &mut Context<Self>) {
1309 if self.rings.is_empty() {
1310 return;
1311 }
1312 for (ring_id, outcome) in self.rings.tick(Instant::now()) {
1313 self.finish_ring(ring_id, outcome, cx);
1314 }
1315 }
1316
1317 pub fn accept_ringing_call(&mut self, mode: AcceptMode, cx: &mut Context<Self>) {
1318 if let Some(ring_id) = self.rings.first_ringing_id() {
1319 self.accept_ring(ring_id, mode, cx);
1320 }
1321 }
1322
1323 pub fn decline_ringing_call(&mut self, cx: &mut Context<Self>) {
1324 if let Some(ring_id) = self.rings.first_ringing_id() {
1325 self.decline_ring(ring_id, cx);
1326 }
1327 }
1328
1329 pub fn accept_ring(&mut self, ring_id: u64, mode: AcceptMode, cx: &mut Context<Self>) {
1330 let Some(entry) = self.rings.get(ring_id).cloned() else {
1331 return;
1332 };
1333 if self.call.is_some() {
1334 self.leave_call(cx);
1335 }
1336 if let Some(held) = &self.held_call {
1337 let _ = held.commands.send(CallCommand::Hangup);
1338 }
1339 self.signal_ring(ring_id, RingSignal::Accept, cx);
1340 let conversation_id = entry.ring.thread_id.clone();
1341 let title = conversation_id
1342 .as_deref()
1343 .and_then(|id| self.sidebar.chats.iter().find(|chat| chat.id == id))
1344 .filter(|_| entry.ring.is_group)
1345 .map(chat_title)
1346 .unwrap_or_else(|| entry.caller_name().to_owned());
1347 let model = CallModel::incoming(&title, &entry.ring.caller.mri, entry.caller_name());
1348 if entry.demo {
1349 let handle = start_demo_call(DemoCall::Incoming(demo_caller()));
1350 self.begin_call(handle, model, conversation_id, cx);
1351 if mode == AcceptMode::Video {
1352 self.send_call_command(CallCommand::SetCamera(true));
1353 }
1354 return;
1355 }
1356 let Some(launcher) = self.call_launcher.clone() else {
1357 self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
1358 return;
1359 };
1360 let receiver =
1361 crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });
1362 cx.spawn(async move |this, cx| {
1363 let handle = receiver.await.ok().flatten();
1364 this.update(cx, |state, cx| match handle {
1365 Some(handle) => state.begin_call(handle, model, conversation_id, cx),
1366 None => state.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx),
1367 })
1368 .ok();
1369 })
1370 .detach();
1371 }
1372
1373 pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
1374 let Some(entry) = self.rings.get(ring_id) else {
1375 return;
1376 };
1377 let demo = entry.demo;
1378 if !demo && let Some(launcher) = &self.call_launcher {
1379 launcher.decline_ring(ring_id);
1380 }
1381 self.signal_ring(ring_id, RingSignal::Decline, cx);
1382 }
1383
1384 pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {
1385 if let Some(thread_id) = missed
1386 .thread_id
1387 .as_ref()
1388 .filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id))
1389 {
1390 return Some(thread_id.clone());
1391 }
1392 let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;
1393 self.sidebar
1394 .chats
1395 .iter()
1396 .find(|chat| {
1397 crate::data::is_one_on_one(chat)
1398 && chat
1399 .members
1400 .iter()
1401 .any(|member| member.user_id.as_deref() == Some(user_id))
1402 })
1403 .map(|chat| chat.id.clone())
1404 }
1405}
1406
1407impl AppState {
1408 pub fn running_meeting(&self, conversation_id: &str) -> Option<&LiveMeeting> {
1409 self.live_meetings
1410 .get(conversation_id)
1411 .filter(|meeting| meeting.is_running(now_unix()) && meeting.target().is_some())
1412 }
1413
1414 pub fn demo_live_meetings(&mut self) {
1415 for conversation_id in ["demo-chat-meeting-standup", DEMO_LOBBY_MEETING] {
1416 self.live_meetings.insert(
1417 conversation_id.to_owned(),
1418 LiveMeeting {
1419 thread_id: conversation_id.to_owned(),
1420 conversation_url: None,
1421 expiration: Some(now_unix() + DEMO_LIVE_MINUTES * 60),
1422 organizer_id: Some("demo-jonas".to_owned()),
1423 tenant_id: Some("demo-tenant".to_owned()),
1424 meeting_code: None,
1425 passcode: None,
1426 },
1427 );
1428 }
1429 }
1430
1431 pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {
1432 let meeting_chat =
1433 self.sidebar.chats.iter().any(|chat| {
1434 chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND)
1435 });
1436 meeting_chat
1437 || matches!(
1438 selection_for(&self.sidebar, conversation_id),
1439 Some(Selection::Channel(_))
1440 )
1441 }
1442
1443 pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1444 if self.watches_live_meeting(conversation_id) {
1445 self.fetch_live_meeting(conversation_id, cx);
1446 }
1447 }
1448
1449 pub fn fetch_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1450 if self.mode.demo {
1451 return;
1452 }
1453 let Some(launcher) = self.call_launcher.clone() else {
1454 return;
1455 };
1456 if !self.live_refreshing.insert(conversation_id.to_owned()) {
1457 return;
1458 }
1459 let thread_id = conversation_id.to_owned();
1460 let receiver =
1461 crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
1462 let conversation_id = conversation_id.to_owned();
1463 cx.spawn(async move |this, cx| {
1464 let meeting = receiver.await.ok().flatten();
1465 this.update(cx, |state, cx| {
1466 state.apply_live_meeting(conversation_id, meeting, cx)
1467 })
1468 .ok();
1469 })
1470 .detach();
1471 }
1472
1473 pub fn apply_live_meeting(
1474 &mut self,
1475 conversation_id: String,
1476 meeting: Option<LiveMeeting>,
1477 cx: &mut Context<Self>,
1478 ) {
1479 self.live_refreshing.remove(&conversation_id);
1480 let changed = match meeting {
1481 Some(meeting) => {
1482 self.live_meetings
1483 .insert(conversation_id.clone(), meeting.clone())
1484 != Some(meeting)
1485 }
1486 None => self.live_meetings.remove(&conversation_id).is_some(),
1487 };
1488 if changed {
1489 cx.emit(AppEvent::LiveMeeting);
1490 cx.notify();
1491 }
1492 }
1493
1494 pub fn on_thread_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1495 self.refresh_live_meeting(conversation_id, cx);
1496 }
1497}
1498
1499#[cfg(test)]
1500mod tests {
1501 use std::sync::Arc;
1502 use std::time::{Duration, Instant};
1503
1504 use std::path::PathBuf;
1505
1506 use calling::{
1507 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1508 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, RecordingKind,
1509 StopScope, VideoQuality, call_channel,
1510 };
1511 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1512 use store::{ChatRecord, MemberRecord, Store};
1513
1514 use super::{
1515 ActiveCall, CallModel, load_camera, load_camera_effects, load_input, load_output,
1516 load_video_quality,
1517 };
1518 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1519 use crate::call::TransferCandidate;
1520 use crate::call::background::BackgroundPick;
1521 use crate::call::demo::demo_ring;
1522 use crate::call::features::room_closed_move;
1523 use crate::call::model::BreakoutState;
1524 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1525 use crate::data::Person;
1526 use chatsvc::sounds::CallTone;
1527
1528 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1529 cx.update(gpui_kit::init);
1530 let store = Arc::new(Store::open_in_memory().unwrap());
1531 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1532 let (handle, _control) = call_channel();
1533 cx.update(|cx| {
1534 app.update(cx, |state, _| {
1535 state.call = Some(ActiveCall::new(
1536 7,
1537 CallModel::test(),
1538 handle.commands,
1539 None,
1540 handle.video,
1541 ));
1542 })
1543 });
1544 app
1545 }
1546
1547 fn app_with_commands(
1548 cx: &mut TestAppContext,
1549 model: CallModel,
1550 conversation_id: Option<&str>,
1551 ) -> (Entity<AppState>, CallControl) {
1552 cx.update(gpui_kit::init);
1553 let store = Arc::new(Store::open_in_memory().unwrap());
1554 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1555 let (handle, control) = call_channel();
1556 let conversation_id = conversation_id.map(str::to_owned);
1557 cx.update(|cx| {
1558 app.update(cx, |state, _| {
1559 state.call = Some(ActiveCall::new(
1560 7,
1561 model,
1562 handle.commands,
1563 conversation_id,
1564 handle.video,
1565 ));
1566 })
1567 });
1568 (app, control)
1569 }
1570
1571 fn live_meeting(can_end: bool) -> CallModel {
1572 let mut model = CallModel::meeting("Standup", can_end);
1573 model.apply(CallUpdate::State(CallState::Connected {
1574 since: Instant::now(),
1575 }));
1576 model.apply(CallUpdate::OwnIdentity {
1577 mri: "8:orgid:me".into(),
1578 });
1579 model
1580 }
1581
1582 #[gpui_kit::test]
1583 fn high_rate_updates_do_not_emit_call_events(cx: &mut TestAppContext) {
1584 let app = app_with_call(cx);
1585 let emitted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1586 let counter = emitted.clone();
1587 cx.update(|cx| {
1588 cx.subscribe(&app, move |_, event: &AppEvent, _| {
1589 if matches!(event, AppEvent::Call) {
1590 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1591 }
1592 })
1593 .detach();
1594 app.update(cx, |state, cx| {
1595 state.apply_call_update(7, CallUpdate::VideoReady, cx);
1596 state.apply_call_update(
1597 7,
1598 CallUpdate::Levels {
1599 local: 0.5,
1600 remote: 0.5,
1601 },
1602 cx,
1603 );
1604 state.apply_call_update(
1605 7,
1606 CallUpdate::Stats {
1607 inbound_packets: 1,
1608 outbound_packets: 1,
1609 },
1610 cx,
1611 );
1612 });
1613 });
1614 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);
1615 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));
1616 cx.update(|cx| {
1617 app.update(cx, |state, cx| {
1618 state.apply_call_update(7, CallUpdate::Muted(true), cx)
1619 })
1620 });
1621 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);
1622 }
1623
1624 #[gpui_kit::test]
1625 fn a_camera_the_peer_stops_leaves_the_tile_at_once(cx: &mut TestAppContext) {
1626 let app = app_with_call(cx);
1627 let key = calling::VideoKey::Person("8:orgid:peer".into());
1628 let shown = |app: &Entity<AppState>, cx: &mut TestAppContext| {
1629 cx.update(|cx| {
1630 app.read(cx)
1631 .call
1632 .as_ref()
1633 .unwrap()
1634 .pictures
1635 .live(&key, Instant::now())
1636 .is_some()
1637 })
1638 };
1639 cx.update(|cx| {
1640 app.update(cx, |state, cx| {
1641 let hub = state.call.as_ref().unwrap().video.clone();
1642 hub.publish(key.clone(), calling::VideoPicture::solid(4, 4, 10, 20, 30));
1643 state.apply_call_update(7, CallUpdate::VideoReady, cx);
1644 })
1645 });
1646 assert!(shown(&app, cx));
1647 cx.update(|cx| {
1648 app.update(cx, |state, cx| {
1649 state.apply_call_update(7, CallUpdate::VideoStopped(key.clone()), cx)
1650 })
1651 });
1652 assert!(!shown(&app, cx));
1653 }
1654
1655 #[gpui_kit::test]
1656 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1657 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1658 let store = cx.update(|cx| app.read(cx).store.clone());
1659 assert!(!cx.update(|cx| app.read(cx).call_share_sound));
1660 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));
1661 assert_eq!(
1662 control.try_recv_command(),
1663 Some(CallCommand::SetShareSound(true))
1664 );
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 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));
1668 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1669 assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));
1670 }
1671
1672 #[gpui_kit::test]
1673 fn in_call_device_picks_are_saved_including_system_default(cx: &mut TestAppContext) {
1674 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1675 let store = cx.update(|cx| app.read(cx).store.clone());
1676 assert_eq!(load_input(&store), DeviceChoice::SystemDefault);
1677 cx.update(|cx| {
1678 app.update(cx, |state, cx| {
1679 state.select_call_input(DeviceChoice::Device("headset-mic".into()), cx);
1680 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1681 })
1682 });
1683 assert_eq!(
1684 load_input(&store),
1685 DeviceChoice::Device("headset-mic".into())
1686 );
1687 assert_eq!(load_output(&store), DeviceChoice::Device("headset".into()));
1688 assert_eq!(
1689 control.try_recv_command(),
1690 Some(CallCommand::SelectInput(DeviceChoice::Device(
1691 "headset-mic".into()
1692 )))
1693 );
1694 cx.update(|cx| {
1695 app.update(cx, |state, cx| {
1696 state.select_call_input(DeviceChoice::SystemDefault, cx)
1697 })
1698 });
1699 assert_eq!(load_input(&store), DeviceChoice::SystemDefault);
1700 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1701 assert_eq!(
1702 cx.update(|cx| reopened.read(cx).call_output.clone()),
1703 DeviceChoice::Device("headset".into())
1704 );
1705 }
1706
1707 #[gpui_kit::test]
1708 fn every_call_starts_with_the_saved_devices_even_when_they_are_not_present(
1709 cx: &mut TestAppContext,
1710 ) {
1711 cx.update(gpui_kit::init);
1712 let store = Arc::new(Store::open_in_memory().unwrap());
1713 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1714 cx.update(|cx| {
1715 app.update(cx, |state, cx| {
1716 state.select_call_input(DeviceChoice::Device("unplugged-mic".into()), cx);
1717 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1718 })
1719 });
1720 let (handle, mut control) = call_channel();
1721 cx.update(|cx| {
1722 app.update(cx, |state, cx| {
1723 state.begin_call(handle, CallModel::test(), None, cx)
1724 })
1725 });
1726 let mut commands = Vec::new();
1727 while let Some(command) = control.try_recv_command() {
1728 commands.push(command);
1729 }
1730 assert!(
1731 commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1732 "unplugged-mic".into()
1733 )))
1734 );
1735 assert!(
1736 commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1737 "headset".into()
1738 )))
1739 );
1740 assert!(commands.contains(&CallCommand::SetVideoQuality(VideoQuality::Auto)));
1741 assert_eq!(
1742 load_input(&store),
1743 DeviceChoice::Device("unplugged-mic".into())
1744 );
1745 }
1746
1747 #[gpui_kit::test]
1748 fn the_camera_pick_is_remembered_and_the_next_call_starts_with_it(cx: &mut TestAppContext) {
1749 let (app, _control) = app_with_commands(cx, live_meeting(false), None);
1750 let store = cx.update(|cx| app.read(cx).store.clone());
1751 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1752 cx.update(|cx| {
1753 app.update(cx, |state, cx| {
1754 state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)
1755 })
1756 });
1757 assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));
1758 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1759 assert_eq!(
1760 cx.update(|cx| reopened.read(cx).call_camera.clone()),
1761 DeviceChoice::Device("cam-2".into())
1762 );
1763 cx.update(|cx| {
1764 app.update(cx, |state, cx| {
1765 state.select_call_camera(DeviceChoice::SystemDefault, cx)
1766 })
1767 });
1768 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1769 }
1770
1771 #[gpui_kit::test]
1772 fn the_camera_effects_are_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1773 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1774 let store = cx.update(|cx| app.read(cx).store.clone());
1775 assert_eq!(load_camera_effects(&store), CameraEffects::default());
1776 let effects = CameraEffects {
1777 mirror: false,
1778 auto_framing: true,
1779 soft_focus: true,
1780 soft_focus_strength: 75,
1781 ..CameraEffects::default()
1782 };
1783 cx.update(|cx| app.update(cx, |state, cx| state.set_call_effects(effects, cx)));
1784 assert_eq!(
1785 control.try_recv_command(),
1786 Some(CallCommand::SetCameraEffects(effects))
1787 );
1788 assert_eq!(load_camera_effects(&store), effects);
1789 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1790 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1791 }
1792
1793 #[gpui_kit::test]
1794 fn the_video_quality_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1795 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1796 let store = cx.update(|cx| app.read(cx).store.clone());
1797 assert_eq!(load_video_quality(&store), VideoQuality::Auto);
1798 cx.update(|cx| {
1799 app.update(cx, |state, cx| {
1800 state.set_call_video_quality(VideoQuality::P1080, cx)
1801 })
1802 });
1803 assert_eq!(
1804 control.try_recv_command(),
1805 Some(CallCommand::SetVideoQuality(VideoQuality::P1080))
1806 );
1807 assert_eq!(load_video_quality(&store), VideoQuality::P1080);
1808 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1809 assert_eq!(
1810 cx.update(|cx| reopened.read(cx).call_video_quality),
1811 VideoQuality::P1080
1812 );
1813 }
1814
1815 #[gpui_kit::test]
1816 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1817 cx: &mut TestAppContext,
1818 ) {
1819 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1820 cx.update(|cx| {
1821 app.update(cx, |state, cx| {
1822 state.toggle_call_hand(cx);
1823 state.send_call_reaction(Reaction::Heart, cx);
1824 state.lower_call_hand("8:orgid:a".into(), cx);
1825 state.lower_all_call_hands(cx);
1826 })
1827 });
1828 assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));
1829 assert_eq!(
1830 control.try_recv_command(),
1831 Some(CallCommand::SendReaction(Reaction::Heart))
1832 );
1833 assert_eq!(control.try_recv_command(), None);
1834 let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);
1835 cx.update(|cx| {
1836 organizer.update(cx, |state, cx| {
1837 state.apply_call_update(
1838 7,
1839 CallUpdate::Roster(vec![calling::RosterEntry {
1840 mri: "8:orgid:a".into(),
1841 display_name: "Ana".into(),
1842 muted: false,
1843 in_lobby: false,
1844 has_video: false,
1845 sharing: false,
1846 hand: Some(calling::RaisedHand {
1847 state_id: "s".into(),
1848 rank: 1,
1849 }),
1850 spotlight: None,
1851 organizer: false,
1852 ..Default::default()
1853 }]),
1854 cx,
1855 );
1856 state.lower_call_hand("8:orgid:a".into(), cx);
1857 state.lower_all_call_hands(cx);
1858 })
1859 });
1860 assert_eq!(
1861 organizer_control.try_recv_command(),
1862 Some(CallCommand::LowerHand {
1863 mri: "8:orgid:a".into()
1864 })
1865 );
1866 assert_eq!(
1867 organizer_control.try_recv_command(),
1868 Some(CallCommand::LowerAllHands)
1869 );
1870 }
1871
1872 fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {
1873 calling::RosterEntry {
1874 mri: mri.into(),
1875 display_name: name.into(),
1876 muted: false,
1877 in_lobby,
1878 has_video: false,
1879 sharing: false,
1880 hand: None,
1881 spotlight: spotlit.then(|| calling::Spotlight {
1882 state_id: "sp".into(),
1883 rank: 1,
1884 }),
1885 organizer: false,
1886 ..Default::default()
1887 }
1888 }
1889
1890 #[gpui_kit::test]
1891 fn organizer_controls_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {
1892 let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1893 cx.update(|cx| {
1894 attendee.update(cx, |state, cx| {
1895 state.admit_call_guest("8:orgid:g".into(), cx);
1896 state.admit_all_call_guests(cx);
1897 state.deny_call_guest("8:orgid:g".into(), cx);
1898 state.mute_call_participant("8:orgid:a".into(), cx);
1899 state.mute_all_call(cx);
1900 state.remove_call_participant("8:orgid:a".into(), cx);
1901 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1902 })
1903 });
1904 assert_eq!(attendee_control.try_recv_command(), None);
1905 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1906 cx.update(|cx| {
1907 organizer.update(cx, |state, cx| {
1908 state.apply_call_update(
1909 7,
1910 CallUpdate::Roster(vec![
1911 guest("8:orgid:a", "Ana", false, false),
1912 guest("8:orgid:g", "Gast", true, false),
1913 ]),
1914 cx,
1915 );
1916 state.admit_call_guest("8:orgid:g".into(), cx);
1917 state.admit_all_call_guests(cx);
1918 state.deny_call_guest("8:orgid:g".into(), cx);
1919 state.mute_call_participant("8:orgid:a".into(), cx);
1920 state.mute_all_call(cx);
1921 state.remove_call_participant("8:orgid:a".into(), cx);
1922 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1923 })
1924 });
1925 assert_eq!(
1926 control.try_recv_command(),
1927 Some(CallCommand::Admit {
1928 mri: "8:orgid:g".into()
1929 })
1930 );
1931 assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));
1932 assert_eq!(
1933 control.try_recv_command(),
1934 Some(CallCommand::Deny {
1935 mri: "8:orgid:g".into()
1936 })
1937 );
1938 assert_eq!(
1939 control.try_recv_command(),
1940 Some(CallCommand::MuteParticipant {
1941 mri: "8:orgid:a".into()
1942 })
1943 );
1944 assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));
1945 assert_eq!(
1946 control.try_recv_command(),
1947 Some(CallCommand::RemoveParticipant {
1948 mri: "8:orgid:a".into()
1949 })
1950 );
1951 assert_eq!(
1952 control.try_recv_command(),
1953 Some(CallCommand::Spotlight {
1954 mri: "8:orgid:a".into()
1955 })
1956 );
1957 }
1958
1959 #[gpui_kit::test]
1960 fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(
1961 cx: &mut TestAppContext,
1962 ) {
1963 let (app, mut control) = app_with_commands(cx, live_meeting(true), None);
1964 cx.update(|cx| {
1965 app.update(cx, |state, cx| {
1966 state.apply_call_update(
1967 7,
1968 CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]),
1969 cx,
1970 );
1971 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1972 state.toggle_call_pin("8:orgid:a", cx);
1973 assert_eq!(
1974 state.call.as_ref().unwrap().model.pinned.as_deref(),
1975 Some("8:orgid:a")
1976 );
1977 state.toggle_call_pin("8:orgid:a", cx);
1978 assert_eq!(state.call.as_ref().unwrap().model.pinned, None);
1979 })
1980 });
1981 assert_eq!(
1982 control.try_recv_command(),
1983 Some(CallCommand::StopSpotlight {
1984 mri: "8:orgid:a".into()
1985 })
1986 );
1987 assert_eq!(control.try_recv_command(), None);
1988 }
1989
1990 #[gpui_kit::test]
1991 fn captions_toggle_between_on_and_off_and_only_in_meetings(cx: &mut TestAppContext) {
1992 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1993 cx.update(|cx| {
1994 app.update(cx, |state, cx| {
1995 state.toggle_call_captions(cx);
1996 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1997 state.toggle_call_captions(cx);
1998 })
1999 });
2000 assert_eq!(
2001 control.try_recv_command(),
2002 Some(CallCommand::SetCaptions(true))
2003 );
2004 assert_eq!(
2005 control.try_recv_command(),
2006 Some(CallCommand::SetCaptions(false))
2007 );
2008 let app = app_with_call(cx);
2009 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));
2010 }
2011
2012 #[gpui_kit::test]
2013 fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
2014 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2015 let store = cx.update(|cx| app.read(cx).store.clone());
2016 assert_eq!(
2017 cx.update(|cx| app.read(cx).call_background.clone()),
2018 BackgroundPick::None
2019 );
2020 cx.update(|cx| {
2021 app.update(cx, |state, cx| {
2022 state.set_call_background(BackgroundPick::Blur, cx)
2023 })
2024 });
2025 assert_eq!(
2026 control.try_recv_command(),
2027 Some(CallCommand::SetBackground(BackgroundChoice::Blur))
2028 );
2029 assert_eq!(
2030 cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()),
2031 BackgroundPick::Blur
2032 );
2033 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
2034 assert_eq!(
2035 cx.update(|cx| reopened.read(cx).call_background.clone()),
2036 BackgroundPick::Blur
2037 );
2038 let picture = PathBuf::from("/pictures/wall.jpg");
2039 cx.update(|cx| {
2040 app.update(cx, |state, cx| {
2041 state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)
2042 })
2043 });
2044 assert_eq!(
2045 control.try_recv_command(),
2046 Some(CallCommand::SetBackground(BackgroundChoice::Image(
2047 picture.clone()
2048 )))
2049 );
2050 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
2051 assert_eq!(
2052 cx.update(|cx| reopened.read(cx).call_background.clone()),
2053 BackgroundPick::Custom(picture)
2054 );
2055 cx.update(|cx| {
2056 app.update(cx, |state, cx| {
2057 state.set_call_background(BackgroundPick::None, cx)
2058 })
2059 });
2060 assert_eq!(
2061 control.try_recv_command(),
2062 Some(CallCommand::SetBackground(BackgroundChoice::None))
2063 );
2064 }
2065
2066 #[gpui_kit::test]
2067 fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {
2068 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2069 cx.update(|cx| {
2070 app.update(cx, |state, cx| {
2071 state.set_call_background(BackgroundPick::Default("office_01".into()), cx)
2072 })
2073 });
2074 assert_eq!(control.try_recv_command(), None);
2075 }
2076
2077 #[gpui_kit::test]
2078 fn attendees_cannot_start_a_recording_and_the_notice_needs_a_consent_request(
2079 cx: &mut TestAppContext,
2080 ) {
2081 let mut attendee_model = live_meeting(false);
2082 attendee_model.own_role = Some(calling::MeetingRole::Attendee);
2083 let (attendee, mut attendee_control) = app_with_commands(cx, attendee_model, None);
2084 cx.update(|cx| {
2085 attendee.update(cx, |state, cx| {
2086 state.run_call_record_action(RecordAction::Start(RecordingKind::Video), cx);
2087 state.accept_recording_notice(cx);
2088 })
2089 });
2090 assert_eq!(attendee_control.try_recv_command(), None);
2091 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
2092 cx.update(|cx| {
2093 organizer.update(cx, |state, cx| {
2094 state.run_call_record_action(RecordAction::Start(RecordingKind::Video), cx);
2095 state.apply_call_update(7, CallUpdate::Recording(true), cx);
2096 state.run_call_record_action(RecordAction::Stop(StopScope::Both), cx);
2097 state.accept_recording_notice(cx);
2098 state.apply_call_update(7, CallUpdate::ConsentRequired(true), cx);
2099 state.accept_recording_notice(cx);
2100 })
2101 });
2102 assert_eq!(
2103 control.try_recv_command(),
2104 Some(CallCommand::StartRecording {
2105 kind: RecordingKind::Video,
2106 title: "Standup".into()
2107 })
2108 );
2109 assert_eq!(
2110 control.try_recv_command(),
2111 Some(CallCommand::StopRecording {
2112 scope: StopScope::Both
2113 })
2114 );
2115 assert_eq!(
2116 control.try_recv_command(),
2117 Some(CallCommand::ConsentToRecording)
2118 );
2119 assert_eq!(control.try_recv_command(), None);
2120 }
2121
2122 #[gpui_kit::test]
2123 fn every_record_action_becomes_its_own_command_for_the_organizer(cx: &mut TestAppContext) {
2124 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
2125 cx.update(|cx| {
2126 organizer.update(cx, |state, cx| {
2127 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
2128 state
2129 .run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
2130 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
2131 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
2132 })
2133 });
2134 let title = "Standup".to_owned();
2135 assert_eq!(
2136 control.try_recv_command(),
2137 Some(CallCommand::StartRecording {
2138 kind: RecordingKind::AudioOnly,
2139 title: title.clone()
2140 })
2141 );
2142 assert_eq!(
2143 control.try_recv_command(),
2144 Some(CallCommand::StartRecording {
2145 kind: RecordingKind::TranscriptOnly,
2146 title
2147 })
2148 );
2149 assert_eq!(
2150 control.try_recv_command(),
2151 Some(CallCommand::StopRecording {
2152 scope: StopScope::RecordingOnly
2153 })
2154 );
2155 assert_eq!(
2156 control.try_recv_command(),
2157 Some(CallCommand::StopRecording {
2158 scope: StopScope::TranscriptionOnly
2159 })
2160 );
2161 assert_eq!(control.try_recv_command(), None);
2162 }
2163
2164 #[gpui_kit::test]
2165 fn the_transcript_turns_captions_on_and_excludes_the_chat_panel(cx: &mut TestAppContext) {
2166 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2167 cx.update(|cx| {
2168 app.update(cx, |state, cx| {
2169 state.apply_call_update(
2170 7,
2171 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2172 cx,
2173 );
2174 state.toggle_call_chat(cx);
2175 state.show_call_transcript(cx);
2176 })
2177 });
2178 let (chat_open, transcript_open) = cx.update(|cx| {
2179 let call = app.read(cx).call.as_ref().unwrap();
2180 (call.chat_open, call.transcript_open)
2181 });
2182 assert!(!chat_open && transcript_open);
2183 assert_eq!(
2184 control.try_recv_command(),
2185 Some(CallCommand::SetCaptions(true))
2186 );
2187 cx.update(|cx| {
2188 app.update(cx, |state, cx| {
2189 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
2190 state.show_call_transcript(cx);
2191 state.toggle_call_chat(cx);
2192 })
2193 });
2194 let (chat_open, transcript_open) = cx.update(|cx| {
2195 let call = app.read(cx).call.as_ref().unwrap();
2196 (call.chat_open, call.transcript_open)
2197 });
2198 assert!(chat_open && !transcript_open);
2199 assert_eq!(control.try_recv_command(), None);
2200 }
2201
2202 #[gpui_kit::test]
2203 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(
2204 cx: &mut TestAppContext,
2205 ) {
2206 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2207 cx.update(|cx| {
2208 app.update(cx, |state, cx| {
2209 state.choose_call_caption_language("de-DE", cx);
2210 state.apply_call_update(
2211 7,
2212 CallUpdate::Captions(calling::CaptionState::Starting),
2213 cx,
2214 );
2215 })
2216 });
2217 assert_eq!(
2218 control.try_recv_command(),
2219 Some(CallCommand::SetCaptions(true))
2220 );
2221 assert_eq!(control.try_recv_command(), None);
2222 cx.update(|cx| {
2223 app.update(cx, |state, cx| {
2224 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
2225 state.choose_call_caption_language("fr-FR", cx);
2226 })
2227 });
2228 assert_eq!(
2229 control.try_recv_command(),
2230 Some(CallCommand::SetCaptionLanguage("de-DE".into()))
2231 );
2232 assert_eq!(
2233 control.try_recv_command(),
2234 Some(CallCommand::SetCaptionLanguage("fr-FR".into()))
2235 );
2236 assert_eq!(control.try_recv_command(), None);
2237 }
2238
2239 #[gpui_kit::test]
2240 fn caption_size_and_position_are_stored_and_reach_the_call_model(cx: &mut TestAppContext) {
2241 let (app, _control) = app_with_commands(cx, live_meeting(false), None);
2242 cx.update(|cx| {
2243 app.update(cx, |state, cx| {
2244 state.set_call_caption_size(CaptionSize::Large, cx);
2245 state.set_call_caption_position(CaptionPosition::Top, cx);
2246 })
2247 });
2248 let (view, stored) = cx.update(|cx| {
2249 let state = app.read(cx);
2250 (
2251 state.call.as_ref().unwrap().model.view,
2252 ViewSettings::load(&state.store),
2253 )
2254 });
2255 assert_eq!(
2256 (view.caption_size, view.caption_position),
2257 (CaptionSize::Large, CaptionPosition::Top)
2258 );
2259 assert_eq!(
2260 (stored.caption_size, stored.caption_position),
2261 (CaptionSize::Large, CaptionPosition::Top)
2262 );
2263 }
2264
2265 fn live_one_to_one() -> CallModel {
2266 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
2267 model.apply(CallUpdate::State(CallState::Connected {
2268 since: Instant::now(),
2269 }));
2270 model
2271 }
2272
2273 #[gpui_kit::test]
2274 fn hold_and_resume_alternate_and_stop_while_the_other_side_holds(cx: &mut TestAppContext) {
2275 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2276 cx.update(|cx| {
2277 app.update(cx, |state, cx| {
2278 state.toggle_call_hold(cx);
2279 state.apply_call_update(7, CallUpdate::Hold(HoldState::Local), cx);
2280 state.toggle_call_hold(cx);
2281 state.apply_call_update(7, CallUpdate::Hold(HoldState::Remote), cx);
2282 state.toggle_call_hold(cx);
2283 })
2284 });
2285 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(true)));
2286 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(false)));
2287 assert_eq!(control.try_recv_command(), None);
2288 let (meeting, mut meeting_control) = app_with_commands(cx, live_meeting(true), None);
2289 cx.update(|cx| meeting.update(cx, |state, cx| state.toggle_call_hold(cx)));
2290 assert_eq!(meeting_control.try_recv_command(), None);
2291 }
2292
2293 fn candidate(name: &str) -> TransferCandidate {
2294 TransferCandidate {
2295 mri: format!("8:orgid:{name}"),
2296 name: name.into(),
2297 user_id: Some(name.into()),
2298 chat_id: format!("19:{name}"),
2299 }
2300 }
2301
2302 #[gpui_kit::test]
2303 fn a_blind_transfer_names_the_target(cx: &mut TestAppContext) {
2304 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2305 cx.update(|cx| {
2306 app.update(cx, |state, cx| {
2307 state.transfer_call_blind(candidate("ana"), cx)
2308 })
2309 });
2310 assert_eq!(
2311 control.try_recv_command(),
2312 Some(CallCommand::Transfer {
2313 target: calling::Callee {
2314 mri: "8:orgid:ana".into(),
2315 display_name: "ana".into()
2316 },
2317 replaces: None
2318 })
2319 );
2320 }
2321
2322 #[gpui_kit::test]
2323 fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(
2324 cx: &mut TestAppContext,
2325 ) {
2326 let app = app_with_chats(cx);
2327 cx.update(|cx| {
2328 app.update(cx, |state, cx| {
2329 let names: Vec<String> = state
2330 .transfer_candidates()
2331 .into_iter()
2332 .map(|candidate| candidate.name)
2333 .collect();
2334 assert_eq!(names, vec!["Bea".to_owned()]);
2335 let (handle, _control) = call_channel();
2336 let mut on_the_call =
2337 CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);
2338 on_the_call.apply(CallUpdate::State(CallState::Connected {
2339 since: Instant::now(),
2340 }));
2341 state.call = Some(ActiveCall::new(
2342 9,
2343 on_the_call,
2344 handle.commands,
2345 None,
2346 handle.video,
2347 ));
2348 assert!(state.transfer_candidates().is_empty());
2349 cx.notify();
2350 })
2351 });
2352 }
2353
2354 fn room_move(returning: bool) -> calling::BreakoutMove {
2355 calling::BreakoutMove {
2356 room_name: "Room 1".into(),
2357 target: calling::MeetingTarget {
2358 thread_id: "19:meeting_room@thread.v2".into(),
2359 tenant_id: "t".into(),
2360 organizer_id: "o".into(),
2361 meeting_data: None,
2362 },
2363 returning,
2364 }
2365 }
2366
2367 fn main_target() -> calling::MeetingTarget {
2368 calling::MeetingTarget {
2369 thread_id: "19:meeting_main@thread.v2".into(),
2370 tenant_id: "t".into(),
2371 organizer_id: "o".into(),
2372 meeting_data: None,
2373 }
2374 }
2375
2376 #[gpui_kit::test]
2377 fn being_moved_to_a_room_leaves_the_call_and_remembers_the_way_back(cx: &mut TestAppContext) {
2378 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2379 cx.update(|cx| {
2380 app.update(cx, |state, cx| {
2381 state.call.as_mut().unwrap().meeting_target = Some(main_target());
2382 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
2383 let pending = state
2384 .call
2385 .as_ref()
2386 .unwrap()
2387 .pending_move
2388 .clone()
2389 .expect("a move is pending");
2390 assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");
2391 assert_eq!(pending.title, "Room 1");
2392 let room = pending.breakout.expect("a room");
2393 assert_eq!(room.main, Some(main_target()));
2394 assert_eq!(room.main_title, "Standup");
2395 assert_eq!(
2396 state.notice.as_ref().map(|notice| notice.text.as_str()),
2397 Some("Moving you to Room 1")
2398 );
2399 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
2400 })
2401 });
2402 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
2403 assert_eq!(control.try_recv_command(), None);
2404 }
2405
2406 #[gpui_kit::test]
2407 fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(
2408 cx: &mut TestAppContext,
2409 ) {
2410 let mut room = live_meeting(false);
2411 room.breakout = Some(BreakoutState {
2412 room_name: "Room 1".into(),
2413 main: Some(main_target()),
2414 main_title: "Standup".into(),
2415 });
2416 let (app, mut control) = app_with_commands(cx, room.clone(), None);
2417 cx.update(|cx| {
2418 app.update(cx, |state, cx| {
2419 state.return_to_main_meeting(cx);
2420 let pending = state
2421 .call
2422 .as_ref()
2423 .unwrap()
2424 .pending_move
2425 .clone()
2426 .expect("a move is pending");
2427 assert_eq!(pending.target, main_target());
2428 assert_eq!(pending.title, "Standup");
2429 assert!(pending.breakout.is_none());
2430 })
2431 });
2432 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
2433 let (closed, _control) = app_with_commands(cx, room, None);
2434 cx.update(|cx| {
2435 closed.update(cx, |state, _| {
2436 let call = state.call.as_ref().unwrap();
2437 let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed))
2438 .expect("goes back");
2439 assert_eq!(moved.target, main_target());
2440 assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());
2441 assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());
2442 })
2443 });
2444 let (plain, _control) = app_with_commands(cx, live_meeting(false), None);
2445 cx.update(|cx| {
2446 plain.update(cx, |state, _| {
2447 assert!(
2448 room_closed_move(
2449 state.call.as_ref().unwrap(),
2450 &EndReason::Remote(EndKind::RoomClosed)
2451 )
2452 .is_none()
2453 )
2454 })
2455 });
2456 }
2457
2458 #[gpui_kit::test]
2459 fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(
2460 cx: &mut TestAppContext,
2461 ) {
2462 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2463 cx.update(|cx| {
2464 app.update(cx, |state, cx| {
2465 state.open_call_whiteboard(cx);
2466 state.apply_call_update(
2467 7,
2468 CallUpdate::Whiteboard(Some(calling::ContentShare {
2469 session_id: "s".into(),
2470 presenter: Some("8:orgid:ana".into()),
2471 subject: "Whiteboard".into(),
2472 url: Some("https://app.whiteboard.microsoft.com/x".into()),
2473 whiteboard: true,
2474 })),
2475 cx,
2476 );
2477 state.open_call_whiteboard(cx);
2478 })
2479 });
2480 assert_eq!(
2481 control.try_recv_command(),
2482 Some(CallCommand::OpenWhiteboard {
2483 title: "Standup".into()
2484 })
2485 );
2486 assert_eq!(control.try_recv_command(), None);
2487 }
2488
2489 #[gpui_kit::test]
2490 fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(
2491 cx: &mut TestAppContext,
2492 ) {
2493 let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
2494 cx.update(|cx| {
2495 app.update(cx, |state, cx| {
2496 state
2497 .directory
2498 .unread_counts
2499 .insert("19:meeting_x@thread.v2".into(), 3);
2500 assert_eq!(state.call_chat_thread(), None);
2501 assert_eq!(state.call_chat_unread(), 0);
2502 state.apply_call_update(
2503 7,
2504 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2505 cx,
2506 );
2507 assert_eq!(state.call_chat_unread(), 3);
2508 state.toggle_call_chat(cx);
2509 assert_eq!(
2510 state.call_chat_thread().as_deref(),
2511 Some("19:meeting_x@thread.v2")
2512 );
2513 assert_eq!(state.call_chat_unread(), 0);
2514 state.toggle_call_chat(cx);
2515 assert_eq!(state.call_chat_thread(), None);
2516 })
2517 });
2518 }
2519
2520 #[gpui_kit::test]
2521 fn a_call_without_a_chat_has_no_panel(cx: &mut TestAppContext) {
2522 let app = app_with_call(cx);
2523 cx.update(|cx| {
2524 app.update(cx, |state, cx| {
2525 state.toggle_call_chat(cx);
2526 assert!(!state.call.as_ref().unwrap().chat_open);
2527 })
2528 });
2529 }
2530
2531 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
2532 cx.update(gpui_kit::init);
2533 let store = Arc::new(Store::open_in_memory().unwrap());
2534 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
2535 cx.update(|cx| {
2536 app.update(cx, |state, _| {
2537 state.directory.me = Some(Person {
2538 user_id: "me-id".into(),
2539 display_name: "Me".into(),
2540 });
2541 state.sidebar.chats = vec![
2542 ChatRecord {
2543 id: "19:meeting@thread.v2".into(),
2544 kind: "meeting".into(),
2545 members: vec![MemberRecord {
2546 user_id: Some("bea-id".into()),
2547 display_name: "Bea".into(),
2548 }],
2549 ..Default::default()
2550 },
2551 ChatRecord {
2552 id: "19:dm@unq.gbl.spaces".into(),
2553 kind: "oneOnOne".into(),
2554 members: vec![
2555 MemberRecord {
2556 user_id: Some("me-id".into()),
2557 display_name: "Me".into(),
2558 },
2559 MemberRecord {
2560 user_id: Some("bea-id".into()),
2561 display_name: "Bea".into(),
2562 },
2563 ],
2564 ..Default::default()
2565 },
2566 ];
2567 })
2568 });
2569 app
2570 }
2571
2572 #[gpui_kit::test]
2573 fn declining_by_shortcut_only_acts_while_a_ring_shows(cx: &mut TestAppContext) {
2574 let app = app_with_chats(cx);
2575 cx.update(|cx| {
2576 app.update(cx, |state, cx| {
2577 state.decline_ringing_call(cx);
2578 assert!(!state.rings.is_ringing());
2579 state.demo_incoming_ring(cx);
2580 assert!(state.rings.is_ringing());
2581 state.decline_ringing_call(cx);
2582 assert!(!state.rings.is_ringing());
2583 })
2584 });
2585 }
2586
2587 #[gpui_kit::test]
2588 fn picking_another_chat_keeps_the_call_window_showing_the_call(cx: &mut TestAppContext) {
2589 let app = app_with_call(cx);
2590 cx.update(|cx| {
2591 app.update(cx, |state, cx| {
2592 assert!(state.viewing_call());
2593 state.select(Selection::Chat("c1".into()), cx);
2594 assert!(state.viewing_call());
2595 })
2596 });
2597 }
2598
2599 #[gpui_kit::test]
2600 fn an_ended_call_closes_the_view_and_raises_a_notice(cx: &mut TestAppContext) {
2601 let app = app_with_call(cx);
2602 let since = Instant::now() - Duration::from_secs(42);
2603 cx.update(|cx| {
2604 app.update(cx, |state, cx| {
2605 state.apply_call_update(7, CallUpdate::State(CallState::Connected { since }), cx);
2606 assert!(state.call.is_some());
2607 state.apply_call_update(
2608 7,
2609 CallUpdate::State(CallState::Ended {
2610 reason: EndReason::LocalHangup,
2611 }),
2612 cx,
2613 );
2614 assert!(state.call.is_none());
2615 let notice = state.notice.as_ref().expect("notice");
2616 assert_eq!(notice.text, "Call ended 00:42");
2617 })
2618 });
2619 }
2620
2621 #[gpui_kit::test]
2622 fn a_dropped_call_shows_the_end_screen_and_plays_the_end_tone(cx: &mut TestAppContext) {
2623 let app = app_with_call(cx);
2624 let tones = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
2625 let heard = tones.clone();
2626 cx.update(|cx| {
2627 cx.subscribe(&app, move |_, event: &AppEvent, _| {
2628 if let AppEvent::CallTone(tone) = event {
2629 heard.borrow_mut().push(*tone);
2630 }
2631 })
2632 .detach();
2633 app.update(cx, |state, cx| {
2634 state.apply_call_update(
2635 7,
2636 CallUpdate::State(CallState::Ended {
2637 reason: EndReason::Dropped,
2638 }),
2639 cx,
2640 );
2641 assert!(state.call.is_none());
2642 assert!(state.notice.is_none());
2643 let screen = state.call_end.as_ref().expect("end screen");
2644 assert_eq!(screen.heading(), "Call dropped");
2645 assert_eq!(screen.retry_label(), "Call back");
2646 state.dismiss_call_end(cx);
2647 assert!(state.call_end.is_none());
2648 })
2649 });
2650 assert_eq!(*tones.borrow(), vec![CallTone::CallEnded]);
2651 }
2652
2653 #[gpui_kit::test]
2654 fn a_normal_end_keeps_the_notice_and_no_end_screen(cx: &mut TestAppContext) {
2655 let app = app_with_call(cx);
2656 cx.update(|cx| {
2657 app.update(cx, |state, cx| {
2658 state.apply_call_update(
2659 7,
2660 CallUpdate::State(CallState::Ended {
2661 reason: EndReason::Remote(EndKind::Removed),
2662 }),
2663 cx,
2664 );
2665 assert!(state.call_end.is_none());
2666 assert!(state.notice.is_some());
2667 })
2668 });
2669 }
2670
2671 #[gpui_kit::test]
2672 fn full_window_exists_only_while_someone_shares_and_escape_leaves_it(cx: &mut TestAppContext) {
2673 let app = app_with_call(cx);
2674 cx.update(|cx| {
2675 app.update(cx, |state, cx| {
2676 state.toggle_stage_fullscreen(cx);
2677 assert!(!state.stage_fullscreen());
2678 state.apply_call_update(7, CallUpdate::ScreenShare(Some("8:orgid:a".into())), cx);
2679 state.toggle_stage_fullscreen(cx);
2680 assert!(state.stage_fullscreen());
2681 state.leave_stage_fullscreen(cx);
2682 assert!(!state.stage_fullscreen());
2683 state.toggle_stage_fullscreen(cx);
2684 state.apply_call_update(7, CallUpdate::ScreenShare(None), cx);
2685 assert!(!state.stage_fullscreen());
2686 })
2687 });
2688 }
2689
2690 #[gpui_kit::test]
2691 fn a_declined_call_names_who_declined(cx: &mut TestAppContext) {
2692 let app = app_with_call(cx);
2693 cx.update(|cx| {
2694 app.update(cx, |state, cx| {
2695 state.call.as_mut().unwrap().model.peer_name = "Bea".into();
2696 state.apply_call_update(
2697 7,
2698 CallUpdate::State(CallState::Ended {
2699 reason: EndReason::Remote(EndKind::Declined),
2700 }),
2701 cx,
2702 );
2703 assert_eq!(state.notice.as_ref().unwrap().text, "Bea declined");
2704 })
2705 });
2706 }
2707
2708 #[gpui_kit::test]
2709 fn updates_of_an_older_call_are_ignored(cx: &mut TestAppContext) {
2710 let app = app_with_call(cx);
2711 cx.update(|cx| {
2712 app.update(cx, |state, cx| {
2713 state.apply_call_update(
2714 6,
2715 CallUpdate::State(CallState::Ended {
2716 reason: EndReason::Dropped,
2717 }),
2718 cx,
2719 );
2720 assert!(state.call.is_some());
2721 assert!(state.notice.is_none());
2722 })
2723 });
2724 }
2725
2726 #[gpui_kit::test]
2727 fn a_ring_that_times_out_becomes_a_missed_call_event(cx: &mut TestAppContext) {
2728 cx.update(gpui_kit::init);
2729 let store = Arc::new(Store::open_in_memory().unwrap());
2730 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
2731 cx.update(|cx| {
2732 app.update(cx, |state, cx| {
2733 state.on_engine_event(EngineEvent::Incoming(demo_ring()), cx);
2734 assert!(state.rings.is_ringing());
2735 state.tick_rings(cx);
2736 assert!(state.rings.is_ringing());
2737 state.on_engine_event(
2738 EngineEvent::RingEnded {
2739 ring_id: demo_ring().ring_id,
2740 kind: EndKind::Cancelled,
2741 answered_by: None,
2742 },
2743 cx,
2744 );
2745 assert!(!state.rings.is_ringing());
2746 })
2747 });
2748 }
2749
2750 #[gpui_kit::test]
2751 fn calls_are_refused_for_meeting_chats_and_missing_chats(cx: &mut TestAppContext) {
2752 let app = app_with_chats(cx);
2753 cx.update(|cx| {
2754 app.update(cx, |state, cx| {
2755 state.start_chat_call("19:meeting@thread.v2", cx);
2756 assert!(state.call.is_none());
2757 assert_eq!(
2758 state.notice.as_ref().unwrap().text,
2759 "This chat cannot be called"
2760 );
2761 state.start_chat_call("19:unknown", cx);
2762 assert!(state.call.is_none());
2763 })
2764 });
2765 }
2766
2767 #[gpui_kit::test]
2768 fn a_missed_call_finds_the_one_on_one_chat_of_the_caller(cx: &mut TestAppContext) {
2769 let app = app_with_chats(cx);
2770 cx.update(|cx| {
2771 app.update(cx, |state, _| {
2772 let missed = super::MissedCall {
2773 caller_mri: "8:orgid:bea-id".into(),
2774 caller_name: "Bea".into(),
2775 thread_id: None,
2776 at: chrono::Utc::now(),
2777 };
2778 assert_eq!(
2779 state.conversation_of_missed_call(&missed).as_deref(),
2780 Some("19:dm@unq.gbl.spaces")
2781 );
2782 let direct = super::MissedCall {
2783 thread_id: Some("19:dm@unq.gbl.spaces".into()),
2784 ..missed.clone()
2785 };
2786 assert_eq!(
2787 state.conversation_of_missed_call(&direct).as_deref(),
2788 Some("19:dm@unq.gbl.spaces")
2789 );
2790 })
2791 });
2792 }
2793
2794 #[gpui_kit::test]
2795 fn only_meeting_chats_and_channels_watch_for_a_running_meeting(cx: &mut TestAppContext) {
2796 let app = app_with_chats(cx);
2797 cx.update(|cx| {
2798 app.update(cx, |state, _| {
2799 assert!(state.watches_live_meeting("19:meeting@thread.v2"));
2800 assert!(!state.watches_live_meeting("19:dm@unq.gbl.spaces"));
2801 assert!(!state.watches_live_meeting("19:unknown"));
2802 })
2803 });
2804 }
2805
2806 #[gpui_kit::test]
2807 fn a_live_meeting_shows_until_it_ends(cx: &mut TestAppContext) {
2808 let app = app_with_chats(cx);
2809 let meeting = calling::meeting::LiveMeeting {
2810 thread_id: "19:meeting@thread.v2".into(),
2811 conversation_url: None,
2812 expiration: Some(chrono::Utc::now().timestamp() + 600),
2813 organizer_id: Some("org".into()),
2814 tenant_id: Some("tenant".into()),
2815 meeting_code: None,
2816 passcode: None,
2817 };
2818 cx.update(|cx| {
2819 app.update(cx, |state, cx| {
2820 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
2821 state.apply_live_meeting("19:meeting@thread.v2".into(), Some(meeting), cx);
2822 assert!(state.running_meeting("19:meeting@thread.v2").is_some());
2823 state.apply_live_meeting("19:meeting@thread.v2".into(), None, cx);
2824 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
2825 })
2826 });
2827 }
2828}