BlueGit

ict rusty-teams

Files

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

actions.rs

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