Skip to content

The open alternative to Salesforce, designed for AI.

feat(call-recorder): toggle to send the bot to all calendar meetings (#25431)

nitinb8df2dac39eb
diff --git a/packages/twenty-apps/public/call-recorder/README.md b/packages/twenty-apps/public/call-recorder/README.md
index e837efa8b73..e99b534d972 100644
--- a/packages/twenty-apps/public/call-recorder/README.md
+++ b/packages/twenty-apps/public/call-recorder/README.md
@@ -30,6 +30,14 @@ happens once the meeting is within the seven-day scheduling window. Set it to
Off to skip a meeting. Past meetings the recorder never joined simply stay
blank.
+## 🗓️ Pausing the recorder
+
+The **Record my calendar meetings** toggle in the app settings is on
+by default. Turn it off to stop scheduling bots for upcoming meetings and cancel
+every recording that is already scheduled; the Recording Bot field of those
+meetings goes back to blank, and an Off you set yourself is left alone. Turn it
+back on and the app sweeps upcoming meetings to schedule bots again.
+
## 🎥 Supported meeting platforms
The recording bot can only join meetings on these platforms:
diff --git a/packages/twenty-apps/public/call-recorder/SETUP.md b/packages/twenty-apps/public/call-recorder/SETUP.md
index 2952e82990a..c401318e741 100644
--- a/packages/twenty-apps/public/call-recorder/SETUP.md
+++ b/packages/twenty-apps/public/call-recorder/SETUP.md
@@ -35,8 +35,11 @@ Set these on the application registration after installing
| `CALL_RECORDER_RECORDING_RETENTION_HOURS` | No | How long Recall.ai retains the source media after processing. Defaults to `166` hours (6 days 22 hours), just under Recall's 168-hour free-storage window. Values above `168` may incur Recall storage charges. Twenty's ingested copy is unaffected. |
| `RECALL_WEBHOOK_SECRET` | Yes | Svix signing secret (`whsec_…`) used to verify incoming Recall webhooks. |
-> **Bot behavior settings** (display name, recording notice, join timing, lobby
-> and leave timeouts), the transcription provider
+> **Calendar scheduling** (`CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED`,
+> the "Record my calendar meetings" toggle; turning it off cancels
+> every scheduled recording), **bot behavior settings** (display name,
+> recording notice, join timing, lobby and leave timeouts), the transcription
+> provider
> (`CALL_RECORDER_TRANSCRIPT_PROVIDER`) and the summary settings
> (`CALL_RECORDER_SUMMARY_ENABLED`,
> `CALL_RECORDER_ADDITIONAL_SUMMARY_PROMPT`) are **application variables** that
diff --git a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
index 33547c2aed4..c6cc784d2ff 100644
--- a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
@@ -11,12 +11,16 @@ import {
vi,
} from 'vitest';
+import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';
import { CALENDAR_EVENT_UPDATE_BATCH_SIZE } from 'src/logic-functions/constants/calendar-event-update-batch-size';
import { cancelCallRecordingRequest } from 'src/logic-functions/flows/cancel-call-recording-request.util';
import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';
import { retryFailedRecallCancellations } from 'src/logic-functions/flows/retry-failed-recall-cancellations.util';
import { scheduleRecallBotsForPendingCallRecordings } from 'src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util';
import { processRecallWebhookHandler } from 'src/logic-functions/process-recall-webhook';
+import { cancelScheduledRecallBotsHandler } from 'src/logic-functions/cancel-scheduled-recall-bots';
+import { cancelScheduledRecallBots } from 'src/logic-functions/flows/cancel-scheduled-recall-bots.util';
+import { syncCalendarBotSchedulingHandler } from 'src/logic-functions/sync-calendar-bot-scheduling';
import reconcileCalendarEventLogicFunction from 'src/logic-functions/reconcile-call-recorder-calendar-event';
// ---------------------------------------------------------------------------
@@ -169,6 +173,7 @@ class FakeRecallApi {
artifactImportRequests: object[] = [];
failNextDelete = false;
failCalendarEventUpdates = false;
+ failRecallRemovals = false;
seedBot(bot: FakeRecallBot): void {
this.bots.set(bot.id, bot);
@@ -239,8 +244,21 @@ class FakeRecallApi {
const botIdMatch = requestUrl.match(/\/bot\/([^/]+)\/$/);
+ const ejectedBotIdMatch = requestUrl.match(/\/bot\/([^/]+)\/leave_call\/$/);
+
+ if (method === 'POST' && ejectedBotIdMatch !== null) {
+ if (this.failRecallRemovals) {
+ return jsonResponse(400, {});
+ }
+
+ this.bots.delete(ejectedBotIdMatch[1]);
+ this.deletedBotIds.push(ejectedBotIdMatch[1]);
+
+ return new Response(null, { status: 204 });
+ }
+
if (method === 'DELETE' && botIdMatch !== null) {
- if (this.failNextDelete) {
+ if (this.failNextDelete || this.failRecallRemovals) {
this.failNextDelete = false;
return jsonResponse(400, {});
@@ -1231,5 +1249,160 @@ describe('call recorder app lifecycle (integration)', () => {
expect(callRecording.recordingRequestStatus).toBe('REQUESTED');
expect(callRecording.externalBotId).toBeTruthy();
});
+
+ it('clears an On the meeting no longer earns', async () => {
+ const { calendarEventId, callRecordingId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('ON');
+
+ await client.mutation({
+ updateCalendarEvent: {
+ __args: { id: calendarEventId, data: { isCanceled: true } },
+ id: true,
+ },
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBeNull();
+ expect(
+ (await fetchCallRecording(callRecordingId)).recordingRequestStatus,
+ ).toBe('CANCELED');
+ });
+
+ it('keeps the On of a meeting that was actually recorded', async () => {
+ const calendarEventId = await createCalendarEvent({
+ startsAt: hoursAgo(3),
+ endsAt: hoursAgo(2),
+ });
+
+ await createPendingCallRecording({
+ calendarEventId,
+ status: 'COMPLETED',
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('ON');
+ });
+ });
+
+ describe('workspace recording switch', () => {
+ const turnRecordingOff = () =>
+ vi.stubEnv(
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME,
+ 'false',
+ );
+
+ it('cancels the request inline and leaves the Recall bot to the enqueued job', async () => {
+ const { callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+
+ turnRecordingOff();
+
+ const result = await syncCalendarBotSchedulingHandler();
+
+ expect(result).toEqual(
+ expect.objectContaining({ outcome: 'scheduled-bots-canceled' }),
+ );
+ expect(
+ (await fetchCallRecording(callRecordingId)).recordingRequestStatus,
+ ).toBe('CANCELED');
+ expect(recall.deletedBotIds).not.toContain(botId);
+
+ await cancelScheduledRecallBotsHandler();
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(recall.deletedBotIds).toContain(botId);
+ });
+
+ it('stops the cancellation chain when Recall is down, leaving the bot to the daily retry', async () => {
+ const { callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+
+ turnRecordingOff();
+ await syncCalendarBotSchedulingHandler();
+
+ recall.failRecallRemovals = true;
+
+ const result = await cancelScheduledRecallBots({ client, sliceSize: 1 });
+
+ expect(result.canceledCallRecordingIds).toEqual([]);
+ expect(result.failedCallRecordingIds).toEqual([callRecordingId]);
+ expect(result.hasMore).toBe(false);
+ expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
+ botId,
+ );
+ });
+
+ it('does not schedule a bot for a request the cancellation missed', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ });
+
+ turnRecordingOff();
+
+ await runPendingRecoveryCron();
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(recall.botForCallRecording(callRecordingId)).toBeUndefined();
+ });
+
+ it('schedules nothing for an upcoming meeting while turned off', async () => {
+ turnRecordingOff();
+
+ const calendarEventId = await createCalendarEvent();
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(
+ await findCallRecordings({
+ calendarEventId: { in: [calendarEventId] },
+ }),
+ ).toEqual([]);
+ expect(recall.bots.size).toBe(0);
+ });
+
+ it('clears the Recording Bot preference of the meetings it paused', async () => {
+ const { calendarEventId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('ON');
+
+ turnRecordingOff();
+ await syncCalendarBotSchedulingHandler();
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBeNull();
+ });
+
+ it('enqueues the upcoming-events sweep when turned back on', async () => {
+ vi.stubEnv(
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME,
+ 'true',
+ );
+
+ await expect(syncCalendarBotSchedulingHandler()).resolves.toEqual({
+ outcome: 'sweep-enqueued',
+ });
+ });
});
});
diff --git a/packages/twenty-apps/public/call-recorder/src/application-config.ts b/packages/twenty-apps/public/call-recorder/src/application-config.ts
index 1f3ea2a489c..4eec5f2dcaa 100644
--- a/packages/twenty-apps/public/call-recorder/src/application-config.ts
+++ b/packages/twenty-apps/public/call-recorder/src/application-config.ts
@@ -7,6 +7,7 @@ import {
APPLICATION_UNIVERSAL_IDENTIFIER,
CALL_RECORDER_ADDITIONAL_SUMMARY_PROMPT_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
CALL_RECORDER_BOT_IMAGE_BACKGROUND_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
CALL_RECORDER_EVERYONE_LEFT_TIMEOUT_SECONDS_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
CALL_RECORDER_JOIN_EARLY_MINUTES_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
CALL_RECORDER_NAME_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
@@ -19,6 +20,7 @@ import {
CALL_RECORDER_WAITING_ROOM_TIMEOUT_SECONDS_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';
import { CALL_RECORDER_BOT_IMAGE_BACKGROUND_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-bot-image-background-env-var-name';
+import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';
import { CALL_RECORDER_EVERYONE_LEFT_TIMEOUT_SECONDS } from 'src/logic-functions/constants/call-recorder-everyone-left-timeout-seconds';
import { CALL_RECORDER_EVERYONE_LEFT_TIMEOUT_SECONDS_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-everyone-left-timeout-seconds-env-var-name';
import { CALL_RECORDER_JOIN_EARLY_MINUTES_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-join-early-minutes-env-var-name';
@@ -36,6 +38,7 @@ import { CALL_RECORDER_USE_WORKSPACE_LOGO_ENV_VAR_NAME } from 'src/logic-functio
import { CALL_RECORDER_WAITING_ROOM_TIMEOUT_SECONDS } from 'src/logic-functions/constants/call-recorder-waiting-room-timeout-seconds';
import { CALL_RECORDER_WAITING_ROOM_TIMEOUT_SECONDS_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-waiting-room-timeout-seconds-env-var-name';
import { DEFAULT_CALL_RECORDER_BOT_IMAGE_BACKGROUND } from 'src/logic-functions/constants/default-call-recorder-bot-image-background';
+import { DEFAULT_CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED } from 'src/logic-functions/constants/default-call-recorder-calendar-bot-scheduling-enabled';
import { DEFAULT_CALL_RECORDER_JOIN_EARLY_MINUTES } from 'src/logic-functions/constants/default-call-recorder-join-early-minutes';
import { DEFAULT_CALL_RECORDER_NAME } from 'src/logic-functions/constants/default-call-recorder-name';
import { DEFAULT_CALL_RECORDER_RECORDING_NOTICE_ENABLED } from 'src/logic-functions/constants/default-call-recorder-recording-notice-enabled';
@@ -58,6 +61,16 @@ export default defineApplication({
author: 'Twenty',
galleryImages: ['public/gallery/call-recorder-cover.png'],
applicationVariables: {
+ [CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME]: {
+ universalIdentifier:
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
+ label: 'Record my calendar meetings',
+ description:
+ 'Whether the recorder is scheduled for every upcoming calendar meeting with a supported video link. Set to false to stop scheduling bots and cancel the ones already scheduled.',
+ isSecret: false,
+ type: FieldType.BOOLEAN,
+ value: DEFAULT_CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED,
+ },
[CALL_RECORDER_NAME_ENV_VAR_NAME]: {
universalIdentifier: CALL_RECORDER_NAME_APP_VARIABLE_UNIVERSAL_IDENTIFIER,
label: 'Recorder name',
diff --git a/packages/twenty-apps/public/call-recorder/src/constants/sync-calendar-bot-scheduling-route-path.ts b/packages/twenty-apps/public/call-recorder/src/constants/sync-calendar-bot-scheduling-route-path.ts
new file mode 100644
index 00000000000..1c06866f2ad
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/constants/sync-calendar-bot-scheduling-route-path.ts
@@ -0,0 +1,2 @@
+export const SYNC_CALENDAR_BOT_SCHEDULING_ROUTE_PATH =
+ '/call-recorder/sync-calendar-bot-scheduling';
diff --git a/packages/twenty-apps/public/call-recorder/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/call-recorder/src/constants/universal-identifiers.ts
index 05447fa0ccd..437e36ae4c6 100644
--- a/packages/twenty-apps/public/call-recorder/src/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/call-recorder/src/constants/universal-identifiers.ts
@@ -16,6 +16,9 @@ export const CALL_RECORDER_ADDITIONAL_SUMMARY_PROMPT_APP_VARIABLE_UNIVERSAL_IDEN
export const CALL_RECORDER_BOT_IMAGE_BACKGROUND_APP_VARIABLE_UNIVERSAL_IDENTIFIER =
'fd0d9495-29ae-443e-84f9-4ec4d1f2d16a';
+export const CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_APP_VARIABLE_UNIVERSAL_IDENTIFIER =
+ 'e1cf956b-356f-468d-b5d9-044ed5fd9e5b';
+
export const CALL_RECORDER_EVERYONE_LEFT_TIMEOUT_SECONDS_APP_VARIABLE_UNIVERSAL_IDENTIFIER =
'c866ddd4-fb7b-4cb4-8ad1-5599755e495c';
@@ -67,6 +70,9 @@ export const CALL_RECORDING_TRANSCRIPT_IMPORT_CLAIMED_AT_FIELD_UNIVERSAL_IDENTIF
export const CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER =
'bb9523d3-457e-4f4b-8c79-27a77afb87da';
+export const CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ 'a1b0f097-edeb-45a3-a53e-bf666cbfe3a4';
+
export const CANCEL_RECALL_BOT_ON_CALL_RECORDING_DELETE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'84981386-881f-4123-a2dd-82e0932ba663';
@@ -120,3 +126,6 @@ export const SUMMARIZE_CALL_RECORDING_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
export const SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'05ab984e-c6ad-4b1c-800f-8f029dc7aac8';
+
+export const SYNC_CALENDAR_BOT_SCHEDULING_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ '1ec45adf-8521-4a53-833f-3b9bc20f0e9d';
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx
index 74cb2daeb98..244cff7e731 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx
@@ -1,6 +1,7 @@
import 'twenty-ui/style.css';
import styled from '@emotion/styled';
+import { useState } from 'react';
import {
useColorScheme,
useFrontComponentId,
@@ -14,7 +15,10 @@ import {
import { InCallSection } from 'src/front-components/components/InCallSection';
import { RecorderSection } from 'src/front-components/components/RecorderSection';
+import { SchedulingSection } from 'src/front-components/components/SchedulingSection';
import { TranscriptionSection } from 'src/front-components/components/TranscriptionSection';
+import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW } from 'src/front-components/constants/call-recorder-settings-layout.constant';
+import { getApplicationVariableValue } from 'src/front-components/utils/get-application-variable-value.util';
const StyledContainer = styled.div`
box-sizing: border-box;
@@ -24,9 +28,21 @@ const StyledContainer = styled.div`
width: 100%;
`;
+const StyledPausedNotice = styled.div`
+ color: ${() => themeCssVariables.font.color.tertiary};
+ font-size: ${() => themeCssVariables.font.size.md};
+ line-height: ${() => themeCssVariables.text.lineHeight.md};
+`;
+
export const CallRecorderSettings = () => {
const colorScheme = useColorScheme();
const frontComponentId = useFrontComponentId();
+ const [isSchedulingEnabled, setIsSchedulingEnabled] = useState(
+ () =>
+ getApplicationVariableValue(
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW.variableKey,
+ ) !== 'false',
+ );
// twenty-ui components read icon sizes off ThemeContext, and the context
// default resolves them to var() strings an SVG size attribute cannot use —
@@ -41,9 +57,23 @@ export const CallRecorderSettings = () => {
}}
>
<StyledContainer>
- <RecorderSection frontComponentId={frontComponentId} />
- <InCallSection frontComponentId={frontComponentId} />
- <TranscriptionSection frontComponentId={frontComponentId} />
+ <SchedulingSection
+ frontComponentId={frontComponentId}
+ isEnabled={isSchedulingEnabled}
+ onEnabledChange={setIsSchedulingEnabled}
+ />
+ {isSchedulingEnabled ? (
+ <>
+ <RecorderSection frontComponentId={frontComponentId} />
+ <InCallSection frontComponentId={frontComponentId} />
+ <TranscriptionSection frontComponentId={frontComponentId} />
+ </>
+ ) : (
+ <StyledPausedNotice>
+ Recording is paused. Turn it back on to schedule recorders and edit
+ how they behave. Your settings are kept.
+ </StyledPausedNotice>
+ )}
</StyledContainer>
</ThemeContext.Provider>
);
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/SchedulingSection.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/SchedulingSection.tsx
new file mode 100644
index 00000000000..1c479406f4c
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/SchedulingSection.tsx
@@ -0,0 +1,45 @@
+import { Section } from 'twenty-ui/layout';
+
+import { SettingsOptionCardContentToggle } from 'src/front-components/components/SettingsOptionCardContentToggle';
+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';
+import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW } from 'src/front-components/constants/call-recorder-settings-layout.constant';
+import { useAutosaveApplicationVariable } from 'src/front-components/hooks/use-autosave-application-variable';
+import { requestCalendarBotSchedulingSync } from 'src/front-components/utils/request-calendar-bot-scheduling-sync.util';
+
+type SchedulingSectionProps = {
+ frontComponentId: string;
+ isEnabled: boolean;
+ onEnabledChange: (isEnabled: boolean) => void;
+};
+
+export const SchedulingSection = ({
+ frontComponentId,
+ isEnabled,
+ onEnabledChange,
+}: SchedulingSectionProps) => {
+ const { saveImmediately } = useAutosaveApplicationVariable({
+ frontComponentId,
+ variableKey: CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW.variableKey,
+ onSaveSuccess: () => requestCalendarBotSchedulingSync(),
+ onSaveError: (value) => onEnabledChange(value !== 'true'),
+ });
+
+ const handleChange = (checked: boolean) => {
+ onEnabledChange(checked);
+ saveImmediately(checked ? 'true' : 'false');
+ };
+
+ return (
+ <Section>
+ <StyledSettingsCard>
+ <SettingsOptionCardContentToggle
+ Icon={CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW.Icon}
+ title={CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW.title}
+ description={CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW.description}
+ checked={isEnabled}
+ onChange={handleChange}
+ />
+ </StyledSettingsCard>
+ </Section>
+ );
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/constants/call-recorder-settings-layout.constant.ts b/packages/twenty-apps/public/call-recorder/src/front-components/constants/call-recorder-settings-layout.constant.ts
index bb03fe148df..6f8c69e3cc2 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/constants/call-recorder-settings-layout.constant.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/constants/call-recorder-settings-layout.constant.ts
@@ -1,4 +1,5 @@
import {
+ IconCalendarEvent,
IconClockPlay,
IconColorSwatch,
IconDoorEnter,
@@ -13,6 +14,7 @@ import {
import { CALL_RECORDER_ADDITIONAL_SUMMARY_PROMPT_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-additional-summary-prompt-env-var-name';
import { CALL_RECORDER_BOT_IMAGE_BACKGROUND_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-bot-image-background-env-var-name';
+import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';
import { CALL_RECORDER_EVERYONE_LEFT_TIMEOUT_SECONDS_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-everyone-left-timeout-seconds-env-var-name';
import { CALL_RECORDER_JOIN_EARLY_MINUTES_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-join-early-minutes-env-var-name';
import { CALL_RECORDER_NAME_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-name-env-var-name';
@@ -32,6 +34,13 @@ export type CallRecorderCounterRow = {
Icon: IconComponent;
};
+export const CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW = {
+ variableKey: CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME,
+ title: 'Record my calendar meetings',
+ description: 'Joins every meeting with a supported video link.',
+ Icon: IconCalendarEvent,
+};
+
export const CALL_RECORDER_RECORDING_NOTICE_ROW = {
variableKey: CALL_RECORDER_RECORDING_NOTICE_ENABLED_ENV_VAR_NAME,
title: 'Send recording notice',
@@ -117,6 +126,7 @@ export const CALL_RECORDER_SUMMARY_PROMPT_FIELD = {
// Keep this list aligned with the app config so every application variable is
// intentionally placed in the synchronous settings UI.
export const CALL_RECORDER_MAPPED_VARIABLE_KEYS: string[] = [
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW.variableKey,
CALL_RECORDER_NAME_FIELD.variableKey,
CALL_RECORDER_RECORDING_NOTICE_ROW.variableKey,
CALL_RECORDER_RECORDING_NOTICE_MESSAGE_FIELD.variableKey,
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts
index 571c50e2bc7..f8b341d89af 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts
@@ -9,22 +9,26 @@ import { createApplicationVariableSaveQueue } from 'src/front-components/utils/c
type UseAutosaveApplicationVariableParams = {
frontComponentId: string;
variableKey: string;
- onSaveSuccess?: (value: string) => void;
+ onSaveSuccess?: (value: string) => void | Promise<void>;
+ onSaveError?: (value: string) => void;
};
export const useAutosaveApplicationVariable = ({
frontComponentId,
variableKey,
onSaveSuccess,
+ onSaveError,
}: UseAutosaveApplicationVariableParams) => {
const { saveApplicationVariable } =
useSaveApplicationVariable(frontComponentId);
const saveApplicationVariableRef = useRef(saveApplicationVariable);
const onSaveSuccessRef = useRef(onSaveSuccess);
+ const onSaveErrorRef = useRef(onSaveError);
const variableKeyRef = useRef(variableKey);
saveApplicationVariableRef.current = saveApplicationVariable;
onSaveSuccessRef.current = onSaveSuccess;
+ onSaveErrorRef.current = onSaveError;
variableKeyRef.current = variableKey;
const saveQueueRef = useRef<
@@ -33,15 +37,23 @@ export const useAutosaveApplicationVariable = ({
if (isUndefined(saveQueueRef.current)) {
saveQueueRef.current = createApplicationVariableSaveQueue({
- saveValue: async (value) => {
+ saveValue: async (value, isSupersededValue) => {
const isSaved = await saveApplicationVariableRef.current({
variableKey: variableKeyRef.current,
value,
});
if (isSaved) {
- onSaveSuccessRef.current?.(value);
+ await onSaveSuccessRef.current?.(value);
+
+ return;
+ }
+
+ if (isSupersededValue()) {
+ return;
}
+
+ onSaveErrorRef.current?.(value);
},
});
}
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/create-application-variable-save-queue.test.ts b/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/create-application-variable-save-queue.test.ts
index ccdf46bf319..3031406c3f8 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/create-application-variable-save-queue.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/create-application-variable-save-queue.test.ts
@@ -16,7 +16,7 @@ describe('createApplicationVariableSaveQueue', () => {
const firstSave = createDeferredPromise();
const latestSave = createDeferredPromise();
const saveValue = vi
- .fn<(value: string) => Promise<void>>()
+ .fn<(value: string, isSupersededValue: () => boolean) => Promise<void>>()
.mockReturnValueOnce(firstSave.promise)
.mockReturnValueOnce(latestSave.promise);
const { enqueueSave } = createApplicationVariableSaveQueue({ saveValue });
@@ -26,16 +26,45 @@ describe('createApplicationVariableSaveQueue', () => {
enqueueSave('latest');
expect(saveValue).toHaveBeenCalledTimes(1);
- expect(saveValue).toHaveBeenNthCalledWith(1, 'first');
+ expect(saveValue).toHaveBeenNthCalledWith(1, 'first', expect.any(Function));
firstSave.resolvePromise();
await firstSave.promise;
await Promise.resolve();
expect(saveValue).toHaveBeenCalledTimes(2);
- expect(saveValue).toHaveBeenNthCalledWith(2, 'latest');
+ expect(saveValue).toHaveBeenNthCalledWith(
+ 2,
+ 'latest',
+ expect.any(Function),
+ );
latestSave.resolvePromise();
await latestSave.promise;
});
+
+ it('reports a value as superseded only while a newer one is queued', async () => {
+ const firstSave = createDeferredPromise();
+ const supersededByValue: Record<string, boolean> = {};
+ const saveValue = vi
+ .fn<(value: string, isSupersededValue: () => boolean) => Promise<void>>()
+ .mockImplementation(async (value, isSupersededValue) => {
+ if (value === 'first') {
+ await firstSave.promise;
+ }
+
+ supersededByValue[value] = isSupersededValue();
+ });
+ const { enqueueSave } = createApplicationVariableSaveQueue({ saveValue });
+
+ enqueueSave('first');
+ enqueueSave('latest');
+
+ firstSave.resolvePromise();
+ await firstSave.promise;
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(supersededByValue).toEqual({ first: true, latest: false });
+ });
});
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/utils/create-application-variable-save-queue.util.ts b/packages/twenty-apps/public/call-recorder/src/front-components/utils/create-application-variable-save-queue.util.ts
index 8918ce49af1..ee8591cb5c5 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/utils/create-application-variable-save-queue.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/utils/create-application-variable-save-queue.util.ts
@@ -1,7 +1,10 @@
import { isUndefined } from '@sniptt/guards';
type CreateApplicationVariableSaveQueueParams = {
- saveValue: (value: string) => Promise<void>;
+ saveValue: (
+ value: string,
+ isSupersededValue: () => boolean,
+ ) => Promise<void>;
};
export const createApplicationVariableSaveQueue = ({
@@ -23,7 +26,7 @@ export const createApplicationVariableSaveQueue = ({
queuedValue = undefined;
- await saveValue(valueToSave);
+ await saveValue(valueToSave, () => !isUndefined(queuedValue));
}
} finally {
isSaving = false;
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/utils/request-calendar-bot-scheduling-sync.util.ts b/packages/twenty-apps/public/call-recorder/src/front-components/utils/request-calendar-bot-scheduling-sync.util.ts
new file mode 100644
index 00000000000..37e76410fc9
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/utils/request-calendar-bot-scheduling-sync.util.ts
@@ -0,0 +1,51 @@
+import { isUndefined } from '@sniptt/guards';
+import { RestApiClient } from 'twenty-client-sdk/rest';
+import { enqueueSnackbar } from 'twenty-sdk/front-component';
+
+import { SYNC_CALENDAR_BOT_SCHEDULING_ROUTE_PATH } from 'src/constants/sync-calendar-bot-scheduling-route-path';
+
+type SyncCalendarBotSchedulingResponse = {
+ outcome?: string;
+ canceledCallRecordingCount?: number;
+};
+
+const buildSnackbarForResponse = (
+ response: SyncCalendarBotSchedulingResponse,
+): { message: string; variant: 'success' | 'error' } | undefined => {
+ if (response.outcome === 'sweep-enqueued') {
+ return undefined;
+ }
+
+ const canceledCount = response.canceledCallRecordingCount ?? 0;
+
+ if (canceledCount === 0) {
+ return undefined;
+ }
+
+ return {
+ message: `Canceled ${canceledCount} scheduled recording${canceledCount === 1 ? '' : 's'}.`,
+ variant: 'success',
+ };
+};
+
+export const requestCalendarBotSchedulingSync = async (): Promise<void> => {
+ try {
+ const response =
+ await new RestApiClient().post<SyncCalendarBotSchedulingResponse>(
+ `/s${SYNC_CALENDAR_BOT_SCHEDULING_ROUTE_PATH}`,
+ {},
+ );
+
+ const snackbar = buildSnackbarForResponse(response ?? {});
+
+ if (!isUndefined(snackbar)) {
+ await enqueueSnackbar(snackbar);
+ }
+ } catch {
+ await enqueueSnackbar({
+ message:
+ 'Setting saved, but scheduled recordings could not be updated yet.',
+ variant: 'error',
+ });
+ }
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/cancel-scheduled-recall-bots.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/cancel-scheduled-recall-bots.ts
new file mode 100644
index 00000000000..8bdfce2df52
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/cancel-scheduled-recall-bots.ts
@@ -0,0 +1,44 @@
+import { CoreApiClient } from 'twenty-client-sdk/core';
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import { CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';
+import {
+ cancelScheduledRecallBots,
+ type CancelScheduledRecallBotsResult,
+} from 'src/logic-functions/flows/cancel-scheduled-recall-bots.util';
+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
+
+export const cancelScheduledRecallBotsHandler =
+ async (): Promise<CancelScheduledRecallBotsResult> => {
+ try {
+ const result = await cancelScheduledRecallBots({
+ client: new CoreApiClient(),
+ });
+
+ if (result.hasMore) {
+ await enqueueLogicFunctionJobs({
+ logicFunctionUniversalIdentifier:
+ CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ payloads: [{}],
+ });
+ }
+
+ return result;
+ } catch (error) {
+ throw buildRetryableStepFailure(
+ 'scheduled Recall bot cancellation',
+ error,
+ );
+ }
+ };
+
+export default defineLogicFunction({
+ universalIdentifier:
+ CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'cancel-scheduled-recall-bots',
+ description:
+ 'Deletes the Recall bots of canceled recording requests in bounded slices, re-enqueueing itself while more remain. The daily cancellation retry stays the backstop.',
+ timeoutSeconds: 900,
+ handler: cancelScheduledRecallBotsHandler,
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name.ts
new file mode 100644
index 00000000000..5fd8a25191c
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name.ts
@@ -0,0 +1,2 @@
+export const CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME =
+ 'CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED';
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/default-call-recorder-calendar-bot-scheduling-enabled.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/default-call-recorder-calendar-bot-scheduling-enabled.ts
new file mode 100644
index 00000000000..d0820384c7f
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/default-call-recorder-calendar-bot-scheduling-enabled.ts
@@ -0,0 +1 @@
+export const DEFAULT_CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED = true;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/scheduled-recall-bot-cancellation.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/scheduled-recall-bot-cancellation.ts
new file mode 100644
index 00000000000..30a6acae279
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/scheduled-recall-bot-cancellation.ts
@@ -0,0 +1,3 @@
+export const SCHEDULED_RECALL_BOT_CANCELLATION_CONCURRENCY = 5;
+
+export const SCHEDULED_RECALL_BOT_CANCELLATION_SLICE_SIZE = 200;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/clear-calendar-events-recording-on.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/clear-calendar-events-recording-on.util.ts
new file mode 100644
index 00000000000..709ceb260c7
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/clear-calendar-events-recording-on.util.ts
@@ -0,0 +1,55 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecorderPreference } from 'src/constants/call-recorder-preference';
+import { CALENDAR_EVENT_UPDATE_BATCH_SIZE } from 'src/logic-functions/constants/calendar-event-update-batch-size';
+import { getBatches } from 'src/logic-functions/utils/get-batches.util';
+import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
+
+export const clearCalendarEventsRecordingOn = async (
+ client: CoreApiClient,
+ calendarEventIds: string[],
+): Promise<number> => {
+ const calendarEventIdBatches = getBatches(
+ getUniqueSortedIds(calendarEventIds),
+ CALENDAR_EVENT_UPDATE_BATCH_SIZE,
+ );
+ let clearedCalendarEventCount = 0;
+ const batchErrors: unknown[] = [];
+
+ for (const calendarEventIdBatch of calendarEventIdBatches) {
+ try {
+ const updateCalendarEventsResult = await client.mutation({
+ updateCalendarEvents: {
+ __args: {
+ filter: {
+ id: { in: calendarEventIdBatch },
+ callRecorderPreference: { eq: CallRecorderPreference.ON },
+ },
+ data: {
+ callRecorderPreference: null,
+ },
+ },
+ id: true,
+ },
+ });
+
+ clearedCalendarEventCount += (
+ updateCalendarEventsResult.updateCalendarEvents ?? []
+ ).length;
+ } catch (error) {
+ batchErrors.push(error);
+ }
+ }
+
+ if (batchErrors.length > 0) {
+ throw new Error(
+ `${batchErrors.length} of ${calendarEventIdBatches.length} calendar event preference batches failed: ${batchErrors
+ .map((batchError) =>
+ batchError instanceof Error ? batchError.message : String(batchError),
+ )
+ .join('; ')}`,
+ );
+ }
+
+ return clearedCalendarEventCount;
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-canceled-call-recordings-with-bot.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-canceled-call-recordings-with-bot.util.ts
new file mode 100644
index 00000000000..aaaceb7c40b
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-canceled-call-recordings-with-bot.util.ts
@@ -0,0 +1,27 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
+import { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';
+import { TWENTY_PAGE_SIZE } from 'src/logic-functions/constants/twenty-page-size';
+import { findCallRecordingsByFilter } from 'src/logic-functions/data/find-call-recordings-by-filter.util';
+import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';
+
+export const findCanceledCallRecordingsWithBot = async (
+ client: CoreApiClient,
+ limit: number,
+): Promise<CallRecordingRecord[]> => {
+ const maximumPageCount = Math.ceil(limit / TWENTY_PAGE_SIZE);
+ let startedPageCount = 0;
+
+ const canceledCallRecordings = await findCallRecordingsByFilter(
+ client,
+ {
+ recordingRequestStatus: { eq: CallRecordingRequestStatus.CANCELED },
+ status: { in: NON_TERMINAL_CALL_RECORDING_STATUSES },
+ externalBotId: { is: 'NOT_NULL' },
+ },
+ () => startedPageCount++ < maximumPageCount,
+ );
+
+ return canceledCallRecordings.slice(0, limit);
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-call-recorder-policy-result.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-call-recorder-policy-result.test.ts
index 129698e32ad..48e1563d7b4 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-call-recorder-policy-result.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-call-recorder-policy-result.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it } from 'vitest';
+import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';
import { buildCallRecorderPolicyResult } from 'src/logic-functions/domain/build-call-recorder-policy-result.util';
import { type CallRecorderPolicyCalendarEventInput } from 'src/logic-functions/types/call-recorder-policy-calendar-event-input.type';
@@ -19,6 +20,12 @@ const buildCalendarEventInput = (
});
describe('buildCallRecorderPolicyResult', () => {
+ afterEach(() => {
+ delete process.env[
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME
+ ];
+ });
+
it('requests a bot for the ON wire value', () => {
const policyResult = buildCallRecorderPolicyResult(
buildCalendarEventInput({
@@ -44,4 +51,19 @@ describe('buildCallRecorderPolicyResult', () => {
expect(policyResult.shouldRequestBot).toBe(false);
expect(policyResult.reason).toBe('PREFERENCE_OFF');
});
+
+ it('does not request a bot when the workspace turned calendar bot scheduling off', () => {
+ process.env[CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME] =
+ 'false';
+
+ const policyResult = buildCallRecorderPolicyResult(
+ buildCalendarEventInput({
+ callRecorderPreference: 'ON',
+ }),
+ NOW,
+ );
+
+ expect(policyResult.shouldRequestBot).toBe(false);
+ expect(policyResult.reason).toBe('CALENDAR_BOT_SCHEDULING_DISABLED');
+ });
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/resolve-call-recorder-policy-result.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/resolve-call-recorder-policy-result.test.ts
index 78d93886338..92dae114ffa 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/resolve-call-recorder-policy-result.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/resolve-call-recorder-policy-result.test.ts
@@ -13,10 +13,30 @@ const BEYOND_HORIZON_STARTS_AT = '2026-01-10T13:00:00.000Z';
const BEYOND_HORIZON_ENDS_AT = '2026-01-10T14:00:00.000Z';
describe('resolveCallRecorderPolicyResult', () => {
+ it('does not request a bot when calendar bot scheduling is disabled, even for an ON event', () => {
+ expect(
+ resolveCallRecorderPolicyResult({
+ input: {
+ isCalendarBotSchedulingEnabled: false,
+ callRecorderPreference: CallRecorderPreference.ON,
+ isCanceled: false,
+ startsAt: FUTURE_STARTS_AT,
+ endsAt: FUTURE_ENDS_AT,
+ conferenceLinkUrl: 'https://meet.google.com/abc-defg-hij',
+ },
+ now: NOW,
+ }),
+ ).toEqual({
+ shouldRequestBot: false,
+ reason: 'CALENDAR_BOT_SCHEDULING_DISABLED',
+ });
+ });
+
it('requires a bot when preference is ON and the event is upcoming', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: CallRecorderPreference.ON,
isCanceled: false,
startsAt: FUTURE_STARTS_AT,
@@ -35,6 +55,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: CallRecorderPreference.ON,
isCanceled: false,
startsAt: FUTURE_STARTS_AT,
@@ -53,6 +74,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: CallRecorderPreference.ON,
isCanceled: false,
startsAt: FUTURE_STARTS_AT,
@@ -71,6 +93,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: undefined,
isCanceled: false,
startsAt: FUTURE_STARTS_AT,
@@ -89,6 +112,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: CallRecorderPreference.OFF,
isCanceled: false,
startsAt: FUTURE_STARTS_AT,
@@ -107,6 +131,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: undefined,
isCanceled: false,
startsAt: PAST_STARTS_AT,
@@ -125,6 +150,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: undefined,
isCanceled: true,
startsAt: FUTURE_STARTS_AT,
@@ -143,6 +169,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: CallRecorderPreference.ON,
isCanceled: false,
startsAt: BEYOND_HORIZON_STARTS_AT,
@@ -161,6 +188,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: CallRecorderPreference.ON,
isCanceled: false,
startsAt: FUTURE_STARTS_AT,
@@ -179,6 +207,7 @@ describe('resolveCallRecorderPolicyResult', () => {
expect(
resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: true,
callRecorderPreference: CallRecorderPreference.ON,
isCanceled: false,
startsAt: '',
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/aggregate-call-recorder-policy-results-by-meeting.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/aggregate-call-recorder-policy-results-by-meeting.util.ts
index 9eac855fdf1..6e7bc778edd 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/aggregate-call-recorder-policy-results-by-meeting.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/aggregate-call-recorder-policy-results-by-meeting.util.ts
@@ -1,9 +1,13 @@
+import { CallRecorderPreference } from 'src/constants/call-recorder-preference';
import { type CallRecorderPolicyResultForCalendarEvent } from 'src/logic-functions/types/call-recorder-policy-result-for-calendar-event.type';
import { type CallRecorderPolicyResultForMeeting } from 'src/logic-functions/types/call-recorder-policy-result-for-meeting.type';
type CallRecorderPolicyResultForMeetingInput = Pick<
CallRecorderPolicyResultForCalendarEvent,
- 'calendarEventId' | 'realMeetingKey' | 'shouldRequestBot'
+ | 'calendarEventId'
+ | 'realMeetingKey'
+ | 'shouldRequestBot'
+ | 'callRecorderPreference'
>;
export const aggregateCallRecorderPolicyResultsByMeeting = (
@@ -18,6 +22,7 @@ export const aggregateCallRecorderPolicyResultsByMeeting = (
calendarEventId,
realMeetingKey,
shouldRequestBot,
+ callRecorderPreference,
} of perCalendarEventPolicyResults) {
const meetingPolicyResult = meetingPolicyResultsByMeetingKey.get(
realMeetingKey,
@@ -26,10 +31,15 @@ export const aggregateCallRecorderPolicyResultsByMeeting = (
shouldRequestBot: false,
calendarEventIds: [],
requestingCalendarEventIds: [],
+ calendarEventIdsWithRecordingOn: [],
};
meetingPolicyResult.calendarEventIds.push(calendarEventId);
+ if (callRecorderPreference === CallRecorderPreference.ON) {
+ meetingPolicyResult.calendarEventIdsWithRecordingOn.push(calendarEventId);
+ }
+
if (shouldRequestBot) {
meetingPolicyResult.shouldRequestBot = true;
meetingPolicyResult.requestingCalendarEventIds.push(calendarEventId);
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recorder-policy-result.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recorder-policy-result.util.ts
index 55b6a663d69..8c36ab3da4b 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recorder-policy-result.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recorder-policy-result.util.ts
@@ -3,6 +3,7 @@ import { type CallRecorderPolicyCalendarEventInput } from 'src/logic-functions/t
import { type CallRecorderPolicyResultForCalendarEvent } from 'src/logic-functions/types/call-recorder-policy-result-for-calendar-event.type';
import { computeRealMeetingKey } from 'src/logic-functions/domain/compute-real-meeting-key.util';
import { resolveCallRecorderPolicyResult } from 'src/logic-functions/domain/resolve-call-recorder-policy-result.util';
+import { isCalendarBotSchedulingEnabled } from 'src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util';
export const buildCallRecorderPolicyResult = (
calendarEvent: CallRecorderPolicyCalendarEventInput,
@@ -21,6 +22,7 @@ export const buildCallRecorderPolicyResult = (
const policyResult = resolveCallRecorderPolicyResult({
input: {
+ isCalendarBotSchedulingEnabled: isCalendarBotSchedulingEnabled(),
callRecorderPreference,
isCanceled: calendarEvent.isCanceled,
startsAt: calendarEvent.startsAt,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/resolve-call-recorder-policy-result.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/resolve-call-recorder-policy-result.util.ts
index 1fd4b7dca9c..0ffa7139abc 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/resolve-call-recorder-policy-result.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/resolve-call-recorder-policy-result.util.ts
@@ -18,6 +18,10 @@ export const resolveCallRecorderPolicyResult = ({
input,
now,
}: ResolveCallRecorderPolicyResultArgs): CallRecorderPolicyResult => {
+ if (!input.isCalendarBotSchedulingEnabled) {
+ return botNotRequired('CALENDAR_BOT_SCHEDULING_DISABLED');
+ }
+
if (input.isCanceled) {
return botNotRequired('EVENT_CANCELED');
}
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-recall-bot-for-canceled-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-recall-bot-for-canceled-call-recording.util.ts
new file mode 100644
index 00000000000..4fa4922114f
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-recall-bot-for-canceled-call-recording.util.ts
@@ -0,0 +1,49 @@
+import { isUndefined } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
+import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';
+import { replaceCanceledCallRecordingExternalBotId } from 'src/logic-functions/data/replace-canceled-call-recording-external-bot-id.util';
+import { cancelOrEjectRecallBot } from 'src/logic-functions/recall-api/cancel-or-eject-recall-bot.util';
+
+export type CancelRecallBotForCanceledCallRecordingOutcome =
+ | 'canceled'
+ | 'skipped'
+ | 'failed';
+
+export const cancelRecallBotForCanceledCallRecording = async ({
+ client,
+ callRecordingId,
+ externalBotId,
+}: {
+ client: CoreApiClient;
+ callRecordingId: string;
+ externalBotId: string;
+}): Promise<CancelRecallBotForCanceledCallRecordingOutcome> => {
+ const latestCallRecording = (
+ await findCallRecordingsByIds(client, [callRecordingId])
+ )[0];
+
+ if (
+ latestCallRecording?.recordingRequestStatus !==
+ CallRecordingRequestStatus.CANCELED ||
+ (!isUndefined(latestCallRecording.externalBotId) &&
+ latestCallRecording.externalBotId !== externalBotId)
+ ) {
+ return 'skipped';
+ }
+
+ if (!(await cancelOrEjectRecallBot(externalBotId))) {
+ return 'failed';
+ }
+
+ if (latestCallRecording.externalBotId === externalBotId) {
+ await replaceCanceledCallRecordingExternalBotId(client, {
+ id: callRecordingId,
+ expectedExternalBotId: externalBotId,
+ nextExternalBotId: null,
+ });
+ }
+
+ return 'canceled';
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-scheduled-recall-bots.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-scheduled-recall-bots.util.ts
new file mode 100644
index 00000000000..3718b09b738
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-scheduled-recall-bots.util.ts
@@ -0,0 +1,68 @@
+import { isUndefined } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import {
+ SCHEDULED_RECALL_BOT_CANCELLATION_CONCURRENCY,
+ SCHEDULED_RECALL_BOT_CANCELLATION_SLICE_SIZE,
+} from 'src/logic-functions/constants/scheduled-recall-bot-cancellation';
+import { findCanceledCallRecordingsWithBot } from 'src/logic-functions/data/find-canceled-call-recordings-with-bot.util';
+import { cancelRecallBotForCanceledCallRecording } from 'src/logic-functions/flows/cancel-recall-bot-for-canceled-call-recording.util';
+import { getBatches } from 'src/logic-functions/utils/get-batches.util';
+
+export type CancelScheduledRecallBotsResult = {
+ canceledCallRecordingIds: string[];
+ failedCallRecordingIds: string[];
+ hasMore: boolean;
+};
+
+export const cancelScheduledRecallBots = async ({
+ client,
+ sliceSize = SCHEDULED_RECALL_BOT_CANCELLATION_SLICE_SIZE,
+}: {
+ client: CoreApiClient;
+ sliceSize?: number;
+}): Promise<CancelScheduledRecallBotsResult> => {
+ const callRecordings = await findCanceledCallRecordingsWithBot(
+ client,
+ sliceSize,
+ );
+ const canceledCallRecordingIds: string[] = [];
+ const failedCallRecordingIds: string[] = [];
+
+ for (const concurrentCallRecordings of getBatches(
+ callRecordings,
+ SCHEDULED_RECALL_BOT_CANCELLATION_CONCURRENCY,
+ )) {
+ await Promise.all(
+ concurrentCallRecordings.map(async (callRecording) => {
+ if (isUndefined(callRecording.externalBotId)) {
+ return;
+ }
+
+ const outcome = await cancelRecallBotForCanceledCallRecording({
+ client,
+ callRecordingId: callRecording.id,
+ externalBotId: callRecording.externalBotId,
+ });
+
+ if (outcome === 'canceled') {
+ canceledCallRecordingIds.push(callRecording.id);
+
+ return;
+ }
+
+ if (outcome === 'failed') {
+ failedCallRecordingIds.push(callRecording.id);
+ }
+ }),
+ );
+ }
+
+ return {
+ canceledCallRecordingIds,
+ failedCallRecordingIds,
+ hasMore:
+ callRecordings.length === sliceSize &&
+ canceledCallRecordingIds.length > 0,
+ };
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts
index 6c968787c6a..0a390451735 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts
@@ -20,6 +20,7 @@ import {
import { scheduleRecallBotForCallRecording } from 'src/logic-functions/flows/schedule-recall-bot-for-call-recording.util';
import { fetchCalendarEventsByIds } from 'src/logic-functions/data/fetch-calendar-events-by-ids.util';
import { fetchCalendarEventsByStartsAtValues } from 'src/logic-functions/data/fetch-calendar-events-by-starts-at-values.util';
+import { clearCalendarEventsRecordingOn } from 'src/logic-functions/data/clear-calendar-events-recording-on.util';
import { markCalendarEventsRecordingOn } from 'src/logic-functions/data/mark-calendar-events-recording-on.util';
import { findCallRecordingsByCalendarEventIds } from 'src/logic-functions/data/find-call-recordings-by-calendar-event-ids.util';
import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';
@@ -130,6 +131,7 @@ const resolveCallRecorderPolicyResultsForMeetings = async ({
calendarEventId: policyResult.calendarEventId,
realMeetingKey: policyResult.realMeetingKey,
shouldRequestBot: policyResult.shouldRequestBot,
+ callRecorderPreference: policyResult.callRecorderPreference,
}));
const meetingPolicyResults = aggregateCallRecorderPolicyResultsByMeeting(
perCalendarEventPolicyResults,
@@ -150,6 +152,7 @@ const resolveCallRecorderPolicyResultsForMeetings = async ({
shouldRequestBot: false,
calendarEventIds: [],
requestingCalendarEventIds: [],
+ calendarEventIdsWithRecordingOn: [],
});
}
@@ -437,19 +440,17 @@ const reconcileCanceledMeeting = async ({
...meetingPolicyResult.calendarEventIds,
...removedCalendarEventIds,
]);
- const cancellableCallRecordings = (
- await findCallRecordingsByCalendarEventIds(client, calendarEventIds)
- ).filter(
+ const meetingCallRecordings = await findCallRecordingsByCalendarEventIds(
+ client,
+ calendarEventIds,
+ );
+ const cancellableCallRecordings = meetingCallRecordings.filter(
(callRecording) =>
callRecording.status === CallRecordingStatus.SCHEDULED &&
callRecording.recordingRequestStatus ===
CallRecordingRequestStatus.REQUESTED,
);
- if (cancellableCallRecordings.length === 0) {
- return buildSkippedResult(meetingPolicyResult.realMeetingKey);
- }
-
for (const callRecording of cancellableCallRecordings) {
await cancelCallRecordingRequest({
client,
@@ -457,6 +458,22 @@ const reconcileCanceledMeeting = async ({
});
}
+ const cancellableCallRecordingIds = new Set(
+ cancellableCallRecordings.map((callRecording) => callRecording.id),
+ );
+
+ await clearRecordingOnForMeeting({
+ client,
+ meetingPolicyResult,
+ remainingCallRecordings: meetingCallRecordings.filter(
+ (callRecording) => !cancellableCallRecordingIds.has(callRecording.id),
+ ),
+ });
+
+ if (cancellableCallRecordings.length === 0) {
+ return buildSkippedResult(meetingPolicyResult.realMeetingKey);
+ }
+
return {
action: 'CANCELED',
realMeetingKey: meetingPolicyResult.realMeetingKey,
@@ -464,6 +481,42 @@ const reconcileCanceledMeeting = async ({
};
};
+const clearRecordingOnForMeeting = async ({
+ client,
+ meetingPolicyResult,
+ remainingCallRecordings,
+}: {
+ client: CoreApiClient;
+ meetingPolicyResult: CallRecorderPolicyResultForMeeting;
+ remainingCallRecordings: CallRecordingRecord[];
+}): Promise<void> => {
+ const hasCallRecordingOutsideThisCancellation = remainingCallRecordings.some(
+ (callRecording) =>
+ callRecording.recordingRequestStatus !==
+ CallRecordingRequestStatus.CANCELED,
+ );
+
+ if (
+ meetingPolicyResult.calendarEventIdsWithRecordingOn.length === 0 ||
+ hasCallRecordingOutsideThisCancellation
+ ) {
+ return;
+ }
+
+ try {
+ await clearCalendarEventsRecordingOn(
+ client,
+ meetingPolicyResult.calendarEventIdsWithRecordingOn,
+ );
+ } catch (error) {
+ console.warn(
+ `[call-recorder] failed to clear the recording preference of meeting ${meetingPolicyResult.realMeetingKey}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+};
+
// startedAt/endedAt come from the webhook; calendar writes never touch them.
const buildCalendarDrivenCallRecordingFields = (
calendarEvent: CalendarEventRecord,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts
index b3de1a8b343..2c495295ac5 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts
@@ -6,9 +6,8 @@ import { hasMeetingEnded } from 'src/logic-functions/domain/has-meeting-ended.ut
import { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';
import { fetchCalendarEventsByIds } from 'src/logic-functions/data/fetch-calendar-events-by-ids.util';
import { findCallRecordingsByFilter } from 'src/logic-functions/data/find-call-recordings-by-filter.util';
-import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';
import { replaceCanceledCallRecordingExternalBotId } from 'src/logic-functions/data/replace-canceled-call-recording-external-bot-id.util';
-import { cancelOrEjectRecallBot } from 'src/logic-functions/recall-api/cancel-or-eject-recall-bot.util';
+import { cancelRecallBotForCanceledCallRecording } from 'src/logic-functions/flows/cancel-recall-bot-for-canceled-call-recording.util';
import { findScheduledRecallBotIdsByCallRecordingId } from 'src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util';
import { type CalendarEventRecord } from 'src/logic-functions/types/calendar-event-record.type';
import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';
@@ -80,32 +79,16 @@ export const retryFailedRecallCancellations = async ({
continue;
}
- // Calendar reconciliation can reactivate the request while this job is running.
- const latestCallRecording = (
- await findCallRecordingsByIds(client, [callRecording.id])
- )[0];
-
- if (
- latestCallRecording?.recordingRequestStatus !==
- CallRecordingRequestStatus.CANCELED ||
- (!isUndefined(latestCallRecording.externalBotId) &&
- latestCallRecording.externalBotId !== externalBotId)
- ) {
- continue;
- }
+ const outcome = await cancelRecallBotForCanceledCallRecording({
+ client,
+ callRecordingId: callRecording.id,
+ externalBotId,
+ });
- if (!(await cancelOrEjectRecallBot(externalBotId))) {
+ if (outcome !== 'canceled') {
continue;
}
- if (latestCallRecording.externalBotId === externalBotId) {
- await replaceCanceledCallRecordingExternalBotId(client, {
- id: callRecording.id,
- expectedExternalBotId: externalBotId,
- nextExternalBotId: null,
- });
- }
-
canceledExternalBotCallRecordingIds.push(callRecording.id);
}
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts
index c0806d47cf6..1dd5dba8cf7 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts
@@ -9,6 +9,7 @@ import { buildRecallRoutingMetadata } from 'src/logic-functions/domain/build-rec
import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';
import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';
import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';
+import { isCalendarBotSchedulingEnabled } from 'src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util';
import {
computeRecallBotCreationIdempotencyKey,
scheduleRecallBot,
@@ -27,6 +28,10 @@ export const scheduleRecallBotForCallRecording = async (
return false;
}
+ if (!isCalendarBotSchedulingEnabled()) {
+ return false;
+ }
+
const joinAt = computeRecallBotJoinAt(meetingStartsAt);
const freshCallRecording = (
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/sync-calendar-bot-scheduling.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/sync-calendar-bot-scheduling.ts
new file mode 100644
index 00000000000..5e30d26dac0
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/sync-calendar-bot-scheduling.ts
@@ -0,0 +1,72 @@
+import { CoreApiClient } from 'twenty-client-sdk/core';
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import {
+ CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ SYNC_CALENDAR_BOT_SCHEDULING_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
+import { SYNC_CALENDAR_BOT_SCHEDULING_ROUTE_PATH } from 'src/constants/sync-calendar-bot-scheduling-route-path';
+import { cancelOpenScheduledCallRecordingRequests } from 'src/logic-functions/data/cancel-open-scheduled-call-recording-requests.util';
+import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';
+import { findOpenScheduledCallRecordings } from 'src/logic-functions/data/find-open-scheduled-call-recordings.util';
+import { isCalendarBotSchedulingEnabled } from 'src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util';
+
+export type SyncCalendarBotSchedulingResult =
+ | { outcome: 'sweep-enqueued' }
+ | {
+ outcome: 'scheduled-bots-canceled';
+ canceledCallRecordingCount: number;
+ };
+
+export const syncCalendarBotSchedulingHandler =
+ async (): Promise<SyncCalendarBotSchedulingResult> => {
+ if (isCalendarBotSchedulingEnabled()) {
+ await enqueueLogicFunctionJobs({
+ logicFunctionUniversalIdentifier:
+ SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ payloads: [{}],
+ });
+
+ return { outcome: 'sweep-enqueued' };
+ }
+
+ const client = new CoreApiClient();
+ const openCallRecordings = await findOpenScheduledCallRecordings(client);
+
+ const canceledCallRecordingCount =
+ await cancelOpenScheduledCallRecordingRequests(
+ client,
+ openCallRecordings.map((callRecording) => callRecording.id),
+ () => true,
+ );
+
+ await enqueueLogicFunctionJobs({
+ logicFunctionUniversalIdentifier:
+ CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ payloads: [{}],
+ });
+
+ await enqueueLogicFunctionJobs({
+ logicFunctionUniversalIdentifier:
+ SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ payloads: [{}],
+ });
+
+ return { outcome: 'scheduled-bots-canceled', canceledCallRecordingCount };
+ };
+
+export default defineLogicFunction({
+ universalIdentifier:
+ SYNC_CALENDAR_BOT_SCHEDULING_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'sync-calendar-bot-scheduling',
+ description:
+ 'Applies the calendar bot scheduling setting: cancels every open recording request and enqueues Recall bot cleanup when it is off, then sweeps upcoming meetings either way.',
+ timeoutSeconds: 900,
+ handler: syncCalendarBotSchedulingHandler,
+ httpRouteTriggerSettings: {
+ path: SYNC_CALENDAR_BOT_SCHEDULING_ROUTE_PATH,
+ httpMethod: 'POST',
+ isAuthRequired: true,
+ },
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-input.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-input.type.ts
index e81c29612bb..ae1773400e2 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-input.type.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-input.type.ts
@@ -1,6 +1,7 @@
import { type CallRecorderPreference } from 'src/constants/call-recorder-preference';
export type CallRecorderPolicyInput = {
+ isCalendarBotSchedulingEnabled: boolean;
callRecorderPreference: CallRecorderPreference | undefined;
isCanceled: boolean;
startsAt: string | undefined;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-not-required-reason.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-not-required-reason.type.ts
index 52c24f75f04..9f0e01b4d0f 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-not-required-reason.type.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-not-required-reason.type.ts
@@ -1,4 +1,5 @@
export type CallRecorderPolicyNotRequiredReason =
+ | 'CALENDAR_BOT_SCHEDULING_DISABLED'
| 'EVENT_CANCELED'
| 'PREFERENCE_OFF'
| 'MISSING_CONFERENCE_LINK'
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-result-for-meeting.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-result-for-meeting.type.ts
index d3e37eda638..ed9bb1895dd 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-result-for-meeting.type.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-policy-result-for-meeting.type.ts
@@ -3,4 +3,5 @@ export type CallRecorderPolicyResultForMeeting = {
shouldRequestBot: boolean;
calendarEventIds: string[];
requestingCalendarEventIds: string[];
+ calendarEventIdsWithRecordingOn: string[];
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util.ts
new file mode 100644
index 00000000000..5b2c62285ad
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util.ts
@@ -0,0 +1,10 @@
+import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';
+import { DEFAULT_CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED } from 'src/logic-functions/constants/default-call-recorder-calendar-bot-scheduling-enabled';
+import { getBooleanApplicationVariableValue } from 'src/logic-functions/utils/get-boolean-application-variable-value.util';
+
+export const isCalendarBotSchedulingEnabled = (): boolean =>
+ getBooleanApplicationVariableValue({
+ applicationVariableName:
+ CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME,
+ defaultValue: DEFAULT_CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED,
+ });