Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

perf(calls): speed up call start (#7793)

Eric Hayesa932983ab051
diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rs
index 52b11683c3..73dc573997 100644
--- a/crates/call/src/domain/service.rs
+++ b/crates/call/src/domain/service.rs
@@ -3,6 +3,7 @@
#[cfg(test)]
mod test;
+mod channel_startup;
mod guest_chat;
mod meeting_invites;
mod meetings;
@@ -78,15 +79,15 @@ pub struct CallServiceImpl<
> {
repo: R,
rtc_client: Arc<C>,
- connection_service: Cn,
+ connection_service: Arc<Cn>,
entity_access_service: E,
- notification_ingress: N,
+ notification_ingress: Arc<N>,
recording_storage: S,
server_url: String,
egress_s3_config: Option<EgressS3Config>,
internal_call_secret: Option<String>,
summarizer: Option<Sm>,
- voip_push_sender: V,
+ voip_push_sender: Arc<V>,
voice_repo: Vr,
ring_status_base_url: Option<String>,
event_broker: B,
@@ -115,15 +116,15 @@ impl<
Self {
repo,
rtc_client: Arc::new(rtc_client),
- connection_service,
+ connection_service: Arc::new(connection_service),
entity_access_service,
- notification_ingress,
+ notification_ingress: Arc::new(notification_ingress),
recording_storage,
server_url: server_url.into(),
egress_s3_config: None,
internal_call_secret: None,
summarizer: None,
- voip_push_sender: (),
+ voip_push_sender: Arc::new(()),
voice_repo: NoOpVoiceRepository,
ring_status_base_url: None,
event_broker: NoopMacroEventBroker,
@@ -188,7 +189,7 @@ impl<
egress_s3_config: self.egress_s3_config,
internal_call_secret: self.internal_call_secret,
summarizer: self.summarizer,
- voip_push_sender: sender,
+ voip_push_sender: Arc::new(sender),
voice_repo: self.voice_repo,
ring_status_base_url: self.ring_status_base_url,
event_broker: self.event_broker,
@@ -866,34 +867,6 @@ impl<
.await?
{
Some(call) => {
- // We are the creator — dispatch transcription agent (best-effort).
- self.rtc_client
- .dispatch_transcription_agent(&room_name)
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "failed to dispatch transcription agent")
- })
- .ok();
-
- // Start recording if configured.
- if let Some(s3_config) = &self.egress_s3_config {
- match self
- .rtc_client
- .start_room_composite_egress(&room_name, s3_config)
- .await
- {
- Ok(egress_id) => {
- self.repo
- .set_egress_id(&call.id, &egress_id)
- .await
- .map_err(|e| CallError::Internal(e.into()))?;
- }
- Err(e) => {
- tracing::error!(error=?e, "failed to start egress recording");
- }
- }
- }
-
match MacroUserIdStr::parse_from_str(&call.created_by) {
Ok(created_by) => {
self.publish_call_event(&CallMacroEvent::started(
@@ -915,182 +888,25 @@ impl<
}
}
- // Notify channel members about the new call (best-effort).
- self.send_call_event(
- &Some(*channel_id),
- "call_started",
- &serde_json::json!({
- "channel_id": channel_id,
- "call_id": call.id,
- "created_by": user_id,
- }),
- Some(user_id.copied()),
- )
- .await;
-
- // Send push notification and VoIP push to channel members (best-effort).
- let _: Result<(), anyhow::Error> = async {
- let channel_id_str = channel_id.to_string();
- let recipient_ids: HashSet<MacroUserIdStr<'_>> = self
- .entity_access_service
- .get_users_by_entity(&channel_id_str, EntityType::Channel)
- .await?
- .into_iter()
- .filter(|u| u.as_ref() != user_id.as_ref())
- .collect();
- if recipient_ids.is_empty() {
- return Ok(());
- }
-
- // Resolve the channel name from each recipient's
- // perspective: a DM is named after the other
- // participant, so the caller's view of the name
- // would be the callee's own name.
- let recipient_vec: Vec<MacroUserIdStr<'static>> = recipient_ids
- .iter()
- .cloned()
- .map(CowLike::into_owned)
- .collect();
- let channel_names_by_recipient = self
- .repo
- .resolve_channel_name_for_viewers(channel_id, &recipient_vec)
- .await
- .map_err(Into::into)?;
-
- let sender_profile_picture_url = self
- .repo
- .get_user_profile_picture(user_id.copied())
- .await
- .ok()
- .flatten();
-
- let caller_name = self
- .repo
- .get_user_display_name(user_id.copied())
- .await
- .ok()
- .flatten()
- .unwrap_or_else(|| user_id.email_str().to_string());
-
- // Try native call pushes first; ordinary alerts remain fallbacks
- // independently for iOS and Android.
-
- // Resolve VoIP endpoints before minting tokens:
- // users without PushKit endpoints should not get
- // LiveKit tokens minted for them. If endpoint
- // resolution fails, fall back to normal APNS for
- // everyone rather than dropping the notification.
- let voip_targets = match self
- .voip_push_sender
- .get_voip_push_targets(&recipient_vec)
- .await
- {
- Ok(targets) => targets,
- Err(e) => {
- tracing::error!(
- error=?e,
- "failed to resolve VoIP push targets; falling back to APNS"
- );
- Vec::new()
- }
- };
- let ring_status_url =
- self.ring_status_base_url.as_deref().map(|base| {
- format!(
- "{}/call/ring-status/{}",
- base.trim_end_matches('/'),
- call.id
- )
- });
- // One payload batch per distinct channel name, so
- // each recipient's native sheet shows the name they
- // know the channel by.
- let mut payloads_by_recipient: HashMap<
- MacroUserIdStr<'static>,
- VoipPushPayload,
- > = HashMap::new();
- let voip_groups = group_recipients_by_channel_name(
- voip_targets
- .iter()
- .map(|target| target.recipient_id.clone()),
- &channel_names_by_recipient,
- );
- for (voip_channel_name, voip_group_recipients) in voip_groups {
- let voip_group_recipients: Vec<MacroUserIdStr<'static>> =
- voip_group_recipients.into_iter().collect();
- let payloads = self
- .rtc_client
- .build_voip_push_payloads(VoipPushPayloadRequest {
- recipients: &voip_group_recipients,
- room_name: &call.room_name,
- call_id: call.id,
- channel_id: &channel_id_str,
- channel_name: voip_channel_name.as_deref().unwrap_or(""),
- caller_name: &caller_name,
- livekit_server_url: &self.server_url,
- ring_status_url: ring_status_url.as_deref(),
- })
- .await;
- payloads_by_recipient.extend(payloads);
- }
- // Rejoin resolved endpoints with successfully
- // minted payloads. A failed token mint skips only
- // that recipient's VoIP push.
- let pushes = voip_targets
- .into_iter()
- .filter_map(|target| {
- payloads_by_recipient
- .remove(&target.recipient_id)
- .map(|payload| (target, payload))
- })
- .collect();
-
- let native_delivery =
- self.voip_push_sender.send_voip_pushes(pushes).await;
-
- let apns_recipient_ids = exclude_voip_recipients(
- recipient_ids,
- &native_delivery.fully_delivered,
- );
-
- // Persist and alert only recipients with an unhandled platform.
- // Suppress ordinary alerts on platforms reached natively. One
- // request per distinct channel name, so the alert
- // title and stored metadata match what each
- // recipient calls the channel.
- let apns_groups = group_recipients_by_channel_name(
- apns_recipient_ids,
- &channel_names_by_recipient,
- );
- for (channel_name, apns_group_recipients) in apns_groups {
- let req = SendNotificationRequestBuilder {
- notification_entity: EntityType::Channel
- .with_entity_string(channel_id_str.clone()),
- secondary_notification_entity: None,
- notification: CallStartedNotification {
- sender_profile_picture_url: sender_profile_picture_url
- .clone(),
- channel_name,
- },
- sender_id: Some(user_id.copied()),
- recipient_ids: apns_group_recipients,
- }
- .into_request()
- .with_apns()
- .with_mobile_push_exclusions(native_delivery.delivered.clone());
-
- self.notification_ingress
- .send_notification(req)
- .await
- .map_err(|e| anyhow::anyhow!(e))?;
- }
-
- Ok(())
+ // Only the allocation winner starts media and ringing. Schedule
+ // before subsequent join steps, so a failed first join cannot
+ // strand the room without recording or notifications.
+ channel_startup::ChannelCallStartup {
+ repo: self.repo.clone(),
+ rtc_client: self.rtc_client.clone(),
+ connection_service: self.connection_service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ notification_ingress: self.notification_ingress.clone(),
+ voip_push_sender: self.voip_push_sender.clone(),
+ server_url: self.server_url.clone(),
+ ring_status_base_url: self.ring_status_base_url.clone(),
+ egress_s3_config: self.egress_s3_config.clone(),
}
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "failed to send call started notification");
- });
+ .spawn(
+ call.clone(),
+ *channel_id,
+ user_id.clone().into_owned(),
+ );
call
}
diff --git a/crates/call/src/domain/service/channel_startup.rs b/crates/call/src/domain/service/channel_startup.rs
new file mode 100644
index 0000000000..a6f208379b
--- /dev/null
+++ b/crates/call/src/domain/service/channel_startup.rs
@@ -0,0 +1,223 @@
+//! Best-effort channel media and notifications after room allocation.
+
+use super::*;
+use tracing::Instrument;
+
+pub(super) struct ChannelCallStartup<R, C, Cn, E, N, V> {
+ pub repo: R,
+ pub rtc_client: Arc<C>,
+ pub connection_service: Arc<Cn>,
+ pub entity_access_service: E,
+ pub notification_ingress: Arc<N>,
+ pub voip_push_sender: Arc<V>,
+ pub server_url: String,
+ pub ring_status_base_url: Option<String>,
+ pub egress_s3_config: Option<EgressS3Config>,
+}
+
+impl<
+ R: CallRepository,
+ C: CallRtcClient,
+ Cn: ConnectionService,
+ E: EntityAccessService,
+ N: NotificationIngress,
+ V: VoipPushSender,
+> ChannelCallStartup<R, C, Cn, E, N, V>
+{
+ pub fn spawn(
+ self,
+ call: Call,
+ channel_id: Uuid,
+ user_id: MacroUserIdStr<'static>,
+ ) -> tokio::task::JoinHandle<()> {
+ let span = tracing::info_span!("start_channel_call", call_id = %call.id, %channel_id);
+ tokio::spawn(async move {
+ let transcription = async {
+ self.rtc_client.dispatch_transcription_agent(&call.room_name).await
+ .inspect_err(|error| tracing::error!(error=?error, "failed to dispatch transcription agent")).ok();
+ };
+ let recording = meetings::start_meeting_recording(&self.repo, self.rtc_client.as_ref(), call.id, &call.room_name, self.egress_s3_config.as_ref());
+ let notifications = async {
+ self.notify(&call, &channel_id, user_id).await
+ .inspect_err(|error| tracing::error!(error=?error, "failed to send call started notification")).ok();
+ };
+ tokio::join!(transcription, recording, notifications);
+ }.instrument(span))
+ }
+
+ #[tracing::instrument(err, skip_all, fields(call_id = %call.id))]
+ async fn notify(
+ &self,
+ call: &Call,
+ channel_id: &Uuid,
+ user_id: MacroUserIdStr<'_>,
+ ) -> anyhow::Result<()> {
+ let channel_id_str = channel_id.to_string();
+ let recipient_ids: HashSet<MacroUserIdStr<'_>> = self
+ .entity_access_service
+ .get_users_by_entity(&channel_id_str, EntityType::Channel)
+ .await?
+ .into_iter()
+ .filter(|u| u.as_ref() != user_id.as_ref())
+ .collect();
+ if recipient_ids.is_empty() {
+ return Ok(());
+ }
+ // Do not start ringing a call that ended while resolving its recipients.
+ if self
+ .repo
+ .get_call_by_id(&call.id)
+ .await
+ .map_err(Into::into)?
+ .is_none()
+ {
+ return Ok(());
+ }
+ let users: Vec<_> = recipient_ids.iter().map(CowLike::copied).collect();
+ self.connection_service
+ .send_channel_message(
+ &users,
+ "call_started",
+ serde_json::json!({
+ "channel_id": channel_id, "call_id": call.id, "created_by": user_id,
+ }),
+ )
+ .await
+ .inspect_err(|error| tracing::error!(error=?error, "failed to send call started event"))
+ .ok();
+
+ // Resolve the channel name from each recipient's
+ // perspective: a DM is named after the other
+ // participant, so the caller's view of the name
+ // would be the callee's own name.
+ let recipient_vec: Vec<MacroUserIdStr<'static>> = recipient_ids
+ .iter()
+ .cloned()
+ .map(CowLike::into_owned)
+ .collect();
+ let channel_names_by_recipient = self
+ .repo
+ .resolve_channel_name_for_viewers(channel_id, &recipient_vec)
+ .await
+ .map_err(Into::into)?;
+
+ let sender_profile_picture_url = self
+ .repo
+ .get_user_profile_picture(user_id.copied())
+ .await
+ .ok()
+ .flatten();
+
+ let caller_name = self
+ .repo
+ .get_user_display_name(user_id.copied())
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| user_id.email_str().to_string());
+
+ // Try native call pushes first; ordinary alerts remain fallbacks
+ // independently for iOS and Android.
+
+ // Resolve VoIP endpoints before minting tokens:
+ // users without PushKit endpoints should not get
+ // LiveKit tokens minted for them. If endpoint
+ // resolution fails, fall back to normal APNS for
+ // everyone rather than dropping the notification.
+ let voip_targets = match self
+ .voip_push_sender
+ .get_voip_push_targets(&recipient_vec)
+ .await
+ {
+ Ok(targets) => targets,
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ "failed to resolve VoIP push targets; falling back to APNS"
+ );
+ Vec::new()
+ }
+ };
+ let ring_status_url = self.ring_status_base_url.as_deref().map(|base| {
+ format!(
+ "{}/call/ring-status/{}",
+ base.trim_end_matches('/'),
+ call.id
+ )
+ });
+ // One payload batch per distinct channel name, so
+ // each recipient's native sheet shows the name they
+ // know the channel by.
+ let mut payloads_by_recipient: HashMap<MacroUserIdStr<'static>, VoipPushPayload> =
+ HashMap::new();
+ let voip_groups = group_recipients_by_channel_name(
+ voip_targets
+ .iter()
+ .map(|target| target.recipient_id.clone()),
+ &channel_names_by_recipient,
+ );
+ for (voip_channel_name, voip_group_recipients) in voip_groups {
+ let voip_group_recipients: Vec<MacroUserIdStr<'static>> =
+ voip_group_recipients.into_iter().collect();
+ let payloads = self
+ .rtc_client
+ .build_voip_push_payloads(VoipPushPayloadRequest {
+ recipients: &voip_group_recipients,
+ room_name: &call.room_name,
+ call_id: call.id,
+ channel_id: &channel_id_str,
+ channel_name: voip_channel_name.as_deref().unwrap_or(""),
+ caller_name: &caller_name,
+ livekit_server_url: &self.server_url,
+ ring_status_url: ring_status_url.as_deref(),
+ })
+ .await;
+ payloads_by_recipient.extend(payloads);
+ }
+ // Rejoin resolved endpoints with successfully
+ // minted payloads. A failed token mint skips only
+ // that recipient's VoIP push.
+ let pushes = voip_targets
+ .into_iter()
+ .filter_map(|target| {
+ payloads_by_recipient
+ .remove(&target.recipient_id)
+ .map(|payload| (target, payload))
+ })
+ .collect();
+
+ let native_delivery = self.voip_push_sender.send_voip_pushes(pushes).await;
+
+ let apns_recipient_ids =
+ exclude_voip_recipients(recipient_ids, &native_delivery.fully_delivered);
+
+ // Persist and alert only recipients with an unhandled platform.
+ // Suppress ordinary alerts on platforms reached natively. One
+ // request per distinct channel name, so the alert
+ // title and stored metadata match what each
+ // recipient calls the channel.
+ let apns_groups =
+ group_recipients_by_channel_name(apns_recipient_ids, &channel_names_by_recipient);
+ for (channel_name, apns_group_recipients) in apns_groups {
+ let req = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Channel.with_entity_string(channel_id_str.clone()),
+ secondary_notification_entity: None,
+ notification: CallStartedNotification {
+ sender_profile_picture_url: sender_profile_picture_url.clone(),
+ channel_name,
+ },
+ sender_id: Some(user_id.copied()),
+ recipient_ids: apns_group_recipients,
+ }
+ .into_request()
+ .with_apns()
+ .with_mobile_push_exclusions(native_delivery.delivered.clone());
+
+ self.notification_ingress
+ .send_notification(req)
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
+ }
+ Ok(())
+ }
+}
diff --git a/crates/call/src/domain/service/meetings.rs b/crates/call/src/domain/service/meetings.rs
index 92ad141fa5..2754f39de8 100644
--- a/crates/call/src/domain/service/meetings.rs
+++ b/crates/call/src/domain/service/meetings.rs
@@ -22,7 +22,7 @@ impl<
> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>
{
/// Webhooks can beat the startup API response, especially if a call ends
- /// immediately. Correlate only standalone rooms whose UUID is their call ID.
+ /// immediately. Correlate rooms whose UUID is their call ID, including channel sessions.
#[tracing::instrument(err, skip_all)]
pub(super) async fn link_meeting_recording_webhook(
&self,
@@ -41,7 +41,6 @@ impl<
.await
.map_err(|e| CallError::Internal(e.into()))?;
if let Some(record) = record
- && record.channel_id.is_none()
&& record.room_name.as_deref() == Some(room_name)
{
self.repo
diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rs
index 008205e068..c7ff993f9a 100644
--- a/crates/call/src/domain/service/test.rs
+++ b/crates/call/src/domain/service/test.rs
@@ -24,7 +24,9 @@ use notification::domain::service::NotificationIngress;
use serde_json::json;
use uuid::Uuid;
+mod access;
mod active_meetings;
+mod channel_startup;
mod guest_chat;
mod meeting_invites;
mod meeting_participants;
@@ -440,11 +442,7 @@ fn started_event_call(created_by: &str) -> Call {
}
}
-fn mock_get_or_create_repo(
- scenario: GetOrCreateScenario,
- call: Call,
- recording_enabled: bool,
-) -> MockCallRepository {
+fn mock_get_or_create_repo(scenario: GetOrCreateScenario, call: Call) -> MockCallRepository {
let mut repo = MockCallRepository::new();
match scenario {
@@ -482,12 +480,6 @@ fn mock_get_or_create_repo(
}
}
- if recording_enabled {
- repo.expect_set_egress_id()
- .times(1)
- .returning(|_, _| Box::pin(async { Ok(()) }));
- }
-
repo.expect_find_active_call_for_user()
.times(1)
.returning(|_| Box::pin(async { Ok(None) }));
@@ -505,7 +497,7 @@ fn mock_get_or_create_repo(
repo
}
-type BaseGetOrCreateCallService<Cn> = CallServiceImpl<
+type BaseGetOrCreateCallService<Cn, B = macro_event_broker::NoopMacroEventBroker> = CallServiceImpl<
MockCallRepository,
MockRtcClient,
Cn,
@@ -513,6 +505,9 @@ type BaseGetOrCreateCallService<Cn> = CallServiceImpl<
StubNotificationIngress,
StubRecordingStorage,
NoopCallSummarizer,
+ (),
+ NoOpVoiceRepository,
+ B,
>;
fn build_get_or_create_service<B: MacroEventBroker + Clone, Cn: ConnectionService>(
@@ -520,7 +515,7 @@ fn build_get_or_create_service<B: MacroEventBroker + Clone, Cn: ConnectionServic
connection_service: Cn,
event_broker: B,
recording_enabled: bool,
-) -> impl CallService {
+) -> BaseGetOrCreateCallService<Cn, B> {
let service: BaseGetOrCreateCallService<Cn> = CallServiceImpl::new(
repo,
MockRtcClient::new(),
@@ -551,13 +546,40 @@ async fn get_or_create_call(
recording_enabled: bool,
) -> Result<crate::domain::models::CallTokenResponse, CallError> {
let call = started_event_call(created_by);
- let repo = mock_get_or_create_repo(scenario, call, recording_enabled);
+ let repo = mock_get_or_create_repo(scenario, call);
let service =
build_get_or_create_service(repo, StubConnectionService, broker, recording_enabled);
- service
+ let mut completed = None;
+ if matches!(scenario, GetOrCreateScenario::CreatorWins) && recording_enabled {
+ let (sent, received) = tokio::sync::oneshot::channel();
+ let mut background_repo = MockCallRepository::new();
+ background_repo
+ .expect_attach_meeting_recording()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(true) }));
+ background_repo
+ .expect_get_call_by_id()
+ .times(1)
+ .return_once(move |_| {
+ Box::pin(async move {
+ sent.send(()).unwrap();
+ Ok(Some(started_event_call(STARTED_EVENT_CREATOR)))
+ })
+ });
+ configure_repository_clone(&service.repo, background_repo);
+ completed = Some(received);
+ }
+ let result = service
.get_or_create_call(&STARTED_EVENT_CHANNEL_ID, user("[email protected]"))
- .await
+ .await;
+ if let Some(completed) = completed {
+ tokio::time::timeout(Duration::from_secs(2), completed)
+ .await
+ .unwrap()
+ .unwrap();
+ }
+ result
}
#[tokio::test]
@@ -677,7 +699,7 @@ async fn malformed_stored_creator_skips_only_started_event() {
#[tokio::test]
async fn get_or_create_call_sends_call_answered_to_joining_user() {
let call = started_event_call(STARTED_EVENT_CREATOR);
- let repo = mock_get_or_create_repo(GetOrCreateScenario::ExistingCall, call, false);
+ let repo = mock_get_or_create_repo(GetOrCreateScenario::ExistingCall, call);
let connection_service = RecordingConnectionService::default();
let service = build_get_or_create_service(
repo,
diff --git a/crates/call/src/domain/service/test/meeting_invites/access.rs b/crates/call/src/domain/service/test/access.rs
similarity index 97%
rename from crates/call/src/domain/service/test/meeting_invites/access.rs
rename to crates/call/src/domain/service/test/access.rs
index 5345067c49..7dada52501 100644
--- a/crates/call/src/domain/service/test/meeting_invites/access.rs
+++ b/crates/call/src/domain/service/test/access.rs
@@ -15,6 +15,7 @@ use uuid::Uuid;
pub(super) struct TeamAccessService {
pub(super) teams: HashMap<String, Uuid>,
pub(super) fail_lookup: bool,
+ pub(super) channel_users: Vec<MacroUserIdStr<'static>>,
}
impl EntityAccessService for TeamAccessService {
@@ -104,9 +105,7 @@ impl EntityAccessService for TeamAccessService {
_entity_id: &str,
_entity_type: EntityType,
) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
- Err(AccessError::internal(
- "entity access service not configured",
- ))
+ Ok(self.channel_users.clone())
}
async fn get_call_channel(
diff --git a/crates/call/src/domain/service/test/channel_startup.rs b/crates/call/src/domain/service/test/channel_startup.rs
new file mode 100644
index 0000000000..862c8bfb37
--- /dev/null
+++ b/crates/call/src/domain/service/test/channel_startup.rs
@@ -0,0 +1,255 @@
+use super::access::TeamAccessService;
+use super::*;
+use tokio::sync::{Notify, mpsc};
+
+struct SlowConnectionService {
+ release: Arc<Notify>,
+ events: mpsc::UnboundedSender<&'static str>,
+}
+
+impl ConnectionService for SlowConnectionService {
+ async fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
+ &self,
+ _: InvalidationEvent<'a, T>,
+ ) -> Result<(), ConnectionError> {
+ unreachable!()
+ }
+
+ async fn send_channel_message<'a>(
+ &self,
+ users: &[MacroUserIdStr<'a>],
+ message_type: &str,
+ message: serde_json::Value,
+ ) -> Result<(), ConnectionError> {
+ match message_type {
+ "call_answered" => Ok(()),
+ "call_started" => {
+ assert_eq!(users, &[user("[email protected]")]);
+ assert_eq!(message["call_id"], json!(STARTED_EVENT_CALL_ID));
+ self.events.send("notification").unwrap();
+ self.release.notified().await;
+ Ok(())
+ }
+ _ => panic!("unexpected call event"),
+ }
+ }
+}
+
+struct RecordingNotificationIngress(mpsc::UnboundedSender<&'static str>);
+
+impl NotificationIngress for RecordingNotificationIngress {
+ async fn send_notification<
+ 'a,
+ T: notification::domain::models::Notification + Clone + 'static,
+ U: serde::Serialize + Send + Sync + 'static,
+ >(
+ &self,
+ _: notification::domain::models::request::SendNotificationRequest<'a, T, U>,
+ ) -> Result<
+ Option<notification::domain::models::NotificationResult<'a>>,
+ rootcause::Report<notification::domain::service::SendNotificationError>,
+ > {
+ self.0.send("push").unwrap();
+ Ok(None)
+ }
+}
+
+async fn next_event(events: &mut mpsc::UnboundedReceiver<&'static str>) -> &'static str {
+ tokio::time::timeout(Duration::from_secs(2), events.recv())
+ .await
+ .expect("background task should progress")
+ .expect("event sender is alive")
+}
+
+#[tokio::test]
+async fn channel_token_does_not_wait_for_media_or_recipient_notifications() {
+ let (events, mut received) = mpsc::unbounded_channel();
+ let release_agent = Arc::new(Notify::new());
+ let release_recorder = Arc::new(Notify::new());
+ let release_notifications = Arc::new(Notify::new());
+ let call = started_event_call(STARTED_EVENT_CREATOR);
+ let repo = mock_get_or_create_repo(GetOrCreateScenario::CreatorWins, call.clone());
+ let mut rtc = MockCallRtcClient::new();
+ rtc.expect_create_room()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(()) }));
+ rtc.expect_generate_token()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok("token".into()) }));
+ let gate = release_agent.clone();
+ let sender = events.clone();
+ rtc.expect_dispatch_transcription_agent()
+ .times(1)
+ .return_once(move |_| {
+ Box::pin(async move {
+ sender.send("transcription").unwrap();
+ gate.notified().await;
+ sender.send("transcription_done").unwrap();
+ // A best-effort failure must not invalidate issued credentials.
+ Err(anyhow::anyhow!("agent unavailable"))
+ })
+ });
+ let gate = release_recorder.clone();
+ let sender = events.clone();
+ rtc.expect_start_room_composite_egress()
+ .times(1)
+ .return_once(move |_, _| {
+ Box::pin(async move {
+ sender.send("recording").unwrap();
+ gate.notified().await;
+ Ok("egress".into())
+ })
+ });
+ let mut background_repo = MockCallRepository::new();
+ background_repo
+ .expect_get_call_by_id()
+ .times(2)
+ .returning(move |_| {
+ let call = call.clone();
+ Box::pin(async move { Ok(Some(call)) })
+ });
+ let sender = events.clone();
+ background_repo
+ .expect_attach_meeting_recording()
+ .times(1)
+ .return_once(move |id, egress| {
+ assert_eq!(*id, STARTED_EVENT_CALL_ID);
+ assert_eq!(egress, "egress");
+ Box::pin(async move {
+ sender.send("attached").unwrap();
+ Ok(true)
+ })
+ });
+ background_repo
+ .expect_resolve_channel_name_for_viewers()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(HashMap::new()) }));
+ background_repo
+ .expect_get_user_profile_picture()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(None) }));
+ background_repo
+ .expect_get_user_display_name()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(None) }));
+ let service = CallServiceImpl::<_, _, _, _, _, _, NoopCallSummarizer>::new(
+ repo,
+ rtc,
+ SlowConnectionService {
+ release: release_notifications.clone(),
+ events: events.clone(),
+ },
+ TeamAccessService {
+ channel_users: vec![user("[email protected]"), user("[email protected]")],
+ ..Default::default()
+ },
+ RecordingNotificationIngress(events),
+ StubRecordingStorage,
+ "wss://example.com",
+ )
+ .with_egress(EgressS3Config {
+ bucket: "test".into(),
+ region: "test".into(),
+ access_key: "test".into(),
+ secret: "test".into(),
+ });
+ configure_repository_clone(&service.repo, background_repo);
+ let token = tokio::time::timeout(
+ Duration::from_millis(200),
+ service.get_or_create_call(&STARTED_EVENT_CHANNEL_ID, user("[email protected]")),
+ )
+ .await
+ .expect("credentials must not wait for background services")
+ .unwrap();
+ assert_eq!(token.token, "token");
+ let mut started = HashSet::new();
+ for _ in 0..3 {
+ started.insert(next_event(&mut received).await);
+ }
+ assert_eq!(
+ started,
+ HashSet::from(["transcription", "recording", "notification"])
+ );
+ release_recorder.notify_one();
+ assert_eq!(next_event(&mut received).await, "attached");
+ release_notifications.notify_one();
+ assert_eq!(next_event(&mut received).await, "push");
+ release_agent.notify_one();
+ assert_eq!(next_event(&mut received).await, "transcription_done");
+ tokio::task::yield_now().await;
+}
+
+#[tokio::test]
+async fn existing_and_race_losing_joins_do_not_start_background_services() {
+ for scenario in [
+ GetOrCreateScenario::ExistingCall,
+ GetOrCreateScenario::RaceLoses,
+ ] {
+ let repo = mock_get_or_create_repo(scenario, started_event_call(STARTED_EVENT_CREATOR));
+ let mut rtc = MockCallRtcClient::new();
+ if matches!(scenario, GetOrCreateScenario::RaceLoses) {
+ rtc.expect_create_room()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(()) }));
+ rtc.expect_delete_room()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(()) }));
+ }
+ rtc.expect_generate_token()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok("token".into()) }));
+ rtc.expect_dispatch_transcription_agent().never();
+ rtc.expect_start_room_composite_egress().never();
+ let service: BaseWebhookCallService<StubConnectionService> = CallServiceImpl::new(
+ repo,
+ rtc,
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ "wss://example.com",
+ );
+ service
+ .get_or_create_call(&STARTED_EVENT_CHANNEL_ID, user("[email protected]"))
+ .await
+ .unwrap();
+ tokio::task::yield_now().await;
+ }
+}
+
+#[tokio::test]
+async fn ended_call_does_not_ring_recipients() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_by_id()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(None) }));
+ let mut rtc = MockCallRtcClient::new();
+ rtc.expect_dispatch_transcription_agent()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(()) }));
+ rtc.expect_start_room_composite_egress().never();
+ let connection = RecordingConnectionService::default();
+ let startup = super::super::channel_startup::ChannelCallStartup {
+ repo,
+ rtc_client: Arc::new(rtc),
+ connection_service: Arc::new(connection.clone()),
+ entity_access_service: TeamAccessService {
+ channel_users: vec![user("[email protected]")],
+ ..Default::default()
+ },
+ notification_ingress: Arc::new(StubNotificationIngress),
+ voip_push_sender: Arc::new(()),
+ server_url: "wss://example.com".into(),
+ ring_status_base_url: None,
+ egress_s3_config: None,
+ };
+ startup
+ .spawn(
+ started_event_call(STARTED_EVENT_CREATOR),
+ STARTED_EVENT_CHANNEL_ID,
+ )
+ .await
+ .unwrap();
+ assert!(connection.messages().is_empty());
+}
diff --git a/crates/call/src/domain/service/test/meeting_invites.rs b/crates/call/src/domain/service/test/meeting_invites.rs
index 7e462d7d90..9f71f55c54 100644
--- a/crates/call/src/domain/service/test/meeting_invites.rs
+++ b/crates/call/src/domain/service/test/meeting_invites.rs
@@ -1,8 +1,7 @@
use super::*;
use crate::domain::meetings::{InviteMeetingUsersRequest, Meeting};
-mod access;
-use access::TeamAccessService;
+use super::access::TeamAccessService;
const OWNER_EMAIL: &str = "[email protected]";
const TEAMMATE_EMAIL: &str = "[email protected]";
@@ -29,6 +28,7 @@ fn same_team() -> TeamAccessService {
.map(|email| (user(email).to_string(), team_id))
.collect(),
fail_lookup: false,
+ ..Default::default()
}
}
diff --git a/crates/call/src/domain/service/test/meeting_startup.rs b/crates/call/src/domain/service/test/meeting_startup.rs
index b9e298d4cd..79cbbcbcd3 100644
--- a/crates/call/src/domain/service/test/meeting_startup.rs
+++ b/crates/call/src/domain/service/test/meeting_startup.rs
@@ -359,8 +359,13 @@ fn test_egress_config() -> EgressS3Config {
#[tokio::test]
async fn recording_webhook_can_link_before_the_startup_response() {
- for correct_room in [false, true] {
+ for (correct_room, channel_id) in [
+ (false, None),
+ (true, None),
+ (true, Some(STARTED_EVENT_CHANNEL_ID)),
+ ] {
let mut record = standalone_record(false);
+ record.channel_id = channel_id;
let call_id = record.call_id;
let room_name = call_id.to_string();
record.room_name = Some(if correct_room {
diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.md
index 6ffc0d3cb8..e7dd78081f 100644
--- a/docs/agent-guide/calls.md
+++ b/docs/agent-guide/calls.md
@@ -15,7 +15,10 @@ opens the recipient picker directly. `Start an instant call` opens `/app/meet/ne
without creating a meeting, the same setup reached from `New Call` beside
Calendar's `New event` or `Create` → `Call` (`C C`). Scheduled calls are created
through Calendar and can be shared with people who do not have a Macro account.
-The channel/contact option opens the recipient picker.
+The channel/contact option opens the recipient picker. Starting a channel call
+connects the creator without waiting for recording, transcription, or recipient
+notification delivery. Verify that a second participant still receives the ring
+and can join, and that leaving immediately does not leave a recording running.
Recordings, transcriptions
and summaries appear here; empty state notes "Calls are available to agents."
diff --git a/docs/agent-guide/observability.md b/docs/agent-guide/observability.md
index 74875ecc3b..a7092e3e19 100644
--- a/docs/agent-guide/observability.md
+++ b/docs/agent-guide/observability.md
@@ -119,7 +119,10 @@ The HTTP requests can have separate trace IDs across asynchronous mutation
boundaries. Capture each request's `traceparent` as described above and inspect
the backend trace as well. For the join request, compare `create_room`,
`prepare_meeting_call`, and `join_invitation`; `start_meeting_media` runs in the
-background and must not be added to the time spent waiting for credentials.
+background and must not be added to the time spent waiting for credentials. Channel
+calls similarly launch `start_channel_call` for recording, transcription, and
+recipient notifications; these run concurrently outside the token response path.
+A slow recorder or push provider should not hold the creator on Connecting.
## Agent sessions