BlueGit

ict rusty-teams

Files

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

actions.rs

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