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.

feat(calls): highlight call icon if call is active (#2503)

Will Hutchinsonfdac003a5fd9
diff --git a/js/app/packages/channel/Call/ChannelCallButton.tsx b/js/app/packages/channel/Call/ChannelCallButton.tsx
index 8b302dd09f..55d9d7e20d 100644
--- a/js/app/packages/channel/Call/ChannelCallButton.tsx
+++ b/js/app/packages/channel/Call/ChannelCallButton.tsx
@@ -4,6 +4,7 @@ import { DEFAULT_CHANNEL_TAB } from '@channel/Channel/channel-tabs';
import { Button } from '@ui/components/Button';
import PhoneIcon from '@icon/regular/phone.svg';
import PhoneDisconnectIcon from '@icon/regular/phone-disconnect.svg';
+import { useActiveCallQuery } from '@queries/call/call';
import { useCall } from './useCall';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -14,8 +15,18 @@ export function ChannelCallButton(props: { channelId: string }) {
onLeave: () => setActiveTab(DEFAULT_CHANNEL_TAB),
});
+ const activeCallQuery = useActiveCallQuery(() => props.channelId);
+ const isCallInProgress = () => !!activeCallQuery.data;
+ const isHighlighted = () => call.isInThisChannel() || isCallInProgress();
+
const isPending = () => call.isJoining() || call.isLeaving();
+ const tooltip = () => {
+ if (call.isInThisChannel()) return 'Leave Call';
+ if (isCallInProgress()) return 'Join Call';
+ return 'Call';
+ };
+
const handleClick = async () => {
if (isPending()) return;
try {
@@ -33,9 +44,9 @@ export function ChannelCallButton(props: { channelId: string }) {
<Button
onClick={handleClick}
disabled={isPending()}
- tooltip={call.isInThisChannel() ? 'Leave Call' : 'Call'}
+ tooltip={tooltip()}
class={
- call.isInThisChannel()
+ isHighlighted()
? 'px-1 bg-accent/20 hover:bg-accent/30 text-accent-ink'
: 'px-1'
}
diff --git a/js/app/packages/queries/call/call.ts b/js/app/packages/queries/call/call.ts
index 3e64a07cbf..7e75d4abe7 100644
--- a/js/app/packages/queries/call/call.ts
+++ b/js/app/packages/queries/call/call.ts
@@ -1,12 +1,26 @@
import { throwOnErr } from '@core/util/maybeResult';
import { callServiceClient } from '@service-call/client';
-import { useMutation } from '@tanstack/solid-query';
+import { queryClient } from '@queries/client';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+export function useActiveCallQuery(channelId: Accessor<string>) {
+ return useQuery(() => ({
+ queryKey: ['call', 'active', channelId()],
+ queryFn: async () =>
+ await throwOnErr(() => callServiceClient.checkActiveCall(channelId())),
+ refetchInterval: 15_000,
+ }));
+}
export function useJoinCallMutation() {
return useMutation(() => ({
gcTime: 0,
mutationFn: async (channelId: string) =>
await throwOnErr(() => callServiceClient.getOrCreateCall(channelId)),
+ onSuccess() {
+ queryClient.invalidateQueries({ queryKey: ['call', 'active'] });
+ },
onError(error: Error) {
console.error('failed to join call', error);
},
@@ -18,6 +32,9 @@ export function useLeaveCallMutation() {
gcTime: 0,
mutationFn: (channelId: string) =>
throwOnErr(() => callServiceClient.leaveCall(channelId)),
+ onSuccess() {
+ queryClient.invalidateQueries({ queryKey: ['call', 'active'] });
+ },
onError(error: Error) {
console.error('failed to leave call', error);
},
diff --git a/js/app/packages/service-clients/service-call/client.ts b/js/app/packages/service-clients/service-call/client.ts
index d2cd56b770..f2dd828b71 100644
--- a/js/app/packages/service-clients/service-call/client.ts
+++ b/js/app/packages/service-clients/service-call/client.ts
@@ -1,9 +1,10 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import { mapOk } from '@core/util/maybeResult';
+import type { CallActiveResponse } from '@service-storage/generated/schemas/callActiveResponse';
import type { CallTokenResponse } from '@service-storage/generated/schemas/callTokenResponse';
import type { LeaveCallResponse } from '@service-storage/generated/schemas/leaveCallResponse';
-export type { CallTokenResponse, LeaveCallResponse };
+export type { CallActiveResponse, CallTokenResponse, LeaveCallResponse };
const host: string = SERVER_HOSTS['document-storage-service'];
@@ -25,4 +26,15 @@ export const callServiceClient = {
(result) => result
);
},
+
+ async checkActiveCall(channelId: string) {
+ return mapOk(
+ await fetchWithToken<CallActiveResponse>(
+ `${host}/call/${channelId}/active`,
+ { method: 'GET' }
+ ),
+ // safeFetch returns {} for 204 (no Content-Type header)
+ (data) => ('callId' in data ? (data as CallActiveResponse) : null)
+ );
+ },
};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/callActiveResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/callActiveResponse.ts
new file mode 100644
index 0000000000..76c8e063ce
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/callActiveResponse.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response indicating whether an active call exists for a channel.
+ */
+export interface CallActiveResponse {
+ /** The call identifier. */
+ callId: string;
+ /** The channel this call belongs to. */
+ channelId: string;
+ /** When the call was created. */
+ createdAt: string;
+ /** User who created the call. */
+ createdBy: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 6f10acd29d..9f29183a6b 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -76,6 +76,7 @@ export * from './basicDocumentSubTypeProperty';
export * from './basicDocumentType';
export * from './basicDocumentUpdatedAt';
export * from './bomPart';
+export * from './callActiveResponse';
export * from './callTokenResponse';
export * from './channel';
export * from './channelFilters';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 2ddd2a7084..fff935a57f 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -849,6 +849,26 @@ export const leaveOrEndCallResponse = zod
})
.describe('Response for the leave/end call operation.');
+/**
+ * Returns 200 with call info if an active call exists, or 204 No Content if not.
+ * @summary Handler for `GET /call/{channel_id}/active`.
+ */
+export const checkActiveCallParams = zod.object({
+ channel_id: zod.string().uuid().describe('Channel ID'),
+});
+
+export const checkActiveCallResponse = zod
+ .object({
+ callId: zod.string().uuid().describe('The call identifier.'),
+ channelId: zod
+ .string()
+ .uuid()
+ .describe('The channel this call belongs to.'),
+ createdAt: zod.string().datetime({}).describe('When the call was created.'),
+ createdBy: zod.string().describe('User who created the call.'),
+ })
+ .describe('Response indicating whether an active call exists for a channel.');
+
/**
* Receives transcript segments from the transcription agent.
Authenticated via the `x-macro-internal-call` shared secret.
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index ffb9cbf74a..e0e459eb53 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -731,6 +731,61 @@
}
}
},
+ "/call/{channel_id}/active": {
+ "get": {
+ "tags": ["call::inbound::axum_router"],
+ "summary": "Handler for `GET /call/{channel_id}/active`.",
+ "description": "Returns 200 with call info if an active call exists, or 204 No Content if not.",
+ "operationId": "check_active_call",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "description": "Channel ID",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CallActiveResponse"
+ }
+ }
+ }
+ },
+ "204": {
+ "description": "No active call"
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/call/{channel_id}/transcript": {
"post": {
"tags": ["call::inbound::axum_router"],
@@ -5701,6 +5756,32 @@
}
}
},
+ "CallActiveResponse": {
+ "type": "object",
+ "description": "Response indicating whether an active call exists for a channel.",
+ "required": ["callId", "channelId", "createdBy", "createdAt"],
+ "properties": {
+ "callId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The call identifier."
+ },
+ "channelId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The channel this call belongs to."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the call was created."
+ },
+ "createdBy": {
+ "type": "string",
+ "description": "User who created the call."
+ }
+ }
+ },
"CallTokenResponse": {
"type": "object",
"description": "Response returned when creating or joining a call.",
diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rs
index 7510259f47..23f06a5469 100644
--- a/rust/cloud-storage/call/src/domain/models.rs
+++ b/rust/cloud-storage/call/src/domain/models.rs
@@ -59,6 +59,21 @@ pub struct LeaveCallResponse {
pub call_ended: bool,
}
+/// Response indicating whether an active call exists for a channel.
+#[derive(Debug, serde::Serialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CallActiveResponse {
+ /// The call identifier.
+ pub call_id: Uuid,
+ /// The channel this call belongs to.
+ pub channel_id: Uuid,
+ /// User who created the call.
+ pub created_by: String,
+ /// When the call was created.
+ pub created_at: DateTime<Utc>,
+}
+
/// Configuration for S3 egress output.
#[derive(Clone)]
pub struct EgressS3Config {
diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rs
index b5942181e0..a54e3e4463 100644
--- a/rust/cloud-storage/call/src/domain/ports.rs
+++ b/rust/cloud-storage/call/src/domain/ports.rs
@@ -8,8 +8,8 @@ use std::future::Future;
use uuid::Uuid;
use super::models::{
- Call, CallError, CallParticipant, CallTokenResponse, CallWebhookEvent, EgressS3Config,
- LeaveCallResponse, TranscriptSegmentRequest,
+ Call, CallActiveResponse, CallError, CallParticipant, CallTokenResponse, CallWebhookEvent,
+ EgressS3Config, LeaveCallResponse, TranscriptSegmentRequest,
};
/// Repository port for persisting call state to the database.
@@ -34,6 +34,12 @@ pub trait CallRepository: Send + Sync + 'static {
channel_id: &Uuid,
) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;
+ /// Check whether an active call exists for a channel. Queries `calls` table only.
+ fn get_active_call_by_channel(
+ &self,
+ channel_id: &Uuid,
+ ) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;
+
/// Get an active call by its RTC room name.
fn get_call_by_room_name(
&self,
@@ -169,6 +175,13 @@ pub trait CallService: Send + Sync + 'static {
/// Validate an internal call token (e.g. from the `x-macro-internal-call` header).
fn validate_internal_call(&self, token: &str) -> bool;
+ /// Check if an active call exists for a channel.
+ /// Returns the call info if active, or `None` if no call exists.
+ fn check_active_call(
+ &self,
+ channel_id: &Uuid,
+ ) -> impl Future<Output = Result<Option<CallActiveResponse>, CallError>> + Send;
+
/// Get or create a call in a channel. If a call already exists, joins it;
/// otherwise creates a new one. Always returns a join token.
fn get_or_create_call(
diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rs
index b8ac568de5..4d4a5576d3 100644
--- a/rust/cloud-storage/call/src/domain/service.rs
+++ b/rust/cloud-storage/call/src/domain/service.rs
@@ -5,7 +5,8 @@ use connection::domain::ports::ConnectionService;
use uuid::Uuid;
use super::models::{
- CallError, CallTokenResponse, EgressS3Config, LeaveCallResponse, TranscriptSegmentRequest,
+ CallActiveResponse, CallError, CallTokenResponse, EgressS3Config, LeaveCallResponse,
+ TranscriptSegmentRequest,
};
use super::ports::{CallRepository, CallRtcClient, CallService};
@@ -88,6 +89,25 @@ impl<R: CallRepository, C: CallRtcClient, Cn: ConnectionService> CallService
.is_some_and(|secret| secret == token)
}
+ #[tracing::instrument(err, skip(self))]
+ async fn check_active_call(
+ &self,
+ channel_id: &Uuid,
+ ) -> Result<Option<CallActiveResponse>, CallError> {
+ let call = self
+ .repo
+ .get_active_call_by_channel(channel_id)
+ .await
+ .map_err(|e| CallError::Internal(e.into()))?;
+
+ Ok(call.map(|c| CallActiveResponse {
+ call_id: c.id,
+ channel_id: c.channel_id,
+ created_by: c.created_by,
+ created_at: c.created_at,
+ }))
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_or_create_call(
&self,
diff --git a/rust/cloud-storage/call/src/inbound/axum_router.rs b/rust/cloud-storage/call/src/inbound/axum_router.rs
index 62909ba5d4..f59e974e89 100644
--- a/rust/cloud-storage/call/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/call/src/inbound/axum_router.rs
@@ -29,7 +29,7 @@ use model_user::axum_extractor::MacroUserExtractor;
use uuid::Uuid;
use crate::domain::models::{
- CallError, CallTokenResponse, LeaveCallResponse, TranscriptSegmentRequest,
+ CallActiveResponse, CallError, CallTokenResponse, LeaveCallResponse, TranscriptSegmentRequest,
};
use crate::domain::ports::CallService;
@@ -72,6 +72,7 @@ impl<S, Svc> FromRef<CallRouterState<S, Svc>> for Arc<Svc> {
///
/// Routes:
/// - `GET /{channel_id}` — get or create a call (join existing or start new)
+/// - `GET /{channel_id}/active` — check if an active call exists
/// - `DELETE /{channel_id}` — leave or end a call
pub fn call_router<S, Svc, T>(state: CallRouterState<S, Svc>) -> Router<T>
where
@@ -84,6 +85,10 @@ where
"/{channel_id}",
get(get_or_create_call_handler::<S, Svc>).delete(leave_or_end_call_handler::<S, Svc>),
)
+ .route(
+ "/{channel_id}/active",
+ get(check_active_call_handler::<S, Svc>),
+ )
.with_state(state)
}
@@ -245,6 +250,37 @@ pub async fn get_or_create_call_handler<S: CallService, Svc: EntityAccessService
Ok(Json(response))
}
+/// Handler for `GET /call/{channel_id}/active`.
+///
+/// Returns 200 with call info if an active call exists, or 204 No Content if not.
+#[utoipa::path(
+ get,
+ operation_id = "check_active_call",
+ path = "/call/{channel_id}/active",
+ params(
+ ("channel_id" = Uuid, Path, description = "Channel ID"),
+ ),
+ responses(
+ (status = 200, body = CallActiveResponse),
+ (status = 204, description = "No active call"),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn check_active_call_handler<S: CallService, Svc: EntityAccessService>(
+ State(state): State<CallRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+) -> Result<axum::response::Response, CallError> {
+ let channel_id = Uuid::parse_str(&access.entity_access_receipt.entity().entity_id)
+ .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))?;
+
+ match state.service.check_active_call(&channel_id).await? {
+ Some(response) => Ok(Json(response).into_response()),
+ None => Ok(StatusCode::NO_CONTENT.into_response()),
+ }
+}
+
/// Handler for `DELETE /call/{channel_id}`.
#[utoipa::path(
delete,
diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
index b750002d27..92421f093e 100644
--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
@@ -137,6 +137,33 @@ impl CallRepository for PgCallRepo {
})
}
+ #[tracing::instrument(err, skip(self))]
+ async fn get_active_call_by_channel(
+ &self,
+ channel_id: &Uuid,
+ ) -> Result<Option<Call>, Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT id, channel_id, room_name, created_by, created_at, egress_id
+ FROM calls
+ WHERE channel_id = $1
+ "#,
+ channel_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map(|opt| {
+ opt.map(|row| Call {
+ id: row.id,
+ channel_id: row.channel_id,
+ room_name: row.room_name,
+ created_by: row.created_by,
+ created_at: row.created_at,
+ egress_id: row.egress_id,
+ })
+ })
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_call_by_room_name(&self, room_name: &str) -> Result<Option<Call>, Self::Err> {
sqlx::query!(
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index ea4f5ed5d0..0ee4a0c8c5 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -193,6 +193,7 @@ use utoipa::OpenApi;
// calls
call::inbound::axum_router::get_or_create_call_handler,
+ call::inbound::axum_router::check_active_call_handler,
call::inbound::axum_router::leave_or_end_call_handler,
call::inbound::axum_router::webhook_handler,
call::inbound::axum_router::transcript_handler,
@@ -335,6 +336,7 @@ use utoipa::OpenApi;
// Calls
call::domain::models::CallTokenResponse,
+ call::domain::models::CallActiveResponse,
call::domain::models::LeaveCallResponse,
call::domain::models::TranscriptSegmentRequest,