BlueGit

ict rusty-teams

Files

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

actions.rs

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