Skip to content

The open alternative to Salesforce, designed for AI.

Call recorder: replace the nightly pending-request cron with per-request follow-ups (#26917)

nitin921eac4c79b3
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 6bee7644cd0..bdabbd194ef 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
@@ -3,7 +3,7 @@ import { randomUUID } from 'crypto';
import { isNull, isUndefined } from '@sniptt/guards';
import { CoreApiClient } from 'twenty-client-sdk/core';
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
-import { getJobs } from 'twenty-sdk/logic-function';
+import { enqueueJobs, getJobs } from 'twenty-sdk/logic-function';
import { isDefined } from 'twenty-sdk/utils';
import {
afterEach,
@@ -17,13 +17,25 @@ import {
import {
APPLICATION_UNIVERSAL_IDENTIFIER,
+ CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ PENDING_CALL_RECORDING_REQUESTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';
import { CallRecorderPreference } from 'src/constants/call-recorder-preference';
+import { followUpCallRecordingRequestHandler } from 'src/logic-functions/follow-up-call-recording-request';
+import { processPendingCallRecordingRequestsHandler } from 'src/logic-functions/process-pending-call-recording-requests';
import { reconcileStaleBotStateHandler } from 'src/logic-functions/reconcile-stale-bot-state';
+import { startPostInstallBackfillsHandler } from 'src/logic-functions/start-post-install-backfills';
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 { CALL_RECORDING_REQUEST_FOLLOW_UP_DELAY_MS } from 'src/logic-functions/constants/call-recording-request-follow-up-delay-ms';
+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { updatePendingCallRecording } from 'src/logic-functions/data/update-pending-call-recording.util';
import { getBatches } from 'src/logic-functions/utils/get-batches.util';
import { markCalendarEventsRecordingOn } from 'src/logic-functions/data/mark-calendar-events-recording-on.util';
import { cancelCallRecordingRequest } from 'src/logic-functions/flows/cancel-call-recording-request.util';
@@ -35,30 +47,18 @@ import { handlePreJoinCreditCheckJob } from 'src/logic-functions/flows/handle-pr
import { enqueuePreJoinCreditCheck } from 'src/logic-functions/data/enqueue-pre-join-credit-check.util';
import { PRE_JOIN_CREDIT_CHECK_LEAD_MINUTES } from 'src/logic-functions/constants/pre-join-credit-check-lead-minutes';
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';
-// Call Recorder end-to-end behavior against a live Twenty server.
-//
-// The app is installed on the test server by the vitest global setup, and all
-// reads and writes go through the real API into the test database. Lifecycle
-// scenarios control delivery order with fakes for:
-// - the Recall API (a fetch interceptor that replays the same bot for a
-// repeated Idempotency-Key, like the real API),
-// - the trigger transports: webhook deliveries invoke the webhook logic
-// function handler directly, and cron / database-event triggers invoke
-// the flows they dispatch, including queued artifact imports.
-//
-// Queue scenarios bypass those fakes and use the installed app's real worker.
-//
-// The suite issues a few hundred API requests; if the test server runs with
-// the default API_RATE_LIMITING_LONG_LIMIT of 100 requests per minute,
-// raise it (e.g. to 100000) or the runs trip the limiter.
+// Lifecycle tests use the real Twenty API/database with simulated Recall responses
+// and trigger delivery. runArmedFollowUps advances time and invokes handlers directly;
+// it does not prove queue timing or deduplication. The real-worker cases remove
+// fetch interception and exercise the installed app's queue and worker.
+// Test-server API limits are raised for fixture throughput; throttling behavior
+// is verified separately with synthetic responses in fetch-with-rate-limit-retry.test.ts.
const WORKSPACE_API_KEY_ENV = 'TWENTY_API_KEY';
const RECALL_BASE_URL = 'https://us-west-2.recall.ai/api/v1';
@@ -263,6 +263,13 @@ type FakeRecallBot = {
recordings?: Array<{ id: string; started_at: string; completed_at: string }>;
};
+type ArmedFollowUp = {
+ jobId: string;
+ payload: { callRecordingId: string; attempt: number };
+ delayMs: number;
+ dueAt: number;
+};
+
type FakeRecallTranscript = {
id: string;
statusCode: string;
@@ -324,6 +331,10 @@ class FakeRecallApi {
artifactImportRequests: object[] = [];
activeArtifactJobIds = new Set<string>();
recoveryRequests: object[] = [];
+ stuckRequestSweepRequests: object[] = [];
+ calendarEventSweepRequests: object[] = [];
+ followUps: ArmedFollowUp[] = [];
+ cancellationCleanupRequests: object[] = [];
creditCheckRequests: object[] = [];
// Undefined lets the credit verdict fall through to the real server.
creditAvailability:
@@ -331,7 +342,10 @@ class FakeRecallApi {
| { hasAvailableCredits: false; reason: string }
| undefined = undefined;
hasExpiredMedia = false;
+ failBotCreation = false;
failNextDelete = false;
+ failFollowUpEnqueue = false;
+ failCancellationCleanupEnqueue = false;
failCalendarEventUpdates = false;
failCallRecordingReads = false;
failRecallRemovals = false;
@@ -459,22 +473,53 @@ class FakeRecallApi {
logicFunctionUniversalIdentifier: string;
payloads: object[];
jobs?: { jobId: string; payload: object }[];
+ delayMs?: number;
}[];
const payloads =
input?.jobs?.map(({ payload }) => payload) ?? input?.payloads ?? [];
- if (
- input?.logicFunctionUniversalIdentifier ===
- STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER
- ) {
- this.recoveryRequests.push(...payloads);
- } else if (
- input?.logicFunctionUniversalIdentifier ===
- CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER
- ) {
- this.creditCheckRequests.push(...payloads);
- } else {
- this.artifactImportRequests.push(...payloads);
+ switch (input?.logicFunctionUniversalIdentifier) {
+ case STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER:
+ this.recoveryRequests.push(...payloads);
+ break;
+ case PENDING_CALL_RECORDING_REQUESTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER:
+ this.stuckRequestSweepRequests.push(...payloads);
+ break;
+ case SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER:
+ this.calendarEventSweepRequests.push(...payloads);
+ break;
+ case FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER: {
+ if (this.failFollowUpEnqueue) {
+ return jsonResponse(503, {});
+ }
+
+ const delayMs = input.delayMs ?? 0;
+ this.followUps.push(
+ ...(input.jobs ?? []).map(({ jobId, payload }) => ({
+ jobId,
+ payload: payload as ArmedFollowUp['payload'],
+ delayMs,
+ dueAt: Date.now() + delayMs,
+ })),
+ );
+ break;
+ }
+ case CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER:
+ this.creditCheckRequests.push(...payloads);
+ break;
+ case CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER:
+ if (this.failCancellationCleanupEnqueue) {
+ return jsonResponse(503, {});
+ }
+ this.cancellationCleanupRequests.push(...payloads);
+ break;
+ case IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER:
+ this.artifactImportRequests.push(...payloads);
+ break;
+ default:
+ throw new Error(
+ `Unexpected queued logic function: ${input?.logicFunctionUniversalIdentifier}`,
+ );
}
return jsonResponse(200, {
@@ -695,6 +740,10 @@ class FakeRecallApi {
}
private createBot(requestInit: any): Response {
+ if (this.failBotCreation) {
+ return jsonResponse(503, {});
+ }
+
const idempotencyKey: string | undefined =
requestInit?.headers?.['Idempotency-Key'];
const alreadyCreatedBotId =
@@ -837,6 +886,7 @@ describe('call recorder app lifecycle (integration)', () => {
beforeEach(() => {
recall = new FakeRecallApi();
nextArtifactImportRequestIndex = 0;
+ nextFollowUpIndex = 0;
const realFetch = globalThis.fetch;
@@ -867,6 +917,7 @@ describe('call recorder app lifecycle (integration)', () => {
afterEach(async () => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
+ vi.useRealTimers();
await destroyCreatedRows();
});
@@ -978,7 +1029,7 @@ describe('call recorder app lifecycle (integration)', () => {
calendarEventId,
...overrides
}: Record<string, unknown> & {
- calendarEventId: string;
+ calendarEventId?: string;
}): Promise<string> => {
const callRecordingId = randomUUID();
@@ -1259,11 +1310,33 @@ describe('call recorder app lifecycle (integration)', () => {
}
};
- // Mocked cron trigger: runs the flows the recovery cron dispatches.
- const runPendingRecoveryCron = () =>
- scheduleRecallBotsForPendingCallRecordings({ client, now: new Date() });
- const runCancellationRetryCron = () =>
- retryFailedRecallCancellations({ client, now: new Date() });
+ // Mocked job queue: runs the follow-ups armed since the last call, each with
+ // the clock moved to when the queue would have released it. Follow-ups they
+ // re-arm wait for the next call.
+ let nextFollowUpIndex = 0;
+
+ const runArmedFollowUps = async () => {
+ const armedFollowUps = recall.followUps.slice(nextFollowUpIndex);
+ const results = [];
+
+ nextFollowUpIndex = recall.followUps.length;
+
+ for (const { payload, dueAt } of armedFollowUps) {
+ if (dueAt > Date.now()) {
+ vi.setSystemTime(dueAt);
+ }
+
+ results.push(await followUpCallRecordingRequestHandler(payload));
+ }
+
+ return results;
+ };
+
+ const followUpsArmedFor = (callRecordingId: string) =>
+ recall.followUps.filter(
+ ({ payload }) => payload.callRecordingId === callRecordingId,
+ );
+
const runStaleStateCron = async () => {
const result = await convergeDivergedCallRecordings({
client,
@@ -2300,6 +2373,19 @@ describe('call recorder app lifecycle (integration)', () => {
});
describe('cancellation', () => {
+ const cancelThroughCalendar = async (calendarEventId: string) => {
+ await client.mutation({
+ updateCalendarEvent: {
+ __args: { id: calendarEventId, data: { isCanceled: true } },
+ id: true,
+ },
+ });
+ return reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+ };
+
it('cancels the request and deletes the Recall bot', async () => {
const { callRecordingId, botId } =
await scheduleRecordingThroughCalendarReconciliation();
@@ -2317,28 +2403,90 @@ describe('call recorder app lifecycle (integration)', () => {
expect(recall.deletedBotIds).toEqual([botId]);
});
- it('retries a failed Recall cancellation on the next cron run', async () => {
- const { callRecordingId, botId } =
+ it('persists cancellation and deletes the bot even when follow-up enqueueing fails', async () => {
+ const { calendarEventId, callRecordingId, botId } =
await scheduleRecordingThroughCalendarReconciliation();
+ recall.failFollowUpEnqueue = true;
- recall.failNextDelete = true;
- await cancelCallRecordingRequest({
- client,
- callRecording: { id: callRecordingId, externalBotId: botId },
+ await expect(cancelThroughCalendar(calendarEventId)).rejects.toThrow();
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+ expect(callRecording.recordingRequestStatus).toBe('CANCELED');
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(recall.deletedBotIds).toContain(botId);
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBeNull();
+ });
+
+ it('cancels a meeting in a mixed batch before active follow-up enqueueing fails', async () => {
+ const { calendarEventId, callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ await client.mutation({
+ updateCalendarEvent: {
+ __args: { id: calendarEventId, data: { isCanceled: true } },
+ id: true,
+ },
+ });
+ const activeCalendarEventId = await createCalendarEvent({
+ conferenceLink: {
+ primaryLinkUrl: 'https://meet.google.com/another-meeting',
+ },
});
+ recall.failFollowUpEnqueue = true;
+
+ await expect(
+ reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId, activeCalendarEventId],
+ }),
+ ).rejects.toThrow();
+
+ expect(
+ (await fetchCallRecording(callRecordingId)).recordingRequestStatus,
+ ).toBe('CANCELED');
+ expect(recall.deletedBotIds).toContain(botId);
+ });
+
+ it('cancels the bot in the follow-up when the inline Recall cancellation failed', async () => {
+ const { calendarEventId, callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+
+ recall.failNextDelete = true;
+ await cancelThroughCalendar(calendarEventId);
- // The Recall half failed, so the bot id must survive for the retry.
expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
botId,
);
- await runCancellationRetryCron();
+ await runArmedFollowUps();
expect(
(await fetchCallRecording(callRecordingId)).externalBotId,
).toBeFalsy();
expect(recall.deletedBotIds).toContain(botId);
});
+
+ it('cancels a bot whose booking reached Recall without its id being saved', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ botScheduleAttemptedAt: new Date().toISOString(),
+ });
+
+ recall.seedBot({
+ id: 'recall-bot-booked-during-cancellation',
+ metadata: buildBotMetadata(callRecordingId, workspaceId),
+ });
+
+ await cancelThroughCalendar(calendarEventId);
+ await runArmedFollowUps();
+
+ expect(recall.deletedBotIds).toEqual([
+ 'recall-bot-booked-during-cancellation',
+ ]);
+ expect(
+ (await fetchCallRecording(callRecordingId)).externalBotId,
+ ).toBeFalsy();
+ });
});
describe('artifact import queue', () => {
@@ -3047,20 +3195,95 @@ describe('call recorder app lifecycle (integration)', () => {
});
});
- describe('crash recovery cron', () => {
- it('schedules a bot for a recording created without one, with zero Recall list reads', async () => {
+ describe('request follow-up', () => {
+ it('books the bot half an hour after the first try failed', async () => {
+ const calendarEventId = await createCalendarEvent();
+
+ recall.failBotCreation = true;
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ const [callRecording] = await findCallRecordings({
+ calendarEventId: { eq: calendarEventId },
+ });
+
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(followUpsArmedFor(callRecording.id)).toMatchObject([
+ { delayMs: CALL_RECORDING_REQUEST_FOLLOW_UP_DELAY_MS },
+ ]);
+
+ recall.failBotCreation = false;
+ await runArmedFollowUps();
+
+ const externalBotId = (await fetchCallRecording(callRecording.id))
+ .externalBotId;
+
+ expect(externalBotId).toBeTruthy();
+ expect(recall.botForCallRecording(callRecording.id)?.id).toBe(
+ externalBotId,
+ );
+ expect(recall.listRequestCount).toBe(0);
+ });
+
+ it('keeps the follow-up armed when the run dies before writing the recording', async () => {
+ const calendarEventId = await createCalendarEvent();
+
+ interceptCoreApiRequests(async ({ query }, sendRequest) =>
+ query.includes('createCallRecording(')
+ ? new Response('Recording creation failed', { status: 500 })
+ : sendRequest(),
+ );
+
+ const [reconciliation] = await reconcileCallRecorderForCalendarEventIds({
+ client: new CoreApiClient(),
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(reconciliation).toMatchObject({ action: 'FAILED' });
+ expect(recall.followUps).toMatchObject([
+ { delayMs: CALL_RECORDING_REQUEST_FOLLOW_UP_DELAY_MS },
+ ]);
+ });
+
+ it('waits instead of racing a booking attempt that is still recent', async () => {
const calendarEventId = await createCalendarEvent();
const callRecordingId = await createPendingCallRecording({
calendarEventId,
+ botScheduleAttemptedAt: new Date().toISOString(),
});
- await runPendingRecoveryCron();
+ expect(
+ await followUpCallRecordingRequestHandler({ callRecordingId }),
+ ).toMatchObject({
+ status: 'follow-up-again',
+ reason: 'a bot booking may still be running',
+ });
+ expect(recall.bots.size).toBe(0);
+ expect(recall.listRequestCount).toBe(0);
- const callRecording = await fetchCallRecording(callRecordingId);
+ await runArmedFollowUps();
- expect(callRecording.externalBotId).toBeTruthy();
+ expect(
+ (await fetchCallRecording(callRecordingId)).externalBotId,
+ ).toBeTruthy();
+ });
+
+ it('books a bot for a request that never reached Recall, with zero Recall list reads', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ });
+
+ await followUpCallRecordingRequestHandler({ callRecordingId });
+
+ const externalBotId = (await fetchCallRecording(callRecordingId))
+ .externalBotId;
+
+ expect(externalBotId).toBeTruthy();
expect(recall.botForCallRecording(callRecordingId)?.id).toBe(
- callRecording.externalBotId,
+ externalBotId,
);
expect(recall.listRequestCount).toBe(0);
});
@@ -3071,13 +3294,11 @@ describe('call recorder app lifecycle (integration)', () => {
calendarEventId,
});
- // First recovery run creates the bot and records the attempt.
- await runPendingRecoveryCron();
+ await followUpCallRecordingRequestHandler({ callRecordingId });
+
const firstBotId = (await fetchCallRecording(callRecordingId))
.externalBotId;
- // Simulate the id write-back getting lost after the POST reached
- // Recall.
await client.mutation({
updateCallRecording: {
__args: { id: callRecordingId, data: { externalBotId: null } },
@@ -3085,10 +3306,9 @@ describe('call recorder app lifecycle (integration)', () => {
},
});
- await runPendingRecoveryCron();
+ vi.setSystemTime(Date.now() + CALL_RECORDING_REQUEST_FOLLOW_UP_DELAY_MS);
+ await followUpCallRecordingRequestHandler({ callRecordingId });
- // Recall dedupes the repeated idempotency key: the very same bot is
- // written back, without any list request.
expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
firstBotId,
);
@@ -3099,7 +3319,7 @@ describe('call recorder app lifecycle (integration)', () => {
const calendarEventId = await createCalendarEvent();
const callRecordingId = await createPendingCallRecording({
calendarEventId,
- botScheduleAttemptedAt: hoursAgo(0.25),
+ botScheduleAttemptedAt: hoursAgo(0.5),
botScheduleIdempotencyKey: 'key-from-before-the-meeting-moved',
});
@@ -3109,12 +3329,16 @@ describe('call recorder app lifecycle (integration)', () => {
statusCode: 'ready',
});
- await runPendingRecoveryCron();
+ await followUpCallRecordingRequestHandler({ callRecordingId });
expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
'recall-bot-from-crashed-run',
);
- expect(recall.listRequestCount).toBe(1);
+ expect(
+ [...recall.bots.values()].filter(
+ (bot) => bot.metadata.twentyCallRecordingId === callRecordingId,
+ ),
+ ).toHaveLength(1);
});
it('attaches a scheduled bot that has no status yet instead of creating a twin', async () => {
@@ -3129,7 +3353,7 @@ describe('call recorder app lifecycle (integration)', () => {
metadata: buildBotMetadata(callRecordingId, workspaceId),
});
- await runPendingRecoveryCron();
+ await followUpCallRecordingRequestHandler({ callRecordingId });
expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
'recall-bot-scheduled-before-lost-write-back',
@@ -3137,6 +3361,101 @@ describe('call recorder app lifecycle (integration)', () => {
expect(recall.bots.size).toBe(1);
});
+ it('only writes to a request that still awaits its bot', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ });
+ const externalBotId = randomUUID();
+
+ expect(
+ await updatePendingCallRecording({
+ client,
+ id: callRecordingId,
+ data: { externalBotId },
+ }),
+ ).toBe(true);
+ expect(
+ await updatePendingCallRecording({
+ client,
+ id: callRecordingId,
+ data: { externalBotId: randomUUID() },
+ }),
+ ).toBe(false);
+ expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
+ externalBotId,
+ );
+
+ await client.mutation({
+ updateCallRecording: {
+ __args: {
+ id: callRecordingId,
+ data: { recordingRequestStatus: 'CANCELED', externalBotId: null },
+ },
+ id: true,
+ },
+ });
+
+ expect(
+ await updatePendingCallRecording({
+ client,
+ id: callRecordingId,
+ data: { externalBotId: randomUUID() },
+ }),
+ ).toBe(false);
+ expect(
+ (await fetchCallRecording(callRecordingId)).externalBotId,
+ ).toBeFalsy();
+ });
+
+ it('settles without a bot for a meeting without a link', async () => {
+ const calendarEventId = await createCalendarEvent({
+ conferenceLink: { primaryLinkUrl: '' },
+ });
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ });
+
+ expect(
+ await followUpCallRecordingRequestHandler({ callRecordingId }),
+ ).toMatchObject({ status: 'settled' });
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+
+ expect(callRecording.status).toBe('SCHEDULED');
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(recall.followUps).toEqual([]);
+ });
+
+ it('settles a request that already has its bot without calling Recall', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ externalBotId: 'recall-bot-already-attached',
+ });
+
+ expect(
+ await followUpCallRecordingRequestHandler({ callRecordingId }),
+ ).toMatchObject({ status: 'settled' });
+ expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
+ 'recall-bot-already-attached',
+ );
+ expect(recall.bots.size).toBe(0);
+ expect(recall.listRequestCount).toBe(0);
+ });
+
+ it('leaves a pending recording without a calendar event untouched', async () => {
+ const callRecordingId = await createPendingCallRecording({});
+
+ expect(
+ await followUpCallRecordingRequestHandler({ callRecordingId }),
+ ).toMatchObject({ status: 'settled' });
+ expect((await fetchCallRecording(callRecordingId)).status).toBe(
+ 'SCHEDULED',
+ );
+ expect(recall.followUps).toEqual([]);
+ });
+
it('fails a recording whose meeting ended before any bot creation was attempted', async () => {
const calendarEventId = await createCalendarEvent({
startsAt: hoursAgo(3),
@@ -3146,15 +3465,195 @@ describe('call recorder app lifecycle (integration)', () => {
calendarEventId,
});
- await runPendingRecoveryCron();
+ await followUpCallRecordingRequestHandler({ callRecordingId });
- const callRecording = await fetchCallRecording(callRecordingId);
+ expect(await fetchCallRecording(callRecordingId)).toMatchObject({
+ status: 'FAILED',
+ callRecorderFailureReason: 'bot_never_scheduled',
+ });
+ expect(recall.botForCallRecording(callRecordingId)).toBeUndefined();
+ });
- expect(callRecording.status).toBe('FAILED');
- expect(callRecording.callRecorderFailureReason).toBe(
- 'bot_never_scheduled',
+ it('checks an ended recording again a week after its meeting while webhooks can still settle its attempt', async () => {
+ const meetingEndsAt = hoursAgo(2);
+ const calendarEventId = await createCalendarEvent({
+ startsAt: hoursAgo(3),
+ endsAt: meetingEndsAt,
+ });
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ botScheduleAttemptedAt: hoursAgo(4),
+ });
+
+ expect(
+ await followUpCallRecordingRequestHandler({ callRecordingId }),
+ ).toMatchObject({ status: 'follow-up-again' });
+ expect((await fetchCallRecording(callRecordingId)).status).toBe(
+ 'SCHEDULED',
);
- expect(recall.botForCallRecording(callRecordingId)).toBeUndefined();
+
+ const weekAfterMeeting =
+ new Date(meetingEndsAt).getTime() +
+ 7 * 24 * 60 * MILLISECONDS_PER_MINUTE;
+ const [armedFollowUp] = followUpsArmedFor(callRecordingId);
+
+ expect(armedFollowUp.dueAt).toBeGreaterThanOrEqual(weekAfterMeeting);
+ expect(armedFollowUp.dueAt).toBeLessThan(
+ weekAfterMeeting + MILLISECONDS_PER_MINUTE,
+ );
+ });
+
+ it('fails an unresolved attempt after the convergence lookback', async () => {
+ const calendarEventId = await createCalendarEvent({
+ startsAt: daysAgo(9),
+ endsAt: daysAgo(8),
+ });
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ botScheduleAttemptedAt: daysAgo(9),
+ });
+
+ await followUpCallRecordingRequestHandler({ callRecordingId });
+
+ expect(await fetchCallRecording(callRecordingId)).toMatchObject({
+ status: 'FAILED',
+ callRecorderFailureReason: 'bot_schedule_outcome_unknown',
+ });
+ });
+
+ it('follows up on requests left stuck by an earlier version after an upgrade', async () => {
+ const pendingCallRecordingId = await createPendingCallRecording({
+ calendarEventId: await createCalendarEvent(),
+ });
+ const canceledCallRecordingId = await createPendingCallRecording({
+ calendarEventId: await createCalendarEvent(),
+ recordingRequestStatus: 'CANCELED',
+ externalBotId: 'recall-bot-left-behind',
+ });
+
+ recall.seedBot({
+ id: 'recall-bot-left-behind',
+ metadata: buildBotMetadata(canceledCallRecordingId, workspaceId),
+ });
+
+ await startPostInstallBackfillsHandler({
+ previousVersion: '1.15.0',
+ newVersion: '1.16.0',
+ });
+
+ expect(recall.stuckRequestSweepRequests).toHaveLength(1);
+ expect(recall.calendarEventSweepRequests).toHaveLength(0);
+
+ await processPendingCallRecordingRequestsHandler();
+
+ for (const callRecordingId of [
+ pendingCallRecordingId,
+ canceledCallRecordingId,
+ ]) {
+ expect(followUpsArmedFor(callRecordingId)).toHaveLength(1);
+ await followUpCallRecordingRequestHandler({ callRecordingId });
+ }
+
+ expect(
+ (await fetchCallRecording(pendingCallRecordingId)).externalBotId,
+ ).toBeTruthy();
+ expect(recall.deletedBotIds).toEqual(['recall-bot-left-behind']);
+ });
+
+ it('starts the upcoming meetings sweep on a fresh install', async () => {
+ expect(
+ await startPostInstallBackfillsHandler({ newVersion: '1.16.0' }),
+ ).toEqual({ calendarEventSweepOutcome: 'sweep-enqueued' });
+ expect(recall.calendarEventSweepRequests).toHaveLength(1);
+ expect(recall.stuckRequestSweepRequests).toHaveLength(0);
+ });
+
+ describe('with real queue transport', () => {
+ beforeEach(() => {
+ vi.unstubAllGlobals();
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', applicationAccessToken);
+ });
+
+ it('leaves a request canceled while its follow-up waited alone', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ });
+ const jobId = `follow-up-test-${callRecordingId}`;
+
+ await enqueueJobs({
+ logicFunctionUniversalIdentifier:
+ FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [{ jobId, payload: { callRecordingId, attempt: 0 } }],
+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,
+ delayMs: 5_000,
+ });
+
+ expect(await getJobs([jobId])).toMatchObject([{ state: 'DELAYED' }]);
+
+ await client.mutation({
+ updateCallRecording: {
+ __args: {
+ id: callRecordingId,
+ data: { recordingRequestStatus: 'CANCELED' },
+ },
+ id: true,
+ },
+ });
+
+ await expect
+ .poll(() => getJobs([jobId]), { timeout: 30_000, interval: 500 })
+ .toMatchObject([{ jobId, state: 'COMPLETED', attemptsMade: 1 }]);
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+
+ expect(callRecording.recordingRequestStatus).toBe('CANCELED');
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(callRecording.botScheduleAttemptedAt).toBeFalsy();
+ });
+
+ it('redelivers a follow-up the Core API rejects until its retry budget is exhausted', async () => {
+ const callRecordingId = `invalid-${randomUUID()}`;
+ const jobId = `follow-up-test-${callRecordingId}`;
+
+ await enqueueJobs({
+ logicFunctionUniversalIdentifier:
+ FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [{ jobId, payload: { callRecordingId, attempt: 0 } }],
+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,
+ });
+
+ await expect
+ .poll(() => getJobs([jobId]), { timeout: 30_000, interval: 500 })
+ .toMatchObject([
+ {
+ jobId,
+ state: 'COMPLETED',
+ attemptsMade: ENQUEUED_JOB_RETRY_LIMIT + 1,
+ },
+ ]);
+ });
+
+ it('reports a failed upgrade sweep enqueue as retryable', async () => {
+ await createPendingCallRecording({
+ calendarEventId: await createCalendarEvent(),
+ });
+
+ // A workspace token can read recordings, but enqueueing requires an application token.
+ vi.stubEnv(
+ 'TWENTY_APP_ACCESS_TOKEN',
+ process.env[WORKSPACE_API_KEY_ENV] ?? '',
+ );
+
+ await expect(
+ processPendingCallRecordingRequestsHandler(),
+ ).rejects.toMatchObject({
+ name: 'RetryableLogicFunctionError',
+ message: expect.stringContaining(
+ 'stuck call recording request follow-up enqueueing failed',
+ ),
+ });
+ });
});
});
@@ -3623,7 +4122,47 @@ describe('call recorder app lifecycle (integration)', () => {
expect(recall.deletedBotIds).toContain(botId);
});
- it('stops the cancellation chain when Recall is down, leaving the bot to the daily retry', async () => {
+ it.each(['known bot', 'uncertain booking'])(
+ 're-arms a canceled %s after workspace-disable enqueueing fails',
+ async (booking) => {
+ const callRecordingId = await createPendingCallRecording({
+ ...(booking === 'known bot'
+ ? { externalBotId: 'recall-bot-awaiting-cancellation' }
+ : { botScheduleAttemptedAt: new Date().toISOString() }),
+ });
+ turnRecordingOff();
+ recall.failFollowUpEnqueue = true;
+
+ await expect(syncCalendarBotSchedulingHandler()).rejects.toThrow();
+ expect(
+ (await fetchCallRecording(callRecordingId)).recordingRequestStatus,
+ ).toBe('CANCELED');
+ expect(followUpsArmedFor(callRecordingId)).toHaveLength(0);
+ expect(recall.cancellationCleanupRequests).toHaveLength(1);
+
+ recall.failFollowUpEnqueue = false;
+ await syncCalendarBotSchedulingHandler();
+ expect(followUpsArmedFor(callRecordingId)).toHaveLength(1);
+ },
+ );
+
+ it('persists cancellation and arms follow-up even when cleanup enqueueing fails', async () => {
+ const { callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ turnRecordingOff();
+ recall.followUps = [];
+ recall.failCancellationCleanupEnqueue = true;
+
+ await expect(syncCalendarBotSchedulingHandler()).rejects.toThrow();
+
+ expect(await fetchCallRecording(callRecordingId)).toMatchObject({
+ recordingRequestStatus: 'CANCELED',
+ externalBotId: botId,
+ });
+ expect(followUpsArmedFor(callRecordingId)).toHaveLength(1);
+ });
+
+ it('stops the cancellation chain when Recall is down, leaving the bot to its follow-up', async () => {
const { callRecordingId, botId } =
await scheduleRecordingThroughCalendarReconciliation();
@@ -3640,6 +4179,14 @@ describe('call recorder app lifecycle (integration)', () => {
expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
botId,
);
+
+ recall.failRecallRemovals = false;
+ await runArmedFollowUps();
+
+ expect(
+ (await fetchCallRecording(callRecordingId)).externalBotId,
+ ).toBeFalsy();
+ expect(recall.deletedBotIds).toContain(botId);
});
it('does not schedule a bot for a request the cancellation missed', async () => {
@@ -3650,7 +4197,7 @@ describe('call recorder app lifecycle (integration)', () => {
turnRecordingOff();
- await runPendingRecoveryCron();
+ await followUpCallRecordingRequestHandler({ callRecordingId });
const callRecording = await fetchCallRecording(callRecordingId);
@@ -3719,15 +4266,13 @@ describe('call recorder app lifecycle (integration)', () => {
},
});
- const result = await deliverCalendarEventUpdates({
+ await deliverCalendarEventUpdates({
calendarEventId,
updatedFields: ['callRecorderPreference'],
before: { callRecorderPreference: null },
after: { callRecorderPreference: 'ON' },
});
- expect(result).toEqual(expect.objectContaining({ reconciled: true }));
-
const callRecording = await fetchCallRecording(callRecordingId);
expect(callRecording.recordingRequestStatus).toBe('REQUESTED');
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 ee7af0c02a5..2dd5a1812aa 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
@@ -88,6 +88,9 @@ export const ENQUEUE_CALL_RECORDING_RECOVERY_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER
export const ENQUEUE_ORPHANED_RECALL_BOT_CLEANUP_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'455458ce-bbc3-4b39-a3f2-950540c9eda7';
+export const FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ '3e362527-0f8a-432b-94ea-95909a8e49ea';
+
export const GENERATE_CALL_RECORDING_SUMMARIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'3467c68d-5d81-4f16-8234-b4182cb17f19';
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/schedule-recall-bot-on-call-recording-update.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/schedule-recall-bot-on-call-recording-update.test.ts
index 51a9b42612b..4b68ec73f48 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/schedule-recall-bot-on-call-recording-update.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/schedule-recall-bot-on-call-recording-update.test.ts
@@ -43,7 +43,9 @@ type HandlerEvent = Parameters<
typeof scheduleRecallBotOnCallRecordingUpdateHandler
>[0];
-const buildUpdateEvent = (overrides: Partial<HandlerEvent> = {}): HandlerEvent =>
+const buildUpdateEvent = (
+ overrides: Partial<HandlerEvent> = {},
+): HandlerEvent =>
({
name: 'callRecording.updated',
recordId: 'call-recording-1',
@@ -167,9 +169,8 @@ describe('scheduleRecallBotOnCallRecordingUpdateHandler', () => {
it('schedules a bot when an update clears the bot id of a requested recording', async () => {
stubPendingCallRecordingQueries();
- const result = await scheduleRecallBotOnCallRecordingUpdateHandler(
- buildUpdateEvent(),
- );
+ const result =
+ await scheduleRecallBotOnCallRecordingUpdateHandler(buildUpdateEvent());
expect(result).toEqual({
callRecordingId: 'call-recording-1',
@@ -301,7 +302,7 @@ describe('scheduleRecallBotOnCallRecordingUpdateHandler', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
- it('defers rows with an ambiguous prior attempt to the recovery cron instead of listing bots', async () => {
+ it('defers rows with an ambiguous prior attempt to the follow-up instead of listing bots', async () => {
queryMock.mockImplementationOnce(async () => ({
callRecordings: buildConnection([
{
@@ -328,15 +329,15 @@ describe('scheduleRecallBotOnCallRecordingUpdateHandler', () => {
]),
}));
- const result = await scheduleRecallBotOnCallRecordingUpdateHandler(
- buildUpdateEvent(),
- );
+ const result =
+ await scheduleRecallBotOnCallRecordingUpdateHandler(buildUpdateEvent());
expect(result).toEqual({
callRecordingId: 'call-recording-1',
result: {
status: 'deferred',
- reason: 'ambiguous prior attempt; the recovery cron will reconcile it',
+ reason:
+ 'ambiguous prior attempt; the follow-up will look it up at Recall',
},
});
expect(fetchMock).not.toHaveBeenCalled();
@@ -385,9 +386,8 @@ describe('scheduleRecallBotOnCallRecordingUpdateHandler', () => {
]),
}));
- const result = await scheduleRecallBotOnCallRecordingUpdateHandler(
- buildUpdateEvent(),
- );
+ const result =
+ await scheduleRecallBotOnCallRecordingUpdateHandler(buildUpdateEvent());
expect(result).toEqual({
callRecordingId: 'call-recording-1',
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/start-post-install-backfills.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/start-post-install-backfills.test.ts
deleted file mode 100644
index 743ba66fdad..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/start-post-install-backfills.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';
-import postInstallLogicFunction, {
- startPostInstallBackfillsHandler,
-} from 'src/logic-functions/start-post-install-backfills';
-
-const enqueueJobsMock = vi.hoisted(() => vi.fn());
-
-vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- enqueueJobs: enqueueJobsMock,
-}));
-
-describe('start-post-install-backfills', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- enqueueJobsMock.mockResolvedValue({ enqueued: true, enqueuedJobsCount: 1 });
- });
-
- it('is configured to run on fresh installs only', () => {
- expect(postInstallLogicFunction.config).toEqual(
- expect.objectContaining({
- name: 'start-post-install-backfills',
- timeoutSeconds: 30,
- }),
- );
- expect(postInstallLogicFunction.config).not.toHaveProperty(
- 'shouldRunOnVersionUpgrade',
- );
- });
-
- it('enqueues the upcoming calendar events sweep', async () => {
- const result = await startPostInstallBackfillsHandler();
-
- expect(result).toEqual({ calendarEventSweepOutcome: 'sweep-enqueued' });
- expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({
- logicFunctionUniversalIdentifier:
- SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- payloads: [{}],
- retryLimit: ENQUEUED_JOB_RETRY_LIMIT,
- });
- });
-
- it('throws when the sweep enqueue fails so the hook retries', async () => {
- enqueueJobsMock.mockRejectedValue(new Error('Network failed'));
-
- await expect(startPostInstallBackfillsHandler()).rejects.toMatchObject({
- name: 'RetryableLogicFunctionError',
- message: expect.stringContaining('Network failed'),
- });
- });
-});
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
index 8bdfce2df52..567ce8b9a4a 100644
--- 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
@@ -38,7 +38,7 @@ export default defineLogicFunction({
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.',
+ 'Deletes the Recall bots of canceled recording requests in bounded slices, re-enqueueing itself while more remain. The follow-up armed with each cancellation stays the backstop.',
timeoutSeconds: 900,
handler: cancelScheduledRecallBotsHandler,
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-request-follow-up-delay-ms.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-request-follow-up-delay-ms.ts
new file mode 100644
index 00000000000..d8baf408042
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-request-follow-up-delay-ms.ts
@@ -0,0 +1,4 @@
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+
+export const CALL_RECORDING_REQUEST_FOLLOW_UP_DELAY_MS =
+ 30 * MILLISECONDS_PER_MINUTE;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-request-follow-up-retry-delays-ms.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-request-follow-up-retry-delays-ms.ts
new file mode 100644
index 00000000000..be3f2abd55a
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-request-follow-up-retry-delays-ms.ts
@@ -0,0 +1,9 @@
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+
+const MILLISECONDS_PER_HOUR = 60 * MILLISECONDS_PER_MINUTE;
+
+export const CALL_RECORDING_REQUEST_FOLLOW_UP_RETRY_DELAYS_MS = [
+ MILLISECONDS_PER_HOUR,
+ 4 * MILLISECONDS_PER_HOUR,
+ 24 * MILLISECONDS_PER_HOUR,
+];
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/pending-call-recording-requests-cron-pattern.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/pending-call-recording-requests-cron-pattern.ts
deleted file mode 100644
index 8cdcba9ff2e..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/pending-call-recording-requests-cron-pattern.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-// The callRecording.updated trigger resumes most stuck rows within seconds;
-// this cron is the backstop for crashed creations and missed events.
-export const PENDING_CALL_RECORDING_REQUESTS_CRON_PATTERN = '0 3 * * *';
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-request-follow-ups.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-request-follow-ups.test.ts
new file mode 100644
index 00000000000..4723317cbb0
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-request-follow-ups.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';
+import { enqueueCallRecordingRequestFollowUps } from 'src/logic-functions/data/enqueue-call-recording-request-follow-ups.util';
+import { RECALL_RECOVERY_CALLS_PER_MINUTE } from 'src/logic-functions/constants/recall-recovery-calls-per-minute';
+
+const enqueueJobsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+
+describe('enqueueCallRecordingRequestFollowUps', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-01T12:04:30.000Z'));
+ enqueueJobsMock.mockReset().mockResolvedValue({ enqueued: true });
+ });
+
+ afterEach(() => vi.useRealTimers());
+
+ it('paces every batch and includes each recording exactly once', async () => {
+ const callRecordingIds = Array.from(
+ { length: 121 },
+ (_, index) => `recording-${index}`,
+ );
+ await enqueueCallRecordingRequestFollowUps({ callRecordingIds });
+
+ const calls = enqueueJobsMock.mock.calls.map(([input]) => input);
+ expect(calls.map(({ jobs }) => jobs.length)).toEqual([60, 60, 1]);
+ expect(calls.map(({ delayMs }) => delayMs)).toEqual([
+ 1_800_000, 1_860_000, 1_920_000,
+ ]);
+ expect(
+ calls
+ .flatMap(({ jobs }) =>
+ jobs.map(
+ ({ payload }: { payload: { callRecordingId: string } }) =>
+ payload.callRecordingId,
+ ),
+ )
+ .sort(),
+ ).toEqual([...callRecordingIds].sort());
+ });
+
+ it('uses the same job ID for bulk and individual arms across a pacing window boundary', async () => {
+ const callRecordingId = 'z-recording';
+ await enqueueCallRecordingRequestFollowUps({
+ callRecordingIds: [
+ ...Array.from(
+ { length: RECALL_RECOVERY_CALLS_PER_MINUTE },
+ (_, index) => `a-recording-${index}`,
+ ),
+ callRecordingId,
+ ],
+ });
+ const bulkCall = enqueueJobsMock.mock.calls[1][0];
+
+ await enqueueCallRecordingRequestFollowUps({
+ callRecordingIds: [callRecordingId],
+ });
+ const individualCall = enqueueJobsMock.mock.calls[2][0];
+
+ expect(bulkCall.jobs).toEqual(individualCall.jobs);
+ expect(bulkCall.delayMs).toBe(individualCall.delayMs + 60_000);
+ expect(bulkCall.retryLimit).toBe(ENQUEUED_JOB_RETRY_LIMIT);
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-request-follow-ups.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-request-follow-ups.util.ts
new file mode 100644
index 00000000000..1f8a3b30fe5
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-request-follow-ups.util.ts
@@ -0,0 +1,53 @@
+import { enqueueJobs } from 'twenty-sdk/logic-function';
+
+import { FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { CALL_RECORDING_REQUEST_FOLLOW_UP_DELAY_MS } from 'src/logic-functions/constants/call-recording-request-follow-up-delay-ms';
+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { RECALL_RECOVERY_CALLS_PER_MINUTE } from 'src/logic-functions/constants/recall-recovery-calls-per-minute';
+import { buildCallRecordingRequestFollowUpJobId } from 'src/logic-functions/domain/build-call-recording-request-follow-up-job-id.util';
+import { getBatches } from 'src/logic-functions/utils/get-batches.util';
+import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
+
+export const enqueueCallRecordingRequestFollowUps = async ({
+ callRecordingIds,
+ delayMs = CALL_RECORDING_REQUEST_FOLLOW_UP_DELAY_MS,
+ attempt = 0,
+}: {
+ callRecordingIds: string[];
+ delayMs?: number;
+ attempt?: number;
+}): Promise<void> => {
+ const now = Date.now();
+ const followUpSlots = getBatches(
+ getUniqueSortedIds(callRecordingIds),
+ RECALL_RECOVERY_CALLS_PER_MINUTE,
+ );
+
+ for (const [slotIndex, slotCallRecordingIds] of followUpSlots.entries()) {
+ const slotDelayMs = delayMs + slotIndex * MILLISECONDS_PER_MINUTE;
+
+ try {
+ await enqueueJobs({
+ logicFunctionUniversalIdentifier:
+ FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: slotCallRecordingIds.map((callRecordingId) => ({
+ jobId: buildCallRecordingRequestFollowUpJobId({
+ callRecordingId,
+ attempt,
+ dueAt: new Date(now + delayMs),
+ }),
+ payload: { callRecordingId, attempt },
+ })),
+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,
+ delayMs: slotDelayMs,
+ });
+ } catch (error) {
+ throw buildRetryableStepFailure(
+ 'call recording follow-up enqueueing',
+ error,
+ );
+ }
+ }
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-stuck-call-recording-request-ids.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-stuck-call-recording-request-ids.util.ts
new file mode 100644
index 00000000000..2ef032cd225
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-stuck-call-recording-request-ids.util.ts
@@ -0,0 +1,29 @@
+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 { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';
+import { findCallRecordingsByFilter } from 'src/logic-functions/data/find-call-recordings-by-filter.util';
+import { findOpenScheduledCallRecordings } from 'src/logic-functions/data/find-open-scheduled-call-recordings.util';
+
+export const findStuckCallRecordingRequestIds = async (
+ client: CoreApiClient,
+): Promise<string[]> => {
+ const pendingCallRecordings = (
+ await findOpenScheduledCallRecordings(client)
+ ).filter((callRecording) => isUndefined(callRecording.externalBotId));
+ const canceledCallRecordings = (
+ await findCallRecordingsByFilter(client, {
+ recordingRequestStatus: { eq: CallRecordingRequestStatus.CANCELED },
+ status: { in: NON_TERMINAL_CALL_RECORDING_STATUSES },
+ })
+ ).filter(
+ (callRecording) =>
+ !isUndefined(callRecording.externalBotId) ||
+ !isUndefined(callRecording.botScheduleAttemptedAt),
+ );
+
+ return [...pendingCallRecordings, ...canceledCallRecordings].map(
+ (callRecording) => callRecording.id,
+ );
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-pending-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-pending-call-recording.util.ts
new file mode 100644
index 00000000000..f26b022420d
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-pending-call-recording.util.ts
@@ -0,0 +1,37 @@
+import { isNonEmptyArray } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';
+
+// Writes only while the request still awaits a bot, so a cancellation or a
+// webhook that landed in the meantime wins.
+export const updatePendingCallRecording = async ({
+ client,
+ id,
+ data,
+}: {
+ client: CoreApiClient;
+ id: string;
+ data: CallRecordingUpdateFields;
+}): Promise<boolean> => {
+ const result = await client.mutation({
+ updateCallRecordings: {
+ __args: {
+ filter: {
+ id: { eq: id },
+ recordingRequestStatus: {
+ eq: CallRecordingRequestStatus.REQUESTED,
+ },
+ status: { in: [CallRecordingStatus.SCHEDULED] },
+ externalBotId: { is: 'NULL' },
+ },
+ data,
+ },
+ id: true,
+ },
+ });
+
+ return isNonEmptyArray(result.updateCallRecordings);
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-call-recording-request-follow-up-job-id.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-call-recording-request-follow-up-job-id.test.ts
new file mode 100644
index 00000000000..db7c87f8ef2
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-call-recording-request-follow-up-job-id.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest';
+
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { buildCallRecordingRequestFollowUpJobId } from 'src/logic-functions/domain/build-call-recording-request-follow-up-job-id.util';
+
+const CALL_RECORDING_ID = '0b4e9a3c-6f61-4a52-9d55-3f0f4d7b6e21';
+const WINDOW_START = new Date('2026-01-01T12:00:00.000Z');
+
+const minutesAfterWindowStart = (minutes: number): Date =>
+ new Date(WINDOW_START.getTime() + minutes * MILLISECONDS_PER_MINUTE);
+
+describe('buildCallRecordingRequestFollowUpJobId', () => {
+ it('gives follow-ups of a recording due within the same five minutes one job id', () => {
+ expect(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 0,
+ dueAt: minutesAfterWindowStart(0),
+ }),
+ ).toBe(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 0,
+ dueAt: minutesAfterWindowStart(4.9),
+ }),
+ );
+ });
+
+ it('gives a follow-up due in a later window its own job id', () => {
+ expect(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 0,
+ dueAt: minutesAfterWindowStart(0),
+ }),
+ ).not.toBe(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 0,
+ dueAt: minutesAfterWindowStart(5),
+ }),
+ );
+ });
+
+ it('gives a re-armed follow-up its own job id even when due in the same window', () => {
+ expect(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 0,
+ dueAt: minutesAfterWindowStart(0),
+ }),
+ ).not.toBe(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 1,
+ dueAt: minutesAfterWindowStart(1),
+ }),
+ );
+ });
+
+ it('gives each recording its own job id', () => {
+ expect(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 0,
+ dueAt: WINDOW_START,
+ }),
+ ).not.toBe(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: 'a51d7d2c-2f6c-4b8e-8f0e-0c1f5c9e7d40',
+ attempt: 0,
+ dueAt: WINDOW_START,
+ }),
+ );
+ });
+
+ it('stays within the queue job id format', () => {
+ expect(
+ buildCallRecordingRequestFollowUpJobId({
+ callRecordingId: CALL_RECORDING_ID,
+ attempt: 12,
+ dueAt: WINDOW_START,
+ }),
+ ).toMatch(/^[A-Za-z0-9_.-]{1,128}$/);
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-call-recording-request-follow-up-retry-delay.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-call-recording-request-follow-up-retry-delay.test.ts
new file mode 100644
index 00000000000..9b7ea415bc9
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-call-recording-request-follow-up-retry-delay.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { computeCallRecordingRequestFollowUpRetryDelayMs } from 'src/logic-functions/domain/compute-call-recording-request-follow-up-retry-delay.util';
+
+const NOW = new Date('2026-01-01T12:00:00.000Z');
+const MILLISECONDS_PER_HOUR = 60 * MILLISECONDS_PER_MINUTE;
+const IN_A_WEEK = new Date(
+ NOW.getTime() + 7 * 24 * MILLISECONDS_PER_HOUR,
+).toISOString();
+
+describe('computeCallRecordingRequestFollowUpRetryDelayMs', () => {
+ it('retries after an hour, then four hours, then once a day', () => {
+ const delaysMs = [0, 1, 2, 3, 10].map((attempt) =>
+ computeCallRecordingRequestFollowUpRetryDelayMs({
+ attempt,
+ meetingStartsAt: IN_A_WEEK,
+ now: NOW,
+ }),
+ );
+
+ expect(delaysMs).toEqual([
+ MILLISECONDS_PER_HOUR,
+ 4 * MILLISECONDS_PER_HOUR,
+ 24 * MILLISECONDS_PER_HOUR,
+ 24 * MILLISECONDS_PER_HOUR,
+ 24 * MILLISECONDS_PER_HOUR,
+ ]);
+ });
+
+ it('retries at the meeting start when the scheduled retry would come after it', () => {
+ expect(
+ computeCallRecordingRequestFollowUpRetryDelayMs({
+ attempt: 0,
+ meetingStartsAt: new Date(
+ NOW.getTime() + 20 * MILLISECONDS_PER_MINUTE,
+ ).toISOString(),
+ now: NOW,
+ }),
+ ).toBe(20 * MILLISECONDS_PER_MINUTE);
+ });
+
+ it('keeps the schedule once the meeting has started', () => {
+ expect(
+ computeCallRecordingRequestFollowUpRetryDelayMs({
+ attempt: 1,
+ meetingStartsAt: new Date(
+ NOW.getTime() - 10 * MILLISECONDS_PER_MINUTE,
+ ).toISOString(),
+ now: NOW,
+ }),
+ ).toBe(4 * MILLISECONDS_PER_HOUR);
+ });
+
+ it('keeps the schedule when the meeting start is unknown', () => {
+ expect(
+ computeCallRecordingRequestFollowUpRetryDelayMs({
+ attempt: 0,
+ meetingStartsAt: undefined,
+ now: NOW,
+ }),
+ ).toBe(MILLISECONDS_PER_HOUR);
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/has-meeting-ended.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/has-meeting-ended.test.ts
new file mode 100644
index 00000000000..7e768b67d61
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/has-meeting-ended.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import { hasMeetingEnded } from 'src/logic-functions/domain/has-meeting-ended.util';
+
+const NOW = new Date('2026-01-01T12:00:00.000Z');
+const BEFORE_NOW = '2026-01-01T11:00:00.000Z';
+const AFTER_NOW = '2026-01-01T13:00:00.000Z';
+
+describe('hasMeetingEnded', () => {
+ it.each([
+ {
+ startsAt: BEFORE_NOW,
+ endsAt: AFTER_NOW,
+ startGraceHours: 0,
+ expected: false,
+ },
+ {
+ startsAt: BEFORE_NOW,
+ endsAt: NOW.toISOString(),
+ startGraceHours: 24,
+ expected: true,
+ },
+ {
+ startsAt: BEFORE_NOW,
+ endsAt: undefined,
+ startGraceHours: 0,
+ expected: true,
+ },
+ {
+ startsAt: BEFORE_NOW,
+ endsAt: 'invalid',
+ startGraceHours: 0,
+ expected: true,
+ },
+ {
+ startsAt: BEFORE_NOW,
+ endsAt: undefined,
+ startGraceHours: 24,
+ expected: false,
+ },
+ {
+ startsAt: BEFORE_NOW,
+ endsAt: 'invalid',
+ startGraceHours: 1,
+ expected: true,
+ },
+ {
+ startsAt: undefined,
+ endsAt: BEFORE_NOW,
+ startGraceHours: 24,
+ expected: true,
+ },
+ {
+ startsAt: undefined,
+ endsAt: undefined,
+ startGraceHours: 0,
+ expected: false,
+ },
+ {
+ startsAt: 'invalid',
+ endsAt: 'invalid',
+ startGraceHours: 0,
+ expected: false,
+ },
+ ])(
+ 'resolves $startsAt / $endsAt with $startGraceHours hours of fallback grace',
+ ({ expected, ...meeting }) => {
+ expect(hasMeetingEnded({ ...meeting, now: NOW })).toBe(expected);
+ },
+ );
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/resolve-call-recording-request-follow-up.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/resolve-call-recording-request-follow-up.test.ts
new file mode 100644
index 00000000000..f066cac32fe
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/resolve-call-recording-request-follow-up.test.ts
@@ -0,0 +1,298 @@
+import { describe, expect, it } from 'vitest';
+
+import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { resolveCallRecordingRequestFollowUp } from 'src/logic-functions/domain/resolve-call-recording-request-follow-up.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';
+
+const NOW = new Date('2026-01-01T12:00:00.000Z');
+const MINUTES_PER_DAY = 24 * 60;
+
+const minutesFromNow = (minutes: number): string =>
+ new Date(NOW.getTime() + minutes * MILLISECONDS_PER_MINUTE).toISOString();
+
+const buildCallRecording = (
+ overrides: Partial<CallRecordingRecord> = {},
+): CallRecordingRecord => ({
+ id: 'call-recording-1',
+ status: CallRecordingStatus.SCHEDULED,
+ recordingRequestStatus: CallRecordingRequestStatus.REQUESTED,
+ calendarEventId: 'calendar-event-1',
+ ...overrides,
+});
+
+const buildCanceledCallRecording = (
+ overrides: Partial<CallRecordingRecord> = {},
+): CallRecordingRecord =>
+ buildCallRecording({
+ recordingRequestStatus: CallRecordingRequestStatus.CANCELED,
+ updatedAt: minutesFromNow(-30),
+ ...overrides,
+ });
+
+const buildCalendarEvent = (
+ overrides: Partial<CalendarEventRecord> = {},
+): CalendarEventRecord => ({
+ id: 'calendar-event-1',
+ title: 'Customer sync',
+ isCanceled: false,
+ startsAt: minutesFromNow(60),
+ endsAt: minutesFromNow(120),
+ iCalUid: undefined,
+ conferenceLinkUrl: 'https://meet.example.com/customer-sync',
+ callRecorderPreference: undefined,
+ ...overrides,
+});
+
+const endedCalendarEvent = buildCalendarEvent({
+ startsAt: minutesFromNow(-120),
+ endsAt: minutesFromNow(-60),
+});
+
+describe('resolveCallRecordingRequestFollowUp', () => {
+ describe('pending request', () => {
+ it('books a bot while the meeting is still ahead', () => {
+ const calendarEvent = buildCalendarEvent();
+
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording(),
+ calendarEvent,
+ now: NOW,
+ }),
+ ).toEqual({ action: 'book-bot', calendarEvent });
+ });
+
+ it('waits for the end of the first-try grace when a booking attempt is recent', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({
+ botScheduleAttemptedAt: minutesFromNow(-5),
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toEqual({
+ action: 'check-again',
+ reason: 'a bot booking may still be running',
+ checkAt: new Date(minutesFromNow(10)),
+ });
+ });
+
+ it('books a bot once the last booking attempt is past the first-try grace', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({
+ botScheduleAttemptedAt: minutesFromNow(-20),
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'book-bot' });
+ });
+
+ it('books a bot when the booking attempt is timestamped in the future', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({
+ botScheduleAttemptedAt: minutesFromNow(5),
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'book-bot' });
+ });
+
+ it('leaves a request without a calendar event alone', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({ calendarEventId: undefined }),
+ calendarEvent: undefined,
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'none' });
+ });
+
+ it('fails a request whose meeting ended before any booking attempt', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording(),
+ calendarEvent: endedCalendarEvent,
+ now: NOW,
+ }),
+ ).toEqual({
+ action: 'mark-failed',
+ failureReason: 'bot_never_scheduled',
+ });
+ });
+
+ it('treats a meeting without an end time as over once it started', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording(),
+ calendarEvent: buildCalendarEvent({
+ startsAt: minutesFromNow(-1),
+ endsAt: undefined,
+ }),
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'mark-failed' });
+ });
+
+ it('waits seven days after the meeting for webhooks to settle an attempt that may have reached Recall', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({
+ botScheduleAttemptedAt: minutesFromNow(-180),
+ }),
+ calendarEvent: endedCalendarEvent,
+ now: NOW,
+ }),
+ ).toEqual({
+ action: 'check-again',
+ reason:
+ 'waiting for Recall webhooks to settle the last booking attempt',
+ checkAt: new Date(minutesFromNow(7 * MINUTES_PER_DAY - 60)),
+ });
+ });
+
+ it('fails a request whose unresolved attempt outlived the seven days', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({
+ botScheduleAttemptedAt: minutesFromNow(-9 * MINUTES_PER_DAY),
+ }),
+ calendarEvent: buildCalendarEvent({
+ startsAt: minutesFromNow(-9 * MINUTES_PER_DAY),
+ endsAt: minutesFromNow(-8 * MINUTES_PER_DAY),
+ }),
+ now: NOW,
+ }),
+ ).toEqual({
+ action: 'mark-failed',
+ failureReason: 'bot_schedule_outcome_unknown',
+ });
+ });
+ });
+
+ describe('request that does not wait on Recall', () => {
+ it('does nothing once the request has its bot', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({ externalBotId: 'recall-bot-1' }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'none' });
+ });
+
+ it('does nothing once the bot is recording', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCallRecording({
+ status: CallRecordingStatus.RECORDING,
+ externalBotId: 'recall-bot-1',
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'none' });
+ });
+ });
+
+ describe('canceled request', () => {
+ it('cancels the bot that is still booked', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCanceledCallRecording({
+ externalBotId: 'recall-bot-1',
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toEqual({ action: 'cancel-bot', externalBotId: 'recall-bot-1' });
+ });
+
+ it('looks for a bot at Recall when a booking may have reached it without its id being saved', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCanceledCallRecording({
+ botScheduleAttemptedAt: minutesFromNow(-40),
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toEqual({ action: 'find-and-cancel-bot' });
+ });
+
+ it('waits for the end of the first-try grace when the booking attempt is recent', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCanceledCallRecording({
+ botScheduleAttemptedAt: minutesFromNow(-1),
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toMatchObject({
+ action: 'check-again',
+ checkAt: new Date(minutesFromNow(14)),
+ });
+ });
+
+ it('does nothing when no booking ever reached Recall', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCanceledCallRecording(),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'none' });
+ });
+
+ it('stops chasing the bot once the meeting is over', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCanceledCallRecording({
+ externalBotId: 'recall-bot-1',
+ }),
+ calendarEvent: endedCalendarEvent,
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'none' });
+ });
+
+ it('does nothing for a recording that already finished', () => {
+ expect(
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCanceledCallRecording({
+ status: CallRecordingStatus.COMPLETED,
+ externalBotId: 'recall-bot-1',
+ }),
+ calendarEvent: buildCalendarEvent(),
+ now: NOW,
+ }),
+ ).toMatchObject({ action: 'none' });
+ });
+
+ it('chases the bot for a day after the cancellation when the meeting time is unknown', () => {
+ const resolveWithoutMeeting = (canceledMinutesAgo: number) =>
+ resolveCallRecordingRequestFollowUp({
+ callRecording: buildCanceledCallRecording({
+ calendarEventId: undefined,
+ externalBotId: 'recall-bot-1',
+ updatedAt: minutesFromNow(-canceledMinutesAgo),
+ }),
+ calendarEvent: undefined,
+ now: NOW,
+ });
+
+ expect(resolveWithoutMeeting(23 * 60)).toMatchObject({
+ action: 'cancel-bot',
+ });
+ expect(resolveWithoutMeeting(25 * 60)).toMatchObject({ action: 'none' });
+ });
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recording-request-follow-up-job-id.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recording-request-follow-up-job-id.util.ts
new file mode 100644
index 00000000000..91c9bed92ad
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recording-request-follow-up-job-id.util.ts
@@ -0,0 +1,20 @@
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+
+const FOLLOW_UP_DEDUPLICATION_WINDOW_MS = 5 * MILLISECONDS_PER_MINUTE;
+
+// Include the attempt so a running job cannot deduplicate its own successor.
+export const buildCallRecordingRequestFollowUpJobId = ({
+ callRecordingId,
+ attempt,
+ dueAt,
+}: {
+ callRecordingId: string;
+ attempt: number;
+ dueAt: Date;
+}): string => {
+ const dueWindow = Math.floor(
+ dueAt.getTime() / FOLLOW_UP_DEDUPLICATION_WINDOW_MS,
+ );
+
+ return `call-recorder-${callRecordingId}-follow-up-${attempt}-${dueWindow}`;
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-call-recording-request-follow-up-retry-delay.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-call-recording-request-follow-up-retry-delay.util.ts
new file mode 100644
index 00000000000..b17b68ac1f1
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-call-recording-request-follow-up-retry-delay.util.ts
@@ -0,0 +1,30 @@
+import { isUndefined } from '@sniptt/guards';
+
+import { CALL_RECORDING_REQUEST_FOLLOW_UP_RETRY_DELAYS_MS } from 'src/logic-functions/constants/call-recording-request-follow-up-retry-delays-ms';
+
+export const computeCallRecordingRequestFollowUpRetryDelayMs = ({
+ attempt,
+ meetingStartsAt,
+ now,
+}: {
+ attempt: number;
+ meetingStartsAt: string | undefined;
+ now: Date;
+}): number => {
+ const scheduledDelayMs =
+ CALL_RECORDING_REQUEST_FOLLOW_UP_RETRY_DELAYS_MS[
+ Math.min(
+ attempt,
+ CALL_RECORDING_REQUEST_FOLLOW_UP_RETRY_DELAYS_MS.length - 1,
+ )
+ ];
+ const timeUntilMeetingStartMs = isUndefined(meetingStartsAt)
+ ? Number.NaN
+ : new Date(meetingStartsAt).getTime() - now.getTime();
+
+ if (timeUntilMeetingStartMs > 0) {
+ return Math.min(scheduledDelayMs, timeUntilMeetingStartMs);
+ }
+
+ return scheduledDelayMs;
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/get-meeting-end-time.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/get-meeting-end-time.util.ts
new file mode 100644
index 00000000000..998c1d4a2ac
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/get-meeting-end-time.util.ts
@@ -0,0 +1,31 @@
+import { isUndefined } from '@sniptt/guards';
+
+export const getMeetingEndTime = ({
+ startsAt,
+ endsAt,
+ startGraceHours = 0,
+}: {
+ startsAt: string | undefined;
+ endsAt: string | undefined;
+ startGraceHours?: number;
+}): number | undefined => {
+ if (!isUndefined(endsAt)) {
+ const meetingEndTime = new Date(endsAt).getTime();
+
+ if (!Number.isNaN(meetingEndTime)) {
+ return meetingEndTime;
+ }
+ }
+
+ if (isUndefined(startsAt)) {
+ return undefined;
+ }
+
+ const meetingStartTime = new Date(startsAt).getTime();
+
+ if (Number.isNaN(meetingStartTime)) {
+ return undefined;
+ }
+
+ return meetingStartTime + startGraceHours * 60 * 60 * 1000;
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-meeting-ended.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-meeting-ended.util.ts
index 32229bb1d8b..c068471521c 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-meeting-ended.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-meeting-ended.util.ts
@@ -1,5 +1,7 @@
import { isUndefined } from '@sniptt/guards';
+import { getMeetingEndTime } from 'src/logic-functions/domain/get-meeting-end-time.util';
+
export const hasMeetingEnded = ({
startsAt,
endsAt,
@@ -11,22 +13,11 @@ export const hasMeetingEnded = ({
now: Date;
startGraceHours?: number;
}): boolean => {
- if (!isUndefined(endsAt)) {
- const meetingEndTime = new Date(endsAt).getTime();
-
- if (!Number.isNaN(meetingEndTime)) {
- return meetingEndTime <= now.getTime();
- }
- }
-
- if (isUndefined(startsAt)) {
- return false;
- }
-
- const meetingStartTime = new Date(startsAt).getTime();
+ const meetingEndTime = getMeetingEndTime({
+ startsAt,
+ endsAt,
+ startGraceHours,
+ });
- return (
- !Number.isNaN(meetingStartTime) &&
- meetingStartTime + startGraceHours * 60 * 60 * 1000 <= now.getTime()
- );
+ return !isUndefined(meetingEndTime) && meetingEndTime <= now.getTime();
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/resolve-call-recording-request-follow-up.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/resolve-call-recording-request-follow-up.util.ts
new file mode 100644
index 00000000000..897fb4d0735
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/resolve-call-recording-request-follow-up.util.ts
@@ -0,0 +1,232 @@
+import { isUndefined } from '@sniptt/guards';
+
+import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';
+import { type CalendarEventRecord } from 'src/logic-functions/types/calendar-event-record.type';
+import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';
+import { getMeetingEndTime } from 'src/logic-functions/domain/get-meeting-end-time.util';
+import { hasMeetingEnded } from 'src/logic-functions/domain/has-meeting-ended.util';
+
+const BOT_NEVER_SCHEDULED_FAILURE_REASON = 'bot_never_scheduled';
+const BOT_SCHEDULE_OUTCOME_UNKNOWN_FAILURE_REASON =
+ 'bot_schedule_outcome_unknown';
+
+// A booking attempt this recent may still be running; acting now would race it.
+const FIRST_TRY_GRACE_MS = 15 * MILLISECONDS_PER_MINUTE;
+
+// Mirrors the stale-state convergence lookback: past it no automatic pull
+// pass will resolve the row anymore, so keeping it pending only wastes runs.
+const UNRESOLVED_ATTEMPT_MAX_AGE_MS = 7 * 24 * 60 * MILLISECONDS_PER_MINUTE;
+
+// A canceled request's bot is chased until its meeting is over, or for a day
+// when the meeting time is unknown; past that, the daily orphaned bot cleanup
+// owns any bot left behind.
+const CANCELED_BOT_FOLLOW_UP_HOURS = 24;
+
+export type CallRecordingRequestFollowUp =
+ | { action: 'none'; reason: string }
+ | { action: 'check-again'; reason: string; checkAt: Date }
+ | { action: 'book-bot'; calendarEvent: CalendarEventRecord }
+ | { action: 'mark-failed'; failureReason: string }
+ | { action: 'cancel-bot'; externalBotId: string }
+ | { action: 'find-and-cancel-bot' };
+
+export const resolveCallRecordingRequestFollowUp = ({
+ callRecording,
+ calendarEvent,
+ now,
+}: {
+ callRecording: CallRecordingRecord;
+ calendarEvent: CalendarEventRecord | undefined;
+ now: Date;
+}): CallRecordingRequestFollowUp => {
+ if (
+ callRecording.recordingRequestStatus === CallRecordingRequestStatus.CANCELED
+ ) {
+ return resolveCanceledRequestFollowUp({
+ callRecording,
+ calendarEvent,
+ now,
+ });
+ }
+
+ if (
+ callRecording.recordingRequestStatus ===
+ CallRecordingRequestStatus.REQUESTED &&
+ callRecording.status === CallRecordingStatus.SCHEDULED &&
+ isUndefined(callRecording.externalBotId)
+ ) {
+ return resolvePendingRequestFollowUp({ callRecording, calendarEvent, now });
+ }
+
+ return { action: 'none', reason: 'request is not waiting on Recall' };
+};
+
+const resolvePendingRequestFollowUp = ({
+ callRecording,
+ calendarEvent,
+ now,
+}: {
+ callRecording: CallRecordingRecord;
+ calendarEvent: CalendarEventRecord | undefined;
+ now: Date;
+}): CallRecordingRequestFollowUp => {
+ if (isUndefined(calendarEvent)) {
+ return { action: 'none', reason: 'no calendar event to book a bot for' };
+ }
+
+ const meetingEndTime = getMeetingEndTime(calendarEvent);
+
+ if (isUndefined(meetingEndTime) || meetingEndTime > now.getTime()) {
+ const firstTryGraceEnd = getFirstTryGraceEnd({
+ botScheduleAttemptedAt: callRecording.botScheduleAttemptedAt,
+ now,
+ });
+
+ if (!isUndefined(firstTryGraceEnd)) {
+ return {
+ action: 'check-again',
+ reason: 'a bot booking may still be running',
+ checkAt: firstTryGraceEnd,
+ };
+ }
+
+ return { action: 'book-bot', calendarEvent };
+ }
+
+ // Only an absent attempt marker proves no POST reached Recall; a marked row
+ // may have a bot that joined and recorded before the id write-back was lost,
+ // so it keeps its recovery chance until the convergence lookback has passed.
+ if (isUndefined(callRecording.botScheduleAttemptedAt)) {
+ return {
+ action: 'mark-failed',
+ failureReason: BOT_NEVER_SCHEDULED_FAILURE_REASON,
+ };
+ }
+
+ const convergenceDeadline = meetingEndTime + UNRESOLVED_ATTEMPT_MAX_AGE_MS;
+
+ if (convergenceDeadline <= now.getTime()) {
+ return {
+ action: 'mark-failed',
+ failureReason: BOT_SCHEDULE_OUTCOME_UNKNOWN_FAILURE_REASON,
+ };
+ }
+
+ return {
+ action: 'check-again',
+ reason: 'waiting for Recall webhooks to settle the last booking attempt',
+ checkAt: new Date(convergenceDeadline),
+ };
+};
+
+const resolveCanceledRequestFollowUp = ({
+ callRecording,
+ calendarEvent,
+ now,
+}: {
+ callRecording: CallRecordingRecord;
+ calendarEvent: CalendarEventRecord | undefined;
+ now: Date;
+}): CallRecordingRequestFollowUp => {
+ if (
+ !isNonTerminalCallRecordingStatus(callRecording.status) ||
+ !canCanceledRequestBotStillJoin({ callRecording, calendarEvent, now })
+ ) {
+ return { action: 'none', reason: 'no bot left to stop' };
+ }
+
+ if (!isUndefined(callRecording.externalBotId)) {
+ return { action: 'cancel-bot', externalBotId: callRecording.externalBotId };
+ }
+
+ if (isUndefined(callRecording.botScheduleAttemptedAt)) {
+ return { action: 'none', reason: 'request never reached Recall' };
+ }
+
+ const firstTryGraceEnd = getFirstTryGraceEnd({
+ botScheduleAttemptedAt: callRecording.botScheduleAttemptedAt,
+ now,
+ });
+
+ if (!isUndefined(firstTryGraceEnd)) {
+ return {
+ action: 'check-again',
+ reason: 'a bot booking may still be running',
+ checkAt: firstTryGraceEnd,
+ };
+ }
+
+ return { action: 'find-and-cancel-bot' };
+};
+
+const getFirstTryGraceEnd = ({
+ botScheduleAttemptedAt,
+ now,
+}: {
+ botScheduleAttemptedAt: string | undefined;
+ now: Date;
+}): Date | undefined => {
+ if (isUndefined(botScheduleAttemptedAt)) {
+ return undefined;
+ }
+
+ const attemptedTime = new Date(botScheduleAttemptedAt).getTime();
+ const elapsedMilliseconds = now.getTime() - attemptedTime;
+
+ // A future timestamp means clock skew or corrupt data, not a running attempt.
+ if (
+ Number.isNaN(attemptedTime) ||
+ elapsedMilliseconds < 0 ||
+ elapsedMilliseconds >= FIRST_TRY_GRACE_MS
+ ) {
+ return undefined;
+ }
+
+ return new Date(attemptedTime + FIRST_TRY_GRACE_MS);
+};
+
+const canCanceledRequestBotStillJoin = ({
+ callRecording,
+ calendarEvent,
+ now,
+}: {
+ callRecording: CallRecordingRecord;
+ calendarEvent: CalendarEventRecord | undefined;
+ now: Date;
+}): boolean => {
+ const meetingStartsAt = calendarEvent?.startsAt;
+
+ if (!isUndefined(meetingStartsAt)) {
+ return !hasMeetingEnded({
+ startsAt: meetingStartsAt,
+ endsAt: calendarEvent?.endsAt,
+ now,
+ startGraceHours: CANCELED_BOT_FOLLOW_UP_HOURS,
+ });
+ }
+
+ // Without a meeting time (its calendar event was deleted), the cancellation
+ // bounds the chase; updatedAt tracks the cancellation write.
+ const canceledAt = callRecording.updatedAt ?? callRecording.createdAt;
+
+ if (isUndefined(canceledAt)) {
+ return false;
+ }
+
+ return (
+ new Date(canceledAt).getTime() +
+ CANCELED_BOT_FOLLOW_UP_HOURS * 60 * MILLISECONDS_PER_MINUTE >
+ now.getTime()
+ );
+};
+
+const isNonTerminalCallRecordingStatus = (
+ status: string | undefined,
+): boolean => {
+ return NON_TERMINAL_CALL_RECORDING_STATUSES.some(
+ (nonTerminalStatus) => nonTerminalStatus === status,
+ );
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts
index ab21bd9656f..e9457364512 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts
@@ -73,6 +73,7 @@ type CallRecordingNode = {
endedAt?: string | null;
calendarEventId?: string | null;
externalBotId?: string | null;
+ botScheduleAttemptedAt?: string | null;
externalRecordingId?: string | null;
callRecorderFailureReason?: string | null;
};
@@ -223,8 +224,10 @@ class FakeCoreApiClient {
const updatedCalendarEvents = this.calendarEvents.filter(
(calendarEvent) =>
filter.id.in.includes(calendarEvent.id) &&
- filter.callRecorderPreference.is === 'NULL' &&
- (calendarEvent.callRecorderPreference ?? null) === null,
+ (filter.callRecorderPreference.is === 'NULL'
+ ? (calendarEvent.callRecorderPreference ?? null) === null
+ : calendarEvent.callRecorderPreference ===
+ filter.callRecorderPreference.eq),
);
for (const calendarEvent of updatedCalendarEvents) {
@@ -604,6 +607,47 @@ describe('reconcileCallRecorderForCalendarEventIds', () => {
]);
});
+ it('clears recordingOn before an enqueue failure and re-arms the canceled request on retry', async () => {
+ const client = buildFakeCoreApiClient({
+ calendarEvents: [
+ buildCalendarEvent({ isCanceled: true, callRecorderPreference: 'ON' }),
+ ],
+ callRecordings: [
+ {
+ id: 'call-recording-1',
+ status: 'SCHEDULED',
+ recordingRequestStatus: 'REQUESTED',
+ calendarEventId: 'calendar-event-1',
+ botScheduleAttemptedAt: NOW.toISOString(),
+ },
+ ],
+ });
+ const enqueueError = new Error('queue unavailable');
+ enqueueJobsMock.mockRejectedValueOnce(enqueueError);
+ const reconcile = () =>
+ reconcileCallRecorderForCalendarEventIds({
+ client: client as unknown as CoreApiClient,
+ calendarEventIds: ['calendar-event-1'],
+ now: NOW,
+ });
+
+ await expect(reconcile()).rejects.toThrow(enqueueError.message);
+ expect(client.callRecordings[0].recordingRequestStatus).toBe('CANCELED');
+ expect(client.calendarEvents[0].callRecorderPreference).toBeNull();
+
+ enqueueJobsMock.mockClear();
+ await reconcile();
+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ jobs: [
+ expect.objectContaining({
+ payload: { callRecordingId: 'call-recording-1', attempt: 0 },
+ }),
+ ],
+ }),
+ );
+ });
+
it('cancels an existing scheduled request when the policy no longer requests a bot', async () => {
const client = buildFakeCoreApiClient({
calendarEvents: [
@@ -649,7 +693,7 @@ describe('reconcileCallRecorderForCalendarEventIds', () => {
]);
});
- it('persists the cancel intent and leaves the bot for the planned stale-state cron when the Recall cancel fails', async () => {
+ it('persists the cancel intent and leaves the bot for recovery when the Recall cancel fails', async () => {
vi.useFakeTimers();
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ detail: 'server error' }), {
@@ -1071,7 +1115,7 @@ describe('reconcileCallRecorderForCalendarEventIds', () => {
]);
});
- it('clears the stale bot id for the stale-state cron to re-create when the existing Recall bot no longer exists', async () => {
+ it('clears the stale bot id for recovery to re-create when the existing Recall bot no longer exists', async () => {
fetchMock.mockImplementation(
async (requestUrl: string, requestInit: RequestInit) => {
if (requestInit.method === 'PATCH') {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/retry-failed-recall-cancellations.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/retry-failed-recall-cancellations.test.ts
deleted file mode 100644
index 3c1bf650418..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/retry-failed-recall-cancellations.test.ts
+++ /dev/null
@@ -1,542 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { retryFailedRecallCancellations } from 'src/logic-functions/flows/retry-failed-recall-cancellations.util';
-
-const BASE_URL = 'https://us-west-2.recall.ai/api/v1';
-const NOW = new Date('2026-01-01T12:00:00.000Z');
-const WORKSPACE_ID = '123e4567-e89b-12d3-a456-426614174000';
-
-const buildAccessToken = (payload: Record<string, unknown>): string =>
- [
- Buffer.from(JSON.stringify({ alg: 'none' })).toString('base64url'),
- Buffer.from(JSON.stringify(payload)).toString('base64url'),
- 'signature',
- ].join('.');
-
-type CallRecordingNode = {
- id: string;
- recordingRequestStatus?: string | null;
- status?: string | null;
- createdAt?: string | null;
- updatedAt?: string | null;
- calendarEventId?: string | null;
- externalBotId?: string | null;
-};
-
-type CalendarEventNode = {
- id: string;
- startsAt?: string | null;
- endsAt?: string | null;
-};
-
-class FakeCoreApiClient {
- callRecordings: CallRecordingNode[];
- callRecordingQueryResponses: CallRecordingNode[][] = [];
- calendarEvents: CalendarEventNode[];
- filters: Array<Record<string, unknown>> = [];
- conditionalMutationFilters: Array<Record<string, unknown>> = [];
- mutations: Array<{ id: string; data: Record<string, unknown> }> = [];
-
- constructor(
- callRecordings: CallRecordingNode[],
- calendarEvents: CalendarEventNode[] = [],
- ) {
- this.callRecordings = callRecordings;
- this.calendarEvents = calendarEvents;
- }
-
- async query(query: any): Promise<any> {
- if (query.callRecordings !== undefined) {
- this.filters.push(query.callRecordings.__args.filter);
-
- return {
- callRecordings: buildConnection(
- this.callRecordingQueryResponses.shift() ?? this.callRecordings,
- ),
- };
- }
-
- if (query.calendarEvents !== undefined) {
- const calendarEventIds = query.calendarEvents.__args.filter.id.in;
-
- return {
- calendarEvents: buildConnection(
- this.calendarEvents.filter((calendarEvent) =>
- calendarEventIds.includes(calendarEvent.id),
- ),
- ),
- };
- }
-
- throw new Error(`Unhandled query: ${JSON.stringify(query)}`);
- }
-
- async mutation(mutation: any): Promise<any> {
- if (mutation.updateCallRecordings !== undefined) {
- const { filter, data } = mutation.updateCallRecordings.__args;
-
- this.conditionalMutationFilters.push(filter);
-
- const matchingCallRecordings = this.callRecordings.filter(
- (callRecording) =>
- callRecording.id === filter.id.eq &&
- (filter.recordingRequestStatus === undefined ||
- callRecording.recordingRequestStatus ===
- filter.recordingRequestStatus.eq) &&
- filter.status.in.includes(callRecording.status) &&
- (filter.externalBotId.is === 'NULL'
- ? callRecording.externalBotId === null
- : callRecording.externalBotId === filter.externalBotId.eq),
- );
-
- matchingCallRecordings.forEach((callRecording) => {
- this.mutations.push({ id: callRecording.id, data });
- Object.assign(callRecording, data);
- });
-
- return {
- updateCallRecordings: matchingCallRecordings.map(({ id }) => ({ id })),
- };
- }
-
- const { id, data } = mutation.updateCallRecording.__args;
-
- this.mutations.push({ id, data });
- const callRecording = this.callRecordings.find(
- (candidateCallRecording) => candidateCallRecording.id === id,
- );
-
- if (callRecording !== undefined) {
- Object.assign(callRecording, data);
- }
-
- return { updateCallRecording: { id } };
- }
-}
-
-const buildConnection = <Node>(nodes: Node[]) => ({
- pageInfo: { hasNextPage: false, endCursor: undefined },
- edges: nodes.map((node) => ({ node })),
-});
-
-const fetchMock = vi.fn();
-
-const buildJsonResponse = (status: number) => ({
- ok: status < 400,
- status,
- json: async () => ({}),
-});
-
-describe('retryFailedRecallCancellations', () => {
- beforeEach(() => {
- vi.spyOn(console, 'warn').mockImplementation(() => {});
- vi.stubGlobal('fetch', fetchMock);
- vi.stubEnv('RECALL_API_KEY', 'recall-api-key');
- vi.stubEnv('RECALL_REGION', 'us-west-2');
- vi.stubEnv(
- 'TWENTY_APP_ACCESS_TOKEN',
- buildAccessToken({ workspaceId: WORKSPACE_ID }),
- );
- fetchMock.mockReset();
- fetchMock.mockImplementation(async () => buildJsonResponse(204));
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- vi.unstubAllEnvs();
- vi.restoreAllMocks();
- });
-
- it('queries canceled non-terminal recordings including rows missing a bot id', async () => {
- const client = new FakeCoreApiClient([]);
-
- await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(client.filters).toEqual([
- expect.objectContaining({
- recordingRequestStatus: { eq: 'CANCELED' },
- status: {
- in: ['SCHEDULED', 'JOINING', 'RECORDING', 'PROCESSING'],
- },
- }),
- ]);
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it('cancels the bot and clears the id when the Recall cancel succeeds', async () => {
- const client = new FakeCoreApiClient([
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- externalBotId: 'recall-bot-1',
- },
- ]);
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(fetchMock).toHaveBeenCalledWith(
- `${BASE_URL}/bot/recall-bot-1/`,
- expect.objectContaining({ method: 'DELETE' }),
- );
- expect(client.mutations).toEqual([
- {
- id: 'call-recording-1',
- data: {
- externalBotId: null,
- botScheduleAttemptedAt: null,
- botScheduleIdempotencyKey: null,
- },
- },
- ]);
- expect(result.canceledExternalBotCallRecordingIds).toEqual([
- 'call-recording-1',
- ]);
- });
-
- it('keeps the bot id when the Recall cancel fails so the next run retries', async () => {
- fetchMock.mockImplementation(async () => buildJsonResponse(400));
- const client = new FakeCoreApiClient([
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- externalBotId: 'recall-bot-1',
- },
- ]);
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(fetchMock).toHaveBeenCalledWith(
- `${BASE_URL}/bot/recall-bot-1/leave_call/`,
- expect.objectContaining({ method: 'POST' }),
- );
- expect(client.mutations).toEqual([]);
- expect(result.canceledExternalBotCallRecordingIds).toEqual([]);
- });
-
- it('does not cancel a bot after its request was reactivated', async () => {
- const canceledCallRecording = {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- externalBotId: 'recall-bot-1',
- };
- const client = new FakeCoreApiClient([canceledCallRecording]);
- client.callRecordingQueryResponses = [
- [canceledCallRecording],
- [
- {
- ...canceledCallRecording,
- recordingRequestStatus: 'REQUESTED',
- },
- ],
- ];
-
- await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it('persists a metadata-recovered bot id when cancellation fails after its calendar event was deleted', async () => {
- const client = new FakeCoreApiClient([
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- calendarEventId: 'deleted-calendar-event',
- externalBotId: null,
- },
- ]);
- fetchMock
- .mockResolvedValueOnce({
- ...buildJsonResponse(200),
- json: async () => ({
- next: null,
- results: [
- {
- id: 'recall-bot-recovered',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- },
- ],
- }),
- })
- .mockResolvedValueOnce(buildJsonResponse(400))
- .mockResolvedValueOnce(buildJsonResponse(400));
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- const listRequestUrl = fetchMock.mock.calls[0][0];
- const listRequestParameters = new URL(listRequestUrl).searchParams;
-
- expect(listRequestParameters.has('join_at_after')).toBe(false);
- expect(listRequestParameters.has('join_at_before')).toBe(false);
- expect(fetchMock).toHaveBeenCalledWith(
- `${BASE_URL}/bot/recall-bot-recovered/leave_call/`,
- expect.objectContaining({ method: 'POST' }),
- );
- expect(client.mutations).toEqual([
- {
- id: 'call-recording-1',
- data: { externalBotId: 'recall-bot-recovered' },
- },
- ]);
- expect(client.callRecordings[0].externalBotId).toBe(
- 'recall-bot-recovered',
- );
- expect(client.conditionalMutationFilters).toEqual([
- expect.objectContaining({
- recordingRequestStatus: { eq: 'CANCELED' },
- status: { in: ['SCHEDULED', 'JOINING', 'RECORDING', 'PROCESSING'] },
- externalBotId: { is: 'NULL' },
- }),
- ]);
- expect(result.canceledExternalBotCallRecordingIds).toEqual([]);
- });
-
- it('stops looking up a botless cancellation without a calendar event once it ages past the recovery window', async () => {
- const client = new FakeCoreApiClient([
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- createdAt: '2026-01-01T11:00:00.000Z',
- calendarEventId: null,
- externalBotId: null,
- },
- ]);
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: new Date('2026-01-02T12:00:00.000Z'),
- });
-
- expect(fetchMock).not.toHaveBeenCalled();
- expect(client.mutations).toEqual([]);
- expect(result.canceledExternalBotCallRecordingIds).toEqual([]);
- });
-
- it('recovers a long-scheduled cancellation whose recent cancellation is within the recovery window', async () => {
- const client = new FakeCoreApiClient([
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- createdAt: '2026-01-01T11:00:00.000Z',
- updatedAt: '2026-01-02T11:30:00.000Z',
- calendarEventId: null,
- externalBotId: null,
- },
- ]);
- fetchMock.mockImplementation(
- async (requestUrl: string, requestInit?: { method?: string }) => {
- if (requestInit?.method === 'DELETE') {
- return buildJsonResponse(204);
- }
-
- if (requestUrl.startsWith(`${BASE_URL}/bot/?`)) {
- return {
- ...buildJsonResponse(200),
- json: async () => ({
- next: null,
- results: [
- {
- id: 'recall-bot-recovered',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- },
- ],
- }),
- };
- }
-
- throw new Error(`Unhandled fetch: ${requestUrl}`);
- },
- );
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: new Date('2026-01-02T12:00:00.000Z'),
- });
-
- expect(fetchMock).toHaveBeenCalledWith(
- `${BASE_URL}/bot/recall-bot-recovered/`,
- expect.objectContaining({ method: 'DELETE' }),
- );
- expect(result.canceledExternalBotCallRecordingIds).toEqual([
- 'call-recording-1',
- ]);
- });
-
- it('still recovers a recently created botless cancellation without a calendar event', async () => {
- const client = new FakeCoreApiClient([
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- createdAt: '2026-01-01T11:00:00.000Z',
- calendarEventId: null,
- externalBotId: null,
- },
- ]);
- fetchMock.mockImplementation(
- async (requestUrl: string, requestInit?: { method?: string }) => {
- if (requestInit?.method === 'DELETE') {
- return buildJsonResponse(204);
- }
-
- if (requestUrl.startsWith(`${BASE_URL}/bot/?`)) {
- return {
- ...buildJsonResponse(200),
- json: async () => ({
- next: null,
- results: [
- {
- id: 'recall-bot-recovered',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- },
- ],
- }),
- };
- }
-
- throw new Error(`Unhandled fetch: ${requestUrl}`);
- },
- );
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(fetchMock).toHaveBeenCalledWith(
- `${BASE_URL}/bot/recall-bot-recovered/`,
- expect.objectContaining({ method: 'DELETE' }),
- );
- expect(result.canceledExternalBotCallRecordingIds).toEqual([
- 'call-recording-1',
- ]);
- });
-
- it('does not claim a listed bot for a cancellation whose recovery window elapsed', async () => {
- const client = new FakeCoreApiClient([
- {
- id: 'call-recording-recent',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- createdAt: '2026-01-02T11:30:00.000Z',
- calendarEventId: null,
- externalBotId: null,
- },
- {
- id: 'call-recording-aged',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- createdAt: '2026-01-01T11:00:00.000Z',
- calendarEventId: null,
- externalBotId: null,
- },
- ]);
- fetchMock.mockImplementation(
- async (requestUrl: string, requestInit?: { method?: string }) => {
- if (requestInit?.method === 'DELETE') {
- return buildJsonResponse(204);
- }
-
- if (requestUrl.startsWith(`${BASE_URL}/bot/?`)) {
- return {
- ...buildJsonResponse(200),
- json: async () => ({
- next: null,
- results: [
- {
- id: 'recall-bot-recent',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-recent',
- },
- },
- {
- id: 'recall-bot-aged',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-aged',
- },
- },
- ],
- }),
- };
- }
-
- throw new Error(`Unhandled fetch: ${requestUrl}`);
- },
- );
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: new Date('2026-01-02T12:00:00.000Z'),
- });
-
- expect(result.canceledExternalBotCallRecordingIds).toEqual([
- 'call-recording-recent',
- ]);
- expect(fetchMock).not.toHaveBeenCalledWith(
- `${BASE_URL}/bot/recall-bot-aged/`,
- expect.objectContaining({ method: 'DELETE' }),
- );
- });
-
- it('does not repeatedly look up botless cancellations after their meeting ended', async () => {
- const client = new FakeCoreApiClient(
- [
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- calendarEventId: 'calendar-event-1',
- externalBotId: null,
- },
- ],
- [
- {
- id: 'calendar-event-1',
- startsAt: '2026-01-01T10:00:00.000Z',
- endsAt: '2026-01-01T11:00:00.000Z',
- },
- ],
- );
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(fetchMock).not.toHaveBeenCalled();
- expect(client.mutations).toEqual([]);
- expect(result.canceledExternalBotCallRecordingIds).toEqual([]);
- });
-});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bots-for-pending-call-recordings.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bots-for-pending-call-recordings.test.ts
deleted file mode 100644
index d4b397ff09c..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bots-for-pending-call-recordings.test.ts
+++ /dev/null
@@ -1,561 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';
-import { scheduleRecallBotsForPendingCallRecordings } from 'src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util';
-import { computeRecallBotCreationIdempotencyKey } from 'src/logic-functions/recall-api/schedule-recall-bot.util';
-
-const enqueueJobsMock = vi.hoisted(() => vi.fn());
-
-vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- enqueueJobs: enqueueJobsMock,
-}));
-
-const NOW = new Date('2026-01-01T12:00:00.000Z');
-const WORKSPACE_ID = '123e4567-e89b-12d3-a456-426614174000';
-const UPCOMING_STARTS_AT = '2026-01-01T13:00:00.000Z';
-const UPCOMING_ENDS_AT = '2026-01-01T14:00:00.000Z';
-const PAST_STARTS_AT = '2026-01-01T10:00:00.000Z';
-const PAST_ENDS_AT = '2026-01-01T11:00:00.000Z';
-const RECALL_BASE_URL = 'https://us-west-2.recall.ai/api/v1';
-const RECALL_CREATE_BOT_URL = `${RECALL_BASE_URL}/bot/`;
-const RECALL_LIST_BOTS_URL_PREFIX = `${RECALL_BASE_URL}/bot/?`;
-
-const buildAccessToken = (payload: Record<string, unknown>): string =>
- [
- Buffer.from(JSON.stringify({ alg: 'none' })).toString('base64url'),
- Buffer.from(JSON.stringify(payload)).toString('base64url'),
- 'signature',
- ].join('.');
-
-const fetchMock = vi.fn();
-
-type CallRecordingNode = {
- id: string;
- status?: string;
- recordingRequestStatus?: string | null;
- calendarEventId?: string | null;
- externalBotId?: string | null;
- botScheduleAttemptedAt?: string | null;
- botScheduleIdempotencyKey?: string | null;
- callRecorderFailureReason?: string | null;
-};
-
-type CalendarEventNode = {
- id: string;
- startsAt?: string | null;
- endsAt?: string | null;
- iCalUid?: string | null;
- conferenceLink?: { primaryLinkUrl?: string | null } | null;
-};
-
-const matchesCallRecordingFilter = (
- callRecording: CallRecordingNode,
- filter: Record<string, { eq?: unknown; in?: unknown[]; is?: 'NULL' }>,
-): boolean =>
- Object.entries(filter).every(([field, condition]) => {
- const value = callRecording[field as keyof CallRecordingNode] ?? null;
-
- if (condition.is === 'NULL') {
- return value === null || value === '';
- }
-
- if (condition.in !== undefined) {
- return condition.in.includes(value);
- }
-
- if ('eq' in condition) {
- return value === condition.eq;
- }
-
- throw new Error(
- `Unhandled filter on ${field}: ${JSON.stringify(condition)}`,
- );
- });
-
-class FakeCoreApiClient {
- callRecordings: CallRecordingNode[];
- calendarEvents: CalendarEventNode[];
-
- constructor({
- callRecordings = [],
- calendarEvents = [],
- }: {
- callRecordings?: CallRecordingNode[];
- calendarEvents?: CalendarEventNode[];
- }) {
- this.callRecordings = callRecordings;
- this.calendarEvents = calendarEvents;
- }
-
- async query(query: any): Promise<any> {
- if (query.callRecordings !== undefined) {
- const filter = query.callRecordings.__args.filter;
- const matches =
- filter.id?.in !== undefined
- ? this.callRecordings.filter((callRecording) =>
- filter.id.in.includes(callRecording.id),
- )
- : this.callRecordings.filter(
- (callRecording) =>
- callRecording.recordingRequestStatus ===
- filter.recordingRequestStatus.eq &&
- callRecording.status === filter.status.eq,
- );
-
- return { callRecordings: buildConnection(matches) };
- }
-
- if (query.calendarEvents !== undefined) {
- const calendarEventIds = query.calendarEvents.__args.filter.id.in;
-
- return {
- calendarEvents: buildConnection(
- this.calendarEvents.filter((calendarEvent) =>
- calendarEventIds.includes(calendarEvent.id),
- ),
- ),
- };
- }
-
- throw new Error(`Unhandled query: ${JSON.stringify(query)}`);
- }
-
- async mutation(mutation: any): Promise<any> {
- if (mutation.updateCallRecordings !== undefined) {
- const { filter, data } = mutation.updateCallRecordings.__args;
- const matchingCallRecordings = this.callRecordings.filter(
- (callRecording) => matchesCallRecordingFilter(callRecording, filter),
- );
-
- matchingCallRecordings.forEach((callRecording) =>
- Object.assign(callRecording, data),
- );
-
- return {
- updateCallRecordings: matchingCallRecordings.map(({ id }) => ({ id })),
- };
- }
-
- if (mutation.updateCallRecording !== undefined) {
- const { id, data } = mutation.updateCallRecording.__args;
- const callRecording = this.callRecordings.find(
- (candidate) => candidate.id === id,
- );
-
- if (callRecording !== undefined) {
- Object.assign(callRecording, data);
- }
-
- return { updateCallRecording: { id } };
- }
-
- throw new Error(`Unhandled mutation: ${JSON.stringify(mutation)}`);
- }
-}
-
-const buildConnection = <Node>(nodes: Node[]) => ({
- pageInfo: { hasNextPage: false, endCursor: undefined },
- edges: nodes.map((node) => ({ node })),
-});
-
-const buildPendingCallRecording = (
- overrides: Partial<CallRecordingNode> = {},
-): CallRecordingNode => ({
- id: 'call-recording-1',
- status: 'SCHEDULED',
- recordingRequestStatus: 'REQUESTED',
- calendarEventId: 'calendar-event-1',
- externalBotId: null,
- ...overrides,
-});
-
-const buildCalendarEvent = (
- overrides: Partial<CalendarEventNode> = {},
-): CalendarEventNode => ({
- id: 'calendar-event-1',
- startsAt: UPCOMING_STARTS_AT,
- endsAt: UPCOMING_ENDS_AT,
- iCalUid: 'calendar-event-uid',
- conferenceLink: { primaryLinkUrl: 'https://meet.example.com/customer-sync' },
- ...overrides,
-});
-
-const stubRecallApi = ({
- listStatus = 200,
- createBotStatus = 201,
-}: {
- listStatus?: number;
- createBotStatus?: number;
-} = {}) => {
- fetchMock.mockImplementation(
- async (requestUrl: string, requestInit?: { method?: string }) => {
- const method = requestInit?.method ?? 'GET';
-
- if (
- method === 'GET' &&
- requestUrl.startsWith(RECALL_LIST_BOTS_URL_PREFIX)
- ) {
- return new Response(JSON.stringify({ next: null, results: [] }), {
- status: listStatus,
- });
- }
-
- if (method === 'POST' && requestUrl === RECALL_CREATE_BOT_URL) {
- return new Response(JSON.stringify({ id: 'recall-bot-1' }), {
- status: createBotStatus,
- });
- }
-
- throw new Error(`Unhandled fetch in test: ${method} ${requestUrl}`);
- },
- );
-};
-
-const listBotRequestUrls = (): string[] =>
- fetchMock.mock.calls
- .filter(
- ([requestUrl, requestInit]) =>
- (requestInit?.method ?? 'GET') === 'GET' &&
- requestUrl.startsWith(RECALL_LIST_BOTS_URL_PREFIX),
- )
- .map(([requestUrl]) => requestUrl);
-
-const createBotCalls = () =>
- fetchMock.mock.calls.filter(
- ([, requestInit]) => requestInit?.method === 'POST',
- );
-
-describe('scheduleRecallBotsForPendingCallRecordings', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(NOW);
- vi.spyOn(console, 'warn').mockImplementation(() => {});
- vi.stubGlobal('fetch', fetchMock);
- vi.stubEnv('RECALL_API_KEY', 'recall-api-key');
- vi.stubEnv('RECALL_REGION', 'us-west-2');
- vi.stubEnv('CALL_RECORDER_USE_WORKSPACE_LOGO', 'false');
- vi.stubEnv(
- 'TWENTY_APP_ACCESS_TOKEN',
- buildAccessToken({ workspaceId: WORKSPACE_ID }),
- );
- fetchMock.mockReset();
- enqueueJobsMock.mockReset();
- stubRecallApi();
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- vi.unstubAllEnvs();
- vi.useRealTimers();
- vi.restoreAllMocks();
- });
-
- it('schedules a bot and writes the id for an upcoming pending recording', async () => {
- const client = new FakeCoreApiClient({
- callRecordings: [buildPendingCallRecording()],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.scheduledCallRecordingIds).toEqual(['call-recording-1']);
- expect(result.attachedCallRecordingIds).toEqual([]);
- // A row that never attempted a bot creation needs no Recall lookup.
- expect(listBotRequestUrls()).toHaveLength(0);
- expect(client.callRecordings[0].botScheduleAttemptedAt).toBe(
- NOW.toISOString(),
- );
- expect(createBotCalls()).toHaveLength(1);
- const [requestUrl, requestInit] = createBotCalls()[0];
- expect(requestUrl).toBe(RECALL_CREATE_BOT_URL);
- expect(requestInit.headers).toMatchObject({
- Authorization: 'Token recall-api-key',
- });
- expect(JSON.parse(requestInit.body)).toMatchObject({
- meeting_url: 'https://meet.example.com/customer-sync',
- join_at: '2026-01-01T12:59:00.000Z',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- });
- expect(client.callRecordings[0].externalBotId).toBe('recall-bot-1');
- });
-
- it('defers scheduling when the existing-bot lookup fails so no duplicate bot is created', async () => {
- stubRecallApi({ listStatus: 400 });
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2026-01-01T11:55:00.000Z',
- }),
- ],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.attachedCallRecordingIds).toEqual([]);
- expect(result.scheduledCallRecordingIds).toEqual([]);
- expect(createBotCalls()).toHaveLength(0);
- expect(client.callRecordings[0].externalBotId).toBeNull();
- });
-
- it('re-sends the creation without any Recall lookup when the stored idempotency key still matches', async () => {
- const unchangedIdempotencyKey = computeRecallBotCreationIdempotencyKey({
- meetingUrl: 'https://meet.example.com/customer-sync',
- joinAt: computeRecallBotJoinAt(UPCOMING_STARTS_AT),
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- attemptedAt: '2026-01-01T11:55:00.000Z',
- });
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2026-01-01T11:55:00.000Z',
- botScheduleIdempotencyKey: unchangedIdempotencyKey,
- }),
- ],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(listBotRequestUrls()).toHaveLength(0);
- expect(result.scheduledCallRecordingIds).toEqual(['call-recording-1']);
- const [, requestInit] = createBotCalls()[0];
- expect(requestInit.headers).toMatchObject({
- 'Idempotency-Key': unchangedIdempotencyKey,
- });
- expect(client.callRecordings[0].externalBotId).toBe('recall-bot-1');
- // The first attempt timestamp survives the re-send so repeated unknown
- // outcomes age out of the resend window.
- expect(client.callRecordings[0].botScheduleAttemptedAt).toBe(
- '2026-01-01T11:55:00.000Z',
- );
- });
-
- it('falls back to the Recall lookup when the recorded attempt is too old to trust its idempotency key', async () => {
- const unchangedIdempotencyKey = computeRecallBotCreationIdempotencyKey({
- meetingUrl: 'https://meet.example.com/customer-sync',
- joinAt: computeRecallBotJoinAt(UPCOMING_STARTS_AT),
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- attemptedAt: '2025-12-30T12:00:00.000Z',
- });
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2025-12-30T12:00:00.000Z',
- botScheduleIdempotencyKey: unchangedIdempotencyKey,
- }),
- ],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(listBotRequestUrls()).toHaveLength(1);
- expect(result.scheduledCallRecordingIds).toEqual(['call-recording-1']);
- });
-
- it('falls back to the Recall lookup when the meeting moved since the recorded attempt', async () => {
- const staleIdempotencyKey = computeRecallBotCreationIdempotencyKey({
- meetingUrl: 'https://meet.example.com/customer-sync',
- joinAt: computeRecallBotJoinAt('2026-01-01T09:00:00.000Z'),
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- attemptedAt: '2026-01-01T11:55:00.000Z',
- });
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2026-01-01T11:55:00.000Z',
- botScheduleIdempotencyKey: staleIdempotencyKey,
- }),
- ],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(listBotRequestUrls()).toHaveLength(1);
- expect(result.scheduledCallRecordingIds).toEqual(['call-recording-1']);
- });
-
- it('re-schedules an ambiguous recording when the lookup confirms no bot exists', async () => {
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2026-01-01T11:55:00.000Z',
- }),
- ],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(listBotRequestUrls()).toHaveLength(1);
- expect(result.scheduledCallRecordingIds).toEqual(['call-recording-1']);
- expect(createBotCalls()).toHaveLength(1);
- expect(client.callRecordings[0].externalBotId).toBe('recall-bot-1');
- });
-
- it('does not report a recording as scheduled when Recall scheduling fails', async () => {
- stubRecallApi({ createBotStatus: 500 });
- const client = new FakeCoreApiClient({
- callRecordings: [buildPendingCallRecording()],
- calendarEvents: [buildCalendarEvent()],
- });
-
- vi.useFakeTimers();
- const resultPromise = scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
- await vi.runAllTimersAsync();
- const result = await resultPromise;
-
- expect(result.scheduledCallRecordingIds).toEqual([]);
- // One scheduling attempt, retried to exhaustion on the wire.
- expect(createBotCalls()).toHaveLength(3);
- expect(client.callRecordings[0].externalBotId).toBeNull();
- });
-
- it('marks a recording failed when its meeting ended before any bot was scheduled', async () => {
- const client = new FakeCoreApiClient({
- callRecordings: [buildPendingCallRecording()],
- calendarEvents: [
- buildCalendarEvent({
- startsAt: PAST_STARTS_AT,
- endsAt: PAST_ENDS_AT,
- }),
- ],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.scheduledCallRecordingIds).toEqual([]);
- expect(result.markedFailedCallRecordingIds).toEqual(['call-recording-1']);
- expect(fetchMock).not.toHaveBeenCalled();
- expect(client.callRecordings[0].status).toBe('FAILED');
- expect(client.callRecordings[0].callRecorderFailureReason).toBe(
- 'bot_never_scheduled',
- );
- });
-
- it('keeps an ended recording with an unresolved attempt pending while convergence may still resolve it', async () => {
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2026-01-01T09:55:00.000Z',
- }),
- ],
- calendarEvents: [
- buildCalendarEvent({
- startsAt: PAST_STARTS_AT,
- endsAt: PAST_ENDS_AT,
- }),
- ],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.markedFailedCallRecordingIds).toEqual([]);
- expect(fetchMock).not.toHaveBeenCalled();
- expect(client.callRecordings[0].status).toBe('SCHEDULED');
- });
-
- it('fails an ended recording with an unresolved attempt once the convergence lookback has passed', async () => {
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2025-12-20T09:55:00.000Z',
- }),
- ],
- calendarEvents: [
- buildCalendarEvent({
- startsAt: '2025-12-20T10:00:00.000Z',
- endsAt: '2025-12-20T11:00:00.000Z',
- }),
- ],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.markedFailedCallRecordingIds).toEqual(['call-recording-1']);
- expect(fetchMock).not.toHaveBeenCalled();
- expect(client.callRecordings[0].status).toBe('FAILED');
- expect(client.callRecordings[0].callRecorderFailureReason).toBe(
- 'bot_schedule_outcome_unknown',
- );
- });
-
- it('leaves a recording untouched when its calendar event is missing', async () => {
- const client = new FakeCoreApiClient({
- callRecordings: [buildPendingCallRecording()],
- calendarEvents: [],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.markedFailedCallRecordingIds).toEqual([]);
- expect(fetchMock).not.toHaveBeenCalled();
- expect(client.callRecordings[0].status).toBe('SCHEDULED');
- });
-
- it('does nothing when every scheduled recording already has a bot', async () => {
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({ externalBotId: 'recall-bot-existing' }),
- ],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.scheduledCallRecordingIds).toEqual([]);
- expect(fetchMock).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-call-recording-request.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-call-recording-request.util.ts
index f156110ade2..d3a30900d26 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-call-recording-request.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-call-recording-request.util.ts
@@ -7,7 +7,6 @@ import { cancelRecallBot } from 'src/logic-functions/recall-api/cancel-recall-bo
import { clearCanceledRecallBot } from 'src/logic-functions/data/clear-canceled-recall-bot.util';
import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';
-// Intent-first: the stale-state cron finishes the Recall half when this call fails.
export const cancelCallRecordingRequest = async ({
client,
callRecording,
@@ -32,7 +31,7 @@ export const cancelCallRecordingRequest = async ({
if (!cancelResult.ok) {
console.warn(
- `[call-recorder] failed to cancel Recall bot for callRecording ${callRecording.id}, leaving it for the stale-state cron: ${cancelResult.errorMessage}`,
+ `[call-recorder] failed to cancel Recall bot for callRecording ${callRecording.id}, leaving it for the follow-up: ${cancelResult.errorMessage}`,
);
return;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/follow-up-call-recording-request.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/follow-up-call-recording-request.util.ts
new file mode 100644
index 00000000000..a1ff8f89d20
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/follow-up-call-recording-request.util.ts
@@ -0,0 +1,267 @@
+import { isUndefined } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { type CalendarEventRecord } from 'src/logic-functions/types/calendar-event-record.type';
+import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';
+import { computeCallRecordingRequestFollowUpRetryDelayMs } from 'src/logic-functions/domain/compute-call-recording-request-follow-up-retry-delay.util';
+import {
+ resolveCallRecordingRequestFollowUp,
+ type CallRecordingRequestFollowUp,
+} from 'src/logic-functions/domain/resolve-call-recording-request-follow-up.util';
+import { fetchCalendarEventsByIds } from 'src/logic-functions/data/fetch-calendar-events-by-ids.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 { updatePendingCallRecording } from 'src/logic-functions/data/update-pending-call-recording.util';
+import { cancelRecallBotForCanceledCallRecording } from 'src/logic-functions/flows/cancel-recall-bot-for-canceled-call-recording.util';
+import {
+ recoverPendingCallRecording,
+ type RecoverPendingCallRecordingResult,
+} from 'src/logic-functions/flows/recover-pending-call-recording.util';
+import { findScheduledRecallBotIdsByCallRecordingId } from 'src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util';
+
+export type FollowUpCallRecordingRequestResult =
+ | { status: 'settled'; outcome: string }
+ | { status: 'follow-up-again'; reason: string; dueAt: Date };
+
+type FollowUpActionResult =
+ | { status: 'done'; outcome: string }
+ | { status: 'failed'; reason: string };
+
+export const followUpCallRecordingRequest = async ({
+ client,
+ callRecordingId,
+ attempt,
+ now,
+}: {
+ client: CoreApiClient;
+ callRecordingId: string;
+ attempt: number;
+ now: Date;
+}): Promise<FollowUpCallRecordingRequestResult> => {
+ const callRecording = (
+ await findCallRecordingsByIds(client, [callRecordingId])
+ )[0];
+
+ if (isUndefined(callRecording)) {
+ return { status: 'settled', outcome: 'call recording not found' };
+ }
+
+ const calendarEvent = isUndefined(callRecording.calendarEventId)
+ ? undefined
+ : (
+ await fetchCalendarEventsByIds(client, [callRecording.calendarEventId])
+ )[0];
+ const followUp = resolveCallRecordingRequestFollowUp({
+ callRecording,
+ calendarEvent,
+ now,
+ });
+
+ if (followUp.action === 'check-again') {
+ return {
+ status: 'follow-up-again',
+ reason: followUp.reason,
+ dueAt: followUp.checkAt,
+ };
+ }
+
+ const actionResult = await runFollowUpAction({
+ client,
+ callRecording,
+ followUp,
+ now,
+ });
+
+ if (actionResult.status === 'failed') {
+ return {
+ status: 'follow-up-again',
+ reason: actionResult.reason,
+ dueAt: new Date(
+ now.getTime() +
+ computeCallRecordingRequestFollowUpRetryDelayMs({
+ attempt,
+ meetingStartsAt: calendarEvent?.startsAt,
+ now,
+ }),
+ ),
+ };
+ }
+
+ return { status: 'settled', outcome: actionResult.outcome };
+};
+
+const runFollowUpAction = async ({
+ client,
+ callRecording,
+ followUp,
+ now,
+}: {
+ client: CoreApiClient;
+ callRecording: CallRecordingRecord;
+ followUp: Exclude<CallRecordingRequestFollowUp, { action: 'check-again' }>;
+ now: Date;
+}): Promise<FollowUpActionResult> => {
+ switch (followUp.action) {
+ case 'none':
+ return { status: 'done', outcome: followUp.reason };
+ case 'book-bot':
+ return bookRecallBot({
+ client,
+ callRecording,
+ calendarEvent: followUp.calendarEvent,
+ now,
+ });
+ case 'mark-failed':
+ return markCallRecordingFailed({
+ client,
+ callRecordingId: callRecording.id,
+ failureReason: followUp.failureReason,
+ });
+ case 'cancel-bot':
+ return cancelLeftoverRecallBot({
+ client,
+ callRecordingId: callRecording.id,
+ externalBotId: followUp.externalBotId,
+ });
+ case 'find-and-cancel-bot':
+ return findAndCancelLeftoverRecallBot({
+ client,
+ callRecordingId: callRecording.id,
+ });
+ }
+};
+
+const bookRecallBot = async ({
+ client,
+ callRecording,
+ calendarEvent,
+ now,
+}: {
+ client: CoreApiClient;
+ callRecording: CallRecordingRecord;
+ calendarEvent: CalendarEventRecord;
+ now: Date;
+}): Promise<FollowUpActionResult> => {
+ const recoverResult = await recoverPendingCallRecording({
+ client,
+ callRecording,
+ calendarEvent,
+ now,
+ });
+
+ if (recoverResult.status === 'failed') {
+ return { status: 'failed', reason: recoverResult.reason };
+ }
+
+ return { status: 'done', outcome: describeRecovery(recoverResult) };
+};
+
+const describeRecovery = (
+ recoverResult: Exclude<
+ RecoverPendingCallRecordingResult,
+ { status: 'failed' }
+ >,
+): string => {
+ switch (recoverResult.status) {
+ case 'attached':
+ return 'attached the Recall bot found for the request';
+ case 'scheduled':
+ return 'scheduled a Recall bot';
+ case 'skipped':
+ return recoverResult.reason;
+ case 'blocked':
+ return recoverResult.failureReason;
+ }
+};
+
+const markCallRecordingFailed = async ({
+ client,
+ callRecordingId,
+ failureReason,
+}: {
+ client: CoreApiClient;
+ callRecordingId: string;
+ failureReason: string;
+}): Promise<FollowUpActionResult> => {
+ const isMarkedFailed = await updatePendingCallRecording({
+ client,
+ id: callRecordingId,
+ data: {
+ status: CallRecordingStatus.FAILED,
+ callRecorderFailureReason: failureReason,
+ },
+ });
+
+ if (!isMarkedFailed) {
+ return { status: 'done', outcome: 'request changed before it failed' };
+ }
+
+ console.warn(
+ `[call-recorder] call recording ${callRecordingId} got no Recall bot before its meeting ended; marked it failed (${failureReason})`,
+ );
+
+ return { status: 'done', outcome: failureReason };
+};
+
+const cancelLeftoverRecallBot = async ({
+ client,
+ callRecordingId,
+ externalBotId,
+}: {
+ client: CoreApiClient;
+ callRecordingId: string;
+ externalBotId: string;
+}): Promise<FollowUpActionResult> => {
+ const cancelOutcome = await cancelRecallBotForCanceledCallRecording({
+ client,
+ callRecordingId,
+ externalBotId,
+ });
+
+ if (cancelOutcome === 'failed') {
+ return { status: 'failed', reason: 'Recall bot cancellation failed' };
+ }
+
+ return {
+ status: 'done',
+ outcome: `Recall bot cancellation ${cancelOutcome}`,
+ };
+};
+
+const findAndCancelLeftoverRecallBot = async ({
+ client,
+ callRecordingId,
+}: {
+ client: CoreApiClient;
+ callRecordingId: string;
+}): Promise<FollowUpActionResult> => {
+ const lookupResult = await findScheduledRecallBotIdsByCallRecordingId([
+ callRecordingId,
+ ]);
+
+ if (!lookupResult.ok) {
+ return { status: 'failed', reason: 'Recall bot lookup failed' };
+ }
+
+ const externalBotId =
+ lookupResult.externalBotIdByCallRecordingId.get(callRecordingId);
+
+ if (isUndefined(externalBotId)) {
+ return { status: 'done', outcome: 'no Recall bot left to cancel' };
+ }
+
+ const isClaimed = await replaceCanceledCallRecordingExternalBotId(client, {
+ id: callRecordingId,
+ expectedExternalBotId: null,
+ nextExternalBotId: externalBotId,
+ });
+
+ // Another writer saved a bot id in the meantime; the next follow-up cancels
+ // whichever bot the request holds by then.
+ if (!isClaimed) {
+ return { status: 'failed', reason: 'request changed during the lookup' };
+ }
+
+ return cancelLeftoverRecallBot({ client, callRecordingId, externalBotId });
+};
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 2a8abdb62a4..67634f9bcdd 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
@@ -22,6 +22,7 @@ import { scheduleRecallBotForCallRecording } from 'src/logic-functions/flows/sch
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 { enqueueCallRecordingRequestFollowUps } from 'src/logic-functions/data/enqueue-call-recording-request-follow-ups.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';
@@ -226,16 +227,18 @@ const reconcileCallRecorderForMeetingOccurrences = async ({
)
).map((callRecording) => [callRecording.id, callRecording]),
);
- const canceledMeetingReconciliations = await reconcileCanceledMeetings({
- client,
- meetingPolicyResults: meetingPolicyResults.filter(
- (meetingPolicyResult) => !meetingPolicyResult.shouldRequestBot,
- ),
- removedCalendarEventIdsByMeetingKey,
- callRecordingsByCalendarEventId,
- policyManagedCallRecordingsById,
- activeMeetingCallRecordingIds: new Set(activeMeetingCallRecordingIds),
- });
+
+ const { canceledMeetingReconciliations, callRecordingIdsToFollowUp } =
+ await reconcileCanceledMeetings({
+ client,
+ meetingPolicyResults: meetingPolicyResults.filter(
+ (meetingPolicyResult) => !meetingPolicyResult.shouldRequestBot,
+ ),
+ removedCalendarEventIdsByMeetingKey,
+ callRecordingsByCalendarEventId,
+ policyManagedCallRecordingsById,
+ activeMeetingCallRecordingIds: new Set(activeMeetingCallRecordingIds),
+ });
await clearCanceledMeetingsRecordingOn(
client,
@@ -245,6 +248,19 @@ const reconcileCallRecorderForMeetingOccurrences = async ({
),
);
+ // Armed before creating or re-enabling requests, so a run that dies mid-batch still leaves every
+ // new or re-enabled request its follow-up.
+ await enqueueCallRecordingRequestFollowUps({
+ callRecordingIds: [
+ ...callRecordingIdsToFollowUp,
+ ...activeMeetingCallRecordingIds.filter((callRecordingId) =>
+ isUndefined(
+ policyManagedCallRecordingsById.get(callRecordingId)?.externalBotId,
+ ),
+ ),
+ ],
+ });
+
const activeMeetingReconciliations = await reconcileActiveMeetings({
client,
meetingPolicyResults: activeMeetingPolicyResults,
@@ -282,7 +298,11 @@ const reconcileCanceledMeetings = async ({
callRecordingsByCalendarEventId: Map<string, CallRecordingRecord[]>;
policyManagedCallRecordingsById: Map<string, CallRecordingRecord>;
activeMeetingCallRecordingIds: Set<string>;
-}): Promise<CanceledMeetingReconciliation[]> => {
+}): Promise<{
+ canceledMeetingReconciliations: CanceledMeetingReconciliation[];
+ callRecordingIdsToFollowUp: string[];
+}> => {
+ const callRecordingIdsToFollowUp: string[] = [];
const callRecordingIdsCanceledInBatch = new Set<string>();
const canceledMeetingReconciliations: CanceledMeetingReconciliation[] = [];
@@ -304,6 +324,20 @@ const reconcileCanceledMeetings = async ({
isCancellableCallRecording,
);
+ // A redelivery must also arm requests whose cancellation was already persisted.
+ callRecordingIdsToFollowUp.push(
+ ...meetingCallRecordings
+ .filter(
+ (callRecording) =>
+ isCancellableCallRecording(callRecording) ||
+ (callRecording.recordingRequestStatus ===
+ CallRecordingRequestStatus.CANCELED &&
+ (!isUndefined(callRecording.externalBotId) ||
+ !isUndefined(callRecording.botScheduleAttemptedAt))),
+ )
+ .map((callRecording) => callRecording.id),
+ );
+
try {
canceledMeetingReconciliations.push(
await reconcileCanceledMeeting({
@@ -325,7 +359,7 @@ const reconcileCanceledMeetings = async ({
}
}
- return canceledMeetingReconciliations;
+ return { canceledMeetingReconciliations, callRecordingIdsToFollowUp };
};
const reconcileActiveMeetings = async ({
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/recover-pending-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/recover-pending-call-recording.util.ts
new file mode 100644
index 00000000000..effafec0aee
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/recover-pending-call-recording.util.ts
@@ -0,0 +1,85 @@
+import { isUndefined } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { type MeetingRecording } from 'src/logic-functions/types/meeting-recording.type';
+import { canRescheduleCallRecordingWithoutRecallLookup } from 'src/logic-functions/domain/can-reschedule-call-recording-without-recall-lookup.util';
+import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';
+import { enqueuePreJoinCreditCheck } from 'src/logic-functions/data/enqueue-pre-join-credit-check.util';
+import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';
+import { updatePendingCallRecording } from 'src/logic-functions/data/update-pending-call-recording.util';
+import {
+ scheduleRecallBotForCallRecording,
+ type ScheduleRecallBotForCallRecordingResult,
+} from 'src/logic-functions/flows/schedule-recall-bot-for-call-recording.util';
+import { findScheduledRecallBotIdsByCallRecordingId } from 'src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util';
+
+export type RecoverPendingCallRecordingResult =
+ | { status: 'attached' }
+ | ScheduleRecallBotForCallRecordingResult;
+
+export const recoverPendingCallRecording = async ({
+ client,
+ callRecording,
+ calendarEvent,
+ now,
+}: MeetingRecording & {
+ client: CoreApiClient;
+ now: Date;
+}): Promise<RecoverPendingCallRecordingResult> => {
+ if (
+ canRescheduleCallRecordingWithoutRecallLookup({
+ callRecording,
+ calendarEvent,
+ workspaceId: getCurrentWorkspaceId(),
+ now,
+ })
+ ) {
+ return scheduleRecallBotForCallRecording(client, {
+ callRecording,
+ calendarEvent,
+ });
+ }
+
+ const lookupResult = await findScheduledRecallBotIdsByCallRecordingId([
+ callRecording.id,
+ ]);
+
+ // A failed lookup can hide an existing bot; creating one now could duplicate it.
+ if (!lookupResult.ok) {
+ return { status: 'failed', reason: 'Recall bot lookup failed' };
+ }
+
+ const existingExternalBotId = lookupResult.externalBotIdByCallRecordingId.get(
+ callRecording.id,
+ );
+
+ if (isUndefined(existingExternalBotId)) {
+ return scheduleRecallBotForCallRecording(client, {
+ callRecording,
+ calendarEvent,
+ });
+ }
+
+ const isAttached = await updatePendingCallRecording({
+ client,
+ id: callRecording.id,
+ data: { externalBotId: existingExternalBotId },
+ });
+
+ if (!isAttached) {
+ return {
+ status: 'skipped',
+ reason: 'call recording no longer awaits a bot',
+ };
+ }
+
+ if (!isUndefined(calendarEvent.startsAt)) {
+ await enqueuePreJoinCreditCheck({
+ callRecordingId: callRecording.id,
+ externalBotId: existingExternalBotId,
+ joinAt: computeRecallBotJoinAt(calendarEvent.startsAt),
+ });
+ }
+
+ return { status: 'attached' };
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.ts
index cd03597d0dd..cf2dcc4ad3b 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.ts
@@ -5,6 +5,7 @@ import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recal
import { type MeetingRecording } from 'src/logic-functions/types/meeting-recording.type';
import { buildRecallRoutingMetadata } from 'src/logic-functions/domain/build-recall-routing-metadata.util';
import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';
+import { enqueueCallRecordingRequestFollowUps } from 'src/logic-functions/data/enqueue-call-recording-request-follow-ups.util';
import { enqueuePreJoinCreditCheck } from 'src/logic-functions/data/enqueue-pre-join-credit-check.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';
@@ -78,6 +79,9 @@ export const rescheduleCallRecordingBot = async (
return;
}
+ await enqueueCallRecordingRequestFollowUps({
+ callRecordingIds: [callRecording.id],
+ });
await updateCallRecording(client, {
id: callRecording.id,
data: {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts
index 324910e03f1..202dfd1c6bb 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts
@@ -17,9 +17,6 @@ export type ResumePendingCallRecordingResult =
| { status: 'skipped'; reason: string }
| { status: 'deferred'; reason: string };
-// Single-recording variant of the recovery sweep: finishes bot scheduling for
-// one row that transitioned back to pending. Deferred outcomes are retried by
-// the queue and ultimately by the recovery cron.
export const resumePendingCallRecording = async ({
client,
callRecordingId,
@@ -65,7 +62,7 @@ export const resumePendingCallRecording = async ({
now,
})
) {
- // The recovery cron owns failing rows whose meeting is over.
+ // The follow-up owns failing rows whose meeting is over.
return { status: 'skipped', reason: 'meeting already ended' };
}
@@ -82,7 +79,7 @@ export const resumePendingCallRecording = async ({
return {
status: 'deferred',
- reason: 'ambiguous prior attempt; the recovery cron will reconcile it',
+ reason: 'ambiguous prior attempt; the follow-up will look it up at Recall',
};
};
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
deleted file mode 100644
index dd91bbdae65..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-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 { hasMeetingEnded } from 'src/logic-functions/domain/has-meeting-ended.util';
-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 { replaceCanceledCallRecordingExternalBotId } from 'src/logic-functions/data/replace-canceled-call-recording-external-bot-id.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';
-import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
-
-export type RetryFailedRecallCancellationsResult = {
- canceledExternalBotCallRecordingIds: string[];
-};
-
-const CANCELED_BOT_RECOVERY_AFTER_START_HOURS = 24;
-const CANCELED_BOT_RECOVERY_MAX_AGE_HOURS = 24;
-
-// Retries the Recall half of cancelCallRecordingRequest when its bot cancel failed; the recording keeps its bot id until the bot is confirmed gone.
-export const retryFailedRecallCancellations = async ({
- client,
- now,
-}: {
- client: CoreApiClient;
- now: Date;
-}): Promise<RetryFailedRecallCancellationsResult> => {
- const canceledCallRecordings = await findCallRecordingsByFilter(client, {
- recordingRequestStatus: { eq: CallRecordingRequestStatus.CANCELED },
- status: { in: NON_TERMINAL_CALL_RECORDING_STATUSES },
- });
- const botlessCanceledCallRecordings = canceledCallRecordings.filter(
- (callRecording) => isUndefined(callRecording.externalBotId),
- );
- const calendarEventsById = new Map(
- (
- await fetchCalendarEventsByIds(
- client,
- getUniqueSortedIds(
- botlessCanceledCallRecordings.map(
- (callRecording) => callRecording.calendarEventId,
- ),
- ),
- )
- ).map((calendarEvent) => [calendarEvent.id, calendarEvent]),
- );
- const recoverableCallRecordingIds = canceledCallRecordings
- .filter(
- (callRecording) =>
- isUndefined(callRecording.externalBotId) &&
- isWithinCanceledBotRecoveryWindow({
- callRecording,
- calendarEvent: isUndefined(callRecording.calendarEventId)
- ? undefined
- : calendarEventsById.get(callRecording.calendarEventId),
- now,
- }),
- )
- .map((callRecording) => callRecording.id);
- const lookupResult = await findScheduledRecallBotIdsByCallRecordingId(
- recoverableCallRecordingIds,
- );
- const externalBotIdByCallRecordingId = lookupResult.ok
- ? lookupResult.externalBotIdByCallRecordingId
- : new Map<string, string>();
- const canceledExternalBotCallRecordingIds: string[] = [];
-
- for (const callRecording of canceledCallRecordings) {
- const externalBotId = await recoverRecallBotIdForCanceledCallRecording({
- client,
- callRecording,
- listedExternalBotId: externalBotIdByCallRecordingId.get(callRecording.id),
- });
-
- if (isUndefined(externalBotId)) {
- continue;
- }
-
- const outcome = await cancelRecallBotForCanceledCallRecording({
- client,
- callRecordingId: callRecording.id,
- externalBotId,
- });
-
- if (outcome !== 'canceled') {
- continue;
- }
-
- canceledExternalBotCallRecordingIds.push(callRecording.id);
- }
-
- return { canceledExternalBotCallRecordingIds };
-};
-
-const isWithinCanceledBotRecoveryWindow = ({
- callRecording,
- calendarEvent,
- now,
-}: {
- callRecording: CallRecordingRecord;
- calendarEvent: CalendarEventRecord | undefined;
- now: Date;
-}): boolean => {
- if (
- !isUndefined(calendarEvent) &&
- hasMeetingEnded({
- startsAt: calendarEvent.startsAt,
- endsAt: calendarEvent.endsAt,
- now,
- startGraceHours: CANCELED_BOT_RECOVERY_AFTER_START_HOURS,
- })
- ) {
- return false;
- }
-
- // Recovery only closes the crash window right after cancellation; once a row ages out the daily cleanup sweep owns it, so stop the per-run Recall lookup instead of listing forever (notably for rows whose calendar event was deleted and can no longer bound the retry).
- // updatedAt tracks the cancellation write, so a request scheduled far ahead but canceled recently still gets its window; createdAt would age it out from scheduling time.
- return !hasCanceledRecoveryWindowElapsed({
- canceledAt: callRecording.updatedAt ?? callRecording.createdAt,
- now,
- });
-};
-
-const hasCanceledRecoveryWindowElapsed = ({
- canceledAt,
- now,
-}: {
- canceledAt: string | undefined;
- now: Date;
-}): boolean => {
- if (isUndefined(canceledAt)) {
- return false;
- }
-
- const canceledTime = new Date(canceledAt).getTime();
-
- return (
- !Number.isNaN(canceledTime) &&
- canceledTime + CANCELED_BOT_RECOVERY_MAX_AGE_HOURS * 60 * 60 * 1000 <=
- now.getTime()
- );
-};
-
-const recoverRecallBotIdForCanceledCallRecording = async ({
- client,
- callRecording,
- listedExternalBotId,
-}: {
- client: CoreApiClient;
- callRecording: CallRecordingRecord;
- listedExternalBotId: string | undefined;
-}): Promise<string | undefined> => {
- if (!isUndefined(callRecording.externalBotId)) {
- return callRecording.externalBotId;
- }
-
- if (isUndefined(listedExternalBotId)) {
- return undefined;
- }
-
- const didClaimRecoveredBot = await replaceCanceledCallRecordingExternalBotId(
- client,
- {
- id: callRecording.id,
- expectedExternalBotId: null,
- nextExternalBotId: listedExternalBotId,
- },
- );
-
- return didClaimRecoveredBot ? listedExternalBotId : undefined;
-};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util.ts
deleted file mode 100644
index 52d8a6fbcc0..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util.ts
+++ /dev/null
@@ -1,288 +0,0 @@
-import { isUndefined } from '@sniptt/guards';
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-
-import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
-import { type CalendarEventRecord } from 'src/logic-functions/types/calendar-event-record.type';
-import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';
-import { canRescheduleCallRecordingWithoutRecallLookup } from 'src/logic-functions/domain/can-reschedule-call-recording-without-recall-lookup.util';
-import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';
-import { enqueuePreJoinCreditCheck } from 'src/logic-functions/data/enqueue-pre-join-credit-check.util';
-import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';
-import { hasMeetingEnded } from 'src/logic-functions/domain/has-meeting-ended.util';
-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 { findOpenScheduledCallRecordings } from 'src/logic-functions/data/find-open-scheduled-call-recordings.util';
-import { findScheduledRecallBotIdsByCallRecordingId } from 'src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util';
-import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
-import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';
-
-export const BOT_NEVER_SCHEDULED_FAILURE_REASON = 'bot_never_scheduled';
-export const BOT_SCHEDULE_OUTCOME_UNKNOWN_FAILURE_REASON =
- 'bot_schedule_outcome_unknown';
-
-// Mirrors the stale-state convergence lookback: past it no automatic pull
-// pass will resolve the row anymore, so keeping it pending only wastes runs.
-const UNRESOLVED_ATTEMPT_MAX_AGE_DAYS = 7;
-
-export type ScheduleRecallBotsForPendingCallRecordingsResult = {
- attachedCallRecordingIds: string[];
- scheduledCallRecordingIds: string[];
- markedFailedCallRecordingIds: string[];
-};
-
-type ResumableCallRecording = {
- callRecording: CallRecordingRecord;
- calendarEvent: CalendarEventRecord;
-};
-
-// Resumes a CallRecording inserted before its Recall bot was scheduled.
-export const scheduleRecallBotsForPendingCallRecordings = async ({
- client,
- now,
-}: {
- client: CoreApiClient;
- now: Date;
-}): Promise<ScheduleRecallBotsForPendingCallRecordingsResult> => {
- const result: ScheduleRecallBotsForPendingCallRecordingsResult = {
- attachedCallRecordingIds: [],
- scheduledCallRecordingIds: [],
- markedFailedCallRecordingIds: [],
- };
- const pendingCallRecordings = (
- await findOpenScheduledCallRecordings(client)
- ).filter((callRecording) => isUndefined(callRecording.externalBotId));
-
- if (pendingCallRecordings.length === 0) {
- return result;
- }
-
- const calendarEventsById = new Map(
- (
- await fetchCalendarEventsByIds(
- client,
- getUniqueSortedIds(
- pendingCallRecordings.map(
- (callRecording) => callRecording.calendarEventId,
- ),
- ),
- )
- ).map((calendarEvent) => [calendarEvent.id, calendarEvent]),
- );
- const resumableCallRecordings: ResumableCallRecording[] = [];
-
- for (const callRecording of pendingCallRecordings) {
- const calendarEvent = isUndefined(callRecording.calendarEventId)
- ? undefined
- : calendarEventsById.get(callRecording.calendarEventId);
-
- if (isUndefined(calendarEvent)) {
- continue;
- }
-
- if (
- hasMeetingEnded({
- startsAt: calendarEvent.startsAt,
- endsAt: calendarEvent.endsAt,
- now,
- })
- ) {
- await resolveEndedPendingCallRecording({
- client,
- callRecording,
- calendarEvent,
- now,
- result,
- });
- continue;
- }
-
- resumableCallRecordings.push({ callRecording, calendarEvent });
- }
-
- if (resumableCallRecordings.length === 0) {
- return result;
- }
-
- const workspaceId = getCurrentWorkspaceId();
- const ambiguousCallRecordings = resumableCallRecordings.filter(
- ({ callRecording, calendarEvent }) =>
- !canRescheduleCallRecordingWithoutRecallLookup({
- callRecording,
- calendarEvent,
- workspaceId,
- now,
- }),
- );
- const unambiguousCallRecordings = resumableCallRecordings.filter(
- ({ callRecording, calendarEvent }) =>
- canRescheduleCallRecordingWithoutRecallLookup({
- callRecording,
- calendarEvent,
- workspaceId,
- now,
- }),
- );
-
- for (const { callRecording, calendarEvent } of unambiguousCallRecordings) {
- await scheduleBotForResumableCallRecording({
- client,
- callRecording,
- calendarEvent,
- result,
- });
- }
-
- if (ambiguousCallRecordings.length === 0) {
- return result;
- }
-
- const lookupResult = await findScheduledRecallBotIdsByCallRecordingId(
- ambiguousCallRecordings.map(({ callRecording }) => callRecording.id),
- );
-
- // A failed lookup can hide existing bots; creating one now could duplicate
- // them, so defer to the next run.
- if (!lookupResult.ok) {
- return result;
- }
-
- for (const { callRecording, calendarEvent } of ambiguousCallRecordings) {
- const existingExternalBotId =
- lookupResult.externalBotIdByCallRecordingId.get(callRecording.id);
-
- if (!isUndefined(existingExternalBotId)) {
- await updateCallRecording(client, {
- id: callRecording.id,
- data: { externalBotId: existingExternalBotId },
- });
- result.attachedCallRecordingIds.push(callRecording.id);
-
- if (!isUndefined(calendarEvent.startsAt)) {
- await enqueuePreJoinCreditCheck({
- callRecordingId: callRecording.id,
- externalBotId: existingExternalBotId,
- joinAt: computeRecallBotJoinAt(calendarEvent.startsAt),
- });
- }
- continue;
- }
-
- await scheduleBotForResumableCallRecording({
- client,
- callRecording,
- calendarEvent,
- result,
- });
- }
-
- return result;
-};
-
-const scheduleBotForResumableCallRecording = async ({
- client,
- callRecording,
- calendarEvent,
- result,
-}: {
- client: CoreApiClient;
- callRecording: CallRecordingRecord;
- calendarEvent: CalendarEventRecord;
- result: ScheduleRecallBotsForPendingCallRecordingsResult;
-}): Promise<void> => {
- const scheduleResult = await scheduleRecallBotForCallRecording(client, {
- callRecording,
- calendarEvent,
- });
-
- if (scheduleResult.status === 'scheduled') {
- result.scheduledCallRecordingIds.push(callRecording.id);
- }
-};
-
-// Only an absent attempt marker proves no POST reached Recall; a marked row
-// may have a bot that joined and recorded before the id write-back was lost,
-// so it keeps its recovery chance until the convergence lookback has passed.
-const resolveEndedPendingCallRecording = async ({
- client,
- callRecording,
- calendarEvent,
- now,
- result,
-}: {
- client: CoreApiClient;
- callRecording: CallRecordingRecord;
- calendarEvent: CalendarEventRecord;
- now: Date;
- result: ScheduleRecallBotsForPendingCallRecordingsResult;
-}): Promise<void> => {
- if (isUndefined(callRecording.botScheduleAttemptedAt)) {
- await markCallRecordingFailed({
- client,
- callRecording,
- failureReason: BOT_NEVER_SCHEDULED_FAILURE_REASON,
- logMessage: `call recording ${callRecording.id} never got a Recall bot and its meeting has ended; marking it failed`,
- });
- result.markedFailedCallRecordingIds.push(callRecording.id);
-
- return;
- }
-
- if (!hasUnresolvedAttemptAgedOut({ calendarEvent, now })) {
- console.warn(
- `[call-recorder] call recording ${callRecording.id} has an unresolved Recall bot creation attempt and its meeting has ended; waiting for convergence`,
- );
-
- return;
- }
-
- await markCallRecordingFailed({
- client,
- callRecording,
- failureReason: BOT_SCHEDULE_OUTCOME_UNKNOWN_FAILURE_REASON,
- logMessage: `call recording ${callRecording.id} has an unresolved Recall bot creation attempt older than the convergence lookback; marking it failed`,
- });
- result.markedFailedCallRecordingIds.push(callRecording.id);
-};
-
-const hasUnresolvedAttemptAgedOut = ({
- calendarEvent,
- now,
-}: {
- calendarEvent: CalendarEventRecord;
- now: Date;
-}): boolean => {
- // Mirrors hasMeetingEnded: an unparseable end time falls back to the start
- // time so these rows still age out of the pending sweep eventually.
- const meetingEndTime = [calendarEvent.endsAt, calendarEvent.startsAt]
- .filter((candidate) => !isUndefined(candidate))
- .map((candidate) => new Date(candidate).getTime())
- .find((candidateTime) => !Number.isNaN(candidateTime));
-
- return (
- !isUndefined(meetingEndTime) &&
- meetingEndTime + UNRESOLVED_ATTEMPT_MAX_AGE_DAYS * 24 * 60 * 60 * 1000 <=
- now.getTime()
- );
-};
-
-const markCallRecordingFailed = async ({
- client,
- callRecording,
- failureReason,
- logMessage,
-}: {
- client: CoreApiClient;
- callRecording: CallRecordingRecord;
- failureReason: string;
- logMessage: string;
-}): Promise<void> => {
- console.warn(`[call-recorder] ${logMessage}`);
-
- await updateCallRecording(client, {
- id: callRecording.id,
- data: {
- status: CallRecordingStatus.FAILED,
- callRecorderFailureReason: failureReason,
- },
- });
-};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/follow-up-call-recording-request.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/follow-up-call-recording-request.ts
new file mode 100644
index 00000000000..80b862a7c3c
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/follow-up-call-recording-request.ts
@@ -0,0 +1,70 @@
+import { isNumber, isUndefined } from '@sniptt/guards';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import { FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { enqueueCallRecordingRequestFollowUps } from 'src/logic-functions/data/enqueue-call-recording-request-follow-ups.util';
+import {
+ followUpCallRecordingRequest,
+ type FollowUpCallRecordingRequestResult,
+} from 'src/logic-functions/flows/follow-up-call-recording-request.util';
+import { asRecord } from 'src/logic-functions/utils/as-record.util';
+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
+import { fetchWithRateLimitRetry } from 'src/logic-functions/utils/fetch-with-rate-limit-retry.util';
+import { getString } from 'src/logic-functions/utils/get-string.util';
+
+export const followUpCallRecordingRequestHandler = async (
+ payload: unknown,
+): Promise<
+ FollowUpCallRecordingRequestResult | { status: 'skipped'; reason: string }
+> => {
+ const body = asRecord(payload);
+ const callRecordingId = getString(body?.callRecordingId);
+
+ if (isUndefined(callRecordingId)) {
+ return { status: 'skipped', reason: 'invalid follow-up job' };
+ }
+
+ const attemptValue = body?.attempt;
+ const attempt = isNumber(attemptValue) ? attemptValue : 0;
+ const now = new Date();
+
+ try {
+ const result = await followUpCallRecordingRequest({
+ // The follow-up runs long after the run that armed it, so it must not
+ // borrow that run's user.
+ client: new CoreApiClient({
+ runAs: 'application',
+ fetch: fetchWithRateLimitRetry,
+ }),
+ callRecordingId,
+ attempt,
+ now,
+ });
+
+ if (result.status === 'follow-up-again') {
+ await enqueueCallRecordingRequestFollowUps({
+ callRecordingIds: [callRecordingId],
+ delayMs: Math.max(0, result.dueAt.getTime() - now.getTime()),
+ attempt: attempt + 1,
+ });
+ }
+
+ return result;
+ } catch (error) {
+ throw buildRetryableStepFailure(
+ `follow-up of call recording ${callRecordingId}`,
+ error,
+ );
+ }
+};
+
+export default defineLogicFunction({
+ universalIdentifier:
+ FOLLOW_UP_CALL_RECORDING_REQUEST_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'follow-up-call-recording-request',
+ description:
+ 'Checks a call recording request a while after it changed and finishes what Recall left undone: books a missing bot, cancels a leftover one, or marks the recording failed once its meeting is over.',
+ timeoutSeconds: 300,
+ handler: followUpCallRecordingRequestHandler,
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/process-pending-call-recording-requests.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/process-pending-call-recording-requests.ts
index 80ff9aa6689..4d2e5e94977 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/process-pending-call-recording-requests.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/process-pending-call-recording-requests.ts
@@ -2,57 +2,26 @@ import { CoreApiClient } from 'twenty-client-sdk/core';
import { defineLogicFunction } from 'twenty-sdk/define';
import { PENDING_CALL_RECORDING_REQUESTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import { PENDING_CALL_RECORDING_REQUESTS_CRON_PATTERN } from 'src/logic-functions/constants/pending-call-recording-requests-cron-pattern';
-import {
- retryFailedRecallCancellations,
- type RetryFailedRecallCancellationsResult,
-} from 'src/logic-functions/flows/retry-failed-recall-cancellations.util';
-import {
- scheduleRecallBotsForPendingCallRecordings,
- type ScheduleRecallBotsForPendingCallRecordingsResult,
-} from 'src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util';
-import {
- buildStepFailure,
- type StepFailure,
-} from 'src/logic-functions/utils/build-step-failure.util';
+import { enqueueCallRecordingRequestFollowUps } from 'src/logic-functions/data/enqueue-call-recording-request-follow-ups.util';
+import { findStuckCallRecordingRequestIds } from 'src/logic-functions/data/find-stuck-call-recording-request-ids.util';
+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
-const processPendingCallRecordingRequestsHandler =
- async (): Promise<object> => {
- const now = new Date();
- const client = new CoreApiClient();
-
- const pendingCallRecordingScheduleResult =
- await scheduleRecallBotsForPendingCallRecordingsSafely(client, now);
- const failedCancellationResult = await retryFailedRecallCancellationsSafely(
- client,
- now,
+export const processPendingCallRecordingRequestsHandler = async (): Promise<{
+ followedUpCallRecordingIds: string[];
+}> => {
+ try {
+ const callRecordingIds = await findStuckCallRecordingRequestIds(
+ new CoreApiClient(),
);
- return {
- pendingCallRecordingScheduleResult,
- failedCancellationResult,
- };
- };
+ await enqueueCallRecordingRequestFollowUps({ callRecordingIds });
-const scheduleRecallBotsForPendingCallRecordingsSafely = async (
- client: CoreApiClient,
- now: Date,
-): Promise<ScheduleRecallBotsForPendingCallRecordingsResult | StepFailure> => {
- try {
- return await scheduleRecallBotsForPendingCallRecordings({ client, now });
+ return { followedUpCallRecordingIds: callRecordingIds };
} catch (error) {
- return buildStepFailure('pending Recall bot scheduling', error);
- }
-};
-
-const retryFailedRecallCancellationsSafely = async (
- client: CoreApiClient,
- now: Date,
-): Promise<RetryFailedRecallCancellationsResult | StepFailure> => {
- try {
- return await retryFailedRecallCancellations({ client, now });
- } catch (error) {
- return buildStepFailure('failed cancellation retry', error);
+ throw buildRetryableStepFailure(
+ 'stuck call recording request follow-up enqueueing',
+ error,
+ );
}
};
@@ -61,10 +30,7 @@ export default defineLogicFunction({
PENDING_CALL_RECORDING_REQUESTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'process-pending-call-recording-requests',
description:
- 'Processes pending CallRecording requests by attaching or scheduling missing Recall bots and retrying incomplete cancellations.',
+ 'Arms a follow-up for every call recording request still waiting on Recall. Runs after each app upgrade, so requests stuck before then are not left behind.',
timeoutSeconds: 250,
handler: processPendingCallRecordingRequestsHandler,
- cronTriggerSettings: {
- pattern: PENDING_CALL_RECORDING_REQUESTS_CRON_PATTERN,
- },
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
index b5b3ed644d6..70052896237 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
@@ -18,7 +18,7 @@ import { fetchCalendarEventsByIds } from 'src/logic-functions/data/fetch-calenda
import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';
import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';
-import { fetchWithTransientRetry } from 'src/logic-functions/utils/fetch-with-transient-retry.util';
+import { fetchWithRateLimitRetry } from 'src/logic-functions/utils/fetch-with-rate-limit-retry.util';
const CALENDAR_EVENT_OBJECT_NAME = 'calendarEvent';
@@ -55,7 +55,7 @@ const handler = async (
return { skipped: true, reason: 'no relevant calendar event change' };
}
- const client = new CoreApiClient({ fetch: fetchWithTransientRetry });
+ const client = new CoreApiClient({ fetch: fetchWithRateLimitRetry });
const calendarEventIds = await resolveCalendarEventIdsToReconcile({
client,
changedCalendarEventIds: reconciliationPayload.calendarEventIds,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.ts
index ed3348dfec8..4bff282890f 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.ts
@@ -16,6 +16,7 @@ type ReconcileUpcomingCalendarEventsResult =
reconciledCalendarEventIds: string[];
actionCounts: CallRecorderReconciliationActionCounts;
};
+import { fetchWithRateLimitRetry } from 'src/logic-functions/utils/fetch-with-rate-limit-retry.util';
export const reconcileUpcomingCalendarEventsHandler = async (
payload: unknown,
@@ -29,7 +30,7 @@ export const reconcileUpcomingCalendarEventsHandler = async (
try {
const reconciliationResults =
await reconcileCallRecorderForCalendarEventIds({
- client: new CoreApiClient(),
+ client: new CoreApiClient({ fetch: fetchWithRateLimitRetry }),
calendarEventIds,
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/schedule-recall-bot-on-call-recording-update.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/schedule-recall-bot-on-call-recording-update.ts
index 68fa1492a46..36ea899e6a1 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/schedule-recall-bot-on-call-recording-update.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/schedule-recall-bot-on-call-recording-update.ts
@@ -9,10 +9,12 @@ import {
import { SCHEDULE_RECALL_BOT_ON_CALL_RECORDING_UPDATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { enqueueCallRecordingRequestFollowUps } from 'src/logic-functions/data/enqueue-call-recording-request-follow-ups.util';
import {
resumePendingCallRecording,
type ResumePendingCallRecordingResult,
} from 'src/logic-functions/flows/resume-pending-call-recording.util';
+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';
const CALL_RECORDING_OBJECT_NAME = 'callRecording';
@@ -43,8 +45,8 @@ type CallRecordingDatabaseEvent = DatabaseEventPayload<
// creations here would race that run into duplicate Recall creates. This
// trigger only resumes rows that fall back to pending later (a bot cleared
// after vanishing at Recall, a canceled request re-requested, a failed row
-// reset by calendar reconciliation), which the recovery cron would otherwise
-// pick up minutes later.
+// reset by calendar reconciliation), which their follow-up would otherwise
+// only pick up half an hour later.
export const scheduleRecallBotOnCallRecordingUpdateHandler = async (
event: CallRecordingDatabaseEvent,
): Promise<
@@ -71,6 +73,18 @@ export const scheduleRecallBotOnCallRecordingUpdateHandler = async (
return { skipped: true, reason: 'call recording is not pending' };
}
+ // Writes from outside the app (API, workflows) arm no follow-up of their own.
+ try {
+ await enqueueCallRecordingRequestFollowUps({
+ callRecordingIds: [event.recordId],
+ });
+ } catch (error) {
+ throw buildRetryableStepFailure(
+ 'call recording request follow-up enqueueing',
+ error,
+ );
+ }
+
const result = await resumePendingCallRecording({
client: new CoreApiClient(),
callRecordingId: event.recordId,
@@ -121,7 +135,7 @@ export default defineLogicFunction({
SCHEDULE_RECALL_BOT_ON_CALL_RECORDING_UPDATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'schedule-recall-bot-on-call-recording-update',
description:
- 'Resumes Recall bot scheduling as soon as a call recording transitions back to pending instead of waiting for the recovery cron.',
+ 'Resumes Recall bot scheduling as soon as a call recording transitions back to pending, and arms its follow-up in case that fails.',
timeoutSeconds: 60,
handler: scheduleRecallBotOnCallRecordingUpdateHandler,
databaseEventTriggerSettings: {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.ts
index 74159298bf9..9aff76b5a2f 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.ts
@@ -1,19 +1,28 @@
-import { definePostInstallLogicFunction } from 'twenty-sdk/define';
+import { isUndefined } from '@sniptt/guards';
+import {
+ definePostInstallLogicFunction,
+ type InstallPayload,
+} from 'twenty-sdk/define';
import {
+ PENDING_CALL_RECORDING_REQUESTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
START_POST_INSTALL_BACKFILLS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';
import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';
+import { enqueueWorkspaceDistributedJob } from 'src/logic-functions/data/enqueue-workspace-distributed-job.util';
+import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';
import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
-type StartPostInstallBackfillsResult = {
- calendarEventSweepOutcome: 'sweep-enqueued';
-};
+type StartPostInstallBackfillsResult =
+ | { calendarEventSweepOutcome: 'sweep-enqueued' }
+ | { stuckRequestFollowUpDelayMs: number };
// The async install hook is redelivered only for retryable failures.
-export const startPostInstallBackfillsHandler =
- async (): Promise<StartPostInstallBackfillsResult> => {
+export const startPostInstallBackfillsHandler = async ({
+ previousVersion,
+}: InstallPayload): Promise<StartPostInstallBackfillsResult> => {
+ if (isUndefined(previousVersion)) {
try {
await enqueueLogicFunctionJobs({
logicFunctionUniversalIdentifier:
@@ -25,14 +34,32 @@ export const startPostInstallBackfillsHandler =
}
return { calendarEventSweepOutcome: 'sweep-enqueued' };
- };
+ }
+
+ // Requests that got stuck under an earlier version never had a follow-up.
+ const workspaceId = getCurrentWorkspaceId();
+
+ if (isUndefined(workspaceId)) {
+ throw new Error('workspace id unavailable');
+ }
+
+ const { delayMs } = await enqueueWorkspaceDistributedJob({
+ workspaceId,
+ logicFunctionUniversalIdentifier:
+ PENDING_CALL_RECORDING_REQUESTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ stepLabel: 'post-upgrade stuck request follow-up kickoff',
+ });
+
+ return { stuckRequestFollowUpDelayMs: delayMs };
+};
export default definePostInstallLogicFunction({
universalIdentifier:
START_POST_INSTALL_BACKFILLS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'start-post-install-backfills',
description:
- 'Schedules recording bots for upcoming meetings when the app is installed.',
+ 'Schedules recording bots for upcoming meetings when the app is installed, and follows up on requests left stuck by an earlier version when it is upgraded.',
timeoutSeconds: 30,
+ shouldRunOnVersionUpgrade: true,
handler: startPostInstallBackfillsHandler,
});
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
index 5e30d26dac0..324d75aa5c3 100644
--- 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
@@ -8,9 +8,14 @@ import {
} 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 { enqueueCallRecordingRequestFollowUps } from 'src/logic-functions/data/enqueue-call-recording-request-follow-ups.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 { findCallRecordingsByFilter } from 'src/logic-functions/data/find-call-recordings-by-filter.util';
+import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';
import { isCalendarBotSchedulingEnabled } from 'src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util';
+import { fetchWithRateLimitRetry } from 'src/logic-functions/utils/fetch-with-rate-limit-retry.util';
export type SyncCalendarBotSchedulingResult =
| { outcome: 'sweep-enqueued' }
@@ -31,29 +36,60 @@ export const syncCalendarBotSchedulingHandler =
return { outcome: 'sweep-enqueued' };
}
- const client = new CoreApiClient();
- const openCallRecordings = await findOpenScheduledCallRecordings(client);
+ const client = new CoreApiClient({ fetch: fetchWithRateLimitRetry });
+ // Include unfinished cancellations so a retry after an enqueue failure does not lose them.
+ const callRecordings = await findCallRecordingsByFilter(client, {
+ or: [
+ {
+ recordingRequestStatus: { eq: CallRecordingRequestStatus.REQUESTED },
+ status: { eq: CallRecordingStatus.SCHEDULED },
+ },
+ {
+ recordingRequestStatus: { eq: CallRecordingRequestStatus.CANCELED },
+ status: { in: NON_TERMINAL_CALL_RECORDING_STATUSES },
+ or: [
+ { externalBotId: { is: 'NOT_NULL' } },
+ { botScheduleAttemptedAt: { is: 'NOT_NULL' } },
+ ],
+ },
+ ],
+ });
+ const openCallRecordingIds = callRecordings
+ .filter(
+ (callRecording) =>
+ callRecording.recordingRequestStatus ===
+ CallRecordingRequestStatus.REQUESTED,
+ )
+ .map((callRecording) => callRecording.id);
- const canceledCallRecordingCount =
- await cancelOpenScheduledCallRecordingRequests(
- client,
- openCallRecordings.map((callRecording) => callRecording.id),
- () => true,
- );
+ try {
+ const canceledCallRecordingCount =
+ await cancelOpenScheduledCallRecordingRequests(
+ client,
+ openCallRecordingIds,
+ () => true,
+ );
- await enqueueLogicFunctionJobs({
- logicFunctionUniversalIdentifier:
- CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- payloads: [{}],
- });
+ await enqueueLogicFunctionJobs({
+ logicFunctionUniversalIdentifier:
+ CANCEL_SCHEDULED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ payloads: [{}],
+ });
- await enqueueLogicFunctionJobs({
- logicFunctionUniversalIdentifier:
- SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- payloads: [{}],
- });
+ await enqueueLogicFunctionJobs({
+ logicFunctionUniversalIdentifier:
+ SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ payloads: [{}],
+ });
- return { outcome: 'scheduled-bots-canceled', canceledCallRecordingCount };
+ return { outcome: 'scheduled-bots-canceled', canceledCallRecordingCount };
+ } finally {
+ await enqueueCallRecordingRequestFollowUps({
+ callRecordingIds: callRecordings.map(
+ (callRecording) => callRecording.id,
+ ),
+ });
+ }
};
export default defineLogicFunction({
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/fetch-with-rate-limit-retry.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/fetch-with-rate-limit-retry.test.ts
new file mode 100644
index 00000000000..b73af6bf152
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/fetch-with-rate-limit-retry.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
+
+import { fetchWithRateLimitRetry } from 'src/logic-functions/utils/fetch-with-rate-limit-retry.util';
+
+const fetchMock = vi.fn<typeof fetch>();
+const OPTIONS = {
+ method: 'POST',
+ body: JSON.stringify({ query: 'mutation { cancel }' }),
+};
+const rateLimitedResponse = (retryAfterMs: number) =>
+ Response.json({
+ errors: [{ extensions: { code: 'RATE_LIMITED', retryAfterMs } }],
+ });
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(0);
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('fetchWithRateLimitRetry', () => {
+ it('waits for GraphQL retryAfterMs and retries only the throttled request', async () => {
+ fetchMock
+ .mockImplementationOnce(async () => rateLimitedResponse(15_000))
+ .mockImplementationOnce(async () =>
+ Response.json({ data: { cancel: { id: 'recording' } } }),
+ );
+ const result = fetchWithRateLimitRetry(
+ 'https://example.test/graphql',
+ OPTIONS,
+ );
+ await vi.advanceTimersByTimeAsync(14_000);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(await (await result).json()).toEqual({
+ data: { cancel: { id: 'recording' } },
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('honors HTTP Retry-After and adds jitter', async () => {
+ vi.mocked(Math.random).mockReturnValue(0.5);
+ fetchMock
+ .mockImplementationOnce(
+ async () =>
+ new Response('rate limited', {
+ status: 429,
+ headers: { 'Retry-After': '5' },
+ }),
+ )
+ .mockImplementationOnce(async () => Response.json({ data: {} }));
+ const result = fetchWithRateLimitRetry(
+ 'https://example.test/graphql',
+ OPTIONS,
+ );
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(500);
+ await result;
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('hands persistent throttling back to the queue after the wait budget', async () => {
+ fetchMock.mockImplementation(async () => rateLimitedResponse(60_000));
+ const result = fetchWithRateLimitRetry(
+ 'https://example.test/graphql',
+ OPTIONS,
+ );
+ const assertion = expect(result).rejects.toBeInstanceOf(
+ RetryableLogicFunctionError,
+ );
+ await vi.advanceTimersByTimeAsync(120_000);
+ await assertion;
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not replay a partially successful mutation', async () => {
+ const body = {
+ data: { firstMutation: { id: 'recording' }, secondMutation: null },
+ errors: [{ extensions: { code: 'RATE_LIMITED', retryAfterMs: 1_000 } }],
+ };
+ fetchMock.mockImplementation(async () => Response.json(body));
+ const response = await fetchWithRateLimitRetry(
+ 'https://example.test/graphql',
+ OPTIONS,
+ );
+ expect(await response.json()).toEqual(body);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not retry unrelated GraphQL errors or uncertain mutation failures', async () => {
+ fetchMock
+ .mockImplementationOnce(async () =>
+ Response.json({
+ errors: [{ extensions: { code: 'FORBIDDEN' } }],
+ }),
+ )
+ .mockImplementationOnce(
+ async () => new Response('unavailable', { status: 503 }),
+ );
+ await fetchWithRateLimitRetry('https://example.test/graphql', OPTIONS);
+ expect(
+ (await fetchWithRateLimitRetry('https://example.test/graphql', OPTIONS))
+ .status,
+ ).toBe(503);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-rate-limit-retry.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-rate-limit-retry.util.ts
new file mode 100644
index 00000000000..a5daffbc473
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-rate-limit-retry.util.ts
@@ -0,0 +1,94 @@
+import {
+ isNonEmptyArray,
+ isNumber,
+ isString,
+ isUndefined,
+} from '@sniptt/guards';
+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
+
+import { asRecord } from 'src/logic-functions/utils/as-record.util';
+import { fetchWithTransientRetry } from 'src/logic-functions/utils/fetch-with-transient-retry.util';
+
+const MAX_ATTEMPTS = 8;
+const MAX_TOTAL_WAIT_MS = 120_000;
+const MAX_RETRY_AFTER_MS = 60_000;
+
+const parseRetryAfterHeaderMs = (retryAfter: string | null): number => {
+ if (!isString(retryAfter)) {
+ return 0;
+ }
+
+ if (Number.isFinite(Number(retryAfter))) {
+ return Math.max(0, Number(retryAfter) * 1_000);
+ }
+
+ const delayMs = Date.parse(retryAfter) - Date.now();
+
+ return Number.isFinite(delayMs) ? Math.max(0, delayMs) : 0;
+};
+
+const getRateLimitDelayMs = async (
+ response: Response,
+): Promise<number | undefined> => {
+ const retryAfter = response.headers.get('retry-after');
+ const headerDelayMs = parseRetryAfterHeaderMs(retryAfter);
+
+ try {
+ const body = asRecord(await response.clone().json());
+ const errors = body?.errors;
+ const data = asRecord(body?.data);
+
+ // Retrying a partially successful mutation could repeat an already-applied write.
+ if (
+ isNonEmptyArray(errors) &&
+ Object.values(data ?? {}).every((value) => value === null) &&
+ errors.every(
+ (error) =>
+ asRecord(asRecord(error)?.extensions)?.code === 'RATE_LIMITED',
+ )
+ ) {
+ return Math.max(
+ 0,
+ ...errors.map((error) => {
+ const delayMs = asRecord(asRecord(error)?.extensions)?.retryAfterMs;
+ return isNumber(delayMs) && Number.isFinite(delayMs) ? delayMs : 0;
+ }),
+ );
+ }
+ } catch {
+ // An HTTP 429 may contain a proxy's plain-text body instead of GraphQL errors.
+ }
+
+ return response.status === 429 ? headerDelayMs : undefined;
+};
+
+export const fetchWithRateLimitRetry: typeof fetch = async (input, options) => {
+ let totalWaitMs = 0;
+
+ for (let attempt = 1; ; attempt += 1) {
+ const response = await fetchWithTransientRetry(input, options);
+ const retryAfterMs = await getRateLimitDelayMs(response);
+
+ if (isUndefined(retryAfterMs) || options?.signal?.aborted) {
+ return response;
+ }
+
+ const delayMs =
+ Math.max(
+ Math.min(2_000 * 2 ** (attempt - 1), 30_000),
+ Math.min(retryAfterMs, MAX_RETRY_AFTER_MS),
+ ) +
+ Math.random() * 1_000;
+
+ await response.body?.cancel();
+
+ if (attempt >= MAX_ATTEMPTS || totalWaitMs + delayMs > MAX_TOTAL_WAIT_MS) {
+ throw new RetryableLogicFunctionError(
+ '[call-recorder] Twenty API rate limit retry budget exhausted',
+ );
+ }
+
+ totalWaitMs += delayMs;
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ }
+};