Skip to content

The open alternative to Salesforce, designed for AI.

Make call recorder imports resumable with deterministic jobs (#26080)

nitin45a02a2daf93
diff --git a/.github/actions/spawn-twenty-server/action.yml b/.github/actions/spawn-twenty-server/action.yml
index 58214c5c2cd..a85317bd3fc 100644
--- a/.github/actions/spawn-twenty-server/action.yml
+++ b/.github/actions/spawn-twenty-server/action.yml
@@ -103,6 +103,12 @@ runs:
shell: bash
run: npx wait-on http://localhost:3000/healthz --timeout 180000 --interval 1000
+ - name: Start worker
+ if: inputs.source == 'local'
+ shell: bash
+ working-directory: packages/twenty-server
+ run: nohup yarn worker:prod > /tmp/twenty-worker.log 2>&1 &
+
- name: Resolve server url and api key
id: resolve
shell: bash
diff --git a/packages/twenty-apps/public/call-recorder/package.json b/packages/twenty-apps/public/call-recorder/package.json
index edc1f9ab528..4f6dfecb630 100644
--- a/packages/twenty-apps/public/call-recorder/package.json
+++ b/packages/twenty-apps/public/call-recorder/package.json
@@ -6,7 +6,7 @@
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2",
- "twenty": ">=2.37.0"
+ "twenty": ">=2.38.0"
},
"keywords": [
"twenty-app"
@@ -35,8 +35,8 @@
"oxlint": "^0.16.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
- "twenty-client-sdk": "2.37.0",
- "twenty-sdk": "2.37.0",
+ "twenty-client-sdk": "2.38.0",
+ "twenty-sdk": "2.38.0",
"twenty-ui": "^1.0.0-alpha.1",
"typescript": "^5.9.3",
"use-debounce": "^10.0.0",
diff --git a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
index d552ef576ee..6872ac25f3a 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
@@ -1,6 +1,9 @@
import { randomUUID } from 'crypto';
+import { isUndefined } from '@sniptt/guards';
import { CoreApiClient } from 'twenty-client-sdk/core';
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+import { getJobs } from 'twenty-sdk/logic-function';
import {
afterEach,
beforeAll,
@@ -11,11 +14,17 @@ import {
vi,
} from 'vitest';
-import { STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import {
+ APPLICATION_UNIVERSAL_IDENTIFIER,
+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
+import { type CallRecorderPreference } from 'src/constants/call-recorder-preference';
import { reconcileStaleBotStateHandler } from 'src/logic-functions/reconcile-stale-bot-state';
import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';
import { CALENDAR_EVENT_UPDATE_BATCH_SIZE } from 'src/logic-functions/constants/calendar-event-update-batch-size';
import { cancelCallRecordingRequest } from 'src/logic-functions/flows/cancel-call-recording-request.util';
+import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';
+import { saveCallRecordingImportProgress } from 'src/logic-functions/data/save-call-recording-import-progress.util';
import { convergeDivergedCallRecordings } from 'src/logic-functions/flows/converge-diverged-call-recordings.util';
import { handleCallRecordingArtifactsImportJob } from 'src/logic-functions/flows/handle-call-recording-artifacts-import-job.util';
import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';
@@ -31,15 +40,15 @@ import reconcileCalendarEventLogicFunction from 'src/logic-functions/reconcile-c
// Call Recorder end-to-end behavior against a live Twenty server.
//
// The app is installed on the test server by the vitest global setup, and all
-// reads and writes go through the real API into the test database. Only the
-// externals are mocked:
+// reads and writes go through the real API into the test database. Lifecycle
+// scenarios control delivery order with fakes for:
// - the Recall API (a fetch interceptor that replays the same bot for a
// repeated Idempotency-Key, like the real API),
// - the trigger transports: webhook deliveries invoke the webhook logic
// function handler directly, and cron / database-event triggers invoke
-// the flows they dispatch.
+// the flows they dispatch, including queued artifact imports.
//
-// Every scenario then asserts the resulting CallRecording rows in the DB.
+// Queue scenarios bypass those fakes and use the installed app's real worker.
//
// The suite issues a few hundred API requests; if the test server runs with
// the default API_RATE_LIMITING_LONG_LIMIT of 100 requests per minute,
@@ -85,7 +94,7 @@ type CalendarEventFixture = {
iCalUid: string;
isCanceled: boolean;
isFullDay: boolean;
- callRecorderPreference: string | null;
+ callRecorderPreference: CallRecorderPreference | null;
conferenceLink: {
primaryLinkLabel: string;
primaryLinkUrl: string;
@@ -208,6 +217,7 @@ class FakeRecallApi {
deletedBotIds: string[] = [];
listRequestCount = 0;
artifactImportRequests: object[] = [];
+ activeArtifactJobIds = new Set<string>();
recoveryRequests: object[] = [];
hasExpiredMedia = false;
failNextDelete = false;
@@ -302,6 +312,24 @@ class FakeRecallApi {
handle(requestUrl: string, requestInit?: any): Response | undefined {
const method: string = requestInit?.method ?? 'GET';
+ if (
+ requestUrl === `${process.env.TWENTY_API_URL}/metadata` &&
+ String(requestInit?.body ?? '').includes('getJobs')
+ ) {
+ const sentBody: { variables?: Record<string, string[]> } = JSON.parse(
+ requestInit?.body ?? '{}',
+ );
+ const requestedJobIds = Object.values(sentBody.variables ?? {}).flat();
+
+ return jsonResponse(200, {
+ data: {
+ getJobs: [...this.activeArtifactJobIds]
+ .filter((jobId) => requestedJobIds.includes(jobId))
+ .map((jobId) => ({ jobId, state: 'ACTIVE' })),
+ },
+ });
+ }
+
// Capture the artifact-import enqueue instead of letting the job run.
if (
requestUrl === `${process.env.TWENTY_API_URL}/metadata` &&
@@ -311,15 +339,18 @@ class FakeRecallApi {
const [input] = Object.values(sentBody.variables ?? {}) as {
logicFunctionUniversalIdentifier: string;
payloads: object[];
+ jobs?: { jobId: string; payload: object }[];
}[];
+ const payloads =
+ input?.jobs?.map(({ payload }) => payload) ?? input?.payloads ?? [];
if (
input?.logicFunctionUniversalIdentifier ===
STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER
) {
- this.recoveryRequests.push(...(input.payloads ?? []));
+ this.recoveryRequests.push(...payloads);
} else {
- this.artifactImportRequests.push(...(input?.payloads ?? []));
+ this.artifactImportRequests.push(...payloads);
}
return jsonResponse(200, {
@@ -328,7 +359,8 @@ class FakeRecallApi {
enqueued: true,
logicFunctionUniversalIdentifier:
input?.logicFunctionUniversalIdentifier ?? '',
- enqueuedJobsCount: input?.payloads?.length ?? 0,
+ enqueuedJobsCount: payloads.length,
+ jobIds: input?.jobs?.map(({ jobId }) => jobId) ?? [],
},
},
});
@@ -641,6 +673,7 @@ describe('call recorder app lifecycle (integration)', () => {
// Built before the fetch interceptor is installed so the shared client's
// Twenty API traffic always uses the real fetch.
let client: CoreApiClient;
+ let applicationAccessToken: string;
let workspaceId: string;
let availableCalendarEventFixtures: CalendarEventFixture[];
let nextCalendarEventFixtureIndex = 0;
@@ -662,6 +695,28 @@ describe('call recorder app lifecycle (integration)', () => {
workspaceId = readWorkspaceIdFromApiKey();
availableCalendarEventFixtures =
await discoverVisibleCalendarEventFixtures();
+
+ const metadataClient = new MetadataApiClient();
+ const { findManyApplications } = await metadataClient.query({
+ findManyApplications: { id: true, universalIdentifier: true },
+ });
+ const application = findManyApplications.find(
+ ({ universalIdentifier }) =>
+ universalIdentifier === APPLICATION_UNIVERSAL_IDENTIFIER,
+ );
+
+ if (isUndefined(application)) {
+ throw new Error('Call recorder is not installed');
+ }
+
+ const { generateApplicationToken } = await metadataClient.mutation({
+ generateApplicationToken: {
+ __args: { applicationId: application.id },
+ applicationAccessToken: { token: true },
+ },
+ });
+ applicationAccessToken =
+ generateApplicationToken.applicationAccessToken.token;
});
beforeEach(() => {
@@ -903,16 +958,20 @@ describe('call recorder app lifecycle (integration)', () => {
}> => {
const calendarEventId = await createCalendarEvent();
- await reconcileCallRecorderForCalendarEventIds({
+ const [reconciliation] = await reconcileCallRecorderForCalendarEventIds({
client,
calendarEventIds: [calendarEventId],
});
- const callRecording = (
- await findCallRecordings({ calendarEventId: { in: [calendarEventId] } })
- )[0];
+ if (reconciliation.action === 'FAILED' || !reconciliation.callRecordingId) {
+ throw new Error(
+ `Recording fixture failed: ${JSON.stringify(reconciliation)}`,
+ );
+ }
- expect(callRecording).toBeDefined();
+ const callRecording = await fetchCallRecording(
+ reconciliation.callRecordingId,
+ );
expect(callRecording.externalBotId).toBeTruthy();
return {
@@ -1083,7 +1142,7 @@ describe('call recorder app lifecycle (integration)', () => {
'recall-recording-1',
);
expect(processedCallRecording.endedAt).toBeTruthy();
- expect(recall.artifactImportRequests).toHaveLength(2);
+ expect(recall.artifactImportRequests).toHaveLength(3);
});
it('queues another artifact import when the transcript finishes later', async () => {
@@ -1102,8 +1161,8 @@ describe('call recorder app lifecycle (integration)', () => {
buildTranscriptDoneWebhook({ botId, metadata }),
);
- expect(recall.artifactImportRequests).toHaveLength(3);
- expect(recall.artifactImportRequests[2]).toMatchObject({
+ expect(recall.artifactImportRequests).toHaveLength(4);
+ expect(recall.artifactImportRequests[3]).toMatchObject({
callRecordingId,
});
});
@@ -1351,6 +1410,72 @@ describe('call recorder app lifecycle (integration)', () => {
});
});
+ describe('artifact import queue', () => {
+ beforeEach(() => {
+ vi.unstubAllGlobals();
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', applicationAccessToken);
+ });
+
+ const waitForCompletedJob = async (jobId: string) => {
+ await expect
+ .poll(() => getJobs([jobId]), { timeout: 30_000, interval: 500 })
+ .toMatchObject([{ jobId, state: 'COMPLETED' }]);
+
+ return getJobs([jobId]);
+ };
+
+ it.each([
+ { scope: 'transcript', trigger: 'transcript-ready', suffix: 'ready' },
+ { scope: 'video', trigger: 'recovery', suffix: 'recovery-2026-06-10' },
+ { scope: 'audio', trigger: 'expired', suffix: 'expired' },
+ ] as const)(
+ 'deduplicates $scope imports and allows a later $trigger job',
+ async ({ scope, trigger, suffix }) => {
+ // A missing recording lets the real worker finish without contacting Recall.
+ const callRecordingId = randomUUID();
+ const request = {
+ callRecordingIds: [callRecordingId],
+ scopes: [scope],
+ requestedAt: '2026-06-10T03:30:00.000Z',
+ };
+ const jobId = `call-recorder-${callRecordingId}-${scope}`;
+
+ await enqueueCallRecordingArtifactsImport(request);
+ const originalJob = await waitForCompletedJob(jobId);
+ await enqueueCallRecordingArtifactsImport(request);
+ expect(await getJobs([jobId])).toEqual(originalJob);
+
+ await enqueueCallRecordingArtifactsImport({ ...request, trigger });
+ const laterJobId = `${jobId}-${suffix}`;
+ const laterJob = await waitForCompletedJob(laterJobId);
+ await enqueueCallRecordingArtifactsImport({ ...request, trigger });
+ expect(await getJobs([laterJobId])).toEqual(laterJob);
+ },
+ );
+
+ it.each([
+ { scope: 'video', attemptsMade: 1 },
+ { scope: 'audio', attemptsMade: 3 },
+ ] as const)(
+ 'stops failed $scope executions after $attemptsMade attempts',
+ async ({ scope, attemptsMade }) => {
+ // Invalid UUID input makes the real database read fail before any Recall request.
+ const callRecordingId = `invalid-${randomUUID()}`;
+ const jobId = `call-recorder-${callRecordingId}-${scope}`;
+
+ await enqueueCallRecordingArtifactsImport({
+ callRecordingIds: [callRecordingId],
+ scopes: [scope],
+ });
+
+ // The worker completes the job when the application's retry budget is exhausted.
+ await expect
+ .poll(() => getJobs([jobId]), { timeout: 30_000, interval: 500 })
+ .toMatchObject([{ jobId, state: 'COMPLETED', attemptsMade }]);
+ },
+ );
+ });
+
describe('settling recordings whose Recall media expired', () => {
const recordingStartedAt = () => hoursAgo(1);
@@ -1394,8 +1519,8 @@ describe('call recorder app lifecycle (integration)', () => {
callRecording: Awaited<ReturnType<typeof fetchCallRecording>>,
) => {
expect(callRecording.status).toBe('FAILED');
- expect(callRecording.callRecorderFailureReason).toBe(
- 'video_import_expired,audio_import_expired',
+ expect(callRecording.callRecorderFailureReason.split(',').sort()).toEqual(
+ ['audio_import_expired', 'video_import_expired'],
);
expect(callRecording.transcript).toEqual({
recallTranscriptId: null,
@@ -1404,6 +1529,93 @@ describe('call recorder app lifecycle (integration)', () => {
});
};
+ it('preserves independent failure outcomes when audio and video save concurrently', async () => {
+ const { callRecordingId, botId, metadata } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ await deliverRecordingDone({ botId, metadata });
+
+ await Promise.all(
+ ['audio_file_too_large', 'video_import_failed'].map(
+ (callRecorderFailureReason) =>
+ saveCallRecordingImportProgress(client, {
+ callRecordingId,
+ externalBotId: botId,
+ data: { callRecorderFailureReason },
+ }),
+ ),
+ );
+
+ await saveCallRecordingImportProgress(client, {
+ callRecordingId,
+ externalBotId: botId,
+ data: { video: [{ fileId: randomUUID(), label: 'late-video.mp4' }] },
+ });
+
+ expect(
+ (await fetchCallRecording(callRecordingId)).callRecorderFailureReason
+ .split(',')
+ .sort(),
+ ).toEqual(['audio_file_too_large', 'video_import_failed']);
+ expect((await fetchCallRecording(callRecordingId)).video ?? []).toEqual(
+ [],
+ );
+ });
+
+ it('replaces a pending transcript and ignores late pending or failed results', async () => {
+ const { callRecordingId, botId, metadata } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ await deliverRecordingDone({ botId, metadata });
+ const pending = { status: 'PENDING', recallTranscriptId: 'transcript-1' };
+ const transcript = { utterances: [{ text: 'Ready transcript' }] };
+ for (const data of [
+ { transcript: pending },
+ { transcript },
+ { transcript: pending },
+ {
+ transcript: { status: 'FAILED' },
+ callRecorderFailureReason: 'transcript_failed',
+ },
+ ]) {
+ await saveCallRecordingImportProgress(client, {
+ callRecordingId,
+ externalBotId: botId,
+ data,
+ });
+ }
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+ expect(callRecording.transcript).toEqual(transcript);
+ expect(callRecording.callRecorderFailureReason).toBeFalsy();
+ });
+
+ it.each([
+ { status: 'COMPLETED' },
+ { externalBotId: 'replacement-bot' },
+ ] as const)(
+ 'ignores late import progress after the recording changes: %j',
+ async (data) => {
+ const { callRecordingId, botId, metadata } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ await deliverRecordingDone({ botId, metadata });
+ await client.mutation({
+ updateCallRecording: {
+ __args: { id: callRecordingId, data },
+ id: true,
+ },
+ });
+
+ await saveCallRecordingImportProgress(client, {
+ callRecordingId,
+ externalBotId: botId,
+ data: { transcript: { status: 'FAILED' } },
+ });
+
+ expect(
+ (await fetchCallRecording(callRecordingId)).transcript,
+ ).toBeNull();
+ },
+ );
+
it('fails a processing recording whose media expired before any artifact was imported', async () => {
const { calendarEventId, callRecordingId, botId, metadata } =
await scheduleRecordingThroughCalendarReconciliation();
@@ -1428,38 +1640,52 @@ describe('call recorder app lifecycle (integration)', () => {
expectFailedWithExpiredArtifacts(callRecording);
});
- it('defers media settlement while an artifact import holds its claim', async () => {
- const { calendarEventId, callRecordingId, botId, metadata } =
- await scheduleRecordingThroughCalendarReconciliation();
- const { startedAt, completedAt } = await deliverRecordingDone({
- botId,
- metadata,
- });
+ it.each(
+ (['audio', 'video'] as const).flatMap((scope) =>
+ (['recovery', 'expired'] as const).flatMap((trigger) =>
+ ['', '-expired', '-recovery-2026-06-10', '-recovery-2026-06-09'].map(
+ (suffix) => ({ scope, trigger, suffix }),
+ ),
+ ),
+ ),
+ )(
+ 'leaves the active $scope$suffix import to the queue on $trigger while settling the other expired artifacts',
+ async ({ scope, trigger, suffix }) => {
+ const { calendarEventId, callRecordingId, botId, metadata } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ const { startedAt, completedAt } = await deliverRecordingDone({
+ botId,
+ metadata,
+ });
- await expireMediaAndAgeMeeting({
- calendarEventId,
- botId,
- startedAt,
- completedAt,
- });
- await client.mutation({
- updateCallRecording: {
- __args: {
- id: callRecordingId,
- data: { artifactsImportClaimedAt: new Date().toISOString() },
- },
- id: true,
- },
- });
+ await expireMediaAndAgeMeeting({
+ calendarEventId,
+ botId,
+ startedAt,
+ completedAt,
+ });
+ recall.artifactImportRequests = [];
+ recall.activeArtifactJobIds.add(
+ `call-recorder-${callRecordingId}-${scope}${suffix}`,
+ );
- await runStaleStateCron();
+ await enqueueCallRecordingArtifactsImport({
+ callRecordingIds: [callRecordingId],
+ scopes: ['transcript', 'audio', 'video'],
+ trigger,
+ requestedAt: '2026-06-10T00:05:00.000Z',
+ });
+ await runQueuedArtifactImports();
- const callRecording = await fetchCallRecording(callRecordingId);
+ const callRecording = await fetchCallRecording(callRecordingId);
- expect(callRecording.status).toBe('PROCESSING');
- expect(callRecording.callRecorderFailureReason).toBeFalsy();
- expect(callRecording.transcript).toMatchObject({ status: 'EMPTY' });
- });
+ expect(callRecording.status).toBe('PROCESSING');
+ expect(callRecording.callRecorderFailureReason).toBe(
+ `${scope === 'audio' ? 'video' : 'audio'}_import_expired`,
+ );
+ expect(callRecording.transcript).toMatchObject({ status: 'EMPTY' });
+ },
+ );
it('completes a processing recording with imported media once Recall expires the rest', async () => {
const { calendarEventId, callRecordingId, botId, metadata } =
@@ -1470,6 +1696,15 @@ describe('call recorder app lifecycle (integration)', () => {
});
await runQueuedArtifactImports();
+ const imported = await fetchCallRecording(callRecordingId);
+ await saveCallRecordingImportProgress(client, {
+ callRecordingId,
+ externalBotId: botId,
+ data: {
+ video: [{ fileId: randomUUID(), label: 'late-video.mp4' }],
+ callRecorderFailureReason: 'video_import_failed',
+ },
+ });
await expireMediaAndAgeMeeting({
calendarEventId,
botId,
@@ -1484,6 +1719,9 @@ describe('call recorder app lifecycle (integration)', () => {
const callRecording = await fetchCallRecording(callRecordingId);
expect(callRecording.status).toBe('COMPLETED');
+ expect(callRecording.video).toMatchObject([
+ { fileId: imported.video[0].fileId },
+ ]);
expect(callRecording.callRecorderFailureReason).toBeFalsy();
expect(callRecording.transcript).toEqual({
recallTranscriptId: 'recall-transcript-1',
@@ -1492,7 +1730,7 @@ describe('call recorder app lifecycle (integration)', () => {
});
});
- it('completes a processing recording with only audio and records the expired video', async () => {
+ it('keeps audio and never retries a saved video failure, including during repair', async () => {
const { calendarEventId, callRecordingId, botId, metadata } =
await scheduleRecordingThroughCalendarReconciliation();
@@ -1503,9 +1741,15 @@ describe('call recorder app lifecycle (integration)', () => {
metadata,
});
- await expect(runQueuedArtifactImports()).rejects.toMatchObject({
- name: 'RetryableLogicFunctionError',
- });
+ await runQueuedArtifactImports();
+ recall.failVideoDownload = false;
+ await runStaleStateCron();
+
+ const repaired = await fetchCallRecording(callRecordingId);
+ expect(repaired.audio).toHaveLength(1);
+ expect(repaired.video ?? []).toHaveLength(0);
+ expect(repaired.callRecorderFailureReason).toBe('video_import_failed');
+
await expireMediaAndAgeMeeting({
calendarEventId,
botId,
@@ -1519,11 +1763,59 @@ describe('call recorder app lifecycle (integration)', () => {
expect(callRecording.status).toBe('COMPLETED');
expect(callRecording.callRecorderFailureReason).toBe(
- 'video_import_expired',
+ 'video_import_failed',
);
expect(callRecording.transcript).toMatchObject({ status: 'EMPTY' });
});
+ it('saves and settles a video timeout even after its work signal has aborted', async () => {
+ const { callRecordingId, botId, metadata } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ await deliverRecordingDone({ botId, metadata });
+ await saveCallRecordingImportProgress(client, {
+ callRecordingId,
+ externalBotId: botId,
+ data: { transcript: { status: 'EMPTY', recallTranscriptId: null } },
+ });
+
+ const controller = new AbortController();
+ const originalTimeout = AbortSignal.timeout.bind(AbortSignal);
+ const timeout = vi
+ .spyOn(AbortSignal, 'timeout')
+ .mockImplementation((milliseconds) =>
+ milliseconds === 14 * 60 * 1000
+ ? controller.signal
+ : originalTimeout(milliseconds),
+ );
+ const originalFetch = globalThis.fetch;
+ vi.stubGlobal(
+ 'fetch',
+ (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ if (String(input).endsWith('/media/video.mp4')) {
+ controller.abort(
+ new DOMException('Video deadline elapsed', 'TimeoutError'),
+ );
+ return Promise.reject(controller.signal.reason);
+ }
+
+ return originalFetch(input, init);
+ },
+ );
+
+ try {
+ await runQueuedArtifactImports();
+ } finally {
+ timeout.mockRestore();
+ }
+
+ const callRecording = await fetchCallRecording(callRecordingId);
+ expect(callRecording.status).toBe('COMPLETED');
+ expect(callRecording.audio).toHaveLength(1);
+ expect(callRecording.callRecorderFailureReason).toBe(
+ 'video_import_failed',
+ );
+ });
+
it('fails a recording whose media was too large to store and whose transcript never arrived', async () => {
const { calendarEventId, callRecordingId, botId, metadata } =
await scheduleRecordingThroughCalendarReconciliation();
@@ -1539,7 +1831,7 @@ describe('call recorder app lifecycle (integration)', () => {
expect(
(await fetchCallRecording(callRecordingId)).callRecorderFailureReason,
- ).toBe('video_file_too_large,audio_file_too_large');
+ ).toBe('audio_file_too_large,video_file_too_large');
await expireMediaAndAgeMeeting({
calendarEventId,
@@ -1554,7 +1846,7 @@ describe('call recorder app lifecycle (integration)', () => {
expect(callRecording.status).toBe('FAILED');
expect(callRecording.callRecorderFailureReason).toBe(
- 'video_file_too_large,audio_file_too_large',
+ 'audio_file_too_large,video_file_too_large',
);
expect(callRecording.transcript).toMatchObject({ status: 'EMPTY' });
});
@@ -1580,7 +1872,7 @@ describe('call recorder app lifecycle (integration)', () => {
}),
);
- expect(recall.artifactImportRequests).toHaveLength(4);
+ expect(recall.artifactImportRequests).toHaveLength(6);
await runQueuedArtifactImports();
@@ -1606,7 +1898,7 @@ describe('call recorder app lifecycle (integration)', () => {
buildRecordingDeletedWebhook({ botId, metadata }),
);
- expect(recall.artifactImportRequests).toHaveLength(4);
+ expect(recall.artifactImportRequests).toHaveLength(6);
await runQueuedArtifactImports();
diff --git a/packages/twenty-apps/public/call-recorder/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/call-recorder/src/constants/universal-identifiers.ts
index 3fd682cd3d2..aea83c50b19 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
@@ -55,18 +55,12 @@ export const CALL_RECORDER_USE_WORKSPACE_LOGO_APP_VARIABLE_UNIVERSAL_IDENTIFIER
export const CALL_RECORDER_WAITING_ROOM_TIMEOUT_SECONDS_APP_VARIABLE_UNIVERSAL_IDENTIFIER =
'12e4e14d-d539-4d07-b477-4773539dd20b';
-export const CALL_RECORDING_ARTIFACTS_IMPORT_CLAIMED_AT_FIELD_UNIVERSAL_IDENTIFIER =
- 'bf8ebf7e-4d52-4a7b-8d41-337c53d478ab';
-
export const CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER =
'2eafc2d0-8fec-430c-a939-65ca5fbc0f08';
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-artifacts-import-claimed-at-on-call-recording.field.ts b/packages/twenty-apps/public/call-recorder/src/fields/call-recording-artifacts-import-claimed-at-on-call-recording.field.ts
deleted file mode 100644
index 6ae8738a2fa..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/fields/call-recording-artifacts-import-claimed-at-on-call-recording.field.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import {
- defineField,
- FieldType,
- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
-} from 'twenty-sdk/define';
-
-import { CALL_RECORDING_ARTIFACTS_IMPORT_CLAIMED_AT_FIELD_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-
-export default defineField({
- universalIdentifier:
- CALL_RECORDING_ARTIFACTS_IMPORT_CLAIMED_AT_FIELD_UNIVERSAL_IDENTIFIER,
- objectUniversalIdentifier:
- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.callRecording.universalIdentifier,
- type: FieldType.DATE_TIME,
- name: 'artifactsImportClaimedAt',
- label: 'Artifacts Import Claimed At',
- description:
- 'Lease held by the worker importing this recording’s artifacts; prevents concurrent webhook retries from duplicating provider imports.',
- icon: 'IconLock',
- isNullable: true,
- isUIEditable: false,
-});
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.ts
deleted file mode 100644
index c4b7df69c74..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/fields/call-recording-transcript-import-claimed-at-on-call-recording.field.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-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__/process-recall-webhook.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/process-recall-webhook.test.ts
index 7a99ffdc8e7..1608347e4aa 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/process-recall-webhook.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/process-recall-webhook.test.ts
@@ -116,7 +116,7 @@ describe('process-recall-webhook', () => {
},
});
expect(enqueueArtifactImportMock).toHaveBeenCalledWith(
- expect.objectContaining({ callRecordingId: 'call-recording-1' }),
+ expect.objectContaining({ callRecordingIds: ['call-recording-1'] }),
);
expect(result).toEqual({
status: 'updated',
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifact-import-work-budget-ms.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifact-import-work-budget-ms.ts
new file mode 100644
index 00000000000..8d5ea020417
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifact-import-work-budget-ms.ts
@@ -0,0 +1,3 @@
+export const ARTIFACT_IMPORT_WORK_BUDGET_MS = 200_000;
+// Leave a minute to persist the outcome before Lambda's 15-minute hard limit.
+export const VIDEO_IMPORT_WORK_BUDGET_MS = 14 * 60 * 1000;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifacts-import-claim-field-by-scope.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifacts-import-claim-field-by-scope.ts
deleted file mode 100644
index 84b4897ac97..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/artifacts-import-claim-field-by-scope.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export const ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE = {
- transcript: 'transcriptImportClaimedAt',
- media: 'artifactsImportClaimedAt',
-} as const;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-artifact-import-scopes.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-artifact-import-scopes.ts
index 69f82074044..0b47fe2ecf8 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-artifact-import-scopes.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/call-recording-artifact-import-scopes.ts
@@ -2,5 +2,6 @@ import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types
export const CALL_RECORDING_ARTIFACT_IMPORT_SCOPES = [
'transcript',
- 'media',
+ 'audio',
+ 'video',
] satisfies CallRecordingArtifactImportScope[];
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/video-import-failed-failure-reason.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/video-import-failed-failure-reason.ts
new file mode 100644
index 00000000000..f5404b42e72
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/video-import-failed-failure-reason.ts
@@ -0,0 +1 @@
+export const VIDEO_IMPORT_FAILED_FAILURE_REASON = 'video_import_failed';
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.ts
deleted file mode 100644
index 7e22f6ecf00..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/claim-call-recording-artifacts-import.test.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-import { describe, expect, it } from 'vitest';
-
-import { ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE } from 'src/logic-functions/constants/artifacts-import-claim-field-by-scope';
-import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
-import {
- claimCallRecordingArtifactsImport,
- releaseCallRecordingArtifactsImportClaim,
-} from 'src/logic-functions/data/claim-call-recording-artifacts-import.util';
-import { updateClaimedCallRecordingArtifacts } from 'src/logic-functions/data/update-claimed-call-recording-artifacts.util';
-import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';
-
-type ClaimField = 'artifactsImportClaimedAt' | 'transcriptImportClaimedAt';
-type Predicate = { eq?: string; is?: 'NULL'; lte?: string };
-type ClaimFilter = Partial<Record<ClaimField, Predicate>> & {
- id: { eq: string };
- status?: { eq: string };
- or?: Partial<Record<ClaimField, Predicate>>[];
-};
-
-const buildStore = () => {
- const row: CallRecordingUpdateFields & { id: string } = {
- id: 'recording',
- status: CallRecordingStatus.PROCESSING,
- artifactsImportClaimedAt: null,
- transcriptImportClaimedAt: null,
- };
- const matches = (field: ClaimField, predicate: Predicate | undefined) => {
- if (predicate === undefined) return true;
- const value = row[field];
- if (predicate.is === 'NULL') return value === null;
- if (predicate.eq !== undefined) return value === predicate.eq;
- return (
- typeof value === 'string' &&
- predicate.lte !== undefined &&
- value <= predicate.lte
- );
- };
- const client = {
- mutation: async ({
- updateCallRecordings,
- }: {
- updateCallRecordings: {
- __args: { filter: ClaimFilter; data: CallRecordingUpdateFields };
- };
- }) => {
- const { filter, data } = updateCallRecordings.__args;
- const claimFields: ClaimField[] = [
- 'artifactsImportClaimedAt',
- 'transcriptImportClaimedAt',
- ];
- const hasMatched =
- filter.id.eq === row.id &&
- (filter.status === undefined || row.status === filter.status.eq) &&
- claimFields.every((field) => matches(field, filter[field])) &&
- (filter.or === undefined ||
- filter.or.some((part) =>
- claimFields.every((field) => matches(field, part[field])),
- ));
-
- if (!hasMatched) return { updateCallRecordings: [] };
- Object.assign(row, data);
- return { updateCallRecordings: [{ ...row }] };
- },
- };
-
- return { row, client: client as unknown as CoreApiClient };
-};
-
-const NOW = new Date('2026-01-01T14:06:00.000Z');
-
-describe.each(['media', 'transcript'] as const)(
- '%s artifact import claim',
- (scope) => {
- const field = ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope];
- const otherField =
- ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[
- scope === 'media' ? 'transcript' : 'media'
- ];
-
- it('claims processing work and rejects a concurrent worker', async () => {
- const { client, row } = buildStore();
- const request = { callRecordingId: row.id, scope, now: NOW };
-
- expect(
- await claimCallRecordingArtifactsImport(client, request),
- ).toMatchObject({ id: row.id, status: CallRecordingStatus.PROCESSING });
- expect(
- await claimCallRecordingArtifactsImport(client, request),
- ).toBeUndefined();
- expect(row[field]).toBe(NOW.toISOString());
- });
-
- it('does not reclaim while an earlier Lambda can still be running', async () => {
- const { client, row } = buildStore();
- row[field] = new Date(NOW.getTime() - 14 * 60_000).toISOString();
-
- expect(
- await claimCallRecordingArtifactsImport(client, {
- callRecordingId: row.id,
- scope,
- now: NOW,
- }),
- ).toBeUndefined();
- });
-
- it('reclaims an abandoned claim after the maximum execution window', async () => {
- const { client, row } = buildStore();
- row[field] = new Date(NOW.getTime() - 17 * 60_000).toISOString();
-
- expect(
- await claimCallRecordingArtifactsImport(client, {
- callRecordingId: row.id,
- scope,
- now: NOW,
- }),
- ).toMatchObject({ id: row.id });
- });
-
- it('prevents an old worker from writing progress or releasing its replacement claim', async () => {
- const { client, row } = buildStore();
- const oldClaimedAt = new Date(NOW.getTime() - 17 * 60_000).toISOString();
- row[field] = oldClaimedAt;
- await claimCallRecordingArtifactsImport(client, {
- callRecordingId: row.id,
- scope,
- now: NOW,
- });
-
- await expect(
- updateClaimedCallRecordingArtifacts(client, {
- callRecordingId: row.id,
- scope,
- claimedAt: oldClaimedAt,
- data: { callRecorderFailureReason: 'old-result' },
- }),
- ).rejects.toThrow('no longer active');
- await releaseCallRecordingArtifactsImportClaim(client, {
- callRecordingId: row.id,
- scope,
- claimedAt: oldClaimedAt,
- });
-
- expect(row[field]).toBe(NOW.toISOString());
- expect(row.callRecorderFailureReason).toBeUndefined();
- });
-
- it('saves progress and releases only the owned scope', async () => {
- const { client, row } = buildStore();
- row.artifactsImportClaimedAt = NOW.toISOString();
- row.transcriptImportClaimedAt = NOW.toISOString();
- const claim = {
- callRecordingId: row.id,
- scope,
- claimedAt: NOW.toISOString(),
- };
-
- await updateClaimedCallRecordingArtifacts(client, {
- ...claim,
- data: { callRecorderFailureReason: 'video_file_too_large' },
- });
- await releaseCallRecordingArtifactsImportClaim(client, claim);
-
- expect(row.callRecorderFailureReason).toBe('video_file_too_large');
- expect(row[field]).toBeNull();
- expect(row[otherField]).toBe(NOW.toISOString());
- });
- it('cannot claim or write to an already completed recording', async () => {
- const { client, row } = buildStore();
- row.status = CallRecordingStatus.COMPLETED;
- row[field] = NOW.toISOString();
-
- expect(
- await claimCallRecordingArtifactsImport(client, {
- callRecordingId: row.id,
- scope,
- now: NOW,
- }),
- ).toBeUndefined();
- await expect(
- updateClaimedCallRecordingArtifacts(client, {
- callRecordingId: row.id,
- scope,
- claimedAt: NOW.toISOString(),
- data: { callRecorderFailureReason: 'late-result' },
- }),
- ).rejects.toThrow('no longer active');
- expect(row.callRecorderFailureReason).toBeUndefined();
- });
- },
-);
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-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
deleted file mode 100644
index 336971516f6..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-artifacts-import.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';
-import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';
-
-const enqueueJobsMock = vi.hoisted(() => vi.fn());
-
-vi.mock('twenty-sdk/logic-function', () => ({
- enqueueJobs: enqueueJobsMock,
-}));
-
-describe('enqueueCallRecordingArtifactsImport', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- enqueueJobsMock.mockResolvedValue({ enqueued: true, enqueuedJobsCount: 1 });
- });
-
- 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({
- logicFunctionUniversalIdentifier:
- IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- payloads: [
- {
- 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,
- });
- });
-
- it('propagates enqueue failures to the caller', async () => {
- enqueueJobsMock.mockRejectedValue(new Error('Network failed'));
-
- 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.ts
deleted file mode 100644
index d16e804a9a5..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/claim-call-recording-artifacts-import.util.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-
-import { ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE } from 'src/logic-functions/constants/artifacts-import-claim-field-by-scope';
-import { CALL_RECORDING_FOR_ARTIFACTS_IMPORT_SELECTION } from 'src/logic-functions/constants/call-recording-for-artifacts-import-selection';
-import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
-import { parseCallRecordingForArtifactsImportNode } from 'src/logic-functions/data/parse-call-recording-for-artifacts-import-node.util';
-import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';
-import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';
-
-// The executor Lambda runs with this hard timeout regardless of the function's
-// timeoutSeconds, which only bounds how long the server waits for the invoke.
-const LOGIC_FUNCTION_LAMBDA_HARD_TIMEOUT_MS = 15 * 60 * 1000;
-
-// Crash safety net: a lease older than this is reclaimable so a worker that died
-// mid-import never blocks the recording forever. It must outlive the Lambda so
-// a second job never uploads on top of one that is still running.
-const ARTIFACTS_IMPORT_CLAIM_TTL_MS =
- LOGIC_FUNCTION_LAMBDA_HARD_TIMEOUT_MS + 60 * 1000;
-
-export const claimCallRecordingArtifactsImport = async (
- client: CoreApiClient,
- {
- callRecordingId,
- scope,
- now,
- }: {
- callRecordingId: string;
- scope: CallRecordingArtifactImportScope;
- now: Date;
- },
-): Promise<CallRecordingForArtifactsImport | undefined> => {
- const claimField = ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope];
- const staleBefore = new Date(
- now.getTime() - ARTIFACTS_IMPORT_CLAIM_TTL_MS,
- ).toISOString();
-
- const result = await client.mutation({
- updateCallRecordings: {
- __args: {
- filter: {
- id: { eq: callRecordingId },
- status: { eq: CallRecordingStatus.PROCESSING },
- or: [
- { [claimField]: { is: 'NULL' } },
- { [claimField]: { lte: staleBefore } },
- ],
- },
- data: { [claimField]: now.toISOString() },
- },
- ...CALL_RECORDING_FOR_ARTIFACTS_IMPORT_SELECTION,
- },
- });
-
- return parseCallRecordingForArtifactsImportNode(
- result.updateCallRecordings?.[0],
- );
-};
-
-export const releaseCallRecordingArtifactsImportClaim = async (
- client: CoreApiClient,
- {
- callRecordingId,
- scope,
- claimedAt,
- }: {
- callRecordingId: string;
- scope: CallRecordingArtifactImportScope;
- claimedAt: string;
- },
-): Promise<void> => {
- await client.mutation({
- updateCallRecordings: {
- __args: {
- filter: {
- id: { eq: callRecordingId },
- [ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope]]: { eq: claimedAt },
- },
- data: { [ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope]]: null },
- },
- id: true,
- },
- });
-};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts
index 0b68f223eb8..6ce06892c69 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,23 +1,110 @@
+import { isNonEmptyArray, isUndefined } from '@sniptt/guards';
+import { enqueueJobs, getJobs } from 'twenty-sdk/logic-function';
+
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 { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';
+import { MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL } from 'src/logic-functions/constants/max-payloads-per-enqueue-jobs-call';
import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';
+import { getBatches } from 'src/logic-functions/utils/get-batches.util';
export const enqueueCallRecordingArtifactsImport = async ({
- callRecordingId,
+ callRecordingIds,
scopes,
+ trigger = 'recording',
+ requestedAt = new Date().toISOString(),
}: {
- callRecordingId: string;
+ callRecordingIds: string[];
scopes: CallRecordingArtifactImportScope[];
+ trigger?: 'recording' | 'transcript-ready' | 'expired' | 'recovery';
+ requestedAt?: string;
}): Promise<void> => {
- const requestedAt = new Date().toISOString();
-
- await enqueueLogicFunctionJobs({
- logicFunctionUniversalIdentifier:
- IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- payloads: scopes.map((scope) => ({
- callRecordingId,
- requestedAt,
- scope,
- })),
- });
+ const isQueueStatusRequired = trigger === 'recovery' || trigger === 'expired';
+ const recoveryDate = requestedAt.slice(0, 10);
+ // An import started before midnight can still be running the next day.
+ const previousRecoveryDate = new Date(
+ new Date(requestedAt).getTime() - 24 * 60 * 60 * 1000,
+ )
+ .toISOString()
+ .slice(0, 10);
+
+ for (const scope of scopes) {
+ const jobIdSuffixes = [
+ '',
+ '-expired',
+ `-recovery-${recoveryDate}`,
+ `-recovery-${previousRecoveryDate}`,
+ ...(scope === 'transcript' ? ['-ready'] : []),
+ ];
+
+ for (const recordingIds of getBatches(
+ callRecordingIds,
+ Math.floor(
+ MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL /
+ (isQueueStatusRequired ? jobIdSuffixes.length : 1),
+ ),
+ )) {
+ const baseJobs = recordingIds.map((callRecordingId) => ({
+ jobId: `call-recorder-${callRecordingId}-${scope}`,
+ payload: { callRecordingId, requestedAt, scope },
+ }));
+ const statuses = isQueueStatusRequired
+ ? await getJobs(
+ baseJobs.flatMap(({ jobId }) =>
+ jobIdSuffixes.map((suffix) => `${jobId}${suffix}`),
+ ),
+ )
+ : [];
+ const statusesById = new Map(
+ statuses.map((status) => [status.jobId, status]),
+ );
+ const jobs = baseJobs.flatMap(({ jobId, payload }) => {
+ const initialJobStatus = statusesById.get(jobId);
+ const transcriptReadyJobStatus = statusesById.get(`${jobId}-ready`);
+
+ if (
+ jobIdSuffixes.some((suffix) => {
+ const status = statusesById.get(`${jobId}${suffix}`);
+
+ return (
+ !isUndefined(status) &&
+ status.state !== 'COMPLETED' &&
+ status.state !== 'FAILED'
+ );
+ })
+ ) {
+ return [];
+ }
+
+ // Queue history deduplicates completed and failed IDs, so repairs need a new ID.
+ if (
+ trigger === 'recovery' &&
+ (!isUndefined(initialJobStatus) ||
+ !isUndefined(transcriptReadyJobStatus))
+ ) {
+ return [{ jobId: `${jobId}-recovery-${recoveryDate}`, payload }];
+ }
+
+ if (trigger === 'transcript-ready') {
+ return [{ jobId: `${jobId}-ready`, payload }];
+ }
+
+ if (trigger === 'expired') {
+ return [{ jobId: `${jobId}-expired`, payload }];
+ }
+
+ return [{ jobId, payload }];
+ });
+
+ if (!isNonEmptyArray(jobs)) {
+ continue;
+ }
+
+ await enqueueJobs({
+ logicFunctionUniversalIdentifier:
+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs,
+ retryLimit: scope === 'video' ? 0 : ENQUEUED_JOB_RETRY_LIMIT,
+ });
+ }
+ }
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/save-call-recording-import-progress.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/save-call-recording-import-progress.util.ts
new file mode 100644
index 00000000000..9b69c876bf0
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/save-call-recording-import-progress.util.ts
@@ -0,0 +1,165 @@
+import { isNonEmptyArray, isUndefined } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
+import { findCallRecordingForArtifactsImport } from 'src/logic-functions/data/find-call-recording-for-artifacts-import.util';
+import { hasCallRecordingUpdateFields } from 'src/logic-functions/domain/has-call-recording-update-fields.util';
+import { parseTranscriptMarker } from 'src/logic-functions/domain/parse-transcript-marker.util';
+import { parseUnrecoverableMediaMarkers } from 'src/logic-functions/domain/parse-unrecoverable-media-markers.util';
+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';
+import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';
+
+// Queue redelivery can overlap a Lambda that is still running.
+export const saveCallRecordingImportProgress = async (
+ client: CoreApiClient,
+ {
+ callRecordingId,
+ externalBotId,
+ data,
+ }: {
+ callRecordingId: string;
+ externalBotId: string | undefined;
+ data: CallRecordingUpdateFields;
+ },
+): Promise<void> => {
+ if (!hasCallRecordingUpdateFields(data)) {
+ return;
+ }
+
+ for (let saveAttempt = 0; saveAttempt < 3; saveAttempt++) {
+ const currentCallRecording = await findCallRecordingForArtifactsImport(
+ client,
+ callRecordingId,
+ );
+
+ if (
+ isUndefined(currentCallRecording) ||
+ currentCallRecording.status !== CallRecordingStatus.PROCESSING ||
+ currentCallRecording.externalBotId !== externalBotId
+ ) {
+ return;
+ }
+
+ const transcriptMarker = parseTranscriptMarker(
+ currentCallRecording.transcript,
+ );
+
+ if (
+ !isUndefined(data.transcript) &&
+ !isUndefined(currentCallRecording.transcript) &&
+ (transcriptMarker?.status !== 'PENDING' ||
+ parseTranscriptMarker(data.transcript)?.status === 'PENDING')
+ ) {
+ return;
+ }
+
+ const { isAudioUnrecoverable, isVideoUnrecoverable } =
+ parseUnrecoverableMediaMarkers(
+ currentCallRecording.callRecorderFailureReason,
+ );
+ const isResolvedByMediaField = {
+ audio:
+ isNonEmptyArray(currentCallRecording.audio) || isAudioUnrecoverable,
+ video:
+ isNonEmptyArray(currentCallRecording.video) || isVideoUnrecoverable,
+ };
+ const { audio, video, callRecorderFailureReason, ...otherUpdateData } =
+ data;
+
+ const failureReasons = (callRecorderFailureReason ?? '')
+ .split(',')
+ .filter(isNonEmptyString)
+ .filter(
+ (reason) =>
+ !(['audio', 'video'] as const).some(
+ (field) =>
+ isResolvedByMediaField[field] && reason.startsWith(`${field}_`),
+ ),
+ );
+
+ const mergedCallRecorderFailureReason = [
+ ...new Set([
+ ...(currentCallRecording.callRecorderFailureReason ?? '')
+ .split(',')
+ .filter(isNonEmptyString),
+ ...failureReasons,
+ ]),
+ ].join(',');
+ const updateData: CallRecordingUpdateFields = {
+ ...otherUpdateData,
+ ...(isResolvedByMediaField.audio || isUndefined(audio) ? {} : { audio }),
+ ...(isResolvedByMediaField.video || isUndefined(video) ? {} : { video }),
+ ...(!isUndefined(callRecorderFailureReason) &&
+ mergedCallRecorderFailureReason !==
+ (currentCallRecording.callRecorderFailureReason ?? '')
+ ? { callRecorderFailureReason: mergedCallRecorderFailureReason }
+ : {}),
+ };
+
+ if (!hasCallRecordingUpdateFields(updateData)) {
+ return;
+ }
+
+ const result = await client.mutation({
+ updateCallRecordings: {
+ __args: {
+ filter: {
+ id: { eq: callRecordingId },
+ status: { eq: CallRecordingStatus.PROCESSING },
+ externalBotId: isUndefined(externalBotId)
+ ? { is: 'NULL' }
+ : { eq: externalBotId },
+ callRecorderFailureReason: isUndefined(
+ currentCallRecording.callRecorderFailureReason,
+ )
+ ? { is: 'NULL' }
+ : { eq: currentCallRecording.callRecorderFailureReason },
+ and: [
+ ...(['audio', 'video'] as const)
+ .filter(
+ (field) =>
+ !isUndefined(updateData[field]) ||
+ failureReasons.some((reason) =>
+ reason.startsWith(`${field}_`),
+ ),
+ )
+ .map((field) => ({
+ or: [
+ { [field]: { is: 'NULL' as const } },
+ { [field]: { like: '[]' } },
+ ],
+ })),
+ ...(isUndefined(updateData.transcript)
+ ? []
+ : [
+ {
+ or: [
+ { transcript: { is: 'NULL' as const } },
+ ...(parseTranscriptMarker(updateData.transcript)
+ ?.status === 'PENDING'
+ ? []
+ : [
+ {
+ transcript: { like: '{%"status": "PENDING"%}' },
+ },
+ ]),
+ ],
+ },
+ ]),
+ ],
+ },
+ data: updateData,
+ },
+ id: true,
+ },
+ });
+
+ if (isNonEmptyArray(result.updateCallRecordings)) {
+ return;
+ }
+ }
+
+ throw new Error(
+ `Call recording ${callRecordingId} changed while saving import progress`,
+ );
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-claimed-call-recording-artifacts.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-claimed-call-recording-artifacts.util.ts
deleted file mode 100644
index b727de4d002..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/update-claimed-call-recording-artifacts.util.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-
-import { ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE } from 'src/logic-functions/constants/artifacts-import-claim-field-by-scope';
-import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
-import { hasCallRecordingUpdateFields } from 'src/logic-functions/domain/has-call-recording-update-fields.util';
-import { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';
-import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';
-
-export const updateClaimedCallRecordingArtifacts = async (
- client: CoreApiClient,
- {
- callRecordingId,
- scope,
- claimedAt,
- data,
- }: {
- callRecordingId: string;
- scope: CallRecordingArtifactImportScope;
- claimedAt: string;
- data: CallRecordingUpdateFields;
- },
-): Promise<void> => {
- if (!hasCallRecordingUpdateFields(data)) {
- return;
- }
-
- const result = await client.mutation({
- updateCallRecordings: {
- __args: {
- filter: {
- id: { eq: callRecordingId },
- status: { eq: CallRecordingStatus.PROCESSING },
- [ARTIFACTS_IMPORT_CLAIM_FIELD_BY_SCOPE[scope]]: { eq: claimedAt },
- },
- data,
- },
- id: true,
- },
- });
-
- if ((result.updateCallRecordings ?? []).length === 0) {
- throw new Error(
- `Artifact import claim for ${callRecordingId} is no longer active`,
- );
- }
-};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-expired-media-import-update.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-expired-media-import-update.test.ts
new file mode 100644
index 00000000000..4c711ad4fb9
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-expired-media-import-update.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildExpiredMediaImportUpdate } from 'src/logic-functions/domain/build-expired-media-import-update.util';
+
+describe('buildExpiredMediaImportUpdate', () => {
+ it.each(['audio', 'video'] as const)(
+ 'leaves the other artifact unresolved when %s sees source expiry',
+ (scope) => {
+ expect(
+ buildExpiredMediaImportUpdate({
+ audio: undefined,
+ video: undefined,
+ callRecorderFailureReason: undefined,
+ scope,
+ }),
+ ).toEqual({ callRecorderFailureReason: `${scope}_import_expired` });
+ },
+ );
+
+ it('keeps a saved video failure when a later audio import expires', () => {
+ expect(
+ buildExpiredMediaImportUpdate({
+ audio: undefined,
+ video: undefined,
+ callRecorderFailureReason: 'video_import_failed',
+ scope: 'audio',
+ }),
+ ).toEqual({
+ callRecorderFailureReason: 'video_import_failed,audio_import_expired',
+ });
+ });
+
+ it('leaves stored audio untouched when the video expires', () => {
+ expect(
+ buildExpiredMediaImportUpdate({
+ audio: [{ fileId: 'saved-audio' }],
+ video: undefined,
+ callRecorderFailureReason: undefined,
+ scope: 'video',
+ }),
+ ).toEqual({ callRecorderFailureReason: 'video_import_expired' });
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-expired-media-import-update.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-expired-media-import-update.util.ts
index 6b5a2fa03a3..b32cbb7e314 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-expired-media-import-update.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-expired-media-import-update.util.ts
@@ -13,18 +13,20 @@ export const buildExpiredMediaImportUpdate = ({
audio,
video,
callRecorderFailureReason,
+ scope,
}: {
audio: FilesFieldValue | undefined;
video: FilesFieldValue | undefined;
callRecorderFailureReason: string | undefined;
+ scope: 'audio' | 'video';
}): Pick<CallRecordingUpdateFields, 'callRecorderFailureReason'> => {
const { isAudioUnrecoverable, isVideoUnrecoverable } =
parseUnrecoverableMediaMarkers(callRecorderFailureReason);
const expiredFailureReasons = [
- ...(isNonEmptyArray(video) || isVideoUnrecoverable
+ ...(scope === 'audio' || isNonEmptyArray(video) || isVideoUnrecoverable
? []
: [VIDEO_IMPORT_EXPIRED_FAILURE_REASON]),
- ...(isNonEmptyArray(audio) || isAudioUnrecoverable
+ ...(scope === 'video' || isNonEmptyArray(audio) || isAudioUnrecoverable
? []
: [AUDIO_IMPORT_EXPIRED_FAILURE_REASON]),
];
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-reconcilable-call-recording-status.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-reconcilable-call-recording-status.util.ts
index 15845d91f12..70cbea731f1 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-reconcilable-call-recording-status.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/is-reconcilable-call-recording-status.util.ts
@@ -1,8 +1,9 @@
import { isUndefined } from '@sniptt/guards';
+import { type CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
import { RECONCILABLE_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/reconcilable-call-recording-statuses';
export const isReconcilableCallRecordingStatus = (
status: string | undefined,
-): status is string =>
+): status is CallRecordingStatus =>
!isUndefined(status) && RECONCILABLE_CALL_RECORDING_STATUSES.includes(status);
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-unrecoverable-media-markers.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-unrecoverable-media-markers.util.ts
index d09f6224f1f..9220a617e56 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-unrecoverable-media-markers.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-unrecoverable-media-markers.util.ts
@@ -7,6 +7,7 @@ import {
VIDEO_IMPORT_EXPIRED_FAILURE_REASON,
} from 'src/logic-functions/constants/media-import-expired-failure-reasons';
import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';
+import { VIDEO_IMPORT_FAILED_FAILURE_REASON } from 'src/logic-functions/constants/video-import-failed-failure-reason';
export type UnrecoverableMediaMarkers = {
isAudioUnrecoverable: boolean;
@@ -25,6 +26,7 @@ export const parseUnrecoverableMediaMarkers = (
failureReasons.includes(AUDIO_FILE_TOO_LARGE_FAILURE_REASON) ||
failureReasons.includes(AUDIO_IMPORT_EXPIRED_FAILURE_REASON),
isVideoUnrecoverable:
+ failureReasons.includes(VIDEO_IMPORT_FAILED_FAILURE_REASON) ||
failureReasons.includes(VIDEO_FILE_TOO_LARGE_FAILURE_REASON) ||
failureReasons.includes(VIDEO_IMPORT_EXPIRED_FAILURE_REASON),
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/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
index 31922b333b2..d3dff5dcd9f 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
@@ -7,9 +7,15 @@ import {
} from 'src/constants/universal-identifiers';
import { convergeDivergedCallRecordings } from 'src/logic-functions/flows/converge-diverged-call-recordings.util';
-const enqueueJobsMock = vi.hoisted(() => vi.fn());
+const { enqueueJobsMock, getJobsMock } = vi.hoisted(() => ({
+ enqueueJobsMock: vi.fn(),
+ getJobsMock: vi.fn(),
+}));
-vi.mock('twenty-sdk/logic-function', () => ({ enqueueJobs: enqueueJobsMock }));
+vi.mock('twenty-sdk/logic-function', () => ({
+ enqueueJobs: enqueueJobsMock,
+ getJobs: getJobsMock,
+}));
const NOW = new Date('2026-06-10T12:00:00.000Z');
@@ -49,11 +55,19 @@ const buildClient = (nodes: Candidate[]) => ({
});
const queuedBatches = (): EnqueuedBatch[] =>
- enqueueJobsMock.mock.calls.map(([batch]) => batch);
+ enqueueJobsMock.mock.calls.map(([batch]) => ({
+ ...batch,
+ payloads:
+ batch.payloads ??
+ batch.jobs.map(
+ (job: { payload: Record<string, unknown> }) => job.payload,
+ ),
+ }));
describe('convergeDivergedCallRecordings', () => {
beforeEach(() => {
enqueueJobsMock.mockReset().mockResolvedValue({ enqueued: true });
+ getJobsMock.mockReset().mockResolvedValue([]);
vi.stubGlobal(
'fetch',
vi.fn(() => {
@@ -76,7 +90,7 @@ describe('convergeDivergedCallRecordings', () => {
expect(client.mutation).not.toHaveBeenCalled();
});
- it('enqueues the existing media and transcript workers in one batch', async () => {
+ it('dispatches transcript, audio and video independently', async () => {
const client = buildClient([{ id: 'recording-1', status: 'PROCESSING' }]);
await convergeDivergedCallRecordings({
@@ -84,27 +98,49 @@ describe('convergeDivergedCallRecordings', () => {
now: NOW,
});
- expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({
- logicFunctionUniversalIdentifier:
- IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- retryLimit: 2,
- payloads: [
- {
- callRecordingId: 'recording-1',
- requestedAt: NOW.toISOString(),
- scope: 'transcript',
- },
- {
- callRecordingId: 'recording-1',
- requestedAt: NOW.toISOString(),
- scope: 'media',
- },
- ],
- });
+ expect(queuedBatches().flatMap(({ payloads }) => payloads)).toEqual(
+ ['transcript', 'audio', 'video'].map((scope) => ({
+ callRecordingId: 'recording-1',
+ requestedAt: NOW.toISOString(),
+ scope,
+ })),
+ );
expect(client.mutation).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
});
+ it.each([
+ { suffix: '-expired', state: 'ACTIVE' },
+ { suffix: '-recovery-2026-06-10', state: 'ACTIVE' },
+ { suffix: '-recovery-2026-06-09', state: 'ACTIVE' },
+ { suffix: '-recovery-2026-06-10', state: 'WAITING' },
+ { suffix: '-recovery-2026-06-10', state: 'DELAYED' },
+ ])(
+ 'leaves $state $suffix imports to the queue',
+ async ({ suffix, state }) => {
+ const client = buildClient([{ id: 'recording-1', status: 'PROCESSING' }]);
+ const activeJobIds = new Set(
+ ['transcript', 'audio', 'video'].map(
+ (scope) => `call-recorder-recording-1-${scope}${suffix}`,
+ ),
+ );
+
+ getJobsMock.mockImplementation(async (jobIds: string[]) =>
+ jobIds
+ .filter((jobId) => activeJobIds.has(jobId))
+ .map((jobId) => ({ jobId, state })),
+ );
+
+ await convergeDivergedCallRecordings({
+ client: client as unknown as CoreApiClient,
+ now: NOW,
+ });
+
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
+ expect(client.mutation).not.toHaveBeenCalled();
+ },
+ );
+
it('reaches every recording across pages, even when earlier recordings remain processing', async () => {
const nodes = Array.from({ length: 225 }, (_, index) => ({
id: `recording-${index}`,
@@ -120,7 +156,11 @@ describe('convergeDivergedCallRecordings', () => {
await runPage();
expect(client.query).toHaveBeenCalledTimes(1);
- expect(queuedBatches()[0].payloads).toHaveLength(200);
+ expect(
+ queuedBatches().flatMap(({ payloads }) =>
+ payloads.filter(({ scope }) => scope === 'transcript'),
+ ),
+ ).toHaveLength(100);
for (
let batchIndex = 0;
@@ -147,7 +187,7 @@ describe('convergeDivergedCallRecordings', () => {
)
.flatMap(({ payloads }) =>
payloads
- .filter(({ scope }) => scope === 'media')
+ .filter(({ scope }) => scope === 'video')
.map(({ callRecordingId }) => callRecordingId),
);
@@ -156,6 +196,9 @@ describe('convergeDivergedCallRecordings', () => {
expect(
queuedBatches().every(({ payloads }) => payloads.length <= 200),
).toBe(true);
+ expect(
+ getJobsMock.mock.calls.every(([jobIds]) => jobIds.length <= 200),
+ ).toBe(true);
});
it('recovers processing recordings without a bot id or a recent meeting date', async () => {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.ts
index 90532d5c4e5..b12f7b5d670 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/download-transcript.test.ts
@@ -117,4 +117,12 @@ describe('downloadTranscript', () => {
expect.stringContaining('socket leaked detail'),
);
});
+ it('settles a pending transcript whose provider resource now returns 404', async () => {
+ fetchMock.mockResolvedValue(new Response('{}', { status: 404 }));
+
+ await expect(
+ downloadTranscript({ transcriptId: 'recall-transcript-1' }),
+ ).resolves.toEqual({ outcome: 'deleted' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
});
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.ts
index 7f9e992af8e..c598ddfece0 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
@@ -1,10 +1,14 @@
import { type ClientRequest, type IncomingMessage } from 'node:http';
import { PassThrough, Readable } from 'node:stream';
+import { isUndefined } from '@sniptt/guards';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { importCallRecordingMedia } from 'src/logic-functions/flows/import-call-recording-media.util';
+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';
+
+const saveProgressMock = vi.fn().mockResolvedValue(undefined);
const mutationMock = vi.hoisted(() => vi.fn());
const requestOverHttpsMock = vi.hoisted(() => vi.fn());
@@ -186,6 +190,7 @@ describe('importCallRecordingMedia', () => {
vi.stubEnv('RECALL_API_KEY', 'recall-api-key');
vi.stubEnv('RECALL_REGION', 'us-west-2');
mutationMock.mockReset();
+ saveProgressMock.mockReset().mockResolvedValue(undefined);
stubUploadRequests();
buildRecallRecordingResponse = () =>
new Response(JSON.stringify(RECORDING_WITH_MEDIA), { status: 200 });
@@ -212,6 +217,7 @@ describe('importCallRecordingMedia', () => {
it('streams and uploads every missing artifact', async () => {
const { updateData } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -252,6 +258,7 @@ describe('importCallRecordingMedia', () => {
it('declares the presigned upload with the download size, folder and field identifier', async () => {
await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: true,
@@ -282,6 +289,7 @@ describe('importCallRecordingMedia', () => {
it('skips artifacts already on the record', async () => {
const { updateData } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -296,6 +304,7 @@ describe('importCallRecordingMedia', () => {
it('does not fetch the recording when both artifacts are present', async () => {
const { updateData } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: true,
@@ -330,6 +339,7 @@ describe('importCallRecordingMedia', () => {
});
const { updateData, hasRetryableFailure } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -338,8 +348,9 @@ describe('importCallRecordingMedia', () => {
expect(updateData).toEqual({
audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],
+ callRecorderFailureReason: 'video_import_failed',
});
- expect(hasRetryableFailure).toBe(true);
+ expect(hasRetryableFailure).toBe(false);
expect(cancelMock).toHaveBeenCalledTimes(1);
expect(getUploadRequestCall('video.mp4')).toBeUndefined();
expect(console.warn).toHaveBeenCalledWith(
@@ -347,7 +358,7 @@ describe('importCallRecordingMedia', () => {
);
});
- it('keeps the artifact it imported and asks for a redelivery when the other download has no content length', async () => {
+ it('keeps audio and settles video when its download has no content length', async () => {
const cancelMock = vi.fn().mockRejectedValue(new Error('cancel exploded'));
stubFetch({
@@ -360,6 +371,7 @@ describe('importCallRecordingMedia', () => {
});
const { updateData, hasRetryableFailure } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -368,8 +380,9 @@ describe('importCallRecordingMedia', () => {
expect(updateData).toEqual({
audio: [{ fileId: 'file-audio-1', label: 'audio.mp3' }],
+ callRecorderFailureReason: 'video_import_failed',
});
- expect(hasRetryableFailure).toBe(true);
+ expect(hasRetryableFailure).toBe(false);
expect(getUploadRequestCall('video.mp4')).toBeUndefined();
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining('content-length'),
@@ -386,6 +399,7 @@ describe('importCallRecordingMedia', () => {
});
const mediaImportResult = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -395,6 +409,7 @@ describe('importCallRecordingMedia', () => {
expect(mediaImportResult).toEqual({
updateData: {},
hasRetryableFailure: false,
+ isRecordingGone: false,
});
expect(mutationMock).not.toHaveBeenCalled();
});
@@ -407,6 +422,7 @@ describe('importCallRecordingMedia', () => {
vi.useFakeTimers();
const mediaImportResultPromise = importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -418,6 +434,7 @@ describe('importCallRecordingMedia', () => {
expect(mediaImportResult).toEqual({
updateData: {},
hasRetryableFailure: true,
+ isRecordingGone: false,
});
expect(mutationMock).not.toHaveBeenCalled();
expect(console.warn).toHaveBeenCalledWith(
@@ -439,6 +456,7 @@ describe('importCallRecordingMedia', () => {
});
const { updateData } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -464,6 +482,7 @@ describe('importCallRecordingMedia', () => {
new Response(JSON.stringify({ detail: 'Not found.' }), { status: 404 });
const mediaImportResult = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -478,11 +497,12 @@ describe('importCallRecordingMedia', () => {
expect(mutationMock).not.toHaveBeenCalled();
});
- it('records an expired marker for a deleted artifact', async () => {
+ it('records an expired marker for a deleted artifact without an expiry field', async () => {
buildRecallRecordingResponse = () =>
new Response(
JSON.stringify({
id: 'recall-recording-1',
+ expires_at: '2026-09-14T14:09:46.365456Z',
media_shortcuts: {
video_mixed: { status: { code: 'deleted' } },
audio_mixed: { download_url: AUDIO_URL, status: { code: 'done' } },
@@ -497,6 +517,7 @@ describe('importCallRecordingMedia', () => {
});
const mediaImportResult = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -509,6 +530,7 @@ describe('importCallRecordingMedia', () => {
callRecorderFailureReason: 'video_import_expired',
},
hasRetryableFailure: false,
+ isRecordingGone: false,
});
expect(getUploadRequestCall('video.mp4')).toBeUndefined();
});
@@ -526,6 +548,7 @@ describe('importCallRecordingMedia', () => {
});
const { updateData } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: false,
@@ -548,6 +571,7 @@ describe('importCallRecordingMedia', () => {
});
const { updateData } = await importCallRecordingMedia({
+ saveProgress: saveProgressMock,
callRecordingId: 'call-recording-1',
externalRecordingId: 'recall-recording-1',
hasAudio: true,
@@ -558,4 +582,97 @@ describe('importCallRecordingMedia', () => {
video: [{ fileId: 'file-video-1', label: 'video.mp4' }],
});
});
+ it('checkpoints video before audio fails and resumes with only the missing file', async () => {
+ const saved: Pick<CallRecordingUpdateFields, 'audio' | 'video'> = {};
+ saveProgressMock.mockImplementation(async (data) =>
+ Object.assign(saved, data),
+ );
+ const fetchImplementation = fetchMock.getMockImplementation();
+
+ fetchMock.mockImplementation((url, options) => {
+ if (url === AUDIO_URL) {
+ expect(saved.video).toEqual([
+ { fileId: 'file-video-1', label: 'video.mp4' },
+ ]);
+ return Promise.reject(
+ new DOMException('Transfer timed out', 'TimeoutError'),
+ );
+ }
+ return fetchImplementation?.(url, options);
+ });
+
+ const firstAttempt = await importCallRecordingMedia({
+ callRecordingId: 'call-recording-1',
+ externalRecordingId: 'recall-recording-1',
+ hasVideo: false,
+ hasAudio: false,
+ saveProgress: saveProgressMock,
+ });
+
+ expect(firstAttempt.hasRetryableFailure).toBe(true);
+ expect(saved.audio).toBeUndefined();
+
+ stubFetch({
+ downloadsByUrl: {
+ [AUDIO_URL]: buildDownloadResponse({ contentLengthBytes: 8 }),
+ },
+ });
+ const secondAttempt = await importCallRecordingMedia({
+ callRecordingId: 'call-recording-1',
+ externalRecordingId: 'recall-recording-1',
+ hasVideo: !isUndefined(saved.video),
+ hasAudio: false,
+ saveProgress: saveProgressMock,
+ });
+
+ expect(secondAttempt.hasRetryableFailure).toBe(false);
+ expect(saved.audio).toEqual([
+ { fileId: 'file-audio-1', label: 'audio.mp3' },
+ ]);
+ expect(fetchMock.mock.calls.some(([url]) => url === VIDEO_URL)).toBe(false);
+ });
+
+ it('stops before the next transfer when saving the first file fails', async () => {
+ saveProgressMock.mockRejectedValue(new Error('Progress save failed'));
+
+ await expect(
+ importCallRecordingMedia({
+ callRecordingId: 'call-recording-1',
+ externalRecordingId: 'recall-recording-1',
+ hasVideo: false,
+ hasAudio: false,
+ saveProgress: saveProgressMock,
+ }),
+ ).rejects.toThrow('Progress save failed');
+
+ expect(fetchMock.mock.calls.some(([url]) => url === AUDIO_URL)).toBe(false);
+ });
+
+ it('keeps an existing size marker while settling the other expired artifact', async () => {
+ buildRecallRecordingResponse = () =>
+ new Response(
+ JSON.stringify({
+ media_shortcuts: {
+ video_mixed: { status: { code: 'deleted' } },
+ audio_mixed: { status: { code: 'deleted' } },
+ },
+ }),
+ { status: 200 },
+ );
+
+ const result = await importCallRecordingMedia({
+ callRecordingId: 'call-recording-1',
+ externalRecordingId: 'recall-recording-1',
+ hasVideo: false,
+ hasAudio: false,
+ callRecorderFailureReason: 'video_file_too_large',
+ saveProgress: saveProgressMock,
+ });
+
+ expect(result.updateData).toEqual({
+ callRecorderFailureReason: 'video_file_too_large,audio_import_expired',
+ });
+ expect(saveProgressMock).toHaveBeenCalledExactlyOnceWith(result.updateData);
+ expect(requestOverHttpsMock).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/put-media-download-body-to-upload-target.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/put-media-download-body-to-upload-target.test.ts
index 1f2115c6a2a..73df2cafae8 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/put-media-download-body-to-upload-target.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/put-media-download-body-to-upload-target.test.ts
@@ -7,17 +7,15 @@ const requestOverHttpMock = vi.hoisted(() => vi.fn());
const requestOverHttpsMock = vi.hoisted(() => vi.fn());
vi.mock('node:http', async () => {
- const actualHttp = await vi.importActual<typeof import('node:http')>(
- 'node:http',
- );
+ const actualHttp =
+ await vi.importActual<typeof import('node:http')>('node:http');
return { ...actualHttp, request: requestOverHttpMock };
});
vi.mock('node:https', async () => {
- const actualHttps = await vi.importActual<typeof import('node:https')>(
- 'node:https',
- );
+ const actualHttps =
+ await vi.importActual<typeof import('node:https')>('node:https');
return { ...actualHttps, request: requestOverHttpsMock };
});
@@ -98,13 +96,16 @@ const buildUploadRequest = ({
const putDefaultMediaDownloadBodyToUploadTarget = ({
mediaDownloadBody = buildMediaDownloadBody(),
uploadUrl = HTTPS_UPLOAD_URL,
+ signal = new AbortController().signal,
}: {
mediaDownloadBody?: ReadableStream<Uint8Array>;
uploadUrl?: string;
+ signal?: AbortSignal;
} = {}) =>
putMediaDownloadBodyToUploadTarget({
fileName: 'video.mp4',
mediaDownloadBody,
+ signal,
sizeBytes: 4,
uploadTarget: {
uploadUrl,
@@ -131,7 +132,8 @@ describe('putMediaDownloadBodyToUploadTarget', () => {
await putDefaultMediaDownloadBodyToUploadTarget();
- const [uploadUrl, uploadRequestOptions] = requestOverHttpsMock.mock.calls[0];
+ const [uploadUrl, uploadRequestOptions] =
+ requestOverHttpsMock.mock.calls[0];
expect(uploadUrl.href).toBe(HTTPS_UPLOAD_URL);
expect(uploadRequestOptions).toMatchObject({
@@ -207,4 +209,30 @@ describe('putMediaDownloadBodyToUploadTarget', () => {
expect(mediaDownloadBodyCancelMock).toHaveBeenCalledTimes(1);
});
+ it('aborts an in-flight upload and cancels the download when the work deadline expires', async () => {
+ const abortController = new AbortController();
+ const cancelDownload = vi.fn();
+ const { uploadRequest } = buildUploadRequest();
+ requestOverHttpsMock.mockReturnValue(uploadRequest);
+
+ const transfer = putDefaultMediaDownloadBodyToUploadTarget({
+ mediaDownloadBody: buildMediaDownloadBody({
+ chunks: [],
+ close: false,
+ cancel: cancelDownload,
+ }),
+ signal: abortController.signal,
+ });
+ const assertion = expect(transfer).rejects.toMatchObject({
+ name: 'AbortError',
+ });
+
+ abortController.abort(
+ new DOMException('Import work deadline', 'TimeoutError'),
+ );
+ await assertion;
+
+ expect(uploadRequest.destroyed).toBe(true);
+ expect(cancelDownload).toHaveBeenCalledTimes(1);
+ });
});
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.ts
index 3292f7edc2f..c2fb47b7fcd 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts
@@ -1,16 +1,14 @@
import { isUndefined } from '@sniptt/guards';
import { type CoreApiClient } from 'twenty-client-sdk/core';
-import {
- IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
-} from 'src/constants/universal-identifiers';
+import { STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { CALL_RECORDING_ARTIFACT_IMPORT_SCOPES } from 'src/logic-functions/constants/call-recording-artifact-import-scopes';
import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
import { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';
import { TWENTY_PAGE_SIZE } from 'src/logic-functions/constants/twenty-page-size';
import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';
+import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';
import { type ConnectionPage } from 'src/logic-functions/data/fetch-all-nodes.util';
import { type ConvergeDivergedCallRecordingsResult } from 'src/logic-functions/flows/converge-diverged-call-recordings-result.type';
import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';
@@ -83,19 +81,13 @@ export const convergeDivergedCallRecordings = async ({
throw new Error('Call recording recovery returned an invalid next cursor');
}
- const importPayloads: Record<string, unknown>[] = [];
+ const importCallRecordingIds: string[] = [];
const reconcilePayloads: Record<string, unknown>[] = [];
const enqueuedCallRecordingIds: string[] = [];
for (const { node } of page.edges ?? []) {
if (node.status === CallRecordingStatus.PROCESSING) {
- for (const scope of CALL_RECORDING_ARTIFACT_IMPORT_SCOPES) {
- importPayloads.push({
- callRecordingId: node.id,
- requestedAt: now.toISOString(),
- scope,
- });
- }
+ importCallRecordingIds.push(node.id);
} else {
const startsAt = node.calendarEvent?.startsAt;
@@ -112,10 +104,11 @@ export const convergeDivergedCallRecordings = async ({
enqueuedCallRecordingIds.push(node.id);
}
- await enqueueLogicFunctionJobs({
- logicFunctionUniversalIdentifier:
- IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- payloads: importPayloads,
+ await enqueueCallRecordingArtifactsImport({
+ callRecordingIds: importCallRecordingIds,
+ scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,
+ trigger: 'recovery',
+ requestedAt: now.toISOString(),
});
await enqueueLogicFunctionJobs({
logicFunctionUniversalIdentifier:
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.ts
index 59aefa880e8..ba3827edca7 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/download-transcript.util.ts
@@ -2,6 +2,7 @@ import { isUndefined } from '@sniptt/guards';
import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';
import { retrieveRecallTranscript } from 'src/logic-functions/recall-api/retrieve-recall-transcript.util';
+import { buildAbortSignalWithTimeout } from 'src/logic-functions/utils/build-abort-signal-with-timeout.util';
const TRANSCRIPT_DOWNLOAD_TIMEOUT_MS = 20_000;
@@ -14,10 +15,15 @@ export type DownloadTranscriptResult =
export const downloadTranscript = async ({
transcriptId,
+ signal,
}: {
transcriptId: string;
+ signal?: AbortSignal;
}): Promise<DownloadTranscriptResult> => {
- const retrieveResult = await retrieveRecallTranscript({ transcriptId });
+ const retrieveResult = await retrieveRecallTranscript({
+ transcriptId,
+ signal,
+ });
if (!retrieveResult.ok) {
return retrieveResult.status === RECALL_API_NOT_FOUND_STATUS
@@ -28,7 +34,7 @@ export const downloadTranscript = async ({
const { downloadUrl, statusCode, statusSubCode } = retrieveResult.transcript;
if (!isUndefined(downloadUrl)) {
- return downloadTranscriptContent(downloadUrl);
+ return downloadTranscriptContent({ downloadUrl, signal });
}
if (statusCode === 'error' || statusCode === 'failed') {
@@ -42,12 +48,19 @@ export const downloadTranscript = async ({
return { outcome: 'pending' };
};
-const downloadTranscriptContent = async (
- downloadUrl: string,
-): Promise<DownloadTranscriptResult> => {
+const downloadTranscriptContent = async ({
+ downloadUrl,
+ signal,
+}: {
+ downloadUrl: string;
+ signal?: AbortSignal;
+}): Promise<DownloadTranscriptResult> => {
try {
const response = await fetch(downloadUrl, {
- signal: AbortSignal.timeout(TRANSCRIPT_DOWNLOAD_TIMEOUT_MS),
+ signal: buildAbortSignalWithTimeout({
+ timeoutMs: TRANSCRIPT_DOWNLOAD_TIMEOUT_MS,
+ signal,
+ }),
});
if (!response.ok) {
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.ts
index 438168c38e4..277975033ba 100644
--- 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.ts
@@ -7,6 +7,7 @@ import {
} 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 { fetchWithTimeout } from 'src/logic-functions/utils/fetch-with-timeout.util';
import { getString } from 'src/logic-functions/utils/get-string.util';
type HandleCallRecordingArtifactsImportJobResult =
@@ -28,7 +29,7 @@ export const handleCallRecordingArtifactsImportJob = async (
if (
isUndefined(callRecordingId) ||
isUndefined(requestedAt) ||
- (scope !== 'transcript' && scope !== 'media')
+ (scope !== 'transcript' && scope !== 'audio' && scope !== 'video')
) {
return {
status: 'skipped',
@@ -39,7 +40,7 @@ export const handleCallRecordingArtifactsImportJob = async (
try {
return await importCallRecordingArtifacts({
- client: new CoreApiClient(),
+ client: new CoreApiClient({ fetch: fetchWithTimeout }),
request: { callRecordingId, requestedAt },
scope,
});
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.ts
index e42f2c5fa7c..3a5f876ecf5 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,8 +140,12 @@ const handleRecallStatusEvent = async ({
})
) {
await enqueueCallRecordingArtifactsImport({
- callRecordingId: callRecording.id,
+ callRecordingIds: [callRecording.id],
scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,
+ trigger:
+ event === 'recording.deleted' || statusCode === 'media_expired'
+ ? 'expired'
+ : 'recording',
});
}
@@ -178,8 +182,9 @@ const queueCallRecordingArtifactsImport = async ({
}
await enqueueCallRecordingArtifactsImport({
- callRecordingId: callRecording.id,
+ callRecordingIds: [callRecording.id],
scopes: ['transcript'],
+ trigger: 'transcript-ready',
});
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.ts
index e263a5bb27e..5d5bc425d8e 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,15 +1,19 @@
import { isNonEmptyArray, isUndefined } from '@sniptt/guards';
import { type CoreApiClient } from 'twenty-client-sdk/core';
+import {
+ ARTIFACT_IMPORT_WORK_BUDGET_MS,
+ VIDEO_IMPORT_WORK_BUDGET_MS,
+} from 'src/logic-functions/constants/artifact-import-work-budget-ms';
import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';
import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';
-import { updateClaimedCallRecordingArtifacts } from 'src/logic-functions/data/update-claimed-call-recording-artifacts.util';
import { buildCallRecordingSyncUpdate } from 'src/logic-functions/domain/build-call-recording-sync-update.util';
import { buildExpiredMediaImportUpdate } from 'src/logic-functions/domain/build-expired-media-import-update.util';
import { hasCallRecordingUpdateFields } from 'src/logic-functions/domain/has-call-recording-update-fields.util';
import { importCallRecordingMedia } from 'src/logic-functions/flows/import-call-recording-media.util';
import { importCallRecordingTranscript } from 'src/logic-functions/flows/import-call-recording-transcript.util';
-import { runCallRecordingArtifactImportWithClaim } from 'src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util';
+import { findCallRecordingForArtifactsImport } from 'src/logic-functions/data/find-call-recording-for-artifacts-import.util';
+import { saveCallRecordingImportProgress } from 'src/logic-functions/data/save-call-recording-import-progress.util';
import { settleCallRecordingImport } from 'src/logic-functions/flows/settle-call-recording-import.util';
import { extractRecallBotSyncState } from 'src/logic-functions/recall-api/extract-recall-bot-sync-state.util';
import { getRecallBot } from 'src/logic-functions/recall-api/get-recall-bot.util';
@@ -32,6 +36,8 @@ export type ImportCallRecordingArtifactsResult =
reason: string;
};
+type SaveProgress = (data: CallRecordingUpdateFields) => Promise<void>;
+
type RecallBotSyncResult = {
externalRecordingId: string | undefined;
isMediaExpired: boolean;
@@ -54,98 +60,99 @@ export const importCallRecordingArtifacts = async ({
request: CallRecordingArtifactsImportRequest;
scope: CallRecordingArtifactImportScope;
}): Promise<ImportCallRecordingArtifactsResult> => {
- const now = new Date();
- const saveUnderClaim = (data: CallRecordingUpdateFields) =>
- updateClaimedCallRecordingArtifacts(client, {
+ const signal = AbortSignal.timeout(
+ scope === 'video'
+ ? VIDEO_IMPORT_WORK_BUDGET_MS
+ : ARTIFACT_IMPORT_WORK_BUDGET_MS,
+ );
+ const callRecording = await findCallRecordingForArtifactsImport(
+ client,
+ request.callRecordingId,
+ );
+
+ if (
+ isUndefined(callRecording) ||
+ callRecording.status !== CallRecordingStatus.PROCESSING
+ ) {
+ return {
+ status: 'skipped',
callRecordingId: request.callRecordingId,
scope,
- claimedAt: now.toISOString(),
+ reason: 'call recording is not processing',
+ };
+ }
+
+ const saveProgress: SaveProgress = (data) =>
+ saveCallRecordingImportProgress(client, {
+ callRecordingId: callRecording.id,
+ externalBotId: callRecording.externalBotId,
data,
});
- const artifactImportExecution = await runCallRecordingArtifactImportWithClaim(
- {
- client,
- callRecordingId: request.callRecordingId,
+ const botSync = await syncRecallBotState({ callRecording, signal });
+
+ await saveProgress(botSync.updateData);
+
+ if (
+ !isUndefined(botSync.updateData.status) &&
+ botSync.updateData.status !== CallRecordingStatus.PROCESSING
+ ) {
+ return {
+ status: 'skipped',
+ callRecordingId: callRecording.id,
scope,
- now,
- runImport: async (callRecording) => {
- const botSync = await syncRecallBotState(callRecording);
-
- if (
- !isUndefined(botSync.updateData.status) &&
- botSync.updateData.status !== CallRecordingStatus.PROCESSING
- ) {
- await saveUnderClaim(botSync.updateData);
-
- return {
- status: 'skipped',
- callRecordingId: callRecording.id,
- scope,
- reason: 'call recording is not processing',
- } satisfies ImportCallRecordingArtifactsResult;
- }
-
- const scopeArtifactsImport = await importScopeArtifacts({
- callRecording,
- scope,
- requestedAt: request.requestedAt,
- externalRecordingId: botSync.externalRecordingId,
- isMediaExpired: botSync.isMediaExpired,
- });
-
- const updateData = {
- ...botSync.updateData,
- ...scopeArtifactsImport.updateData,
- };
-
- // Artifacts that landed are kept even when a sibling must be retried.
- await saveUnderClaim(updateData);
-
- if (scopeArtifactsImport.hasRetryableFailure) {
- throw new Error(
- `Recall ${scope} artifacts for call recording ${callRecording.id} could not be imported`,
- );
- }
-
- const hasSettled = await settleCallRecordingImport(client, {
- callRecordingId: callRecording.id,
- });
-
- if (!hasCallRecordingUpdateFields(updateData) && !hasSettled) {
- 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;
- },
- },
- );
+ reason: 'call recording is not processing',
+ };
+ }
- if (artifactImportExecution.status === 'skipped') {
+ const scopeArtifactsImport = await importScopeArtifacts({
+ callRecording,
+ scope,
+ requestedAt: request.requestedAt,
+ externalRecordingId: botSync.externalRecordingId,
+ isMediaExpired: botSync.isMediaExpired,
+ saveProgress,
+ signal,
+ });
+
+ if (scopeArtifactsImport.hasRetryableFailure) {
+ throw new Error(
+ `Recall ${scope} artifacts for call recording ${callRecording.id} could not be imported`,
+ );
+ }
+
+ // A video deadline is a saved terminal outcome; settlement still needs to run.
+ const hasSettled = await settleCallRecordingImport(client, {
+ callRecordingId: callRecording.id,
+ });
+ const hasUpdates =
+ hasCallRecordingUpdateFields(botSync.updateData) ||
+ hasCallRecordingUpdateFields(scopeArtifactsImport.updateData);
+
+ if (!hasUpdates && !hasSettled) {
return {
status: 'skipped',
- callRecordingId: request.callRecordingId,
+ callRecordingId: callRecording.id,
scope,
- reason: 'no claimable processing call recording',
+ reason: 'no artifact updates',
};
}
- return artifactImportExecution.result;
+ return {
+ status: 'imported',
+ callRecordingId: callRecording.id,
+ scope,
+ outcome: 'call-recording-artifacts-imported',
+ };
};
// One GET /bot fills whatever the webhooks did not deliver; a vanished bot means its media is gone too.
-const syncRecallBotState = async (
- callRecording: CallRecordingForArtifactsImport,
-): Promise<RecallBotSyncResult> => {
+const syncRecallBotState = async ({
+ callRecording,
+ signal,
+}: {
+ callRecording: CallRecordingForArtifactsImport;
+ signal: AbortSignal;
+}): Promise<RecallBotSyncResult> => {
const hasCompleteBotState =
!isUndefined(callRecording.externalRecordingId) &&
!isUndefined(callRecording.startedAt) &&
@@ -161,6 +168,7 @@ const syncRecallBotState = async (
const botResult = await getRecallBot({
externalBotId: callRecording.externalBotId,
+ signal,
});
if (!botResult.ok) {
@@ -191,29 +199,42 @@ const importScopeArtifacts = async ({
requestedAt,
externalRecordingId,
isMediaExpired,
+ saveProgress,
+ signal,
}: {
callRecording: CallRecordingForArtifactsImport;
scope: CallRecordingArtifactImportScope;
requestedAt: string;
externalRecordingId: string | undefined;
isMediaExpired: boolean;
+ saveProgress: SaveProgress;
+ signal: AbortSignal;
}): Promise<ScopeArtifactsImportResult> => {
if (scope === 'transcript') {
- return importCallRecordingTranscript({
+ const transcriptImport = await importCallRecordingTranscript({
callRecordingId: callRecording.id,
currentStatus: callRecording.status,
externalRecordingId,
requestedAt,
transcript: callRecording.transcript,
isMediaExpired,
+ signal,
});
+
+ await saveProgress(transcriptImport.updateData);
+
+ return transcriptImport;
}
if (isMediaExpired) {
- return {
- updateData: buildExpiredMediaImportUpdate(callRecording),
- hasRetryableFailure: false,
- };
+ const updateData = buildExpiredMediaImportUpdate({
+ ...callRecording,
+ scope,
+ });
+
+ await saveProgress(updateData);
+
+ return { updateData, hasRetryableFailure: false };
}
if (isUndefined(externalRecordingId)) {
@@ -223,17 +244,20 @@ const importScopeArtifacts = async ({
const mediaImport = await importCallRecordingMedia({
callRecordingId: callRecording.id,
externalRecordingId,
- hasAudio: isNonEmptyArray(callRecording.audio),
- hasVideo: isNonEmptyArray(callRecording.video),
+ hasAudio: scope === 'video' || isNonEmptyArray(callRecording.audio),
+ hasVideo: scope === 'audio' || isNonEmptyArray(callRecording.video),
+ callRecorderFailureReason: callRecording.callRecorderFailureReason,
+ saveProgress,
+ signal,
});
+ const expiredMediaUpdate = mediaImport.isRecordingGone
+ ? buildExpiredMediaImportUpdate({ ...callRecording, scope })
+ : {};
+
+ await saveProgress(expiredMediaUpdate);
return {
- updateData: {
- ...mediaImport.updateData,
- ...(mediaImport.isRecordingGone === true
- ? buildExpiredMediaImportUpdate(callRecording)
- : {}),
- },
+ updateData: { ...mediaImport.updateData, ...expiredMediaUpdate },
hasRetryableFailure: mediaImport.hasRetryableFailure,
};
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-media.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-media.util.ts
index fa3f2da6f60..e4b3e3d4847 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
@@ -7,6 +7,8 @@ import {
} from 'src/constants/universal-identifiers';
import { CALL_RECORDER_MAX_MEDIA_FILE_SIZE_BYTES } from 'src/logic-functions/constants/call-recorder-max-media-file-size-bytes';
import { RECALL_API_NOT_FOUND_STATUS } from 'src/logic-functions/constants/recall-api-not-found-status';
+import { VIDEO_IMPORT_WORK_BUDGET_MS } from 'src/logic-functions/constants/artifact-import-work-budget-ms';
+import { VIDEO_IMPORT_FAILED_FAILURE_REASON } from 'src/logic-functions/constants/video-import-failed-failure-reason';
import {
AUDIO_FILE_TOO_LARGE_FAILURE_REASON,
VIDEO_FILE_TOO_LARGE_FAILURE_REASON,
@@ -15,11 +17,15 @@ import {
AUDIO_IMPORT_EXPIRED_FAILURE_REASON,
VIDEO_IMPORT_EXPIRED_FAILURE_REASON,
} from 'src/logic-functions/constants/media-import-expired-failure-reasons';
+import { appendCallRecorderFailureReasons } from 'src/logic-functions/domain/append-call-recorder-failure-reasons.util';
+import { parseUnrecoverableMediaMarkers } from 'src/logic-functions/domain/parse-unrecoverable-media-markers.util';
import { putMediaDownloadBodyToUploadTarget } from 'src/logic-functions/flows/put-media-download-body-to-upload-target.util';
import { extractRecallMediaArtifacts } from 'src/logic-functions/recall-api/extract-recall-media-artifacts.util';
import { getRecallRecording } from 'src/logic-functions/recall-api/get-recall-recording.util';
import { type CallRecordingMediaFile } from 'src/logic-functions/types/call-recording-media-file.type';
import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';
+import { buildAbortSignalWithTimeout } from 'src/logic-functions/utils/build-abort-signal-with-timeout.util';
+import { fetchWithTimeout } from 'src/logic-functions/utils/fetch-with-timeout.util';
import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';
type CallRecordingMediaUpdateFields = Pick<
@@ -31,7 +37,7 @@ type ImportCallRecordingMediaResult = {
updateData: CallRecordingMediaUpdateFields;
hasRetryableFailure: boolean;
// Recall answers 404 for a recording whose media retention has elapsed.
- isRecordingGone?: true;
+ isRecordingGone: boolean;
};
type ImportMediaArtifactResult =
@@ -49,7 +55,7 @@ type MediaUploadTarget = {
contentType: string;
};
-const MEDIA_DOWNLOAD_TIMEOUT_MS = 120_000;
+const MEDIA_TRANSFER_TIMEOUT_MS = 120_000;
const MEDIA_FILE_FOLDER = 'FilesField';
const MEDIA_ARTIFACT_DESCRIPTORS = [
@@ -60,6 +66,7 @@ const MEDIA_ARTIFACT_DESCRIPTORS = [
CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER,
tooLargeFailureReason: VIDEO_FILE_TOO_LARGE_FAILURE_REASON,
expiredFailureReason: VIDEO_IMPORT_EXPIRED_FAILURE_REASON,
+ timeoutMs: VIDEO_IMPORT_WORK_BUDGET_MS,
},
{
field: 'audio',
@@ -68,6 +75,7 @@ const MEDIA_ARTIFACT_DESCRIPTORS = [
CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER,
tooLargeFailureReason: AUDIO_FILE_TOO_LARGE_FAILURE_REASON,
expiredFailureReason: AUDIO_IMPORT_EXPIRED_FAILURE_REASON,
+ timeoutMs: MEDIA_TRANSFER_TIMEOUT_MS,
},
] as const;
@@ -76,17 +84,36 @@ export const importCallRecordingMedia = async ({
externalRecordingId,
hasAudio,
hasVideo,
+ callRecorderFailureReason,
+ saveProgress,
+ signal,
}: {
callRecordingId: string;
externalRecordingId: string;
hasAudio: boolean;
hasVideo: boolean;
+ callRecorderFailureReason?: string;
+ saveProgress: (data: CallRecordingMediaUpdateFields) => Promise<void>;
+ signal?: AbortSignal;
}): Promise<ImportCallRecordingMediaResult> => {
- if (hasAudio && hasVideo) {
- return { updateData: {}, hasRetryableFailure: false };
+ const { isAudioUnrecoverable, isVideoUnrecoverable } =
+ parseUnrecoverableMediaMarkers(callRecorderFailureReason);
+
+ if (
+ (hasAudio || isAudioUnrecoverable) &&
+ (hasVideo || isVideoUnrecoverable)
+ ) {
+ return {
+ updateData: {},
+ hasRetryableFailure: false,
+ isRecordingGone: false,
+ };
}
- const recordingResult = await getRecallRecording({ externalRecordingId });
+ const recordingResult = await getRecallRecording({
+ externalRecordingId,
+ signal,
+ });
if (!recordingResult.ok) {
console.warn(
@@ -101,17 +128,40 @@ export const importCallRecordingMedia = async ({
};
}
- return { updateData: {}, hasRetryableFailure: true };
+ return {
+ updateData: {},
+ hasRetryableFailure: true,
+ isRecordingGone: false,
+ };
}
const mediaArtifacts = extractRecallMediaArtifacts(recordingResult.recording);
- const metadataClient = new MetadataApiClient();
+ const metadataClient = new MetadataApiClient({
+ fetch: fetchWithTimeout,
+ signal,
+ });
const updateFields: CallRecordingMediaUpdateFields = {};
const unrecoverableFailureReasons: string[] = [];
+ const recordUnrecoverableFailure = async (failureReason: string) => {
+ unrecoverableFailureReasons.push(failureReason);
+ updateFields.callRecorderFailureReason = appendCallRecorderFailureReasons({
+ callRecorderFailureReason,
+ failureReasons: unrecoverableFailureReasons,
+ });
+ await saveProgress({
+ callRecorderFailureReason: updateFields.callRecorderFailureReason,
+ });
+ };
const failedMediaArtifactFields: string[] = [];
const artifactStateByField = {
- video: { alreadyImported: hasVideo, artifact: mediaArtifacts.video },
- audio: { alreadyImported: hasAudio, artifact: mediaArtifacts.audio },
+ video: {
+ alreadyImported: hasVideo || isVideoUnrecoverable,
+ artifact: mediaArtifacts.video,
+ },
+ audio: {
+ alreadyImported: hasAudio || isAudioUnrecoverable,
+ artifact: mediaArtifacts.audio,
+ },
};
for (const descriptor of MEDIA_ARTIFACT_DESCRIPTORS) {
@@ -123,7 +173,7 @@ export const importCallRecordingMedia = async ({
}
if (artifact.statusCode === 'deleted') {
- unrecoverableFailureReasons.push(descriptor.expiredFailureReason);
+ await recordUnrecoverableFailure(descriptor.expiredFailureReason);
continue;
}
@@ -142,29 +192,32 @@ export const importCallRecordingMedia = async ({
fieldMetadataUniversalIdentifier:
descriptor.fieldMetadataUniversalIdentifier,
maxMediaFileSizeBytes: CALL_RECORDER_MAX_MEDIA_FILE_SIZE_BYTES,
+ timeoutMs: descriptor.timeoutMs,
+ signal,
});
if (importResult.outcome === 'imported') {
+ await saveProgress({ [descriptor.field]: importResult.files });
updateFields[descriptor.field] = importResult.files;
}
if (importResult.outcome === 'too-large') {
- unrecoverableFailureReasons.push(descriptor.tooLargeFailureReason);
+ await recordUnrecoverableFailure(descriptor.tooLargeFailureReason);
}
if (importResult.outcome === 'failed') {
- failedMediaArtifactFields.push(descriptor.field);
+ if (descriptor.field === 'video') {
+ await recordUnrecoverableFailure(VIDEO_IMPORT_FAILED_FAILURE_REASON);
+ } else {
+ failedMediaArtifactFields.push(descriptor.field);
+ }
}
}
- if (unrecoverableFailureReasons.length > 0) {
- updateFields.callRecorderFailureReason =
- unrecoverableFailureReasons.join(',');
- }
-
return {
updateData: updateFields,
hasRetryableFailure: isNonEmptyArray(failedMediaArtifactFields),
+ isRecordingGone: false,
};
};
@@ -175,6 +228,8 @@ const importMediaArtifact = async ({
fileName,
fieldMetadataUniversalIdentifier,
maxMediaFileSizeBytes,
+ timeoutMs,
+ signal,
}: {
callRecordingId: string;
metadataClient: InstanceType<typeof MetadataApiClient>;
@@ -182,13 +237,21 @@ const importMediaArtifact = async ({
fileName: string;
fieldMetadataUniversalIdentifier: string;
maxMediaFileSizeBytes: number;
+ timeoutMs: number;
+ signal?: AbortSignal;
}): Promise<ImportMediaArtifactResult> => {
+ const transferSignal = buildAbortSignalWithTimeout({
+ timeoutMs,
+ signal,
+ });
+
try {
const download = await openMediaDownload({
callRecordingId,
fileName,
url,
maxMediaFileSizeBytes,
+ signal: transferSignal,
});
if (download.outcome === 'too-large') {
@@ -206,6 +269,7 @@ const importMediaArtifact = async ({
fieldMetadataUniversalIdentifier,
body: download.body,
sizeBytes: download.sizeBytes,
+ signal: transferSignal,
});
return {
@@ -226,14 +290,16 @@ const openMediaDownload = async ({
fileName,
url,
maxMediaFileSizeBytes,
+ signal,
}: {
callRecordingId: string;
fileName: string;
url: string;
maxMediaFileSizeBytes: number;
+ signal: AbortSignal;
}): Promise<OpenMediaDownloadResult> => {
const response = await fetch(url, {
- signal: AbortSignal.timeout(MEDIA_DOWNLOAD_TIMEOUT_MS),
+ signal,
});
const contentLengthBytes = parseContentLengthBytes(
response.headers.get('content-length'),
@@ -291,6 +357,7 @@ const uploadMediaStreamToStorage = async ({
fieldMetadataUniversalIdentifier,
body,
sizeBytes,
+ signal,
}: {
callRecordingId: string;
metadataClient: InstanceType<typeof MetadataApiClient>;
@@ -298,6 +365,7 @@ const uploadMediaStreamToStorage = async ({
fieldMetadataUniversalIdentifier: string;
body: ReadableStream<Uint8Array>;
sizeBytes: number;
+ signal: AbortSignal;
}): Promise<string> => {
const uploadTarget = await createFileUploadTarget({
metadataClient,
@@ -323,6 +391,7 @@ const uploadMediaStreamToStorage = async ({
mediaDownloadBody: body,
sizeBytes,
uploadTarget,
+ signal,
});
return completeFileUpload({ metadataClient, fileId: uploadTarget.fileId });
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.ts
index ae930fa044b..60b78b80367 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
@@ -30,6 +30,7 @@ export const importCallRecordingTranscript = async ({
requestedAt,
transcript,
isMediaExpired,
+ signal,
}: {
callRecordingId: string;
currentStatus: string | undefined;
@@ -37,6 +38,7 @@ export const importCallRecordingTranscript = async ({
requestedAt: string;
transcript: unknown;
isMediaExpired: boolean;
+ signal?: AbortSignal;
}): Promise<ImportCallRecordingTranscriptResult> => {
const existingTranscriptMarker = parseTranscriptMarker(transcript);
@@ -60,7 +62,10 @@ export const importCallRecordingTranscript = async ({
: buildEmptyTranscriptArtifactResult();
}
- const listResult = await listRecallTranscripts({ externalRecordingId });
+ const listResult = await listRecallTranscripts({
+ externalRecordingId,
+ signal,
+ });
if (!listResult.ok) {
console.warn(
@@ -112,6 +117,7 @@ export const importCallRecordingTranscript = async ({
const createResult = await createAsyncRecallTranscript({
externalRecordingId,
+ signal,
});
if (!createResult.ok) {
@@ -119,13 +125,12 @@ export const importCallRecordingTranscript = async ({
`[call-recorder] failed to request transcript for Recall recording ${externalRecordingId}: ${createResult.errorMessage}`,
);
- // A lost response may still have created the transcript, and the next
- // run lists transcripts before requesting a new one.
- if (isNull(createResult.status)) {
- return buildEmptyTranscriptArtifactResult();
- }
-
- if (isRetryableRecallApiStatus(createResult.status)) {
+ // The idempotency key makes a retried create safe, so a lost response
+ // is retried now instead of waiting for the next run.
+ if (
+ isNull(createResult.status) ||
+ isRetryableRecallApiStatus(createResult.status)
+ ) {
return buildEmptyTranscriptArtifactResult({
hasRetryableFailure: true,
});
@@ -191,6 +196,7 @@ export const importCallRecordingTranscript = async ({
const downloadResult = await downloadTranscript({
transcriptId: transcriptIdToDownload,
+ signal,
});
if (downloadResult.outcome === 'filled') {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/put-media-download-body-to-upload-target.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/put-media-download-body-to-upload-target.util.ts
index 7441242e438..c3c03847296 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/put-media-download-body-to-upload-target.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/put-media-download-body-to-upload-target.util.ts
@@ -13,7 +13,6 @@ type MediaUploadTarget = {
contentType: string;
};
-const MEDIA_UPLOAD_TIMEOUT_MS = 14 * 60 * 1000;
const HTTP_STATUS_OK_LOWER_BOUND = 200;
const HTTP_STATUS_OK_UPPER_BOUND = 300;
@@ -22,11 +21,13 @@ export const putMediaDownloadBodyToUploadTarget = async ({
fileName,
sizeBytes,
uploadTarget,
+ signal,
}: {
mediaDownloadBody: ReadableStream<Uint8Array>;
fileName: string;
sizeBytes: number;
uploadTarget: MediaUploadTarget;
+ signal: AbortSignal;
}): Promise<void> => {
// Use node:http instead of fetch here: fetch can buffer ReadableStream
// request bodies in memory, which OOMs Lambda for large recordings.
@@ -39,6 +40,7 @@ export const putMediaDownloadBodyToUploadTarget = async ({
mediaDownloadReadable,
sizeBytes,
uploadTarget,
+ signal,
});
};
@@ -47,11 +49,13 @@ const streamMediaDownloadReadableToUploadTarget = async ({
mediaDownloadReadable,
sizeBytes,
uploadTarget,
+ signal,
}: {
fileName: string;
mediaDownloadReadable: Readable;
sizeBytes: number;
uploadTarget: MediaUploadTarget;
+ signal: AbortSignal;
}): Promise<void> => {
const uploadUrl = new URL(uploadTarget.uploadUrl);
const requestUpload =
@@ -62,11 +66,13 @@ const streamMediaDownloadReadableToUploadTarget = async ({
'Content-Type': uploadTarget.contentType,
'Content-Length': sizeBytes,
},
- signal: AbortSignal.timeout(MEDIA_UPLOAD_TIMEOUT_MS),
+ signal,
});
const uploadResponsePromise = waitForUploadResponse({ uploadRequest });
- const uploadPipelinePromise = pipeline(mediaDownloadReadable, uploadRequest);
+ const uploadPipelinePromise = pipeline(mediaDownloadReadable, uploadRequest, {
+ signal,
+ });
let uploadResponse: IncomingMessage;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recording.util.ts
index c0c8bcefa29..3dbe244006c 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recording.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recording.util.ts
@@ -36,8 +36,9 @@ export const reconcileCallRecording = async ({
if (reconcilableStatus === CallRecordingStatus.PROCESSING) {
await enqueueCallRecordingArtifactsImport({
- callRecordingId,
+ callRecordingIds: [callRecordingId],
scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,
+ trigger: 'recovery',
});
return;
@@ -84,8 +85,9 @@ export const reconcileCallRecording = async ({
data.status === CallRecordingStatus.PROCESSING
) {
await enqueueCallRecordingArtifactsImport({
- callRecordingId,
+ callRecordingIds: [callRecordingId],
scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,
+ trigger: 'recovery',
});
}
};
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.ts
deleted file mode 100644
index d480488661f..00000000000
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/run-call-recording-artifact-import-with-claim.util.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-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 { type CallRecordingArtifactImportScope } from 'src/logic-functions/types/call-recording-artifact-scope.type';
-import { type CallRecordingForArtifactsImport } from 'src/logic-functions/types/call-recording-for-artifacts-import.type';
-
-type CallRecordingArtifactImportExecutionResult<TResult> =
- | {
- status: 'executed';
- result: TResult;
- }
- | { status: 'skipped' };
-
-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 claimedCallRecording = await claimCallRecordingArtifactsImport(client, {
- callRecordingId,
- scope,
- now,
- });
-
- if (isUndefined(claimedCallRecording)) {
- return { status: 'skipped' };
- }
-
- try {
- return {
- status: 'executed',
- result: await runImport(claimedCallRecording),
- };
- } finally {
- await releaseCallRecordingArtifactsImportClaim(client, {
- callRecordingId,
- scope,
- claimedAt: now.toISOString(),
- });
- }
-};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts
index a3ae3959f03..d5fe0757863 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
@@ -9,6 +9,6 @@ export default defineLogicFunction({
name: 'import-call-recording-artifacts',
description:
'Imports one recording artifact scope as an enqueued job after a verified Recall webhook resolves the owning CallRecording.',
- timeoutSeconds: 250,
+ timeoutSeconds: 900,
handler: handleCallRecordingArtifactsImportJob,
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.ts
index 368529cc462..34ced7d9263 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.ts
@@ -691,24 +691,20 @@ describe('recall bot api', () => {
});
});
- it('does not retry async transcript creation failures', async () => {
+ it('sends the transcript creation with an idempotency key for the recording', async () => {
fetchMock.mockResolvedValue({
- ok: false,
- status: 503,
- json: async () => ({ detail: 'service unavailable' }),
+ ok: true,
+ status: 201,
+ json: async () => ({ id: 'recall-transcript-id' }),
});
- const result = await createAsyncRecallTranscript({
+ await createAsyncRecallTranscript({
externalRecordingId: 'recall-recording-id',
});
- expect(result).toEqual({
- ok: false,
- status: 503,
- errorMessage:
- 'Recall API responded with HTTP 503: {"detail":"service unavailable"}',
- });
- expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0][1].headers['Idempotency-Key']).toBe(
+ 'create-transcript:recall-recording-id',
+ );
});
it('fails when the transcript creation response has no id', async () => {
@@ -876,6 +872,30 @@ describe('recall bot api', () => {
);
});
+ it('retries a lost transcript creation with the same idempotency key', async () => {
+ fetchMock.mockRejectedValueOnce(new Error('socket hang up'));
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ status: 201,
+ json: async () => ({ id: 'recall-transcript-id' }),
+ });
+
+ const resultPromise = createAsyncRecallTranscript({
+ externalRecordingId: 'recall-recording-id',
+ });
+
+ await vi.runAllTimersAsync();
+
+ expect(await resultPromise).toEqual({
+ ok: true,
+ transcriptId: 'recall-transcript-id',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[0][1].headers['Idempotency-Key']).toBe(
+ fetchMock.mock.calls[1][1].headers['Idempotency-Key'],
+ );
+ });
+
it('retries a 503 response and succeeds on the next attempt', async () => {
fetchMock.mockResolvedValueOnce({
ok: false,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/create-async-recall-transcript.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/create-async-recall-transcript.util.ts
index 1e6bfd2ae28..c1de1adf75e 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/create-async-recall-transcript.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/create-async-recall-transcript.util.ts
@@ -11,8 +11,10 @@ type CreateAsyncRecallTranscriptResult =
export const createAsyncRecallTranscript = async ({
externalRecordingId,
+ signal,
}: {
externalRecordingId: string;
+ signal?: AbortSignal;
}): Promise<CreateAsyncRecallTranscriptResult> => {
const configResult = getRecallApiConfig();
@@ -22,13 +24,14 @@ export const createAsyncRecallTranscript = async ({
const result = await recallBotApiRequest<{ id?: unknown }>({
config: configResult.config,
+ signal,
path: `/recording/${externalRecordingId}/create_transcript/`,
method: 'POST',
body: {
provider: getRecallAsyncTranscriptProvider(),
diarization: { use_separate_streams_when_available: true },
},
- maxAttempts: 1,
+ idempotencyKey: `create-transcript:${externalRecordingId}`,
});
if (!result.ok) {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.ts
index b88aa2770ec..3aec46a32e6 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.ts
@@ -16,6 +16,7 @@ export const fetchRecallListPages = async <TItem>({
shouldStartPageRequest,
extractPageItems,
malformedErrorMessage,
+ signal,
}: {
config: RecallApiConfig;
initialPath: string;
@@ -25,6 +26,7 @@ export const fetchRecallListPages = async <TItem>({
response: RecallListResponse | undefined,
) => TItem[] | undefined;
malformedErrorMessage: string;
+ signal?: AbortSignal;
}): Promise<
{ ok: true; items: TItem[]; truncated: boolean } | RecallBotOperationFailure
> => {
@@ -44,6 +46,7 @@ export const fetchRecallListPages = async <TItem>({
config,
path,
method: 'GET',
+ signal,
});
if (!result.ok) {
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-bot.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-bot.util.ts
index eaf738c3e6f..46aacf9a7a6 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-bot.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-bot.util.ts
@@ -11,8 +11,10 @@ type GetRecallBotResult =
export const getRecallBot = async ({
externalBotId,
+ signal,
}: {
externalBotId: string;
+ signal?: AbortSignal;
}): Promise<GetRecallBotResult> => {
const configResult = getRecallApiConfig();
@@ -22,6 +24,7 @@ export const getRecallBot = async ({
const result = await recallBotApiRequest<Record<string, unknown>>({
config: configResult.config,
+ signal,
path: `/bot/${externalBotId}/`,
method: 'GET',
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-recording.util.ts
index a81133ec09b..bd02ce690c9 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-recording.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-recall-recording.util.ts
@@ -8,8 +8,10 @@ type GetRecallRecordingResult =
export const getRecallRecording = async ({
externalRecordingId,
+ signal,
}: {
externalRecordingId: string;
+ signal?: AbortSignal;
}): Promise<GetRecallRecordingResult> => {
const configResult = getRecallApiConfig();
@@ -19,6 +21,7 @@ export const getRecallRecording = async ({
const result = await recallBotApiRequest<Record<string, unknown>>({
config: configResult.config,
+ signal,
path: `/recording/${externalRecordingId}/`,
method: 'GET',
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.ts
index a613ea4f5e6..fa58ec9e522 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.ts
@@ -18,8 +18,10 @@ const RECALL_TRANSCRIPT_LIST_MAX_PAGES = 10;
export const listRecallTranscripts = async ({
externalRecordingId,
+ signal,
}: {
externalRecordingId: string;
+ signal?: AbortSignal;
}): Promise<ListRecallTranscriptsResult> => {
const configResult = getRecallApiConfig();
@@ -32,6 +34,7 @@ export const listRecallTranscripts = async ({
});
const result = await fetchRecallListPages({
config: configResult.config,
+ signal,
initialPath: `/transcript/?${searchParams.toString()}`,
maxPages: RECALL_TRANSCRIPT_LIST_MAX_PAGES,
shouldStartPageRequest: () => true,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.ts
index c98f30f7fff..0adcf51a392 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/recall-bot-api-request.util.ts
@@ -9,6 +9,7 @@ import {
isRetryableRecallApiStatus,
resolveRecallApiRetryDelayMs,
} from 'src/logic-functions/recall-api/recall-api-retry-policy.util';
+import { fetchWithTimeout } from 'src/logic-functions/utils/fetch-with-timeout.util';
type RecallBotApiRequestArgs = {
config: RecallApiConfig;
@@ -17,7 +18,7 @@ type RecallBotApiRequestArgs = {
body?: unknown;
idempotencyKey?: string;
allowNotFound?: boolean;
- maxAttempts?: number;
+ signal?: AbortSignal;
};
type RecallBotApiRequestResult<TData> =
@@ -37,14 +38,14 @@ type RecallBotApiRequestResult<TData> =
export const recallBotApiRequest = async <TData>(
requestArgs: RecallBotApiRequestArgs,
): Promise<RecallBotApiRequestResult<TData>> => {
- const maxAttempts = requestArgs.maxAttempts ?? RECALL_API_MAX_ATTEMPTS;
let totalRetryWaitMs = 0;
for (let attemptNumber = 1; ; attemptNumber++) {
+ requestArgs.signal?.throwIfAborted();
const { result, isRetryable, retryAfterMs } =
await performRecallBotApiRequestAttempt<TData>(requestArgs);
- if (!isRetryable || attemptNumber >= maxAttempts) {
+ if (!isRetryable || attemptNumber >= RECALL_API_MAX_ATTEMPTS) {
return result;
}
@@ -74,6 +75,7 @@ const performRecallBotApiRequestAttempt = async <TData>({
body,
idempotencyKey,
allowNotFound = false,
+ signal,
}: RecallBotApiRequestArgs): Promise<{
result: RecallBotApiRequestResult<TData>;
isRetryable: boolean;
@@ -82,8 +84,9 @@ const performRecallBotApiRequestAttempt = async <TData>({
let response: Response;
try {
- response = await fetch(`${config.baseUrl}${path}`, {
+ response = await fetchWithTimeout(`${config.baseUrl}${path}`, {
method,
+ signal,
headers: {
Authorization: buildRecallApiAuthorizationHeader(config.apiKey),
...(isUndefined(idempotencyKey)
@@ -94,6 +97,10 @@ const performRecallBotApiRequestAttempt = async <TData>({
...(isUndefined(body) ? {} : { body: JSON.stringify(body) }),
});
} catch (error) {
+ if (signal?.aborted) {
+ throw error;
+ }
+
return {
isRetryable: true,
result: {
@@ -153,11 +160,15 @@ const performRecallBotApiRequestAttempt = async <TData>({
},
};
} catch (error) {
+ const isAborted =
+ error instanceof Error &&
+ (error.name === 'TimeoutError' || error.name === 'AbortError');
+
return {
- isRetryable: false,
+ isRetryable: isAborted,
result: {
ok: false,
- status: response.status,
+ status: isAborted ? null : response.status,
errorMessage: `Recall API returned a non-JSON response: ${
error instanceof Error ? error.message : String(error)
}`,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/retrieve-recall-transcript.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/retrieve-recall-transcript.util.ts
index a096da7c62b..473e7a327fb 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/retrieve-recall-transcript.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/retrieve-recall-transcript.util.ts
@@ -18,8 +18,10 @@ type RetrieveRecallTranscriptResult =
export const retrieveRecallTranscript = async ({
transcriptId,
+ signal,
}: {
transcriptId: string;
+ signal?: AbortSignal;
}): Promise<RetrieveRecallTranscriptResult> => {
const configResult = getRecallApiConfig();
@@ -29,6 +31,7 @@ export const retrieveRecallTranscript = async ({
const result = await recallBotApiRequest<Record<string, unknown>>({
config: configResult.config,
+ signal,
path: `/transcript/${transcriptId}/`,
method: 'GET',
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.ts
index 7bb94858991..650671a7b04 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-stale-bot-state.ts
@@ -7,6 +7,7 @@ import { convergeDivergedCallRecordings } from 'src/logic-functions/flows/conver
import { reconcileCallRecording } from 'src/logic-functions/flows/reconcile-call-recording.util';
import { asRecord } from 'src/logic-functions/utils/as-record.util';
import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';
+import { fetchWithTimeout } from 'src/logic-functions/utils/fetch-with-timeout.util';
import { getString } from 'src/logic-functions/utils/get-string.util';
export const reconcileStaleBotStateHandler = async (
@@ -14,7 +15,7 @@ export const reconcileStaleBotStateHandler = async (
): Promise<object> => {
const body = asRecord(payload);
const callRecordingId = getString(body?.callRecordingId);
- const client = new CoreApiClient();
+ const client = new CoreApiClient({ fetch: fetchWithTimeout });
try {
if (!isUndefined(callRecordingId)) {
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.ts
index da4497c6dd2..1c600e74cbf 100644
--- 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.ts
@@ -1 +1 @@
-export type CallRecordingArtifactImportScope = 'transcript' | 'media';
+export type CallRecordingArtifactImportScope = 'transcript' | 'audio' | 'video';
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.ts
index b30efbbadec..3c2e6788030 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
@@ -22,7 +22,4 @@ export type CallRecordingUpdateFields = Partial<{
audio: CallRecordingMediaFile[];
video: CallRecordingMediaFile[];
summary: CallRecordingSummary;
- // null releases the concurrent-import lease.
- artifactsImportClaimedAt: string | null;
- transcriptImportClaimedAt: string | null;
}>;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/fetch-with-timeout.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/fetch-with-timeout.test.ts
new file mode 100644
index 00000000000..73ee7d489b8
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/fetch-with-timeout.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { fetchWithTimeout } from 'src/logic-functions/utils/fetch-with-timeout.util';
+
+const stubPendingFetch = () => {
+ const fetchMock = vi.fn(
+ (_input: Parameters<typeof fetch>[0], options?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ options?.signal?.addEventListener(
+ 'abort',
+ () => reject(options.signal?.reason),
+ { once: true },
+ );
+ }),
+ );
+
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+};
+
+describe('fetchWithTimeout', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it('aborts a stalled request when its request deadline expires', async () => {
+ const deadline = new AbortController();
+ vi.spyOn(AbortSignal, 'timeout').mockReturnValue(deadline.signal);
+ stubPendingFetch();
+ const request = fetchWithTimeout('https://recall.example.com/recording');
+ const assertion = expect(request).rejects.toMatchObject({
+ name: 'TimeoutError',
+ });
+
+ deadline.abort(new DOMException('Request timed out', 'TimeoutError'));
+ await assertion;
+ });
+
+ it('preserves an earlier invocation deadline supplied by the caller', async () => {
+ const invocation = new AbortController();
+ stubPendingFetch();
+ const request = fetchWithTimeout('https://recall.example.com/recording', {
+ signal: invocation.signal,
+ });
+ const assertion = expect(request).rejects.toMatchObject({
+ name: 'AbortError',
+ });
+
+ invocation.abort();
+ await assertion;
+ });
+
+ it('preserves the cancellation signal carried by a Request', async () => {
+ const invocation = new AbortController();
+ stubPendingFetch();
+ const request = fetchWithTimeout(
+ new Request('https://recall.example.com/recording', {
+ signal: invocation.signal,
+ }),
+ );
+ const assertion = expect(request).rejects.toMatchObject({
+ name: 'AbortError',
+ });
+
+ invocation.abort();
+ await assertion;
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/build-abort-signal-with-timeout.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/build-abort-signal-with-timeout.util.ts
new file mode 100644
index 00000000000..87816258d0b
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/build-abort-signal-with-timeout.util.ts
@@ -0,0 +1,13 @@
+import { isUndefined } from '@sniptt/guards';
+
+export const buildAbortSignalWithTimeout = ({
+ timeoutMs,
+ signal,
+}: {
+ timeoutMs: number;
+ signal: AbortSignal | undefined;
+}): AbortSignal =>
+ AbortSignal.any([
+ AbortSignal.timeout(timeoutMs),
+ ...(isUndefined(signal) ? [] : [signal]),
+ ]);
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-timeout.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-timeout.util.ts
new file mode 100644
index 00000000000..7efbc5feb64
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-timeout.util.ts
@@ -0,0 +1,16 @@
+import { buildAbortSignalWithTimeout } from 'src/logic-functions/utils/build-abort-signal-with-timeout.util';
+
+const REQUEST_TIMEOUT_MS = 10_000;
+
+export const fetchWithTimeout: typeof fetch = (input, options) => {
+ const signal =
+ options?.signal ?? (input instanceof Request ? input.signal : undefined);
+
+ return fetch(input, {
+ ...options,
+ signal: buildAbortSignalWithTimeout({
+ timeoutMs: REQUEST_TIMEOUT_MS,
+ signal,
+ }),
+ });
+};
diff --git a/packages/twenty-apps/public/call-recorder/yarn.lock b/packages/twenty-apps/public/call-recorder/yarn.lock
index 477a5df9b56..8d017d412ff 100644
--- a/packages/twenty-apps/public/call-recorder/yarn.lock
+++ b/packages/twenty-apps/public/call-recorder/yarn.lock
@@ -1401,8 +1401,8 @@ __metadata:
react: "npm:^19.0.0"
react-dom: "npm:^19.0.0"
sharp: "npm:^0.35.3"
- twenty-client-sdk: "npm:2.37.0"
- twenty-sdk: "npm:2.37.0"
+ twenty-client-sdk: "npm:2.38.0"
+ twenty-sdk: "npm:2.38.0"
twenty-ui: "npm:^1.0.0-alpha.1"
typescript: "npm:^5.9.3"
use-debounce: "npm:^10.0.0"
@@ -3620,22 +3620,22 @@ __metadata:
languageName: node
linkType: hard
-"twenty-client-sdk@npm:2.37.0":
- version: 2.37.0
- resolution: "twenty-client-sdk@npm:2.37.0"
+"twenty-client-sdk@npm:2.38.0":
+ version: 2.38.0
+ resolution: "twenty-client-sdk@npm:2.38.0"
dependencies:
"@genql/runtime": "npm:^2.10.0"
esbuild: "npm:^0.28.1"
graphql: "npm:^16.8.1"
lodash: "npm:^4.17.21"
prettier: "npm:^3.8.3"
- checksum: 10c0/0250a95b803a468f7bd9261b7a55a862b9b6daf840adf21ab7a4067906761e710703f79f7571f6400716afc4e612eda7da2bb1948c23a5adff07d59cc30ba10e
+ checksum: 10c0/2ab1c0371a5b48187211477740d833c8454e624d45b4ea1b964864077745d85e6921f5e8452eacb1eceab44e698507a4854686e225e467dd4f5fc481553b047b
languageName: node
linkType: hard
-"twenty-sdk@npm:2.37.0":
- version: 2.37.0
- resolution: "twenty-sdk@npm:2.37.0"
+"twenty-sdk@npm:2.38.0":
+ version: 2.38.0
+ resolution: "twenty-sdk@npm:2.38.0"
dependencies:
"@sniptt/guards": "npm:^0.2.0"
axios: "npm:^1.16.0"
@@ -3654,12 +3654,12 @@ __metadata:
semver: "npm:7.6.3"
sharp: "npm:^0.35.3"
tinyglobby: "npm:^0.2.15"
- twenty-client-sdk: "npm:2.37.0"
+ twenty-client-sdk: "npm:2.38.0"
typescript: "npm:^5.9.3"
uuid: "npm:^13.0.2"
bin:
twenty: dist/cli.cjs
- checksum: 10c0/ddbc01430cfbcc878d2b23851b5f5ae7a76fb453d5a578e876ab7e999093a62aa8c025d22b1095d20fad363f8e6cf885a7c002ad64498fdbb9dfc695a1fc1f9c
+ checksum: 10c0/9946e0018f6233bbd8bd3ab0ca9dcc96276b25126b9c14328b90b15b8f2948d550ebb9395354ec87066bd8ab74372d242d94c4e5629b4cd16421bf21beb8a62e
languageName: node
linkType: hard