Skip to content

The open alternative to Salesforce, designed for AI.

Call recorder: Pause recording when the workspace has no credits (#26151)

nitin086cf6101baf
diff --git a/packages/twenty-apps/public/call-recorder/README.md b/packages/twenty-apps/public/call-recorder/README.md
index e99b534d972..a02e7b91162 100644
--- a/packages/twenty-apps/public/call-recorder/README.md
+++ b/packages/twenty-apps/public/call-recorder/README.md
@@ -17,6 +17,12 @@ Metered in Twenty credits based on the bot's actual recording time, prorated by
duration — **$1.00 per recording-hour** (1 credit). No recording — opted out,
canceled, or no-show — means no charge.
+When the workspace cannot spend credits, each meeting is skipped shortly before
+its bot would join: the bot is canceled, or never created, and the recording is
+marked `NOT_RECORDED` with the reason. Later meetings are recorded again once
+credits are available; the skipped meeting itself is not retried. A call that
+is already being recorded is never cut short for credits.
+
AI summaries use workspace AI credits, billed on the model's token usage — the
cost scales with how much was said in the meeting, typically **$0.02–$0.06 per
meeting** on default models. Set the `CALL_RECORDER_SUMMARY_ENABLED` app
diff --git a/packages/twenty-apps/public/call-recorder/SETUP.md b/packages/twenty-apps/public/call-recorder/SETUP.md
index c401318e741..28ca325753f 100644
--- a/packages/twenty-apps/public/call-recorder/SETUP.md
+++ b/packages/twenty-apps/public/call-recorder/SETUP.md
@@ -98,6 +98,7 @@ webhook update is missed.
| Symptom | Likely cause | Fix |
|---|---|---|
| No bot joined a meeting | **Recording** was off, the event had no conference link, it wasn't synced from a connected calendar, or `RECALL_API_KEY` isn't set | Confirm the event is on, upcoming, has a video link, and came from a synced calendar; confirm `RECALL_API_KEY` is set |
+| Recording is `NOT_RECORDED` with reason `workspace_out_of_credits`, `workspace_without_subscription` or `workspace_suspended` | The workspace could not spend credits about ten minutes before the bot would have joined, so the bot was canceled or never created | Top up credits or fix the subscription in **Settings → Billing**; later meetings are recorded again, the skipped meeting is not retried |
| Recording never reaches `COMPLETED` | A Recall webhook was missed, or only one of audio/video was produced | The reconciliation job pulls the latest status from Recall within a few minutes; if it is marked `FAILED`, inspect the bot in the Recall dashboard |
| Transcript empty, or marked pending/failed | Recall hasn't finished async transcription yet, or transcription failed for that call | Wait for the reconciliation job to ingest the transcript; a persistent failure leaves a marker in the transcript |
| Webhook rejected with `500` (`Invalid webhook signature`, Recall keeps retrying) | `RECALL_WEBHOOK_SECRET` doesn't match the Recall endpoint's signing secret | Re-copy the `whsec_…` secret from the Recall webhook endpoint into the `RECALL_WEBHOOK_SECRET` server variable |
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 6872ac25f3a..3395602d665 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
@@ -16,6 +16,7 @@ import {
import {
APPLICATION_UNIVERSAL_IDENTIFIER,
+ CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';
import { type CallRecorderPreference } from 'src/constants/call-recorder-preference';
@@ -27,6 +28,9 @@ import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/en
import { saveCallRecordingImportProgress } from 'src/logic-functions/data/save-call-recording-import-progress.util';
import { convergeDivergedCallRecordings } from 'src/logic-functions/flows/converge-diverged-call-recordings.util';
import { handleCallRecordingArtifactsImportJob } from 'src/logic-functions/flows/handle-call-recording-artifacts-import-job.util';
+import { handlePreJoinCreditCheckJob } from 'src/logic-functions/flows/handle-pre-join-credit-check-job.util';
+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';
@@ -219,6 +223,12 @@ class FakeRecallApi {
artifactImportRequests: object[] = [];
activeArtifactJobIds = new Set<string>();
recoveryRequests: object[] = [];
+ creditCheckRequests: object[] = [];
+ // Undefined lets the credit verdict fall through to the real server.
+ creditAvailability:
+ | { hasAvailableCredits: true }
+ | { hasAvailableCredits: false; reason: string }
+ | undefined = undefined;
hasExpiredMedia = false;
failNextDelete = false;
failCalendarEventUpdates = false;
@@ -312,6 +322,13 @@ class FakeRecallApi {
handle(requestUrl: string, requestInit?: any): Response | undefined {
const method: string = requestInit?.method ?? 'GET';
+ if (
+ requestUrl === `${process.env.TWENTY_API_URL}/app/billing/credits` &&
+ this.creditAvailability !== undefined
+ ) {
+ return jsonResponse(200, this.creditAvailability);
+ }
+
if (
requestUrl === `${process.env.TWENTY_API_URL}/metadata` &&
String(requestInit?.body ?? '').includes('getJobs')
@@ -349,6 +366,11 @@ class FakeRecallApi {
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);
}
@@ -1074,6 +1096,7 @@ describe('call recorder app lifecycle (integration)', () => {
expect(recall.bots.get(botId)?.metadata).toEqual(
buildBotMetadata(callRecordingId, workspaceId),
);
+ expect(recall.creditCheckRequests).toEqual([{ callRecordingId }]);
});
it('creates nothing for a meeting without a conference link', async () => {
@@ -1094,6 +1117,120 @@ describe('call recorder app lifecycle (integration)', () => {
});
});
+ describe('credit gate', () => {
+ it('cancels the scheduled bot before it joins when the workspace cannot spend credits', async () => {
+ const { callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ recall.creditAvailability = {
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ };
+
+ const result = await handlePreJoinCreditCheckJob(
+ recall.creditCheckRequests[0],
+ );
+ const callRecording = await fetchCallRecording(callRecordingId);
+
+ expect(result).toEqual({
+ status: 'blocked',
+ failureReason: 'workspace_out_of_credits',
+ });
+ expect(recall.deletedBotIds).toEqual([botId]);
+ expect(callRecording.status).toBe('NOT_RECORDED');
+ expect(callRecording.callRecorderFailureReason).toBe(
+ 'workspace_out_of_credits',
+ );
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(callRecording.botScheduleIdempotencyKey).toBeFalsy();
+ });
+
+ it('leaves the bot alone when the workspace can spend credits', async () => {
+ const { callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ recall.creditAvailability = { hasAvailableCredits: true };
+
+ const result = await handlePreJoinCreditCheckJob(
+ recall.creditCheckRequests[0],
+ );
+ const callRecording = await fetchCallRecording(callRecordingId);
+
+ expect(result).toEqual({ status: 'allowed' });
+ expect(recall.deletedBotIds).toEqual([]);
+ expect(callRecording.status).toBe('SCHEDULED');
+ expect(callRecording.externalBotId).toBe(botId);
+ });
+
+ it('runs the queued check through the real worker and leaves a funded bot alone', async ({
+ skip,
+ }) => {
+ const { findManyLogicFunctions } = await new MetadataApiClient().query({
+ findManyLogicFunctions: { name: true },
+ });
+
+ if (
+ !findManyLogicFunctions.some(
+ ({ name }) => name === 'check-credits-before-recall-bot-join',
+ )
+ ) {
+ skip('the installed call recorder predates the credit check');
+ }
+
+ const { callRecordingId, botId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+
+ // The worker runs this job, so the enqueue and the job reads must reach the real server.
+ vi.unstubAllGlobals();
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', applicationAccessToken);
+
+ const joinAt = new Date(
+ Date.now() + PRE_JOIN_CREDIT_CHECK_LEAD_MINUTES * 60 * 1000,
+ ).toISOString();
+ const jobId = `credit-check.${callRecordingId}.${botId}.${new Date(joinAt).getTime()}`;
+
+ await enqueuePreJoinCreditCheck({
+ callRecordingId,
+ externalBotId: botId,
+ joinAt,
+ });
+
+ await expect
+ .poll(() => getJobs([jobId]), { timeout: 30_000, interval: 500 })
+ .toMatchObject([{ jobId, state: 'COMPLETED' }]);
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+
+ expect(callRecording.status).toBe('SCHEDULED');
+ expect(callRecording.externalBotId).toBe(botId);
+ });
+
+ it('creates no bot for a meeting about to start when the workspace cannot spend credits', async () => {
+ recall.creditAvailability = {
+ hasAvailableCredits: false,
+ reason: 'no-subscription',
+ };
+ const calendarEventId = await createCalendarEvent({
+ startsAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(),
+ });
+
+ const [reconciliation] = await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+ const [callRecording] = await findCallRecordings({
+ calendarEventId: { in: [calendarEventId] },
+ });
+
+ expect(reconciliation.action).toBe('CREATED');
+ expect(callRecording.status).toBe('NOT_RECORDED');
+ expect(callRecording.callRecorderFailureReason).toBe(
+ 'workspace_without_subscription',
+ );
+ expect(callRecording.externalBotId).toBeFalsy();
+ expect(recall.bots.size).toBe(0);
+ expect(recall.creditCheckRequests).toEqual([]);
+ });
+ });
+
describe('Recall webhook lifecycle', () => {
it('moves the recording through joining, recording, and processing', async () => {
const { callRecordingId, botId, metadata } =
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 aea83c50b19..ee7af0c02a5 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
@@ -73,6 +73,9 @@ export const CANCEL_RECALL_BOT_ON_CALL_RECORDING_DELETE_LOGIC_FUNCTION_UNIVERSAL
export const CANCEL_RECALL_BOTS_ON_UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'8f00ec95-38f0-4dc7-816a-78374affa32a';
+export const CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ 'bf482989-973e-48be-994e-050431686994';
+
export const CLEANUP_ORPHANED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'fa394597-dc73-4fee-9758-dea7401b0b8f';
diff --git a/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-failure-reason-on-call-recording.field.ts b/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-failure-reason-on-call-recording.field.ts
index 70296b05043..53bf446116f 100644
--- a/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-failure-reason-on-call-recording.field.ts
+++ b/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-failure-reason-on-call-recording.field.ts
@@ -15,7 +15,7 @@ export default defineField({
name: 'callRecorderFailureReason',
label: 'Call Recorder Failure Reason',
description:
- 'Provider-specific reason the call recorder could not produce a recording.',
+ 'Why the call recorder could not produce a recording: a provider outcome or a workspace billing state.',
icon: 'IconAlertTriangle',
isNullable: true,
isUIEditable: false,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/check-credits-before-recall-bot-join.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/check-credits-before-recall-bot-join.test.ts
new file mode 100644
index 00000000000..97ed673f543
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/check-credits-before-recall-bot-join.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { handlePreJoinCreditCheckJob } from 'src/logic-functions/flows/handle-pre-join-credit-check-job.util';
+
+const queryMock = vi.hoisted(() => vi.fn());
+const mutationMock = vi.hoisted(() => vi.fn());
+const getCreditAvailabilityMock = vi.hoisted(() => vi.fn());
+
+vi.mock('twenty-client-sdk/core', () => ({
+ CoreApiClient: class {
+ query = queryMock;
+ mutation = mutationMock;
+ },
+}));
+
+vi.mock('twenty-sdk/billing', () => ({
+ getCreditAvailability: getCreditAvailabilityMock,
+}));
+
+const fetchMock = vi.fn();
+
+const NOW = new Date('2026-01-01T12:49:00.000Z');
+
+const buildConnection = <TNode>(nodes: TNode[]) => ({
+ pageInfo: { hasNextPage: false, endCursor: undefined },
+ edges: nodes.map((node) => ({ node })),
+});
+
+describe('check-credits-before-recall-bot-join', () => {
+ 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');
+ fetchMock.mockReset();
+ queryMock.mockReset();
+ mutationMock.mockReset();
+ getCreditAvailabilityMock.mockReset();
+ queryMock.mockImplementation(async (query) =>
+ query.callRecordings !== undefined
+ ? {
+ callRecordings: buildConnection([
+ {
+ id: 'call-recording-1',
+ status: 'SCHEDULED',
+ recordingRequestStatus: 'REQUESTED',
+ calendarEventId: 'calendar-event-1',
+ externalBotId: 'recall-bot-1',
+ },
+ ]),
+ }
+ : {
+ calendarEvents: buildConnection([
+ { id: 'calendar-event-1', startsAt: '2026-01-01T13:00:00.000Z' },
+ ]),
+ },
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('asks the queue to redeliver when Recall refuses the cancellation', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ fetchMock.mockImplementation(
+ async () => new Response(null, { status: 403 }),
+ );
+
+ await expect(
+ handlePreJoinCreditCheckJob({ callRecordingId: 'call-recording-1' }),
+ ).rejects.toMatchObject({ name: 'RetryableLogicFunctionError' });
+
+ expect(mutationMock).not.toHaveBeenCalled();
+ });
+});
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 bdad0f7790f..8b410f79cea 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
@@ -14,6 +14,13 @@ vi.mock('twenty-client-sdk/core', () => ({
},
}));
+const enqueueJobsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+
const fetchMock = vi.fn();
const NOW = new Date('2026-01-01T12:00:00.000Z');
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/check-credits-before-recall-bot-join.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/check-credits-before-recall-bot-join.ts
new file mode 100644
index 00000000000..72bd6d68b48
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/check-credits-before-recall-bot-join.ts
@@ -0,0 +1,14 @@
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import { CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { handlePreJoinCreditCheckJob } from 'src/logic-functions/flows/handle-pre-join-credit-check-job.util';
+
+export default defineLogicFunction({
+ universalIdentifier:
+ CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'check-credits-before-recall-bot-join',
+ description:
+ 'Cancels a scheduled Recall bot shortly before it joins when the workspace has no credits.',
+ timeoutSeconds: 60,
+ handler: handlePreJoinCreditCheckJob,
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/failure-reason-by-credit-unavailable-reason.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/failure-reason-by-credit-unavailable-reason.ts
new file mode 100644
index 00000000000..aee50d45b34
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/failure-reason-by-credit-unavailable-reason.ts
@@ -0,0 +1,10 @@
+import { type CreditUnavailableReason } from 'src/logic-functions/types/credit-unavailable-reason.type';
+
+export const FAILURE_REASON_BY_CREDIT_UNAVAILABLE_REASON: Record<
+ CreditUnavailableReason,
+ string
+> = {
+ 'no-credits': 'workspace_out_of_credits',
+ 'no-subscription': 'workspace_without_subscription',
+ 'workspace-suspended': 'workspace_suspended',
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/pre-join-credit-check-lead-minutes.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/pre-join-credit-check-lead-minutes.ts
new file mode 100644
index 00000000000..2cf1b3c1b44
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/pre-join-credit-check-lead-minutes.ts
@@ -0,0 +1,2 @@
+// Late enough for a top-up to count, early enough for the queue retries of a failed cancellation.
+export const PRE_JOIN_CREDIT_CHECK_LEAD_MINUTES = 10;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-bot-already-joined-status.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-bot-already-joined-status.ts
new file mode 100644
index 00000000000..d1dad513766
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-bot-already-joined-status.ts
@@ -0,0 +1,2 @@
+// Recall refuses to delete a bot once it has started joining: 405 cannot_delete_bot.
+export const RECALL_BOT_ALREADY_JOINED_STATUS = 405;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-pre-join-credit-check.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-pre-join-credit-check.util.ts
new file mode 100644
index 00000000000..52ae79587ed
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-pre-join-credit-check.util.ts
@@ -0,0 +1,45 @@
+import { enqueueJobs } from 'twenty-sdk/logic-function';
+
+import { CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+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 { PRE_JOIN_CREDIT_CHECK_LEAD_MINUTES } from 'src/logic-functions/constants/pre-join-credit-check-lead-minutes';
+
+export const enqueuePreJoinCreditCheck = async ({
+ callRecordingId,
+ externalBotId,
+ joinAt,
+}: {
+ callRecordingId: string;
+ externalBotId: string;
+ joinAt: string;
+}): Promise<void> => {
+ const joinAtMilliseconds = new Date(joinAt).getTime();
+ const checkAtMilliseconds =
+ joinAtMilliseconds -
+ PRE_JOIN_CREDIT_CHECK_LEAD_MINUTES * MILLISECONDS_PER_MINUTE;
+
+ try {
+ await enqueueJobs({
+ logicFunctionUniversalIdentifier:
+ CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [
+ {
+ // A re-created or rescheduled bot gets its own check; the queue keeps a completed id for hours.
+ jobId: `credit-check.${callRecordingId}.${externalBotId}.${joinAtMilliseconds}`,
+ payload: { callRecordingId },
+ },
+ ],
+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,
+ // The server rejects a negative delay.
+ delayMs: Math.max(0, checkAtMilliseconds - Date.now()),
+ });
+ } catch (error) {
+ // Fail open: a missed check means a charged recording, not a failed schedule.
+ console.warn(
+ `[call-recorder] failed to enqueue the pre-join credit check for callRecording ${callRecordingId}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/get-credits-unavailable-failure-reason.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/get-credits-unavailable-failure-reason.util.ts
new file mode 100644
index 00000000000..a76a207d609
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/get-credits-unavailable-failure-reason.util.ts
@@ -0,0 +1,13 @@
+import { getCreditAvailability } from 'twenty-sdk/billing';
+
+import { FAILURE_REASON_BY_CREDIT_UNAVAILABLE_REASON } from 'src/logic-functions/constants/failure-reason-by-credit-unavailable-reason';
+
+export const getCreditsUnavailableFailureReason = async (): Promise<
+ string | undefined
+> => {
+ const creditAvailability = await getCreditAvailability();
+
+ return creditAvailability.hasAvailableCredits
+ ? undefined
+ : FAILURE_REASON_BY_CREDIT_UNAVAILABLE_REASON[creditAvailability.reason];
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/mark-call-recording-not-recorded.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/mark-call-recording-not-recorded.util.ts
new file mode 100644
index 00000000000..4e7a54a60ad
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/mark-call-recording-not-recorded.util.ts
@@ -0,0 +1,34 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { updateNonTerminalCallRecordingState } from 'src/logic-functions/data/update-non-terminal-call-recording-state.util';
+
+export const markCallRecordingNotRecorded = async (
+ client: CoreApiClient,
+ {
+ callRecordingId,
+ failureReason,
+ }: {
+ callRecordingId: string;
+ failureReason: string;
+ },
+): Promise<boolean> => {
+ const didUpdate = await updateNonTerminalCallRecordingState(client, {
+ callRecordingId,
+ data: {
+ status: CallRecordingStatus.NOT_RECORDED,
+ callRecorderFailureReason: failureReason,
+ externalBotId: null,
+ botScheduleAttemptedAt: null,
+ botScheduleIdempotencyKey: null,
+ },
+ });
+
+ if (didUpdate) {
+ console.warn(
+ `[call-recorder] callRecording ${callRecordingId} will not be recorded: ${failureReason}`,
+ );
+ }
+
+ return didUpdate;
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-non-terminal-call-recording-state.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-non-terminal-call-recording-state.util.ts
index 6002833d357..943afca52ef 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-non-terminal-call-recording-state.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-non-terminal-call-recording-state.util.ts
@@ -6,7 +6,11 @@ import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-r
type CallRecordingStateUpdate = Pick<
CallRecordingUpdateFields,
- 'status' | 'callRecorderFailureReason'
+ | 'status'
+ | 'callRecorderFailureReason'
+ | 'externalBotId'
+ | 'botScheduleAttemptedAt'
+ | 'botScheduleIdempotencyKey'
>;
export const updateNonTerminalCallRecordingState = async (
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/is-recall-bot-join-within-credit-check-lead.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/is-recall-bot-join-within-credit-check-lead.test.ts
new file mode 100644
index 00000000000..6096411a3bd
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/is-recall-bot-join-within-credit-check-lead.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { isRecallBotJoinWithinCreditCheckLead } from 'src/logic-functions/domain/is-recall-bot-join-within-credit-check-lead.util';
+
+const NOW = new Date('2026-01-01T12:00:00.000Z');
+
+describe('isRecallBotJoinWithinCreditCheckLead', () => {
+ it('is within the lead exactly ten minutes before the join', () => {
+ expect(
+ isRecallBotJoinWithinCreditCheckLead({
+ joinAt: '2026-01-01T12:10:00.000Z',
+ now: NOW,
+ }),
+ ).toBe(true);
+ });
+
+ it('is outside the lead one millisecond earlier', () => {
+ expect(
+ isRecallBotJoinWithinCreditCheckLead({
+ joinAt: '2026-01-01T12:10:00.001Z',
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+
+ it('is within the lead once the join time has passed', () => {
+ expect(
+ isRecallBotJoinWithinCreditCheckLead({
+ joinAt: '2026-01-01T11:30:00.000Z',
+ now: NOW,
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-recall-bot-join-within-credit-check-lead.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-recall-bot-join-within-credit-check-lead.util.ts
new file mode 100644
index 00000000000..b4d395ad954
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-recall-bot-join-within-credit-check-lead.util.ts
@@ -0,0 +1,12 @@
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { PRE_JOIN_CREDIT_CHECK_LEAD_MINUTES } from 'src/logic-functions/constants/pre-join-credit-check-lead-minutes';
+
+export const isRecallBotJoinWithinCreditCheckLead = ({
+ joinAt,
+ now,
+}: {
+ joinAt: string;
+ now: Date;
+}): boolean =>
+ new Date(joinAt).getTime() - now.getTime() <=
+ PRE_JOIN_CREDIT_CHECK_LEAD_MINUTES * MILLISECONDS_PER_MINUTE;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/check-credits-before-recall-bot-join.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/check-credits-before-recall-bot-join.test.ts
new file mode 100644
index 00000000000..f4f43120b7a
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/check-credits-before-recall-bot-join.test.ts
@@ -0,0 +1,352 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { checkCreditsBeforeRecallBotJoin } from 'src/logic-functions/flows/check-credits-before-recall-bot-join.util';
+
+const getCreditAvailabilityMock = vi.hoisted(() => vi.fn());
+
+vi.mock('twenty-sdk/billing', () => ({
+ getCreditAvailability: getCreditAvailabilityMock,
+}));
+
+const fetchMock = vi.fn();
+
+const MEETING_STARTS_AT = '2026-01-01T13:00:00.000Z';
+const JOIN_AT = '2026-01-01T12:59:00.000Z';
+const TEN_MINUTES_BEFORE_JOIN = new Date('2026-01-01T12:49:00.000Z');
+const RECALL_BOT_URL = 'https://us-west-2.recall.ai/api/v1/bot/recall-bot-1/';
+
+type CallRecordingNode = {
+ id: string;
+ status: string;
+ recordingRequestStatus: string;
+ calendarEventId: string | null;
+ externalBotId: string | null;
+ botScheduleAttemptedAt?: string | null;
+ botScheduleIdempotencyKey?: string | null;
+ callRecorderFailureReason?: string | null;
+};
+
+const buildConnection = <TNode>(nodes: TNode[]) => ({
+ pageInfo: { hasNextPage: false, endCursor: undefined },
+ edges: nodes.map((node) => ({ node })),
+});
+
+class FakeCoreApiClient {
+ callRecording: CallRecordingNode;
+ meetingStartsAt: string | null;
+
+ constructor({
+ callRecording = {},
+ meetingStartsAt = MEETING_STARTS_AT,
+ }: {
+ callRecording?: Partial<CallRecordingNode>;
+ meetingStartsAt?: string | null;
+ } = {}) {
+ this.callRecording = {
+ id: 'call-recording-1',
+ status: 'SCHEDULED',
+ recordingRequestStatus: 'REQUESTED',
+ calendarEventId: 'calendar-event-1',
+ externalBotId: 'recall-bot-1',
+ botScheduleAttemptedAt: '2026-01-01T08:00:00.000Z',
+ botScheduleIdempotencyKey: 'idempotency-key',
+ ...callRecording,
+ };
+ this.meetingStartsAt = meetingStartsAt;
+ }
+
+ async query(query: any): Promise<any> {
+ if (query.callRecordings !== undefined) {
+ return { callRecordings: buildConnection([this.callRecording]) };
+ }
+
+ if (query.calendarEvents !== undefined) {
+ return {
+ calendarEvents: buildConnection([
+ {
+ id: 'calendar-event-1',
+ startsAt: this.meetingStartsAt,
+ endsAt: '2026-01-01T14:00:00.000Z',
+ conferenceLink: {
+ primaryLinkUrl: 'https://meet.example.com/customer-sync',
+ },
+ },
+ ]),
+ };
+ }
+
+ 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 isMatch =
+ filter.id.eq === this.callRecording.id &&
+ filter.status.in.includes(this.callRecording.status);
+
+ if (isMatch) {
+ Object.assign(this.callRecording, data);
+ }
+
+ return {
+ updateCallRecordings: isMatch ? [{ id: this.callRecording.id }] : [],
+ };
+ }
+
+ if (mutation.updateCallRecording !== undefined) {
+ Object.assign(
+ this.callRecording,
+ mutation.updateCallRecording.__args.data,
+ );
+
+ return { updateCallRecording: { id: this.callRecording.id } };
+ }
+
+ throw new Error(`Unhandled mutation: ${JSON.stringify(mutation)}`);
+ }
+}
+
+const checkCredits = ({
+ client,
+ now,
+}: {
+ client: FakeCoreApiClient;
+ now: Date;
+}) =>
+ checkCreditsBeforeRecallBotJoin({
+ client: client as unknown as CoreApiClient,
+ callRecordingId: 'call-recording-1',
+ now,
+ });
+
+const stubRecallBotRemoval = (status: number) => {
+ fetchMock.mockImplementation(async () => new Response(null, { status }));
+};
+
+describe('checkCreditsBeforeRecallBotJoin', () => {
+ 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');
+ fetchMock.mockReset();
+ getCreditAvailabilityMock.mockReset();
+ stubRecallBotRemoval(204);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it('leaves the bot alone when the workspace has credits', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({ hasAvailableCredits: true });
+ const client = new FakeCoreApiClient();
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result).toEqual({ status: 'allowed' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(client.callRecording.status).toBe('SCHEDULED');
+ expect(client.callRecording.externalBotId).toBe('recall-bot-1');
+ });
+
+ it('cancels the bot and marks the recording not recorded when the workspace is out of credits', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ const client = new FakeCoreApiClient();
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result).toEqual({
+ status: 'blocked',
+ failureReason: 'workspace_out_of_credits',
+ });
+ expect(fetchMock).toHaveBeenCalledExactlyOnceWith(
+ RECALL_BOT_URL,
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ expect(client.callRecording).toMatchObject({
+ status: 'NOT_RECORDED',
+ callRecorderFailureReason: 'workspace_out_of_credits',
+ externalBotId: null,
+ botScheduleAttemptedAt: null,
+ botScheduleIdempotencyKey: null,
+ });
+ });
+
+ it.each([
+ ['no-subscription', 'workspace_without_subscription'],
+ ['workspace-suspended', 'workspace_suspended'],
+ ])(
+ 'blocks the recording when the verdict is %s',
+ async (reason, failureReason) => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason,
+ });
+ const client = new FakeCoreApiClient();
+
+ const result = await checkCredits({
+ client,
+ now: TEN_MINUTES_BEFORE_JOIN,
+ });
+
+ expect(result).toEqual({ status: 'blocked', failureReason });
+ expect(client.callRecording.callRecorderFailureReason).toBe(
+ failureReason,
+ );
+ },
+ );
+
+ it('never reads the verdict for a call that is already being recorded', async () => {
+ const client = new FakeCoreApiClient({
+ callRecording: { status: 'RECORDING' },
+ });
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result.status).toBe('skipped');
+ expect(getCreditAvailabilityMock).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(client.callRecording.status).toBe('RECORDING');
+ });
+
+ it('does nothing once the bot join time has passed', async () => {
+ const client = new FakeCoreApiClient();
+
+ const result = await checkCredits({ client, now: new Date(JOIN_AT) });
+
+ expect(result).toEqual({
+ status: 'skipped',
+ reason: 'bot join time has passed',
+ });
+ expect(getCreditAvailabilityMock).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('reads the join time from the calendar event, not from when the job was enqueued', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ const client = new FakeCoreApiClient({
+ meetingStartsAt: '2026-01-01T12:45:00.000Z',
+ });
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result).toEqual({
+ status: 'skipped',
+ reason: 'bot join time has passed',
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when the meeting has no start time', async () => {
+ const client = new FakeCoreApiClient({ meetingStartsAt: null });
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result).toEqual({
+ status: 'skipped',
+ reason: 'meeting has no start time',
+ });
+ expect(getCreditAvailabilityMock).not.toHaveBeenCalled();
+ });
+
+ it('throws and keeps the recording scheduled when Recall refuses the cancellation', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ stubRecallBotRemoval(403);
+ const client = new FakeCoreApiClient();
+
+ await expect(
+ checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN }),
+ ).rejects.toThrow('could not be canceled');
+
+ expect(client.callRecording.status).toBe('SCHEDULED');
+ expect(client.callRecording.externalBotId).toBe('recall-bot-1');
+ });
+
+ it('leaves a bot that has already joined alone instead of ejecting it', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ stubRecallBotRemoval(405);
+ const client = new FakeCoreApiClient();
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result).toEqual({
+ status: 'skipped',
+ reason: 'bot has already joined',
+ });
+ expect(fetchMock).toHaveBeenCalledExactlyOnceWith(
+ RECALL_BOT_URL,
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ expect(client.callRecording.status).toBe('SCHEDULED');
+ expect(client.callRecording.externalBotId).toBe('recall-bot-1');
+ });
+
+ it('does nothing for the canceled recording of a meeting that moved', async () => {
+ const client = new FakeCoreApiClient({
+ callRecording: {
+ recordingRequestStatus: 'CANCELED',
+ externalBotId: null,
+ },
+ });
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result.status).toBe('skipped');
+ expect(getCreditAvailabilityMock).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('treats a bot that is already gone as canceled so a retried job completes', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ stubRecallBotRemoval(404);
+ const client = new FakeCoreApiClient();
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result.status).toBe('blocked');
+ expect(client.callRecording.status).toBe('NOT_RECORDED');
+ });
+
+ it('leaves a terminal status untouched when it changed while the bot was being canceled', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ const client = new FakeCoreApiClient();
+ fetchMock.mockImplementation(async () => {
+ client.callRecording.status = 'FAILED';
+
+ return new Response(null, { status: 204 });
+ });
+
+ const result = await checkCredits({ client, now: TEN_MINUTES_BEFORE_JOIN });
+
+ expect(result.status).toBe('skipped');
+ expect(client.callRecording).toMatchObject({
+ status: 'FAILED',
+ externalBotId: 'recall-bot-1',
+ botScheduleIdempotencyKey: 'idempotency-key',
+ });
+ expect(client.callRecording.callRecorderFailureReason).toBeUndefined();
+ });
+});
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 265457806aa..26d66006181 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
@@ -4,6 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { computeCallRecordingIdForMeeting } from 'src/logic-functions/domain/compute-call-recording-id-for-meeting.util';
import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';
+const enqueueJobsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+
const fetchMock = vi.fn();
const NOW = new Date('2026-01-01T12:00:00.000Z');
@@ -255,6 +262,7 @@ describe('reconcileCallRecorderForCalendarEventIds', () => {
vi.stubEnv('RECALL_API_KEY', 'recall-api-key');
vi.stubEnv('RECALL_REGION', 'us-west-2');
vi.stubEnv('CALL_RECORDER_USE_WORKSPACE_LOGO', 'false');
+ enqueueJobsMock.mockReset();
fetchMock.mockReset();
fetchMock.mockImplementation(
async (requestUrl: string, requestInit: RequestInit) => {
@@ -503,6 +511,16 @@ describe('reconcileCallRecorderForCalendarEventIds', () => {
},
}),
);
+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ jobs: [
+ {
+ jobId: `credit-check.${buildCustomerSyncCallRecordingId()}.recall-bot-1.${new Date(FUTURE_RECALL_BOT_JOIN_AT).getTime()}`,
+ payload: { callRecordingId: buildCustomerSyncCallRecordingId() },
+ },
+ ],
+ }),
+ );
});
it('replaces a stale visible title with the fallback title when the calendar title becomes unavailable', async () => {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bot-for-call-recording.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bot-for-call-recording.test.ts
new file mode 100644
index 00000000000..18f3110053e
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bot-for-call-recording.test.ts
@@ -0,0 +1,229 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';
+import { scheduleRecallBotForCallRecording } from 'src/logic-functions/flows/schedule-recall-bot-for-call-recording.util';
+
+const getCreditAvailabilityMock = vi.hoisted(() => vi.fn());
+const enqueueJobsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('twenty-sdk/billing', () => ({
+ getCreditAvailability: getCreditAvailabilityMock,
+}));
+
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+
+const fetchMock = vi.fn();
+
+const NOW = new Date('2026-01-01T12:00:00.000Z');
+const WORKSPACE_ID = '123e4567-e89b-12d3-a456-426614174000';
+const MEETING_IN_ONE_HOUR_STARTS_AT = '2026-01-01T13:00:00.000Z';
+const MEETING_IN_FIVE_MINUTES_STARTS_AT = '2026-01-01T12:05:00.000Z';
+const RECALL_CREATE_BOT_URL = 'https://us-west-2.recall.ai/api/v1/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('.');
+
+type CallRecordingNode = {
+ id: string;
+ status: string;
+ recordingRequestStatus: string;
+ calendarEventId: string;
+ externalBotId: string | null;
+ callRecorderFailureReason?: string | null;
+};
+
+class FakeCoreApiClient {
+ callRecording: CallRecordingNode = {
+ id: 'call-recording-1',
+ status: 'SCHEDULED',
+ recordingRequestStatus: 'REQUESTED',
+ calendarEventId: 'calendar-event-1',
+ externalBotId: null,
+ };
+
+ async query(query: any): Promise<any> {
+ if (query.callRecordings !== undefined) {
+ return {
+ callRecordings: {
+ pageInfo: { hasNextPage: false, endCursor: undefined },
+ edges: [{ node: this.callRecording }],
+ },
+ };
+ }
+
+ 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 isMatch = filter.status.in.includes(this.callRecording.status);
+
+ if (isMatch) {
+ Object.assign(this.callRecording, data);
+ }
+
+ return {
+ updateCallRecordings: isMatch ? [{ id: this.callRecording.id }] : [],
+ };
+ }
+
+ if (mutation.updateCallRecording !== undefined) {
+ Object.assign(
+ this.callRecording,
+ mutation.updateCallRecording.__args.data,
+ );
+
+ return { updateCallRecording: { id: this.callRecording.id } };
+ }
+
+ throw new Error(`Unhandled mutation: ${JSON.stringify(mutation)}`);
+ }
+}
+
+const scheduleBot = ({
+ client,
+ meetingStartsAt,
+}: {
+ client: FakeCoreApiClient;
+ meetingStartsAt: string;
+}) =>
+ scheduleRecallBotForCallRecording(client as unknown as CoreApiClient, {
+ callRecording: { id: 'call-recording-1' },
+ calendarEvent: {
+ id: 'calendar-event-1',
+ title: 'Customer sync',
+ isCanceled: false,
+ startsAt: meetingStartsAt,
+ endsAt: '2026-01-01T14:00:00.000Z',
+ iCalUid: 'calendar-event-uid',
+ conferenceLinkUrl: 'https://meet.example.com/customer-sync',
+ callRecorderPreference: 'ON',
+ },
+ });
+
+const createBotCalls = () =>
+ fetchMock.mock.calls.filter(
+ ([requestUrl, requestInit]) =>
+ requestUrl === RECALL_CREATE_BOT_URL && requestInit?.method === 'POST',
+ );
+
+describe('scheduleRecallBotForCallRecording', () => {
+ 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();
+ fetchMock.mockImplementation(
+ async () =>
+ new Response(JSON.stringify({ id: 'recall-bot-1' }), { status: 201 }),
+ );
+ getCreditAvailabilityMock.mockReset();
+ enqueueJobsMock.mockReset();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('enqueues the credit check ten minutes before the join for a meeting that is far enough away', async () => {
+ const client = new FakeCoreApiClient();
+
+ const scheduleResult = await scheduleBot({
+ client,
+ meetingStartsAt: MEETING_IN_ONE_HOUR_STARTS_AT,
+ });
+
+ expect(scheduleResult).toEqual({ status: 'scheduled' });
+ expect(client.callRecording.externalBotId).toBe('recall-bot-1');
+ expect(getCreditAvailabilityMock).not.toHaveBeenCalled();
+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({
+ logicFunctionUniversalIdentifier:
+ CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [
+ {
+ jobId: `credit-check.call-recording-1.recall-bot-1.${new Date('2026-01-01T12:59:00.000Z').getTime()}`,
+ payload: { callRecordingId: 'call-recording-1' },
+ },
+ ],
+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,
+ delayMs: 49 * 60_000,
+ });
+ });
+
+ it('creates no bot for a meeting about to start when the workspace is out of credits', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ const client = new FakeCoreApiClient();
+
+ const scheduleResult = await scheduleBot({
+ client,
+ meetingStartsAt: MEETING_IN_FIVE_MINUTES_STARTS_AT,
+ });
+
+ expect(scheduleResult).toEqual({
+ status: 'blocked',
+ failureReason: 'workspace_out_of_credits',
+ });
+ expect(createBotCalls()).toHaveLength(0);
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
+ expect(client.callRecording).toMatchObject({
+ status: 'NOT_RECORDED',
+ callRecorderFailureReason: 'workspace_out_of_credits',
+ externalBotId: null,
+ });
+ });
+
+ it('creates the bot without a delayed check for a meeting about to start when credits are available', async () => {
+ getCreditAvailabilityMock.mockResolvedValue({ hasAvailableCredits: true });
+ const client = new FakeCoreApiClient();
+
+ const scheduleResult = await scheduleBot({
+ client,
+ meetingStartsAt: MEETING_IN_FIVE_MINUTES_STARTS_AT,
+ });
+
+ expect(scheduleResult).toEqual({ status: 'scheduled' });
+ expect(createBotCalls()).toHaveLength(1);
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
+ expect(client.callRecording.status).toBe('SCHEDULED');
+ });
+
+ it('still schedules the bot when the credit check cannot be enqueued', async () => {
+ enqueueJobsMock.mockRejectedValue(new Error('queue unavailable'));
+ const client = new FakeCoreApiClient();
+
+ const scheduleResult = await scheduleBot({
+ client,
+ meetingStartsAt: MEETING_IN_ONE_HOUR_STARTS_AT,
+ });
+
+ expect(scheduleResult).toEqual({ status: 'scheduled' });
+ expect(client.callRecording.externalBotId).toBe('recall-bot-1');
+ expect(console.warn).toHaveBeenCalledWith(
+ expect.stringContaining('failed to enqueue the pre-join credit check'),
+ );
+ });
+});
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
index 86a57da5879..5989c15e179 100644
--- 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
@@ -5,6 +5,13 @@ import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recal
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';
@@ -198,6 +205,7 @@ describe('scheduleRecallBotsForPendingCallRecordings', () => {
buildAccessToken({ workspaceId: WORKSPACE_ID }),
);
fetchMock.mockReset();
+ enqueueJobsMock.mockReset();
stubRecallApi();
});
@@ -272,6 +280,16 @@ describe('scheduleRecallBotsForPendingCallRecordings', () => {
expect(result.attachedCallRecordingIds).toEqual(['call-recording-1']);
expect(result.scheduledCallRecordingIds).toEqual([]);
expect(createBotCalls()).toHaveLength(0);
+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ jobs: [
+ {
+ jobId: `credit-check.call-recording-1.recall-bot-existing.${new Date(computeRecallBotJoinAt(UPCOMING_STARTS_AT)).getTime()}`,
+ payload: { callRecordingId: 'call-recording-1' },
+ },
+ ],
+ }),
+ );
const lookupParameters = new URL(listBotRequestUrls()[0]).searchParams;
expect(lookupParameters.get('metadata__twentyWorkspaceId')).toBe(
WORKSPACE_ID,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/check-credits-before-recall-bot-join.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/check-credits-before-recall-bot-join.util.ts
new file mode 100644
index 00000000000..2526c46bcfb
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/check-credits-before-recall-bot-join.util.ts
@@ -0,0 +1,103 @@
+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 { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { RECALL_BOT_ALREADY_JOINED_STATUS } from 'src/logic-functions/constants/recall-bot-already-joined-status';
+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 { getCreditsUnavailableFailureReason } from 'src/logic-functions/data/get-credits-unavailable-failure-reason.util';
+import { markCallRecordingNotRecorded } from 'src/logic-functions/data/mark-call-recording-not-recorded.util';
+import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';
+import { cancelRecallBot } from 'src/logic-functions/recall-api/cancel-recall-bot.util';
+
+export type CheckCreditsBeforeRecallBotJoinResult =
+ | { status: 'skipped'; reason: string }
+ | { status: 'allowed' }
+ | { status: 'blocked'; failureReason: string };
+
+export const checkCreditsBeforeRecallBotJoin = async ({
+ client,
+ callRecordingId,
+ now,
+}: {
+ client: CoreApiClient;
+ callRecordingId: string;
+ now: Date;
+}): Promise<CheckCreditsBeforeRecallBotJoinResult> => {
+ const callRecording = (
+ await findCallRecordingsByIds(client, [callRecordingId])
+ )[0];
+
+ if (
+ isUndefined(callRecording) ||
+ callRecording.recordingRequestStatus !==
+ CallRecordingRequestStatus.REQUESTED ||
+ callRecording.status !== CallRecordingStatus.SCHEDULED ||
+ isUndefined(callRecording.externalBotId) ||
+ isUndefined(callRecording.calendarEventId)
+ ) {
+ return {
+ status: 'skipped',
+ reason: 'call recording no longer awaits a scheduled bot',
+ };
+ }
+
+ const meetingStartsAt = (
+ await fetchCalendarEventsByIds(client, [callRecording.calendarEventId])
+ )[0]?.startsAt;
+
+ if (isUndefined(meetingStartsAt)) {
+ return { status: 'skipped', reason: 'meeting has no start time' };
+ }
+
+ // A late job must never cut a call that is already being recorded.
+ if (
+ now.getTime() >= new Date(computeRecallBotJoinAt(meetingStartsAt)).getTime()
+ ) {
+ console.warn(
+ `[call-recorder] pre-join credit check for callRecording ${callRecordingId} ran after the bot join time; the recording proceeds unchecked`,
+ );
+
+ return { status: 'skipped', reason: 'bot join time has passed' };
+ }
+
+ const failureReason = await getCreditsUnavailableFailureReason();
+
+ if (isUndefined(failureReason)) {
+ return { status: 'allowed' };
+ }
+
+ // Delete only, never eject: Recall refuses the delete once the bot has joined, so a late job cannot cut a call.
+ const cancelResult = await cancelRecallBot({
+ externalBotId: callRecording.externalBotId,
+ });
+
+ if (
+ !cancelResult.ok &&
+ cancelResult.status === RECALL_BOT_ALREADY_JOINED_STATUS
+ ) {
+ return { status: 'skipped', reason: 'bot has already joined' };
+ }
+
+ if (!cancelResult.ok) {
+ throw new Error(
+ `Recall bot ${callRecording.externalBotId} could not be canceled: ${cancelResult.errorMessage}`,
+ );
+ }
+
+ const didMarkNotRecorded = await markCallRecordingNotRecorded(client, {
+ callRecordingId,
+ failureReason,
+ });
+
+ if (!didMarkNotRecorded) {
+ return {
+ status: 'skipped',
+ reason:
+ 'call recording reached a terminal status while its bot was being canceled',
+ };
+ }
+
+ return { status: 'blocked', failureReason };
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-pre-join-credit-check-job.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-pre-join-credit-check-job.util.ts
new file mode 100644
index 00000000000..5244a77b185
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-pre-join-credit-check-job.util.ts
@@ -0,0 +1,39 @@
+import { isUndefined } from '@sniptt/guards';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+
+import {
+ checkCreditsBeforeRecallBotJoin,
+ type CheckCreditsBeforeRecallBotJoinResult,
+} from 'src/logic-functions/flows/check-credits-before-recall-bot-join.util';
+import { asRecord } from 'src/logic-functions/utils/as-record.util';
+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
+import { fetchWithTimeout } from 'src/logic-functions/utils/fetch-with-timeout.util';
+import { getString } from 'src/logic-functions/utils/get-string.util';
+
+export const handlePreJoinCreditCheckJob = async (
+ payload: unknown,
+): Promise<CheckCreditsBeforeRecallBotJoinResult> => {
+ const body = asRecord(payload);
+ const callRecordingId = getString(body?.callRecordingId);
+
+ if (isUndefined(callRecordingId)) {
+ return { status: 'skipped', reason: 'invalid pre-join credit check job' };
+ }
+
+ try {
+ return await checkCreditsBeforeRecallBotJoin({
+ // The job may fire days after the run that enqueued it, so it must not borrow that run's user.
+ client: new CoreApiClient({
+ runAs: 'application',
+ fetch: fetchWithTimeout,
+ }),
+ callRecordingId,
+ now: new Date(),
+ });
+ } catch (error) {
+ throw buildRetryableStepFailure(
+ `pre-join credit check for call recording ${callRecordingId}`,
+ error,
+ );
+ }
+};
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 0a390451735..f15d292f11a 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
@@ -376,7 +376,7 @@ const createPolicyManagedCallRecording = async ({
}
// Winning the deterministic-id insert elects this run as the single writer that creates the bot.
- const didScheduleBot = await scheduleRecallBotForCallRecording(client, {
+ const scheduleResult = await scheduleRecallBotForCallRecording(client, {
callRecording: {
id: callRecordingId,
...scheduledFields,
@@ -384,7 +384,11 @@ const createPolicyManagedCallRecording = async ({
calendarEvent: representativeCalendarEvent,
});
- if (!didScheduleBot && process.env.NODE_ENV !== 'test') {
+ if (
+ scheduleResult.status !== 'scheduled' &&
+ scheduleResult.status !== 'blocked' &&
+ process.env.NODE_ENV !== 'test'
+ ) {
console.warn(
`[call-recorder] created callRecording ${callRecordingId}, but did not schedule a Recall bot`,
);
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 c6254d3e152..f4ed992ea8b 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 { 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 { rescheduleRecallBot } from 'src/logic-functions/recall-api/reschedule-recall-bot.util';
import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';
@@ -50,6 +51,13 @@ export const rescheduleCallRecordingBot = async (
});
if (rescheduleResult.ok) {
+ // The queued check is keyed to the previous join time; a moved join needs its own.
+ await enqueuePreJoinCreditCheck({
+ callRecordingId: callRecording.id,
+ externalBotId,
+ joinAt,
+ });
+
return;
}
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 618db44d3a2..e2fb181e389 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
@@ -98,15 +98,19 @@ const scheduleBot = async ({
callRecording: CallRecordingRecord;
calendarEvent: CalendarEventRecord;
}): Promise<ResumePendingCallRecordingResult> => {
- const didScheduleRecallBot = await scheduleRecallBotForCallRecording(
- client,
- {
- callRecording,
- calendarEvent,
- },
- );
+ const scheduleResult = await scheduleRecallBotForCallRecording(client, {
+ callRecording,
+ calendarEvent,
+ });
- return didScheduleRecallBot
- ? { status: 'scheduled' }
- : { status: 'deferred', reason: 'Recall bot scheduling failed' };
+ switch (scheduleResult.status) {
+ case 'scheduled':
+ return { status: 'scheduled' };
+ case 'blocked':
+ return { status: 'skipped', reason: scheduleResult.failureReason };
+ case 'skipped':
+ return { status: 'skipped', reason: scheduleResult.reason };
+ case 'failed':
+ return { status: 'deferred', reason: 'Recall bot scheduling failed' };
+ }
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts
index 1dd5dba8cf7..1430a4e9132 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bot-for-call-recording.util.ts
@@ -7,8 +7,12 @@ import { type MeetingRecording } from 'src/logic-functions/types/meeting-recordi
import { buildRecallBotAutomaticVideoOutput } from 'src/logic-functions/domain/build-recall-bot-automatic-video-output.util';
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 { isRecallBotJoinWithinCreditCheckLead } from 'src/logic-functions/domain/is-recall-bot-join-within-credit-check-lead.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 { getCreditsUnavailableFailureReason } from 'src/logic-functions/data/get-credits-unavailable-failure-reason.util';
import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';
+import { markCallRecordingNotRecorded } from 'src/logic-functions/data/mark-call-recording-not-recorded.util';
import { isCalendarBotSchedulingEnabled } from 'src/logic-functions/utils/is-calendar-bot-scheduling-enabled.util';
import {
computeRecallBotCreationIdempotencyKey,
@@ -16,20 +20,26 @@ import {
} from 'src/logic-functions/recall-api/schedule-recall-bot.util';
import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';
+export type ScheduleRecallBotForCallRecordingResult =
+ | { status: 'scheduled' }
+ | { status: 'skipped'; reason: string }
+ | { status: 'blocked'; failureReason: string }
+ | { status: 'failed'; reason: string };
+
// The sole place a Recall bot is created. Only the deterministic-create winner and the stale-state cron call it, so one writer per meeting POSTs exactly one bot.
export const scheduleRecallBotForCallRecording = async (
client: CoreApiClient,
{ callRecording, calendarEvent }: MeetingRecording,
-): Promise<boolean> => {
+): Promise<ScheduleRecallBotForCallRecordingResult> => {
const meetingUrl = calendarEvent.conferenceLinkUrl;
const meetingStartsAt = calendarEvent.startsAt;
if (isUndefined(meetingUrl) || isUndefined(meetingStartsAt)) {
- return false;
+ return { status: 'skipped', reason: 'meeting has no link or start time' };
}
if (!isCalendarBotSchedulingEnabled()) {
- return false;
+ return { status: 'skipped', reason: 'calendar bot scheduling is off' };
}
const joinAt = computeRecallBotJoinAt(meetingStartsAt);
@@ -45,7 +55,31 @@ export const scheduleRecallBotForCallRecording = async (
freshCallRecording.status !== CallRecordingStatus.SCHEDULED ||
!isUndefined(freshCallRecording.externalBotId)
) {
- return false;
+ return {
+ status: 'skipped',
+ reason: 'call recording no longer awaits a bot',
+ };
+ }
+
+ // A bot created this close to the join starts joining at once, so the verdict comes first.
+ const isJoinWithinCreditCheckLead = isRecallBotJoinWithinCreditCheckLead({
+ joinAt,
+ now: new Date(),
+ });
+ const creditsUnavailableFailureReason = isJoinWithinCreditCheckLead
+ ? await getCreditsUnavailableFailureReason()
+ : undefined;
+
+ if (!isUndefined(creditsUnavailableFailureReason)) {
+ await markCallRecordingNotRecorded(client, {
+ callRecordingId: callRecording.id,
+ failureReason: creditsUnavailableFailureReason,
+ });
+
+ return {
+ status: 'blocked',
+ failureReason: creditsUnavailableFailureReason,
+ };
}
const workspaceId = getCurrentWorkspaceId();
@@ -55,7 +89,7 @@ export const scheduleRecallBotForCallRecording = async (
`[call-recorder] cannot schedule Recall bot for callRecording ${callRecording.id}: workspace id unavailable, the shared webhook could not be routed back`,
);
- return false;
+ return { status: 'failed', reason: 'workspace id unavailable' };
}
const automaticVideoOutput = await buildRecallBotAutomaticVideoOutput();
@@ -103,7 +137,7 @@ export const scheduleRecallBotForCallRecording = async (
`[call-recorder] failed to schedule Recall bot for callRecording ${callRecording.id}: ${scheduleResult.errorMessage}`,
);
- return false;
+ return { status: 'failed', reason: scheduleResult.errorMessage };
}
await updateCallRecording(client, {
@@ -111,5 +145,13 @@ export const scheduleRecallBotForCallRecording = async (
data: { externalBotId: scheduleResult.externalBotId },
});
- return true;
+ if (!isJoinWithinCreditCheckLead) {
+ await enqueuePreJoinCreditCheck({
+ callRecordingId: callRecording.id,
+ externalBotId: scheduleResult.externalBotId,
+ joinAt,
+ });
+ }
+
+ return { status: 'scheduled' };
};
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
index 6f005ee39ec..977c9ba5df1 100644
--- 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
@@ -5,6 +5,8 @@ import { CallRecordingStatus } from 'src/logic-functions/constants/call-recordin
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';
@@ -160,6 +162,14 @@ export const scheduleRecallBotsForPendingCallRecordings = async ({
data: { externalBotId: existingExternalBotId },
});
result.attachedCallRecordingIds.push(callRecording.id);
+
+ if (!isUndefined(calendarEvent.startsAt)) {
+ await enqueuePreJoinCreditCheck({
+ callRecordingId: callRecording.id,
+ externalBotId: existingExternalBotId,
+ joinAt: computeRecallBotJoinAt(calendarEvent.startsAt),
+ });
+ }
continue;
}
@@ -185,15 +195,12 @@ const scheduleBotForResumableCallRecording = async ({
calendarEvent: CalendarEventRecord;
result: ScheduleRecallBotsForPendingCallRecordingsResult;
}): Promise<void> => {
- const didScheduleRecallBot = await scheduleRecallBotForCallRecording(
- client,
- {
- callRecording,
- calendarEvent,
- },
- );
+ const scheduleResult = await scheduleRecallBotForCallRecording(client, {
+ callRecording,
+ calendarEvent,
+ });
- if (didScheduleRecallBot) {
+ if (scheduleResult.status === 'scheduled') {
result.scheduledCallRecordingIds.push(callRecording.id);
}
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/credit-unavailable-reason.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/credit-unavailable-reason.type.ts
new file mode 100644
index 00000000000..cd6d9f089a0
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/credit-unavailable-reason.type.ts
@@ -0,0 +1,7 @@
+import { type getCreditAvailability } from 'twenty-sdk/billing';
+
+// twenty-sdk/billing does not export its verdict types.
+export type CreditUnavailableReason = Extract<
+ Awaited<ReturnType<typeof getCreditAvailability>>,
+ { hasAvailableCredits: false }
+>['reason'];