BlueGit

ict rusty-teams

Files

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

actions.rs

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