BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 87.9 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 == DemoScene::Gallery {
1092 self.queue_demo_bubbles(conversation_id, cx);
1093 }
1094 if scene == DemoScene::Consult {
1095 if let Some(call) = self.call.as_mut() {
1096 call.model.apply(CallUpdate::State(CallState::Connected {
1097 since: Instant::now(),
1098 }));
1099 }
1100 self.start_consult(demo_consult_target(), cx);
1101 }
1102 }
1103
1104 fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {
1105 if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {
1106 self.finish_ring(ring_id, outcome, cx);
1107 }
1108 }
1109
1110 fn finish_ring(&mut self, ring_id: u64, outcome: RingOutcome, cx: &mut Context<Self>) {
1111 if let RingOutcome::Missed(missed) = outcome {
1112 if let Some(launcher) = &self.call_launcher {
1113 launcher.drop_ring(ring_id);
1114 }
1115 cx.emit(AppEvent::MissedCall(missed));
1116 }
1117 cx.emit(AppEvent::Ring);
1118 cx.notify();
1119 }
1120
1121 pub fn tick_rings(&mut self, cx: &mut Context<Self>) {
1122 if self.rings.is_empty() {
1123 return;
1124 }
1125 for (ring_id, outcome) in self.rings.tick(Instant::now()) {
1126 self.finish_ring(ring_id, outcome, cx);
1127 }
1128 }
1129
1130 pub fn accept_ringing_call(&mut self, cx: &mut Context<Self>) {
1131 if let Some(ring_id) = self.rings.first_ringing_id() {
1132 self.accept_ring(ring_id, AcceptMode::Audio, cx);
1133 }
1134 }
1135
1136 pub fn decline_ringing_call(&mut self, cx: &mut Context<Self>) {
1137 if let Some(ring_id) = self.rings.first_ringing_id() {
1138 self.decline_ring(ring_id, cx);
1139 }
1140 }
1141
1142 pub fn accept_ring(&mut self, ring_id: u64, mode: AcceptMode, cx: &mut Context<Self>) {
1143 let Some(entry) = self.rings.get(ring_id).cloned() else {
1144 return;
1145 };
1146 if self.call.is_some() {
1147 self.leave_call(cx);
1148 }
1149 self.signal_ring(ring_id, RingSignal::Accept, cx);
1150 let conversation_id = entry.ring.thread_id.clone();
1151 let title = conversation_id
1152 .as_deref()
1153 .and_then(|id| self.sidebar.chats.iter().find(|chat| chat.id == id))
1154 .filter(|_| entry.ring.is_group)
1155 .map(chat_title)
1156 .unwrap_or_else(|| entry.caller_name().to_owned());
1157 let model = CallModel::incoming(&title, &entry.ring.caller.mri, entry.caller_name());
1158 if entry.demo {
1159 let handle = start_demo_call(DemoCall::Incoming(demo_caller()));
1160 self.begin_call(handle, model, conversation_id, cx);
1161 if mode == AcceptMode::Video {
1162 self.send_call_command(CallCommand::SetCamera(true));
1163 }
1164 return;
1165 }
1166 let Some(launcher) = self.call_launcher.clone() else {
1167 self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
1168 return;
1169 };
1170 let receiver =
1171 crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });
1172 cx.spawn(async move |this, cx| {
1173 let handle = receiver.await.ok().flatten();
1174 this.update(cx, |state, cx| match handle {
1175 Some(handle) => state.begin_call(handle, model, conversation_id, cx),
1176 None => state.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx),
1177 })
1178 .ok();
1179 })
1180 .detach();
1181 }
1182
1183 pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
1184 let Some(entry) = self.rings.get(ring_id) else {
1185 return;
1186 };
1187 let demo = entry.demo;
1188 if !demo && let Some(launcher) = &self.call_launcher {
1189 launcher.decline_ring(ring_id);
1190 }
1191 self.signal_ring(ring_id, RingSignal::Decline, cx);
1192 }
1193
1194 pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {
1195 if let Some(thread_id) = missed
1196 .thread_id
1197 .as_ref()
1198 .filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id))
1199 {
1200 return Some(thread_id.clone());
1201 }
1202 let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;
1203 self.sidebar
1204 .chats
1205 .iter()
1206 .find(|chat| {
1207 crate::data::is_one_on_one(chat)
1208 && chat
1209 .members
1210 .iter()
1211 .any(|member| member.user_id.as_deref() == Some(user_id))
1212 })
1213 .map(|chat| chat.id.clone())
1214 }
1215}
1216
1217impl AppState {
1218 pub fn running_meeting(&self, conversation_id: &str) -> Option<&LiveMeeting> {
1219 self.live_meetings
1220 .get(conversation_id)
1221 .filter(|meeting| meeting.is_running(now_unix()) && meeting.target().is_some())
1222 }
1223
1224 pub fn demo_live_meetings(&mut self) {
1225 for conversation_id in ["demo-chat-meeting-standup", DEMO_LOBBY_MEETING] {
1226 self.live_meetings.insert(
1227 conversation_id.to_owned(),
1228 LiveMeeting {
1229 thread_id: conversation_id.to_owned(),
1230 conversation_url: None,
1231 expiration: Some(now_unix() + DEMO_LIVE_MINUTES * 60),
1232 organizer_id: Some("demo-jonas".to_owned()),
1233 tenant_id: Some("demo-tenant".to_owned()),
1234 meeting_code: None,
1235 passcode: None,
1236 },
1237 );
1238 }
1239 }
1240
1241 pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {
1242 let meeting_chat =
1243 self.sidebar.chats.iter().any(|chat| {
1244 chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND)
1245 });
1246 meeting_chat
1247 || matches!(
1248 selection_for(&self.sidebar, conversation_id),
1249 Some(Selection::Channel(_))
1250 )
1251 }
1252
1253 pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1254 if self.mode.demo || !self.watches_live_meeting(conversation_id) {
1255 return;
1256 }
1257 let Some(launcher) = self.call_launcher.clone() else {
1258 return;
1259 };
1260 if !self.live_refreshing.insert(conversation_id.to_owned()) {
1261 return;
1262 }
1263 let thread_id = conversation_id.to_owned();
1264 let receiver =
1265 crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
1266 let conversation_id = conversation_id.to_owned();
1267 cx.spawn(async move |this, cx| {
1268 let meeting = receiver.await.ok().flatten();
1269 this.update(cx, |state, cx| {
1270 state.apply_live_meeting(conversation_id, meeting, cx)
1271 })
1272 .ok();
1273 })
1274 .detach();
1275 }
1276
1277 pub fn apply_live_meeting(
1278 &mut self,
1279 conversation_id: String,
1280 meeting: Option<LiveMeeting>,
1281 cx: &mut Context<Self>,
1282 ) {
1283 self.live_refreshing.remove(&conversation_id);
1284 let changed = match meeting {
1285 Some(meeting) => {
1286 self.live_meetings
1287 .insert(conversation_id.clone(), meeting.clone())
1288 != Some(meeting)
1289 }
1290 None => self.live_meetings.remove(&conversation_id).is_some(),
1291 };
1292 if changed {
1293 cx.emit(AppEvent::LiveMeeting);
1294 cx.notify();
1295 }
1296 }
1297
1298 pub fn on_thread_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1299 self.refresh_live_meeting(conversation_id, cx);
1300 }
1301}
1302
1303#[cfg(test)]
1304mod tests {
1305 use std::sync::Arc;
1306 use std::time::{Duration, Instant};
1307
1308 use std::path::PathBuf;
1309
1310 use calling::{
1311 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1312 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, RecordingKind,
1313 StopScope, call_channel,
1314 };
1315 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1316 use store::{ChatRecord, MemberRecord, Store};
1317
1318 use super::{ActiveCall, CallModel, load_camera, load_camera_effects};
1319 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1320 use crate::call::TransferCandidate;
1321 use crate::call::background::BackgroundPick;
1322 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1323 use crate::call::demo::demo_ring;
1324 use crate::call::features::room_closed_move;
1325 use crate::call::model::BreakoutState;
1326 use crate::data::Person;
1327
1328 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1329 cx.update(gpui_kit::init);
1330 let store = Arc::new(Store::open_in_memory().unwrap());
1331 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1332 let (handle, _control) = call_channel();
1333 cx.update(|cx| {
1334 app.update(cx, |state, _| {
1335 state.call = Some(ActiveCall::new(
1336 7,
1337 CallModel::test(),
1338 handle.commands,
1339 None,
1340 handle.video,
1341 ));
1342 })
1343 });
1344 app
1345 }
1346
1347 fn app_with_commands(
1348 cx: &mut TestAppContext,
1349 model: CallModel,
1350 conversation_id: Option<&str>,
1351 ) -> (Entity<AppState>, CallControl) {
1352 cx.update(gpui_kit::init);
1353 let store = Arc::new(Store::open_in_memory().unwrap());
1354 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1355 let (handle, control) = call_channel();
1356 let conversation_id = conversation_id.map(str::to_owned);
1357 cx.update(|cx| {
1358 app.update(cx, |state, _| {
1359 state.call = Some(ActiveCall::new(
1360 7,
1361 model,
1362 handle.commands,
1363 conversation_id,
1364 handle.video,
1365 ));
1366 })
1367 });
1368 (app, control)
1369 }
1370
1371 fn live_meeting(can_end: bool) -> CallModel {
1372 let mut model = CallModel::meeting("Standup", can_end);
1373 model.apply(CallUpdate::State(CallState::Connected {
1374 since: Instant::now(),
1375 }));
1376 model.apply(CallUpdate::OwnIdentity {
1377 mri: "8:orgid:me".into(),
1378 });
1379 model
1380 }
1381
1382 #[gpui_kit::test]
1383 fn high_rate_updates_do_not_emit_call_events(cx: &mut TestAppContext) {
1384 let app = app_with_call(cx);
1385 let emitted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1386 let counter = emitted.clone();
1387 cx.update(|cx| {
1388 cx.subscribe(&app, move |_, event: &AppEvent, _| {
1389 if matches!(event, AppEvent::Call) {
1390 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1391 }
1392 })
1393 .detach();
1394 app.update(cx, |state, cx| {
1395 state.apply_call_update(7, CallUpdate::VideoReady, cx);
1396 state.apply_call_update(
1397 7,
1398 CallUpdate::Levels {
1399 local: 0.5,
1400 remote: 0.5,
1401 },
1402 cx,
1403 );
1404 state.apply_call_update(
1405 7,
1406 CallUpdate::Stats {
1407 inbound_packets: 1,
1408 outbound_packets: 1,
1409 },
1410 cx,
1411 );
1412 });
1413 });
1414 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);
1415 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));
1416 cx.update(|cx| {
1417 app.update(cx, |state, cx| {
1418 state.apply_call_update(7, CallUpdate::Muted(true), cx)
1419 })
1420 });
1421 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);
1422 }
1423
1424 #[gpui_kit::test]
1425 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1426 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1427 let store = cx.update(|cx| app.read(cx).store.clone());
1428 assert!(!cx.update(|cx| app.read(cx).call_share_sound));
1429 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));
1430 assert_eq!(
1431 control.try_recv_command(),
1432 Some(CallCommand::SetShareSound(true))
1433 );
1434 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1435 assert!(cx.update(|cx| reopened.read(cx).call_share_sound));
1436 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));
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 }
1440
1441 #[gpui_kit::test]
1442 fn the_camera_pick_is_remembered_and_the_next_call_starts_with_it(cx: &mut TestAppContext) {
1443 let (app, _control) = app_with_commands(cx, live_meeting(false), None);
1444 let store = cx.update(|cx| app.read(cx).store.clone());
1445 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1446 cx.update(|cx| {
1447 app.update(cx, |state, cx| {
1448 state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)
1449 })
1450 });
1451 assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));
1452 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1453 assert_eq!(
1454 cx.update(|cx| reopened.read(cx).call_camera.clone()),
1455 DeviceChoice::Device("cam-2".into())
1456 );
1457 cx.update(|cx| {
1458 app.update(cx, |state, cx| {
1459 state.select_call_camera(DeviceChoice::SystemDefault, cx)
1460 })
1461 });
1462 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1463 }
1464
1465 #[gpui_kit::test]
1466 fn the_camera_effects_are_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1467 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1468 let store = cx.update(|cx| app.read(cx).store.clone());
1469 assert_eq!(load_camera_effects(&store), CameraEffects::default());
1470 let effects = CameraEffects {
1471 mirror: false,
1472 auto_framing: true,
1473 soft_focus: true,
1474 soft_focus_strength: 75,
1475 ..CameraEffects::default()
1476 };
1477 cx.update(|cx| app.update(cx, |state, cx| state.set_call_effects(effects, cx)));
1478 assert_eq!(
1479 control.try_recv_command(),
1480 Some(CallCommand::SetCameraEffects(effects))
1481 );
1482 assert_eq!(load_camera_effects(&store), effects);
1483 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1484 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1485 }
1486
1487 #[gpui_kit::test]
1488 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1489 cx: &mut TestAppContext,
1490 ) {
1491 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1492 cx.update(|cx| {
1493 app.update(cx, |state, cx| {
1494 state.toggle_call_hand(cx);
1495 state.send_call_reaction(Reaction::Heart, cx);
1496 state.lower_call_hand("8:orgid:a".into(), cx);
1497 state.lower_all_call_hands(cx);
1498 })
1499 });
1500 assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));
1501 assert_eq!(
1502 control.try_recv_command(),
1503 Some(CallCommand::SendReaction(Reaction::Heart))
1504 );
1505 assert_eq!(control.try_recv_command(), None);
1506 let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);
1507 cx.update(|cx| {
1508 organizer.update(cx, |state, cx| {
1509 state.apply_call_update(
1510 7,
1511 CallUpdate::Roster(vec![calling::RosterEntry {
1512 mri: "8:orgid:a".into(),
1513 display_name: "Ana".into(),
1514 muted: false,
1515 in_lobby: false,
1516 has_video: false,
1517 sharing: false,
1518 hand: Some(calling::RaisedHand {
1519 state_id: "s".into(),
1520 rank: 1,
1521 }),
1522 spotlight: None,
1523 organizer: false,
1524 ..Default::default()
1525 }]),
1526 cx,
1527 );
1528 state.lower_call_hand("8:orgid:a".into(), cx);
1529 state.lower_all_call_hands(cx);
1530 })
1531 });
1532 assert_eq!(
1533 organizer_control.try_recv_command(),
1534 Some(CallCommand::LowerHand {
1535 mri: "8:orgid:a".into()
1536 })
1537 );
1538 assert_eq!(
1539 organizer_control.try_recv_command(),
1540 Some(CallCommand::LowerAllHands)
1541 );
1542 }
1543
1544 fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {
1545 calling::RosterEntry {
1546 mri: mri.into(),
1547 display_name: name.into(),
1548 muted: false,
1549 in_lobby,
1550 has_video: false,
1551 sharing: false,
1552 hand: None,
1553 spotlight: spotlit.then(|| calling::Spotlight {
1554 state_id: "sp".into(),
1555 rank: 1,
1556 }),
1557 organizer: false,
1558 ..Default::default()
1559 }
1560 }
1561
1562 #[gpui_kit::test]
1563 fn organizer_controls_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {
1564 let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1565 cx.update(|cx| {
1566 attendee.update(cx, |state, cx| {
1567 state.admit_call_guest("8:orgid:g".into(), cx);
1568 state.admit_all_call_guests(cx);
1569 state.deny_call_guest("8:orgid:g".into(), cx);
1570 state.mute_call_participant("8:orgid:a".into(), cx);
1571 state.mute_all_call(cx);
1572 state.remove_call_participant("8:orgid:a".into(), cx);
1573 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1574 })
1575 });
1576 assert_eq!(attendee_control.try_recv_command(), None);
1577 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1578 cx.update(|cx| {
1579 organizer.update(cx, |state, cx| {
1580 state.apply_call_update(
1581 7,
1582 CallUpdate::Roster(vec![
1583 guest("8:orgid:a", "Ana", false, false),
1584 guest("8:orgid:g", "Gast", true, false),
1585 ]),
1586 cx,
1587 );
1588 state.admit_call_guest("8:orgid:g".into(), cx);
1589 state.admit_all_call_guests(cx);
1590 state.deny_call_guest("8:orgid:g".into(), cx);
1591 state.mute_call_participant("8:orgid:a".into(), cx);
1592 state.mute_all_call(cx);
1593 state.remove_call_participant("8:orgid:a".into(), cx);
1594 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1595 })
1596 });
1597 assert_eq!(
1598 control.try_recv_command(),
1599 Some(CallCommand::Admit {
1600 mri: "8:orgid:g".into()
1601 })
1602 );
1603 assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));
1604 assert_eq!(
1605 control.try_recv_command(),
1606 Some(CallCommand::Deny {
1607 mri: "8:orgid:g".into()
1608 })
1609 );
1610 assert_eq!(
1611 control.try_recv_command(),
1612 Some(CallCommand::MuteParticipant {
1613 mri: "8:orgid:a".into()
1614 })
1615 );
1616 assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));
1617 assert_eq!(
1618 control.try_recv_command(),
1619 Some(CallCommand::RemoveParticipant {
1620 mri: "8:orgid:a".into()
1621 })
1622 );
1623 assert_eq!(
1624 control.try_recv_command(),
1625 Some(CallCommand::Spotlight {
1626 mri: "8:orgid:a".into()
1627 })
1628 );
1629 }
1630
1631 #[gpui_kit::test]
1632 fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(
1633 cx: &mut TestAppContext,
1634 ) {
1635 let (app, mut control) = app_with_commands(cx, live_meeting(true), None);
1636 cx.update(|cx| {
1637 app.update(cx, |state, cx| {
1638 state.apply_call_update(
1639 7,
1640 CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]),
1641 cx,
1642 );
1643 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1644 state.toggle_call_pin("8:orgid:a", cx);
1645 assert_eq!(
1646 state.call.as_ref().unwrap().model.pinned.as_deref(),
1647 Some("8:orgid:a")
1648 );
1649 state.toggle_call_pin("8:orgid:a", cx);
1650 assert_eq!(state.call.as_ref().unwrap().model.pinned, None);
1651 })
1652 });
1653 assert_eq!(
1654 control.try_recv_command(),
1655 Some(CallCommand::StopSpotlight {
1656 mri: "8:orgid:a".into()
1657 })
1658 );
1659 assert_eq!(control.try_recv_command(), None);
1660 }
1661
1662 #[gpui_kit::test]
1663 fn captions_toggle_between_on_and_off_and_only_in_meetings(cx: &mut TestAppContext) {
1664 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1665 cx.update(|cx| {
1666 app.update(cx, |state, cx| {
1667 state.toggle_call_captions(cx);
1668 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1669 state.toggle_call_captions(cx);
1670 })
1671 });
1672 assert_eq!(
1673 control.try_recv_command(),
1674 Some(CallCommand::SetCaptions(true))
1675 );
1676 assert_eq!(
1677 control.try_recv_command(),
1678 Some(CallCommand::SetCaptions(false))
1679 );
1680 let app = app_with_call(cx);
1681 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));
1682 }
1683
1684 #[gpui_kit::test]
1685 fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1686 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1687 let store = cx.update(|cx| app.read(cx).store.clone());
1688 assert_eq!(
1689 cx.update(|cx| app.read(cx).call_background.clone()),
1690 BackgroundPick::None
1691 );
1692 cx.update(|cx| {
1693 app.update(cx, |state, cx| {
1694 state.set_call_background(BackgroundPick::Blur, cx)
1695 })
1696 });
1697 assert_eq!(
1698 control.try_recv_command(),
1699 Some(CallCommand::SetBackground(BackgroundChoice::Blur))
1700 );
1701 assert_eq!(
1702 cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()),
1703 BackgroundPick::Blur
1704 );
1705 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1706 assert_eq!(
1707 cx.update(|cx| reopened.read(cx).call_background.clone()),
1708 BackgroundPick::Blur
1709 );
1710 let picture = PathBuf::from("/pictures/wall.jpg");
1711 cx.update(|cx| {
1712 app.update(cx, |state, cx| {
1713 state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)
1714 })
1715 });
1716 assert_eq!(
1717 control.try_recv_command(),
1718 Some(CallCommand::SetBackground(BackgroundChoice::Image(
1719 picture.clone()
1720 )))
1721 );
1722 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1723 assert_eq!(
1724 cx.update(|cx| reopened.read(cx).call_background.clone()),
1725 BackgroundPick::Custom(picture)
1726 );
1727 cx.update(|cx| {
1728 app.update(cx, |state, cx| {
1729 state.set_call_background(BackgroundPick::None, cx)
1730 })
1731 });
1732 assert_eq!(
1733 control.try_recv_command(),
1734 Some(CallCommand::SetBackground(BackgroundChoice::None))
1735 );
1736 }
1737
1738 #[gpui_kit::test]
1739 fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {
1740 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1741 cx.update(|cx| {
1742 app.update(cx, |state, cx| {
1743 state.set_call_background(BackgroundPick::Default("office_01".into()), cx)
1744 })
1745 });
1746 assert_eq!(control.try_recv_command(), None);
1747 }
1748
1749 #[gpui_kit::test]
1750 fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(
1751 cx: &mut TestAppContext,
1752 ) {
1753 let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1754 cx.update(|cx| {
1755 attendee.update(cx, |state, cx| {
1756 state.run_call_record_action(RecordAction::Start(RecordingKind::Video), cx);
1757 state.accept_recording_notice(cx);
1758 })
1759 });
1760 assert_eq!(attendee_control.try_recv_command(), None);
1761 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1762 cx.update(|cx| {
1763 organizer.update(cx, |state, cx| {
1764 state.run_call_record_action(RecordAction::Start(RecordingKind::Video), cx);
1765 state.apply_call_update(7, CallUpdate::Recording(true), cx);
1766 state.run_call_record_action(RecordAction::Stop(StopScope::Both), cx);
1767 state.accept_recording_notice(cx);
1768 state.apply_call_update(7, CallUpdate::ConsentRequired(true), cx);
1769 state.accept_recording_notice(cx);
1770 })
1771 });
1772 assert_eq!(
1773 control.try_recv_command(),
1774 Some(CallCommand::StartRecording {
1775 kind: RecordingKind::Video,
1776 title: "Standup".into()
1777 })
1778 );
1779 assert_eq!(
1780 control.try_recv_command(),
1781 Some(CallCommand::StopRecording {
1782 scope: StopScope::Both
1783 })
1784 );
1785 assert_eq!(
1786 control.try_recv_command(),
1787 Some(CallCommand::ConsentToRecording)
1788 );
1789 assert_eq!(control.try_recv_command(), None);
1790 }
1791
1792 #[gpui_kit::test]
1793 fn every_record_action_becomes_its_own_command_for_the_organizer(cx: &mut TestAppContext) {
1794 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1795 cx.update(|cx| {
1796 organizer.update(cx, |state, cx| {
1797 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
1798 state.run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
1799 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
1800 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
1801 })
1802 });
1803 let title = "Standup".to_owned();
1804 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::AudioOnly, title: title.clone() }));
1805 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::TranscriptOnly, title }));
1806 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::RecordingOnly }));
1807 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::TranscriptionOnly }));
1808 assert_eq!(control.try_recv_command(), None);
1809 }
1810
1811 #[gpui_kit::test]
1812 fn the_transcript_turns_captions_on_and_excludes_the_chat_panel(cx: &mut TestAppContext) {
1813 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1814 cx.update(|cx| {
1815 app.update(cx, |state, cx| {
1816 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
1817 state.toggle_call_chat(cx);
1818 state.show_call_transcript(cx);
1819 })
1820 });
1821 let (chat_open, transcript_open) = cx.update(|cx| {
1822 let call = app.read(cx).call.as_ref().unwrap();
1823 (call.chat_open, call.transcript_open)
1824 });
1825 assert!(!chat_open && transcript_open);
1826 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
1827 cx.update(|cx| {
1828 app.update(cx, |state, cx| {
1829 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1830 state.show_call_transcript(cx);
1831 state.toggle_call_chat(cx);
1832 })
1833 });
1834 let (chat_open, transcript_open) = cx.update(|cx| {
1835 let call = app.read(cx).call.as_ref().unwrap();
1836 (call.chat_open, call.transcript_open)
1837 });
1838 assert!(chat_open && !transcript_open);
1839 assert_eq!(control.try_recv_command(), None);
1840 }
1841
1842 #[gpui_kit::test]
1843 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(cx: &mut TestAppContext) {
1844 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1845 cx.update(|cx| {
1846 app.update(cx, |state, cx| {
1847 state.choose_call_caption_language("de-DE", cx);
1848 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::Starting), cx);
1849 })
1850 });
1851 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
1852 assert_eq!(control.try_recv_command(), None);
1853 cx.update(|cx| {
1854 app.update(cx, |state, cx| {
1855 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1856 state.choose_call_caption_language("fr-FR", cx);
1857 })
1858 });
1859 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("de-DE".into())));
1860 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("fr-FR".into())));
1861 assert_eq!(control.try_recv_command(), None);
1862 }
1863
1864 #[gpui_kit::test]
1865 fn caption_size_and_position_are_stored_and_reach_the_call_model(cx: &mut TestAppContext) {
1866 let (app, _control) = app_with_commands(cx, live_meeting(false), None);
1867 cx.update(|cx| {
1868 app.update(cx, |state, cx| {
1869 state.set_call_caption_size(CaptionSize::Large, cx);
1870 state.set_call_caption_position(CaptionPosition::Top, cx);
1871 })
1872 });
1873 let (view, stored) = cx.update(|cx| {
1874 let state = app.read(cx);
1875 (state.call.as_ref().unwrap().model.view, ViewSettings::load(&state.store))
1876 });
1877 assert_eq!((view.caption_size, view.caption_position), (CaptionSize::Large, CaptionPosition::Top));
1878 assert_eq!((stored.caption_size, stored.caption_position), (CaptionSize::Large, CaptionPosition::Top));
1879 }
1880
1881 fn live_one_to_one() -> CallModel {
1882 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1883 model.apply(CallUpdate::State(CallState::Connected {
1884 since: Instant::now(),
1885 }));
1886 model
1887 }
1888
1889 #[gpui_kit::test]
1890 fn hold_and_resume_alternate_and_stop_while_the_other_side_holds(cx: &mut TestAppContext) {
1891 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1892 cx.update(|cx| {
1893 app.update(cx, |state, cx| {
1894 state.toggle_call_hold(cx);
1895 state.apply_call_update(7, CallUpdate::Hold(HoldState::Local), cx);
1896 state.toggle_call_hold(cx);
1897 state.apply_call_update(7, CallUpdate::Hold(HoldState::Remote), cx);
1898 state.toggle_call_hold(cx);
1899 })
1900 });
1901 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(true)));
1902 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(false)));
1903 assert_eq!(control.try_recv_command(), None);
1904 let (meeting, mut meeting_control) = app_with_commands(cx, live_meeting(true), None);
1905 cx.update(|cx| meeting.update(cx, |state, cx| state.toggle_call_hold(cx)));
1906 assert_eq!(meeting_control.try_recv_command(), None);
1907 }
1908
1909 fn candidate(name: &str) -> TransferCandidate {
1910 TransferCandidate {
1911 mri: format!("8:orgid:{name}"),
1912 name: name.into(),
1913 user_id: Some(name.into()),
1914 chat_id: format!("19:{name}"),
1915 }
1916 }
1917
1918 #[gpui_kit::test]
1919 fn a_blind_transfer_names_the_target(
1920 cx: &mut TestAppContext,
1921 ) {
1922 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1923 cx.update(|cx| {
1924 app.update(cx, |state, cx| {
1925 state.transfer_call_blind(candidate("ana"), cx)
1926 })
1927 });
1928 assert_eq!(
1929 control.try_recv_command(),
1930 Some(CallCommand::Transfer {
1931 target: calling::Callee {
1932 mri: "8:orgid:ana".into(),
1933 display_name: "ana".into()
1934 },
1935 replaces: None
1936 })
1937 );
1938 }
1939
1940 #[gpui_kit::test]
1941 fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(
1942 cx: &mut TestAppContext,
1943 ) {
1944 let app = app_with_chats(cx);
1945 cx.update(|cx| {
1946 app.update(cx, |state, cx| {
1947 let names: Vec<String> = state
1948 .transfer_candidates()
1949 .into_iter()
1950 .map(|candidate| candidate.name)
1951 .collect();
1952 assert_eq!(names, vec!["Bea".to_owned()]);
1953 let (handle, _control) = call_channel();
1954 let mut on_the_call =
1955 CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);
1956 on_the_call.apply(CallUpdate::State(CallState::Connected {
1957 since: Instant::now(),
1958 }));
1959 state.call = Some(ActiveCall::new(
1960 9,
1961 on_the_call,
1962 handle.commands,
1963 None,
1964 handle.video,
1965 ));
1966 assert!(state.transfer_candidates().is_empty());
1967 cx.notify();
1968 })
1969 });
1970 }
1971
1972 fn room_move(returning: bool) -> calling::BreakoutMove {
1973 calling::BreakoutMove {
1974 room_name: "Room 1".into(),
1975 target: calling::MeetingTarget {
1976 thread_id: "19:meeting_room@thread.v2".into(),
1977 tenant_id: "t".into(),
1978 organizer_id: "o".into(),
1979 meeting_data: None,
1980 },
1981 returning,
1982 }
1983 }
1984
1985 fn main_target() -> calling::MeetingTarget {
1986 calling::MeetingTarget {
1987 thread_id: "19:meeting_main@thread.v2".into(),
1988 tenant_id: "t".into(),
1989 organizer_id: "o".into(),
1990 meeting_data: None,
1991 }
1992 }
1993
1994 #[gpui_kit::test]
1995 fn being_moved_to_a_room_leaves_the_call_and_remembers_the_way_back(cx: &mut TestAppContext) {
1996 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1997 cx.update(|cx| {
1998 app.update(cx, |state, cx| {
1999 state.call.as_mut().unwrap().meeting_target = Some(main_target());
2000 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
2001 let pending = state
2002 .call
2003 .as_ref()
2004 .unwrap()
2005 .pending_move
2006 .clone()
2007 .expect("a move is pending");
2008 assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");
2009 assert_eq!(pending.title, "Room 1");
2010 let room = pending.breakout.expect("a room");
2011 assert_eq!(room.main, Some(main_target()));
2012 assert_eq!(room.main_title, "Standup");
2013 assert_eq!(
2014 state.notice.as_ref().map(|notice| notice.text.as_str()),
2015 Some("Moving you to Room 1")
2016 );
2017 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
2018 })
2019 });
2020 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
2021 assert_eq!(control.try_recv_command(), None);
2022 }
2023
2024 #[gpui_kit::test]
2025 fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(
2026 cx: &mut TestAppContext,
2027 ) {
2028 let mut room = live_meeting(false);
2029 room.breakout = Some(BreakoutState {
2030 room_name: "Room 1".into(),
2031 main: Some(main_target()),
2032 main_title: "Standup".into(),
2033 });
2034 let (app, mut control) = app_with_commands(cx, room.clone(), None);
2035 cx.update(|cx| {
2036 app.update(cx, |state, cx| {
2037 state.return_to_main_meeting(cx);
2038 let pending = state
2039 .call
2040 .as_ref()
2041 .unwrap()
2042 .pending_move
2043 .clone()
2044 .expect("a move is pending");
2045 assert_eq!(pending.target, main_target());
2046 assert_eq!(pending.title, "Standup");
2047 assert!(pending.breakout.is_none());
2048 })
2049 });
2050 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
2051 let (closed, _control) = app_with_commands(cx, room, None);
2052 cx.update(|cx| {
2053 closed.update(cx, |state, _| {
2054 let call = state.call.as_ref().unwrap();
2055 let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed))
2056 .expect("goes back");
2057 assert_eq!(moved.target, main_target());
2058 assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());
2059 assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());
2060 })
2061 });
2062 let (plain, _control) = app_with_commands(cx, live_meeting(false), None);
2063 cx.update(|cx| {
2064 plain.update(cx, |state, _| {
2065 assert!(
2066 room_closed_move(
2067 state.call.as_ref().unwrap(),
2068 &EndReason::Remote(EndKind::RoomClosed)
2069 )
2070 .is_none()
2071 )
2072 })
2073 });
2074 }
2075
2076 #[gpui_kit::test]
2077 fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(
2078 cx: &mut TestAppContext,
2079 ) {
2080 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2081 cx.update(|cx| {
2082 app.update(cx, |state, cx| {
2083 state.open_call_whiteboard(cx);
2084 state.apply_call_update(
2085 7,
2086 CallUpdate::Whiteboard(Some(calling::ContentShare {
2087 session_id: "s".into(),
2088 presenter: Some("8:orgid:ana".into()),
2089 subject: "Whiteboard".into(),
2090 url: Some("https://app.whiteboard.microsoft.com/x".into()),
2091 whiteboard: true,
2092 })),
2093 cx,
2094 );
2095 state.open_call_whiteboard(cx);
2096 })
2097 });
2098 assert_eq!(
2099 control.try_recv_command(),
2100 Some(CallCommand::OpenWhiteboard {
2101 title: "Standup".into()
2102 })
2103 );
2104 assert_eq!(control.try_recv_command(), None);
2105 }
2106
2107 #[gpui_kit::test]
2108 fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(
2109 cx: &mut TestAppContext,
2110 ) {
2111 let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
2112 cx.update(|cx| {
2113 app.update(cx, |state, cx| {
2114 state
2115 .directory
2116 .unread_counts
2117 .insert("19:meeting_x@thread.v2".into(), 3);
2118 assert_eq!(state.call_chat_thread(), None);
2119 assert_eq!(state.call_chat_unread(), 0);
2120 state.apply_call_update(
2121 7,
2122 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2123 cx,
2124 );
2125 assert_eq!(state.call_chat_unread(), 3);
2126 state.toggle_call_chat(cx);
2127 assert_eq!(
2128 state.call_chat_thread().as_deref(),
2129 Some("19:meeting_x@thread.v2")
2130 );
2131 assert_eq!(state.call_chat_unread(), 0);
2132 state.toggle_call_chat(cx);
2133 assert_eq!(state.call_chat_thread(), None);
2134 })
2135 });
2136 }
2137
2138 #[gpui_kit::test]
2139 fn a_call_without_a_chat_has_no_panel(cx: &mut TestAppContext) {
2140 let app = app_with_call(cx);
2141 cx.update(|cx| {
2142 app.update(cx, |state, cx| {
2143 state.toggle_call_chat(cx);
2144 assert!(!state.call.as_ref().unwrap().chat_open);
2145 })
2146 });
2147 }
2148
2149 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
2150 cx.update(gpui_kit::init);
2151 let store = Arc::new(Store::open_in_memory().unwrap());
2152 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
2153 cx.update(|cx| {
2154 app.update(cx, |state, _| {
2155 state.directory.me = Some(Person {
2156 user_id: "me-id".into(),
2157 display_name: "Me".into(),
2158 });
2159 state.sidebar.chats = vec![
2160 ChatRecord {
2161 id: "19:meeting@thread.v2".into(),
2162 kind: "meeting".into(),
2163 members: vec![MemberRecord {
2164 user_id: Some("bea-id".into()),
2165 display_name: "Bea".into(),
2166 }],
2167 ..Default::default()
2168 },
2169 ChatRecord {
2170 id: "19:dm@unq.gbl.spaces".into(),
2171 kind: "oneOnOne".into(),
2172 members: vec![
2173 MemberRecord {
2174 user_id: Some("me-id".into()),
2175 display_name: "Me".into(),
2176 },
2177 MemberRecord {
2178 user_id: Some("bea-id".into()),
2179 display_name: "Bea".into(),
2180 },
2181 ],
2182 ..Default::default()
2183 },
2184 ];
2185 })
2186 });
2187 app
2188 }
2189
2190 #[gpui_kit::test]
2191 fn declining_by_shortcut_only_acts_while_a_ring_shows(cx: &mut TestAppContext) {
2192 let app = app_with_chats(cx);
2193 cx.update(|cx| {
2194 app.update(cx, |state, cx| {
2195 state.decline_ringing_call(cx);
2196 assert!(!state.rings.is_ringing());
2197 state.demo_incoming_ring(cx);
2198 assert!(state.rings.is_ringing());
2199 state.decline_ringing_call(cx);
2200 assert!(!state.rings.is_ringing());
2201 })
2202 });
2203 }
2204
2205 #[gpui_kit::test]
2206 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
2207 let app = app_with_call(cx);
2208 cx.update(|cx| {
2209 app.update(cx, |state, cx| {
2210 assert!(state.viewing_call());
2211 state.select(Selection::Chat("c1".into()), cx);
2212 assert!(!state.viewing_call());
2213 state.show_call(true, cx);
2214 assert!(state.viewing_call());
2215 })
2216 });
2217 }
2218
2219 #[gpui_kit::test]
2220 fn an_ended_call_closes_the_view_and_raises_a_notice(cx: &mut TestAppContext) {
2221 let app = app_with_call(cx);
2222 let since = Instant::now() - Duration::from_secs(42);
2223 cx.update(|cx| {
2224 app.update(cx, |state, cx| {
2225 state.apply_call_update(7, CallUpdate::State(CallState::Connected { since }), cx);
2226 assert!(state.call.is_some());
2227 state.apply_call_update(
2228 7,
2229 CallUpdate::State(CallState::Ended {
2230 reason: EndReason::LocalHangup,
2231 }),
2232 cx,
2233 );
2234 assert!(state.call.is_none());
2235 let notice = state.notice.as_ref().expect("notice");
2236 assert_eq!(notice.text, "Call ended 00:42");
2237 })
2238 });
2239 }
2240
2241 #[gpui_kit::test]
2242 fn full_window_exists_only_while_someone_shares_and_escape_leaves_it(cx: &mut TestAppContext) {
2243 let app = app_with_call(cx);
2244 cx.update(|cx| {
2245 app.update(cx, |state, cx| {
2246 state.toggle_stage_fullscreen(cx);
2247 assert!(!state.stage_fullscreen());
2248 state.apply_call_update(7, CallUpdate::ScreenShare(Some("8:orgid:a".into())), cx);
2249 state.toggle_stage_fullscreen(cx);
2250 assert!(state.stage_fullscreen());
2251 state.leave_stage_fullscreen(cx);
2252 assert!(!state.stage_fullscreen());
2253 state.toggle_stage_fullscreen(cx);
2254 state.apply_call_update(7, CallUpdate::ScreenShare(None), cx);
2255 assert!(!state.stage_fullscreen());
2256 })
2257 });
2258 }
2259
2260 #[gpui_kit::test]
2261 fn a_declined_call_names_who_declined(cx: &mut TestAppContext) {
2262 let app = app_with_call(cx);
2263 cx.update(|cx| {
2264 app.update(cx, |state, cx| {
2265 state.call.as_mut().unwrap().model.peer_name = "Bea".into();
2266 state.apply_call_update(
2267 7,
2268 CallUpdate::State(CallState::Ended {
2269 reason: EndReason::Remote(EndKind::Declined),
2270 }),
2271 cx,
2272 );
2273 assert_eq!(state.notice.as_ref().unwrap().text, "Bea declined");
2274 })
2275 });
2276 }
2277
2278 #[gpui_kit::test]
2279 fn updates_of_an_older_call_are_ignored(cx: &mut TestAppContext) {
2280 let app = app_with_call(cx);
2281 cx.update(|cx| {
2282 app.update(cx, |state, cx| {
2283 state.apply_call_update(
2284 6,
2285 CallUpdate::State(CallState::Ended {
2286 reason: EndReason::Dropped,
2287 }),
2288 cx,
2289 );
2290 assert!(state.call.is_some());
2291 assert!(state.notice.is_none());
2292 })
2293 });
2294 }
2295
2296 #[gpui_kit::test]
2297 fn a_ring_that_times_out_becomes_a_missed_call_event(cx: &mut TestAppContext) {
2298 cx.update(gpui_kit::init);
2299 let store = Arc::new(Store::open_in_memory().unwrap());
2300 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
2301 cx.update(|cx| {
2302 app.update(cx, |state, cx| {
2303 state.on_engine_event(EngineEvent::Incoming(demo_ring()), cx);
2304 assert!(state.rings.is_ringing());
2305 state.tick_rings(cx);
2306 assert!(state.rings.is_ringing());
2307 state.on_engine_event(
2308 EngineEvent::RingEnded {
2309 ring_id: demo_ring().ring_id,
2310 kind: EndKind::Cancelled,
2311 answered_by: None,
2312 },
2313 cx,
2314 );
2315 assert!(!state.rings.is_ringing());
2316 })
2317 });
2318 }
2319
2320 #[gpui_kit::test]
2321 fn calls_are_refused_for_meeting_chats_and_missing_chats(cx: &mut TestAppContext) {
2322 let app = app_with_chats(cx);
2323 cx.update(|cx| {
2324 app.update(cx, |state, cx| {
2325 state.start_chat_call("19:meeting@thread.v2", cx);
2326 assert!(state.call.is_none());
2327 assert_eq!(
2328 state.notice.as_ref().unwrap().text,
2329 "This chat cannot be called"
2330 );
2331 state.start_chat_call("19:unknown", cx);
2332 assert!(state.call.is_none());
2333 })
2334 });
2335 }
2336
2337 #[gpui_kit::test]
2338 fn a_missed_call_finds_the_one_on_one_chat_of_the_caller(cx: &mut TestAppContext) {
2339 let app = app_with_chats(cx);
2340 cx.update(|cx| {
2341 app.update(cx, |state, _| {
2342 let missed = super::MissedCall {
2343 caller_mri: "8:orgid:bea-id".into(),
2344 caller_name: "Bea".into(),
2345 thread_id: None,
2346 at: chrono::Utc::now(),
2347 };
2348 assert_eq!(
2349 state.conversation_of_missed_call(&missed).as_deref(),
2350 Some("19:dm@unq.gbl.spaces")
2351 );
2352 let direct = super::MissedCall {
2353 thread_id: Some("19:dm@unq.gbl.spaces".into()),
2354 ..missed.clone()
2355 };
2356 assert_eq!(
2357 state.conversation_of_missed_call(&direct).as_deref(),
2358 Some("19:dm@unq.gbl.spaces")
2359 );
2360 })
2361 });
2362 }
2363
2364 #[gpui_kit::test]
2365 fn only_meeting_chats_and_channels_watch_for_a_running_meeting(cx: &mut TestAppContext) {
2366 let app = app_with_chats(cx);
2367 cx.update(|cx| {
2368 app.update(cx, |state, _| {
2369 assert!(state.watches_live_meeting("19:meeting@thread.v2"));
2370 assert!(!state.watches_live_meeting("19:dm@unq.gbl.spaces"));
2371 assert!(!state.watches_live_meeting("19:unknown"));
2372 })
2373 });
2374 }
2375
2376 #[gpui_kit::test]
2377 fn a_live_meeting_shows_until_it_ends(cx: &mut TestAppContext) {
2378 let app = app_with_chats(cx);
2379 let meeting = calling::meeting::LiveMeeting {
2380 thread_id: "19:meeting@thread.v2".into(),
2381 conversation_url: None,
2382 expiration: Some(chrono::Utc::now().timestamp() + 600),
2383 organizer_id: Some("org".into()),
2384 tenant_id: Some("tenant".into()),
2385 meeting_code: None,
2386 passcode: None,
2387 };
2388 cx.update(|cx| {
2389 app.update(cx, |state, cx| {
2390 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
2391 state.apply_live_meeting("19:meeting@thread.v2".into(), Some(meeting), cx);
2392 assert!(state.running_meeting("19:meeting@thread.v2").is_some());
2393 state.apply_live_meeting("19:meeting@thread.v2".into(), None, cx);
2394 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
2395 })
2396 });
2397 }
2398}