BlueGit

ict rusty-teams

Files

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

actions.rs

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