The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Settle call recordings whose Recall media expired (#25795)
nitin48cf3af19d37
diff --git a/packages/twenty-apps/public/call-recorder/package.json b/packages/twenty-apps/public/call-recorder/package.jsonindex afd6edd40b3..edc1f9ab528 100644--- a/packages/twenty-apps/public/call-recorder/package.json+++ b/packages/twenty-apps/public/call-recorder/package.json@@ -1,6 +1,6 @@{"name": "@twentyhq/call-recorder",- "version": "1.13.1",+ "version": "1.14.0","license": "MIT","engines": {"node": "^24.5.0",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.tsindex 057f0534998..d552ef576ee 100644--- a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts+++ b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts@@ -11,9 +11,12 @@ import {vi,} from 'vitest';+import { STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { reconcileStaleBotStateHandler } from 'src/logic-functions/reconcile-stale-bot-state';import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';import { CALENDAR_EVENT_UPDATE_BATCH_SIZE } from 'src/logic-functions/constants/calendar-event-update-batch-size';import { cancelCallRecordingRequest } from 'src/logic-functions/flows/cancel-call-recording-request.util';+import { 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 { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';import { retryFailedRecallCancellations } from 'src/logic-functions/flows/retry-failed-recall-cancellations.util';@@ -153,6 +156,7 @@ const inTwoHours = () =>new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString();const hoursAgo = (hours: number) =>new Date(Date.now() - hours * 60 * 60 * 1000).toISOString();+const daysAgo = (days: number) => hoursAgo(days * 24);// ---------------------------------------------------------------------------// Recall API fake, installed as a fetch interceptor. Twenty API traffic falls@@ -160,10 +164,18 @@ const hoursAgo = (hours: number) =>// captured here so fanned-out jobs do not run inside the test.// ---------------------------------------------------------------------------+type FakeRecallBotStatusChange = {+ code: string;+ sub_code?: string;+ created_at: string;+};+type FakeRecallBot = {id: string;metadata: Record<string, string>;statusCode: string;+ statusChanges?: FakeRecallBotStatusChange[];+ recordings?: Array<{ id: string; started_at: string; completed_at: string }>;};type FakeRecallTranscript = {@@ -191,9 +203,13 @@ class FakeRecallApi {botIdByIdempotencyKey = new Map<string, string>();transcripts = new Map<string, FakeRecallTranscript>();transcriptRequestFailureStatus: number | undefined = undefined;+ failVideoDownload = false;+ mediaContentLengthBytes: number | undefined = undefined;deletedBotIds: string[] = [];listRequestCount = 0;artifactImportRequests: object[] = [];+ recoveryRequests: object[] = [];+ hasExpiredMedia = false;failNextDelete = false;failCalendarEventUpdates = false;failRecallRemovals = false;@@ -209,6 +225,74 @@ class FakeRecallApi {}}+ // Mirrors Recall after retention: the bot history ends with media_expired,+ // the recording disappears from the bot, and its transcripts read as deleted.+ expireBotMedia({+ botId,+ recordingStartedAt,+ recordingEndedAt,+ }: {+ botId: string;+ recordingStartedAt: string;+ recordingEndedAt: string;+ }): void {+ const bot = this.finishBotRecording({+ botId,+ recordingStartedAt,+ recordingEndedAt,+ });++ this.hasExpiredMedia = true;+ bot.statusCode = 'media_expired';+ bot.statusChanges = [+ ...(bot.statusChanges ?? []),+ { code: 'media_expired', created_at: new Date().toISOString() },+ ];+ bot.recordings = [];++ for (const transcript of this.transcripts.values()) {+ transcript.statusCode = 'deleted';+ }+ }++ // Mirrors Recall after a call the app never heard the end of: the bot+ // history and its recording are complete, but no webhook reached the app.+ finishBotRecording({+ botId,+ recordingStartedAt,+ recordingEndedAt,+ }: {+ botId: string;+ recordingStartedAt: string;+ recordingEndedAt: string;+ }): FakeRecallBot {+ const bot = this.bots.get(botId);++ if (bot === undefined) {+ throw new Error(`Unknown fake Recall bot ${botId}`);+ }++ bot.statusCode = 'done';+ bot.statusChanges = [+ { code: 'in_call_recording', created_at: recordingStartedAt },+ {+ code: 'call_ended',+ sub_code: 'timeout_exceeded_everyone_left',+ created_at: recordingEndedAt,+ },+ { code: 'done', created_at: recordingEndedAt },+ ];+ bot.recordings = [+ {+ id: 'recall-recording-1',+ started_at: recordingStartedAt,+ completed_at: recordingEndedAt,+ },+ ];++ return bot;+ }+botForCallRecording(callRecordingId: string): FakeRecallBot | undefined {return [...this.bots.values()].find((bot) => bot.metadata.twentyCallRecordingId === callRecordingId,@@ -229,7 +313,14 @@ class FakeRecallApi {payloads: object[];}[];- this.artifactImportRequests.push(...(input?.payloads ?? []));+ if (+ input?.logicFunctionUniversalIdentifier ===+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER+ ) {+ this.recoveryRequests.push(...(input.payloads ?? []));+ } else {+ this.artifactImportRequests.push(...(input?.payloads ?? []));+ }return jsonResponse(200, {data: {@@ -268,12 +359,30 @@ class FakeRecallApi {id: bot.id,metadata: bot.metadata,status: { code: bot.statusCode },+ status_changes: bot.statusChanges ?? [],+ recordings: bot.recordings ?? [],})),});}const botIdMatch = requestUrl.match(/\/bot\/([^/]+)\/$/);+ if (method === 'GET' && botIdMatch !== null) {+ const bot = this.bots.get(botIdMatch[1]);++ if (bot === undefined) {+ return jsonResponse(404, {});+ }++ return jsonResponse(200, {+ id: bot.id,+ metadata: bot.metadata,+ status: { code: bot.statusCode },+ status_changes: bot.statusChanges ?? [],+ recordings: bot.recordings ?? [],+ });+ }+const ejectedBotIdMatch = requestUrl.match(/\/bot\/([^/]+)\/leave_call\/$/);if (method === 'POST' && ejectedBotIdMatch !== null) {@@ -304,6 +413,8 @@ class FakeRecallApi {method === 'POST' &&/\/recording\/[^/]+\/create_transcript\/$/.test(requestUrl)) {+ if (this.hasExpiredMedia) return jsonResponse(404, {});+if (this.transcriptRequestFailureStatus !== undefined) {return jsonResponse(this.transcriptRequestFailureStatus, {});}@@ -366,6 +477,7 @@ class FakeRecallApi {}if (method === 'GET' && /\/recording\/[^/]+\/$/.test(requestUrl)) {+ if (this.hasExpiredMedia) return jsonResponse(404, {});return jsonResponse(200, {media_shortcuts: {video_mixed: {@@ -382,6 +494,10 @@ class FakeRecallApi {method === 'GET' &&requestUrl.startsWith(`${FAKE_RECALL_DOWNLOAD_BASE_URL}/media/`)) {+ if (this.failVideoDownload && requestUrl.endsWith('.mp4')) {+ return jsonResponse(500, {});+ }+// Twenty checks uploads by magic bytes, so the fake media needs real headers.const mediaBytes = requestUrl.endsWith('.mp4')? MP4_FILE_HEADER_BYTES@@ -389,7 +505,11 @@ class FakeRecallApi {return new Response(mediaBytes, {status: 200,- headers: { 'content-length': String(mediaBytes.byteLength) },+ headers: {+ 'content-length': String(+ this.mediaContentLengthBytes ?? mediaBytes.byteLength,+ ),+ },});}@@ -484,6 +604,20 @@ const buildRecordingDoneWebhook = ({},});+const buildRecordingDeletedWebhook = ({+ botId,+ metadata,+}: {+ botId: string;+ metadata: Record<string, string>;+}) => ({+ event: 'recording.deleted',+ data: {+ bot: { id: botId, metadata },+ recording: { id: 'recall-recording-1' },+ },+});+const buildTranscriptDoneWebhook = ({botId,metadata,@@ -718,6 +852,8 @@ describe('call recorder app lifecycle (integration)', () => {startedAt: true,endedAt: true,transcript: true,+ audio: { fileId: true },+ video: { fileId: true },},},},@@ -787,6 +923,18 @@ describe('call recorder app lifecycle (integration)', () => {};};+ // The recovery cron only reconciles a bot once its meeting has started.+ const moveMeetingIntoPast = (calendarEventId: string) =>+ client.mutation({+ updateCalendarEvent: {+ __args: {+ id: calendarEventId,+ data: { startsAt: daysAgo(9), endsAt: daysAgo(8) },+ },+ id: true,+ },+ });+const deliverCalendarEventUpdate = ({calendarEventId,updatedFields,@@ -839,6 +987,19 @@ describe('call recorder app lifecycle (integration)', () => {scheduleRecallBotsForPendingCallRecordings({ client, now: new Date() });const runCancellationRetryCron = () =>retryFailedRecallCancellations({ client, now: new Date() });+ const runStaleStateCron = async () => {+ const result = await convergeDivergedCallRecordings({+ client,+ now: new Date(),+ });++ while (recall.recoveryRequests.length > 0) {+ await reconcileStaleBotStateHandler(recall.recoveryRequests.shift());+ }++ await runQueuedArtifactImports();+ return result;+ };describe('scheduling from calendar changes', () => {it('creates a recording and schedules a Recall bot for a meeting with recording enabled', async () => {@@ -1190,6 +1351,479 @@ describe('call recorder app lifecycle (integration)', () => {});});+ describe('settling recordings whose Recall media expired', () => {+ const recordingStartedAt = () => hoursAgo(1);++ const deliverRecordingDone = async ({+ botId,+ metadata,+ }: {+ botId: string;+ metadata: Record<string, string>;+ }): Promise<{ startedAt: string; completedAt: string }> => {+ const startedAt = recordingStartedAt();+ const completedAt = new Date().toISOString();++ await deliverRecallWebhook(+ buildRecordingDoneWebhook({ botId, metadata, startedAt, completedAt }),+ );++ return { startedAt, completedAt };+ };++ const expireMediaAndAgeMeeting = async ({+ calendarEventId,+ botId,+ startedAt,+ completedAt,+ }: {+ calendarEventId: string;+ botId: string;+ startedAt: string;+ completedAt: string;+ }) => {+ recall.expireBotMedia({+ botId,+ recordingStartedAt: startedAt,+ recordingEndedAt: completedAt,+ });+ await moveMeetingIntoPast(calendarEventId);+ };++ const expectFailedWithExpiredArtifacts = (+ callRecording: Awaited<ReturnType<typeof fetchCallRecording>>,+ ) => {+ expect(callRecording.status).toBe('FAILED');+ expect(callRecording.callRecorderFailureReason).toBe(+ 'video_import_expired,audio_import_expired',+ );+ expect(callRecording.transcript).toEqual({+ recallTranscriptId: null,+ status: 'EMPTY',+ subCode: 'transcript_expired',+ });+ };++ it('fails a processing recording whose media expired before any artifact was imported', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const { startedAt, completedAt } = await deliverRecordingDone({+ botId,+ metadata,+ });++ await expireMediaAndAgeMeeting({+ calendarEventId,+ botId,+ startedAt,+ completedAt,+ });++ const cronResult = await runStaleStateCron();++ expect(cronResult.enqueuedCallRecordingIds).toEqual([callRecordingId]);++ const callRecording = await fetchCallRecording(callRecordingId);++ expectFailedWithExpiredArtifacts(callRecording);+ });++ it('defers media settlement while an artifact import holds its claim', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const { startedAt, completedAt } = await deliverRecordingDone({+ botId,+ metadata,+ });++ await expireMediaAndAgeMeeting({+ calendarEventId,+ botId,+ startedAt,+ completedAt,+ });+ await client.mutation({+ updateCallRecording: {+ __args: {+ id: callRecordingId,+ data: { artifactsImportClaimedAt: new Date().toISOString() },+ },+ id: true,+ },+ });++ await runStaleStateCron();++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('PROCESSING');+ expect(callRecording.callRecorderFailureReason).toBeFalsy();+ expect(callRecording.transcript).toMatchObject({ status: 'EMPTY' });+ });++ it('completes a processing recording with imported media once Recall expires the rest', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const { startedAt, completedAt } = await deliverRecordingDone({+ botId,+ metadata,+ });++ await runQueuedArtifactImports();+ await expireMediaAndAgeMeeting({+ calendarEventId,+ botId,+ startedAt,+ completedAt,+ });++ const cronResult = await runStaleStateCron();++ expect(cronResult.enqueuedCallRecordingIds).toEqual([callRecordingId]);++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('COMPLETED');+ expect(callRecording.callRecorderFailureReason).toBeFalsy();+ expect(callRecording.transcript).toEqual({+ recallTranscriptId: 'recall-transcript-1',+ status: 'EMPTY',+ subCode: 'transcript_expired',+ });+ });++ it('completes a processing recording with only audio and records the expired video', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ recall.failVideoDownload = true;++ const { startedAt, completedAt } = await deliverRecordingDone({+ botId,+ metadata,+ });++ await expect(runQueuedArtifactImports()).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ });+ await expireMediaAndAgeMeeting({+ calendarEventId,+ botId,+ startedAt,+ completedAt,+ });++ await runStaleStateCron();++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('COMPLETED');+ expect(callRecording.callRecorderFailureReason).toBe(+ 'video_import_expired',+ );+ expect(callRecording.transcript).toMatchObject({ status: 'EMPTY' });+ });++ it('fails a recording whose media was too large to store and whose transcript never arrived', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ recall.mediaContentLengthBytes = 600 * 1024 * 1024;++ const { startedAt, completedAt } = await deliverRecordingDone({+ botId,+ metadata,+ });++ await runQueuedArtifactImports();++ expect(+ (await fetchCallRecording(callRecordingId)).callRecorderFailureReason,+ ).toBe('video_file_too_large,audio_file_too_large');++ await expireMediaAndAgeMeeting({+ calendarEventId,+ botId,+ startedAt,+ completedAt,+ });++ await runStaleStateCron();++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('FAILED');+ expect(callRecording.callRecorderFailureReason).toBe(+ 'video_file_too_large,audio_file_too_large',+ );+ expect(callRecording.transcript).toMatchObject({ status: 'EMPTY' });+ });++ it('settles a processing recording when Recall reports its media expired by webhook', async () => {+ const { callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ const { startedAt, completedAt } = await deliverRecordingDone({+ botId,+ metadata,+ });+ recall.expireBotMedia({+ botId,+ recordingStartedAt: startedAt,+ recordingEndedAt: completedAt,+ });+ await deliverRecallWebhook(+ buildBotStatusChangeWebhook({+ botId,+ metadata,+ statusCode: 'media_expired',+ }),+ );++ expect(recall.artifactImportRequests).toHaveLength(4);++ await runQueuedArtifactImports();++ const callRecording = await fetchCallRecording(callRecordingId);++ expectFailedWithExpiredArtifacts(callRecording);+ });++ it('settles a processing recording when Recall announces retention expiry by recording.deleted', async () => {+ const { callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ const { startedAt, completedAt } = await deliverRecordingDone({+ botId,+ metadata,+ });+ recall.expireBotMedia({+ botId,+ recordingStartedAt: startedAt,+ recordingEndedAt: completedAt,+ });+ await deliverRecallWebhook(+ buildRecordingDeletedWebhook({ botId, metadata }),+ );++ expect(recall.artifactImportRequests).toHaveLength(4);++ await runQueuedArtifactImports();++ const callRecording = await fetchCallRecording(callRecordingId);++ expectFailedWithExpiredArtifacts(callRecording);+ });++ it('drops a recording.deleted webhook for a recording that already completed', async () => {+ const { callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ await deliverRecordingDone({ botId, metadata });+ await runQueuedArtifactImports();+ recall.completeTranscripts([]);+ await deliverRecallWebhook(+ buildTranscriptDoneWebhook({ botId, metadata }),+ );+ await runQueuedArtifactImports();++ expect((await fetchCallRecording(callRecordingId)).status).toBe(+ 'COMPLETED',+ );++ const importRequestCountBeforeDeletion =+ recall.artifactImportRequests.length;++ await deliverRecallWebhook(+ buildRecordingDeletedWebhook({ botId, metadata }),+ );++ expect(recall.artifactImportRequests).toHaveLength(+ importRequestCountBeforeDeletion,+ );++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('COMPLETED');+ expect(callRecording.callRecorderFailureReason).toBeFalsy();+ expect(callRecording.audio).toHaveLength(1);+ expect(callRecording.video).toHaveLength(1);+ });++ it('fails a processing recording whose recording.done was lost once the bot reports its media expired', async () => {+ const { callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const startedAt = recordingStartedAt();+ const endedAt = new Date().toISOString();++ await deliverRecallWebhook(+ buildBotStatusChangeWebhook({+ botId,+ metadata,+ statusCode: 'call_ended',+ statusTimestamp: endedAt,+ }),+ );++ const processingCallRecording = await fetchCallRecording(callRecordingId);++ expect(processingCallRecording.status).toBe('PROCESSING');+ expect(processingCallRecording.externalRecordingId).toBeFalsy();+ expect(processingCallRecording.startedAt).toBeFalsy();++ recall.expireBotMedia({+ botId,+ recordingStartedAt: startedAt,+ recordingEndedAt: endedAt,+ });++ await runStaleStateCron();++ const callRecording = await fetchCallRecording(callRecordingId);++ expectFailedWithExpiredArtifacts(callRecording);+ expect(callRecording.startedAt).toBeTruthy();+ });++ it('keeps converging a processing recording whose media is still available', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ await deliverRecordingDone({ botId, metadata });+ await client.mutation({+ updateCalendarEvent: {+ __args: {+ id: calendarEventId,+ data: { startsAt: daysAgo(2), endsAt: daysAgo(1) },+ },+ id: true,+ },+ });++ await runStaleStateCron();++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('PROCESSING');+ expect(callRecording.callRecorderFailureReason).toBeFalsy();+ });+ });++ describe('recovering recordings whose Recall webhooks were lost', () => {+ it('imports the media of a processing recording whose recording.done was lost', async () => {+ const { callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const startedAt = hoursAgo(1);+ const endedAt = new Date().toISOString();++ await deliverRecallWebhook(+ buildBotStatusChangeWebhook({+ botId,+ metadata,+ statusCode: 'call_ended',+ statusTimestamp: endedAt,+ }),+ );+ recall.finishBotRecording({+ botId,+ recordingStartedAt: startedAt,+ recordingEndedAt: endedAt,+ });++ const cronResult = await runStaleStateCron();++ expect(cronResult.enqueuedCallRecordingIds).toEqual([callRecordingId]);++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('PROCESSING');+ expect(callRecording.externalRecordingId).toBe('recall-recording-1');+ expect(callRecording.startedAt).toBeTruthy();+ expect(callRecording.audio).toHaveLength(1);+ expect(callRecording.video).toHaveLength(1);+ expect(callRecording.transcript).toMatchObject({ status: 'PENDING' });+ });++ it('moves a recording still marked recording to processing once Recall shows the bot finished', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const startedAt = hoursAgo(1);+ const endedAt = new Date().toISOString();++ await deliverRecallWebhook(+ buildBotStatusChangeWebhook({+ botId,+ metadata,+ statusCode: 'in_call_recording',+ statusTimestamp: startedAt,+ }),+ );+ recall.finishBotRecording({+ botId,+ recordingStartedAt: startedAt,+ recordingEndedAt: endedAt,+ });+ await moveMeetingIntoPast(calendarEventId);++ const cronResult = await runStaleStateCron();++ expect(cronResult.enqueuedCallRecordingIds).toEqual([callRecordingId]);++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('PROCESSING');+ expect(callRecording.externalRecordingId).toBe('recall-recording-1');+ expect(callRecording.endedAt).toBeTruthy();+ expect(callRecording.audio).toHaveLength(1);+ expect(callRecording.video).toHaveLength(1);+ });++ it('fails a recording still marked recording whose bot vanished from Recall', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ await deliverRecallWebhook(+ buildBotStatusChangeWebhook({+ botId,+ metadata,+ statusCode: 'in_call_recording',+ }),+ );+ recall.bots.delete(botId);+ await moveMeetingIntoPast(calendarEventId);++ await runStaleStateCron();++ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.status).toBe('FAILED');+ expect(callRecording.callRecorderFailureReason).toBe(+ 'recall_bot_not_found',+ );+ });++ it('leaves an upcoming meeting alone', async () => {+ const { callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();++ await deliverRecallWebhook(+ buildBotStatusChangeWebhook({+ botId,+ metadata,+ statusCode: 'joining_call',+ }),+ );+ recall.bots.delete(botId);++ const cronResult = await runStaleStateCron();++ expect(cronResult.enqueuedCallRecordingIds).toEqual([]);+ expect((await fetchCallRecording(callRecordingId)).status).toBe(+ 'JOINING',+ );+ });+ });+describe('crash recovery cron', () => {it('schedules a bot for a recording created without one, with zero Recall list reads', async () => {const calendarEventId = await createCalendarEvent();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.tsindex 437e36ae4c6..3fd682cd3d2 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@@ -85,6 +85,9 @@ export const CLEANUP_ORPHANED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER ='5fcf4d3a-0aca-42d9-9beb-7387f43ec180';+export const ENQUEUE_CALL_RECORDING_RECOVERY_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =+ 'e93a646b-31bd-45e6-86e3-9a54f4f7d141';+export const ENQUEUE_ORPHANED_RECALL_BOT_CLEANUP_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER ='455458ce-bbc3-4b39-a3f2-950540c9eda7';diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifacts-import-claim-field-by-scope.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifacts-import-claim-field-by-scope.tsnew file mode 100644index 00000000000..84b4897ac97--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifacts-import-claim-field-by-scope.ts@@ -0,0 +1,4 @@+export const ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE = {+ transcript: 'transcriptImportClaimedAt',+ media: 'artifactsImportClaimedAt',+} as const;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-artifact-import-scopes.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-artifact-import-scopes.tsnew file mode 100644index 00000000000..69f82074044--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-artifact-import-scopes.ts@@ -0,0 +1,6 @@+import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';++export const CALL_RECORDING_ARTIFACT_IMPORT_SCOPES = [+ 'transcript',+ 'media',+] satisfies CallRecordingArtifactImportScope[];diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-for-artifacts-import-selection.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-for-artifacts-import-selection.tsnew file mode 100644index 00000000000..abfed43569b--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-for-artifacts-import-selection.ts@@ -0,0 +1,12 @@+export const CALL_RECORDING_FOR_ARTIFACTS_IMPORT_SELECTION = {+ id: true,+ status: true,+ startedAt: true,+ endedAt: true,+ externalBotId: true,+ externalRecordingId: true,+ callRecorderFailureReason: true,+ transcript: true,+ audio: { fileId: true },+ video: { fileId: true },+} as const;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/media-import-expired-failure-reasons.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/media-import-expired-failure-reasons.tsnew file mode 100644index 00000000000..c60d4f915bd--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/media-import-expired-failure-reasons.ts@@ -0,0 +1,2 @@+export const VIDEO_IMPORT_EXPIRED_FAILURE_REASON = 'video_import_expired';+export const AUDIO_IMPORT_EXPIRED_FAILURE_REASON = 'audio_import_expired';diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/orphaned-recall-bot-cleanup-distribution-window-ms.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/orphaned-recall-bot-cleanup-distribution-window-ms.tsdeleted file mode 100644index 75a1a7fdc30..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/orphaned-recall-bot-cleanup-distribution-window-ms.ts+++ /dev/null@@ -1,2 +0,0 @@-export const ORPHANED_RECALL_BOT_CLEANUP_DISTRIBUTION_WINDOW_MS =- 60 * 60 * 1000;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-api-not-found-status.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-api-not-found-status.tsnew file mode 100644index 00000000000..6f58a587871--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-api-not-found-status.ts@@ -0,0 +1 @@+export const RECALL_API_NOT_FOUND_STATUS = 404;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/reconcilable-call-recording-statuses.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/reconcilable-call-recording-statuses.tsnew file mode 100644index 00000000000..7a2e9d1cb4e--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/reconcilable-call-recording-statuses.ts@@ -0,0 +1,7 @@+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';++export const RECONCILABLE_CALL_RECORDING_STATUSES: readonly string[] = [+ ...NON_TERMINAL_CALL_RECORDING_STATUSES,+ CallRecordingStatus.COMPLETED,+];diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/transcript-expired-sub-code.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/transcript-expired-sub-code.tsnew file mode 100644index 00000000000..fd9d4638094--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/transcript-expired-sub-code.ts@@ -0,0 +1 @@+export const TRANSCRIPT_EXPIRED_SUB_CODE = 'transcript_expired';diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/workspace-distribution-window-ms.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/workspace-distribution-window-ms.tsnew file mode 100644index 00000000000..3f7c40282b2--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/workspace-distribution-window-ms.ts@@ -0,0 +1 @@+export const WORKSPACE_DISTRIBUTION_WINDOW_MS = 60 * 60 * 1000;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/claim-call-recording-artifacts-import.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/claim-call-recording-artifacts-import.test.tsindex 5281933be30..7e22f6ecf00 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/claim-call-recording-artifacts-import.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/claim-call-recording-artifacts-import.test.ts@@ -1,150 +1,191 @@import { type CoreApiClient } from 'twenty-client-sdk/core';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';+import { ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE } from 'src/logic-functions/constants/artifacts-import-claim-field-by-scope';+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';import {claimCallRecordingArtifactsImport,releaseCallRecordingArtifactsImportClaim,} from 'src/logic-functions/data/claim-call-recording-artifacts-import.util';--const mutationMock = vi.fn();--const client = { mutation: mutationMock } as unknown as CoreApiClient;--describe('claimCallRecordingArtifactsImport', () => {- beforeEach(() => {- mutationMock.mockReset();- });-- it('claims the media lease when no fresh lease is held and stamps the lease timestamp', async () => {- mutationMock.mockResolvedValue({- updateCallRecordings: [{ id: 'call-recording-1' }],- });-- const claimed = await claimCallRecordingArtifactsImport(client, {- callRecordingId: 'call-recording-1',- scope: 'media',- now: new Date('2026-01-01T14:06:00.000Z'),- });-- expect(claimed).toBe(true);- expect(mutationMock).toHaveBeenCalledWith({+import { updateClaimedCallRecordingArtifacts } from 'src/logic-functions/data/update-claimed-call-recording-artifacts.util';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';++type ClaimField = 'artifactsImportClaimedAt' | 'transcriptImportClaimedAt';+type Predicate = { eq?: string; is?: 'NULL'; lte?: string };+type ClaimFilter = Partial<Record<ClaimField, Predicate>> & {+ id: { eq: string };+ status?: { eq: string };+ or?: Partial<Record<ClaimField, Predicate>>[];+};++const buildStore = () => {+ const row: CallRecordingUpdateFields & { id: string } = {+ id: 'recording',+ status: CallRecordingStatus.PROCESSING,+ artifactsImportClaimedAt: null,+ transcriptImportClaimedAt: null,+ };+ const matches = (field: ClaimField, predicate: Predicate | undefined) => {+ if (predicate === undefined) return true;+ const value = row[field];+ if (predicate.is === 'NULL') return value === null;+ if (predicate.eq !== undefined) return value === predicate.eq;+ return (+ typeof value === 'string' &&+ predicate.lte !== undefined &&+ value <= predicate.lte+ );+ };+ const client = {+ mutation: async ({+ updateCallRecordings,+ }: {updateCallRecordings: {- __args: {- filter: {- id: { eq: 'call-recording-1' },- or: [- { artifactsImportClaimedAt: { is: 'NULL' } },- { artifactsImportClaimedAt: { lte: '2026-01-01T13:56:00.000Z' } },- ],- },- data: { artifactsImportClaimedAt: '2026-01-01T14:06:00.000Z' },- },- id: true,- },+ __args: { filter: ClaimFilter; data: CallRecordingUpdateFields };+ };+ }) => {+ const { filter, data } = updateCallRecordings.__args;+ const claimFields: ClaimField[] = [+ 'artifactsImportClaimedAt',+ 'transcriptImportClaimedAt',+ ];+ const hasMatched =+ filter.id.eq === row.id &&+ (filter.status === undefined || row.status === filter.status.eq) &&+ claimFields.every((field) => matches(field, filter[field])) &&+ (filter.or === undefined ||+ filter.or.some((part) =>+ claimFields.every((field) => matches(field, part[field])),+ ));++ if (!hasMatched) return { updateCallRecordings: [] };+ Object.assign(row, data);+ return { updateCallRecordings: [{ ...row }] };+ },+ };++ return { row, client: client as unknown as CoreApiClient };+};++const NOW = new Date('2026-01-01T14:06:00.000Z');++describe.each(['media', 'transcript'] as const)(+ '%s artifact import claim',+ (scope) => {+ const field = ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope];+ const otherField =+ ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[+ scope === 'media' ? 'transcript' : 'media'+ ];++ it('claims processing work and rejects a concurrent worker', async () => {+ const { client, row } = buildStore();+ const request = { callRecordingId: row.id, scope, now: NOW };++ expect(+ await claimCallRecordingArtifactsImport(client, request),+ ).toMatchObject({ id: row.id, status: CallRecordingStatus.PROCESSING });+ expect(+ await claimCallRecordingArtifactsImport(client, request),+ ).toBeUndefined();+ expect(row[field]).toBe(NOW.toISOString());});- });- it('claims the transcript lease on its own field so a held media lease cannot block it', async () => {- mutationMock.mockResolvedValue({- updateCallRecordings: [{ id: 'call-recording-1' }],+ it('does not reclaim while an earlier Lambda can still be running', async () => {+ const { client, row } = buildStore();+ row[field] = new Date(NOW.getTime() - 14 * 60_000).toISOString();++ expect(+ await claimCallRecordingArtifactsImport(client, {+ callRecordingId: row.id,+ scope,+ now: NOW,+ }),+ ).toBeUndefined();});- const claimed = await claimCallRecordingArtifactsImport(client, {- callRecordingId: 'call-recording-1',- scope: 'transcript',- now: new Date('2026-01-01T14:06:00.000Z'),+ it('reclaims an abandoned claim after the maximum execution window', async () => {+ const { client, row } = buildStore();+ row[field] = new Date(NOW.getTime() - 17 * 60_000).toISOString();++ expect(+ await claimCallRecordingArtifactsImport(client, {+ callRecordingId: row.id,+ scope,+ now: NOW,+ }),+ ).toMatchObject({ id: row.id });});- expect(claimed).toBe(true);- expect(mutationMock).toHaveBeenCalledWith({- updateCallRecordings: {- __args: {- filter: {- id: { eq: 'call-recording-1' },- or: [- { transcriptImportClaimedAt: { is: 'NULL' } },- { transcriptImportClaimedAt: { lte: '2026-01-01T13:56:00.000Z' } },- ],- },- data: { transcriptImportClaimedAt: '2026-01-01T14:06:00.000Z' },- },- id: true,- },+ it('prevents an old worker from writing progress or releasing its replacement claim', async () => {+ const { client, row } = buildStore();+ const oldClaimedAt = new Date(NOW.getTime() - 17 * 60_000).toISOString();+ row[field] = oldClaimedAt;+ await claimCallRecordingArtifactsImport(client, {+ callRecordingId: row.id,+ scope,+ now: NOW,+ });++ await expect(+ updateClaimedCallRecordingArtifacts(client, {+ callRecordingId: row.id,+ scope,+ claimedAt: oldClaimedAt,+ data: { callRecorderFailureReason: 'old-result' },+ }),+ ).rejects.toThrow('no longer active');+ await releaseCallRecordingArtifactsImportClaim(client, {+ callRecordingId: row.id,+ scope,+ claimedAt: oldClaimedAt,+ });++ expect(row[field]).toBe(NOW.toISOString());+ expect(row.callRecorderFailureReason).toBeUndefined();});- });-- it('does not claim when a fresh lease already blocks the update', async () => {- mutationMock.mockResolvedValue({ updateCallRecordings: [] });- const claimed = await claimCallRecordingArtifactsImport(client, {- callRecordingId: 'call-recording-1',- scope: 'media',- now: new Date('2026-01-01T14:06:00.000Z'),+ it('saves progress and releases only the owned scope', async () => {+ const { client, row } = buildStore();+ row.artifactsImportClaimedAt = NOW.toISOString();+ row.transcriptImportClaimedAt = NOW.toISOString();+ const claim = {+ callRecordingId: row.id,+ scope,+ claimedAt: NOW.toISOString(),+ };++ await updateClaimedCallRecordingArtifacts(client, {+ ...claim,+ data: { callRecorderFailureReason: 'video_file_too_large' },+ });+ await releaseCallRecordingArtifactsImportClaim(client, claim);++ expect(row.callRecorderFailureReason).toBe('video_file_too_large');+ expect(row[field]).toBeNull();+ expect(row[otherField]).toBe(NOW.toISOString());});-- expect(claimed).toBe(false);- });-- it('reclaims a lease older than the TTL', async () => {- // Emulate the DB-side filter so the lte staleBefore branch and TTL math are exercised.- const storedClaimedAt = '2026-01-01T13:45:00.000Z'; // 21 minutes before now- mutationMock.mockImplementation(async (mutation: any) => {- const { filter } = mutation.updateCallRecordings.__args;- const staleBefore = filter.or[1].artifactsImportClaimedAt.lte;- const matches = storedClaimedAt <= staleBefore;-- return { updateCallRecordings: matches ? [{ id: filter.id.eq }] : [] };- });-- const claimed = await claimCallRecordingArtifactsImport(client, {- callRecordingId: 'call-recording-1',- scope: 'media',- now: new Date('2026-01-01T14:06:00.000Z'),- });-- expect(claimed).toBe(true);- expect(- mutationMock.mock.calls[0][0].updateCallRecordings.__args.data,- ).toEqual({ artifactsImportClaimedAt: '2026-01-01T14:06:00.000Z' });- });-- it('does not reclaim a lease still within the TTL', async () => {- const storedClaimedAt = '2026-01-01T14:02:00.000Z'; // 4 minutes before now- mutationMock.mockImplementation(async (mutation: any) => {- const { filter } = mutation.updateCallRecordings.__args;- const staleBefore = filter.or[1].artifactsImportClaimedAt.lte;- const matches = storedClaimedAt <= staleBefore;-- return { updateCallRecordings: matches ? [{ id: filter.id.eq }] : [] };- });-- const claimed = await claimCallRecordingArtifactsImport(client, {- callRecordingId: 'call-recording-1',- scope: 'media',- now: new Date('2026-01-01T14:06:00.000Z'),- });-- expect(claimed).toBe(false);- });-- it('releases the lease idempotently when the call recording no longer exists', async () => {- mutationMock.mockResolvedValue({- updateCallRecordings: [],- });-- await releaseCallRecordingArtifactsImportClaim(client, {- callRecordingId: 'call-recording-1',- scope: 'transcript',- });-- expect(mutationMock).toHaveBeenCalledWith({- updateCallRecordings: {- __args: {- filter: { id: { eq: 'call-recording-1' } },- data: { transcriptImportClaimedAt: null },- },- id: true,- },+ it('cannot claim or write to an already completed recording', async () => {+ const { client, row } = buildStore();+ row.status = CallRecordingStatus.COMPLETED;+ row[field] = NOW.toISOString();++ expect(+ await claimCallRecordingArtifactsImport(client, {+ callRecordingId: row.id,+ scope,+ now: NOW,+ }),+ ).toBeUndefined();+ await expect(+ updateClaimedCallRecordingArtifacts(client, {+ callRecordingId: row.id,+ scope,+ claimedAt: NOW.toISOString(),+ data: { callRecorderFailureReason: 'late-result' },+ }),+ ).rejects.toThrow('no longer active');+ expect(row.callRecorderFailureReason).toBeUndefined();});- });-});+ },+);diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-workspace-distributed-job.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-workspace-distributed-job.test.tsnew file mode 100644index 00000000000..b00b407c667--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-workspace-distributed-job.test.ts@@ -0,0 +1,52 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';+import { WORKSPACE_DISTRIBUTION_WINDOW_MS } from 'src/logic-functions/constants/workspace-distribution-window-ms';+import { enqueueWorkspaceDistributedJob } from 'src/logic-functions/data/enqueue-workspace-distributed-job.util';++const enqueueJobsMock = vi.hoisted(() => vi.fn());++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ enqueueJobs: enqueueJobsMock,+}));++describe('enqueueWorkspaceDistributedJob', () => {+ afterEach(() => {+ enqueueJobsMock.mockReset();+ });++ it('enqueues one job for the function at the workspace delay', async () => {+ enqueueJobsMock.mockResolvedValue(undefined);++ const { delayMs } = await enqueueWorkspaceDistributedJob({+ workspaceId: '20202020-1111-4444-8888-303030303030',+ logicFunctionUniversalIdentifier: 'logic-function-universal-identifier',+ stepLabel: 'recovery enqueueing',+ });++ expect(delayMs).toBeGreaterThanOrEqual(0);+ expect(delayMs).toBeLessThan(WORKSPACE_DISTRIBUTION_WINDOW_MS);+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier: 'logic-function-universal-identifier',+ payloads: [{}],+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ delayMs,+ });+ });++ it('reports a failed enqueue as retryable', async () => {+ enqueueJobsMock.mockRejectedValue(new Error('queue unavailable'));++ await expect(+ enqueueWorkspaceDistributedJob({+ workspaceId: '20202020-1111-4444-8888-303030303030',+ logicFunctionUniversalIdentifier: 'logic-function-universal-identifier',+ stepLabel: 'recovery enqueueing',+ }),+ ).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ message: expect.stringContaining('recovery enqueueing failed'),+ });+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/parse-call-recording-for-artifacts-import-node.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/parse-call-recording-for-artifacts-import-node.test.tsnew file mode 100644index 00000000000..296e3f18a0a--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/parse-call-recording-for-artifacts-import-node.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';++import { parseCallRecordingForArtifactsImportNode } from 'src/logic-functions/data/parse-call-recording-for-artifacts-import-node.util';++describe('parseCallRecordingForArtifactsImportNode', () => {+ it('returns undefined for a missing node or one without an id', () => {+ expect(parseCallRecordingForArtifactsImportNode(undefined)).toBeUndefined();+ expect(parseCallRecordingForArtifactsImportNode(null)).toBeUndefined();+ expect(+ parseCallRecordingForArtifactsImportNode({ status: 'PROCESSING' }),+ ).toBeUndefined();+ });++ it('reads nullable fields as undefined', () => {+ expect(+ parseCallRecordingForArtifactsImportNode({+ id: 'call-recording-1',+ status: 'PROCESSING',+ startedAt: null,+ endedAt: null,+ externalBotId: 'bot-1',+ externalRecordingId: null,+ callRecorderFailureReason: null,+ transcript: null,+ audio: null,+ video: [{ fileId: 'file-1' }],+ }),+ ).toEqual({+ id: 'call-recording-1',+ status: 'PROCESSING',+ startedAt: undefined,+ endedAt: undefined,+ externalBotId: 'bot-1',+ externalRecordingId: undefined,+ callRecorderFailureReason: undefined,+ transcript: undefined,+ audio: undefined,+ video: [{ fileId: 'file-1' }],+ });+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/claim-call-recording-artifacts-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/claim-call-recording-artifacts-import.util.tsindex 61e494ca3ee..d16e804a9a5 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/claim-call-recording-artifacts-import.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/claim-call-recording-artifacts-import.util.ts@@ -1,15 +1,21 @@import { type CoreApiClient } from 'twenty-client-sdk/core';+import { ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE } from 'src/logic-functions/constants/artifacts-import-claim-field-by-scope';+import { CALL_RECORDING_FOR_ARTIFACTS_IMPORT_SELECTION } from 'src/logic-functions/constants/call-recording-for-artifacts-import-selection';+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { parseCallRecordingForArtifactsImportNode } from 'src/logic-functions/data/parse-call-recording-for-artifacts-import-node.util';import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';+import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';-// Crash safety net: a lease older than this is reclaimable so a worker that died-// mid-import never blocks the recording forever. Normal runs release explicitly.-const ARTIFACTS_IMPORT_CLAIM_TTL_MS = 10 * 60 * 1000;+// The executor Lambda runs with this hard timeout regardless of the function's+// timeoutSeconds, which only bounds how long the server waits for the invoke.+const LOGIC_FUNCTION_LAMBDA_HARD_TIMEOUT_MS = 15 * 60 * 1000;-const CLAIM_FIELD_BY_SCOPE = {- transcript: 'transcriptImportClaimedAt',- media: 'artifactsImportClaimedAt',-} as const;+// Crash safety net: a lease older than this is reclaimable so a worker that died+// mid-import never blocks the recording forever. It must outlive the Lambda so+// a second job never uploads on top of one that is still running.+const ARTIFACTS_IMPORT_CLAIM_TTL_MS =+ LOGIC_FUNCTION_LAMBDA_HARD_TIMEOUT_MS + 60 * 1000;export const claimCallRecordingArtifactsImport = async (client: CoreApiClient,@@ -22,8 +28,8 @@ export const claimCallRecordingArtifactsImport = async (scope: CallRecordingArtifactImportScope;now: Date;},-): Promise<boolean> => {- const claimField = CLAIM_FIELD_BY_SCOPE[scope];+): Promise<CallRecordingForArtifactsImport | undefined> => {+ const claimField = ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope];const staleBefore = new Date(now.getTime() - ARTIFACTS_IMPORT_CLAIM_TTL_MS,).toISOString();@@ -33,6 +39,7 @@ export const claimCallRecordingArtifactsImport = async (__args: {filter: {id: { eq: callRecordingId },+ status: { eq: CallRecordingStatus.PROCESSING },or: [{ [claimField]: { is: 'NULL' } },{ [claimField]: { lte: staleBefore } },@@ -40,11 +47,13 @@ export const claimCallRecordingArtifactsImport = async (},data: { [claimField]: now.toISOString() },},- id: true,+ ...CALL_RECORDING_FOR_ARTIFACTS_IMPORT_SELECTION,},});- return (result.updateCallRecordings ?? []).length > 0;+ return parseCallRecordingForArtifactsImportNode(+ result.updateCallRecordings?.[0],+ );};export const releaseCallRecordingArtifactsImportClaim = async (@@ -52,16 +61,21 @@ export const releaseCallRecordingArtifactsImportClaim = async ({callRecordingId,scope,+ claimedAt,}: {callRecordingId: string;scope: CallRecordingArtifactImportScope;+ claimedAt: string;},): Promise<void> => {await client.mutation({updateCallRecordings: {__args: {- filter: { id: { eq: callRecordingId } },- data: { [CLAIM_FIELD_BY_SCOPE[scope]]: null },+ filter: {+ id: { eq: callRecordingId },+ [ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope]]: { eq: claimedAt },+ },+ data: { [ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope]]: null },},id: true,},diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-workspace-distributed-job.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-workspace-distributed-job.util.tsnew file mode 100644index 00000000000..76da7b4ddb4--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-workspace-distributed-job.util.ts@@ -0,0 +1,34 @@+import { enqueueJobs } from 'twenty-sdk/logic-function';++import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';+import { computeWorkspaceDistributionDelay } from 'src/logic-functions/domain/compute-workspace-distribution-delay.util';+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';++export type EnqueueWorkspaceDistributedJobResult = {+ delayMs: number;+};++export const enqueueWorkspaceDistributedJob = async ({+ workspaceId,+ logicFunctionUniversalIdentifier,+ stepLabel,+}: {+ workspaceId: string;+ logicFunctionUniversalIdentifier: string;+ stepLabel: string;+}): Promise<EnqueueWorkspaceDistributedJobResult> => {+ const delayMs = computeWorkspaceDistributionDelay(workspaceId);++ try {+ await enqueueJobs({+ logicFunctionUniversalIdentifier,+ payloads: [{}],+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ delayMs,+ });+ } catch (error) {+ throw buildRetryableStepFailure(stepLabel, error);+ }++ return { delayMs };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-for-artifacts-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-for-artifacts-import.util.tsindex 57eec97c3d4..fd3d99b9433 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-for-artifacts-import.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-for-artifacts-import.util.ts@@ -1,26 +1,8 @@-import { isNull, isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';-import { type SyncableCallRecording } from 'src/logic-functions/flows/sync-call-recording.util';-import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';-import { getString } from 'src/logic-functions/utils/get-string.util';--export type CallRecordingForArtifactsImport = SyncableCallRecording & {- externalBotId: string | undefined;-};--type CallRecordingForArtifactsImportNode = {- id?: string | null;- status?: string | null;- startedAt?: string | null;- endedAt?: string | null;- externalBotId?: string | null;- externalRecordingId?: string | null;- callRecorderFailureReason?: string | null;- transcript?: unknown;- audio?: FilesFieldValue | null;- video?: FilesFieldValue | null;-};+import { CALL_RECORDING_FOR_ARTIFACTS_IMPORT_SELECTION } from 'src/logic-functions/constants/call-recording-for-artifacts-import-selection';+import { parseCallRecordingForArtifactsImportNode } from 'src/logic-functions/data/parse-call-recording-for-artifacts-import-node.util';+import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';export const findCallRecordingForArtifactsImport = async (client: CoreApiClient,@@ -33,42 +15,12 @@ export const findCallRecordingForArtifactsImport = async (first: 1,},edges: {- node: {- id: true,- status: true,- startedAt: true,- endedAt: true,- externalBotId: true,- externalRecordingId: true,- callRecorderFailureReason: true,- transcript: true,- audio: { fileId: true },- video: { fileId: true },- },+ node: CALL_RECORDING_FOR_ARTIFACTS_IMPORT_SELECTION,},},});- const node = queryResult.callRecordings?.edges?.[0]?.node as- | CallRecordingForArtifactsImportNode- | null- | undefined;- const id = getString(node?.id);-- if (isUndefined(node) || isNull(node) || isUndefined(id)) {- return undefined;- }-- return {- id,- status: getString(node.status),- startedAt: getString(node.startedAt),- endedAt: getString(node.endedAt),- externalBotId: getString(node.externalBotId),- externalRecordingId: getString(node.externalRecordingId),- callRecorderFailureReason: getString(node.callRecorderFailureReason),- transcript: node.transcript ?? undefined,- audio: node.audio ?? undefined,- video: node.video ?? undefined,- };+ return parseCallRecordingForArtifactsImportNode(+ queryResult.callRecordings?.edges?.[0]?.node,+ );};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/parse-call-recording-for-artifacts-import-node.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/parse-call-recording-for-artifacts-import-node.util.tsnew file mode 100644index 00000000000..35d476b4eb7--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/parse-call-recording-for-artifacts-import-node.util.ts@@ -0,0 +1,41 @@+import { isNull, isUndefined } from '@sniptt/guards';++import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';+import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';+import { getString } from 'src/logic-functions/utils/get-string.util';++type CallRecordingForArtifactsImportNode = {+ id?: string | null;+ status?: string | null;+ startedAt?: string | null;+ endedAt?: string | null;+ externalBotId?: string | null;+ externalRecordingId?: string | null;+ callRecorderFailureReason?: string | null;+ transcript?: unknown;+ audio?: FilesFieldValue | null;+ video?: FilesFieldValue | null;+};++export const parseCallRecordingForArtifactsImportNode = (+ node: CallRecordingForArtifactsImportNode | null | undefined,+): CallRecordingForArtifactsImport | undefined => {+ const id = getString(node?.id);++ if (isUndefined(node) || isNull(node) || isUndefined(id)) {+ return undefined;+ }++ return {+ id,+ status: getString(node.status),+ startedAt: getString(node.startedAt),+ endedAt: getString(node.endedAt),+ externalBotId: getString(node.externalBotId),+ externalRecordingId: getString(node.externalRecordingId),+ callRecorderFailureReason: getString(node.callRecorderFailureReason),+ transcript: node.transcript ?? undefined,+ audio: node.audio ?? undefined,+ video: node.video ?? undefined,+ };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-claimed-call-recording-artifacts.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-claimed-call-recording-artifacts.util.tsnew file mode 100644index 00000000000..b727de4d002--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-claimed-call-recording-artifacts.util.ts@@ -0,0 +1,46 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE } from 'src/logic-functions/constants/artifacts-import-claim-field-by-scope';+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { hasCallRecordingUpdateFields } from 'src/logic-functions/domain/has-call-recording-update-fields.util';+import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';++export const updateClaimedCallRecordingArtifacts = async (+ client: CoreApiClient,+ {+ callRecordingId,+ scope,+ claimedAt,+ data,+ }: {+ callRecordingId: string;+ scope: CallRecordingArtifactImportScope;+ claimedAt: string;+ data: CallRecordingUpdateFields;+ },+): Promise<void> => {+ if (!hasCallRecordingUpdateFields(data)) {+ return;+ }++ const result = await client.mutation({+ updateCallRecordings: {+ __args: {+ filter: {+ id: { eq: callRecordingId },+ status: { eq: CallRecordingStatus.PROCESSING },+ [ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope]]: { eq: claimedAt },+ },+ data,+ },+ id: true,+ },+ });++ if ((result.updateCallRecordings ?? []).length === 0) {+ throw new Error(+ `Artifact import claim for ${callRecordingId} is no longer active`,+ );+ }+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-orphaned-recall-bot-cleanup-delay.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-orphaned-recall-bot-cleanup-delay.test.tsdeleted file mode 100644index bbe52085134..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-orphaned-recall-bot-cleanup-delay.test.ts+++ /dev/null@@ -1,13 +0,0 @@-import { describe, expect, it } from 'vitest';--import { computeOrphanedRecallBotCleanupDelay } from 'src/logic-functions/domain/compute-orphaned-recall-bot-cleanup-delay.util';--describe('computeOrphanedRecallBotCleanupDelay', () => {- it('returns the same delay for the same workspace', () => {- const workspaceId = '20202020-1111-4444-8888-303030303030';-- expect(computeOrphanedRecallBotCleanupDelay(workspaceId)).toBe(- computeOrphanedRecallBotCleanupDelay(workspaceId),- );- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-workspace-distribution-delay.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-workspace-distribution-delay.test.tsnew file mode 100644index 00000000000..ee6220e6922--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/compute-workspace-distribution-delay.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import { WORKSPACE_DISTRIBUTION_WINDOW_MS } from 'src/logic-functions/constants/workspace-distribution-window-ms';+import { computeWorkspaceDistributionDelay } from 'src/logic-functions/domain/compute-workspace-distribution-delay.util';++describe('computeWorkspaceDistributionDelay', () => {+ it('returns the same delay for the same workspace', () => {+ const workspaceId = '20202020-1111-4444-8888-303030303030';++ expect(computeWorkspaceDistributionDelay(workspaceId)).toBe(+ computeWorkspaceDistributionDelay(workspaceId),+ );+ });++ it('spreads different workspaces across the window', () => {+ expect(+ computeWorkspaceDistributionDelay('20202020-1111-4444-8888-303030303030'),+ ).not.toBe(+ computeWorkspaceDistributionDelay('20202020-2222-4444-8888-303030303030'),+ );+ });++ it('stays inside the distribution window', () => {+ const delayMs = computeWorkspaceDistributionDelay(+ '20202020-2222-4444-8888-303030303030',+ );++ expect(delayMs).toBeGreaterThanOrEqual(0);+ expect(delayMs).toBeLessThan(WORKSPACE_DISTRIBUTION_WINDOW_MS);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/is-call-recording-import-complete.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/is-call-recording-import-complete.test.tsindex e632cce6205..d37c6d66115 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/is-call-recording-import-complete.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/is-call-recording-import-complete.test.ts@@ -117,6 +117,17 @@ describe('isCallRecordingImportComplete', () => {).toBe(true);});+ it('treats a media file whose import expired as resolved', () => {+ expect(+ isCallRecordingImportComplete({+ transcript: TRANSCRIPT_CONTENT,+ audio: AUDIO_VALUE,+ video: undefined,+ callRecorderFailureReason: 'video_import_expired',+ }),+ ).toBe(true);+ });+it('does not let a size marker excuse the other missing artifact', () => {expect(isCallRecordingImportComplete({diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-media-file-too-large-markers.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-media-file-too-large-markers.test.tsdeleted file mode 100644index 3b86d03283d..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-media-file-too-large-markers.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import { describe, expect, it } from 'vitest';--import { parseMediaFileTooLargeMarkers } from 'src/logic-functions/domain/parse-media-file-too-large-markers.util';--describe('parseMediaFileTooLargeMarkers', () => {- it('parses single-artifact markers', () => {- expect(parseMediaFileTooLargeMarkers('video_file_too_large')).toEqual({- audioFileTooLarge: false,- videoFileTooLarge: true,- });- expect(parseMediaFileTooLargeMarkers('audio_file_too_large')).toEqual({- audioFileTooLarge: true,- videoFileTooLarge: false,- });- });-- it('parses comma-joined markers for both artifacts', () => {- expect(- parseMediaFileTooLargeMarkers(- 'video_file_too_large,audio_file_too_large',- ),- ).toEqual({- audioFileTooLarge: true,- videoFileTooLarge: true,- });- });-- it('reports no markers for unset or unrelated reasons', () => {- expect(parseMediaFileTooLargeMarkers(undefined)).toEqual({- audioFileTooLarge: false,- videoFileTooLarge: false,- });- expect(parseMediaFileTooLargeMarkers(null)).toEqual({- audioFileTooLarge: false,- videoFileTooLarge: false,- });- expect(parseMediaFileTooLargeMarkers('')).toEqual({- audioFileTooLarge: false,- videoFileTooLarge: false,- });- expect(parseMediaFileTooLargeMarkers('recall_bot_not_found')).toEqual({- audioFileTooLarge: false,- videoFileTooLarge: false,- });- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-unrecoverable-media-markers.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-unrecoverable-media-markers.test.tsnew file mode 100644index 00000000000..e81ed65b5c6--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-unrecoverable-media-markers.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { parseUnrecoverableMediaMarkers } from 'src/logic-functions/domain/parse-unrecoverable-media-markers.util';++describe('parseUnrecoverableMediaMarkers', () => {+ it('parses single-artifact size markers', () => {+ expect(parseUnrecoverableMediaMarkers('video_file_too_large')).toEqual({+ isAudioUnrecoverable: false,+ isVideoUnrecoverable: true,+ });+ expect(parseUnrecoverableMediaMarkers('audio_file_too_large')).toEqual({+ isAudioUnrecoverable: true,+ isVideoUnrecoverable: false,+ });+ });++ it('parses single-artifact expiry markers', () => {+ expect(parseUnrecoverableMediaMarkers('video_import_expired')).toEqual({+ isAudioUnrecoverable: false,+ isVideoUnrecoverable: true,+ });+ expect(parseUnrecoverableMediaMarkers('audio_import_expired')).toEqual({+ isAudioUnrecoverable: true,+ isVideoUnrecoverable: false,+ });+ });++ it('parses comma-joined markers of mixed kinds', () => {+ expect(+ parseUnrecoverableMediaMarkers(+ 'audio_file_too_large,video_import_expired',+ ),+ ).toEqual({+ isAudioUnrecoverable: true,+ isVideoUnrecoverable: true,+ });+ });++ it('reports no markers for unset or unrelated reasons', () => {+ expect(parseUnrecoverableMediaMarkers(undefined)).toEqual({+ isAudioUnrecoverable: false,+ isVideoUnrecoverable: false,+ });+ expect(parseUnrecoverableMediaMarkers(null)).toEqual({+ isAudioUnrecoverable: false,+ isVideoUnrecoverable: false,+ });+ expect(parseUnrecoverableMediaMarkers('')).toEqual({+ isAudioUnrecoverable: false,+ isVideoUnrecoverable: false,+ });+ expect(parseUnrecoverableMediaMarkers('recall_bot_not_found')).toEqual({+ isAudioUnrecoverable: false,+ isVideoUnrecoverable: false,+ });+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/append-call-recorder-failure-reasons.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/append-call-recorder-failure-reasons.util.tsnew file mode 100644index 00000000000..668ed74a94a--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/append-call-recorder-failure-reasons.util.ts@@ -0,0 +1,12 @@+import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';++export const appendCallRecorderFailureReasons = ({+ callRecorderFailureReason,+ failureReasons,+}: {+ callRecorderFailureReason: string | undefined;+ failureReasons: string[];+}): string =>+ [callRecorderFailureReason, ...failureReasons]+ .filter(isNonEmptyString)+ .join(',');diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recording-sync-update.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recording-sync-update.util.tsnew file mode 100644index 00000000000..b51a39ae102--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-call-recording-sync-update.util.ts@@ -0,0 +1,133 @@+import { isNonEmptyArray, isUndefined } from '@sniptt/guards';++import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';+import { isCallRecordingStatusDowngrade } from 'src/logic-functions/domain/is-call-recording-status-downgrade.util';+import { isUnavailableCallRecordingStatus } from 'src/logic-functions/domain/is-unavailable-call-recording-status.util';+import { parseTranscriptMarker } from 'src/logic-functions/domain/parse-transcript-marker.util';+import { type RecallBotSyncState } from 'src/logic-functions/recall-api/extract-recall-bot-sync-state.util';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';++export const buildCallRecordingSyncUpdate = ({+ callRecording,+ syncState,+}: {+ callRecording: CallRecordingForArtifactsImport;+ syncState: RecallBotSyncState;+}): CallRecordingUpdateFields => {+ const updateData = buildSyncStateFieldUpdates({ callRecording, syncState });+ const externalRecordingId =+ callRecording.externalRecordingId ?? syncState.externalRecordingId;++ if (+ syncState.isRecallRecordingDone &&+ isUndefined(externalRecordingId) &&+ isUndefined(syncState.mediaExpiredAt) &&+ !hasRecordingArtifactPath({ callRecording, updateData })+ ) {+ return {+ ...updateData,+ ...buildMissingArtifactsFailureUpdate({+ currentStatus: callRecording.status,+ pendingStatus: updateData.status,+ recallFailureReason: syncState.failureReason,+ }),+ };+ }++ return updateData;+};++const buildSyncStateFieldUpdates = ({+ callRecording,+ syncState,+}: {+ callRecording: CallRecordingForArtifactsImport;+ syncState: RecallBotSyncState;+}): CallRecordingUpdateFields => {+ const updateData: CallRecordingUpdateFields = {};++ if (+ !isUndefined(syncState.status) &&+ syncState.status !== callRecording.status &&+ !isCallRecordingStatusDowngrade({+ fromStatus: callRecording.status,+ toStatus: syncState.status,+ })+ ) {+ updateData.status = syncState.status;++ if (isUnavailableCallRecordingStatus(syncState.status)) {+ updateData.callRecorderFailureReason =+ syncState.failureReason ?? 'recall_bot_failed';+ }+ }++ if (+ isUndefined(callRecording.startedAt) &&+ !isUndefined(syncState.startedAt)+ ) {+ updateData.startedAt = syncState.startedAt;+ }++ if (isUndefined(callRecording.endedAt) && !isUndefined(syncState.endedAt)) {+ updateData.endedAt = syncState.endedAt;+ }++ if (+ isUndefined(callRecording.externalRecordingId) &&+ !isUndefined(syncState.externalRecordingId)+ ) {+ updateData.externalRecordingId = syncState.externalRecordingId;+ }++ return updateData;+};++// The bot completed without ever producing a recording, so nothing was captured.+const buildMissingArtifactsFailureUpdate = ({+ currentStatus,+ pendingStatus,+ recallFailureReason,+}: {+ currentStatus: string | undefined;+ pendingStatus: string | undefined;+ recallFailureReason: string | undefined;+}): CallRecordingUpdateFields => {+ if (+ isUnavailableCallRecordingStatus(pendingStatus) ||+ isCallRecordingStatusDowngrade({+ fromStatus: currentStatus,+ toStatus: CallRecordingStatus.NOT_RECORDED,+ })+ ) {+ return {};+ }++ return {+ status: CallRecordingStatus.NOT_RECORDED,+ callRecorderFailureReason:+ recallFailureReason ?? 'recall_bot_did_not_record',+ };+};++const hasRecordingArtifactPath = ({+ callRecording,+ updateData,+}: {+ callRecording: CallRecordingForArtifactsImport;+ updateData: CallRecordingUpdateFields;+}): boolean =>+ isNonEmptyArray(updateData.audio ?? callRecording.audio) ||+ isNonEmptyArray(updateData.video ?? callRecording.video) ||+ hasReachableTranscript(updateData.transcript ?? callRecording.transcript);++const hasReachableTranscript = (transcript: unknown): boolean => {+ if (isUndefined(transcript)) {+ return false;+ }++ const transcriptMarker = parseTranscriptMarker(transcript);++ return isUndefined(transcriptMarker) || transcriptMarker.status !== 'FAILED';+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-expired-media-import-update.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-expired-media-import-update.util.tsnew file mode 100644index 00000000000..6b5a2fa03a3--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-expired-media-import-update.util.ts@@ -0,0 +1,42 @@+import { isNonEmptyArray } from '@sniptt/guards';++import {+ AUDIO_IMPORT_EXPIRED_FAILURE_REASON,+ VIDEO_IMPORT_EXPIRED_FAILURE_REASON,+} from 'src/logic-functions/constants/media-import-expired-failure-reasons';+import { appendCallRecorderFailureReasons } from 'src/logic-functions/domain/append-call-recorder-failure-reasons.util';+import { parseUnrecoverableMediaMarkers } from 'src/logic-functions/domain/parse-unrecoverable-media-markers.util';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';+import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';++export const buildExpiredMediaImportUpdate = ({+ audio,+ video,+ callRecorderFailureReason,+}: {+ audio: FilesFieldValue | undefined;+ video: FilesFieldValue | undefined;+ callRecorderFailureReason: string | undefined;+}): Pick<CallRecordingUpdateFields, 'callRecorderFailureReason'> => {+ const { isAudioUnrecoverable, isVideoUnrecoverable } =+ parseUnrecoverableMediaMarkers(callRecorderFailureReason);+ const expiredFailureReasons = [+ ...(isNonEmptyArray(video) || isVideoUnrecoverable+ ? []+ : [VIDEO_IMPORT_EXPIRED_FAILURE_REASON]),+ ...(isNonEmptyArray(audio) || isAudioUnrecoverable+ ? []+ : [AUDIO_IMPORT_EXPIRED_FAILURE_REASON]),+ ];++ if (expiredFailureReasons.length === 0) {+ return {};+ }++ return {+ callRecorderFailureReason: appendCallRecorderFailureReasons({+ callRecorderFailureReason,+ failureReasons: expiredFailureReasons,+ }),+ };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-failed-call-recording-import-update.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-failed-call-recording-import-update.util.tsnew file mode 100644index 00000000000..1ae1281b64a--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-failed-call-recording-import-update.util.ts@@ -0,0 +1,40 @@+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { hasStoredCallRecordingArtifact } from 'src/logic-functions/domain/has-stored-call-recording-artifact.util';+import { isCallRecordingImportComplete } from 'src/logic-functions/domain/is-call-recording-import-complete.util';+import { isUnavailableCallRecordingStatus } from 'src/logic-functions/domain/is-unavailable-call-recording-status.util';+import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';+import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';++// Every artifact is resolved but none was stored: completing would show an empty recording.+export const buildFailedCallRecordingImportUpdate = ({+ status,+ transcript,+ audio,+ video,+ callRecorderFailureReason,+}: {+ status: string | undefined;+ transcript: unknown;+ audio: FilesFieldValue | undefined;+ video: FilesFieldValue | undefined;+ callRecorderFailureReason: string | undefined;+}):+ | { status: CallRecordingStatus.FAILED; callRecorderFailureReason: string }+ | undefined => {+ if (+ status === CallRecordingStatus.COMPLETED ||+ isUnavailableCallRecordingStatus(status) ||+ !isNonEmptyString(callRecorderFailureReason) ||+ hasStoredCallRecordingArtifact({ transcript, audio, video }) ||+ !isCallRecordingImportComplete({+ transcript,+ audio,+ video,+ callRecorderFailureReason,+ })+ ) {+ return undefined;+ }++ return { status: CallRecordingStatus.FAILED, callRecorderFailureReason };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-orphaned-recall-bot-cleanup-delay.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-orphaned-recall-bot-cleanup-delay.util.tsdeleted file mode 100644index a1ed5ff25d0..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-orphaned-recall-bot-cleanup-delay.util.ts+++ /dev/null@@ -1,9 +0,0 @@-import { createHash } from 'crypto';--import { ORPHANED_RECALL_BOT_CLEANUP_DISTRIBUTION_WINDOW_MS } from 'src/logic-functions/constants/orphaned-recall-bot-cleanup-distribution-window-ms';--export const computeOrphanedRecallBotCleanupDelay = (- workspaceId: string,-): number =>- createHash('sha256').update(workspaceId).digest().readUInt32BE(0) %- ORPHANED_RECALL_BOT_CLEANUP_DISTRIBUTION_WINDOW_MS;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-workspace-distribution-delay.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-workspace-distribution-delay.util.tsnew file mode 100644index 00000000000..32a579a04c5--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/compute-workspace-distribution-delay.util.ts@@ -0,0 +1,11 @@+import { createHash } from 'crypto';++import { WORKSPACE_DISTRIBUTION_WINDOW_MS } from 'src/logic-functions/constants/workspace-distribution-window-ms';++// Every workspace's cron fires at the same instant; a stable per-workspace+// offset spreads the Recall traffic across the window instead of bursting it.+export const computeWorkspaceDistributionDelay = (+ workspaceId: string,+): number =>+ createHash('sha256').update(workspaceId).digest().readUInt32BE(0) %+ WORKSPACE_DISTRIBUTION_WINDOW_MS;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-call-recording-update-fields.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-call-recording-update-fields.util.tsnew file mode 100644index 00000000000..113639be95b--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-call-recording-update-fields.util.ts@@ -0,0 +1,5 @@+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';++export const hasCallRecordingUpdateFields = (+ updateData: CallRecordingUpdateFields,+): boolean => Object.keys(updateData).length > 0;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-stored-call-recording-artifact.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-stored-call-recording-artifact.util.tsnew file mode 100644index 00000000000..8970bed08ea--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-stored-call-recording-artifact.util.ts@@ -0,0 +1,18 @@+import { isNonEmptyArray, isUndefined } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';++import { parseTranscriptMarker } from 'src/logic-functions/domain/parse-transcript-marker.util';+import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';++export const hasStoredCallRecordingArtifact = ({+ transcript,+ audio,+ video,+}: {+ transcript: unknown;+ audio: FilesFieldValue | undefined;+ video: FilesFieldValue | undefined;+}): boolean =>+ isNonEmptyArray(audio) ||+ isNonEmptyArray(video) ||+ (isDefined(transcript) && isUndefined(parseTranscriptMarker(transcript)));diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-call-recording-import-complete.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-call-recording-import-complete.util.tsindex e9cd5713bb6..dac8c438fbd 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-call-recording-import-complete.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-call-recording-import-complete.util.ts@@ -1,8 +1,9 @@-import { isNonEmptyArray, isNull, isUndefined } from '@sniptt/guards';+import { isNonEmptyArray, isUndefined } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';-import { parseMediaFileTooLargeMarkers } from 'src/logic-functions/domain/parse-media-file-too-large-markers.util';import { parseTranscriptMarker } from 'src/logic-functions/domain/parse-transcript-marker.util';+import { parseUnrecoverableMediaMarkers } from 'src/logic-functions/domain/parse-unrecoverable-media-markers.util';export const isCallRecordingImportComplete = ({transcript,@@ -15,15 +16,14 @@ export const isCallRecordingImportComplete = ({video: FilesFieldValue | undefined;callRecorderFailureReason: string | null | undefined;}): boolean => {- const { audioFileTooLarge, videoFileTooLarge } =- parseMediaFileTooLargeMarkers(callRecorderFailureReason);+ const { isAudioUnrecoverable, isVideoUnrecoverable } =+ parseUnrecoverableMediaMarkers(callRecorderFailureReason);const transcriptMarker = parseTranscriptMarker(transcript);return (- !isNull(transcript) &&- !isUndefined(transcript) &&+ isDefined(transcript) &&(isUndefined(transcriptMarker) || transcriptMarker.status === 'EMPTY') &&- (isNonEmptyArray(audio) || audioFileTooLarge) &&- (isNonEmptyArray(video) || videoFileTooLarge)+ (isNonEmptyArray(audio) || isAudioUnrecoverable) &&+ (isNonEmptyArray(video) || isVideoUnrecoverable));};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-recall-recording-done-signal.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-recall-recording-done-signal.util.tsindex 50b2efef7c7..267dbd994fc 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-recall-recording-done-signal.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-recall-recording-done-signal.util.ts@@ -5,9 +5,12 @@ export const isRecallRecordingDoneSignal = ({event: string;statusCode: string | undefined;}): boolean => {+ // Recall announces retention expiry as recording.deleted; the imports then settle from what Recall still answers.return (event === 'recording.done' ||event === 'recording.failed' ||- statusCode === 'done'+ event === 'recording.deleted' ||+ statusCode === 'done' ||+ statusCode === 'media_expired');};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-reconcilable-call-recording-status.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-reconcilable-call-recording-status.util.tsnew file mode 100644index 00000000000..15845d91f12--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-reconcilable-call-recording-status.util.ts@@ -0,0 +1,8 @@+import { isUndefined } from '@sniptt/guards';++import { RECONCILABLE_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/reconcilable-call-recording-statuses';++export const isReconcilableCallRecordingStatus = (+ status: string | undefined,+): status is string =>+ !isUndefined(status) && RECONCILABLE_CALL_RECORDING_STATUSES.includes(status);diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/map-recall-status-code-to-call-recording-status.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/map-recall-status-code-to-call-recording-status.util.tsindex 05296b8d036..b37db5127cc 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/map-recall-status-code-to-call-recording-status.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/map-recall-status-code-to-call-recording-status.util.ts@@ -25,9 +25,11 @@ export const mapRecallStatusCodeToCallRecordingStatus = ({case 'in_call_recording':return CallRecordingStatus.RECORDING;// 'done' stays PROCESSING: COMPLETED is set only after all artifacts are imported.+ // 'media_expired' follows 'done' once Recall deletes the media; the import settles what was captured.case 'call_ended':case 'analysis_done':case 'done':+ case 'media_expired':return CallRecordingStatus.PROCESSING;case 'fatal':case 'analysis_failed':diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-media-file-too-large-markers.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-media-file-too-large-markers.util.tsdeleted file mode 100644index 58c5c0fe9bb..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-media-file-too-large-markers.util.ts+++ /dev/null@@ -1,27 +0,0 @@-import {- AUDIO_FILE_TOO_LARGE_FAILURE_REASON,- VIDEO_FILE_TOO_LARGE_FAILURE_REASON,-} from 'src/logic-functions/constants/media-file-too-large-failure-reasons';-import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';--export type MediaFileTooLargeMarkers = {- audioFileTooLarge: boolean;- videoFileTooLarge: boolean;-};--export const parseMediaFileTooLargeMarkers = (- callRecorderFailureReason: string | null | undefined,-): MediaFileTooLargeMarkers => {- const failureReasons = isNonEmptyString(callRecorderFailureReason)- ? callRecorderFailureReason.split(',').map((reason) => reason.trim())- : [];-- return {- audioFileTooLarge: failureReasons.includes(- AUDIO_FILE_TOO_LARGE_FAILURE_REASON,- ),- videoFileTooLarge: failureReasons.includes(- VIDEO_FILE_TOO_LARGE_FAILURE_REASON,- ),- };-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-unrecoverable-media-markers.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-unrecoverable-media-markers.util.tsnew file mode 100644index 00000000000..d09f6224f1f--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-unrecoverable-media-markers.util.ts@@ -0,0 +1,31 @@+import {+ AUDIO_FILE_TOO_LARGE_FAILURE_REASON,+ VIDEO_FILE_TOO_LARGE_FAILURE_REASON,+} from 'src/logic-functions/constants/media-file-too-large-failure-reasons';+import {+ AUDIO_IMPORT_EXPIRED_FAILURE_REASON,+ VIDEO_IMPORT_EXPIRED_FAILURE_REASON,+} from 'src/logic-functions/constants/media-import-expired-failure-reasons';+import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';++export type UnrecoverableMediaMarkers = {+ isAudioUnrecoverable: boolean;+ isVideoUnrecoverable: boolean;+};++export const parseUnrecoverableMediaMarkers = (+ callRecorderFailureReason: string | null | undefined,+): UnrecoverableMediaMarkers => {+ const failureReasons = isNonEmptyString(callRecorderFailureReason)+ ? callRecorderFailureReason.split(',').map((reason) => reason.trim())+ : [];++ return {+ isAudioUnrecoverable:+ failureReasons.includes(AUDIO_FILE_TOO_LARGE_FAILURE_REASON) ||+ failureReasons.includes(AUDIO_IMPORT_EXPIRED_FAILURE_REASON),+ isVideoUnrecoverable:+ failureReasons.includes(VIDEO_FILE_TOO_LARGE_FAILURE_REASON) ||+ failureReasons.includes(VIDEO_IMPORT_EXPIRED_FAILURE_REASON),+ };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/enqueue-call-recording-recovery.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/enqueue-call-recording-recovery.tsnew file mode 100644index 00000000000..02059bc38c5--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/enqueue-call-recording-recovery.ts@@ -0,0 +1,36 @@+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';+import { defineLogicFunction } from 'twenty-sdk/define';++import {+ ENQUEUE_CALL_RECORDING_RECOVERY_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { STALE_BOT_STATE_CRON_PATTERN } from 'src/logic-functions/constants/stale-bot-state-cron-pattern';+import {+ enqueueWorkspaceDistributedJob,+ type EnqueueWorkspaceDistributedJobResult,+} from 'src/logic-functions/data/enqueue-workspace-distributed-job.util';++export const enqueueCallRecordingRecoveryHandler = (+ _payload: unknown,+ { workspaceId }: LogicFunctionExecutionContext,+): Promise<EnqueueWorkspaceDistributedJobResult> =>+ enqueueWorkspaceDistributedJob({+ workspaceId,+ logicFunctionUniversalIdentifier:+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ stepLabel: 'call recording recovery enqueueing',+ });++export default defineLogicFunction({+ universalIdentifier:+ ENQUEUE_CALL_RECORDING_RECOVERY_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ name: 'enqueue-call-recording-recovery',+ description:+ 'Enqueues call recording recovery at a stable workspace-specific delay to distribute Recall API traffic.',+ timeoutSeconds: 30,+ handler: enqueueCallRecordingRecoveryHandler,+ cronTriggerSettings: {+ pattern: STALE_BOT_STATE_CRON_PATTERN,+ },+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/enqueue-orphaned-recall-bot-cleanup.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/enqueue-orphaned-recall-bot-cleanup.tsindex d193eaa7d09..594a68fe2ca 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/enqueue-orphaned-recall-bot-cleanup.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/enqueue-orphaned-recall-bot-cleanup.ts@@ -1,7 +1,4 @@-import {- enqueueJobs,- type LogicFunctionExecutionContext,-} from 'twenty-sdk/logic-function';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';import { defineLogicFunction } from 'twenty-sdk/define';import {@@ -9,37 +6,21 @@ import {ENQUEUE_ORPHANED_RECALL_BOT_CLEANUP_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,} from 'src/constants/universal-identifiers';import { CLEANUP_ORPHANED_RECALL_BOTS_CRON_PATTERN } from 'src/logic-functions/constants/cleanup-orphaned-recall-bots-cron-pattern';-import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';-import { computeOrphanedRecallBotCleanupDelay } from 'src/logic-functions/domain/compute-orphaned-recall-bot-cleanup-delay.util';-import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';--type EnqueueOrphanedRecallBotCleanupResult = {- delayMs: number;-};+import {+ enqueueWorkspaceDistributedJob,+ type EnqueueWorkspaceDistributedJobResult,+} from 'src/logic-functions/data/enqueue-workspace-distributed-job.util';-export const enqueueOrphanedRecallBotCleanupHandler = async (+export const enqueueOrphanedRecallBotCleanupHandler = (_payload: unknown,{ workspaceId }: LogicFunctionExecutionContext,-): Promise<EnqueueOrphanedRecallBotCleanupResult> => {- const delayMs = computeOrphanedRecallBotCleanupDelay(workspaceId);-- try {- await enqueueJobs({- logicFunctionUniversalIdentifier:- CLEANUP_ORPHANED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- payloads: [{}],- retryLimit: ENQUEUED_JOB_RETRY_LIMIT,- delayMs,- });- } catch (error) {- throw buildRetryableStepFailure(- 'orphaned Recall bot cleanup enqueueing',- error,- );- }-- return { delayMs };-};+): Promise<EnqueueWorkspaceDistributedJobResult> =>+ enqueueWorkspaceDistributedJob({+ workspaceId,+ logicFunctionUniversalIdentifier:+ CLEANUP_ORPHANED_RECALL_BOTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ stepLabel: 'orphaned Recall bot cleanup enqueueing',+ });export default defineLogicFunction({universalIdentifier:diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.tsindex d85153abb6c..31922b333b2 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.ts@@ -1,826 +1,194 @@import { type CoreApiClient } from 'twenty-client-sdk/core';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';import { convergeDivergedCallRecordings } from 'src/logic-functions/flows/converge-diverged-call-recordings.util';-const getRecallBotMock = vi.hoisted(() => vi.fn());-const getCurrentWorkspaceIdMock = vi.hoisted(() => vi.fn());-const listScheduledRecallBotsMock = vi.hoisted(() => vi.fn());-const listRecallTranscriptsMock = vi.hoisted(() => vi.fn());-const createAsyncRecallTranscriptMock = vi.hoisted(() => vi.fn());-const downloadTranscriptMock = vi.hoisted(() => vi.fn());-const importCallRecordingMediaMock = vi.hoisted(() => vi.fn());-const chargeCompletedCallRecordingMock = vi.hoisted(() => vi.fn());-const claimArtifactsImportMock = vi.hoisted(() => vi.fn());-const releaseArtifactsImportClaimMock = vi.hoisted(() => vi.fn());+const enqueueJobsMock = vi.hoisted(() => vi.fn());-vi.mock('src/logic-functions/recall-api/get-recall-bot.util', () => ({- getRecallBot: getRecallBotMock,-}));--vi.mock('src/logic-functions/data/get-current-workspace-id.util', () => ({- getCurrentWorkspaceId: getCurrentWorkspaceIdMock,-}));--vi.mock(- 'src/logic-functions/recall-api/list-scheduled-recall-bots.util',- () => ({- listScheduledRecallBots: listScheduledRecallBotsMock,- }),-);--vi.mock('src/logic-functions/recall-api/list-recall-transcripts.util', () => ({- listRecallTranscripts: listRecallTranscriptsMock,-}));--vi.mock(- 'src/logic-functions/recall-api/create-async-recall-transcript.util',- () => ({- createAsyncRecallTranscript: createAsyncRecallTranscriptMock,- }),-);--vi.mock('src/logic-functions/flows/download-transcript.util', () => ({- downloadTranscript: downloadTranscriptMock,-}));--vi.mock('src/logic-functions/flows/import-call-recording-media.util', () => ({- importCallRecordingMedia: importCallRecordingMediaMock,-}));--vi.mock(- 'src/logic-functions/flows/charge-completed-call-recording.util',- () => ({- chargeCompletedCallRecording: chargeCompletedCallRecordingMock,- }),-);--vi.mock(- 'src/logic-functions/data/claim-call-recording-artifacts-import.util',- () => ({- claimCallRecordingArtifactsImport: claimArtifactsImportMock,- releaseCallRecordingArtifactsImportClaim: releaseArtifactsImportClaimMock,- }),-);+vi.mock('twenty-sdk/logic-function', () => ({ enqueueJobs: enqueueJobsMock }));const NOW = new Date('2026-06-10T12:00:00.000Z');-type CallRecordingNode = Record<string, unknown>;--class FakeCoreApiClient {- mutations: Array<{ id: string; data: Record<string, unknown> }> = [];-- constructor(private callRecordingNodes: CallRecordingNode[]) {}-- async query(query: {- callRecordings?: {- __args?: { filter?: { id?: { eq?: string } } };- };- }) {- const requestedId = query.callRecordings?.__args?.filter?.id?.eq;- const nodes =- requestedId === undefined- ? this.callRecordingNodes- : this.callRecordingNodes.filter((node) => node.id === requestedId);-- return {- callRecordings: {- pageInfo: { hasNextPage: false, endCursor: undefined },- edges: nodes.map((node) => ({ node: { ...node } })),- },- };- }-- async mutation(mutation: any): Promise<any> {- if (mutation.updateCallRecordings !== undefined) {- const { filter, data } = mutation.updateCallRecordings.__args;- const id = filter.id.eq;- const node = this.findNode(id);-- if (- node === undefined ||- (filter.status?.in !== undefined &&- !filter.status.in.includes(node.status))- ) {- return { updateCallRecordings: [] };- }-- this.mutations.push({ id, data });- Object.assign(node, data);-- return { updateCallRecordings: [{ id }] };- }-- const { id, data } = mutation.updateCallRecording.__args;-- this.mutations.push({ id, data });- Object.assign(this.findNode(id) ?? {}, data);-- return { updateCallRecording: { id } };- }-- private findNode(id: string): CallRecordingNode | undefined {- return this.callRecordingNodes.find((node) => node.id === id);- }-}--const buildClient = (callRecordingNodes: CallRecordingNode[]) =>- new FakeCoreApiClient(callRecordingNodes);--const buildStuckRecordingNode = (- overrides: CallRecordingNode = {},-): CallRecordingNode => ({- id: 'call-recording-1',- status: 'RECORDING',- startedAt: null,- endedAt: null,- externalBotId: 'recall-bot-1',- externalRecordingId: null,- transcript: null,- audio: null,- video: null,- createdAt: '2026-06-09T12:00:00.000Z',- calendarEvent: {- startsAt: '2026-06-09T12:00:00.000Z',- endsAt: '2026-06-09T13:00:00.000Z',- },- ...overrides,+type Candidate = {+ id: string;+ status: string;+ calendarEvent?: { startsAt: string };+};++type EnqueuedBatch = {+ logicFunctionUniversalIdentifier: string;+ payloads: Record<string, unknown>[];+};++const buildClient = (nodes: Candidate[]) => ({+ query: vi.fn(+ async (query: {+ callRecordings: { __args: { first: number; after?: string } };+ }) => {+ const { first, after } = query.callRecordings.__args;+ const startIndex =+ after === undefined ? 0 : nodes.findIndex(({ id }) => id === after) + 1;+ const page = nodes.slice(startIndex, startIndex + first);++ return {+ callRecordings: {+ edges: page.map((node) => ({ node })),+ pageInfo: {+ hasNextPage: startIndex + first < nodes.length,+ endCursor: page[page.length - 1]?.id,+ },+ },+ };+ },+ ),+ mutation: vi.fn(),});+const queuedBatches = (): EnqueuedBatch[] =>+ enqueueJobsMock.mock.calls.map(([batch]) => batch);+describe('convergeDivergedCallRecordings', () => {beforeEach(() => {- vi.spyOn(console, 'warn').mockImplementation(() => {});- getRecallBotMock.mockReset();- getCurrentWorkspaceIdMock.mockReset();- getCurrentWorkspaceIdMock.mockReturnValue('workspace-1');- listScheduledRecallBotsMock.mockReset();- listScheduledRecallBotsMock.mockResolvedValue({- ok: true,- bots: [],- truncated: false,- });- listRecallTranscriptsMock.mockReset();- listRecallTranscriptsMock.mockResolvedValue({- ok: true,- transcripts: [],- });- createAsyncRecallTranscriptMock.mockReset();- createAsyncRecallTranscriptMock.mockResolvedValue({- ok: true,- transcriptId: 'recall-transcript-1',- });- downloadTranscriptMock.mockReset();- downloadTranscriptMock.mockResolvedValue({ outcome: 'pending' });- importCallRecordingMediaMock.mockReset();- importCallRecordingMediaMock.mockResolvedValue({- updateData: {},- hasRetryableFailure: false,- });- chargeCompletedCallRecordingMock.mockReset();- chargeCompletedCallRecordingMock.mockResolvedValue(undefined);- claimArtifactsImportMock.mockReset();- claimArtifactsImportMock.mockResolvedValue(true);- releaseArtifactsImportClaimMock.mockReset();- releaseArtifactsImportClaimMock.mockResolvedValue(undefined);- });-- it('does not call Recall when there are no stale database candidates', async () => {- const result = await convergeDivergedCallRecordings({- client: buildClient([]) as unknown as CoreApiClient,- now: NOW,- });-- expect(listScheduledRecallBotsMock).not.toHaveBeenCalled();- expect(getRecallBotMock).not.toHaveBeenCalled();- expect(result.candidateCount).toBe(0);- });-- it('uses a listed workspace bot without issuing a per-recording read', async () => {- listScheduledRecallBotsMock.mockResolvedValue({- ok: true,- truncated: false,- bots: [- {- id: 'recall-bot-1',- metadata: { twentyWorkspaceId: 'workspace-1' },- statusChanges: [- {- code: 'in_call_recording',- createdAt: '2026-06-09T13:02:00.000Z',- },- ],- recordings: [],- },- ],- });- const client = buildClient([buildStuckRecordingNode()]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(listScheduledRecallBotsMock).toHaveBeenCalledWith({- joinAtAfter: '2026-06-02T12:00:00.000Z',- joinAtBefore: '2026-06-10T13:00:00.000Z',- metadata: { twentyWorkspaceId: 'workspace-1' },- });- expect(getRecallBotMock).not.toHaveBeenCalled();- expect(result.updatedCallRecordingIds).toEqual(['call-recording-1']);- });-- it('defers convergence without per-recording fan-out when the bot list fails', async () => {- listScheduledRecallBotsMock.mockResolvedValue({- ok: false,- status: 429,- errorMessage: 'Recall API responded with HTTP 429',- });- const client = buildClient([buildStuckRecordingNode()]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(getRecallBotMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([]);- expect(result.candidateCount).toBe(1);- });-- it('advances the capped fallback by a full batch on each interval', async () => {- const candidateNodes = Array.from({ length: 27 }, (_, index) =>- buildStuckRecordingNode({- id: `call-recording-${index + 1}`,- externalBotId: `recall-bot-${index + 1}`,- calendarEvent: null,- createdAt: null,+ enqueueJobsMock.mockReset().mockResolvedValue({ enqueued: true });+ vi.stubGlobal(+ 'fetch',+ vi.fn(() => {+ throw new Error('Recovery must not download provider artifacts');}),);- getRecallBotMock.mockResolvedValue({- ok: false,- status: 400,- errorMessage: 'Recall API responded with HTTP 400',- });-- await convergeDivergedCallRecordings({- client: buildClient(candidateNodes) as unknown as CoreApiClient,- now: new Date(0),- });-- expect(- getRecallBotMock.mock.calls.map(([input]) => input.externalBotId),- ).toEqual(- Array.from({ length: 25 }, (_, index) => `recall-bot-${index + 1}`),- );-- getRecallBotMock.mockClear();-- await convergeDivergedCallRecordings({- client: buildClient(candidateNodes) as unknown as CoreApiClient,- now: new Date(15 * 60 * 1000),- });-- expect(- getRecallBotMock.mock.calls.map(([input]) => input.externalBotId),- ).toEqual([- 'recall-bot-26',- 'recall-bot-27',- ...Array.from({ length: 23 }, (_, index) => `recall-bot-${index + 1}`),- ]);- });-- it('heals a stuck RECORDING record from the Recall bot state', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'in_call_recording', createdAt: '2026-06-09T13:02:30.000Z' },- { code: 'call_ended', createdAt: '2026-06-09T14:00:30.000Z' },- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },- });- const client = buildClient([buildStuckRecordingNode()]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(getRecallBotMock).toHaveBeenCalledWith({- externalBotId: 'recall-bot-1',- });- expect(importCallRecordingMediaMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- externalRecordingId: 'recall-recording-1',- hasAudio: false,- hasVideo: false,- });- expect(listRecallTranscriptsMock).toHaveBeenCalledWith({- externalRecordingId: 'recall-recording-1',- });- expect(createAsyncRecallTranscriptMock).toHaveBeenCalledWith({- externalRecordingId: 'recall-recording-1',- });- expect(client.mutations).toEqual([- expect.objectContaining({- id: 'call-recording-1',- data: expect.objectContaining({- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',- }),- }),- {- id: 'call-recording-1',- data: { status: 'PROCESSING' },- },- ]);- expect(chargeCompletedCallRecordingMock).not.toHaveBeenCalled();- expect(result).toEqual({- candidateCount: 1,- updatedCallRecordingIds: ['call-recording-1'],- markedFailedCallRecordingIds: [],- requestedTranscriptCallRecordingIds: ['call-recording-1'],- unconvergeableCallRecordingIds: [],- skippedNotStartedCallRecordingIds: [],- });});- it('marks NOT_RECORDED when Recall is done but never produced a recording', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [],- },- });- const client = buildClient([buildStuckRecordingNode()]);+ afterEach(() => vi.unstubAllGlobals());+ it('does nothing when the workspace has no candidates', async () => {+ const client = buildClient([]);const result = await convergeDivergedCallRecordings({client: client as unknown as CoreApiClient,now: NOW,});- expect(listRecallTranscriptsMock).not.toHaveBeenCalled();- expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'NOT_RECORDED',- callRecorderFailureReason: 'recall_bot_did_not_record',- },- },- ]);- expect(result.updatedCallRecordingIds).toEqual(['call-recording-1']);+ expect(result).toEqual({ candidateCount: 0, enqueuedCallRecordingIds: [] });+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ expect(client.mutation).not.toHaveBeenCalled();});- it('does not fail a completed bot sync when a persisted artifact remains reachable', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [],- },- });- const client = buildClient([- buildStuckRecordingNode({- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- }),- ]);+ it('enqueues the existing media and transcript workers in one batch', async () => {+ const client = buildClient([{ id: 'recording-1', status: 'PROCESSING' }]);await convergeDivergedCallRecordings({client: client as unknown as CoreApiClient,now: NOW,});- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: { status: 'PROCESSING' },- },- ]);- });-- it('completes and charges when convergence lands the last artifact', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },- });- importCallRecordingMediaMock.mockResolvedValue({- updateData: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- hasRetryableFailure: false,- });- const client = buildClient([- buildStuckRecordingNode({- status: 'PROCESSING',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',- transcript: [{ participant: { id: 1 }, words: [] }],- }),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(listRecallTranscriptsMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier:+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ retryLimit: 2,+ payloads: [+ {+ callRecordingId: 'recording-1',+ requestedAt: NOW.toISOString(),+ scope: 'transcript',},- },- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(chargeCompletedCallRecordingMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- });- expect(result).toEqual({- candidateCount: 1,- updatedCallRecordingIds: ['call-recording-1'],- markedFailedCallRecordingIds: [],- requestedTranscriptCallRecordingIds: [],- unconvergeableCallRecordingIds: [],- skippedNotStartedCallRecordingIds: [],- });- });-- it('completes and charges when the missing video is marked too large', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },- });- importCallRecordingMediaMock.mockResolvedValue({- updateData: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- callRecorderFailureReason: 'video_file_too_large',- },- hasRetryableFailure: false,- });- const client = buildClient([- buildStuckRecordingNode({- status: 'PROCESSING',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',- transcript: [{ participant: { id: 1 }, words: [] }],- }),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],+ {+ callRecordingId: 'recording-1',+ requestedAt: NOW.toISOString(),+ scope: 'media',},- },- {- id: 'call-recording-1',- data: { callRecorderFailureReason: 'video_file_too_large' },- },- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(chargeCompletedCallRecordingMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- });- expect(result.updatedCallRecordingIds).toEqual(['call-recording-1']);- });-- it('completes from a persisted size marker once the transcript lands', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },+ ],});- const client = buildClient([- buildStuckRecordingNode({- status: 'PROCESSING',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',- callRecorderFailureReason: 'video_file_too_large',- audio: [{ fileId: 'file-audio-1' }],- transcript: [{ participant: { id: 1 }, words: [] }],- }),- ]);+ expect(client.mutation).not.toHaveBeenCalled();+ expect(fetch).not.toHaveBeenCalled();+ });++ it('reaches every recording across pages, even when earlier recordings remain processing', async () => {+ const nodes = Array.from({ length: 225 }, (_, index) => ({+ id: `recording-${index}`,+ status: 'PROCESSING',+ }));+ const client = buildClient(nodes);+ const runPage = (after?: string) =>+ convergeDivergedCallRecordings({+ client: client as unknown as CoreApiClient,+ now: NOW,+ after,+ });++ await runPage();+ expect(client.query).toHaveBeenCalledTimes(1);+ expect(queuedBatches()[0].payloads).toHaveLength(200);++ for (+ let batchIndex = 0;+ batchIndex < queuedBatches().length;+ batchIndex+++ ) {+ const batch = queuedBatches()[batchIndex];- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });+ if (+ batch.logicFunctionUniversalIdentifier ===+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER+ ) {+ const after = batch.payloads[0].after;+ expect(typeof after).toBe('string');+ if (typeof after === 'string') await runPage(after);+ }+ }- expect(importCallRecordingMediaMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- externalRecordingId: 'recall-recording-1',- hasAudio: true,- hasVideo: false,- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(chargeCompletedCallRecordingMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- });- expect(result.updatedCallRecordingIds).toEqual(['call-recording-1']);+ const importedIds = queuedBatches()+ .filter(+ ({ logicFunctionUniversalIdentifier }) =>+ logicFunctionUniversalIdentifier ===+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ )+ .flatMap(({ payloads }) =>+ payloads+ .filter(({ scope }) => scope === 'media')+ .map(({ callRecordingId }) => callRecordingId),+ );++ expect(importedIds).toEqual(nodes.map(({ id }) => id));+ expect(client.query).toHaveBeenCalledTimes(3);+ expect(+ queuedBatches().every(({ payloads }) => payloads.length <= 200),+ ).toBe(true);});- it('keeps the real failure reason over the size marker when the bot failed', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'fatal', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },- });- importCallRecordingMediaMock.mockResolvedValue({- updateData: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- callRecorderFailureReason: 'video_file_too_large',- },- hasRetryableFailure: false,- });+ it('recovers processing recordings without a bot id or a recent meeting date', async () => {const client = buildClient([- buildStuckRecordingNode({- status: 'PROCESSING',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',- transcript: [{ participant: { id: 1 }, words: [] }],- }),- ]);-- await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(client.mutations).toEqual([{- id: 'call-recording-1',- data: {- status: 'FAILED',- callRecorderFailureReason: 'fatal',- },- },- {- id: 'call-recording-1',- data: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- },- },- ]);- expect(chargeCompletedCallRecordingMock).not.toHaveBeenCalled();- });-- it('skips records whose meeting has not started yet', async () => {- const client = buildClient([- buildStuckRecordingNode({- calendarEvent: {- startsAt: '2026-06-10T12:30:00.000Z',- endsAt: '2026-06-10T13:30:00.000Z',- },- }),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(getRecallBotMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([]);- expect(result.skippedNotStartedCallRecordingIds).toEqual([- 'call-recording-1',- ]);- });-- it('converges a meeting that ended early while its scheduled end is still in the future', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-10T11:30:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-10T11:05:00.000Z',- completedAt: '2026-06-10T11:25:00.000Z',- },- ],+ id: 'old-recording',+ status: 'PROCESSING',+ calendarEvent: { startsAt: '2025-01-01T00:00:00Z' },},- });- const client = buildClient([- buildStuckRecordingNode({- calendarEvent: {- startsAt: '2026-06-10T11:00:00.000Z',- endsAt: '2026-06-10T13:00:00.000Z',- },- }),]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(getRecallBotMock).toHaveBeenCalledWith({- externalBotId: 'recall-bot-1',- });- expect(result.updatedCallRecordingIds).toEqual(['call-recording-1']);- expect(result.skippedNotStartedCallRecordingIds).toEqual([]);- });-- it('marks FAILED without clearing the bot id when Recall returns 404', async () => {- getRecallBotMock.mockResolvedValue({- ok: false,- status: 404,- errorMessage: 'Recall API responded with HTTP 404',- });- const client = buildClient([buildStuckRecordingNode()]);-const result = await convergeDivergedCallRecordings({client: client as unknown as CoreApiClient,now: NOW,});- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'FAILED',- callRecorderFailureReason: 'recall_bot_not_found',- },+ expect(result.enqueuedCallRecordingIds).toEqual(['old-recording']);+ expect(client.query.mock.calls[0][0].callRecordings.__args).toMatchObject({+ filter: {+ or: expect.arrayContaining([{ status: { eq: 'PROCESSING' } }]),},- ]);- expect(result.markedFailedCallRecordingIds).toEqual(['call-recording-1']);- expect(console.warn).toHaveBeenCalled();- });-- it('does not downgrade a COMPLETED record when its bot 404s', async () => {- getRecallBotMock.mockResolvedValue({- ok: false,- status: 404,- errorMessage: 'Recall API responded with HTTP 404',+ orderBy: [{ id: 'AscNullsLast' }],});- const client = buildClient([- buildStuckRecordingNode({- status: 'COMPLETED',- startedAt: '2026-06-09T13:02:00.000Z',- transcript: [{ participant: { id: 1 }, words: [] }],- }),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(client.mutations).toEqual([]);- expect(result.unconvergeableCallRecordingIds).toEqual(['call-recording-1']);- });-- it('logs candidates whose meeting ended before the lookback bound instead of converging them', async () => {- const client = buildClient([- buildStuckRecordingNode({- calendarEvent: { endsAt: '2026-06-01T13:00:00.000Z' },- }),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(getRecallBotMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([]);- expect(result.unconvergeableCallRecordingIds).toEqual(['call-recording-1']);- expect(console.warn).toHaveBeenCalled();});- it('converges candidates created long before a recently ended meeting', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'in_call_recording', createdAt: '2026-06-09T13:02:00.000Z' },- ],- recordings: [],- },- });+ it('enqueues lifecycle reconciliation separately and leaves future meetings alone', async () => {const client = buildClient([- buildStuckRecordingNode({- createdAt: '2026-06-01T12:00:00.000Z',- startedAt: '2026-06-09T13:02:00.000Z',- }),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(getRecallBotMock).toHaveBeenCalledWith({- externalBotId: 'recall-bot-1',- });- expect(result.unconvergeableCallRecordingIds).toEqual([]);- });-- it('applies the downgrade guard to pulled statuses while still filling timestamps', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'in_call_recording', createdAt: '2026-06-09T13:02:00.000Z' },- ],- recordings: [- { id: 'recall-recording-1', startedAt: '2026-06-09T13:02:00.000Z' },- ],+ { id: 'recording', status: 'RECORDING' },+ { id: 'completed', status: 'COMPLETED' },+ {+ id: 'future',+ status: 'SCHEDULED',+ calendarEvent: { startsAt: '2026-06-11T00:00:00Z' },},- });- const client = buildClient([- buildStuckRecordingNode({ status: 'PROCESSING' }),]);await convergeDivergedCallRecordings({@@ -828,284 +196,47 @@ describe('convergeDivergedCallRecordings', () => {now: NOW,});- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- startedAt: '2026-06-09T13:02:00.000Z',- externalRecordingId: 'recall-recording-1',- },- },- ]);- });-- it('requests a transcript for a COMPLETED candidate that has none', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },+ expect(queuedBatches()).toEqual([+ expect.objectContaining({+ logicFunctionUniversalIdentifier:+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: [+ { callRecordingId: 'recording' },+ { callRecordingId: 'completed' },],- },- });- const client = buildClient([- buildStuckRecordingNode({- status: 'COMPLETED',- startedAt: '2026-06-09T13:02:00.000Z',- externalRecordingId: 'recall-recording-1',}),]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(createAsyncRecallTranscriptMock).toHaveBeenCalledTimes(1);- expect(createAsyncRecallTranscriptMock).toHaveBeenCalledWith({- externalRecordingId: 'recall-recording-1',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- endedAt: '2026-06-09T14:00:00.000Z',- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: expect.any(String),- },- },- },- ]);- expect(result.requestedTranscriptCallRecordingIds).toEqual([- 'call-recording-1',- ]);- });-- it('does not create a duplicate transcript when Recall already has one processing', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },- });- listRecallTranscriptsMock.mockResolvedValue({- ok: true,- transcripts: [- {- id: 'recall-transcript-1',- statusCode: 'processing',- statusSubCode: undefined,- },- ],- });- const client = buildClient([buildStuckRecordingNode()]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(downloadTranscriptMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',- },- },- {- id: 'call-recording-1',- data: { status: 'PROCESSING' },- },- ]);- expect(result.requestedTranscriptCallRecordingIds).toEqual([]);});- it('fills a completed Recall transcript artifact during convergence', async () => {- const transcriptContent = [- {- participant: { id: 1, name: 'Ada' },- words: [{ text: 'hello', start_timestamp: 1, end_timestamp: 2 }],- },- ];+ it('propagates enqueue failure instead of silently reporting recovery success', async () => {+ enqueueJobsMock.mockRejectedValueOnce(new Error('Queue unavailable'));+ const client = buildClient([{ id: 'recording', status: 'PROCESSING' }]);- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },- });- listRecallTranscriptsMock.mockResolvedValue({- ok: true,- transcripts: [- {- id: 'recall-transcript-1',- statusCode: 'done',- statusSubCode: undefined,- },- ],- });- downloadTranscriptMock.mockResolvedValue({- outcome: 'filled',- content: transcriptContent,- });- const client = buildClient([- buildStuckRecordingNode({- status: 'PROCESSING',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',- transcript: {- recallTranscriptId: 'legacy-pending-transcript',- status: 'PENDING',- requestedAt: '2026-06-09T14:05:30.000Z',- },- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],+ await expect(+ convergeDivergedCallRecordings({+ client: client as unknown as CoreApiClient,+ now: NOW,}),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(downloadTranscriptMock).toHaveBeenCalledWith({- transcriptId: 'recall-transcript-1',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: { transcript: transcriptContent },- },- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(chargeCompletedCallRecordingMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- });- expect(result.requestedTranscriptCallRecordingIds).toEqual([]);+ ).rejects.toThrow('Queue unavailable');});- it('marks the call recording failed when Recall has a failed transcript artifact', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-06-09T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-06-09T13:02:00.000Z',- completedAt: '2026-06-09T14:00:00.000Z',- },- ],- },- });- listRecallTranscriptsMock.mockResolvedValue({- ok: true,- transcripts: [- {- id: 'recall-transcript-1',- statusCode: 'failed',- statusSubCode: 'audio_missing',+ it('rejects a non-advancing cursor instead of enqueueing an endless scan', async () => {+ const client = {+ query: vi.fn().mockResolvedValue({+ callRecordings: {+ edges: [],+ pageInfo: { hasNextPage: true, endCursor: 'same' },},- ],- });- const client = buildClient([- buildStuckRecordingNode({- status: 'PROCESSING',- startedAt: '2026-06-09T13:02:00.000Z',- endedAt: '2026-06-09T14:00:00.000Z',- externalRecordingId: 'recall-recording-1',}),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(downloadTranscriptMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'FAILED',- subCode: 'audio_missing',- },- },- },- {- id: 'call-recording-1',- data: {- status: 'FAILED',- callRecorderFailureReason: 'transcript_failed:audio_missing',- },- },- ]);- expect(result.requestedTranscriptCallRecordingIds).toEqual([]);- });-- it('does not mutate a record the bot state agrees with', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'in_call_recording', createdAt: '2026-06-09T13:02:00.000Z' },- ],- recordings: [],- },- });- const client = buildClient([- buildStuckRecordingNode({ startedAt: '2026-06-09T13:02:00.000Z' }),- ]);-- const result = await convergeDivergedCallRecordings({- client: client as unknown as CoreApiClient,- now: NOW,- });+ };- expect(client.mutations).toEqual([]);- expect(result.updatedCallRecordingIds).toEqual([]);+ await expect(+ convergeDivergedCallRecordings({+ client: client as unknown as CoreApiClient,+ now: NOW,+ after: 'same',+ }),+ ).rejects.toThrow('invalid next cursor');+ expect(enqueueJobsMock).not.toHaveBeenCalled();});});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.tsindex 304bba522df..90532d5c4e5 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.ts@@ -33,6 +33,30 @@ describe('downloadTranscript', () => {vi.restoreAllMocks();});+ it('reports a transcript Recall has deleted', async () => {+ fetchMock.mockImplementation((url: string) => {+ if (url === RECALL_TRANSCRIPT_URL) {+ return Promise.resolve(+ new Response(+ JSON.stringify({+ data: { download_url: null },+ status: { code: 'deleted' },+ }),+ { status: 200 },+ ),+ );+ }++ throw new Error(`Unhandled fetch url in test: ${url}`);+ });++ const result = await downloadTranscript({+ transcriptId: 'recall-transcript-1',+ });++ expect(result).toEqual({ outcome: 'deleted' });+ });+it('downloads transcript content with a timeout', async () => {const transcriptContent = [{ participant: { id: 1 }, words: [] }];diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/handle-recall-webhook.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/handle-recall-webhook.test.tsdeleted file mode 100644index 9966f860abb..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/handle-recall-webhook.test.ts+++ /dev/null@@ -1,1234 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { handleRecallWebhook } from 'src/logic-functions/flows/handle-recall-webhook.util';--const WORKSPACE_ID = '123e4567-e89b-12d3-a456-426614174000';--const buildRecordingDoneWebhookBody = () => ({- event: 'recording.done',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- recording: {- id: 'recall-recording-1',- },- },-});--const getRecallBotMock = vi.hoisted(() => vi.fn());-const listRecallTranscriptsMock = vi.hoisted(() => vi.fn());-const createAsyncRecallTranscriptMock = vi.hoisted(() => vi.fn());-const retrieveRecallTranscriptMock = vi.hoisted(() => vi.fn());-const importCallRecordingMediaMock = vi.hoisted(() => vi.fn());-const chargeCompletedCallRecordingMock = vi.hoisted(() => vi.fn());-const enqueueArtifactImportMock = vi.hoisted(() => vi.fn());--vi.mock('src/logic-functions/recall-api/get-recall-bot.util', () => ({- getRecallBot: getRecallBotMock,-}));--vi.mock('src/logic-functions/recall-api/list-recall-transcripts.util', () => ({- listRecallTranscripts: listRecallTranscriptsMock,-}));--vi.mock(- 'src/logic-functions/recall-api/create-async-recall-transcript.util',- () => ({- createAsyncRecallTranscript: createAsyncRecallTranscriptMock,- }),-);--vi.mock(- 'src/logic-functions/recall-api/retrieve-recall-transcript.util',- () => ({- retrieveRecallTranscript: retrieveRecallTranscriptMock,- }),-);--vi.mock('src/logic-functions/flows/import-call-recording-media.util', () => ({- importCallRecordingMedia: importCallRecordingMediaMock,-}));--vi.mock(- 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util',- () => ({- enqueueCallRecordingArtifactsImport: enqueueArtifactImportMock,- }),-);--vi.mock(- 'src/logic-functions/flows/charge-completed-call-recording.util',- () => ({- chargeCompletedCallRecording: chargeCompletedCallRecordingMock,- }),-);--type CallRecordingNode = {- id: string;- status?: string | null;- externalBotId?: string | null;- externalRecordingId?: string | null;- startedAt?: string | null;- endedAt?: string | null;- transcript?: unknown;- audio?: unknown;- video?: unknown;-};--class FakeCoreApiClient {- callRecordings: CallRecordingNode[];- mutations: Array<{ id: string; data: Record<string, unknown> }> = [];-- constructor(callRecordings: CallRecordingNode[]) {- this.callRecordings = callRecordings;- }-- async query(query: any): Promise<any> {- if (query.callRecordings !== undefined) {- const filter = query.callRecordings.__args.filter;-- return {- callRecordings: {- edges: this.filterCallRecordings(filter).map((callRecording) => ({- node: 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 id = filter.id.eq;-- this.mutations.push({ id, data });-- return { updateCallRecordings: [{ id }] };- }-- if (mutation.updateCallRecording !== undefined) {- const { id, data } = mutation.updateCallRecording.__args;-- this.mutations.push({ id, data });-- return {- updateCallRecording: {- id,- },- };- }-- throw new Error(`Unhandled mutation: ${JSON.stringify(mutation)}`);- }-- private filterCallRecordings(filter: any): CallRecordingNode[] {- if (filter.id?.eq !== undefined) {- return this.callRecordings.filter(- (callRecording) => callRecording.id === filter.id.eq,- );- }-- if (filter.externalBotId?.eq !== undefined) {- return this.callRecordings.filter(- (callRecording) =>- callRecording.externalBotId === filter.externalBotId.eq,- );- }-- throw new Error(- `Unhandled call recording filter: ${JSON.stringify(filter)}`,- );- }-}--describe('handleRecallWebhook', () => {- beforeEach(() => {- vi.spyOn(console, 'warn').mockImplementation(() => {});- getRecallBotMock.mockReset();- getRecallBotMock.mockResolvedValue({- ok: false,- status: null,- errorMessage: 'bot fetch disabled in test',- });- listRecallTranscriptsMock.mockReset();- listRecallTranscriptsMock.mockResolvedValue({- ok: true,- transcripts: [],- });- createAsyncRecallTranscriptMock.mockReset();- createAsyncRecallTranscriptMock.mockResolvedValue({- ok: false,- status: null,- errorMessage: 'transcript request disabled in test',- });- retrieveRecallTranscriptMock.mockReset();- retrieveRecallTranscriptMock.mockResolvedValue({- ok: false,- status: null,- errorMessage: 'transcript retrieval disabled in test',- });- importCallRecordingMediaMock.mockReset();- importCallRecordingMediaMock.mockResolvedValue({});- chargeCompletedCallRecordingMock.mockReset();- chargeCompletedCallRecordingMock.mockResolvedValue('charged');- enqueueArtifactImportMock.mockReset();- enqueueArtifactImportMock.mockResolvedValue(undefined);- });-- it('updates a call recording from bot metadata on status change events', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'JOINING',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'in_call_recording',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'RECORDING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'RECORDING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('keeps FAILED with the sub code as reason for non-benign fatal events', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'RECORDING',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'fatal',- sub_code: 'bot_errored',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'FAILED',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'FAILED',- externalBotId: 'recall-bot-1',- callRecorderFailureReason: 'bot_errored',- },- },- ]);- });-- it('keeps the plain code mapping for a no-capture sub code when a recording is already known', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'RECORDING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'call_ended',- sub_code: 'timeout_exceeded_noone_joined',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'PROCESSING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('treats a bot-detection timeout as a normal call ending', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'RECORDING',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'call_ended',- sub_code:- 'timeout_exceeded_only_bots_detected_using_participant_names',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'PROCESSING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('ignores a no-capture sub code on a non-terminal status code', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'SCHEDULED',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'joining_call',- sub_code: 'timeout_exceeded_noone_joined',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'JOINING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'JOINING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('reads bot metadata nested under data when a top-level bot has none', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'JOINING',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- bot: {- id: 'recall-bot-1',- },- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'in_call_recording',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'RECORDING',- });- });-- it('matches by metadata id when the recording carries no external bot id', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'SCHEDULED',- externalBotId: null,- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'in_call_recording',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'RECORDING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'RECORDING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('prefers the metadata id over a different recording carrying the bot id', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-stale',- status: 'SCHEDULED',- externalBotId: 'recall-bot-1',- },- {- id: 'call-recording-current',- status: 'SCHEDULED',- externalBotId: null,- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-current',- },- },- status: {- code: 'in_call_recording',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-current',- callRecordingStatus: 'RECORDING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-current',- data: {- status: 'RECORDING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('falls back to external bot id matching when call recording metadata is absent', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'recording.done',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- },- },- recording: {- id: 'recall-recording-1',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'recording.done',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'PROCESSING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- },- },- ]);- });-- it('fills startedAt from the status timestamp when the bot starts recording', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'JOINING',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'in_call_recording',- created_at: '2026-01-01T13:02:00.000Z',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'RECORDING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'RECORDING',- externalBotId: 'recall-bot-1',- startedAt: '2026-01-01T13:02:00.000Z',- },- },- ]);- });-- it('fills endedAt from the status timestamp when the recording is done', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- startedAt: '2026-01-01T13:02:00.000Z',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'done',- created_at: '2026-01-01T14:05:00.000Z',- },- },- },- });-- expect(result).toEqual({- status: 'updated',- event: 'bot.status_change',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'PROCESSING',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- endedAt: '2026-01-01T14:05:00.000Z',- },- },- ]);- });-- it('normalizes microsecond-precision Recall timestamps before writing them', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- startedAt: '2026-06-10T11:02:00.000Z',- },- ]);-- await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'done',- created_at: '2026-06-10T12:17:28.281597+00:00',- },- },- },- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- endedAt: '2026-06-10T12:17:28.281Z',- },- },- ]);- });-- it('does not overwrite an already-set startedAt on a redelivered recording event', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'RECORDING',- externalBotId: 'recall-bot-1',- startedAt: '2026-01-01T13:02:00.000Z',- },- ]);-- await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'in_call_recording',- created_at: '2026-01-01T13:09:00.000Z',- },- },- },- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'RECORDING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('does not overwrite an already-set endedAt on a redelivered done event', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- },- ]);-- await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'done',- created_at: '2026-01-01T14:11:00.000Z',- },- },- },- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- },- },- ]);- });-- it('skips a late done event once the recording is COMPLETED', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'COMPLETED',- externalBotId: 'recall-bot-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'done',- created_at: '2026-01-01T14:11:00.000Z',- },- },- },- });-- expect(result).toEqual({- status: 'skipped',- event: 'bot.status_change',- reason: 'stale status event (COMPLETED -> PROCESSING)',- });- expect(client.mutations).toEqual([]);- });-- it('skips out-of-order events that would move the status backwards', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'COMPLETED',- externalBotId: 'recall-bot-1',- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'in_call_recording',- },- },- },- });-- expect(result).toEqual({- status: 'skipped',- event: 'bot.status_change',- reason: 'stale status event (COMPLETED -> RECORDING)',- });- expect(client.mutations).toEqual([]);- });-- it('skips events whose metadata points at a missing call recording', async () => {- const client = new FakeCoreApiClient([]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-deleted',- },- },- status: {- code: 'in_call_recording',- },- },- },- });-- expect(result).toEqual({- status: 'skipped',- event: 'bot.status_change',- reason: 'no matching call recording',- });- expect(client.mutations).toEqual([]);- });-- it('skips unsupported events', async () => {- const client = new FakeCoreApiClient([]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'participant_events.done',- data: {},- },- });-- expect(result).toEqual({- status: 'skipped',- event: 'participant_events.done',- reason: 'unsupported Recall event status participant_events.done',- });- expect(client.mutations).toEqual([]);- });-- it('queues artifact import when the recording first completes', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- transcript: null,- },- ]);-- await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: buildRecordingDoneWebhookBody(),- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledExactlyOnceWith({- callRecordingId: 'call-recording-1',- scopes: ['transcript', 'media'],- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- },- },- ]);- });-- it('queues redelivered done events without touching transcript APIs inline', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- },- ]);-- await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: buildRecordingDoneWebhookBody(),- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(listRecallTranscriptsMock).not.toHaveBeenCalled();- expect(retrieveRecallTranscriptMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledTimes(1);- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- },- },- ]);- });-- it('defers provider lookup when the payload and record lack a recording id', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- transcript: null,- },- ]);-- await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'bot.status_change',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- status: {- code: 'done',- },- },- },- });-- expect(getRecallBotMock).not.toHaveBeenCalled();- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledExactlyOnceWith({- callRecordingId: 'call-recording-1',- scopes: ['transcript', 'media'],- });- expect(client.mutations).toEqual([- expect.objectContaining({- id: 'call-recording-1',- data: expect.objectContaining({- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- }),- }),- ]);- });-- it('queues media import on recording.done instead of completing inline', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- transcript: [{ participant: { id: 1 }, words: [] }],- },- ]);-- await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: buildRecordingDoneWebhookBody(),- });-- expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- },- },- ]);- expect(chargeCompletedCallRecordingMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledTimes(1);- });-- it('keeps the real failure reason on recording.failed and defers media work', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- transcript: [{ participant: { id: 1 }, words: [] }],- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- ...buildRecordingDoneWebhookBody(),- event: 'recording.failed',- },- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- status: 'FAILED',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- callRecorderFailureReason: 'recording.failed',- },- },- ]);- expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(chargeCompletedCallRecordingMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledTimes(1);- expect(result).toEqual({- status: 'updated',- event: 'recording.failed',- callRecordingId: 'call-recording-1',- callRecordingStatus: 'FAILED',- });- });-- it('queues transcript.done without downloading the transcript inline', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'transcript.done',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- transcript: {- id: 'recall-transcript-1',- },- },- },- });-- expect(result).toEqual({- status: 'queued',- event: 'transcript.done',- callRecordingId: 'call-recording-1',- });- expect(retrieveRecallTranscriptMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledExactlyOnceWith({- callRecordingId: 'call-recording-1',- scopes: ['transcript'],- });- expect(client.mutations).toEqual([]);- });-- it('queues transcript.failed without writing the failure marker inline', async () => {- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- },- ]);-- const result = await handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: {- event: 'transcript.failed',- data: {- bot: {- id: 'recall-bot-1',- metadata: {- twentyWorkspaceId: WORKSPACE_ID,- twentyCallRecordingId: 'call-recording-1',- },- },- transcript: {- id: 'recall-transcript-1',- },- status: {- sub_code: 'transcription_failed',- },- },- },- });-- expect(result).toEqual({- status: 'queued',- event: 'transcript.failed',- callRecordingId: 'call-recording-1',- });- expect(enqueueArtifactImportMock).toHaveBeenCalledExactlyOnceWith({- callRecordingId: 'call-recording-1',- scopes: ['transcript'],- });- expect(client.mutations).toEqual([]);- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/import-call-recording-artifacts.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/import-call-recording-artifacts.test.tsdeleted file mode 100644index 26a1f4f98a2..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/import-call-recording-artifacts.test.ts+++ /dev/null@@ -1,729 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { importCallRecordingArtifacts } from 'src/logic-functions/flows/import-call-recording-artifacts.util';--const getRecallBotMock = vi.hoisted(() => vi.fn());-const listRecallTranscriptsMock = vi.hoisted(() => vi.fn());-const createAsyncRecallTranscriptMock = vi.hoisted(() => vi.fn());-const downloadTranscriptMock = vi.hoisted(() => vi.fn());-const importCallRecordingMediaMock = vi.hoisted(() => vi.fn());-const chargeCompletedCallRecordingMock = vi.hoisted(() => vi.fn());-const claimArtifactsImportMock = vi.hoisted(() => vi.fn());-const releaseArtifactsImportClaimMock = vi.hoisted(() => vi.fn());--vi.mock('src/logic-functions/recall-api/get-recall-bot.util', () => ({- getRecallBot: getRecallBotMock,-}));--vi.mock('src/logic-functions/recall-api/list-recall-transcripts.util', () => ({- listRecallTranscripts: listRecallTranscriptsMock,-}));--vi.mock(- 'src/logic-functions/recall-api/create-async-recall-transcript.util',- () => ({- createAsyncRecallTranscript: createAsyncRecallTranscriptMock,- }),-);--vi.mock('src/logic-functions/flows/download-transcript.util', () => ({- downloadTranscript: downloadTranscriptMock,-}));--vi.mock('src/logic-functions/flows/import-call-recording-media.util', () => ({- importCallRecordingMedia: importCallRecordingMediaMock,-}));--vi.mock(- 'src/logic-functions/flows/charge-completed-call-recording.util',- () => ({- chargeCompletedCallRecording: chargeCompletedCallRecordingMock,- }),-);--vi.mock(- 'src/logic-functions/data/claim-call-recording-artifacts-import.util',- () => ({- claimCallRecordingArtifactsImport: claimArtifactsImportMock,- releaseCallRecordingArtifactsImportClaim: releaseArtifactsImportClaimMock,- }),-);--type CallRecordingNode = {- id: string;- status?: string | null;- externalBotId?: string | null;- externalRecordingId?: string | null;- startedAt?: string | null;- endedAt?: string | null;- callRecorderFailureReason?: string | null;- transcript?: unknown;- audio?: unknown;- video?: unknown;-};--class FakeCoreApiClient {- mutations: Array<{ id: string; data: Record<string, unknown> }> = [];-- constructor(private callRecordings: CallRecordingNode[]) {}-- async query(query: any): Promise<any> {- if (query.callRecordings !== undefined) {- const id = query.callRecordings.__args.filter.id.eq;-- return {- callRecordings: {- edges: this.callRecordings- .filter((callRecording) => callRecording.id === id)- .map((node) => ({ node: { ...node } })),- },- };- }-- 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 id = filter.id.eq;- const node = this.callRecordings.find(- (callRecording) => callRecording.id === id,- );-- if (- node === undefined ||- (filter.status?.in !== undefined &&- !filter.status.in.includes(node.status))- ) {- return { updateCallRecordings: [] };- }-- this.mutations.push({ id, data });- Object.assign(node, data);-- return { updateCallRecordings: [{ id }] };- }-- if (mutation.updateCallRecording !== undefined) {- const { id, data } = mutation.updateCallRecording.__args;- const node = this.callRecordings.find(- (callRecording) => callRecording.id === id,- );-- this.mutations.push({ id, data });-- if (node !== undefined) {- Object.assign(node, data);- }-- return { updateCallRecording: { id } };- }-- throw new Error(`Unhandled mutation: ${JSON.stringify(mutation)}`);- }-}--const buildClient = (callRecordings: CallRecordingNode[]) =>- new FakeCoreApiClient(callRecordings);--const buildProcessingCallRecording = (- overrides: Partial<CallRecordingNode> = {},-): CallRecordingNode => ({- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- externalRecordingId: 'recall-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- transcript: null,- audio: null,- video: null,- ...overrides,-});--const buildRequest = () => ({- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',-});--describe('importCallRecordingArtifacts', () => {- beforeEach(() => {- vi.spyOn(console, 'warn').mockImplementation(() => {});- getRecallBotMock.mockReset();- getRecallBotMock.mockResolvedValue({- ok: false,- status: null,- errorMessage: 'bot fetch disabled in test',- });- listRecallTranscriptsMock.mockReset();- listRecallTranscriptsMock.mockResolvedValue({- ok: true,- transcripts: [],- });- createAsyncRecallTranscriptMock.mockReset();- createAsyncRecallTranscriptMock.mockResolvedValue({- ok: true,- transcriptId: 'recall-transcript-1',- });- downloadTranscriptMock.mockReset();- downloadTranscriptMock.mockResolvedValue({ outcome: 'pending' });- importCallRecordingMediaMock.mockReset();- importCallRecordingMediaMock.mockResolvedValue({- updateData: {},- hasRetryableFailure: false,- });- chargeCompletedCallRecordingMock.mockReset();- chargeCompletedCallRecordingMock.mockResolvedValue('charged');- claimArtifactsImportMock.mockReset();- claimArtifactsImportMock.mockResolvedValue(true);- releaseArtifactsImportClaimMock.mockReset();- releaseArtifactsImportClaimMock.mockResolvedValue(undefined);- });-- it('requests a transcript after a recording completion webhook without touching media', async () => {- const client = buildClient([buildProcessingCallRecording()]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(createAsyncRecallTranscriptMock).toHaveBeenCalledWith({- externalRecordingId: 'recall-recording-1',- });- expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- },- },- ]);- expect(result).toEqual({- status: 'imported',- callRecordingId: 'call-recording-1',- scope: 'transcript',- outcome: 'call-recording-artifacts-imported',- });- });-- it('refreshes persisted artifacts after claiming the scope', async () => {- const callRecording = buildProcessingCallRecording();- const client = buildClient([callRecording]);-- claimArtifactsImportMock.mockImplementation(async () => {- callRecording.transcript = [{ participant: { id: 1 }, words: [] }];-- return true;- });-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(listRecallTranscriptsMock).not.toHaveBeenCalled();- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- });-- it('imports media without touching the transcript provider', async () => {- importCallRecordingMediaMock.mockResolvedValue({- updateData: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- hasRetryableFailure: false,- });- const client = buildClient([buildProcessingCallRecording()]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'media',- });-- expect(importCallRecordingMediaMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- externalRecordingId: 'recall-recording-1',- hasAudio: false,- hasVideo: false,- });- expect(listRecallTranscriptsMock).not.toHaveBeenCalled();- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(result).toEqual({- status: 'imported',- callRecordingId: 'call-recording-1',- scope: 'media',- outcome: 'call-recording-artifacts-imported',- });- });-- it('resolves a missing recording id from the Recall bot inside the worker', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [],- recordings: [- {- id: 'recall-recording-9',- startedAt: undefined,- completedAt: undefined,- },- ],- },- });- const client = buildClient([- buildProcessingCallRecording({ externalRecordingId: null }),- ]);-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(getRecallBotMock).toHaveBeenCalledWith({- externalBotId: 'recall-bot-1',- });- expect(createAsyncRecallTranscriptMock).toHaveBeenCalledWith({- externalRecordingId: 'recall-recording-9',- });- expect(client.mutations[0]).toEqual(- expect.objectContaining({- id: 'call-recording-1',- data: expect.objectContaining({- externalRecordingId: 'recall-recording-9',- }),- }),- );- });-- it('keeps a terminal webhook retryable when Recall has not exposed the recording id yet', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [],- recordings: [],- },- });- const client = buildClient([- buildProcessingCallRecording({ externalRecordingId: null }),- ]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([]);- expect(result).toEqual({- status: 'skipped',- callRecordingId: 'call-recording-1',- scope: 'transcript',- reason: 'no artifact updates',- });- });-- it('completes and charges when the media job lands the final media files', async () => {- importCallRecordingMediaMock.mockResolvedValue({- updateData: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- hasRetryableFailure: false,- });- const client = buildClient([- buildProcessingCallRecording({- transcript: [{ participant: { id: 1 }, words: [] }],- }),- ]);-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'media',- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- },- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(chargeCompletedCallRecordingMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- });- });-- it('completes when all artifacts were already present before the continuation ran', async () => {- const client = buildClient([- buildProcessingCallRecording({- transcript: [{ participant: { id: 1 }, words: [] }],- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- }),- ]);-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'media',- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(chargeCompletedCallRecordingMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- });- });-- it('fills a transcript and completes once media is already imported', async () => {- const transcriptContent = [- {- participant: { id: 1, name: 'Alice' },- words: [{ text: 'hello', start_timestamp: { relative: 0.5 } }],- },- ];-- downloadTranscriptMock.mockResolvedValue({- outcome: 'filled',- content: transcriptContent,- });- const client = buildClient([- buildProcessingCallRecording({- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- }),- ]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(downloadTranscriptMock).toHaveBeenCalledWith({- transcriptId: 'recall-transcript-1',- });- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: { transcript: transcriptContent },- },- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(result).toEqual({- status: 'imported',- callRecordingId: 'call-recording-1',- scope: 'transcript',- outcome: 'call-recording-artifacts-imported',- });- });-- it('completes from the re-read when the partner job landed its half after this job read the record', async () => {- const callRecording = buildProcessingCallRecording({- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- });- const client = buildClient([callRecording]);-- importCallRecordingMediaMock.mockImplementation(async () => {- callRecording.transcript = [{ participant: { id: 1 }, words: [] }];-- return {- updateData: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- hasRetryableFailure: false,- };- });-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'media',- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- },- {- id: 'call-recording-1',- data: { status: 'COMPLETED' },- },- ]);- expect(chargeCompletedCallRecordingMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- endedAt: '2026-01-01T14:05:00.000Z',- });- });-- it('leaves the record processing when the re-read still misses the partner half', async () => {- importCallRecordingMediaMock.mockResolvedValue({- updateData: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- hasRetryableFailure: false,- });- const client = buildClient([- buildProcessingCallRecording({- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- }),- ]);-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'media',- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- },- },- ]);- expect(chargeCompletedCallRecordingMock).not.toHaveBeenCalled();- });-- it('does not clobber a downloaded transcript with a late transcript.failed', async () => {- const client = buildClient([- buildProcessingCallRecording({- status: 'COMPLETED',- transcript: [{ participant: { id: 1 }, words: [] }],- }),- ]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(result).toEqual({- status: 'skipped',- callRecordingId: 'call-recording-1',- scope: 'transcript',- reason: 'no artifact updates',- });- expect(client.mutations).toEqual([]);- });-- it('writes a failed transcript marker from the listed transcript on transcript.failed', async () => {- listRecallTranscriptsMock.mockResolvedValue({- ok: true,- transcripts: [- {- id: 'recall-transcript-1',- statusCode: 'failed',- statusSubCode: 'transcription_failed',- },- ],- });- const client = buildClient([- buildProcessingCallRecording({- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'PENDING',- requestedAt: '2026-01-01T14:06:00.000Z',- },- }),- ]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(client.mutations).toEqual([- {- id: 'call-recording-1',- data: {- transcript: {- recallTranscriptId: 'recall-transcript-1',- status: 'FAILED',- subCode: 'transcription_failed',- },- },- },- {- id: 'call-recording-1',- data: {- callRecorderFailureReason: 'transcript_failed:transcription_failed',- status: 'FAILED',- },- },- ]);- expect(result).toEqual({- status: 'imported',- callRecordingId: 'call-recording-1',- scope: 'transcript',- outcome: 'call-recording-artifacts-imported',- });- });-- it('preserves terminal state while persisting media from stale provider work', async () => {- getRecallBotMock.mockResolvedValue({- ok: true,- bot: {- statusChanges: [- { code: 'done', createdAt: '2026-01-01T14:05:00.000Z' },- ],- recordings: [- {- id: 'recall-recording-1',- startedAt: '2026-01-01T13:02:00.000Z',- completedAt: '2026-01-01T14:05:00.000Z',- },- ],- },- });- const callRecording = buildProcessingCallRecording({- status: 'RECORDING',- externalRecordingId: null,- });- const client = buildClient([callRecording]);-- importCallRecordingMediaMock.mockImplementation(async () => {- callRecording.status = 'FAILED';- callRecording.callRecorderFailureReason =- 'transcript_failed:transcription_failed';-- return {- updateData: {- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],- callRecorderFailureReason: 'audio_file_too_large',- },- hasRetryableFailure: false,- };- });-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'media',- });-- expect(callRecording.status).toBe('FAILED');- expect(callRecording.callRecorderFailureReason).toBe(- 'transcript_failed:transcription_failed',- );- expect(callRecording.video).toEqual([- { fileId: 'file-video-1', label: 'video.mp4' },- ]);- });-- it('claims and releases the lease of its own scope only', async () => {- const client = buildClient([buildProcessingCallRecording()]);-- await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(claimArtifactsImportMock).toHaveBeenCalledWith(expect.anything(), {- callRecordingId: 'call-recording-1',- scope: 'transcript',- now: expect.any(Date),- });- expect(releaseArtifactsImportClaimMock).toHaveBeenCalledWith(- expect.anything(),- { callRecordingId: 'call-recording-1', scope: 'transcript' },- );- });-- it('stands aside when another worker already holds the lease for this scope', async () => {- claimArtifactsImportMock.mockResolvedValue(false);- const client = buildClient([buildProcessingCallRecording()]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'transcript',- });-- expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(releaseArtifactsImportClaimMock).not.toHaveBeenCalled();- expect(client.mutations).toEqual([]);- expect(result).toEqual({- status: 'skipped',- callRecordingId: 'call-recording-1',- scope: 'transcript',- reason: 'artifact import already in progress',- });- });-- it('skips a call recording that no longer exists', async () => {- const client = buildClient([]);-- const result = await importCallRecordingArtifacts({- client: client as unknown as CoreApiClient,- request: buildRequest(),- scope: 'media',- });-- expect(claimArtifactsImportMock).not.toHaveBeenCalled();- expect(result).toEqual({- status: 'skipped',- callRecordingId: 'call-recording-1',- scope: 'media',- reason: 'no matching call recording',- });- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/import-call-recording-media.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/import-call-recording-media.test.tsindex f2867fb030e..7f9e992af8e 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/import-call-recording-media.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/import-call-recording-media.test.ts@@ -459,6 +459,60 @@ describe('importCallRecordingMedia', () => {);});+ it('reports the recording gone without asking for a redelivery when Recall answers 404', async () => {+ buildRecallRecordingResponse = () =>+ new Response(JSON.stringify({ detail: 'Not found.' }), { status: 404 });++ const mediaImportResult = await importCallRecordingMedia({+ callRecordingId: 'call-recording-1',+ externalRecordingId: 'recall-recording-1',+ hasAudio: false,+ hasVideo: false,+ });++ expect(mediaImportResult).toEqual({+ updateData: {},+ hasRetryableFailure: false,+ isRecordingGone: true,+ });+ expect(mutationMock).not.toHaveBeenCalled();+ });++ it('records an expired marker for a deleted artifact', async () => {+ buildRecallRecordingResponse = () =>+ new Response(+ JSON.stringify({+ id: 'recall-recording-1',+ media_shortcuts: {+ video_mixed: { status: { code: 'deleted' } },+ audio_mixed: { download_url: AUDIO_URL, status: { code: 'done' } },+ },+ }),+ { status: 200 },+ );+ stubFetch({+ downloadsByUrl: {+ [AUDIO_URL]: buildDownloadResponse({ contentLengthBytes: 8 }),+ },+ });++ const mediaImportResult = await importCallRecordingMedia({+ callRecordingId: 'call-recording-1',+ externalRecordingId: 'recall-recording-1',+ hasAudio: false,+ hasVideo: false,+ });++ expect(mediaImportResult).toEqual({+ updateData: {+ audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],+ callRecorderFailureReason: 'video_import_expired',+ },+ hasRetryableFailure: false,+ });+ expect(getUploadRequestCall('video.mp4')).toBeUndefined();+ });+it('records both markers when video and audio exceed the cap', async () => {stubFetch({downloadsByUrl: {diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings-result.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings-result.type.tsindex d76740720d7..62d643fa2ff 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings-result.type.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings-result.type.ts@@ -1,8 +1,4 @@export type ConvergeDivergedCallRecordingsResult = {candidateCount: number;- updatedCallRecordingIds: string[];- markedFailedCallRecordingIds: string[];- requestedTranscriptCallRecordingIds: string[];- unconvergeableCallRecordingIds: string[];- skippedNotStartedCallRecordingIds: string[];+ enqueuedCallRecordingIds: string[];};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.tsindex 80a66050959..3292f7edc2f 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts@@ -1,469 +1,135 @@import { isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';+import {+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { CALL_RECORDING_ARTIFACT_IMPORT_SCOPES } from 'src/logic-functions/constants/call-recording-artifact-import-scopes';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 { TWENTY_PAGE_SIZE } from 'src/logic-functions/constants/twenty-page-size';-import {- fetchAllNodes,- type ConnectionPage,-} from 'src/logic-functions/data/fetch-all-nodes.util';-import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';-import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';-import { isCallRecordingStatusDowngrade } from 'src/logic-functions/domain/is-call-recording-status-downgrade.util';+import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';+import { type ConnectionPage } from 'src/logic-functions/data/fetch-all-nodes.util';import { type ConvergeDivergedCallRecordingsResult } from 'src/logic-functions/flows/converge-diverged-call-recordings-result.type';-import { runCallRecordingArtifactImportWithClaim } from 'src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util';-import { settleCallRecordingImport } from 'src/logic-functions/flows/settle-call-recording-import.util';-import {- syncCallRecording,- type SyncCallRecordingResult,- type SyncableCallRecording,-} from 'src/logic-functions/flows/sync-call-recording.util';-import { getRecallBot } from 'src/logic-functions/recall-api/get-recall-bot.util';-import {- listScheduledRecallBots,- type RecallScheduledBot,-} from 'src/logic-functions/recall-api/list-scheduled-recall-bots.util';-import { type RecallBotSnapshot } from 'src/logic-functions/recall-api/recall-bot-snapshot.type';-import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';-const CONVERGENCE_LOOKBACK_DAYS = 7;-const CONVERGENCE_BOT_LIST_LOOKBACK_DAYS = CONVERGENCE_LOOKBACK_DAYS + 1;-const CONVERGENCE_BOT_LIST_LOOKAHEAD_MILLISECONDS = 60 * 60 * 1000;-const PER_RECORDING_FALLBACK_LIMIT = 25;-const FALLBACK_ROTATION_INTERVAL_MILLISECONDS = 15 * 60 * 1000;--type DivergedCallRecordingCandidate = SyncableCallRecording & {- externalBotId: string | undefined;- createdAt: string | undefined;- calendarEventStartsAt: string | undefined;- calendarEventEndsAt: string | undefined;-};-type DivergedCallRecordingNode = {id: string;status?: string | null;- startedAt?: string | null;- endedAt?: string | null;- externalBotId?: string | null;- externalRecordingId?: string | null;- callRecorderFailureReason?: string | null;- transcript?: unknown;- audio?: FilesFieldValue | null;- video?: FilesFieldValue | null;- createdAt?: string | null;- calendarEvent?: { startsAt?: string | null; endsAt?: string | null } | null;+ calendarEvent?: { startsAt?: string | null } | null;};-// Webhook deliveries get lost; this pull pass re-derives state from Recall.export const convergeDivergedCallRecordings = async ({client,now,+ after,}: {client: CoreApiClient;now: Date;+ after?: string;}): Promise<ConvergeDivergedCallRecordingsResult> => {- const candidates = await fetchDivergedCallRecordingCandidates(client);- const convergenceLowerBound = new Date(- now.getTime() - CONVERGENCE_LOOKBACK_DAYS * 24 * 60 * 60 * 1000,- );- const result: ConvergeDivergedCallRecordingsResult = {- candidateCount: candidates.length,- updatedCallRecordingIds: [],- markedFailedCallRecordingIds: [],- requestedTranscriptCallRecordingIds: [],- unconvergeableCallRecordingIds: [],- skippedNotStartedCallRecordingIds: [],- };- const actionableCandidates: Array<- DivergedCallRecordingCandidate & { externalBotId: string }- > = [];-- for (const candidate of candidates) {- if (isOutsideConvergenceBound(candidate, convergenceLowerBound)) {- console.warn(- `[call-recorder] call recording ${candidate.id} diverged but its meeting ended more than ${CONVERGENCE_LOOKBACK_DAYS} days ago; it will not converge automatically`,- );- result.unconvergeableCallRecordingIds.push(candidate.id);- continue;- }-- if (isUndefined(candidate.externalBotId)) {- console.warn(- `[call-recorder] call recording ${candidate.id} diverged but has no Recall bot id; it will not converge automatically`,- );- result.unconvergeableCallRecordingIds.push(candidate.id);- continue;- }-- if (isBeforeMeetingStart(candidate, now)) {- result.skippedNotStartedCallRecordingIds.push(candidate.id);- continue;- }-- actionableCandidates.push({- ...candidate,- externalBotId: candidate.externalBotId,- });- }-- if (actionableCandidates.length === 0) {- return result;- }-- const listedRecallBotsById = await listRecallBotsByIdForConvergence(now);-- // A failed list means Recall is degraded; avoid fanning out per-recording reads while the provider asks for less load.- if (isUndefined(listedRecallBotsById)) {- return result;- }-- // Only unlisted candidates spend the per-recording fallback budget, so rotate- // them across runs and keep already-listed candidates (which converge for free) last.- const orderedActionableCandidates = [- ...rotateActionableCandidatesForFallback({- candidates: actionableCandidates.filter(- (candidate) => !listedRecallBotsById.has(candidate.externalBotId),- ),- now,- }),- ...actionableCandidates.filter((candidate) =>- listedRecallBotsById.has(candidate.externalBotId),- ),- ];- let remainingPerRecordingFallbackCount = PER_RECORDING_FALLBACK_LIMIT;-- for (const candidate of orderedActionableCandidates) {- const listedBot = listedRecallBotsById.get(candidate.externalBotId);-- if (isUndefined(listedBot) && remainingPerRecordingFallbackCount === 0) {- console.warn(- `[call-recorder] skipping Recall bot ${candidate.externalBotId} for call recording ${candidate.id}: per-recording convergence fallback budget exhausted`,- );-- continue;- }-- if (isUndefined(listedBot)) {- remainingPerRecordingFallbackCount -= 1;- }-- await convergeCallRecording({- client,- candidate,- externalBotId: candidate.externalBotId,- listedBot,- result,- });- }-- return result;-};--const fetchDivergedCallRecordingCandidates = async (- client: CoreApiClient,-): Promise<DivergedCallRecordingCandidate[]> => {- // No createdAt bound: older-than-lookback candidates must surface in logs.- const filter: Record<string, unknown> = {- or: [- {- recordingRequestStatus: { eq: CallRecordingRequestStatus.REQUESTED },- status: { in: NON_TERMINAL_CALL_RECORDING_STATUSES },- externalBotId: { is: 'NOT_NULL' },- },- {- status: { eq: CallRecordingStatus.COMPLETED },- or: [{ startedAt: { is: 'NULL' } }, { endedAt: { is: 'NULL' } }],- },- ],- };- const candidateNodes = await fetchAllNodes<DivergedCallRecordingNode>(- async (afterCursor) => {- const queryResult = await client.query({- callRecordings: {- __args: {- filter,- first: TWENTY_PAGE_SIZE,- ...(isUndefined(afterCursor) ? {} : { after: afterCursor }),- },- pageInfo: {- hasNextPage: true,- endCursor: true,- },- edges: {- node: {- id: true,- status: true,- startedAt: true,- endedAt: true,- externalBotId: true,- externalRecordingId: true,- callRecorderFailureReason: true,- transcript: true,- audio: { fileId: true },- video: { fileId: true },- createdAt: true,- calendarEvent: {- startsAt: true,- endsAt: true,+ const queryResult = await client.query({+ callRecordings: {+ __args: {+ filter: {+ or: [+ { status: { eq: CallRecordingStatus.PROCESSING } },+ {+ recordingRequestStatus: {+ eq: CallRecordingRequestStatus.REQUESTED,},+ status: {+ in: NON_TERMINAL_CALL_RECORDING_STATUSES.filter(+ (status) => status !== CallRecordingStatus.PROCESSING,+ ),+ },+ externalBotId: { is: 'NOT_NULL' },+ },+ {+ status: { eq: CallRecordingStatus.COMPLETED },+ externalBotId: { is: 'NOT_NULL' },+ or: [{ startedAt: { is: 'NULL' } }, { endedAt: { is: 'NULL' } }],},- },+ ],},- });-- return (queryResult.callRecordings ?? undefined) as- | ConnectionPage<DivergedCallRecordingNode>- | undefined;+ first: TWENTY_PAGE_SIZE,+ orderBy: [{ id: 'AscNullsLast' }],+ ...(isUndefined(after) ? {} : { after }),+ },+ pageInfo: { hasNextPage: true, endCursor: true },+ edges: {+ node: { id: true, status: true, calendarEvent: { startsAt: true } },+ },},- );-- return candidateNodes.map((node) => ({- id: node.id,- status: node.status ?? undefined,- startedAt: node.startedAt ?? undefined,- endedAt: node.endedAt ?? undefined,- externalBotId: isNonEmptyString(node.externalBotId)- ? node.externalBotId- : undefined,- externalRecordingId: isNonEmptyString(node.externalRecordingId)- ? node.externalRecordingId- : undefined,- callRecorderFailureReason: isNonEmptyString(node.callRecorderFailureReason)- ? node.callRecorderFailureReason- : undefined,- transcript: node.transcript ?? undefined,- audio: node.audio ?? undefined,- video: node.video ?? undefined,- createdAt: node.createdAt ?? undefined,- calendarEventStartsAt: node.calendarEvent?.startsAt ?? undefined,- calendarEventEndsAt: node.calendarEvent?.endsAt ?? undefined,- }));-};--// Anchored to meeting end: createdAt is scheduling time and can predate the meeting by weeks.-const isOutsideConvergenceBound = (- candidate: DivergedCallRecordingCandidate,- convergenceLowerBound: Date,-): boolean => {- const meetingEndReference =- candidate.calendarEventEndsAt ??- candidate.endedAt ??- candidate.calendarEventStartsAt ??- candidate.startedAt ??- candidate.createdAt;-- return (- !isUndefined(meetingEndReference) &&- new Date(meetingEndReference).getTime() < convergenceLowerBound.getTime()- );-};--// Until the meeting starts the bot has recorded nothing, so there is nothing to pull yet.-const isBeforeMeetingStart = (- candidate: DivergedCallRecordingCandidate,- now: Date,-): boolean =>- !isUndefined(candidate.calendarEventStartsAt) &&- new Date(candidate.calendarEventStartsAt).getTime() > now.getTime();--const convergeCallRecording = async ({- client,- candidate,- externalBotId,- listedBot,- result,-}: {- client: CoreApiClient;- candidate: DivergedCallRecordingCandidate;- externalBotId: string;- listedBot: RecallBotSnapshot | undefined;- result: ConvergeDivergedCallRecordingsResult;-}): Promise<void> => {- const botResult = isUndefined(listedBot)- ? await getRecallBot({ externalBotId })- : ({ ok: true, bot: listedBot } as const);-- if (!botResult.ok) {- if (botResult.status === 404) {- await markCallRecordingFailedAfterBotLoss({- client,- candidate,- externalBotId,- result,- });-- return;- }-- console.warn(- `[call-recorder] failed to fetch Recall bot ${externalBotId} for call recording ${candidate.id}: ${botResult.errorMessage}`,- );-- return;- }-- const callRecordingSyncResults: SyncCallRecordingResult[] = [];-- for (const artifactImportScope of ['transcript', 'media'] as const) {- const artifactImportClaimedAt = new Date();- const artifactImportExecution =- await runCallRecordingArtifactImportWithClaim({- client,- callRecordingId: candidate.id,- scope: artifactImportScope,- now: artifactImportClaimedAt,- runImport: (callRecording) =>- syncCallRecording({- client,- callRecording,- bot: botResult.bot,- treatRecordingAsDone: false,- requestedAt: artifactImportClaimedAt.toISOString(),- artifactScope: artifactImportScope,- }),- });-- if (artifactImportExecution.status === 'executed') {- callRecordingSyncResults.push(artifactImportExecution.result);- }- }-- const hasCompletedImport = await settleCallRecordingImport(client, {- callRecordingId: candidate.id,});- const hasUpdatedCallRecording = callRecordingSyncResults.some(- (callRecordingSyncResult) => callRecordingSyncResult.updated,- );- const hasRequestedTranscript = callRecordingSyncResults.some(- (callRecordingSyncResult) => callRecordingSyncResult.requestedTranscript,- );+ const page = queryResult.callRecordings as+ | ConnectionPage<DivergedCallRecordingNode>+ | undefined;- if (hasUpdatedCallRecording || hasCompletedImport) {- result.updatedCallRecordingIds.push(candidate.id);+ if (isUndefined(page)) {+ throw new Error('Call recording recovery returned no connection');}- if (hasRequestedTranscript) {- result.requestedTranscriptCallRecordingIds.push(candidate.id);- }-};+ const nextCursor = page.pageInfo?.hasNextPage+ ? page.pageInfo.endCursor+ : undefined;-const rotateActionableCandidatesForFallback = <- Candidate extends { externalBotId: string },->({- candidates,- now,-}: {- candidates: Candidate[];- now: Date;-}): Candidate[] => {- if (candidates.length <= PER_RECORDING_FALLBACK_LIMIT) {- return candidates;+ if (+ page.pageInfo?.hasNextPage &&+ (!isNonEmptyString(nextCursor) || nextCursor === after)+ ) {+ throw new Error('Call recording recovery returned an invalid next cursor');}- const completedRotationIntervalCount = Math.floor(- now.getTime() / FALLBACK_ROTATION_INTERVAL_MILLISECONDS,- );- const rotationOffset =- (completedRotationIntervalCount * PER_RECORDING_FALLBACK_LIMIT) %- candidates.length;-- return [- ...candidates.slice(rotationOffset),- ...candidates.slice(0, rotationOffset),- ];-};--const listRecallBotsByIdForConvergence = async (- now: Date,-): Promise<Map<string, RecallBotSnapshot> | undefined> => {- const currentWorkspaceId = getCurrentWorkspaceId();-- if (isUndefined(currentWorkspaceId)) {- console.warn(- '[call-recorder] workspace id unavailable for Recall bot list fetch; using capped per-recording convergence fallback',- );+ const importPayloads: Record<string, unknown>[] = [];+ const reconcilePayloads: Record<string, unknown>[] = [];+ const enqueuedCallRecordingIds: string[] = [];++ for (const { node } of page.edges ?? []) {+ if (node.status === CallRecordingStatus.PROCESSING) {+ for (const scope of CALL_RECORDING_ARTIFACT_IMPORT_SCOPES) {+ importPayloads.push({+ callRecordingId: node.id,+ requestedAt: now.toISOString(),+ scope,+ });+ }+ } else {+ const startsAt = node.calendarEvent?.startsAt;++ if (+ isNonEmptyString(startsAt) &&+ new Date(startsAt).getTime() > now.getTime()+ ) {+ continue;+ }++ reconcilePayloads.push({ callRecordingId: node.id });+ }- return new Map();+ enqueuedCallRecordingIds.push(node.id);}- const listResult = await listScheduledRecallBots({- joinAtAfter: new Date(- now.getTime() - CONVERGENCE_BOT_LIST_LOOKBACK_DAYS * 24 * 60 * 60 * 1000,- ).toISOString(),- joinAtBefore: new Date(- now.getTime() + CONVERGENCE_BOT_LIST_LOOKAHEAD_MILLISECONDS,- ).toISOString(),- metadata: { twentyWorkspaceId: currentWorkspaceId },+ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier:+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: importPayloads,+ });+ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier:+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: reconcilePayloads,});- if (!listResult.ok) {- console.warn(- `[call-recorder] Recall bot list fetch failed; deferring stale recording convergence to the next run: ${listResult.errorMessage}`,- );-- return undefined;- }-- return new Map(- listResult.bots- .filter((bot) =>- isCurrentWorkspaceManagedBot({ bot, currentWorkspaceId }),- )- .map((bot) => [bot.id, bot]),- );-};--const isCurrentWorkspaceManagedBot = ({- bot,- currentWorkspaceId,-}: {- bot: RecallScheduledBot;- currentWorkspaceId: string;-}): boolean => {- const claimedWorkspaceId = bot.metadata.twentyWorkspaceId;-- return (- isNonEmptyString(claimedWorkspaceId) &&- claimedWorkspaceId.trim() === currentWorkspaceId- );-};--const markCallRecordingFailedAfterBotLoss = async ({- client,- candidate,- externalBotId,- result,-}: {- client: CoreApiClient;- candidate: DivergedCallRecordingCandidate;- externalBotId: string;- result: ConvergeDivergedCallRecordingsResult;-}): Promise<void> => {- // externalBotId is kept for audit even though the bot is gone at Recall.- console.warn(- `[call-recorder] Recall bot ${externalBotId} for call recording ${candidate.id} no longer exists; it will not converge automatically`,- );-- if (- isCallRecordingStatusDowngrade({- fromStatus: candidate.status,- toStatus: CallRecordingStatus.FAILED,- })- ) {- result.unconvergeableCallRecordingIds.push(candidate.id);-- return;+ if (isNonEmptyString(nextCursor)) {+ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier:+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: [{ after: nextCursor }],+ });}- await updateCallRecording(client, {- id: candidate.id,- data: {- status: CallRecordingStatus.FAILED,- callRecorderFailureReason: 'recall_bot_not_found',- },- });- result.markedFailedCallRecordingIds.push(candidate.id);+ return { candidateCount: page.edges?.length ?? 0, enqueuedCallRecordingIds };};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.tsindex 4ae5bc12d27..59aefa880e8 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.ts@@ -1,5 +1,6 @@import { isUndefined } from '@sniptt/guards';+import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';import { retrieveRecallTranscript } from 'src/logic-functions/recall-api/retrieve-recall-transcript.util';const TRANSCRIPT_DOWNLOAD_TIMEOUT_MS = 20_000;@@ -8,6 +9,7 @@ export type DownloadTranscriptResult =| { outcome: 'filled'; content: unknown }| { outcome: 'failed'; subCode: string | null }| { outcome: 'pending' }+ | { outcome: 'deleted' }| { outcome: 'error'; errorMessage: string };export const downloadTranscript = async ({@@ -18,7 +20,9 @@ export const downloadTranscript = async ({const retrieveResult = await retrieveRecallTranscript({ transcriptId });if (!retrieveResult.ok) {- return { outcome: 'error', errorMessage: retrieveResult.errorMessage };+ return retrieveResult.status === RECALL_API_NOT_FOUND_STATUS+ ? { outcome: 'deleted' }+ : { outcome: 'error', errorMessage: retrieveResult.errorMessage };}const { downloadUrl, statusCode, statusSubCode } = retrieveResult.transcript;@@ -31,6 +35,10 @@ export const downloadTranscript = async ({return { outcome: 'failed', subCode: statusSubCode ?? null };}+ if (statusCode === 'deleted') {+ return { outcome: 'deleted' };+ }+return { outcome: 'pending' };};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-recall-webhook.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-recall-webhook.util.tsindex d4422338c56..e42f2c5fa7c 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-recall-webhook.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-recall-webhook.util.ts@@ -1,6 +1,7 @@import { isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';+import { CALL_RECORDING_ARTIFACT_IMPORT_SCOPES } from 'src/logic-functions/constants/call-recording-artifact-import-scopes';import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';import { findCallRecordingsByFilter } from 'src/logic-functions/data/find-call-recordings-by-filter.util';@@ -140,7 +141,7 @@ const handleRecallStatusEvent = async ({) {await enqueueCallRecordingArtifactsImport({callRecordingId: callRecording.id,- scopes: ['transcript', 'media'],+ scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,});}@@ -248,7 +249,7 @@ const mapRecallEventToCallRecordingStatus = ({statusCode: string | undefined;statusSubCode: string | undefined;}): CallRecordingStatus | undefined => {- if (event === 'recording.done') {+ if (event === 'recording.done' || event === 'recording.deleted') {return CallRecordingStatus.PROCESSING;}diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-artifacts.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-artifacts.util.tsindex 8f85c7c9173..e263a5bb27e 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-artifacts.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-artifacts.util.ts@@ -1,17 +1,22 @@-import { isUndefined } from '@sniptt/guards';+import { isNonEmptyArray, isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';-import {- findCallRecordingForArtifactsImport,- type CallRecordingForArtifactsImport,-} from 'src/logic-functions/data/find-call-recording-for-artifacts-import.util';-import { getRecallBot } from 'src/logic-functions/recall-api/get-recall-bot.util';-import { type RecallBotSnapshot } from 'src/logic-functions/recall-api/recall-bot-snapshot.type';+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';+import { updateClaimedCallRecordingArtifacts } from 'src/logic-functions/data/update-claimed-call-recording-artifacts.util';+import { buildCallRecordingSyncUpdate } from 'src/logic-functions/domain/build-call-recording-sync-update.util';+import { buildExpiredMediaImportUpdate } from 'src/logic-functions/domain/build-expired-media-import-update.util';+import { hasCallRecordingUpdateFields } from 'src/logic-functions/domain/has-call-recording-update-fields.util';+import { importCallRecordingMedia } from 'src/logic-functions/flows/import-call-recording-media.util';+import { importCallRecordingTranscript } from 'src/logic-functions/flows/import-call-recording-transcript.util';import { runCallRecordingArtifactImportWithClaim } from 'src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util';import { settleCallRecordingImport } from 'src/logic-functions/flows/settle-call-recording-import.util';-import { syncCallRecording } from 'src/logic-functions/flows/sync-call-recording.util';+import { extractRecallBotSyncState } from 'src/logic-functions/recall-api/extract-recall-bot-sync-state.util';+import { getRecallBot } from 'src/logic-functions/recall-api/get-recall-bot.util';import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';import { type CallRecordingArtifactsImportRequest } from 'src/logic-functions/types/call-recording-artifacts-import-request.type';+import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';export type ImportCallRecordingArtifactsResult =| {@@ -27,6 +32,17 @@ export type ImportCallRecordingArtifactsResult =reason: string;};+type RecallBotSyncResult = {+ externalRecordingId: string | undefined;+ isMediaExpired: boolean;+ updateData: CallRecordingUpdateFields;+};++type ScopeArtifactsImportResult = {+ updateData: CallRecordingUpdateFields;+ hasRetryableFailure: boolean;+};+// Job payloads can carry forged provider ids, so imports resolve only from the// CallRecording's persisted Recall bot.export const importCallRecordingArtifacts = async ({@@ -38,49 +54,64 @@ export const importCallRecordingArtifacts = async ({request: CallRecordingArtifactsImportRequest;scope: CallRecordingArtifactImportScope;}): Promise<ImportCallRecordingArtifactsResult> => {- const initialCallRecording = await findCallRecordingForArtifactsImport(- client,- request.callRecordingId,- );-- if (isUndefined(initialCallRecording)) {- return {- status: 'skipped',+ const now = new Date();+ const saveUnderClaim = (data: CallRecordingUpdateFields) =>+ updateClaimedCallRecordingArtifacts(client, {callRecordingId: request.callRecordingId,scope,- reason: 'no matching call recording',- };- }-+ claimedAt: now.toISOString(),+ data,+ });const artifactImportExecution = await runCallRecordingArtifactImportWithClaim({client,- callRecordingId: initialCallRecording.id,+ callRecordingId: request.callRecordingId,scope,- now: new Date(),+ now,runImport: async (callRecording) => {- const recallBot =- await fetchRecallBotWhenRecordingIdMissing(callRecording);- const callRecordingSyncResult = await syncCallRecording({- client,+ const botSync = await syncRecallBotState(callRecording);++ if (+ !isUndefined(botSync.updateData.status) &&+ botSync.updateData.status !== CallRecordingStatus.PROCESSING+ ) {+ await saveUnderClaim(botSync.updateData);++ return {+ status: 'skipped',+ callRecordingId: callRecording.id,+ scope,+ reason: 'call recording is not processing',+ } satisfies ImportCallRecordingArtifactsResult;+ }++ const scopeArtifactsImport = await importScopeArtifacts({callRecording,- bot: recallBot,- treatRecordingAsDone: true,+ scope,requestedAt: request.requestedAt,- artifactScope: scope,+ externalRecordingId: botSync.externalRecordingId,+ isMediaExpired: botSync.isMediaExpired,});- if (callRecordingSyncResult.hasRetryableArtifactFailure) {+ const updateData = {+ ...botSync.updateData,+ ...scopeArtifactsImport.updateData,+ };++ // Artifacts that landed are kept even when a sibling must be retried.+ await saveUnderClaim(updateData);++ if (scopeArtifactsImport.hasRetryableFailure) {throw new Error(`Recall ${scope} artifacts for call recording ${callRecording.id} could not be imported`,);}- const hasCompletedImport = await settleCallRecordingImport(client, {+ const hasSettled = await settleCallRecordingImport(client, {callRecordingId: callRecording.id,});- if (!callRecordingSyncResult.updated && !hasCompletedImport) {+ if (!hasCallRecordingUpdateFields(updateData) && !hasSettled) {return {status: 'skipped',callRecordingId: callRecording.id,@@ -102,24 +133,30 @@ export const importCallRecordingArtifacts = async ({if (artifactImportExecution.status === 'skipped') {return {status: 'skipped',- callRecordingId: initialCallRecording.id,+ callRecordingId: request.callRecordingId,scope,- reason: artifactImportExecution.reason,+ reason: 'no claimable processing call recording',};}return artifactImportExecution.result;};-const fetchRecallBotWhenRecordingIdMissing = async (+// One GET /bot fills whatever the webhooks did not deliver; a vanished bot means its media is gone too.+const syncRecallBotState = async (callRecording: CallRecordingForArtifactsImport,-): Promise<RecallBotSnapshot | undefined> => {- if (!isUndefined(callRecording.externalRecordingId)) {- return undefined;- }+): Promise<RecallBotSyncResult> => {+ const hasCompleteBotState =+ !isUndefined(callRecording.externalRecordingId) &&+ !isUndefined(callRecording.startedAt) &&+ !isUndefined(callRecording.endedAt);- if (isUndefined(callRecording.externalBotId)) {- return undefined;+ if (hasCompleteBotState || isUndefined(callRecording.externalBotId)) {+ return {+ externalRecordingId: callRecording.externalRecordingId,+ isMediaExpired: false,+ updateData: {},+ };}const botResult = await getRecallBot({@@ -127,12 +164,76 @@ const fetchRecallBotWhenRecordingIdMissing = async (});if (!botResult.ok) {- console.warn(- `[call-recorder] failed to fetch Recall bot ${callRecording.externalBotId} while resolving a recording id: ${botResult.errorMessage}`,- );+ if (botResult.status !== RECALL_API_NOT_FOUND_STATUS) {+ throw new Error(botResult.errorMessage);+ }- return undefined;+ return {+ externalRecordingId: callRecording.externalRecordingId,+ isMediaExpired: true,+ updateData: {},+ };}- return botResult.bot;+ const syncState = extractRecallBotSyncState(botResult.bot);++ return {+ externalRecordingId:+ callRecording.externalRecordingId ?? syncState.externalRecordingId,+ isMediaExpired: !isUndefined(syncState.mediaExpiredAt),+ updateData: buildCallRecordingSyncUpdate({ callRecording, syncState }),+ };+};++const importScopeArtifacts = async ({+ callRecording,+ scope,+ requestedAt,+ externalRecordingId,+ isMediaExpired,+}: {+ callRecording: CallRecordingForArtifactsImport;+ scope: CallRecordingArtifactImportScope;+ requestedAt: string;+ externalRecordingId: string | undefined;+ isMediaExpired: boolean;+}): Promise<ScopeArtifactsImportResult> => {+ if (scope === 'transcript') {+ return importCallRecordingTranscript({+ callRecordingId: callRecording.id,+ currentStatus: callRecording.status,+ externalRecordingId,+ requestedAt,+ transcript: callRecording.transcript,+ isMediaExpired,+ });+ }++ if (isMediaExpired) {+ return {+ updateData: buildExpiredMediaImportUpdate(callRecording),+ hasRetryableFailure: false,+ };+ }++ if (isUndefined(externalRecordingId)) {+ return { updateData: {}, hasRetryableFailure: false };+ }++ const mediaImport = await importCallRecordingMedia({+ callRecordingId: callRecording.id,+ externalRecordingId,+ hasAudio: isNonEmptyArray(callRecording.audio),+ hasVideo: isNonEmptyArray(callRecording.video),+ });++ return {+ updateData: {+ ...mediaImport.updateData,+ ...(mediaImport.isRecordingGone === true+ ? buildExpiredMediaImportUpdate(callRecording)+ : {}),+ },+ hasRetryableFailure: mediaImport.hasRetryableFailure,+ };};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-media.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-media.util.tsindex 2cde196f1b5..fa3f2da6f60 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-media.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-media.util.ts@@ -6,12 +6,17 @@ import {CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER,} from 'src/constants/universal-identifiers';import { CALL_RECORDER_MAX_MEDIA_FILE_SIZE_BYTES } from 'src/logic-functions/constants/call-recorder-max-media-file-size-bytes';+import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';import {AUDIO_FILE_TOO_LARGE_FAILURE_REASON,VIDEO_FILE_TOO_LARGE_FAILURE_REASON,} from 'src/logic-functions/constants/media-file-too-large-failure-reasons';+import {+ AUDIO_IMPORT_EXPIRED_FAILURE_REASON,+ VIDEO_IMPORT_EXPIRED_FAILURE_REASON,+} from 'src/logic-functions/constants/media-import-expired-failure-reasons';import { putMediaDownloadBodyToUploadTarget } from 'src/logic-functions/flows/put-media-download-body-to-upload-target.util';-import { extractRecallMediaUrls } from 'src/logic-functions/recall-api/extract-recall-media-urls.util';+import { extractRecallMediaArtifacts } from 'src/logic-functions/recall-api/extract-recall-media-artifacts.util';import { getRecallRecording } from 'src/logic-functions/recall-api/get-recall-recording.util';import { type CallRecordingMediaFile } from 'src/logic-functions/types/call-recording-media-file.type';import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';@@ -25,6 +30,8 @@ type CallRecordingMediaUpdateFields = Pick<type ImportCallRecordingMediaResult = {updateData: CallRecordingMediaUpdateFields;hasRetryableFailure: boolean;+ // Recall answers 404 for a recording whose media retention has elapsed.+ isRecordingGone?: true;};type ImportMediaArtifactResult =@@ -52,6 +59,7 @@ const MEDIA_ARTIFACT_DESCRIPTORS = [fieldMetadataUniversalIdentifier:CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER,tooLargeFailureReason: VIDEO_FILE_TOO_LARGE_FAILURE_REASON,+ expiredFailureReason: VIDEO_IMPORT_EXPIRED_FAILURE_REASON,},{field: 'audio',@@ -59,6 +67,7 @@ const MEDIA_ARTIFACT_DESCRIPTORS = [fieldMetadataUniversalIdentifier:CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER,tooLargeFailureReason: AUDIO_FILE_TOO_LARGE_FAILURE_REASON,+ expiredFailureReason: AUDIO_IMPORT_EXPIRED_FAILURE_REASON,},] as const;@@ -84,23 +93,44 @@ export const importCallRecordingMedia = async ({`[call-recorder] failed to fetch Recall recording ${externalRecordingId} while importing media for call recording ${callRecordingId}: ${recordingResult.errorMessage}`,);+ if (recordingResult.status === RECALL_API_NOT_FOUND_STATUS) {+ return {+ updateData: {},+ hasRetryableFailure: false,+ isRecordingGone: true,+ };+ }+return { updateData: {}, hasRetryableFailure: true };}- const mediaUrls = extractRecallMediaUrls(recordingResult.recording);+ const mediaArtifacts = extractRecallMediaArtifacts(recordingResult.recording);const metadataClient = new MetadataApiClient();const updateFields: CallRecordingMediaUpdateFields = {};- const tooLargeFailureReasons: string[] = [];+ const unrecoverableFailureReasons: string[] = [];const failedMediaArtifactFields: string[] = [];const artifactStateByField = {- video: { alreadyImported: hasVideo, url: mediaUrls.videoUrl },- audio: { alreadyImported: hasAudio, url: mediaUrls.audioUrl },+ video: { alreadyImported: hasVideo, artifact: mediaArtifacts.video },+ audio: { alreadyImported: hasAudio, artifact: mediaArtifacts.audio },};for (const descriptor of MEDIA_ARTIFACT_DESCRIPTORS) {- const { alreadyImported, url } = artifactStateByField[descriptor.field];+ const { alreadyImported, artifact } =+ artifactStateByField[descriptor.field];++ if (alreadyImported) {+ continue;+ }++ if (artifact.statusCode === 'deleted') {+ unrecoverableFailureReasons.push(descriptor.expiredFailureReason);++ continue;+ }++ const url = artifact.downloadUrl;- if (alreadyImported || isUndefined(url)) {+ if (isUndefined(url)) {continue;}@@ -119,7 +149,7 @@ export const importCallRecordingMedia = async ({}if (importResult.outcome === 'too-large') {- tooLargeFailureReasons.push(descriptor.tooLargeFailureReason);+ unrecoverableFailureReasons.push(descriptor.tooLargeFailureReason);}if (importResult.outcome === 'failed') {@@ -127,8 +157,9 @@ export const importCallRecordingMedia = async ({}}- if (tooLargeFailureReasons.length > 0) {- updateFields.callRecorderFailureReason = tooLargeFailureReasons.join(',');+ if (unrecoverableFailureReasons.length > 0) {+ updateFields.callRecorderFailureReason =+ unrecoverableFailureReasons.join(',');}return {diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript-result.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript-result.type.tsindex 3219afad10c..d6d85b3a896 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript-result.type.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript-result.type.ts@@ -7,6 +7,5 @@ type CallRecordingTranscriptArtifactUpdateFields = Pick<export type ImportCallRecordingTranscriptResult = {updateData: CallRecordingTranscriptArtifactUpdateFields;- requestedTranscript: boolean;hasRetryableFailure: boolean;};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript.util.tsindex 4ca8602d444..ae930fa044b 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-transcript.util.ts@@ -1,6 +1,9 @@-import { isArray, isNull, isUndefined } from '@sniptt/guards';+import { isArray, isNonEmptyArray, isNull, isUndefined } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';+import { TRANSCRIPT_EXPIRED_SUB_CODE } from 'src/logic-functions/constants/transcript-expired-sub-code';import { buildEmptyTranscriptMarker } from 'src/logic-functions/domain/build-empty-transcript-marker.util';import { buildFailedTranscriptMarker } from 'src/logic-functions/domain/build-failed-transcript-marker.util';import { buildPendingTranscriptMarker } from 'src/logic-functions/domain/build-pending-transcript-marker.util';@@ -26,20 +29,18 @@ export const importCallRecordingTranscript = async ({externalRecordingId,requestedAt,transcript,+ isMediaExpired,}: {callRecordingId: string;currentStatus: string | undefined;- externalRecordingId: string;+ externalRecordingId: string | undefined;requestedAt: string;transcript: unknown;+ isMediaExpired: boolean;}): Promise<ImportCallRecordingTranscriptResult> => {const existingTranscriptMarker = parseTranscriptMarker(transcript);- if (- !isNull(transcript) &&- !isUndefined(transcript) &&- isUndefined(existingTranscriptMarker)- ) {+ if (isDefined(transcript) && isUndefined(existingTranscriptMarker)) {return buildEmptyTranscriptArtifactResult();}@@ -50,6 +51,15 @@ export const importCallRecordingTranscript = async ({return buildEmptyTranscriptArtifactResult();}+ if (isUndefined(externalRecordingId)) {+ return isMediaExpired+ ? buildExpiredTranscriptArtifactResult({+ recallTranscriptId:+ existingTranscriptMarker?.recallTranscriptId ?? null,+ })+ : buildEmptyTranscriptArtifactResult();+ }+const listResult = await listRecallTranscripts({ externalRecordingId });if (!listResult.ok) {@@ -57,6 +67,13 @@ export const importCallRecordingTranscript = async ({`[call-recorder] failed to list Recall transcripts for recording ${externalRecordingId}: ${listResult.errorMessage}`,);+ if (listResult.status === RECALL_API_NOT_FOUND_STATUS) {+ return buildExpiredTranscriptArtifactResult({+ recallTranscriptId:+ existingTranscriptMarker?.recallTranscriptId ?? null,+ });+ }+return buildEmptyTranscriptArtifactResult({hasRetryableFailure:isNull(listResult.status) ||@@ -67,6 +84,17 @@ export const importCallRecordingTranscript = async ({const transcriptArtifact = selectRecallTranscriptArtifact(listResult.transcripts,);++ if (+ isNonEmptyArray(listResult.transcripts) &&+ isUndefined(transcriptArtifact)+ ) {+ return buildExpiredTranscriptArtifactResult({+ recallTranscriptId:+ existingTranscriptMarker?.recallTranscriptId ??+ listResult.transcripts[0].id,+ });+ }const pendingTranscriptMarkerRecallTranscriptId =existingTranscriptMarker?.status === 'PENDING'? (existingTranscriptMarker.recallTranscriptId ?? undefined)@@ -78,6 +106,10 @@ export const importCallRecordingTranscript = async ({isUndefined(transcriptArtifact) &&isUndefined(pendingTranscriptMarkerRecallTranscriptId)) {+ if (isMediaExpired) {+ return buildExpiredTranscriptArtifactResult({ recallTranscriptId: null });+ }+const createResult = await createAsyncRecallTranscript({externalRecordingId,});@@ -99,6 +131,12 @@ export const importCallRecordingTranscript = async ({});}+ if (createResult.status === RECALL_API_NOT_FOUND_STATUS) {+ return buildExpiredTranscriptArtifactResult({+ recallTranscriptId: null,+ });+ }+if (isRecallAccountStatus(createResult.status)) {return buildEmptyTranscriptArtifactResult();}@@ -110,7 +148,6 @@ export const importCallRecordingTranscript = async ({subCode: `transcript_request_rejected:${createResult.status}`,}),},- requestedTranscript: false,hasRetryableFailure: false,};}@@ -122,7 +159,6 @@ export const importCallRecordingTranscript = async ({requestedAt,}),},- requestedTranscript: true,hasRetryableFailure: false,};}@@ -138,7 +174,6 @@ export const importCallRecordingTranscript = async ({transcriptId: transcriptArtifact.id,subCode: transcriptArtifact.statusSubCode ?? null,}),- requestedTranscript: false,hasRetryableFailure: false,};}@@ -171,11 +206,16 @@ export const importCallRecordingTranscript = async ({}): (downloadResult.content as Record<string, unknown>),},- requestedTranscript: false,hasRetryableFailure: false,};}+ if (downloadResult.outcome === 'deleted') {+ return buildExpiredTranscriptArtifactResult({+ recallTranscriptId: transcriptIdToDownload,+ });+ }+if (downloadResult.outcome === 'failed') {return {updateData: buildTranscriptFailureUpdate({@@ -183,7 +223,6 @@ export const importCallRecordingTranscript = async ({transcriptId: transcriptIdToDownload,subCode: downloadResult.subCode,}),- requestedTranscript: false,hasRetryableFailure: false,};}@@ -205,10 +244,23 @@ const buildEmptyTranscriptArtifactResult = ({hasRetryableFailure?: boolean;} = {}): ImportCallRecordingTranscriptResult => ({updateData: {},- requestedTranscript: false,hasRetryableFailure,});+const buildExpiredTranscriptArtifactResult = ({+ recallTranscriptId,+}: {+ recallTranscriptId: string | null;+}): ImportCallRecordingTranscriptResult => ({+ updateData: {+ transcript: buildEmptyTranscriptMarker({+ recallTranscriptId,+ subCode: TRANSCRIPT_EXPIRED_SUB_CODE,+ }),+ },+ hasRetryableFailure: false,+});+const selectRecallTranscriptArtifact = (transcripts: RecallTranscriptSummary[],): RecallTranscriptSummary | undefined =>diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recording.util.tsnew file mode 100644index 00000000000..c0c8bcefa29--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recording.util.ts@@ -0,0 +1,100 @@+import { isUndefined } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { CALL_RECORDING_ARTIFACT_IMPORT_SCOPES } from 'src/logic-functions/constants/call-recording-artifact-import-scopes';+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';+import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';+import { findCallRecordingForArtifactsImport } from 'src/logic-functions/data/find-call-recording-for-artifacts-import.util';+import { buildCallRecordingSyncUpdate } from 'src/logic-functions/domain/build-call-recording-sync-update.util';+import { hasCallRecordingUpdateFields } from 'src/logic-functions/domain/has-call-recording-update-fields.util';+import { isReconcilableCallRecordingStatus } from 'src/logic-functions/domain/is-reconcilable-call-recording-status.util';+import { extractRecallBotSyncState } from 'src/logic-functions/recall-api/extract-recall-bot-sync-state.util';+import { getRecallBot } from 'src/logic-functions/recall-api/get-recall-bot.util';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';++export const reconcileCallRecording = async ({+ client,+ callRecordingId,+}: {+ client: CoreApiClient;+ callRecordingId: string;+}): Promise<void> => {+ const callRecording = await findCallRecordingForArtifactsImport(+ client,+ callRecordingId,+ );++ if (+ isUndefined(callRecording) ||+ !isReconcilableCallRecordingStatus(callRecording.status)+ ) {+ return;+ }++ const reconcilableStatus = callRecording.status;++ if (reconcilableStatus === CallRecordingStatus.PROCESSING) {+ await enqueueCallRecordingArtifactsImport({+ callRecordingId,+ scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,+ });++ return;+ }++ if (isUndefined(callRecording.externalBotId)) {+ return;+ }++ const botResult = await getRecallBot({+ externalBotId: callRecording.externalBotId,+ });++ if (!botResult.ok && botResult.status !== RECALL_API_NOT_FOUND_STATUS) {+ throw new Error(botResult.errorMessage);+ }++ const data = botResult.ok+ ? buildCallRecordingSyncUpdate({+ callRecording,+ syncState: extractRecallBotSyncState(botResult.bot),+ })+ : buildLostRecallBotUpdate(reconcilableStatus);++ if (!hasCallRecordingUpdateFields(data)) {+ return;+ }++ const result = await client.mutation({+ updateCallRecordings: {+ __args: {+ filter: {+ id: { eq: callRecordingId },+ status: { eq: reconcilableStatus },+ },+ data,+ },+ id: true,+ },+ });++ if (+ (result.updateCallRecordings ?? []).length > 0 &&+ data.status === CallRecordingStatus.PROCESSING+ ) {+ await enqueueCallRecordingArtifactsImport({+ callRecordingId,+ scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,+ });+ }+};++// A completed recording keeps its artifacts even after Recall forgets the bot.+const buildLostRecallBotUpdate = (status: string): CallRecordingUpdateFields =>+ status === CallRecordingStatus.COMPLETED+ ? {}+ : {+ status: CallRecordingStatus.FAILED,+ callRecorderFailureReason: 'recall_bot_not_found',+ };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.tsindex 6d60fa613cb..c6254d3e152 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@@ -1,6 +1,7 @@import { isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';+import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';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';@@ -8,8 +9,6 @@ import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workimport { rescheduleRecallBot } from 'src/logic-functions/recall-api/reschedule-recall-bot.util';import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';-const RECALL_BOT_NOT_FOUND_STATUS = 404;-export const rescheduleCallRecordingBot = async (client: CoreApiClient,{ callRecording, calendarEvent }: MeetingRecording,@@ -58,7 +57,7 @@ export const rescheduleCallRecordingBot = async (// single writer. The recorded attempt state is resolved (its bot is// confirmed gone), so clearing it lets recovery schedule directly instead// of treating the row as an ambiguous attempt.- if (rescheduleResult.status === RECALL_BOT_NOT_FOUND_STATUS) {+ if (rescheduleResult.status === RECALL_API_NOT_FOUND_STATUS) {await updateCallRecording(client, {id: callRecording.id,data: {diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util.tsindex ee586ea6c82..d480488661f 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util.ts@@ -5,23 +5,15 @@ import {claimCallRecordingArtifactsImport,releaseCallRecordingArtifactsImportClaim,} from 'src/logic-functions/data/claim-call-recording-artifacts-import.util';-import {- findCallRecordingForArtifactsImport,- type CallRecordingForArtifactsImport,-} from 'src/logic-functions/data/find-call-recording-for-artifacts-import.util';import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';+import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';type CallRecordingArtifactImportExecutionResult<TResult> =| {status: 'executed';result: TResult;}- | {- status: 'skipped';- reason:- | 'artifact import already in progress'- | 'no matching call recording';- };+ | { status: 'skipped' };export const runCallRecordingArtifactImportWithClaim = async <TResult>({client,@@ -38,43 +30,26 @@ export const runCallRecordingArtifactImportWithClaim = async <TResult>({callRecording: CallRecordingForArtifactsImport,) => Promise<TResult>;}): Promise<CallRecordingArtifactImportExecutionResult<TResult>> => {- const hasClaimedArtifactImport = await claimCallRecordingArtifactsImport(- client,- {- callRecordingId,- scope,- now,- },- );+ const claimedCallRecording = await claimCallRecordingArtifactsImport(client, {+ callRecordingId,+ scope,+ now,+ });- if (!hasClaimedArtifactImport) {- return {- status: 'skipped',- reason: 'artifact import already in progress',- };+ if (isUndefined(claimedCallRecording)) {+ return { status: 'skipped' };}try {- const callRecording = await findCallRecordingForArtifactsImport(- client,- callRecordingId,- );-- if (isUndefined(callRecording)) {- return {- status: 'skipped',- reason: 'no matching call recording',- };- }-return {status: 'executed',- result: await runImport(callRecording),+ result: await runImport(claimedCallRecording),};} finally {await releaseCallRecordingArtifactsImportClaim(client, {callRecordingId,scope,+ claimedAt: now.toISOString(),});}};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/settle-call-recording-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/settle-call-recording-import.util.tsindex 9c8dbab5d2d..6d96c4cdca6 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/settle-call-recording-import.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/settle-call-recording-import.util.ts@@ -2,6 +2,8 @@ import { isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';import { findCallRecordingForArtifactsImport } from 'src/logic-functions/data/find-call-recording-for-artifacts-import.util';+import { updateNonTerminalCallRecordingState } from 'src/logic-functions/data/update-non-terminal-call-recording-state.util';+import { buildFailedCallRecordingImportUpdate } from 'src/logic-functions/domain/build-failed-call-recording-import-update.util';import { shouldCompleteCallRecordingImport } from 'src/logic-functions/domain/should-complete-call-recording-import.util';import { completeAndChargeCallRecording } from 'src/logic-functions/flows/complete-and-charge-call-recording.util';@@ -14,10 +16,21 @@ export const settleCallRecordingImport = async (callRecordingId,);- if (- isUndefined(callRecording) ||- !shouldCompleteCallRecordingImport(callRecording)- ) {+ if (isUndefined(callRecording)) {+ return false;+ }++ const failedImportUpdate =+ buildFailedCallRecordingImportUpdate(callRecording);++ if (!isUndefined(failedImportUpdate)) {+ return updateNonTerminalCallRecordingState(client, {+ callRecordingId: callRecording.id,+ data: failedImportUpdate,+ });+ }++ if (!shouldCompleteCallRecordingImport(callRecording)) {return false;}diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/sync-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/sync-call-recording.util.tsdeleted file mode 100644index 9f5696f34e2..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/sync-call-recording.util.ts+++ /dev/null@@ -1,281 +0,0 @@-import { isNonEmptyArray, isUndefined } from '@sniptt/guards';-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';-import { isCallRecordingStatusDowngrade } from 'src/logic-functions/domain/is-call-recording-status-downgrade.util';-import { isUnavailableCallRecordingStatus } from 'src/logic-functions/domain/is-unavailable-call-recording-status.util';-import { parseTranscriptMarker } from 'src/logic-functions/domain/parse-transcript-marker.util';-import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';-import { updateNonTerminalCallRecordingState } from 'src/logic-functions/data/update-non-terminal-call-recording-state.util';-import { importCallRecordingMedia } from 'src/logic-functions/flows/import-call-recording-media.util';-import { importCallRecordingTranscript } from 'src/logic-functions/flows/import-call-recording-transcript.util';-import {- extractRecallBotSyncState,- type RecallBotSyncState,-} from 'src/logic-functions/recall-api/extract-recall-bot-sync-state.util';-import { type RecallBotSnapshot } from 'src/logic-functions/recall-api/recall-bot-snapshot.type';-import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';-import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';-import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';--export type SyncableCallRecording = {- id: string;- status: string | undefined;- startedAt: string | undefined;- endedAt: string | undefined;- externalRecordingId: string | undefined;- callRecorderFailureReason: string | undefined;- transcript: unknown;- audio: FilesFieldValue | undefined;- video: FilesFieldValue | undefined;-};--export type SyncCallRecordingResult = {- updated: boolean;- requestedTranscript: boolean;- hasRetryableArtifactFailure: boolean;-};--// The single-record sync shared by webhook-driven imports and the scheduled-// stale-recording sync. It trusts persisted Twenty data and a parsed Recall bot-// snapshot, never provider ids supplied by a route caller.-export const syncCallRecording = async ({- client,- callRecording,- bot,- treatRecordingAsDone,- requestedAt,- artifactScope,-}: {- client: CoreApiClient;- callRecording: SyncableCallRecording;- bot: RecallBotSnapshot | undefined;- // Webhook-driven imports run only for recording-done signals, so completion- // need not be re-derived from a bot snapshot they may not have.- treatRecordingAsDone: boolean;- requestedAt: string;- artifactScope: CallRecordingArtifactImportScope;-}): Promise<SyncCallRecordingResult> => {- const syncState = isUndefined(bot)- ? undefined- : extractRecallBotSyncState(bot);- const externalRecordingId =- callRecording.externalRecordingId ?? syncState?.externalRecordingId;- const isRecordingDone =- treatRecordingAsDone || syncState?.isRecallRecordingDone === true;-- const syncStateUpdate: CallRecordingUpdateFields = isUndefined(syncState)- ? {}- : buildSyncStateFieldUpdates({ callRecording, syncState });-- const missingArtifactsFailureUpdate =- syncState?.isRecallRecordingDone === true &&- isUndefined(externalRecordingId) &&- !hasRecordingArtifactPath({- callRecording,- updateData: syncStateUpdate,- })- ? buildMissingArtifactsFailureUpdate({- currentStatus: callRecording.status,- pendingStatus: syncStateUpdate.status,- recallFailureReason: syncState.failureReason,- })- : {};-- const transcriptImportResult =- isRecordingDone &&- !isUndefined(externalRecordingId) &&- artifactScope === 'transcript'- ? await importCallRecordingTranscript({- callRecordingId: callRecording.id,- currentStatus: callRecording.status,- externalRecordingId,- requestedAt,- transcript: callRecording.transcript,- })- : undefined;-- const mediaImportResult =- isRecordingDone &&- !isUndefined(externalRecordingId) &&- artifactScope === 'media'- ? await importCallRecordingMedia({- callRecordingId: callRecording.id,- externalRecordingId,- hasAudio: isNonEmptyArray(callRecording.audio),- hasVideo: isNonEmptyArray(callRecording.video),- })- : undefined;-- const mediaImportUpdate = isUndefined(mediaImportResult)- ? {}- : resolveMediaImportUpdate({- mediaImportUpdate: mediaImportResult.updateData,- currentStatus: callRecording.status,- pendingStatus: syncStateUpdate.status,- });-- const updateData: CallRecordingUpdateFields = {- ...syncStateUpdate,- ...missingArtifactsFailureUpdate,- ...(transcriptImportResult?.updateData ?? {}),- ...mediaImportUpdate,- };-- const { status, callRecorderFailureReason, ...callRecordingProgressUpdate } =- updateData;- const callRecordingStateUpdate: Pick<- CallRecordingUpdateFields,- 'status' | 'callRecorderFailureReason'- > = {- ...(isUndefined(status) ? {} : { status }),- ...(isUndefined(callRecorderFailureReason)- ? {}- : { callRecorderFailureReason }),- };- const hasCallRecordingProgressUpdate =- Object.keys(callRecordingProgressUpdate).length > 0;-- if (hasCallRecordingProgressUpdate) {- await updateCallRecording(client, {- id: callRecording.id,- data: callRecordingProgressUpdate,- });- }-- const hasUpdatedCallRecordingState =- Object.keys(callRecordingStateUpdate).length > 0- ? await updateNonTerminalCallRecordingState(client, {- callRecordingId: callRecording.id,- data: callRecordingStateUpdate,- })- : false;-- return {- updated: hasCallRecordingProgressUpdate || hasUpdatedCallRecordingState,- requestedTranscript: transcriptImportResult?.requestedTranscript ?? false,- hasRetryableArtifactFailure:- transcriptImportResult?.hasRetryableFailure ??- mediaImportResult?.hasRetryableFailure ??- false,- };-};--const buildSyncStateFieldUpdates = ({- callRecording,- syncState,-}: {- callRecording: SyncableCallRecording;- syncState: RecallBotSyncState;-}): CallRecordingUpdateFields => {- const updateData: CallRecordingUpdateFields = {};-- if (- !isUndefined(syncState.status) &&- syncState.status !== callRecording.status &&- !isCallRecordingStatusDowngrade({- fromStatus: callRecording.status,- toStatus: syncState.status,- })- ) {- updateData.status = syncState.status;-- if (isUnavailableCallRecordingStatus(syncState.status)) {- updateData.callRecorderFailureReason =- syncState.failureReason ?? 'recall_bot_failed';- }- }-- if (- isUndefined(callRecording.startedAt) &&- !isUndefined(syncState.startedAt)- ) {- updateData.startedAt = syncState.startedAt;- }-- if (isUndefined(callRecording.endedAt) && !isUndefined(syncState.endedAt)) {- updateData.endedAt = syncState.endedAt;- }-- if (- isUndefined(callRecording.externalRecordingId) &&- !isUndefined(syncState.externalRecordingId)- ) {- updateData.externalRecordingId = syncState.externalRecordingId;- }-- return updateData;-};--// The bot completed without ever producing a recording, so nothing was captured.-const buildMissingArtifactsFailureUpdate = ({- currentStatus,- pendingStatus,- recallFailureReason,-}: {- currentStatus: string | undefined;- pendingStatus: string | undefined;- recallFailureReason: string | undefined;-}): CallRecordingUpdateFields => {- if (- isUnavailableCallRecordingStatus(pendingStatus) ||- isCallRecordingStatusDowngrade({- fromStatus: currentStatus,- toStatus: CallRecordingStatus.NOT_RECORDED,- })- ) {- return {};- }-- return {- status: CallRecordingStatus.NOT_RECORDED,- callRecorderFailureReason:- recallFailureReason ?? 'recall_bot_did_not_record',- };-};--const hasRecordingArtifactPath = ({- callRecording,- updateData,-}: {- callRecording: SyncableCallRecording;- updateData: CallRecordingUpdateFields;-}): boolean =>- isNonEmptyArray(updateData.audio ?? callRecording.audio) ||- isNonEmptyArray(updateData.video ?? callRecording.video) ||- hasReachableTranscript(updateData.transcript ?? callRecording.transcript);--const hasReachableTranscript = (transcript: unknown): boolean => {- if (isUndefined(transcript)) {- return false;- }-- const transcriptMarker = parseTranscriptMarker(transcript);-- return isUndefined(transcriptMarker) || transcriptMarker.status !== 'FAILED';-};--// A media size marker must not overwrite the failure reason of a FAILED recording.-const resolveMediaImportUpdate = ({- mediaImportUpdate,- currentStatus,- pendingStatus,-}: {- mediaImportUpdate: CallRecordingUpdateFields;- currentStatus: string | undefined;- pendingStatus: string | undefined;-}): CallRecordingUpdateFields => {- const hasNoRecording =- isUnavailableCallRecordingStatus(currentStatus) ||- isUnavailableCallRecordingStatus(pendingStatus);-- if (!hasNoRecording) {- return mediaImportUpdate;- }-- const scrubbedUpdate = { ...mediaImportUpdate };-- delete scrubbedUpdate.callRecorderFailureReason;-- return scrubbedUpdate;-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-bot-sync-state.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-bot-sync-state.test.tsindex 973540c7faa..64116339971 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-bot-sync-state.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-bot-sync-state.test.ts@@ -68,6 +68,7 @@ describe('extractRecallBotSyncState', () => {startedAt: '2026-01-01T13:02:00.000Z',endedAt: '2026-01-01T14:00:00.000Z',externalRecordingId: 'recall-recording-1',+ mediaExpiredAt: undefined,isRecallRecordingDone: true,});});@@ -95,6 +96,7 @@ describe('extractRecallBotSyncState', () => {startedAt: '2026-01-01T13:02:00.000Z',endedAt: '2026-01-01T14:00:00.000Z',externalRecordingId: 'recall-recording-1',+ mediaExpiredAt: undefined,isRecallRecordingDone: false,});});@@ -126,10 +128,41 @@ describe('extractRecallBotSyncState', () => {startedAt: undefined,endedAt: undefined,externalRecordingId: undefined,+ mediaExpiredAt: undefined,isRecallRecordingDone: false,});});+ it('reports when Recall expired the media of a bot that recorded', () => {+ const syncState = extractRecallBotSyncState(+ buildRecallBotSnapshot({+ statusChanges: [+ {+ code: 'in_call_recording',+ createdAt: '2026-09-04T13:24:11.861710Z',+ },+ {+ code: 'call_ended',+ subCode: 'timeout_exceeded_everyone_left',+ createdAt: '2026-09-04T13:27:24.500429Z',+ },+ { code: 'done', createdAt: '2026-09-04T13:27:25.494042Z' },+ { code: 'media_expired', createdAt: '2026-09-11T12:17:33.159774Z' },+ ],+ }),+ );++ expect(syncState).toEqual({+ status: 'PROCESSING',+ failureReason: undefined,+ startedAt: '2026-09-04T13:24:11.861Z',+ endedAt: '2026-09-04T13:27:24.500Z',+ externalRecordingId: undefined,+ mediaExpiredAt: '2026-09-11T12:17:33.159Z',+ isRecallRecordingDone: true,+ });+ });+it('carries the failing Recall status code as the failure reason', () => {const syncState = extractRecallBotSyncState(buildRecallBotSnapshot({diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-media-artifacts.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-media-artifacts.test.tsnew file mode 100644index 00000000000..12a942a48d7--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-media-artifacts.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from 'vitest';++import { extractRecallMediaArtifacts } from 'src/logic-functions/recall-api/extract-recall-media-artifacts.util';++describe('extractRecallMediaArtifacts', () => {+ it('reads download urls and artifact statuses flat from the v1.11 media shortcuts', () => {+ expect(+ extractRecallMediaArtifacts({+ id: 'recall-recording-1',+ expires_at: '2026-09-14T14:09:46.365456Z',+ media_shortcuts: {+ video_mixed: {+ download_url: 'https://media.example.com/video.mp4',+ status: { code: 'done' },+ },+ audio_mixed: {+ download_url: 'https://media.example.com/audio.mp3',+ status: { code: 'done' },+ },+ },+ }),+ ).toEqual({+ video: {+ downloadUrl: 'https://media.example.com/video.mp4',+ statusCode: 'done',+ },+ audio: {+ downloadUrl: 'https://media.example.com/audio.mp3',+ statusCode: 'done',+ },+ });+ });++ it('falls back to the nested data.download_url shape', () => {+ expect(+ extractRecallMediaArtifacts({+ id: 'recall-recording-1',+ media_shortcuts: {+ video_mixed: {+ data: { download_url: 'https://media.example.com/video.mp4' },+ },+ audio_mixed: {+ data: { download_url: 'https://media.example.com/audio.mp3' },+ },+ },+ }),+ ).toEqual({+ video: {+ downloadUrl: 'https://media.example.com/video.mp4',+ statusCode: undefined,+ },+ audio: {+ downloadUrl: 'https://media.example.com/audio.mp3',+ statusCode: undefined,+ },+ });+ });++ it('reports a deleted artifact that carries no download url', () => {+ expect(+ extractRecallMediaArtifacts({+ id: 'recall-recording-1',+ media_shortcuts: {+ video_mixed: { status: { code: 'deleted' } },+ audio_mixed: { status: { code: 'deleted' } },+ },+ }),+ ).toEqual({+ video: { downloadUrl: undefined, statusCode: 'deleted' },+ audio: { downloadUrl: undefined, statusCode: 'deleted' },+ });+ });++ it('returns undefined fields when artifacts are absent', () => {+ expect(+ extractRecallMediaArtifacts({+ id: 'recall-recording-1',+ media_shortcuts: {+ video_mixed: {},+ },+ }),+ ).toEqual({+ video: { downloadUrl: undefined, statusCode: undefined },+ audio: { downloadUrl: undefined, statusCode: undefined },+ });+ });++ it('tolerates malformed recording payloads', () => {+ const emptyArtifacts = {+ video: { downloadUrl: undefined, statusCode: undefined },+ audio: { downloadUrl: undefined, statusCode: undefined },+ };++ expect(extractRecallMediaArtifacts({})).toEqual(emptyArtifacts);+ expect(+ extractRecallMediaArtifacts({ media_shortcuts: 'not-a-record' }),+ ).toEqual(emptyArtifacts);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-media-urls.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-media-urls.test.tsdeleted file mode 100644index 1f254c3cc9d..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/extract-recall-media-urls.test.ts+++ /dev/null@@ -1,67 +0,0 @@-import { describe, expect, it } from 'vitest';--import { extractRecallMediaUrls } from 'src/logic-functions/recall-api/extract-recall-media-urls.util';--describe('extractRecallMediaUrls', () => {- it('reads both download urls flat from the v1.11 media shortcuts', () => {- expect(- extractRecallMediaUrls({- id: 'recall-recording-1',- media_shortcuts: {- video_mixed: {- download_url: 'https://media.example.com/video.mp4',- },- audio_mixed: {- download_url: 'https://media.example.com/audio.mp3',- },- },- }),- ).toEqual({- videoUrl: 'https://media.example.com/video.mp4',- audioUrl: 'https://media.example.com/audio.mp3',- });- });-- it('falls back to the nested data.download_url shape', () => {- expect(- extractRecallMediaUrls({- id: 'recall-recording-1',- media_shortcuts: {- video_mixed: {- data: { download_url: 'https://media.example.com/video.mp4' },- },- audio_mixed: {- data: { download_url: 'https://media.example.com/audio.mp3' },- },- },- }),- ).toEqual({- videoUrl: 'https://media.example.com/video.mp4',- audioUrl: 'https://media.example.com/audio.mp3',- });- });-- it('returns undefined urls when artifacts are absent', () => {- expect(- extractRecallMediaUrls({- id: 'recall-recording-1',- media_shortcuts: {- video_mixed: {},- },- }),- ).toEqual({ videoUrl: undefined, audioUrl: undefined });- });-- it('tolerates malformed recording payloads', () => {- expect(extractRecallMediaUrls({})).toEqual({- videoUrl: undefined,- audioUrl: undefined,- });- expect(extractRecallMediaUrls({ media_shortcuts: 'not-a-record' })).toEqual(- {- videoUrl: undefined,- audioUrl: undefined,- },- );- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-bot-sync-state.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-bot-sync-state.util.tsindex 286640b5644..ebf29231521 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-bot-sync-state.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-bot-sync-state.util.ts@@ -14,6 +14,7 @@ export type RecallBotSyncState = {startedAt: string | undefined;endedAt: string | undefined;externalRecordingId: string | undefined;+ mediaExpiredAt: string | undefined;isRecallRecordingDone: boolean;};@@ -50,6 +51,9 @@ export const extractRecallBotSyncState = (findStatusChangeTimestamp(statusChanges, 'call_ended'),),externalRecordingId: recording?.id,+ mediaExpiredAt: normalizeRecallTimestamp(+ findStatusChangeTimestamp(statusChanges, 'media_expired'),+ ),isRecallRecordingDone:!isUndefined(recording?.completedAt) ||statusChanges.some((statusChange) => statusChange.code === 'done'),diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-media-artifacts.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-media-artifacts.util.tsnew file mode 100644index 00000000000..dae7ff26880--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-media-artifacts.util.ts@@ -0,0 +1,40 @@+import { asRecord } from 'src/logic-functions/utils/as-record.util';+import { getRecordAtPath } from 'src/logic-functions/utils/get-record-at-path.util';+import { getString } from 'src/logic-functions/utils/get-string.util';++export type RecallMediaArtifact = {+ downloadUrl: string | undefined;+ statusCode: string | undefined;+};++export type RecallMediaArtifacts = {+ video: RecallMediaArtifact;+ audio: RecallMediaArtifact;+};++// Pre-signed URLs expire within hours; always re-extract from a fresh GET /recording.+export const extractRecallMediaArtifacts = (+ recording: Record<string, unknown>,+): RecallMediaArtifacts => {+ const mediaShortcuts = asRecord(recording.media_shortcuts);++ return {+ video: extractArtifact(mediaShortcuts, 'video_mixed'),+ audio: extractArtifact(mediaShortcuts, 'audio_mixed'),+ };+};++// v1.11 exposes download_url flat on the artifact; older artifacts nest it under data.+const extractArtifact = (+ mediaShortcuts: Record<string, unknown> | undefined,+ artifactKey: string,+): RecallMediaArtifact => ({+ downloadUrl:+ getString(getRecordAtPath(mediaShortcuts, [artifactKey, 'download_url'])) ??+ getString(+ getRecordAtPath(mediaShortcuts, [artifactKey, 'data', 'download_url']),+ ),+ statusCode: getString(+ getRecordAtPath(mediaShortcuts, [artifactKey, 'status', 'code']),+ ),+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-media-urls.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-media-urls.util.tsdeleted file mode 100644index 83d4bdba7c2..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/extract-recall-media-urls.util.ts+++ /dev/null@@ -1,30 +0,0 @@-import { asRecord } from 'src/logic-functions/utils/as-record.util';-import { getRecordAtPath } from 'src/logic-functions/utils/get-record-at-path.util';-import { getString } from 'src/logic-functions/utils/get-string.util';--export type RecallMediaUrls = {- videoUrl: string | undefined;- audioUrl: string | undefined;-};--// Pre-signed URLs expire within hours; always re-extract from a fresh GET /recording.-export const extractRecallMediaUrls = (- recording: Record<string, unknown>,-): RecallMediaUrls => {- const mediaShortcuts = asRecord(recording.media_shortcuts);-- return {- videoUrl: extractArtifactDownloadUrl(mediaShortcuts, 'video_mixed'),- audioUrl: extractArtifactDownloadUrl(mediaShortcuts, 'audio_mixed'),- };-};--// v1.11 exposes download_url flat on the artifact; older artifacts nest it under data.-const extractArtifactDownloadUrl = (- mediaShortcuts: Record<string, unknown> | undefined,- artifactKey: string,-): string | undefined =>- getString(getRecordAtPath(mediaShortcuts, [artifactKey, 'download_url'])) ??- getString(- getRecordAtPath(mediaShortcuts, [artifactKey, 'data', 'download_url']),- );diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.tsindex f244480da0a..c98f30f7fff 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.ts@@ -2,6 +2,7 @@ import { isUndefined } from '@sniptt/guards';import { RECALL_API_MAX_IN_PROCESS_RETRY_WAIT_MS } from 'src/logic-functions/constants/recall-api-max-in-process-retry-wait-ms';import { RECALL_API_MAX_ATTEMPTS } from 'src/logic-functions/constants/recall-api-max-attempts';+import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';import { type RecallApiConfig } from 'src/logic-functions/recall-api/get-recall-api-config.util';import { parseRecallRetryAfterMs } from 'src/logic-functions/recall-api/parse-recall-retry-after.util';import {@@ -105,7 +106,7 @@ const performRecallBotApiRequestAttempt = async <TData>({};}- if (allowNotFound && response.status === 404) {+ if (allowNotFound && response.status === RECALL_API_NOT_FOUND_STATUS) {return {isRetryable: false,result: {diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.tsindex c5ecf3ce9b1..7bb94858991 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.ts@@ -1,35 +1,36 @@+import { isUndefined } from '@sniptt/guards';import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction } from 'twenty-sdk/define';import { STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { STALE_BOT_STATE_CRON_PATTERN } from 'src/logic-functions/constants/stale-bot-state-cron-pattern';import { convergeDivergedCallRecordings } from 'src/logic-functions/flows/converge-diverged-call-recordings.util';-import { type ConvergeDivergedCallRecordingsResult } from 'src/logic-functions/flows/converge-diverged-call-recordings-result.type';-import {- buildStepFailure,- type StepFailure,-} from 'src/logic-functions/utils/build-step-failure.util';+import { reconcileCallRecording } from 'src/logic-functions/flows/reconcile-call-recording.util';+import { asRecord } from 'src/logic-functions/utils/as-record.util';+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';+import { getString } from 'src/logic-functions/utils/get-string.util';-const reconcileStaleBotStateHandler = async (): Promise<object> => {- const now = new Date();+export const reconcileStaleBotStateHandler = async (+ payload: unknown,+): Promise<object> => {+ const body = asRecord(payload);+ const callRecordingId = getString(body?.callRecordingId);const client = new CoreApiClient();- const statusConvergenceResult = await convergeDivergedCallRecordingsSafely(- client,- now,- );-- return { statusConvergenceResult };-};--const convergeDivergedCallRecordingsSafely = async (- client: CoreApiClient,- now: Date,-): Promise<ConvergeDivergedCallRecordingsResult | StepFailure> => {try {- return await convergeDivergedCallRecordings({ client, now });+ if (!isUndefined(callRecordingId)) {+ await reconcileCallRecording({ client, callRecordingId });+ return { callRecordingId };+ }++ return {+ statusConvergenceResult: await convergeDivergedCallRecordings({+ client,+ now: new Date(),+ after: getString(body?.after),+ }),+ };} catch (error) {- return buildStepFailure('call recording status convergence', error);+ throw buildRetryableStepFailure('call recording recovery', error);}};@@ -37,10 +38,7 @@ export default defineLogicFunction({universalIdentifier: STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'reconcile-stale-bot-state',description:- 'Converges stale Call Recording status and artifacts with Recall when webhook delivery is missed.',+ 'Enqueues missing artifact imports and reconciles recording lifecycle state when Recall webhooks are missed.',timeoutSeconds: 250,handler: reconcileStaleBotStateHandler,- cronTriggerSettings: {- pattern: STALE_BOT_STATE_CRON_PATTERN,- },});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-for-artifacts-import.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-for-artifacts-import.type.tsnew file mode 100644index 00000000000..b6773094651--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-for-artifacts-import.type.ts@@ -0,0 +1,14 @@+import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';++export type CallRecordingForArtifactsImport = {+ id: string;+ status: string | undefined;+ startedAt: string | undefined;+ endedAt: string | undefined;+ externalRecordingId: string | undefined;+ callRecorderFailureReason: string | undefined;+ transcript: unknown;+ audio: FilesFieldValue | undefined;+ video: FilesFieldValue | undefined;+ externalBotId: string | undefined;+};