The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Stop dropping the call recording transcript during media upload (#25274)
nitin4e134a272477
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 58039caa94e..c7075d85c11 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@@ -663,12 +663,7 @@ describe('call recorder app lifecycle (integration)', () => {'recall-recording-1',);expect(processedCallRecording.endedAt).toBeTruthy();- // recording.done hands media and transcript work to the enqueued- // artifact import job.- expect(recall.artifactImportRequests).toHaveLength(1);- expect(recall.artifactImportRequests[0]).toMatchObject({- callRecordingId,- });+ expect(recall.artifactImportRequests).toHaveLength(2);});it('queues another artifact import when the transcript finishes later', async () => {@@ -687,8 +682,8 @@ describe('call recorder app lifecycle (integration)', () => {buildTranscriptDoneWebhook({ botId, metadata }),);- expect(recall.artifactImportRequests).toHaveLength(2);- expect(recall.artifactImportRequests[1]).toMatchObject({+ expect(recall.artifactImportRequests).toHaveLength(3);+ expect(recall.artifactImportRequests[2]).toMatchObject({callRecordingId,});});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 68c75cba453..05447fa0ccd 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@@ -61,6 +61,9 @@ export const CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER =export const CALL_RECORDING_SUMMARIZER_AGENT_UNIVERSAL_IDENTIFIER ='388543f3-ec85-4905-ad7d-99801337ed5c';+export const CALL_RECORDING_TRANSCRIPT_IMPORT_CLAIMED_AT_FIELD_UNIVERSAL_IDENTIFIER =+ '804ca433-2ca9-4ead-b1b5-ed2d5d4a4804';+export const CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER ='bb9523d3-457e-4f4b-8c79-27a77afb87da';diff --git a/packages/twenty-apps/public/call-recorder/src/fields/call-recording-transcript-import-claimed-at-on-call-recording.field.ts b/packages/twenty-apps/public/call-recorder/src/fields/call-recording-transcript-import-claimed-at-on-call-recording.field.tsnew file mode 100644index 00000000000..c4b7df69c74--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/fields/call-recording-transcript-import-claimed-at-on-call-recording.field.ts@@ -0,0 +1,22 @@+import {+ defineField,+ FieldType,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,+} from 'twenty-sdk/define';++import { CALL_RECORDING_TRANSCRIPT_IMPORT_CLAIMED_AT_FIELD_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++export default defineField({+ universalIdentifier:+ CALL_RECORDING_TRANSCRIPT_IMPORT_CLAIMED_AT_FIELD_UNIVERSAL_IDENTIFIER,+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.callRecording.universalIdentifier,+ type: FieldType.DATE_TIME,+ name: 'transcriptImportClaimedAt',+ label: 'Transcript Import Claimed At',+ description:+ 'Lease held by the worker importing this recording’s transcript; prevents concurrent webhook retries from requesting the transcript twice.',+ icon: 'IconLock',+ isNullable: true,+ isUIEditable: false,+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/import-call-recording-artifacts.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/import-call-recording-artifacts.test.tsdeleted file mode 100644index c5c2a698c00..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/import-call-recording-artifacts.test.ts+++ /dev/null@@ -1,113 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import importCallRecordingArtifactsLogicFunction, {- importCallRecordingArtifactsHandler,-} from 'src/logic-functions/import-call-recording-artifacts';--const importCallRecordingArtifactsMock = vi.hoisted(() => vi.fn());-const coreApiClientMock = vi.hoisted(() => vi.fn());--vi.mock(- 'src/logic-functions/flows/import-call-recording-artifacts.util',- () => ({- importCallRecordingArtifacts: importCallRecordingArtifactsMock,- }),-);--vi.mock('twenty-client-sdk/core', () => ({- CoreApiClient: coreApiClientMock,-}));--describe('import-call-recording-artifacts', () => {- beforeEach(() => {- importCallRecordingArtifactsMock.mockReset();- importCallRecordingArtifactsMock.mockResolvedValue({- status: 'imported',- callRecordingId: 'call-recording-1',- outcome: 'call-recording-artifacts-imported',- });- coreApiClientMock.mockReset();- });-- it('is configured as an enqueue-only import worker', () => {- expect(importCallRecordingArtifactsLogicFunction.success).toBe(true);- expect(importCallRecordingArtifactsLogicFunction.config).toEqual(- expect.objectContaining({- name: 'import-call-recording-artifacts',- timeoutSeconds: 250,- }),- );- expect(importCallRecordingArtifactsLogicFunction.config).not.toHaveProperty(- 'httpRouteTriggerSettings',- );- });-- it('forwards a valid import payload to the worker flow', async () => {- const payload = {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- };-- const result = await importCallRecordingArtifactsHandler(payload);-- expect(coreApiClientMock).toHaveBeenCalledTimes(1);- expect(importCallRecordingArtifactsMock).toHaveBeenCalledWith({- client: coreApiClientMock.mock.instances[0],- request: payload,- });- expect(result).toEqual({- status: 'imported',- callRecordingId: 'call-recording-1',- outcome: 'call-recording-artifacts-imported',- });- });-- it('ignores payload-supplied provider ids instead of forwarding them', async () => {- const result = await importCallRecordingArtifactsHandler({- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- event: 'transcript.done',- externalBotId: 'forged-bot-id',- externalRecordingId: 'forged-recording-id',- transcriptId: 'forged-transcript-id',- });-- expect(importCallRecordingArtifactsMock).toHaveBeenCalledWith({- client: coreApiClientMock.mock.instances[0],- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },- });- expect(result).toEqual(expect.objectContaining({ status: 'imported' }));- });-- it('skips invalid import payloads without touching the worker flow', async () => {- const result = await importCallRecordingArtifactsHandler({- requestedAt: '2026-01-01T14:06:00.000Z',- });-- expect(importCallRecordingArtifactsMock).not.toHaveBeenCalled();- expect(result).toEqual({- status: 'skipped',- callRecordingId: 'unknown',- reason: 'invalid call recording artifacts import request',- });- });-- it('rethrows an import failure as retryable so the queue redelivers it', async () => {- importCallRecordingArtifactsMock.mockRejectedValue(- new Error('Service unavailable'),- );-- await expect(- importCallRecordingArtifactsHandler({- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- }),- ).rejects.toMatchObject({- name: 'RetryableLogicFunctionError',- message: expect.stringContaining('Service unavailable'),- });- });-});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 246302aebf0..5281933be30 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@@ -15,13 +15,14 @@ describe('claimCallRecordingArtifactsImport', () => {mutationMock.mockReset();});- it('claims when no fresh lease is held and stamps the lease timestamp', async () => {+ 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'),});@@ -43,11 +44,41 @@ describe('claimCallRecordingArtifactsImport', () => {});});+ 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' }],+ });++ const claimed = await claimCallRecordingArtifactsImport(client, {+ callRecordingId: 'call-recording-1',+ scope: 'transcript',+ now: new Date('2026-01-01T14:06:00.000Z'),+ });++ 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('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'),});@@ -67,6 +98,7 @@ describe('claimCallRecordingArtifactsImport', () => {const claimed = await claimCallRecordingArtifactsImport(client, {callRecordingId: 'call-recording-1',+ scope: 'media',now: new Date('2026-01-01T14:06:00.000Z'),});@@ -88,26 +120,28 @@ describe('claimCallRecordingArtifactsImport', () => {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 by clearing the timestamp', async () => {+ it('releases the lease idempotently when the call recording no longer exists', async () => {mutationMock.mockResolvedValue({- updateCallRecording: { id: 'call-recording-1' },+ updateCallRecordings: [],});await releaseCallRecordingArtifactsImportClaim(client, {callRecordingId: 'call-recording-1',+ scope: 'transcript',});expect(mutationMock).toHaveBeenCalledWith({- updateCallRecording: {+ updateCallRecordings: {__args: {- id: 'call-recording-1',- data: { artifactsImportClaimedAt: null },+ filter: { id: { eq: 'call-recording-1' } },+ data: { transcriptImportClaimedAt: null },},id: true,},diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-artifacts-import.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-artifacts-import.test.tsindex 89dbacd1fc6..336971516f6 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-artifacts-import.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-artifacts-import.test.ts@@ -16,9 +16,10 @@ describe('enqueueCallRecordingArtifactsImport', () => {enqueueJobsMock.mockResolvedValue({ enqueued: true, enqueuedJobsCount: 1 });});- it('enqueues one import job with a fresh request timestamp', async () => {+ it('enqueues each artifact scope as a separate job in one request', async () => {await enqueueCallRecordingArtifactsImport({callRecordingId: 'call-recording-1',+ scopes: ['transcript', 'media'],});expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({@@ -28,6 +29,12 @@ describe('enqueueCallRecordingArtifactsImport', () => {{callRecordingId: 'call-recording-1',requestedAt: expect.any(String),+ scope: 'transcript',+ },+ {+ callRecordingId: 'call-recording-1',+ requestedAt: expect.any(String),+ scope: 'media',},],retryLimit: ENQUEUED_JOB_RETRY_LIMIT,@@ -40,6 +47,7 @@ describe('enqueueCallRecordingArtifactsImport', () => {await expect(enqueueCallRecordingArtifactsImport({callRecordingId: 'call-recording-1',+ scopes: ['media'],}),).rejects.toThrow('Network failed');});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 43d0617bf95..61e494ca3ee 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,24 +1,29 @@import { type CoreApiClient } from 'twenty-client-sdk/core';-import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';+import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.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;-// Atomic per-recording lease. The conditional update matches only when no fresh-// lease is held, so exactly one of several concurrent webhook retries claims the-// import and performs the provider-facing work.+const CLAIM_FIELD_BY_SCOPE = {+ transcript: 'transcriptImportClaimedAt',+ media: 'artifactsImportClaimedAt',+} as const;+export const claimCallRecordingArtifactsImport = async (client: CoreApiClient,{callRecordingId,+ scope,now,}: {callRecordingId: string;+ scope: CallRecordingArtifactImportScope;now: Date;},): Promise<boolean> => {+ const claimField = CLAIM_FIELD_BY_SCOPE[scope];const staleBefore = new Date(now.getTime() - ARTIFACTS_IMPORT_CLAIM_TTL_MS,).toISOString();@@ -29,11 +34,11 @@ export const claimCallRecordingArtifactsImport = async (filter: {id: { eq: callRecordingId },or: [- { artifactsImportClaimedAt: { is: 'NULL' } },- { artifactsImportClaimedAt: { lte: staleBefore } },+ { [claimField]: { is: 'NULL' } },+ { [claimField]: { lte: staleBefore } },],},- data: { artifactsImportClaimedAt: now.toISOString() },+ data: { [claimField]: now.toISOString() },},id: true,},@@ -44,10 +49,21 @@ export const claimCallRecordingArtifactsImport = async (export const releaseCallRecordingArtifactsImportClaim = async (client: CoreApiClient,- { callRecordingId }: { callRecordingId: string },+ {+ callRecordingId,+ scope,+ }: {+ callRecordingId: string;+ scope: CallRecordingArtifactImportScope;+ },): Promise<void> => {- await updateCallRecording(client, {- id: callRecordingId,- data: { artifactsImportClaimedAt: null },+ await client.mutation({+ updateCallRecordings: {+ __args: {+ filter: { id: { eq: callRecordingId } },+ data: { [CLAIM_FIELD_BY_SCOPE[scope]]: null },+ },+ id: true,+ },});};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.tsindex 972fb284f35..0b68f223eb8 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts@@ -1,14 +1,23 @@import { IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';+import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';export const enqueueCallRecordingArtifactsImport = async ({callRecordingId,+ scopes,}: {callRecordingId: string;+ scopes: CallRecordingArtifactImportScope[];}): Promise<void> => {+ const requestedAt = new Date().toISOString();+await enqueueLogicFunctionJobs({logicFunctionUniversalIdentifier:IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- payloads: [{ callRecordingId, requestedAt: new Date().toISOString() }],+ payloads: scopes.map((scope) => ({+ callRecordingId,+ requestedAt,+ scope,+ })),});};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.tsnew file mode 100644index 00000000000..57eec97c3d4--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-for-artifacts-import.util.ts@@ -0,0 +1,74 @@+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;+};++export const findCallRecordingForArtifactsImport = async (+ client: CoreApiClient,+ callRecordingId: string,+): Promise<CallRecordingForArtifactsImport | undefined> => {+ const queryResult = await client.query({+ callRecordings: {+ __args: {+ filter: { id: { eq: callRecordingId } },+ 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 },+ },+ },+ },+ });++ 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,+ };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-non-terminal-call-recording-state.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-non-terminal-call-recording-state.util.tsnew file mode 100644index 00000000000..6002833d357--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-non-terminal-call-recording-state.util.ts@@ -0,0 +1,33 @@+import { isNonEmptyArray } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';++type CallRecordingStateUpdate = Pick<+ CallRecordingUpdateFields,+ 'status' | 'callRecorderFailureReason'+>;++export const updateNonTerminalCallRecordingState = async (+ client: CoreApiClient,+ {+ callRecordingId,+ data,+ }: { callRecordingId: string; data: CallRecordingStateUpdate },+): Promise<boolean> => {+ const updateResult = await client.mutation({+ updateCallRecordings: {+ __args: {+ filter: {+ id: { eq: callRecordingId },+ status: { in: NON_TERMINAL_CALL_RECORDING_STATUSES },+ },+ data,+ },+ id: true,+ },+ });++ return isNonEmptyArray(updateResult.updateCallRecordings);+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/should-complete-call-recording-import.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/should-complete-call-recording-import.test.tsindex 208fcd48342..1b7448ff014 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/should-complete-call-recording-import.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/should-complete-call-recording-import.test.ts@@ -7,61 +7,44 @@ const filledTranscript = [{ participant: { id: 1 }, words: [] }];const filledAudio = [{ fileId: 'file-audio-1', label: 'audio.mp3' }];const filledVideo = [{ fileId: 'file-video-1', label: 'video.mp4' }];+const buildCompletableCallRecording = () => ({+ status: CallRecordingStatus.PROCESSING,+ startedAt: '2026-06-10T09:00:00.000Z',+ endedAt: '2026-06-10T10:00:00.000Z',+ transcript: filledTranscript,+ audio: filledAudio,+ video: filledVideo,+});+describe('shouldCompleteCallRecordingImport', () => {- it('requires complete artifacts and billable timestamps before completion', () => {+ it('completes a recording holding every artifact and billable timestamps', () => {expect(- shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {},- }),+ shouldCompleteCallRecordingImport(buildCompletableCallRecording()),).toBe(true);+ });+ it('does not complete without a billable duration', () => {expect(shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {},+ ...buildCompletableCallRecording(),+ startedAt: undefined,}),).toBe(false);expect(shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- },+ ...buildCompletableCallRecording(),+ startedAt: '2026-06-10T10:00:00.000Z',+ endedAt: '2026-06-10T09:00:00.000Z',}),- ).toBe(true);+ ).toBe(false);+ });+ it('does not complete while an artifact is still missing', () => {expect(shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- startedAt: '2026-06-10T10:00:00.000Z',- endedAt: '2026-06-10T09:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {},+ ...buildCompletableCallRecording(),+ video: undefined,}),).toBe(false);});@@ -69,64 +52,18 @@ describe('shouldCompleteCallRecordingImport', () => {it('completes when a missing media file is marked too large', () => {expect(shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- },- updateData: {- callRecorderFailureReason: 'video_file_too_large',- },- }),- ).toBe(true);-- expect(- shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- callRecorderFailureReason: 'video_file_too_large',- },- updateData: {},+ ...buildCompletableCallRecording(),+ video: undefined,+ callRecorderFailureReason: 'video_file_too_large',}),).toBe(true);});- it('does not complete a persisted failed recording', () => {- expect(- shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.FAILED,- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {},- }),- ).toBe(false);- });-- it('does not complete when the incoming update marks the recording as failed', () => {+ it('does not complete a failed recording', () => {expect(shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {- status: CallRecordingStatus.FAILED,- },+ ...buildCompletableCallRecording(),+ status: CallRecordingStatus.FAILED,}),).toBe(false);});@@ -134,31 +71,17 @@ describe('shouldCompleteCallRecordingImport', () => {it('does not complete a recording classified as NOT_RECORDED', () => {expect(shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.NOT_RECORDED,- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {},+ ...buildCompletableCallRecording(),+ status: CallRecordingStatus.NOT_RECORDED,}),).toBe(false);+ });+ it('does not complete a recording that is already completed', () => {expect(shouldCompleteCallRecordingImport({- current: {- status: CallRecordingStatus.PROCESSING,- startedAt: '2026-06-10T09:00:00.000Z',- endedAt: '2026-06-10T10:00:00.000Z',- transcript: filledTranscript,- audio: filledAudio,- video: filledVideo,- },- updateData: {- status: CallRecordingStatus.NOT_RECORDED,- },+ ...buildCompletableCallRecording(),+ status: CallRecordingStatus.COMPLETED,}),).toBe(false);});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/should-complete-call-recording-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/should-complete-call-recording-import.util.tsindex d894dd92ab6..7ddea63e197 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/should-complete-call-recording-import.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/should-complete-call-recording-import.util.ts@@ -3,34 +3,30 @@ import { type FilesFieldValue } from 'src/logic-functions/types/files-field-valuimport { computeCallRecordingCharge } from 'src/logic-functions/domain/compute-call-recording-charge.util';import { isUnavailableCallRecordingStatus } from 'src/logic-functions/domain/is-unavailable-call-recording-status.util';import { isCallRecordingImportComplete } from 'src/logic-functions/domain/is-call-recording-import-complete.util';-import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';export const shouldCompleteCallRecordingImport = ({- current,- updateData,+ status,+ startedAt,+ endedAt,+ transcript,+ audio,+ video,+ callRecorderFailureReason,}: {- current: {- status?: string;- startedAt?: string;- endedAt?: string;- transcript?: unknown;- audio?: FilesFieldValue;- video?: FilesFieldValue;- callRecorderFailureReason?: string | null;- };- updateData: CallRecordingUpdateFields;+ status?: string;+ startedAt?: string;+ endedAt?: string;+ transcript?: unknown;+ audio?: FilesFieldValue;+ video?: FilesFieldValue;+ callRecorderFailureReason?: string | null;}): boolean =>- current.status !== CallRecordingStatus.COMPLETED &&- !isUnavailableCallRecordingStatus(current.status) &&- !isUnavailableCallRecordingStatus(updateData.status) &&- computeCallRecordingCharge({- startedAt: updateData.startedAt ?? current.startedAt,- endedAt: updateData.endedAt ?? current.endedAt,- }) !== undefined &&+ status !== CallRecordingStatus.COMPLETED &&+ !isUnavailableCallRecordingStatus(status) &&+ computeCallRecordingCharge({ startedAt, endedAt }) !== undefined &&isCallRecordingImportComplete({- transcript: updateData.transcript ?? current.transcript,- audio: updateData.audio ?? current.audio,- video: updateData.video ?? current.video,- callRecorderFailureReason:- updateData.callRecorderFailureReason ?? current.callRecorderFailureReason,+ transcript,+ audio,+ video,+ callRecorderFailureReason,});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 ccd9a5bc84a..d85153abb6c 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@@ -11,6 +11,8 @@ 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,@@ -20,9 +22,12 @@ 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-scheduled-recall-bots.util',+ () => ({+ listScheduledRecallBots: listScheduledRecallBotsMock,+ }),+);vi.mock('src/logic-functions/recall-api/list-recall-transcripts.util', () => ({listRecallTranscripts: listRecallTranscriptsMock,@@ -50,6 +55,14 @@ vi.mock(}),);+vi.mock(+ 'src/logic-functions/data/claim-call-recording-artifacts-import.util',+ () => ({+ claimCallRecordingArtifactsImport: claimArtifactsImportMock,+ releaseCallRecordingArtifactsImportClaim: releaseArtifactsImportClaimMock,+ }),+);+const NOW = new Date('2026-06-10T12:00:00.000Z');type CallRecordingNode = Record<string, unknown>;@@ -59,11 +72,21 @@ class FakeCoreApiClient {constructor(private callRecordingNodes: CallRecordingNode[]) {}- async query(_query: any): Promise<any> {+ 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: this.callRecordingNodes.map((node) => ({ node })),+ edges: nodes.map((node) => ({ node: { ...node } })),},};}@@ -72,8 +95,18 @@ class FakeCoreApiClient {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 }] };}@@ -81,9 +114,14 @@ class FakeCoreApiClient {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[]) =>@@ -134,9 +172,16 @@ describe('convergeDivergedCallRecordings', () => {downloadTranscriptMock.mockReset();downloadTranscriptMock.mockResolvedValue({ outcome: 'pending' });importCallRecordingMediaMock.mockReset();- importCallRecordingMediaMock.mockResolvedValue({});+ 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 () => {@@ -288,12 +333,15 @@ describe('convergeDivergedCallRecordings', () => {expect.objectContaining({id: 'call-recording-1',data: expect.objectContaining({- status: 'PROCESSING',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({@@ -383,8 +431,11 @@ describe('convergeDivergedCallRecordings', () => {},});importCallRecordingMediaMock.mockResolvedValue({- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],+ updateData: {+ audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],+ video: [{ fileId: 'file-video-1', label: 'video.mp4' }],+ },+ hasRetryableFailure: false,});const client = buildClient([buildStuckRecordingNode({@@ -448,8 +499,11 @@ describe('convergeDivergedCallRecordings', () => {},});importCallRecordingMediaMock.mockResolvedValue({- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- callRecorderFailureReason: 'video_file_too_large',+ updateData: {+ audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],+ callRecorderFailureReason: 'video_file_too_large',+ },+ hasRetryableFailure: false,});const client = buildClient([buildStuckRecordingNode({@@ -471,9 +525,12 @@ describe('convergeDivergedCallRecordings', () => {id: 'call-recording-1',data: {audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- callRecorderFailureReason: 'video_file_too_large',},},+ {+ id: 'call-recording-1',+ data: { callRecorderFailureReason: 'video_file_too_large' },+ },{id: 'call-recording-1',data: { status: 'COMPLETED' },@@ -557,8 +614,11 @@ describe('convergeDivergedCallRecordings', () => {},});importCallRecordingMediaMock.mockResolvedValue({- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- callRecorderFailureReason: 'video_file_too_large',+ updateData: {+ audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],+ callRecorderFailureReason: 'video_file_too_large',+ },+ hasRetryableFailure: false,});const client = buildClient([buildStuckRecordingNode({@@ -581,6 +641,11 @@ describe('convergeDivergedCallRecordings', () => {data: {status: 'FAILED',callRecorderFailureReason: 'fatal',+ },+ },+ {+ id: 'call-recording-1',+ data: {audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],},},@@ -815,7 +880,7 @@ describe('convergeDivergedCallRecordings', () => {transcript: {recallTranscriptId: 'recall-transcript-1',status: 'PENDING',- requestedAt: NOW.toISOString(),+ requestedAt: expect.any(String),},},},@@ -864,12 +929,15 @@ describe('convergeDivergedCallRecordings', () => {{id: 'call-recording-1',data: {- status: 'PROCESSING',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([]);});@@ -1000,12 +1068,17 @@ describe('convergeDivergedCallRecordings', () => {{id: 'call-recording-1',data: {- status: 'FAILED',transcript: {recallTranscriptId: 'recall-transcript-1',status: 'FAILED',subCode: 'audio_missing',},+ },+ },+ {+ id: 'call-recording-1',+ data: {+ status: 'FAILED',callRecorderFailureReason: 'transcript_failed:audio_missing',},},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.tsindex 7f982ccbc04..9966f860abb 100644--- 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.ts@@ -960,8 +960,9 @@ describe('handleRecallWebhook', () => {expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledWith({+ expect(enqueueArtifactImportMock).toHaveBeenCalledExactlyOnceWith({callRecordingId: 'call-recording-1',+ scopes: ['transcript', 'media'],});expect(client.mutations).toEqual([{@@ -975,31 +976,6 @@ describe('handleRecallWebhook', () => {]);});- it('throws when the artifact import enqueue fails so Svix redelivers', async () => {- enqueueArtifactImportMock.mockRejectedValue(- new Error(- 'failed to enqueue artifact import for call recording call-recording-1',- ),- );- const client = new FakeCoreApiClient([- {- id: 'call-recording-1',- status: 'PROCESSING',- externalBotId: 'recall-bot-1',- transcript: null,- },- ]);-- await expect(- handleRecallWebhook({- client: client as unknown as CoreApiClient,- body: buildRecordingDoneWebhookBody(),- }),- ).rejects.toThrow(- 'failed to enqueue artifact import for call recording call-recording-1',- );- });-it('queues redelivered done events without touching transcript APIs inline', async () => {const client = new FakeCoreApiClient([{@@ -1067,8 +1043,9 @@ describe('handleRecallWebhook', () => {expect(getRecallBotMock).not.toHaveBeenCalled();expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledWith({+ expect(enqueueArtifactImportMock).toHaveBeenCalledExactlyOnceWith({callRecordingId: 'call-recording-1',+ scopes: ['transcript', 'media'],});expect(client.mutations).toEqual([expect.objectContaining({@@ -1199,8 +1176,9 @@ describe('handleRecallWebhook', () => {callRecordingId: 'call-recording-1',});expect(retrieveRecallTranscriptMock).not.toHaveBeenCalled();- expect(enqueueArtifactImportMock).toHaveBeenCalledWith({+ expect(enqueueArtifactImportMock).toHaveBeenCalledExactlyOnceWith({callRecordingId: 'call-recording-1',+ scopes: ['transcript'],});expect(client.mutations).toEqual([]);});@@ -1247,8 +1225,9 @@ describe('handleRecallWebhook', () => {event: 'transcript.failed',callRecordingId: 'call-recording-1',});- expect(enqueueArtifactImportMock).toHaveBeenCalledWith({+ 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.tsindex e54f0f6a50d..26a1f4f98a2 100644--- 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.ts@@ -76,7 +76,7 @@ class FakeCoreApiClient {callRecordings: {edges: this.callRecordings.filter((callRecording) => callRecording.id === id)- .map((node) => ({ node })),+ .map((node) => ({ node: { ...node } })),},};}@@ -88,17 +88,36 @@ class FakeCoreApiClient {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 } };}@@ -124,6 +143,11 @@ const buildProcessingCallRecording = (...overrides,});+const buildRequest = () => ({+ callRecordingId: 'call-recording-1',+ requestedAt: '2026-01-01T14:06:00.000Z',+});+describe('importCallRecordingArtifacts', () => {beforeEach(() => {vi.spyOn(console, 'warn').mockImplementation(() => {});@@ -146,7 +170,10 @@ describe('importCallRecordingArtifacts', () => {downloadTranscriptMock.mockReset();downloadTranscriptMock.mockResolvedValue({ outcome: 'pending' });importCallRecordingMediaMock.mockReset();- importCallRecordingMediaMock.mockResolvedValue({});+ importCallRecordingMediaMock.mockResolvedValue({+ updateData: {},+ hasRetryableFailure: false,+ });chargeCompletedCallRecordingMock.mockReset();chargeCompletedCallRecordingMock.mockResolvedValue('charged');claimArtifactsImportMock.mockReset();@@ -155,26 +182,19 @@ describe('importCallRecordingArtifacts', () => {releaseArtifactsImportClaimMock.mockResolvedValue(undefined);});- it('requests transcript and media artifacts after a recording completion webhook', async () => {+ 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: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'transcript',});expect(createAsyncRecallTranscriptMock).toHaveBeenCalledWith({externalRecordingId: 'recall-recording-1',});- expect(importCallRecordingMediaMock).toHaveBeenCalledWith({- callRecordingId: 'call-recording-1',- externalRecordingId: 'recall-recording-1',- hasAudio: false,- hasVideo: false,- });+ expect(importCallRecordingMediaMock).not.toHaveBeenCalled();expect(client.mutations).toEqual([{id: 'call-recording-1',@@ -190,6 +210,59 @@ describe('importCallRecordingArtifacts', () => {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',});});@@ -214,10 +287,8 @@ describe('importCallRecordingArtifacts', () => {await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'transcript',});expect(getRecallBotMock).toHaveBeenCalledWith({@@ -250,10 +321,8 @@ describe('importCallRecordingArtifacts', () => {const result = await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'transcript',});expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();@@ -262,14 +331,18 @@ describe('importCallRecordingArtifacts', () => {expect(result).toEqual({status: 'skipped',callRecordingId: 'call-recording-1',+ scope: 'transcript',reason: 'no artifact updates',});});- it('completes and charges when artifact reconciliation lands the final media files', async () => {+ it('completes and charges when the media job lands the final media files', async () => {importCallRecordingMediaMock.mockResolvedValue({- audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],- video: [{ fileId: 'file-video-1', label: 'video.mp4' }],+ updateData: {+ audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],+ video: [{ fileId: 'file-video-1', label: 'video.mp4' }],+ },+ hasRetryableFailure: false,});const client = buildClient([buildProcessingCallRecording({@@ -279,10 +352,8 @@ describe('importCallRecordingArtifacts', () => {await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'media',});expect(client.mutations).toEqual([@@ -316,10 +387,8 @@ describe('importCallRecordingArtifacts', () => {await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'media',});expect(client.mutations).toEqual([@@ -361,10 +430,8 @@ describe('importCallRecordingArtifacts', () => {const result = await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'transcript',});expect(downloadTranscriptMock).toHaveBeenCalledWith({@@ -383,10 +450,95 @@ describe('importCallRecordingArtifacts', () => {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({@@ -397,15 +549,14 @@ describe('importCallRecordingArtifacts', () => {const result = await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'transcript',});expect(result).toEqual({status: 'skipped',callRecordingId: 'call-recording-1',+ scope: 'transcript',reason: 'no artifact updates',});expect(client.mutations).toEqual([]);@@ -434,10 +585,8 @@ describe('importCallRecordingArtifacts', () => {const result = await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'transcript',});expect(client.mutations).toEqual([@@ -449,6 +598,11 @@ describe('importCallRecordingArtifacts', () => {status: 'FAILED',subCode: 'transcription_failed',},+ },+ },+ {+ id: 'call-recording-1',+ data: {callRecorderFailureReason: 'transcript_failed:transcription_failed',status: 'FAILED',},@@ -457,26 +611,92 @@ describe('importCallRecordingArtifacts', () => {expect(result).toEqual({status: 'imported',callRecordingId: 'call-recording-1',+ scope: 'transcript',outcome: 'call-recording-artifacts-imported',});});- it('skips provider work when another worker holds the import lease', async () => {- claimArtifactsImportMock.mockResolvedValue(false);+ 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()]);- const result = await importCallRecordingArtifacts({+ await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ 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();@@ -484,24 +704,26 @@ describe('importCallRecordingArtifacts', () => {expect(result).toEqual({status: 'skipped',callRecordingId: 'call-recording-1',+ scope: 'transcript',reason: 'artifact import already in progress',});});- it('releases the import lease after doing provider work', async () => {- const client = buildClient([buildProcessingCallRecording()]);+ it('skips a call recording that no longer exists', async () => {+ const client = buildClient([]);- await importCallRecordingArtifacts({+ const result = await importCallRecordingArtifacts({client: client as unknown as CoreApiClient,- request: {- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- },+ request: buildRequest(),+ scope: 'media',});- expect(releaseArtifactsImportClaimMock).toHaveBeenCalledWith(- expect.anything(),- { callRecordingId: 'call-recording-1' },- );+ 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 ac79c10ad82..f2867fb030e 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@@ -211,14 +211,14 @@ describe('importCallRecordingMedia', () => {});it('streams and uploads every missing artifact', async () => {- const updateFields = await importCallRecordingMedia({+ const { updateData } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: false,});- expect(updateFields).toEqual({+ expect(updateData).toEqual({video: [{ fileId: 'file-video-1', label: 'video.mp4' }],audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],});@@ -281,28 +281,28 @@ describe('importCallRecordingMedia', () => {});it('skips artifacts already on the record', async () => {- const updateFields = await importCallRecordingMedia({+ const { updateData } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: true,});- expect(updateFields).toEqual({+ expect(updateData).toEqual({audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],});expect(getUploadRequestCall('video.mp4')).toBeUndefined();});it('does not fetch the recording when both artifacts are present', async () => {- const updateFields = await importCallRecordingMedia({+ const { updateData } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: true,hasVideo: true,});- expect(updateFields).toEqual({});+ expect(updateData).toEqual({});expect(fetchMock).not.toHaveBeenCalled();expect(mutationMock).not.toHaveBeenCalled();});@@ -329,16 +329,17 @@ describe('importCallRecordingMedia', () => {},});- const updateFields = await importCallRecordingMedia({+ const { updateData, hasRetryableFailure } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: false,});- expect(updateFields).toEqual({+ expect(updateData).toEqual({audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],});+ expect(hasRetryableFailure).toBe(true);expect(cancelMock).toHaveBeenCalledTimes(1);expect(getUploadRequestCall('video.mp4')).toBeUndefined();expect(console.warn).toHaveBeenCalledWith(@@ -346,7 +347,7 @@ describe('importCallRecordingMedia', () => {);});- it('omits an artifact and warns when the download has no content length', async () => {+ it('keeps the artifact it imported and asks for a redelivery when the other download has no content length', async () => {const cancelMock = vi.fn().mockRejectedValue(new Error('cancel exploded'));stubFetch({@@ -358,16 +359,17 @@ describe('importCallRecordingMedia', () => {},});- const updateFields = await importCallRecordingMedia({+ const { updateData, hasRetryableFailure } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: false,});- expect(updateFields).toEqual({+ expect(updateData).toEqual({audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],});+ expect(hasRetryableFailure).toBe(true);expect(getUploadRequestCall('video.mp4')).toBeUndefined();expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('content-length'),@@ -377,20 +379,23 @@ describe('importCallRecordingMedia', () => {);});- it('returns nothing when the recording exposes no media urls', async () => {+ it('returns nothing and asks for no redelivery when the recording exposes no media urls', async () => {buildRecallRecordingResponse = () =>new Response(JSON.stringify({ id: 'recall-recording-1' }), {status: 200,});- const updateFields = await importCallRecordingMedia({+ const mediaImportResult = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: false,});- expect(updateFields).toEqual({});+ expect(mediaImportResult).toEqual({+ updateData: {},+ hasRetryableFailure: false,+ });expect(mutationMock).not.toHaveBeenCalled();});@@ -401,16 +406,19 @@ describe('importCallRecordingMedia', () => {});vi.useFakeTimers();- const updateFieldsPromise = importCallRecordingMedia({+ const mediaImportResultPromise = importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: false,});await vi.runAllTimersAsync();- const updateFields = await updateFieldsPromise;+ const mediaImportResult = await mediaImportResultPromise;- expect(updateFields).toEqual({});+ expect(mediaImportResult).toEqual({+ updateData: {},+ hasRetryableFailure: true,+ });expect(mutationMock).not.toHaveBeenCalled();expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('recording boom'),@@ -430,14 +438,14 @@ describe('importCallRecordingMedia', () => {},});- const updateFields = await importCallRecordingMedia({+ const { updateData } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: false,});- expect(updateFields).toEqual({+ expect(updateData).toEqual({audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],callRecorderFailureReason: 'video_file_too_large',});@@ -463,14 +471,14 @@ describe('importCallRecordingMedia', () => {},});- const updateFields = await importCallRecordingMedia({+ const { updateData } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: false,hasVideo: false,});- expect(updateFields).toEqual({+ expect(updateData).toEqual({callRecorderFailureReason: 'video_file_too_large,audio_file_too_large',});expect(mutationMock).not.toHaveBeenCalled();@@ -485,14 +493,14 @@ describe('importCallRecordingMedia', () => {},});- const updateFields = await importCallRecordingMedia({+ const { updateData } = await importCallRecordingMedia({callRecordingId: 'call-recording-1',externalRecordingId: 'recall-recording-1',hasAudio: true,hasVideo: false,});- expect(updateFields).toEqual({+ expect(updateData).toEqual({video: [{ fileId: 'file-video-1', label: 'video.mp4' }],});});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 1e4c896c7f9..80a66050959 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@@ -5,26 +5,29 @@ import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-rimport { 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 { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.type';import {fetchAllNodes,type ConnectionPage,} from 'src/logic-functions/data/fetch-all-nodes.util';-import { getRecallBot } from 'src/logic-functions/recall-api/get-recall-bot.util';import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.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 { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';import { isCallRecordingStatusDowngrade } from 'src/logic-functions/domain/is-call-recording-status-downgrade.util';-import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.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 { updateCallRecording } from 'src/logic-functions/data/update-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;@@ -135,10 +138,7 @@ export const convergeDivergedCallRecordings = async ({for (const candidate of orderedActionableCandidates) {const listedBot = listedRecallBotsById.get(candidate.externalBotId);- if (- isUndefined(listedBot) &&- remainingPerRecordingFallbackCount === 0- ) {+ 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`,);@@ -155,7 +155,6 @@ export const convergeDivergedCallRecordings = async ({candidate,externalBotId: candidate.externalBotId,listedBot,- now,result,});}@@ -275,14 +274,12 @@ const convergeCallRecording = async ({candidate,externalBotId,listedBot,- now,result,}: {client: CoreApiClient;candidate: DivergedCallRecordingCandidate;externalBotId: string;listedBot: RecallBotSnapshot | undefined;- now: Date;result: ConvergeDivergedCallRecordingsResult;}): Promise<void> => {const botResult = isUndefined(listedBot)@@ -308,19 +305,47 @@ const convergeCallRecording = async ({return;}- const syncResult = await syncCallRecording({- client,- callRecording: candidate,- bot: botResult.bot,- treatRecordingAsDone: false,- requestedAt: now.toISOString(),+ 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,+ );- if (syncResult.updated) {+ if (hasUpdatedCallRecording || hasCompletedImport) {result.updatedCallRecordingIds.push(candidate.id);}- if (syncResult.requestedTranscript) {+ if (hasRequestedTranscript) {result.requestedTranscriptCallRecordingIds.push(candidate.id);}};@@ -366,8 +391,7 @@ const listRecallBotsByIdForConvergence = async (const listResult = await listScheduledRecallBots({joinAtAfter: new Date(- now.getTime() -- CONVERGENCE_BOT_LIST_LOOKBACK_DAYS * 24 * 60 * 60 * 1000,+ now.getTime() - CONVERGENCE_BOT_LIST_LOOKBACK_DAYS * 24 * 60 * 60 * 1000,).toISOString(),joinAtBefore: new Date(now.getTime() + CONVERGENCE_BOT_LIST_LOOKAHEAD_MILLISECONDS,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-call-recording-artifacts-import-job.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-call-recording-artifacts-import-job.util.tsnew file mode 100644index 00000000000..438168c38e4--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-call-recording-artifacts-import-job.util.ts@@ -0,0 +1,52 @@+import { isUndefined } from '@sniptt/guards';+import { CoreApiClient } from 'twenty-client-sdk/core';++import {+ importCallRecordingArtifacts,+ type ImportCallRecordingArtifactsResult,+} from 'src/logic-functions/flows/import-call-recording-artifacts.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';++type HandleCallRecordingArtifactsImportJobResult =+ | ImportCallRecordingArtifactsResult+ | {+ status: 'skipped';+ callRecordingId: string;+ reason: string;+ };++export const handleCallRecordingArtifactsImportJob = async (+ payload: unknown,+): Promise<HandleCallRecordingArtifactsImportJobResult> => {+ const body = asRecord(payload);+ const callRecordingId = getString(body?.callRecordingId);+ const requestedAt = getString(body?.requestedAt);+ const scope = getString(body?.scope);++ if (+ isUndefined(callRecordingId) ||+ isUndefined(requestedAt) ||+ (scope !== 'transcript' && scope !== 'media')+ ) {+ return {+ status: 'skipped',+ callRecordingId: callRecordingId ?? 'unknown',+ reason: 'invalid call recording artifacts import request',+ };+ }++ try {+ return await importCallRecordingArtifacts({+ client: new CoreApiClient(),+ request: { callRecordingId, requestedAt },+ scope,+ });+ } catch (error) {+ throw buildRetryableStepFailure(+ `${scope} artifact import for call recording ${callRecordingId}`,+ error,+ );+ }+};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 8417f0c5036..d4422338c56 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@@ -140,6 +140,7 @@ const handleRecallStatusEvent = async ({) {await enqueueCallRecordingArtifactsImport({callRecordingId: callRecording.id,+ scopes: ['transcript', 'media'],});}@@ -177,6 +178,7 @@ const queueCallRecordingArtifactsImport = async ({await enqueueCallRecordingArtifactsImport({callRecordingId: callRecording.id,+ scopes: ['transcript'],});return {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 b4dd18fa766..8f85c7c9173 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,46 +1,29 @@-import { isNull, isUndefined } from '@sniptt/guards';+import { isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';import {- claimCallRecordingArtifactsImport,- releaseCallRecordingArtifactsImportClaim,-} from 'src/logic-functions/data/claim-call-recording-artifacts-import.util';+ 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 {- syncCallRecording,- type SyncableCallRecording,-} from 'src/logic-functions/flows/sync-call-recording.util';-import { type FilesFieldValue } from 'src/logic-functions/types/files-field-value.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 } from 'src/logic-functions/flows/sync-call-recording.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 { getString } from 'src/logic-functions/utils/get-string.util';--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;-};export type ImportCallRecordingArtifactsResult =| {status: 'imported';callRecordingId: string;+ scope: CallRecordingArtifactImportScope;outcome: 'call-recording-artifacts-imported';}| {status: 'skipped';callRecordingId: string;+ scope: CallRecordingArtifactImportScope;reason: string;};@@ -49,68 +32,83 @@ export type ImportCallRecordingArtifactsResult =export const importCallRecordingArtifacts = async ({client,request,+ scope,}: {client: CoreApiClient;request: CallRecordingArtifactsImportRequest;+ scope: CallRecordingArtifactImportScope;}): Promise<ImportCallRecordingArtifactsResult> => {- const callRecording = await findCallRecordingForArtifactsImport(+ const initialCallRecording = await findCallRecordingForArtifactsImport(client,request.callRecordingId,);- if (isUndefined(callRecording)) {+ if (isUndefined(initialCallRecording)) {return {status: 'skipped',callRecordingId: request.callRecordingId,+ scope,reason: 'no matching call recording',};}- // Svix redelivers a webhook to several workers at once; the lease ensures only- // one performs the provider transcript request and media upload. The lease clock- // is wall-clock, not request.requestedAt, so a retry of the same delivery still- // measures real elapsed time and can reclaim a lease left behind by a crash.- const claimedImport = await claimCallRecordingArtifactsImport(client, {- callRecordingId: callRecording.id,- now: new Date(),- });+ const artifactImportExecution = await runCallRecordingArtifactImportWithClaim(+ {+ client,+ callRecordingId: initialCallRecording.id,+ scope,+ now: new Date(),+ runImport: async (callRecording) => {+ const recallBot =+ await fetchRecallBotWhenRecordingIdMissing(callRecording);+ const callRecordingSyncResult = await syncCallRecording({+ client,+ callRecording,+ bot: recallBot,+ treatRecordingAsDone: true,+ requestedAt: request.requestedAt,+ artifactScope: scope,+ });++ if (callRecordingSyncResult.hasRetryableArtifactFailure) {+ throw new Error(+ `Recall ${scope} artifacts for call recording ${callRecording.id} could not be imported`,+ );+ }++ const hasCompletedImport = await settleCallRecordingImport(client, {+ callRecordingId: callRecording.id,+ });++ if (!callRecordingSyncResult.updated && !hasCompletedImport) {+ return {+ status: 'skipped',+ callRecordingId: callRecording.id,+ scope,+ reason: 'no artifact updates',+ } satisfies ImportCallRecordingArtifactsResult;+ }++ return {+ status: 'imported',+ callRecordingId: callRecording.id,+ scope,+ outcome: 'call-recording-artifacts-imported',+ } satisfies ImportCallRecordingArtifactsResult;+ },+ },+ );- if (!claimedImport) {+ if (artifactImportExecution.status === 'skipped') {return {status: 'skipped',- callRecordingId: callRecording.id,- reason: 'artifact import already in progress',+ callRecordingId: initialCallRecording.id,+ scope,+ reason: artifactImportExecution.reason,};}- try {- const bot = await fetchRecallBotWhenRecordingIdMissing(callRecording);- const syncResult = await syncCallRecording({- client,- callRecording,- bot,- treatRecordingAsDone: true,- requestedAt: request.requestedAt,- });-- if (!syncResult.updated) {- return {- status: 'skipped',- callRecordingId: callRecording.id,- reason: 'no artifact updates',- };- }-- return {- status: 'imported',- callRecordingId: callRecording.id,- outcome: 'call-recording-artifacts-imported',- };- } finally {- await releaseCallRecordingArtifactsImportClaim(client, {- callRecordingId: callRecording.id,- });- }+ return artifactImportExecution.result;};const fetchRecallBotWhenRecordingIdMissing = async (@@ -138,54 +136,3 @@ const fetchRecallBotWhenRecordingIdMissing = async (return botResult.bot;};--const findCallRecordingForArtifactsImport = async (- client: CoreApiClient,- callRecordingId: string,-): Promise<CallRecordingForArtifactsImport | undefined> => {- const queryResult = await client.query({- callRecordings: {- __args: {- filter: { id: { eq: callRecordingId } },- 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 },- },- },- },- });-- 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,- };-};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 25a6fe4d105..2cde196f1b5 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@@ -1,4 +1,4 @@-import { isNull, isUndefined } from '@sniptt/guards';+import { isNonEmptyArray, isNull, isUndefined } from '@sniptt/guards';import { MetadataApiClient } from 'twenty-client-sdk/metadata';import {@@ -22,6 +22,11 @@ type CallRecordingMediaUpdateFields = Pick<'audio' | 'video' | 'callRecorderFailureReason'>;+type ImportCallRecordingMediaResult = {+ updateData: CallRecordingMediaUpdateFields;+ hasRetryableFailure: boolean;+};+type ImportMediaArtifactResult =| { outcome: 'imported'; files: CallRecordingMediaFile[] }| { outcome: 'too-large' }@@ -67,9 +72,9 @@ export const importCallRecordingMedia = async ({externalRecordingId: string;hasAudio: boolean;hasVideo: boolean;-}): Promise<CallRecordingMediaUpdateFields> => {+}): Promise<ImportCallRecordingMediaResult> => {if (hasAudio && hasVideo) {- return {};+ return { updateData: {}, hasRetryableFailure: false };}const recordingResult = await getRecallRecording({ externalRecordingId });@@ -79,13 +84,14 @@ export const importCallRecordingMedia = async ({`[call-recorder] failed to fetch Recall recording ${externalRecordingId} while importing media for call recording ${callRecordingId}: ${recordingResult.errorMessage}`,);- return {};+ return { updateData: {}, hasRetryableFailure: true };}const mediaUrls = extractRecallMediaUrls(recordingResult.recording);const metadataClient = new MetadataApiClient();const updateFields: CallRecordingMediaUpdateFields = {};const tooLargeFailureReasons: string[] = [];+ const failedMediaArtifactFields: string[] = [];const artifactStateByField = {video: { alreadyImported: hasVideo, url: mediaUrls.videoUrl },audio: { alreadyImported: hasAudio, url: mediaUrls.audioUrl },@@ -115,13 +121,20 @@ export const importCallRecordingMedia = async ({if (importResult.outcome === 'too-large') {tooLargeFailureReasons.push(descriptor.tooLargeFailureReason);}++ if (importResult.outcome === 'failed') {+ failedMediaArtifactFields.push(descriptor.field);+ }}if (tooLargeFailureReasons.length > 0) {updateFields.callRecorderFailureReason = tooLargeFailureReasons.join(',');}- return updateFields;+ return {+ updateData: updateFields,+ hasRetryableFailure: isNonEmptyArray(failedMediaArtifactFields),+ };};const importMediaArtifact = async ({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 7d8cfee05ff..3219afad10c 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@@ -8,4 +8,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 3dbdc0f4565..b841d31cee5 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@@ -8,6 +8,7 @@ import { isCallRecordingStatusDowngrade } from 'src/logic-functions/domain/is-caimport { parseTranscriptMarker } from 'src/logic-functions/domain/parse-transcript-marker.util';import { createAsyncRecallTranscript } from 'src/logic-functions/recall-api/create-async-recall-transcript.util';import { listRecallTranscripts } from 'src/logic-functions/recall-api/list-recall-transcripts.util';+import { isRetryableRecallApiStatus } from 'src/logic-functions/recall-api/recall-api-retry-policy.util';import { type RecallTranscriptSummary } from 'src/logic-functions/recall-api/recall-transcript-summary.type';import { downloadTranscript } from 'src/logic-functions/flows/download-transcript.util';import { type ImportCallRecordingTranscriptResult } from 'src/logic-functions/flows/import-call-recording-transcript-result.type';@@ -49,7 +50,11 @@ export const importCallRecordingTranscript = async ({`[call-recorder] failed to list Recall transcripts for recording ${externalRecordingId}: ${listResult.errorMessage}`,);- return buildEmptyTranscriptArtifactResult();+ return buildEmptyTranscriptArtifactResult({+ hasRetryableFailure:+ isNull(listResult.status) ||+ isRetryableRecallApiStatus(listResult.status),+ });}const transcriptArtifact = selectRecallTranscriptArtifact(@@ -75,7 +80,11 @@ export const importCallRecordingTranscript = async ({`[call-recorder] failed to request transcript for Recall recording ${externalRecordingId}: ${createResult.errorMessage}`,);- return buildEmptyTranscriptArtifactResult();+ return buildEmptyTranscriptArtifactResult({+ hasRetryableFailure:+ !isNull(createResult.status) &&+ isRetryableRecallApiStatus(createResult.status),+ });}return {@@ -86,6 +95,7 @@ export const importCallRecordingTranscript = async ({}),},requestedTranscript: true,+ hasRetryableFailure: false,};}@@ -101,6 +111,7 @@ export const importCallRecordingTranscript = async ({subCode: transcriptArtifact.statusSubCode ?? null,}),requestedTranscript: false,+ hasRetryableFailure: false,};}@@ -125,6 +136,7 @@ export const importCallRecordingTranscript = async ({transcript: downloadResult.content as Record<string, unknown>,},requestedTranscript: false,+ hasRetryableFailure: false,};}@@ -136,6 +148,7 @@ export const importCallRecordingTranscript = async ({subCode: downloadResult.subCode,}),requestedTranscript: false,+ hasRetryableFailure: false,};}@@ -143,16 +156,22 @@ export const importCallRecordingTranscript = async ({console.warn(`[call-recorder] could not fill transcript for call recording ${callRecordingId}: ${downloadResult.errorMessage}`,);++ return buildEmptyTranscriptArtifactResult({ hasRetryableFailure: true });}return buildEmptyTranscriptArtifactResult();};-const buildEmptyTranscriptArtifactResult =- (): ImportCallRecordingTranscriptResult => ({- updateData: {},- requestedTranscript: false,- });+const buildEmptyTranscriptArtifactResult = ({+ hasRetryableFailure = false,+}: {+ hasRetryableFailure?: boolean;+} = {}): ImportCallRecordingTranscriptResult => ({+ updateData: {},+ requestedTranscript: false,+ hasRetryableFailure,+});const selectRecallTranscriptArtifact = (transcripts: RecallTranscriptSummary[],diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/persist-call-recording-progress.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/persist-call-recording-progress.util.tsdeleted file mode 100644index 74d53013987..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/persist-call-recording-progress.util.ts+++ /dev/null@@ -1,41 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { completeAndChargeCallRecording } from 'src/logic-functions/flows/complete-and-charge-call-recording.util';-import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';-import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';--export const persistCallRecordingProgress = async (- client: CoreApiClient,- {- id,- current,- updateData,- completesImport,- }: {- id: string;- current: { startedAt?: string; endedAt?: string };- updateData: CallRecordingUpdateFields;- completesImport: boolean;- },-): Promise<void> => {- if (!completesImport) {- await updateCallRecording(client, { id, data: updateData });-- return;- }-- // Strip status so COMPLETED is written only by the atomic claim — its single winner bills once.- const nonStatusUpdate: CallRecordingUpdateFields = { ...updateData };-- delete nonStatusUpdate.status;-- if (Object.keys(nonStatusUpdate).length > 0) {- await updateCallRecording(client, { id, data: nonStatusUpdate });- }-- await completeAndChargeCallRecording(client, {- id,- startedAt: updateData.startedAt ?? current.startedAt,- endedAt: updateData.endedAt ?? current.endedAt,- });-};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.tsnew file mode 100644index 00000000000..ee586ea6c82--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util.ts@@ -0,0 +1,80 @@+import { isUndefined } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';++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';++type CallRecordingArtifactImportExecutionResult<TResult> =+ | {+ status: 'executed';+ result: TResult;+ }+ | {+ status: 'skipped';+ reason:+ | 'artifact import already in progress'+ | 'no matching call recording';+ };++export const runCallRecordingArtifactImportWithClaim = async <TResult>({+ client,+ callRecordingId,+ scope,+ now,+ runImport,+}: {+ client: CoreApiClient;+ callRecordingId: string;+ scope: CallRecordingArtifactImportScope;+ now: Date;+ runImport: (+ callRecording: CallRecordingForArtifactsImport,+ ) => Promise<TResult>;+}): Promise<CallRecordingArtifactImportExecutionResult<TResult>> => {+ const hasClaimedArtifactImport = await claimCallRecordingArtifactsImport(+ client,+ {+ callRecordingId,+ scope,+ now,+ },+ );++ if (!hasClaimedArtifactImport) {+ return {+ status: 'skipped',+ reason: 'artifact import already in progress',+ };+ }++ 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),+ };+ } finally {+ await releaseCallRecordingArtifactsImportClaim(client, {+ callRecordingId,+ scope,+ });+ }+};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.tsnew file mode 100644index 00000000000..9c8dbab5d2d--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/settle-call-recording-import.util.ts@@ -0,0 +1,29 @@+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 { 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';++export const settleCallRecordingImport = async (+ client: CoreApiClient,+ { callRecordingId }: { callRecordingId: string },+): Promise<boolean> => {+ const callRecording = await findCallRecordingForArtifactsImport(+ client,+ callRecordingId,+ );++ if (+ isUndefined(callRecording) ||+ !shouldCompleteCallRecordingImport(callRecording)+ ) {+ return false;+ }++ return completeAndChargeCallRecording(client, {+ id: callRecording.id,+ startedAt: callRecording.startedAt,+ endedAt: callRecording.endedAt,+ });+};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.tsindex bf3d978a28a..baf5ce24eba 100644--- 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.ts@@ -4,16 +4,17 @@ 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 { shouldCompleteCallRecordingImport } from 'src/logic-functions/domain/should-complete-call-recording-import.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 { persistCallRecordingProgress } from 'src/logic-functions/flows/persist-call-recording-progress.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';@@ -32,6 +33,7 @@ export type SyncableCallRecording = {export type SyncCallRecordingResult = {updated: boolean;requestedTranscript: boolean;+ hasRetryableArtifactFailure: boolean;};// The single-record sync shared by webhook-driven imports and the scheduled@@ -43,6 +45,7 @@ export const syncCallRecording = async ({bot,treatRecordingAsDone,requestedAt,+ artifactScope,}: {client: CoreApiClient;callRecording: SyncableCallRecording;@@ -51,6 +54,7 @@ export const syncCallRecording = async ({// 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@@ -60,73 +64,101 @@ export const syncCallRecording = async ({const isRecordingDone =treatRecordingAsDone || syncState?.isRecallRecordingDone === true;- let updateData: CallRecordingUpdateFields = isUndefined(syncState)+ const syncStateUpdate: CallRecordingUpdateFields = isUndefined(syncState)? {}: buildSyncStateFieldUpdates({ callRecording, syncState });- if (+ const missingArtifactsFailureUpdate =syncState?.isRecallRecordingDone === true &&isUndefined(externalRecordingId) &&- !hasRecordingArtifactPath({ callRecording, updateData })- ) {- updateData = {- ...updateData,- ...buildMissingArtifactsFailureUpdate({+ !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: updateData.status,- recallFailureReason: syncState.failureReason,- }),- };- }-- let requestedTranscript = false;-- if (isRecordingDone && !isUndefined(externalRecordingId)) {- const transcriptImportResult = await importCallRecordingTranscript({- callRecordingId: callRecording.id,- currentStatus: callRecording.status,- externalRecordingId,- requestedAt,- transcript: callRecording.transcript,- });+ pendingStatus: syncStateUpdate.status,+ });++ const updateData: CallRecordingUpdateFields = {+ ...syncStateUpdate,+ ...missingArtifactsFailureUpdate,+ ...(transcriptImportResult?.updateData ?? {}),+ ...mediaImportUpdate,+ };- requestedTranscript = transcriptImportResult.requestedTranscript;- updateData = { ...updateData, ...transcriptImportResult.updateData };+ const { status, callRecorderFailureReason, ...callRecordingProgressUpdate } =+ updateData;+ const callRecordingStateUpdate: Pick<+ CallRecordingUpdateFields,+ 'status' | 'callRecorderFailureReason'+ > = {+ ...(isUndefined(status) ? {} : { status }),+ ...(isUndefined(callRecorderFailureReason)+ ? {}+ : { callRecorderFailureReason }),+ };+ const hasCallRecordingProgressUpdate =+ Object.keys(callRecordingProgressUpdate).length > 0;- const mediaImportUpdate = await importCallRecordingMedia({- callRecordingId: callRecording.id,- externalRecordingId,- hasAudio: isNonEmptyArray(callRecording.audio),- hasVideo: isNonEmptyArray(callRecording.video),+ if (hasCallRecordingProgressUpdate) {+ await updateCallRecording(client, {+ id: callRecording.id,+ data: callRecordingProgressUpdate,});-- updateData = {- ...updateData,- ...resolveMediaImportUpdate({- mediaImportUpdate,- currentStatus: callRecording.status,- pendingStatus: updateData.status,- }),- };- }-- const completesImport = shouldCompleteCallRecordingImport({- current: callRecording,- updateData,- });-- if (Object.keys(updateData).length === 0 && !completesImport) {- return { updated: false, requestedTranscript };}- await persistCallRecordingProgress(client, {- id: callRecording.id,- current: callRecording,- updateData,- completesImport,- });+ const hasUpdatedCallRecordingState =+ Object.keys(callRecordingStateUpdate).length > 0+ ? await updateNonTerminalCallRecordingState(client, {+ callRecordingId: callRecording.id,+ data: callRecordingStateUpdate,+ })+ : false;- return { updated: true, requestedTranscript };+ return {+ updated: hasCallRecordingProgressUpdate || hasUpdatedCallRecordingState,+ requestedTranscript: transcriptImportResult?.requestedTranscript ?? false,+ hasRetryableArtifactFailure:+ transcriptImportResult?.hasRetryableFailure ??+ mediaImportResult?.hasRetryableFailure ??+ false,+ };};const buildSyncStateFieldUpdates = ({diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.tsindex 55be3fc132a..a3ae3959f03 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts@@ -1,50 +1,14 @@-import { isUndefined } from '@sniptt/guards';-import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction } from 'twenty-sdk/define';import { IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import {- importCallRecordingArtifacts,- type ImportCallRecordingArtifactsResult,-} from 'src/logic-functions/flows/import-call-recording-artifacts.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';--export const importCallRecordingArtifactsHandler = async (- payload: unknown,-): Promise<ImportCallRecordingArtifactsResult> => {- const body = asRecord(payload);- const callRecordingId = getString(body?.callRecordingId);- const requestedAt = getString(body?.requestedAt);-- if (isUndefined(callRecordingId) || isUndefined(requestedAt)) {- return {- status: 'skipped',- callRecordingId: callRecordingId ?? 'unknown',- reason: 'invalid call recording artifacts import request',- };- }-- try {- return await importCallRecordingArtifacts({- client: new CoreApiClient(),- request: { callRecordingId, requestedAt },- });- } catch (error) {- throw buildRetryableStepFailure(- `artifact import for call recording ${callRecordingId}`,- error,- );- }-};+import { handleCallRecordingArtifactsImportJob } from 'src/logic-functions/flows/handle-call-recording-artifacts-import-job.util';export default defineLogicFunction({universalIdentifier:IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'import-call-recording-artifacts',description:- 'Imports recording media and transcript artifacts as an enqueued job after a verified Recall webhook resolves the owning CallRecording.',+ 'Imports one recording artifact scope as an enqueued job after a verified Recall webhook resolves the owning CallRecording.',timeoutSeconds: 250,- handler: importCallRecordingArtifactsHandler,+ handler: handleCallRecordingArtifactsImportJob,});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-artifact-scope.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-artifact-scope.type.tsnew file mode 100644index 00000000000..da4497c6dd2--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-artifact-scope.type.ts@@ -0,0 +1 @@+export type CallRecordingArtifactImportScope = 'transcript' | 'media';diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-update-fields.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-update-fields.type.tsindex 03eabc041c8..b30efbbadec 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-update-fields.type.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recording-update-fields.type.ts@@ -24,4 +24,5 @@ export type CallRecordingUpdateFields = Partial<{summary: CallRecordingSummary;// null releases the concurrent-import lease.artifactsImportClaimedAt: string | null;+ transcriptImportClaimedAt: string | null;}>;