BlueGit

ict rusty-teams

Files

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

actions.rs

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