BlueGit

ict rusty-teams

Files

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

actions.rs

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