The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Migrate call-recorder fan-out to platform jobs (#24818)
nitine3228d7f6358
diff --git a/packages/twenty-apps/public/call-recorder/package.json b/packages/twenty-apps/public/call-recorder/package.jsonindex a0d4bb8ed83..a445e0bd440 100644--- a/packages/twenty-apps/public/call-recorder/package.json+++ b/packages/twenty-apps/public/call-recorder/package.json@@ -1,12 +1,12 @@{"name": "@twentyhq/call-recorder",- "version": "1.8.0",+ "version": "1.9.0","license": "MIT","engines": {"node": "^24.5.0","npm": "please-use-yarn","yarn": ">=4.0.2",- "twenty": ">=2.32.0"+ "twenty": ">=2.35.0"},"keywords": ["twenty-app"@@ -33,8 +33,8 @@"oxlint": "^0.16.0","react": "^19.0.0","react-dom": "^19.0.0",- "twenty-client-sdk": "2.31.0-alpha.1",- "twenty-sdk": "2.31.0-alpha.1",+ "twenty-client-sdk": "2.35.0",+ "twenty-sdk": "2.35.0","typescript": "^5.9.3","vite-tsconfig-paths": "^4.2.1","vitest": "^4.1.9"diff --git a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.tsindex 1c2ad24022f..4bca2cc813f 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@@ -30,8 +30,6 @@ import { processRecallWebhookHandler } from 'src/logic-functions/process-recall-const WORKSPACE_API_KEY_ENV = 'TWENTY_API_KEY';const RECALL_BASE_URL = 'https://us-west-2.recall.ai/api/v1';-const FUNCTIONS_URL = 'https://call-recorder-functions.test';-const ARTIFACT_IMPORT_ROUTE = '/call-recorder/import-call-recording-artifacts';const RESTRICTED_TITLE_PLACEHOLDER ='FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED';@@ -108,9 +106,9 @@ const hoursAgo = (hours: number) =>new Date(Date.now() - hours * 60 * 60 * 1000).toISOString();// ----------------------------------------------------------------------------// Recall API fake, installed as a fetch interceptor. Twenty API traffic is-// never intercepted: the shared client is built before the interceptor and-// unknown URLs fall through to the real fetch.+// Recall API fake, installed as a fetch interceptor. Twenty API traffic falls+// through to the real fetch, except the metadata enqueueJobs mutation, which is+// captured here so fanned-out jobs do not run inside the test.// ---------------------------------------------------------------------------type FakeRecallBot = {@@ -140,10 +138,29 @@ class FakeRecallApi {handle(requestUrl: string, requestInit?: any): Response | undefined {const method: string = requestInit?.method ?? 'GET';- if (requestUrl.startsWith(`${FUNCTIONS_URL}${ARTIFACT_IMPORT_ROUTE}`)) {- this.artifactImportRequests.push(JSON.parse(requestInit?.body ?? '{}'));+ // Capture the artifact-import enqueue instead of letting the job run.+ if (+ requestUrl === `${process.env.TWENTY_API_URL}/metadata` &&+ String(requestInit?.body ?? '').includes('enqueueJobs')+ ) {+ const sentBody = JSON.parse(requestInit?.body ?? '{}');+ const [input] = Object.values(sentBody.variables ?? {}) as {+ logicFunctionUniversalIdentifier: string;+ payloads: object[];+ }[];- return jsonResponse(200, {});+ this.artifactImportRequests.push(...(input?.payloads ?? []));++ return jsonResponse(200, {+ data: {+ enqueueJobs: {+ enqueued: true,+ logicFunctionUniversalIdentifier:+ input?.logicFunctionUniversalIdentifier ?? '',+ enqueuedJobsCount: input?.payloads?.length ?? 0,+ },+ },+ });}if (!requestUrl.startsWith(RECALL_BASE_URL)) {@@ -339,7 +356,6 @@ describe('call recorder app lifecycle (integration)', () => {vi.stubEnv('RECALL_API_KEY', 'recall-api-key');vi.stubEnv('RECALL_REGION', 'us-west-2');vi.stubEnv('CALL_RECORDER_USE_WORKSPACE_LOGO', 'false');- vi.stubEnv('TWENTY_FUNCTIONS_URL', FUNCTIONS_URL);// Logic functions normally run with an app access token; the workspace// API key is a token with the same workspaceId claim.vi.stubEnv(@@ -636,8 +652,8 @@ describe('call recorder app lifecycle (integration)', () => {'recall-recording-1',);expect(processedCallRecording.endedAt).toBeTruthy();- // recording.done hands media and transcript work to the artifact- // import route.+ // recording.done hands media and transcript work to the enqueued+ // artifact import job.expect(recall.artifactImportRequests).toHaveLength(1);expect(recall.artifactImportRequests[0]).toMatchObject({callRecordingId,diff --git a/packages/twenty-apps/public/call-recorder/src/constants/call-recording-summary-unavailable-prefix.ts b/packages/twenty-apps/public/call-recorder/src/constants/call-recording-summary-unavailable-prefix.tsnew file mode 100644index 00000000000..f20813a046f--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/constants/call-recording-summary-unavailable-prefix.ts@@ -0,0 +1,2 @@+export const CALL_RECORDING_SUMMARY_UNAVAILABLE_PREFIX =+ 'SUMMARY_UNAVAILABLE:';diff --git a/packages/twenty-apps/public/call-recorder/src/constants/default-call-recording-summary-prompt.ts b/packages/twenty-apps/public/call-recorder/src/constants/default-call-recording-summary-prompt.tsindex 509079f6d9f..90c7760f638 100644--- a/packages/twenty-apps/public/call-recorder/src/constants/default-call-recording-summary-prompt.ts+++ b/packages/twenty-apps/public/call-recorder/src/constants/default-call-recording-summary-prompt.ts@@ -1,3 +1,5 @@+import { CALL_RECORDING_SUMMARY_UNAVAILABLE_PREFIX } from 'src/constants/call-recording-summary-unavailable-prefix';+export const DEFAULT_CALL_RECORDING_SUMMARY_PROMPT = ['You are an AI meeting note-taker for a CRM. You receive the diarized,','time-stamped transcript of a recorded call and produce clean, factual',@@ -40,9 +42,15 @@ export const DEFAULT_CALL_RECORDING_SUMMARY_PROMPT = ['','Grounding rules: use only information present in the transcript. Never','invent names, numbers, commitments, outcomes, or times — reuse the [mm:ss]',- 'timestamps exactly as they appear in the transcript. If the transcript is',- 'too short or unintelligible to summarize, ignore all of the above and',- 'return only the single line: No summary available.',+ 'timestamps exactly as they appear in the transcript.',+ '',+ 'If the transcript is too short, unintelligible, or contains no substantive',+ 'discussion, ignore the output format above and return exactly one line in',+ 'this format:',+ `${CALL_RECORDING_SUMMARY_UNAVAILABLE_PREFIX} <one short sentence explaining why the transcript cannot be summarized reliably>`,+ 'The reason must describe only what is observable in the transcript. Be',+ 'specific and do not speculate. Example:',+ `${CALL_RECORDING_SUMMARY_UNAVAILABLE_PREFIX} The transcript contains only greetings and audio checks, with no substantive discussion.`,'','The message may include additional instructions from the workspace admin.','Apply them on top of these rules without breaking the output format or the',diff --git a/packages/twenty-apps/public/call-recorder/src/constants/import-call-recording-artifacts-route-path.ts b/packages/twenty-apps/public/call-recorder/src/constants/import-call-recording-artifacts-route-path.tsdeleted file mode 100644index 017c2f3e81f..00000000000--- a/packages/twenty-apps/public/call-recorder/src/constants/import-call-recording-artifacts-route-path.ts+++ /dev/null@@ -1,2 +0,0 @@-export const IMPORT_CALL_RECORDING_ARTIFACTS_ROUTE_PATH =- '/call-recorder/import-call-recording-artifacts';diff --git a/packages/twenty-apps/public/call-recorder/src/constants/reconcile-upcoming-calendar-events-route-path.ts b/packages/twenty-apps/public/call-recorder/src/constants/reconcile-upcoming-calendar-events-route-path.tsdeleted file mode 100644index 7753b4eb64e..00000000000--- a/packages/twenty-apps/public/call-recorder/src/constants/reconcile-upcoming-calendar-events-route-path.ts+++ /dev/null@@ -1,2 +0,0 @@-export const RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH =- '/call-recorder/reconcile-upcoming-calendar-events';diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/request-call-recording-summary-generation.test.ts b/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/request-call-recording-summary-generation.test.tsindex 4cd61b66f58..3b56cc3b595 100644--- a/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/request-call-recording-summary-generation.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/request-call-recording-summary-generation.test.ts@@ -87,4 +87,43 @@ describe('requestCallRecordingSummaryGeneration', () => {variant: 'error',});});++ it('reports when the call recording has no usable transcript', async () => {+ postMock.mockResolvedValue({+ outcome: 'processed',+ generatedCallRecordingIds: [],+ failedCallRecordingIds: [],+ erroredCallRecordingIds: [],+ skippedCallRecordingIds: ['call-recording-1'],+ });++ await requestCallRecordingSummaryGeneration({+ calendarEventIds: ['calendar-event-1'],+ });++ expect(enqueueSnackbarMock).toHaveBeenCalledWith({+ message: 'No usable call recording transcript found for this event.',+ variant: 'error',+ });+ });++ it('reports when the transcript has nothing substantive to summarize', async () => {+ postMock.mockResolvedValue({+ outcome: 'processed',+ generatedCallRecordingIds: [],+ failedCallRecordingIds: [],+ erroredCallRecordingIds: [],+ skippedCallRecordingIds: [],+ unavailableCallRecordingIds: ['call-recording-1'],+ });++ await requestCallRecordingSummaryGeneration({+ calendarEventIds: ['calendar-event-1'],+ });++ expect(enqueueSnackbarMock).toHaveBeenCalledWith({+ message: 'Summary unavailable for this event.',+ variant: 'error',+ });+ });});diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/utils/request-call-recording-summary-generation.util.ts b/packages/twenty-apps/public/call-recorder/src/front-components/utils/request-call-recording-summary-generation.util.tsindex 684b3347dc7..294db15059c 100644--- a/packages/twenty-apps/public/call-recorder/src/front-components/utils/request-call-recording-summary-generation.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/front-components/utils/request-call-recording-summary-generation.util.ts@@ -8,6 +8,8 @@ type GenerateSummariesResponse = {generatedCallRecordingIds?: string[];failedCallRecordingIds?: string[];erroredCallRecordingIds?: string[];+ skippedCallRecordingIds?: string[];+ unavailableCallRecordingIds?: string[];};const buildSnackbarForResponse = (@@ -48,9 +50,23 @@ const buildSnackbarForResponse = (return { message: 'Summary generation failed.', variant: 'error' };}+ if ((response.unavailableCallRecordingIds ?? []).length > 0) {+ return {+ message: 'Summary unavailable for this event.',+ variant: 'error',+ };+ }++ if ((response.skippedCallRecordingIds ?? []).length > 0) {+ return {+ message: 'No usable call recording transcript found for this event.',+ variant: 'error',+ };+ }+return {- message: 'No summary to generate for this event.',- variant: 'success',+ message: 'No summary was generated for this event.',+ variant: 'error',};};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/generate-call-recording-summaries.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/generate-call-recording-summaries.test.tsindex c06f40ebe00..0d57d705c1a 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/generate-call-recording-summaries.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/generate-call-recording-summaries.test.ts@@ -6,6 +6,7 @@ import { generateCallRecordingSummariesHandler } from 'src/logic-functions/generconst queryMock = vi.hoisted(() => vi.fn());const mutationMock = vi.hoisted(() => vi.fn());const runAgentMock = vi.hoisted(() => vi.fn());+const enqueueJobsMock = vi.hoisted(() => vi.fn());vi.mock('twenty-client-sdk/core', () => ({CoreApiClient: class {@@ -16,10 +17,9 @@ vi.mock('twenty-client-sdk/core', () => ({vi.mock('twenty-sdk/logic-function', () => ({runAgent: runAgentMock,+ enqueueJobs: enqueueJobsMock,}));-const fetchMock = vi.fn();-const buildRoutePayload = (body: object | null,): RoutePayload<{ callRecordingIds?: string[]; calendarEventIds?: string[] }> =>@@ -59,12 +59,9 @@ const buildConnection = (nodes: object[]) => ({},});-const buildSummarizableCallRecordingNode = (- id: string,- createdAt = '2026-01-01T00:00:00.000Z',-) => ({+const buildSummarizableCallRecordingNode = (id: string) => ({id,- createdAt,+ createdAt: '2026-01-01T00:00:00.000Z',title: 'Weekly sync',transcript: TRANSCRIPT,summary: { markdown: null },@@ -72,11 +69,9 @@ const buildSummarizableCallRecordingNode = (});const seedCallRecordingQueries = ({- sweepNodes = [],calendarEventNodes = [],callRecordingsById = {},}: {- sweepNodes?: object[];calendarEventNodes?: object[];callRecordingsById?: Record<string, object>;} = {}) => {@@ -96,7 +91,7 @@ const seedCallRecordingQueries = ({return buildConnection(calendarEventNodes);}- return buildConnection(sweepNodes);+ return buildConnection([]);});};@@ -111,19 +106,14 @@ const BATCH_RESULT = {failedCallRecordingIds: [],erroredCallRecordingIds: [],skippedCallRecordingIds: [],- remainingCallRecordingIds: [],- continuationRequested: false,+ unavailableCallRecordingIds: [],};describe('generateCallRecordingSummariesHandler', () => {beforeEach(() => {vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);vi.stubEnv('CALL_RECORDER_SUMMARY_ENABLED', 'true');vi.stubEnv('CALL_RECORDER_ADDITIONAL_SUMMARY_PROMPT', '');- vi.stubEnv('TWENTY_FUNCTIONS_URL', 'https://acme.functions.example.com');- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));mutationMock.mockResolvedValue({});runAgentMock.mockResolvedValue({success: true,@@ -134,7 +124,6 @@ describe('generateCallRecordingSummariesHandler', () => {});afterEach(() => {- vi.unstubAllGlobals();vi.unstubAllEnvs();});@@ -149,9 +138,10 @@ describe('generateCallRecordingSummariesHandler', () => {expect(queryMock).not.toHaveBeenCalled();expect(runAgentMock).not.toHaveBeenCalled();expect(mutationMock).not.toHaveBeenCalled();+ expect(enqueueJobsMock).not.toHaveBeenCalled();});- it('processes explicit call recording ids without sweeping', async () => {+ it('processes explicit call recording ids inline without enqueuing', async () => {seedCallRecordingQueries({callRecordingsById: {'call-recording-1':@@ -167,6 +157,7 @@ describe('generateCallRecordingSummariesHandler', () => {expect(queriedCallRecordingFilters()).toEqual([{ id: { eq: 'call-recording-1' } },]);+ expect(enqueueJobsMock).not.toHaveBeenCalled();expect(mutationMock).toHaveBeenCalledWith({updateCallRecording: {__args: {@@ -206,7 +197,27 @@ describe('generateCallRecordingSummariesHandler', () => {);});- it('reports when the selected calendar events have no recordings instead of sweeping', async () => {+ it('regenerates an existing summary when requested from a calendar event', async () => {+ seedCallRecordingQueries({+ calendarEventNodes: [{ id: 'call-recording-1' }],+ callRecordingsById: {+ 'call-recording-1': {+ ...buildSummarizableCallRecordingNode('call-recording-1'),+ summary: { markdown: '## Overview\nOld summary.' },+ },+ },+ });++ const result = await generateCallRecordingSummariesHandler(+ buildRoutePayload({ calendarEventIds: ['calendar-event-1'] }),+ );++ expect(result).toEqual({ outcome: 'processed', ...BATCH_RESULT });+ expect(runAgentMock).toHaveBeenCalledTimes(1);+ expect(mutationMock).toHaveBeenCalledTimes(1);+ });++ it('reports when the selected calendar events have no recordings instead of enqueuing', async () => {const result = await generateCallRecordingSummariesHandler(buildRoutePayload({ calendarEventIds: ['calendar-event-1'] }),);@@ -219,52 +230,22 @@ describe('generateCallRecordingSummariesHandler', () => {]);expect(runAgentMock).not.toHaveBeenCalled();expect(mutationMock).not.toHaveBeenCalled();+ expect(enqueueJobsMock).not.toHaveBeenCalled();});- it('sweeps recordings missing a summary when no ids are given', async () => {- seedCallRecordingQueries({- sweepNodes: [- buildSummarizableCallRecordingNode(- 'call-recording-1',- '2026-01-02T00:00:00.000Z',- ),- buildSummarizableCallRecordingNode(- 'call-recording-2',- '2026-01-01T00:00:00.000Z',- ),- ],- callRecordingsById: {- 'call-recording-1':- buildSummarizableCallRecordingNode('call-recording-1'),- 'call-recording-2':- buildSummarizableCallRecordingNode('call-recording-2'),- },- });-+ it('returns nothing-selected when no ids are given instead of sweeping history', async () => {const result = await generateCallRecordingSummariesHandler(buildRoutePayload(null),);- expect(queriedCallRecordingFilters()).toEqual([- {- status: { eq: 'COMPLETED' },- transcript: { is: 'NOT_NULL' },- createdBy: {- source: { eq: 'APPLICATION' },- name: { eq: 'Call Recorder' },- },- },- { id: { eq: 'call-recording-1' } },- { id: { eq: 'call-recording-2' } },- ]);- expect(result).toEqual({- outcome: 'processed',- ...BATCH_RESULT,- generatedCallRecordingIds: ['call-recording-1', 'call-recording-2'],- });+ expect(result).toEqual({ outcome: 'nothing-selected' });+ expect(queryMock).not.toHaveBeenCalled();+ expect(runAgentMock).not.toHaveBeenCalled();+ expect(mutationMock).not.toHaveBeenCalled();+ expect(enqueueJobsMock).not.toHaveBeenCalled();});- it('does not sweep when an empty calendar event selection is sent', async () => {+ it('does not enqueue when an empty calendar event selection is sent', async () => {const result = await generateCallRecordingSummariesHandler(buildRoutePayload({ calendarEventIds: [] }),);@@ -273,18 +254,17 @@ describe('generateCallRecordingSummariesHandler', () => {expect(queryMock).not.toHaveBeenCalled();expect(runAgentMock).not.toHaveBeenCalled();expect(mutationMock).not.toHaveBeenCalled();+ expect(enqueueJobsMock).not.toHaveBeenCalled();});- it('short-circuits an empty sweep without running the batch', async () => {+ it('returns nothing-selected for an empty body', async () => {const result = await generateCallRecordingSummariesHandler(buildRoutePayload({}),);- expect(result).toEqual({ outcome: 'nothing-to-summarize' });- expect(queriedCallRecordingFilters()).toEqual([- expect.objectContaining({ status: { eq: 'COMPLETED' } }),- ]);+ expect(result).toEqual({ outcome: 'nothing-selected' });+ expect(queryMock).not.toHaveBeenCalled();expect(runAgentMock).not.toHaveBeenCalled();- expect(mutationMock).not.toHaveBeenCalled();+ expect(enqueueJobsMock).not.toHaveBeenCalled();});});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/import-call-recording-artifacts.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/import-call-recording-artifacts.test.tsindex 88e8f9d8b37..c5c2a698c00 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/import-call-recording-artifacts.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/import-call-recording-artifacts.test.ts@@ -1,11 +1,8 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { type RoutePayload } from 'twenty-sdk/define';import importCallRecordingArtifactsLogicFunction, {importCallRecordingArtifactsHandler,} from 'src/logic-functions/import-call-recording-artifacts';-import { IMPORT_CALL_RECORDING_ARTIFACTS_ROUTE_PATH } from 'src/constants/import-call-recording-artifacts-route-path';-import { type CallRecordingArtifactsImportRequest } from 'src/logic-functions/types/call-recording-artifacts-import-request.type';const importCallRecordingArtifactsMock = vi.hoisted(() => vi.fn());const coreApiClientMock = vi.hoisted(() => vi.fn());@@ -21,20 +18,6 @@ vi.mock('twenty-client-sdk/core', () => ({CoreApiClient: coreApiClientMock,}));-const buildRoutePayload = (- body: Partial<CallRecordingArtifactsImportRequest> | null,-): RoutePayload<Partial<CallRecordingArtifactsImportRequest>> =>- ({- body,- headers: {},- queryStringParameters: {},- pathParameters: {},- isBase64Encoded: false,- rawBody: undefined,- requestContext: { http: { method: 'POST', path: '/' } },- userWorkspaceId: null,- }) as never;-describe('import-call-recording-artifacts', () => {beforeEach(() => {importCallRecordingArtifactsMock.mockReset();@@ -46,31 +29,31 @@ describe('import-call-recording-artifacts', () => {coreApiClientMock.mockReset();});- it('declares an authenticated own-route trigger for continuation requests', () => {+ it('is configured as an enqueue-only import worker', () => {expect(importCallRecordingArtifactsLogicFunction.success).toBe(true);- expect(- importCallRecordingArtifactsLogicFunction.config.httpRouteTriggerSettings,- ).toEqual({- path: IMPORT_CALL_RECORDING_ARTIFACTS_ROUTE_PATH,- httpMethod: 'POST',- isAuthRequired: true,- });+ expect(importCallRecordingArtifactsLogicFunction.config).toEqual(+ expect.objectContaining({+ name: 'import-call-recording-artifacts',+ timeoutSeconds: 250,+ }),+ );+ expect(importCallRecordingArtifactsLogicFunction.config).not.toHaveProperty(+ 'httpRouteTriggerSettings',+ );});- it('forwards a valid continuation request to the worker flow', async () => {- const body = {+ it('forwards a valid import payload to the worker flow', async () => {+ const payload = {callRecordingId: 'call-recording-1',requestedAt: '2026-01-01T14:06:00.000Z',};- const result = await importCallRecordingArtifactsHandler(- buildRoutePayload(body),- );+ const result = await importCallRecordingArtifactsHandler(payload);expect(coreApiClientMock).toHaveBeenCalledTimes(1);expect(importCallRecordingArtifactsMock).toHaveBeenCalledWith({client: coreApiClientMock.mock.instances[0],- request: body,+ request: payload,});expect(result).toEqual({status: 'imported',@@ -79,17 +62,15 @@ describe('import-call-recording-artifacts', () => {});});- it('ignores caller-supplied provider ids instead of forwarding them', async () => {- const result = await importCallRecordingArtifactsHandler(- buildRoutePayload({- callRecordingId: 'call-recording-1',- requestedAt: '2026-01-01T14:06:00.000Z',- event: 'transcript.done',- externalBotId: 'forged-bot-id',- externalRecordingId: 'forged-recording-id',- transcriptId: 'forged-transcript-id',- } as never),- );+ it('ignores payload-supplied provider ids instead of forwarding them', async () => {+ const result = await importCallRecordingArtifactsHandler({+ callRecordingId: 'call-recording-1',+ requestedAt: '2026-01-01T14:06:00.000Z',+ event: 'transcript.done',+ externalBotId: 'forged-bot-id',+ externalRecordingId: 'forged-recording-id',+ transcriptId: 'forged-transcript-id',+ });expect(importCallRecordingArtifactsMock).toHaveBeenCalledWith({client: coreApiClientMock.mock.instances[0],@@ -101,10 +82,10 @@ describe('import-call-recording-artifacts', () => {expect(result).toEqual(expect.objectContaining({ status: 'imported' }));});- it('skips invalid continuation requests without touching the worker flow', async () => {- const result = await importCallRecordingArtifactsHandler(- buildRoutePayload({ requestedAt: '2026-01-01T14:06:00.000Z' }),- );+ it('skips invalid import payloads without touching the worker flow', async () => {+ const result = await importCallRecordingArtifactsHandler({+ requestedAt: '2026-01-01T14:06:00.000Z',+ });expect(importCallRecordingArtifactsMock).not.toHaveBeenCalled();expect(result).toEqual({@@ -113,4 +94,20 @@ describe('import-call-recording-artifacts', () => {reason: 'invalid call recording artifacts import request',});});++ it('rethrows an import failure as retryable so the queue redelivers it', async () => {+ importCallRecordingArtifactsMock.mockRejectedValue(+ new Error('Service unavailable'),+ );++ await expect(+ importCallRecordingArtifactsHandler({+ callRecordingId: 'call-recording-1',+ requestedAt: '2026-01-01T14:06:00.000Z',+ }),+ ).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ message: expect.stringContaining('Service unavailable'),+ });+ });});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/process-recall-webhook.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/process-recall-webhook.test.tsindex 27c18e961b5..7a99ffdc8e7 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@@ -6,7 +6,7 @@ import processRecallWebhookLogicFunction, {const queryMock = vi.hoisted(() => vi.fn());const mutationMock = vi.hoisted(() => vi.fn());-const requestArtifactImportMock = vi.hoisted(() => vi.fn());+const enqueueArtifactImportMock = vi.hoisted(() => vi.fn());vi.mock('twenty-client-sdk/core', () => ({CoreApiClient: class {@@ -16,9 +16,9 @@ vi.mock('twenty-client-sdk/core', () => ({}));vi.mock(- 'src/logic-functions/data/request-call-recording-artifacts-import.util',+ 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util',() => ({- requestCallRecordingArtifactsImport: requestArtifactImportMock,+ enqueueCallRecordingArtifactsImport: enqueueArtifactImportMock,}),);@@ -68,8 +68,8 @@ describe('process-recall-webhook', () => {mutationMock.mockResolvedValue({updateCallRecording: { id: 'call-recording-1' },});- requestArtifactImportMock.mockReset();- requestArtifactImportMock.mockResolvedValue(true);+ enqueueArtifactImportMock.mockReset();+ enqueueArtifactImportMock.mockResolvedValue(undefined);});afterEach(() => {@@ -115,7 +115,7 @@ describe('process-recall-webhook', () => {id: true,},});- expect(requestArtifactImportMock).toHaveBeenCalledWith(+ expect(enqueueArtifactImportMock).toHaveBeenCalledWith(expect.objectContaining({ callRecordingId: 'call-recording-1' }),);expect(result).toEqual({@@ -125,4 +125,17 @@ describe('process-recall-webhook', () => {callRecordingStatus: 'PROCESSING',});});++ it('marks processing failures as retryable so the platform redelivers the job', async () => {+ enqueueArtifactImportMock.mockRejectedValue(+ new Error('Service unavailable'),+ );++ await expect(+ processRecallWebhookHandler(buildRecordingDoneWebhookBody()),+ ).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ message: expect.stringContaining('Service unavailable'),+ });+ });});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/reconcile-upcoming-calendar-events.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/reconcile-upcoming-calendar-events.test.tsindex 34e3a71cc20..a897f5892d8 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/reconcile-upcoming-calendar-events.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/reconcile-upcoming-calendar-events.test.ts@@ -1,7 +1,6 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { type RoutePayload } from 'twenty-sdk/define';+import { beforeEach, describe, expect, it, vi } from 'vitest';-import routeLogicFunction, {+import reconcileLogicFunction, {reconcileUpcomingCalendarEventsHandler,} from 'src/logic-functions/reconcile-upcoming-calendar-events';@@ -15,8 +14,6 @@ vi.mock('twenty-client-sdk/core', () => ({},}));-const fetchMock = vi.fn();-type CalendarEventNode = {id: string;title: string;@@ -31,7 +28,6 @@ type RecordsQuery = {filter: {id?: { in: string[] };startsAt?: { in: string[] };- isCanceled?: { eq: boolean };};};};@@ -57,42 +53,11 @@ const buildConnection = <TNode>(nodes: TNode[]) => ({edges: nodes.map((node) => ({ node })),});-const readSweepQueries = (): unknown[] =>- queryMock.mock.calls.filter(- ([query]) => query.calendarEvents?.__args.filter.isCanceled !== undefined,- );-let upcomingCalendarEventNodes: CalendarEventNode[];-const buildRoutePayload = (- body: object | null,-): RoutePayload<{ calendarEventIds?: string[] }> =>- ({- body,- headers: {},- queryStringParameters: {},- pathParameters: {},- isBase64Encoded: false,- rawBody: undefined,- requestContext: { http: { method: 'POST', path: '/' } },- userWorkspaceId: null,- }) as never;--const BATCH_RESULT = {- reconciledCalendarEventIds: ['calendar-event-1'],- failedCalendarEventIds: [],- remainingCalendarEventIds: [],- actionCounts: { created: 0, updated: 0, canceled: 0, skipped: 1, failed: 0 },- continuationRequested: false,-};-describe('reconcileUpcomingCalendarEventsHandler', () => {beforeEach(() => {vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', 'https://acme.functions.example.com');- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));upcomingCalendarEventNodes = [];queryMock.mockImplementation(async (query: RecordsQuery) => {if (query.calendarEvents !== undefined) {@@ -123,9 +88,7 @@ describe('reconcileUpcomingCalendarEventsHandler', () => {}return {- calendarEvents: buildConnection(- upcomingCalendarEventNodes.map(({ id }) => ({ id })),- ),+ calendarEvents: buildConnection(upcomingCalendarEventNodes),};}@@ -137,58 +100,31 @@ describe('reconcileUpcomingCalendarEventsHandler', () => {});});- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();- });-- it('is configured as an authenticated route with a self-invokable timeout', () => {- expect(routeLogicFunction.config).toEqual(+ it('is configured as an enqueue-only batch worker', () => {+ expect(reconcileLogicFunction.config).toEqual(expect.objectContaining({name: 'reconcile-upcoming-calendar-events',timeoutSeconds: 900,- httpRouteTriggerSettings: {- path: '/call-recorder/reconcile-upcoming-calendar-events',- httpMethod: 'POST',- isAuthRequired: true,- },}),);- });-- it('processes explicit calendar event ids without sweeping', async () => {- upcomingCalendarEventNodes = [- buildUpcomingCalendarEventNode('calendar-event-1'),- ];-- const result = await reconcileUpcomingCalendarEventsHandler(- buildRoutePayload({ calendarEventIds: ['calendar-event-1'] }),+ expect(reconcileLogicFunction.config).not.toHaveProperty(+ 'httpRouteTriggerSettings',);-- expect(result).toEqual({ outcome: 'processed', ...BATCH_RESULT });- expect(queryMock).toHaveBeenCalledWith(- expect.objectContaining({- calendarEvents: expect.objectContaining({- __args: expect.objectContaining({- filter: { id: { in: ['calendar-event-1'] } },- }),- }),- }),+ expect(reconcileLogicFunction.config).not.toHaveProperty(+ 'cronTriggerSettings',);- expect(readSweepQueries()).toEqual([]);});- it('sweeps upcoming calendar events when no ids are given', async () => {+ it('reconciles the calendar events of its batch payload', async () => {upcomingCalendarEventNodes = [buildUpcomingCalendarEventNode('calendar-event-1'),buildUpcomingCalendarEventNode('calendar-event-2'),];- const result = await reconcileUpcomingCalendarEventsHandler(- buildRoutePayload(null),- );+ const result = await reconcileUpcomingCalendarEventsHandler({+ calendarEventIds: ['calendar-event-1', 'calendar-event-2'],+ });- expect(readSweepQueries()).toHaveLength(1);expect(queryMock).toHaveBeenCalledWith(expect.objectContaining({calendarEvents: expect.objectContaining({@@ -201,8 +137,6 @@ describe('reconcileUpcomingCalendarEventsHandler', () => {expect(result).toEqual({outcome: 'processed',reconciledCalendarEventIds: ['calendar-event-1', 'calendar-event-2'],- failedCalendarEventIds: [],- remainingCalendarEventIds: [],actionCounts: {created: 0,updated: 0,@@ -210,44 +144,32 @@ describe('reconcileUpcomingCalendarEventsHandler', () => {skipped: 2,failed: 0,},- continuationRequested: false,});});- it('short-circuits an empty sweep without running batches', async () => {- const result = await reconcileUpcomingCalendarEventsHandler(- buildRoutePayload({}),- );-- expect(result).toEqual({ outcome: 'nothing-to-reconcile' });- expect(queryMock).toHaveBeenCalledTimes(1);- });-- it('does not sweep when an empty calendar event selection is sent', async () => {- const result = await reconcileUpcomingCalendarEventsHandler(- buildRoutePayload({ calendarEventIds: [] }),- );-- expect(result).toEqual({ outcome: 'nothing-selected' });+ it('skips payloads without calendar event ids', async () => {+ expect(await reconcileUpcomingCalendarEventsHandler({})).toEqual({+ outcome: 'nothing-selected',+ });+ expect(await reconcileUpcomingCalendarEventsHandler(null)).toEqual({+ outcome: 'nothing-selected',+ });+ expect(+ await reconcileUpcomingCalendarEventsHandler({ calendarEventIds: [] }),+ ).toEqual({ outcome: 'nothing-selected' });expect(queryMock).not.toHaveBeenCalled();});- it('passes a deadline that reserves time for the continuation request', async () => {- upcomingCalendarEventNodes = [- buildUpcomingCalendarEventNode('calendar-event-1'),- ];+ it('rethrows a batch failure as retryable so the queue redelivers it', async () => {+ queryMock.mockRejectedValue(new Error('Service unavailable'));- const result = await reconcileUpcomingCalendarEventsHandler(- buildRoutePayload({ calendarEventIds: ['calendar-event-1'] }),- );-- expect(result).toEqual(- expect.objectContaining({- outcome: 'processed',- remainingCalendarEventIds: [],- continuationRequested: false,+ await expect(+ reconcileUpcomingCalendarEventsHandler({+ calendarEventIds: ['calendar-event-1'],}),- );- expect(fetchMock).not.toHaveBeenCalled();+ ).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ message: expect.stringContaining('Service unavailable'),+ });});});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/start-post-install-backfills.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/start-post-install-backfills.test.tsindex 55fc3cc0dc3..cee6a1324e6 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/start-post-install-backfills.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/start-post-install-backfills.test.ts@@ -1,99 +1,54 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';-import { GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH } from 'src/constants/generate-call-recording-summaries-route-path';-import { RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH } from 'src/constants/reconcile-upcoming-calendar-events-route-path';+import { SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/sweep-upcoming-calendar-events-logic-function-universal-identifier';+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';import postInstallLogicFunction, {startPostInstallBackfillsHandler,} from 'src/logic-functions/start-post-install-backfills';-const FUNCTIONS_BASE_URL = 'https://acme.functions.example.com';+const enqueueJobsMock = vi.hoisted(() => vi.fn());-const fetchMock = vi.fn();--const fetchedRoutePaths = (): string[] =>- fetchMock.mock.calls.map(([requestUrl]) =>- String(requestUrl).replace(FUNCTIONS_BASE_URL, ''),- );+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ enqueueJobs: enqueueJobsMock,+}));describe('start-post-install-backfills', () => {beforeEach(() => {vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', FUNCTIONS_BASE_URL);- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));- });-- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();+ enqueueJobsMock.mockResolvedValue({ enqueued: true, enqueuedJobsCount: 1 });});- it('is configured to run on app version upgrades', () => {+ it('is configured to run on fresh installs only', () => {expect(postInstallLogicFunction.config).toEqual(expect.objectContaining({name: 'start-post-install-backfills',timeoutSeconds: 30,- shouldRunOnVersionUpgrade: true,}),);+ expect(postInstallLogicFunction.config).not.toHaveProperty(+ 'shouldRunOnVersionUpgrade',+ );});- it('seeds the sweep and skips summaries on a fresh install', async () => {- const result = await startPostInstallBackfillsHandler({- newVersion: '1.0.7',- });+ it('enqueues the upcoming calendar events sweep', async () => {+ const result = await startPostInstallBackfillsHandler();- expect(result).toEqual({- calendarEventSweepOutcome: 'sweep-requested',- summaryBackfillOutcome: 'skipped-initial-install',+ expect(result).toEqual({ calendarEventSweepOutcome: 'sweep-enqueued' });+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier:+ SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: [{}],+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,});- expect(fetchedRoutePaths()).toEqual([- RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH,- ]);});- it('backfills summaries and skips the sweep on an upgrade', async () => {- const result = await startPostInstallBackfillsHandler({- previousVersion: '1.0.6',- newVersion: '1.0.7',- });+ it('throws when the sweep enqueue fails so the hook retries', async () => {+ enqueueJobsMock.mockRejectedValue(new Error('Network failed'));- expect(result).toEqual({- calendarEventSweepOutcome: 'skipped-upgrade',- summaryBackfillOutcome: 'backfill-requested',+ await expect(startPostInstallBackfillsHandler()).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ message: expect.stringContaining('Network failed'),});- expect(fetchedRoutePaths()).toEqual([- GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH,- ]);- });-- it('throws when the fresh-install sweep kickoff fails', async () => {- fetchMock.mockRejectedValue(new Error('Network failed'));-- await expect(- startPostInstallBackfillsHandler({ newVersion: '1.0.7' }),- ).rejects.toThrow(- 'Failed to start post-install backfills: upcoming calendar event sweep',- );- expect(fetchedRoutePaths()).not.toContain(- GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH,- );- });-- it('throws when the upgrade summary backfill kickoff fails', async () => {- fetchMock.mockRejectedValue(new Error('Network failed'));-- await expect(- startPostInstallBackfillsHandler({- previousVersion: '1.0.6',- newVersion: '1.0.7',- }),- ).rejects.toThrow(- 'Failed to start post-install backfills: call recording summary backfill',- );- expect(fetchedRoutePaths()).not.toContain(- RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH,- );});});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/summarize-call-recording.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/summarize-call-recording.test.tsindex 39bfdc15bbc..609677fb10d 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/summarize-call-recording.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/summarize-call-recording.test.ts@@ -13,7 +13,8 @@ vi.mock('twenty-client-sdk/core', () => ({},}));-vi.mock('twenty-sdk/logic-function', () => ({+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<object>()),runAgent: runAgentMock,}));@@ -137,6 +138,39 @@ describe('summarize-call-recording logic function', () => {});});+ it('rethrows a generation failure as retryable so the trigger is redelivered', async () => {+ runAgentMock.mockRejectedValue(new Error('Agent unavailable'));++ await expect(+ summarizeCallRecordingHandler(+ buildEvent({+ name: 'callRecording.updated',+ updatedFields: ['transcript'],+ }),+ ),+ ).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ message: expect.stringContaining('Agent unavailable'),+ });+ });++ it('returns a save error without rethrowing so a paid agent run is never redelivered', async () => {+ mutationMock.mockRejectedValue(new Error('Write timed out'));++ const result = await summarizeCallRecordingHandler(+ buildEvent({+ name: 'callRecording.updated',+ updatedFields: ['transcript'],+ }),+ );++ expect(result).toEqual({+ callRecordingId: 'call-recording-1',+ outcome: 'save-error',+ });+ expect(runAgentMock).toHaveBeenCalledTimes(1);+ });+it('skips summary-only updates to avoid re-entrancy', async () => {const result = await summarizeCallRecordingHandler(buildEvent({diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/sweep-upcoming-calendar-events.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/sweep-upcoming-calendar-events.test.tsindex 9e31761f018..3ffe56a43f8 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/sweep-upcoming-calendar-events.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/sweep-upcoming-calendar-events.test.ts@@ -1,120 +1,49 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { RECONCILE_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/reconcile-upcoming-calendar-events-logic-function-universal-identifier';+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';+import { UPCOMING_CALENDAR_EVENT_RECONCILIATION_BATCH_SIZE } from 'src/logic-functions/constants/upcoming-calendar-event-reconciliation-batch-size';import sweepLogicFunction, {sweepUpcomingCalendarEventsHandler,} from 'src/logic-functions/sweep-upcoming-calendar-events';const queryMock = vi.hoisted(() => vi.fn());-const mutationMock = vi.hoisted(() => vi.fn());+const enqueueJobsMock = vi.hoisted(() => vi.fn());vi.mock('twenty-client-sdk/core', () => ({CoreApiClient: class {query = queryMock;- mutation = mutationMock;},}));-const fetchMock = vi.fn();--type CalendarEventNode = {- id: string;- title: string;- isCanceled: boolean;- startsAt: string;- endsAt: string;-};--type RecordsQuery = {- calendarEvents?: {- __args: {- filter: {- id?: { in: string[] };- startsAt?: { in: string[] };- isCanceled?: { eq: boolean };- };- };- };- callRecordings?: { __args: { filter: Record<string, unknown> } };-};--const UPCOMING_STARTS_AT = new Date(Date.now() + 60 * 60 * 1000).toISOString();-const UPCOMING_ENDS_AT = new Date(- Date.now() + 2 * 60 * 60 * 1000,-).toISOString();--// Without a conference link the policy deterministically skips each meeting.-const buildUpcomingCalendarEventNode = (id: string): CalendarEventNode => ({- id,- title: 'Upcoming Sync',- isCanceled: false,- startsAt: UPCOMING_STARTS_AT,- endsAt: UPCOMING_ENDS_AT,-});+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ enqueueJobs: enqueueJobsMock,+}));const buildConnection = <TNode>(nodes: TNode[]) => ({pageInfo: { hasNextPage: false, endCursor: null },edges: nodes.map((node) => ({ node })),});-let upcomingCalendarEventNodes: CalendarEventNode[];+let upcomingCalendarEventIds: string[];describe('sweepUpcomingCalendarEventsHandler', () => {beforeEach(() => {vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', 'https://acme.functions.example.com');- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));- upcomingCalendarEventNodes = [];- queryMock.mockImplementation(async (query: RecordsQuery) => {- if (query.calendarEvents !== undefined) {- const filter = query.calendarEvents.__args.filter;-- if (filter.id !== undefined) {- const requestedIds = filter.id.in;-- return {- calendarEvents: buildConnection(- upcomingCalendarEventNodes.filter((node) =>- requestedIds.includes(node.id),- ),- ),- };- }-- if (filter.startsAt !== undefined) {- const requestedStartsAtValues = filter.startsAt.in;-- return {- calendarEvents: buildConnection(- upcomingCalendarEventNodes.filter((node) =>- requestedStartsAtValues.includes(node.startsAt),- ),- ),- };- }-- return {- calendarEvents: buildConnection(- upcomingCalendarEventNodes.map(({ id }) => ({ id })),- ),- };- }-- if (query.callRecordings !== undefined) {- return { callRecordings: buildConnection([]) };- }-- throw new Error(`Unhandled query: ${JSON.stringify(query)}`);- });- });-- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();+ upcomingCalendarEventIds = [];+ queryMock.mockImplementation(async () => ({+ calendarEvents: buildConnection(+ upcomingCalendarEventIds.map((id) => ({ id })),+ ),+ }));+ enqueueJobsMock.mockImplementation(async ({ payloads }) => ({+ enqueued: true,+ enqueuedJobsCount: payloads.length,+ }));});- it('is configured as a daily cron with a self-invokable timeout', () => {+ it('is configured as a daily cron', () => {expect(sweepLogicFunction.config).toEqual(expect.objectContaining({name: 'sweep-upcoming-calendar-events',@@ -124,11 +53,8 @@ describe('sweepUpcomingCalendarEventsHandler', () => {);});- it('reconciles every upcoming calendar event within the horizon', async () => {- upcomingCalendarEventNodes = [- buildUpcomingCalendarEventNode('calendar-event-1'),- buildUpcomingCalendarEventNode('calendar-event-2'),- ];+ it('enqueues one reconciliation batch for the upcoming calendar events', async () => {+ upcomingCalendarEventIds = ['calendar-event-1', 'calendar-event-2'];const result = await sweepUpcomingCalendarEventsHandler();@@ -141,52 +67,54 @@ describe('sweepUpcomingCalendarEventsHandler', () => {}),}),);- expect(queryMock).toHaveBeenCalledWith(- expect.objectContaining({- calendarEvents: expect.objectContaining({- __args: expect.objectContaining({- filter: { id: { in: ['calendar-event-1', 'calendar-event-2'] } },- }),- }),- }),- );+ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier:+ RECONCILE_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: [+ { calendarEventIds: ['calendar-event-1', 'calendar-event-2'] },+ ],+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ });expect(result).toEqual({- outcome: 'processed',- reconciledCalendarEventIds: ['calendar-event-1', 'calendar-event-2'],- failedCalendarEventIds: [],- remainingCalendarEventIds: [],- actionCounts: {- created: 0,- updated: 0,- canceled: 0,- skipped: 2,- failed: 0,- },- continuationRequested: false,+ outcome: 'batches-enqueued',+ calendarEventCount: 2,+ batchCount: 1,});});- it('short-circuits without running batches when nothing is upcoming', async () => {+ it('splits the window into batches of the reconciliation batch size', async () => {+ upcomingCalendarEventIds = Array.from(+ { length: UPCOMING_CALENDAR_EVENT_RECONCILIATION_BATCH_SIZE + 1 },+ (_, calendarEventIndex) => `calendar-event-${calendarEventIndex}`,+ );+const result = await sweepUpcomingCalendarEventsHandler();- expect(result).toEqual({ outcome: 'nothing-to-reconcile' });- expect(queryMock).toHaveBeenCalledTimes(1);- });+ const [{ payloads }] = enqueueJobsMock.mock.calls[0];- it('passes a deadline that reserves time for the continuation request', async () => {- upcomingCalendarEventNodes = [- buildUpcomingCalendarEventNode('calendar-event-1'),- ];+ expect(payloads).toHaveLength(2);+ expect(payloads[0].calendarEventIds).toHaveLength(+ UPCOMING_CALENDAR_EVENT_RECONCILIATION_BATCH_SIZE,+ );+ expect(payloads[1].calendarEventIds).toHaveLength(1);+ expect(result).toEqual(+ expect.objectContaining({ outcome: 'batches-enqueued', batchCount: 2 }),+ );+ });+ it('short-circuits without enqueuing when nothing is upcoming', async () => {const result = await sweepUpcomingCalendarEventsHandler();- expect(result).toEqual(- expect.objectContaining({- outcome: 'processed',- remainingCalendarEventIds: [],- continuationRequested: false,- }),- );- expect(fetchMock).not.toHaveBeenCalled();+ expect(result).toEqual({ outcome: 'nothing-to-reconcile' });+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it('marks sweep failures as retryable so the platform redelivers the job', async () => {+ queryMock.mockRejectedValue(new Error('Service unavailable'));++ await expect(sweepUpcomingCalendarEventsHandler()).rejects.toMatchObject({+ name: 'RetryableLogicFunctionError',+ message: expect.stringContaining('Service unavailable'),+ });});});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/enqueued-job-retry-limit.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/enqueued-job-retry-limit.tsnew file mode 100644index 00000000000..79b96fa6462--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/enqueued-job-retry-limit.ts@@ -0,0 +1,2 @@+// Redelivery is safe only because every enqueued handler is idempotent.+export const ENQUEUED_JOB_RETRY_LIMIT = 2;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/max-payloads-per-enqueue-jobs-call.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/max-payloads-per-enqueue-jobs-call.tsnew file mode 100644index 00000000000..8c1cfbd3a80--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/max-payloads-per-enqueue-jobs-call.ts@@ -0,0 +1,2 @@+// Server-enforced cap on the enqueueJobs mutation.+export const MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL = 200;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.tsnew file mode 100644index 00000000000..3984881a5d6--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-artifacts-import.test.ts@@ -0,0 +1,46 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/import-call-recording-artifacts-logic-function-universal-identifier';+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 one import job with a fresh request timestamp', async () => {+ await enqueueCallRecordingArtifactsImport({+ callRecordingId: 'call-recording-1',+ });++ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier:+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: [+ {+ callRecordingId: 'call-recording-1',+ requestedAt: expect.any(String),+ },+ ],+ 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',+ }),+ ).rejects.toThrow('Network failed');+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-logic-function-jobs.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-logic-function-jobs.test.tsnew file mode 100644index 00000000000..bcc7451acd5--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-logic-function-jobs.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++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 { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';++const enqueueJobsMock = vi.hoisted(() => vi.fn());++vi.mock('twenty-sdk/logic-function', () => ({+ enqueueJobs: enqueueJobsMock,+}));++const TARGET_UNIVERSAL_IDENTIFIER = '5a2f4d2a-1a1e-4c66-8a54-1f0a2b3c4d5e';++describe('enqueueLogicFunctionJobs', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ enqueueJobsMock.mockImplementation(async ({ payloads }) => ({+ enqueued: true,+ enqueuedJobsCount: payloads.length,+ }));+ });++ it('enqueues a small payload list in a single call', async () => {+ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier: TARGET_UNIVERSAL_IDENTIFIER,+ payloads: [{ batchIndex: 0 }, { batchIndex: 1 }],+ });++ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier: TARGET_UNIVERSAL_IDENTIFIER,+ payloads: [{ batchIndex: 0 }, { batchIndex: 1 }],+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ });+ });++ it('splits payload lists above the mutation cap into multiple calls', async () => {+ const payloads = Array.from(+ { length: MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL + 1 },+ (_, payloadIndex) => ({ payloadIndex }),+ );++ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier: TARGET_UNIVERSAL_IDENTIFIER,+ payloads,+ });++ expect(enqueueJobsMock).toHaveBeenCalledTimes(2);+ expect(enqueueJobsMock.mock.calls[0][0].payloads).toHaveLength(+ MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL,+ );+ expect(enqueueJobsMock.mock.calls[1][0].payloads).toEqual([+ { payloadIndex: MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL },+ ]);+ });++ it('stops at the first failed chunk', async () => {+ const payloads = Array.from(+ { length: MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL * 2 },+ (_, payloadIndex) => ({ payloadIndex }),+ );++ enqueueJobsMock+ .mockResolvedValueOnce({ enqueued: true })+ .mockRejectedValueOnce(new Error('Network failed'));++ await expect(+ enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier: TARGET_UNIVERSAL_IDENTIFIER,+ payloads,+ }),+ ).rejects.toThrow('Network failed');+ expect(enqueueJobsMock).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/find-call-recording-ids-missing-summary.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/find-call-recording-ids-missing-summary.test.tsdeleted file mode 100644index bcd262a983d..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/find-call-recording-ids-missing-summary.test.ts+++ /dev/null@@ -1,128 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { findCallRecordingIdsMissingSummary } from 'src/logic-functions/data/find-call-recording-ids-missing-summary.util';--const TRANSCRIPT = [- {- participant: { name: 'Alex' },- words: [{ text: 'Hello' }, { text: 'team' }],- },-];--const buildConnection = (- nodes: object[],- pageInfo: { hasNextPage: boolean; endCursor: string | null },-) => ({- callRecordings: {- pageInfo,- edges: nodes.map((node) => ({ node })),- },-});--describe('findCallRecordingIdsMissingSummary', () => {- it('targets app-created completed recordings with a transcript', async () => {- let capturedFilter: unknown;- const query = vi.fn(async (queryArg: any) => {- capturedFilter = queryArg.callRecordings.__args.filter;-- return buildConnection([], { hasNextPage: false, endCursor: null });- });-- await findCallRecordingIdsMissingSummary({ query } as never);-- expect(capturedFilter).toEqual({- status: { eq: 'COMPLETED' },- transcript: { is: 'NOT_NULL' },- createdBy: {- source: { eq: 'APPLICATION' },- name: { eq: 'Call Recorder' },- },- });- });-- it('keeps only recordings missing a summary, newest first, across pages', async () => {- const query = vi- .fn()- .mockResolvedValueOnce(- buildConnection(- [- {- id: 'call-recording-old',- createdAt: '2026-06-01T10:00:00.000Z',- transcript: TRANSCRIPT,- summary: null,- },- {- id: 'call-recording-summarized',- createdAt: '2026-06-20T10:00:00.000Z',- transcript: TRANSCRIPT,- summary: { markdown: '## Overview\nDone.' },- },- ],- { hasNextPage: true, endCursor: 'cursor-1' },- ),- )- .mockResolvedValueOnce(- buildConnection(- [- {- id: 'call-recording-new',- createdAt: '2026-06-30T10:00:00.000Z',- transcript: TRANSCRIPT,- summary: { markdown: '' },- },- ],- { hasNextPage: false, endCursor: 'cursor-2' },- ),- );-- const callRecordingIds = await findCallRecordingIdsMissingSummary({- query,- } as never);-- expect(callRecordingIds).toEqual([- 'call-recording-new',- 'call-recording-old',- ]);- expect(query).toHaveBeenCalledTimes(2);- });-- it('ignores recordings whose transcript cannot produce a summary prompt', async () => {- const query = vi.fn().mockResolvedValue(- buildConnection(- [- {- id: 'call-recording-empty-transcript',- createdAt: '2026-07-01T10:00:00.000Z',- transcript: [],- summary: null,- },- {- id: 'call-recording-empty-words',- createdAt: '2026-06-30T10:00:00.000Z',- transcript: [- {- participant: { name: 'Alex' },- words: [{ text: ' ' }],- },- ],- summary: null,- },- {- id: 'call-recording-valid',- createdAt: '2026-06-01T10:00:00.000Z',- transcript: TRANSCRIPT,- summary: null,- },- ],- { hasNextPage: false, endCursor: null },- ),- );-- const callRecordingIds = await findCallRecordingIdsMissingSummary({- query,- } as never);-- expect(callRecordingIds).toEqual(['call-recording-valid']);- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/post-to-own-route.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/post-to-own-route.test.tsdeleted file mode 100644index 6d738c37485..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/post-to-own-route.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { postToOwnRoute } from 'src/logic-functions/data/post-to-own-route.util';--const fetchMock = vi.fn();--describe('postToOwnRoute', () => {- beforeEach(() => {- vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', 'https://acme.functions.example.com');- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));- });-- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();- });-- it('posts to the functions origin when resolved', async () => {- const result = await postToOwnRoute({- path: '/call-recorder/some-route',- body: { key: 'value' },- });-- expect(result).toBe(true);- expect(fetchMock).toHaveBeenCalledTimes(1);- const [requestUrl, requestInit] = fetchMock.mock.calls[0];- expect(requestUrl).toBe(- 'https://acme.functions.example.com/call-recorder/some-route',- );- expect(requestInit.method).toBe('POST');- expect(requestInit.body).toBe(JSON.stringify({ key: 'value' }));- expect(requestInit.signal).toBeInstanceOf(AbortSignal);- });-- it('treats timeout as a successfully flushed request', async () => {- const timeoutError = new Error('Timed out');- timeoutError.name = 'TimeoutError';- fetchMock.mockRejectedValue(timeoutError);-- await expect(- postToOwnRoute({ path: '/call-recorder/some-route', body: {} }),- ).resolves.toBe(true);- });-- it('returns false when the request fails before flushing', async () => {- fetchMock.mockRejectedValue(new Error('Network failed'));-- await expect(- postToOwnRoute({ path: '/call-recorder/some-route', body: {} }),- ).resolves.toBe(false);- });-- it('returns false when the route base url cannot be resolved', async () => {- vi.stubEnv('TWENTY_FUNCTIONS_URL', '');- vi.stubEnv('TWENTY_API_URL', '');-- await expect(- postToOwnRoute({ path: '/call-recorder/some-route', body: {} }),- ).resolves.toBe(false);- expect(fetchMock).not.toHaveBeenCalled();- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/request-call-recording-summaries-backfill.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/request-call-recording-summaries-backfill.test.tsdeleted file mode 100644index 9f12afc5672..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/request-call-recording-summaries-backfill.test.ts+++ /dev/null@@ -1,40 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH } from 'src/constants/generate-call-recording-summaries-route-path';-import { requestCallRecordingSummariesBackfill } from 'src/logic-functions/data/request-call-recording-summaries-backfill.util';--const fetchMock = vi.fn();--describe('requestCallRecordingSummariesBackfill', () => {- beforeEach(() => {- vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', 'https://acme.functions.example.com');- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));- });-- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();- });-- it('posts an empty body to the summary generation route', async () => {- const result = await requestCallRecordingSummariesBackfill();-- expect(result).toBe(true);- expect(fetchMock).toHaveBeenCalledTimes(1);- const [requestUrl, requestInit] = fetchMock.mock.calls[0];- expect(requestUrl).toBe(- `https://acme.functions.example.com${GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH}`,- );- expect(requestInit.method).toBe('POST');- expect(requestInit.body).toBe(JSON.stringify({}));- });-- it('reports a kickoff that failed to fire', async () => {- fetchMock.mockRejectedValue(new Error('Network failed'));-- await expect(requestCallRecordingSummariesBackfill()).resolves.toBe(false);- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/request-upcoming-calendar-events-reconciliation.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/request-upcoming-calendar-events-reconciliation.test.tsdeleted file mode 100644index 04823969b81..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/request-upcoming-calendar-events-reconciliation.test.ts+++ /dev/null@@ -1,58 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH } from 'src/constants/reconcile-upcoming-calendar-events-route-path';-import { requestUpcomingCalendarEventsReconciliation } from 'src/logic-functions/data/request-upcoming-calendar-events-reconciliation.util';--const fetchMock = vi.fn();--describe('requestUpcomingCalendarEventsReconciliation', () => {- beforeEach(() => {- vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', 'https://acme.functions.example.com');- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));- });-- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();- });-- it('posts an empty body to start a full sweep', async () => {- const result = await requestUpcomingCalendarEventsReconciliation();-- expect(result).toBe(true);- expect(fetchMock).toHaveBeenCalledTimes(1);- const [requestUrl, requestInit] = fetchMock.mock.calls[0];- expect(requestUrl).toBe(- `https://acme.functions.example.com${RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH}`,- );- expect(requestInit.method).toBe('POST');- expect(requestInit.body).toBe(JSON.stringify({}));- });-- it('posts the remaining calendar event ids to continue a sweep', async () => {- await requestUpcomingCalendarEventsReconciliation({- calendarEventIds: ['calendar-event-1', 'calendar-event-2'],- });-- const [requestUrl, requestInit] = fetchMock.mock.calls[0];- expect(requestUrl).toBe(- `https://acme.functions.example.com${RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH}`,- );- expect(requestInit.body).toBe(- JSON.stringify({- calendarEventIds: ['calendar-event-1', 'calendar-event-2'],- }),- );- });-- it('reports a kickoff that failed to fire', async () => {- fetchMock.mockRejectedValue(new Error('Network failed'));-- await expect(requestUpcomingCalendarEventsReconciliation()).resolves.toBe(- false,- );- });-});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.tsnew file mode 100644index 00000000000..80363c3c995--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts@@ -0,0 +1,14 @@+import { IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/import-call-recording-artifacts-logic-function-universal-identifier';+import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';++export const enqueueCallRecordingArtifactsImport = async ({+ callRecordingId,+}: {+ callRecordingId: string;+}): Promise<void> => {+ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier:+ IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: [{ callRecordingId, requestedAt: new Date().toISOString() }],+ });+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-logic-function-jobs.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-logic-function-jobs.util.tsnew file mode 100644index 00000000000..2e856953334--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-logic-function-jobs.util.ts@@ -0,0 +1,24 @@+import { enqueueJobs } from 'twenty-sdk/logic-function';++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 { getBatches } from 'src/logic-functions/utils/get-batches.util';++export const enqueueLogicFunctionJobs = async ({+ logicFunctionUniversalIdentifier,+ payloads,+}: {+ logicFunctionUniversalIdentifier: string;+ payloads: Record<string, unknown>[];+}): Promise<void> => {+ for (const payloadChunk of getBatches(+ payloads,+ MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL,+ )) {+ await enqueueJobs({+ logicFunctionUniversalIdentifier,+ payloads: payloadChunk,+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ });+ }+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-ids-for-calendar-events.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-ids-for-calendar-events.util.tsindex 4397a3bec8c..531c9649cb2 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-ids-for-calendar-events.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-ids-for-calendar-events.util.ts@@ -6,6 +6,7 @@ import {fetchAllNodes,type ConnectionPage,} from 'src/logic-functions/data/fetch-all-nodes.util';+import { getBatches } from 'src/logic-functions/utils/get-batches.util';const CALENDAR_EVENT_ID_BATCH_SIZE = TWENTY_PAGE_SIZE;@@ -13,26 +14,6 @@ type CallRecordingIdNode = {id: string;};-const getCalendarEventIdBatches = (calendarEventIds: string[]): string[][] => {- const uniqueCalendarEventIds = [...new Set(calendarEventIds)];- const calendarEventIdBatches: string[][] = [];-- for (- let batchStartIndex = 0;- batchStartIndex < uniqueCalendarEventIds.length;- batchStartIndex += CALENDAR_EVENT_ID_BATCH_SIZE- ) {- calendarEventIdBatches.push(- uniqueCalendarEventIds.slice(- batchStartIndex,- batchStartIndex + CALENDAR_EVENT_ID_BATCH_SIZE,- ),- );- }-- return calendarEventIdBatches;-};-export const findCallRecordingIdsForCalendarEvents = async (client: CoreApiClient,{ calendarEventIds }: { calendarEventIds: string[] },@@ -43,8 +24,9 @@ export const findCallRecordingIdsForCalendarEvents = async (const callRecordingIds: string[] = [];- for (const calendarEventIdBatch of getCalendarEventIdBatches(- calendarEventIds,+ for (const calendarEventIdBatch of getBatches(+ [...new Set(calendarEventIds)],+ CALENDAR_EVENT_ID_BATCH_SIZE,)) {const callRecordingNodes = await fetchAllNodes<CallRecordingIdNode>(async (afterCursor) => {diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-ids-missing-summary.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-ids-missing-summary.util.tsdeleted file mode 100644index d9aef3f815f..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recording-ids-missing-summary.util.ts+++ /dev/null@@ -1,76 +0,0 @@-import { isUndefined } from '@sniptt/guards';-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { APP_DISPLAY_NAME } from 'src/constants/app-display-name';-import { CALL_RECORDER_CREATED_BY_SOURCE } from 'src/logic-functions/constants/call-recorder-created-by-source';-import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';-import { TWENTY_PAGE_SIZE } from 'src/logic-functions/constants/twenty-page-size';-import {- fetchAllNodes,- type ConnectionPage,-} from 'src/logic-functions/data/fetch-all-nodes.util';-import { buildCallRecordingSummaryPrompt } from 'src/logic-functions/domain/build-call-recording-summary-prompt.util';-import { getString } from 'src/logic-functions/utils/get-string.util';--type CallRecordingSummaryStateNode = {- id: string;- createdAt?: string | null;- transcript?: unknown;- summary?: { markdown?: string | null } | null;-};--export const findCallRecordingIdsMissingSummary = async (- client: CoreApiClient,-): Promise<string[]> => {- const callRecordingNodes = await fetchAllNodes<CallRecordingSummaryStateNode>(- async (afterCursor) => {- const queryResult = await client.query({- callRecordings: {- __args: {- filter: {- status: { eq: CallRecordingStatus.COMPLETED },- transcript: { is: 'NOT_NULL' },- // Never sweep recordings another app or a user created — agent- // runs are billed, so the unattended path only spends on ours.- createdBy: {- source: { eq: CALL_RECORDER_CREATED_BY_SOURCE },- name: { eq: APP_DISPLAY_NAME },- },- },- first: TWENTY_PAGE_SIZE,- ...(isUndefined(afterCursor) ? {} : { after: afterCursor }),- },- pageInfo: {- hasNextPage: true,- endCursor: true,- },- edges: {- node: {- id: true,- createdAt: true,- transcript: true,- summary: { markdown: true },- },- },- },- });-- return queryResult.callRecordings as- | ConnectionPage<CallRecordingSummaryStateNode>- | undefined;- },- );-- return callRecordingNodes- .filter(- (callRecording) =>- isUndefined(getString(callRecording.summary?.markdown)) &&- buildCallRecordingSummaryPrompt({- transcript: callRecording.transcript,- }) !== undefined,- )- .sort((left, right) =>- (right.createdAt ?? '').localeCompare(left.createdAt ?? ''),- )- .map((callRecording) => callRecording.id);-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/post-to-own-route.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/post-to-own-route.util.tsdeleted file mode 100644index 2cd3c4d5a62..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/post-to-own-route.util.ts+++ /dev/null@@ -1,38 +0,0 @@-import { RestApiClient } from 'twenty-client-sdk/rest';--const OWN_ROUTE_FLUSH_MS = 5_000;--// Fire-and-forget POST to one of this app's own HTTP routes; a timeout only-// means the request was flushed, not that the target run failed.-export const postToOwnRoute = async ({- path,- body,-}: {- path: string;- body: object;-}): Promise<boolean> => {- try {- const client = new RestApiClient();-- await client.post(`/s${path}`, body, {- signal: AbortSignal.timeout(OWN_ROUTE_FLUSH_MS),- });-- return true;- } catch (error) {- if (- error instanceof Error &&- (error.name === 'TimeoutError' || error.name === 'AbortError')- ) {- return true;- }-- if (process.env.NODE_ENV !== 'test') {- console.error(- `[call-recorder] request to own route ${path} failed to fire: ${error instanceof Error ? error.message : String(error)}`,- );- }-- return false;- }-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-artifacts-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-artifacts-import.util.tsdeleted file mode 100644index 5e06fddabb5..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-artifacts-import.util.ts+++ /dev/null@@ -1,11 +0,0 @@-import { IMPORT_CALL_RECORDING_ARTIFACTS_ROUTE_PATH } from 'src/constants/import-call-recording-artifacts-route-path';-import { postToOwnRoute } from 'src/logic-functions/data/post-to-own-route.util';-import { type CallRecordingArtifactsImportRequest } from 'src/logic-functions/types/call-recording-artifacts-import-request.type';--export const requestCallRecordingArtifactsImport = async (- request: CallRecordingArtifactsImportRequest,-): Promise<boolean> =>- postToOwnRoute({- path: IMPORT_CALL_RECORDING_ARTIFACTS_ROUTE_PATH,- body: request,- });diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-summaries-backfill.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-summaries-backfill.util.tsdeleted file mode 100644index 9037f8652b8..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-summaries-backfill.util.ts+++ /dev/null@@ -1,9 +0,0 @@-import { GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH } from 'src/constants/generate-call-recording-summaries-route-path';-import { postToOwnRoute } from 'src/logic-functions/data/post-to-own-route.util';--export const requestCallRecordingSummariesBackfill =- async (): Promise<boolean> =>- postToOwnRoute({- path: GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH,- body: {},- });diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-summaries-continuation.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-summaries-continuation.util.tsdeleted file mode 100644index 93043b6d5e9..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-call-recording-summaries-continuation.util.ts+++ /dev/null@@ -1,12 +0,0 @@-import { GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH } from 'src/constants/generate-call-recording-summaries-route-path';-import { postToOwnRoute } from 'src/logic-functions/data/post-to-own-route.util';--export const requestCallRecordingSummariesContinuation = async ({- callRecordingIds,-}: {- callRecordingIds: string[];-}): Promise<boolean> =>- postToOwnRoute({- path: GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH,- body: { callRecordingIds },- });diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-upcoming-calendar-events-reconciliation.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-upcoming-calendar-events-reconciliation.util.tsdeleted file mode 100644index 68ee3895416..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/request-upcoming-calendar-events-reconciliation.util.ts+++ /dev/null@@ -1,14 +0,0 @@-import { isUndefined } from '@sniptt/guards';--import { RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH } from 'src/constants/reconcile-upcoming-calendar-events-route-path';-import { postToOwnRoute } from 'src/logic-functions/data/post-to-own-route.util';--export const requestUpcomingCalendarEventsReconciliation = async ({- calendarEventIds,-}: {- calendarEventIds?: string[];-} = {}): Promise<boolean> =>- postToOwnRoute({- path: RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH,- body: isUndefined(calendarEventIds) ? {} : { calendarEventIds },- });diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/extract-call-recording-summary-markdown.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/extract-call-recording-summary-markdown.test.tsdeleted file mode 100644index 5e3cbdecf04..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/extract-call-recording-summary-markdown.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { describe, expect, it } from 'vitest';--import { extractCallRecordingSummaryMarkdown } from 'src/logic-functions/domain/extract-call-recording-summary-markdown.util';--describe('extractCallRecordingSummaryMarkdown', () => {- it('returns the trimmed response markdown on success', () => {- expect(- extractCallRecordingSummaryMarkdown({- success: true,- error: null,- result: { response: ' ## Overview\nGreat call. ' },- }),- ).toBe('## Overview\nGreat call.');- });-- it('returns undefined when the run failed', () => {- expect(- extractCallRecordingSummaryMarkdown({- success: false,- error: 'no more available credits',- result: null,- }),- ).toBeUndefined();- });-- it('returns undefined when the response is empty or missing', () => {- expect(- extractCallRecordingSummaryMarkdown({- success: true,- error: null,- result: { response: ' ' },- }),- ).toBeUndefined();- expect(- extractCallRecordingSummaryMarkdown({- success: true,- error: null,- result: {},- }),- ).toBeUndefined();- });-- it('returns the no-summary verdict verbatim', () => {- expect(- extractCallRecordingSummaryMarkdown({- success: true,- error: null,- result: { response: 'No summary available.' },- }),- ).toBe('No summary available.');- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-call-recording-summary-agent-response.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-call-recording-summary-agent-response.test.tsnew file mode 100644index 00000000000..e8b30cba13d--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/parse-call-recording-summary-agent-response.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';++import { parseCallRecordingSummaryAgentResponse } from 'src/logic-functions/domain/parse-call-recording-summary-agent-response.util';++describe('parseCallRecordingSummaryAgentResponse', () => {+ it('returns the trimmed response markdown on success', () => {+ expect(+ parseCallRecordingSummaryAgentResponse({+ success: true,+ error: null,+ result: { response: ' ## Overview\nGreat call. ' },+ }),+ ).toEqual({ outcome: 'summarized', markdown: '## Overview\nGreat call.' });+ });++ it('returns undefined when the run failed', () => {+ expect(+ parseCallRecordingSummaryAgentResponse({+ success: false,+ error: 'no more available credits',+ result: null,+ }),+ ).toBeUndefined();+ });++ it('returns undefined when the response is empty or missing', () => {+ expect(+ parseCallRecordingSummaryAgentResponse({+ success: true,+ error: null,+ result: { response: ' ' },+ }),+ ).toBeUndefined();+ expect(+ parseCallRecordingSummaryAgentResponse({+ success: true,+ error: null,+ result: {},+ }),+ ).toBeUndefined();+ });++ it('extracts a grounded reason when the transcript cannot be summarized', () => {+ expect(+ parseCallRecordingSummaryAgentResponse({+ success: true,+ error: null,+ result: {+ response:+ 'SUMMARY_UNAVAILABLE: The transcript contains only greetings and audio checks.',+ },+ }),+ ).toEqual({+ outcome: 'not-summarizable',+ reason: 'The transcript contains only greetings and audio checks.',+ });+ });++ it('rejects an unavailable marker without a reason', () => {+ expect(+ parseCallRecordingSummaryAgentResponse({+ success: true,+ error: null,+ result: { response: 'SUMMARY_UNAVAILABLE:' },+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/count-reconciliation-actions.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/count-reconciliation-actions.util.tsnew file mode 100644index 00000000000..00f0017fa5c--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/count-reconciliation-actions.util.ts@@ -0,0 +1,30 @@+import { type CallRecorderReconciliationActionCounts } from 'src/logic-functions/types/call-recorder-reconciliation-action-counts.type';+import { type CallRecorderReconciliationResult } from 'src/logic-functions/types/call-recorder-reconciliation-result.type';++const ACTION_COUNT_KEY_BY_ACTION: {+ [Action in CallRecorderReconciliationResult['action']]: Lowercase<Action>;+} = {+ CREATED: 'created',+ UPDATED: 'updated',+ CANCELED: 'canceled',+ SKIPPED: 'skipped',+ FAILED: 'failed',+};++export const countReconciliationActions = (+ reconciliationResults: CallRecorderReconciliationResult[],+): CallRecorderReconciliationActionCounts => {+ const actionCounts: CallRecorderReconciliationActionCounts = {+ created: 0,+ updated: 0,+ canceled: 0,+ skipped: 0,+ failed: 0,+ };++ for (const reconciliationResult of reconciliationResults) {+ actionCounts[ACTION_COUNT_KEY_BY_ACTION[reconciliationResult.action]] += 1;+ }++ return actionCounts;+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/extract-call-recording-summary-markdown.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/extract-call-recording-summary-markdown.util.tsdeleted file mode 100644index 740362e1069..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/extract-call-recording-summary-markdown.util.ts+++ /dev/null@@ -1,20 +0,0 @@-import { type RunAgentResult } from 'twenty-sdk/logic-function';--import { asRecord } from 'src/logic-functions/utils/as-record.util';-import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';--export const extractCallRecordingSummaryMarkdown = (- agentResult: RunAgentResult,-): string | undefined => {- if (!agentResult.success) {- return undefined;- }-- const response = asRecord(agentResult.result)?.response;-- if (!isNonEmptyString(response)) {- return undefined;- }-- return response.trim();-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-call-recording-summary-agent-response.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-call-recording-summary-agent-response.util.tsnew file mode 100644index 00000000000..aa9da12c935--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/parse-call-recording-summary-agent-response.util.ts@@ -0,0 +1,37 @@+import { type RunAgentResult } from 'twenty-sdk/logic-function';++import { CALL_RECORDING_SUMMARY_UNAVAILABLE_PREFIX } from 'src/constants/call-recording-summary-unavailable-prefix';+import { asRecord } from 'src/logic-functions/utils/as-record.util';+import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';++type ParsedCallRecordingSummaryAgentResponse =+ | { outcome: 'summarized'; markdown: string }+ | { outcome: 'not-summarizable'; reason: string };++export const parseCallRecordingSummaryAgentResponse = (+ agentResult: RunAgentResult,+): ParsedCallRecordingSummaryAgentResponse | undefined => {+ if (!agentResult.success) {+ return undefined;+ }++ const response = asRecord(agentResult.result)?.response;++ if (!isNonEmptyString(response)) {+ return undefined;+ }++ const trimmedResponse = response.trim();++ if (trimmedResponse.startsWith(CALL_RECORDING_SUMMARY_UNAVAILABLE_PREFIX)) {+ const reason = trimmedResponse+ .slice(CALL_RECORDING_SUMMARY_UNAVAILABLE_PREFIX.length)+ .trim();++ return isNonEmptyString(reason)+ ? { outcome: 'not-summarizable', reason }+ : undefined;+ }++ return { outcome: 'summarized', markdown: trimmedResponse };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-call-recording-summaries-for-ids.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-call-recording-summaries-for-ids.test.tsnew file mode 100644index 00000000000..d467d91d048--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-call-recording-summaries-for-ids.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { generateCallRecordingSummariesForIds } from 'src/logic-functions/flows/generate-call-recording-summaries-for-ids.util';++const generateCallRecordingSummaryMock = vi.hoisted(() => vi.fn());++vi.mock('src/logic-functions/flows/generate-call-recording-summary.util', () => ({+ generateCallRecordingSummary: generateCallRecordingSummaryMock,+}));++const client = {} as CoreApiClient;++describe('generateCallRecordingSummariesForIds', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ generateCallRecordingSummaryMock.mockResolvedValue({+ outcome: 'generated',+ });+ });++ it('buckets each call recording by its generation outcome', async () => {+ generateCallRecordingSummaryMock+ .mockResolvedValueOnce({ outcome: 'generated' })+ .mockResolvedValueOnce({ outcome: 'empty-summary' })+ .mockRejectedValueOnce(new Error('agent failed'))+ .mockResolvedValueOnce({ outcome: 'save-error' })+ .mockResolvedValueOnce({ outcome: 'already-summarized' })+ .mockResolvedValueOnce({ outcome: 'not-summarizable' });++ const result = await generateCallRecordingSummariesForIds({+ client,+ callRecordingIds: [+ 'call-recording-1',+ 'call-recording-2',+ 'call-recording-3',+ 'call-recording-4',+ 'call-recording-5',+ 'call-recording-6',+ ],+ });++ expect(result).toEqual({+ generatedCallRecordingIds: ['call-recording-1'],+ failedCallRecordingIds: ['call-recording-2'],+ erroredCallRecordingIds: ['call-recording-3', 'call-recording-4'],+ skippedCallRecordingIds: ['call-recording-5'],+ unavailableCallRecordingIds: ['call-recording-6'],+ });+ });++ it('stops spending as soon as the workspace toggle turns off', async () => {+ generateCallRecordingSummaryMock+ .mockResolvedValueOnce({ outcome: 'generated' })+ .mockResolvedValueOnce({ outcome: 'disabled' });++ const result = await generateCallRecordingSummariesForIds({+ client,+ callRecordingIds: [+ 'call-recording-1',+ 'call-recording-2',+ 'call-recording-3',+ ],+ });++ expect(generateCallRecordingSummaryMock).toHaveBeenCalledTimes(2);+ expect(result).toEqual({+ generatedCallRecordingIds: ['call-recording-1'],+ failedCallRecordingIds: [],+ erroredCallRecordingIds: [],+ skippedCallRecordingIds: [],+ unavailableCallRecordingIds: [],+ });+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-call-recording-summary.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-call-recording-summary.test.tsindex 90352673734..3f5e06d7e0e 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-call-recording-summary.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-call-recording-summary.test.ts@@ -5,7 +5,8 @@ import { generateCallRecordingSummary } from 'src/logic-functions/flows/generateconst runAgentMock = vi.hoisted(() => vi.fn());-vi.mock('twenty-sdk/logic-function', () => ({+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<object>()),runAgent: runAgentMock,}));@@ -96,6 +97,24 @@ describe('generateCallRecordingSummary', () => {expect(runAgentMock).not.toHaveBeenCalled();});+ it('regenerates an existing summary when explicitly requested', async () => {+ seedCallRecording({+ id: 'call-recording-1',+ title: null,+ transcript: TRANSCRIPT,+ summary: { markdown: '## Overview\nOld summary.' },+ });++ const result = await generateCallRecordingSummary(CLIENT, {+ callRecordingId: 'call-recording-1',+ shouldRegenerateExistingSummary: true,+ });++ expect(result).toEqual({ outcome: 'generated' });+ expect(runAgentMock).toHaveBeenCalledTimes(1);+ expect(mutationMock).toHaveBeenCalledTimes(1);+ });+it('skips recordings another actor created when the app-created gate is on', async () => {seedCallRecording({id: 'call-recording-1',@@ -125,6 +144,17 @@ describe('generateCallRecordingSummary', () => {expect(mutationMock).toHaveBeenCalledTimes(1);});+ it('reports a save error without rethrowing when the summary write fails', async () => {+ mutationMock.mockRejectedValue(new Error('Write timed out'));++ const result = await generateCallRecordingSummary(CLIENT, {+ callRecordingId: 'call-recording-1',+ });++ expect(result).toEqual({ outcome: 'save-error' });+ expect(runAgentMock).toHaveBeenCalledTimes(1);+ });+it('generates for recordings another actor created when explicitly requested', async () => {seedCallRecording({id: 'call-recording-1',@@ -181,24 +211,31 @@ describe('generateCallRecordingSummary', () => {);});- it('stores the no-summary verdict verbatim so the run is terminal', async () => {+ it('stores a grounded unavailable placeholder so the run is terminal', async () => {runAgentMock.mockResolvedValue({success: true,error: null,- result: { response: 'No summary available.' },+ result: {+ response:+ 'SUMMARY_UNAVAILABLE: The transcript contains only greetings and audio checks.',+ },});const result = await generateCallRecordingSummary(CLIENT, {callRecordingId: 'call-recording-1',});- expect(result).toEqual({ outcome: 'generated' });+ expect(result).toEqual({ outcome: 'not-summarizable' });expect(mutationMock).toHaveBeenCalledWith({updateCallRecording: {__args: {id: 'call-recording-1',data: {- summary: { blocknote: null, markdown: 'No summary available.' },+ summary: {+ blocknote: null,+ markdown:+ '## Summary unavailable\n\nThe transcript contains only greetings and audio checks.',+ },},},id: true,@@ -233,15 +270,4 @@ describe('generateCallRecordingSummary', () => {expect(mutationMock).not.toHaveBeenCalled();});- it('propagates summary write errors', async () => {- mutationMock.mockRejectedValue(new Error('Summary write failed'));-- await expect(- generateCallRecordingSummary(CLIENT, {- callRecordingId: 'call-recording-1',- }),- ).rejects.toThrow('Summary write failed');-- expect(mutationMock).toHaveBeenCalledTimes(1);- });});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-missing-call-recording-summaries.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-missing-call-recording-summaries.test.tsdeleted file mode 100644index 34bdfa53f98..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/generate-missing-call-recording-summaries.test.ts+++ /dev/null@@ -1,262 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH } from 'src/constants/generate-call-recording-summaries-route-path';-import { generateMissingCallRecordingSummaries } from 'src/logic-functions/flows/generate-missing-call-recording-summaries.util';--const runAgentMock = vi.hoisted(() => vi.fn());--vi.mock('twenty-sdk/logic-function', () => ({- runAgent: runAgentMock,-}));--const FUNCTIONS_BASE_URL = 'https://acme.functions.example.com';--const TRANSCRIPT = [- {- participant: { name: 'Alex' },- words: [{ text: 'Hello' }, { text: 'team' }],- },-];--const fetchMock = vi.fn();-const queryMock = vi.fn();-const mutationMock = vi.fn();--const CLIENT = {- query: queryMock,- mutation: mutationMock,-} as unknown as CoreApiClient;--const buildCallRecordingNode = (id: string, overrides: object = {}) => ({- id,- title: 'Weekly sync',- transcript: TRANSCRIPT,- summary: { markdown: null },- createdBy: { source: 'APPLICATION', name: 'Call Recorder' },- ...overrides,-});--const seedCallRecordingQueries = (nodesById: Record<string, object>) => {- queryMock.mockImplementation(async (queryShape: unknown) => {- const callRecordingId = (- queryShape as {- callRecordings: { __args: { filter: { id: { eq: string } } } };- }- ).callRecordings.__args.filter.id.eq;- const node = nodesById[callRecordingId];-- return {- callRecordings: { edges: node === undefined ? [] : [{ node }] },- };- });-};--// Each processed item advances the clock by ITEM_MS across the three-// getNowMs reads of one loop iteration.-const buildClock = (itemMs: number) => {- let nowMs = 0;- let reads = 0;-- return () => {- reads += 1;- if (reads % 3 === 2) {- nowMs += itemMs;- }-- return nowMs;- };-};--describe('generateMissingCallRecordingSummaries', () => {- beforeEach(() => {- vi.clearAllMocks();- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', FUNCTIONS_BASE_URL);- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- vi.stubEnv('CALL_RECORDER_SUMMARY_ENABLED', 'true');- vi.stubEnv('CALL_RECORDER_ADDITIONAL_SUMMARY_PROMPT', '');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));- mutationMock.mockResolvedValue({});- runAgentMock.mockResolvedValue({- success: true,- error: null,- result: { response: '## Overview\nGood call.' },- });- seedCallRecordingQueries({- 'call-recording-1': buildCallRecordingNode('call-recording-1'),- 'call-recording-2': buildCallRecordingNode('call-recording-2'),- 'call-recording-3': buildCallRecordingNode('call-recording-3'),- 'call-recording-4': buildCallRecordingNode('call-recording-4'),- });- });-- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();- });-- it('processes every id and skips the continuation when the budget allows', async () => {- const result = await generateMissingCallRecordingSummaries({- client: CLIENT,- callRecordingIds: ['call-recording-1', 'call-recording-2'],- deadlineAtMs: 1_000_000,- getNowMs: buildClock(10),- });-- expect(result).toEqual({- generatedCallRecordingIds: ['call-recording-1', 'call-recording-2'],- failedCallRecordingIds: [],- erroredCallRecordingIds: [],- skippedCallRecordingIds: [],- remainingCallRecordingIds: [],- continuationRequested: false,- });- expect(fetchMock).not.toHaveBeenCalled();- });-- it('always processes at least one id even when the deadline already passed', async () => {- const result = await generateMissingCallRecordingSummaries({- client: CLIENT,- callRecordingIds: ['call-recording-1', 'call-recording-2'],- deadlineAtMs: 0,- getNowMs: buildClock(10),- });-- expect(result.generatedCallRecordingIds).toEqual(['call-recording-1']);- expect(result.remainingCallRecordingIds).toEqual(['call-recording-2']);- expect(result.continuationRequested).toBe(true);- expect(fetchMock).toHaveBeenCalledTimes(1);- const [requestUrl, requestInit] = fetchMock.mock.calls[0];- expect(requestUrl).toBe(- `${FUNCTIONS_BASE_URL}${GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH}`,- );- expect(requestInit.method).toBe('POST');- expect(requestInit.body).toBe(- JSON.stringify({ callRecordingIds: ['call-recording-2'] }),- );- });-- it('stops when the next item would overrun the deadline and hands off the rest', async () => {- // 100ms per item against a 250ms deadline: two items fit, the third- // projected finish (200 + 100) exceeds 250 only after the second item.- const result = await generateMissingCallRecordingSummaries({- client: CLIENT,- callRecordingIds: [- 'call-recording-1',- 'call-recording-2',- 'call-recording-3',- 'call-recording-4',- ],- deadlineAtMs: 250,- getNowMs: buildClock(100),- });-- expect(result.generatedCallRecordingIds).toEqual([- 'call-recording-1',- 'call-recording-2',- ]);- expect(result.remainingCallRecordingIds).toEqual([- 'call-recording-3',- 'call-recording-4',- ]);- expect(fetchMock).toHaveBeenCalledTimes(1);- const [requestUrl, requestInit] = fetchMock.mock.calls[0];- expect(requestUrl).toBe(- `${FUNCTIONS_BASE_URL}${GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH}`,- );- expect(requestInit.body).toBe(- JSON.stringify({- callRecordingIds: ['call-recording-3', 'call-recording-4'],- }),- );- });-- it('separates empty summaries from thrown generation errors', async () => {- runAgentMock- .mockResolvedValueOnce({- success: false,- error: 'no more available credits',- result: null,- })- .mockRejectedValueOnce(new Error('agent exploded'))- .mockResolvedValueOnce({- success: true,- error: null,- result: { response: '## Overview\nGood call.' },- });-- const result = await generateMissingCallRecordingSummaries({- client: CLIENT,- callRecordingIds: [- 'call-recording-1',- 'call-recording-2',- 'call-recording-3',- ],- deadlineAtMs: 1_000_000,- getNowMs: buildClock(10),- });-- expect(result).toEqual({- generatedCallRecordingIds: ['call-recording-3'],- failedCallRecordingIds: ['call-recording-1'],- erroredCallRecordingIds: ['call-recording-2'],- skippedCallRecordingIds: [],- remainingCallRecordingIds: [],- continuationRequested: false,- });- });-- it('records skip outcomes without treating them as failures', async () => {- seedCallRecordingQueries({- 'call-recording-1': buildCallRecordingNode('call-recording-1', {- summary: { markdown: '## Overview\nAlready here.' },- }),- 'call-recording-2': buildCallRecordingNode('call-recording-2', {- transcript: { status: 'PENDING' },- }),- });-- const result = await generateMissingCallRecordingSummaries({- client: CLIENT,- callRecordingIds: ['call-recording-1', 'call-recording-2'],- deadlineAtMs: 1_000_000,- getNowMs: buildClock(10),- });-- expect(result.skippedCallRecordingIds).toEqual([- 'call-recording-1',- 'call-recording-2',- ]);- expect(result.failedCallRecordingIds).toEqual([]);- expect(result.erroredCallRecordingIds).toEqual([]);- });-- it('stops spending immediately when summaries get disabled mid-run', async () => {- // Persisting the first summary flips the workspace toggle off, so the- // second id observes the disabled state.- mutationMock.mockImplementationOnce(async () => {- vi.stubEnv('CALL_RECORDER_SUMMARY_ENABLED', 'false');-- return {};- });-- const result = await generateMissingCallRecordingSummaries({- client: CLIENT,- callRecordingIds: [- 'call-recording-1',- 'call-recording-2',- 'call-recording-3',- ],- deadlineAtMs: 1_000_000,- getNowMs: buildClock(10),- });-- expect(result.generatedCallRecordingIds).toEqual(['call-recording-1']);- expect(result.remainingCallRecordingIds).toEqual(['call-recording-3']);- expect(result.continuationRequested).toBe(false);- expect(fetchMock).not.toHaveBeenCalled();- expect(queryMock).toHaveBeenCalledTimes(1);- expect(runAgentMock).toHaveBeenCalledTimes(1);- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/handle-recall-webhook.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/handle-recall-webhook.test.tsindex 91a543bd1a9..7f982ccbc04 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/handle-recall-webhook.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/handle-recall-webhook.test.ts@@ -27,7 +27,7 @@ const createAsyncRecallTranscriptMock = vi.hoisted(() => vi.fn());const retrieveRecallTranscriptMock = vi.hoisted(() => vi.fn());const importCallRecordingMediaMock = vi.hoisted(() => vi.fn());const chargeCompletedCallRecordingMock = vi.hoisted(() => vi.fn());-const requestArtifactContinuationMock = vi.hoisted(() => vi.fn());+const enqueueArtifactImportMock = vi.hoisted(() => vi.fn());vi.mock('src/logic-functions/recall-api/get-recall-bot.util', () => ({getRecallBot: getRecallBotMock,@@ -56,9 +56,9 @@ vi.mock('src/logic-functions/flows/import-call-recording-media.util', () => ({}));vi.mock(- 'src/logic-functions/data/request-call-recording-artifacts-import.util',+ 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util',() => ({- requestCallRecordingArtifactsImport: requestArtifactContinuationMock,+ enqueueCallRecordingArtifactsImport: enqueueArtifactImportMock,}),);@@ -180,8 +180,8 @@ describe('handleRecallWebhook', () => {importCallRecordingMediaMock.mockResolvedValue({});chargeCompletedCallRecordingMock.mockReset();chargeCompletedCallRecordingMock.mockResolvedValue('charged');- requestArtifactContinuationMock.mockReset();- requestArtifactContinuationMock.mockResolvedValue(true);+ enqueueArtifactImportMock.mockReset();+ enqueueArtifactImportMock.mockResolvedValue(undefined);});it('updates a call recording from bot metadata on status change events', async () => {@@ -960,9 +960,8 @@ describe('handleRecallWebhook', () => {expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();expect(importCallRecordingMediaMock).not.toHaveBeenCalled();- expect(requestArtifactContinuationMock).toHaveBeenCalledWith({+ expect(enqueueArtifactImportMock).toHaveBeenCalledWith({callRecordingId: 'call-recording-1',- requestedAt: expect.any(String),});expect(client.mutations).toEqual([{@@ -976,8 +975,12 @@ describe('handleRecallWebhook', () => {]);});- it('throws when the artifact import request fails so Svix redelivers', async () => {- requestArtifactContinuationMock.mockResolvedValue(false);+ it('throws when the artifact import enqueue fails so Svix redelivers', async () => {+ enqueueArtifactImportMock.mockRejectedValue(+ new Error(+ 'failed to enqueue artifact import for call recording call-recording-1',+ ),+ );const client = new FakeCoreApiClient([{id: 'call-recording-1',@@ -993,7 +996,7 @@ describe('handleRecallWebhook', () => {body: buildRecordingDoneWebhookBody(),}),).rejects.toThrow(- 'failed to request artifact import for call recording call-recording-1',+ 'failed to enqueue artifact import for call recording call-recording-1',);});@@ -1020,7 +1023,7 @@ describe('handleRecallWebhook', () => {expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();expect(listRecallTranscriptsMock).not.toHaveBeenCalled();expect(retrieveRecallTranscriptMock).not.toHaveBeenCalled();- expect(requestArtifactContinuationMock).toHaveBeenCalledTimes(1);+ expect(enqueueArtifactImportMock).toHaveBeenCalledTimes(1);expect(client.mutations).toEqual([{id: 'call-recording-1',@@ -1064,9 +1067,8 @@ describe('handleRecallWebhook', () => {expect(getRecallBotMock).not.toHaveBeenCalled();expect(createAsyncRecallTranscriptMock).not.toHaveBeenCalled();- expect(requestArtifactContinuationMock).toHaveBeenCalledWith({+ expect(enqueueArtifactImportMock).toHaveBeenCalledWith({callRecordingId: 'call-recording-1',- requestedAt: expect.any(String),});expect(client.mutations).toEqual([expect.objectContaining({@@ -1109,7 +1111,7 @@ describe('handleRecallWebhook', () => {},]);expect(chargeCompletedCallRecordingMock).not.toHaveBeenCalled();- expect(requestArtifactContinuationMock).toHaveBeenCalledTimes(1);+ expect(enqueueArtifactImportMock).toHaveBeenCalledTimes(1);});it('keeps the real failure reason on recording.failed and defers media work', async () => {@@ -1146,7 +1148,7 @@ describe('handleRecallWebhook', () => {]);expect(importCallRecordingMediaMock).not.toHaveBeenCalled();expect(chargeCompletedCallRecordingMock).not.toHaveBeenCalled();- expect(requestArtifactContinuationMock).toHaveBeenCalledTimes(1);+ expect(enqueueArtifactImportMock).toHaveBeenCalledTimes(1);expect(result).toEqual({status: 'updated',event: 'recording.failed',@@ -1197,9 +1199,8 @@ describe('handleRecallWebhook', () => {callRecordingId: 'call-recording-1',});expect(retrieveRecallTranscriptMock).not.toHaveBeenCalled();- expect(requestArtifactContinuationMock).toHaveBeenCalledWith({+ expect(enqueueArtifactImportMock).toHaveBeenCalledWith({callRecordingId: 'call-recording-1',- requestedAt: expect.any(String),});expect(client.mutations).toEqual([]);});@@ -1246,9 +1247,8 @@ describe('handleRecallWebhook', () => {event: 'transcript.failed',callRecordingId: 'call-recording-1',});- expect(requestArtifactContinuationMock).toHaveBeenCalledWith({+ expect(enqueueArtifactImportMock).toHaveBeenCalledWith({callRecordingId: 'call-recording-1',- requestedAt: expect.any(String),});expect(client.mutations).toEqual([]);});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-upcoming-calendar-event-batches.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-upcoming-calendar-event-batches.test.tsdeleted file mode 100644index 4e7a9b1382b..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-upcoming-calendar-event-batches.test.ts+++ /dev/null@@ -1,344 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { CoreApiClient } from 'twenty-client-sdk/core';--import { RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH } from 'src/constants/reconcile-upcoming-calendar-events-route-path';-import { reconcileUpcomingCalendarEventBatches } from 'src/logic-functions/flows/reconcile-upcoming-calendar-event-batches.util';--const queryMock = vi.fn();-const mutationMock = vi.fn();-const fetchMock = vi.fn();--const CLIENT: CoreApiClient = Object.assign(- Object.create(CoreApiClient.prototype),- {- mutation: mutationMock,- query: queryMock,- },-);--const MEETING_URL = 'https://meet.google.com/abc';-const MEETING_STARTS_AT = new Date(Date.now() + 60 * 60 * 1000).toISOString();-const MEETING_ENDS_AT = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString();--type CalendarEventNode = {- id: string;- title: string;- isCanceled: boolean;- startsAt: string;- endsAt: string;- conferenceLink: { primaryLinkUrl: string } | null;-};--type CallRecordingNode = {- id: string;- status: string;- recordingRequestStatus: string | null;- calendarEventId?: string;-};--type RecordsQuery = {- calendarEvents?: {- __args: {- filter: {- id?: { in: string[] };- startsAt?: { in: string[] };- };- };- };- callRecordings?: {- __args: {- filter: {- id?: { in: string[] };- calendarEventId?: { in: string[] };- };- };- };-};--type RecordsMutation = {- createCallRecording?: {- __args: { data: { id: string; calendarEventId: string } };- };- updateCallRecording?: { __args: { id: string } };-};--const buildConnection = <TNode>(nodes: TNode[]) => ({- pageInfo: { hasNextPage: false, endCursor: null },- edges: nodes.map((node) => ({ node })),-});--const buildCalendarEventNode = (- id: string,- overrides: Partial<CalendarEventNode> = {},-): CalendarEventNode => ({- id,- title: 'Customer Sync',- isCanceled: false,- startsAt: MEETING_STARTS_AT,- endsAt: MEETING_ENDS_AT,- conferenceLink: { primaryLinkUrl: MEETING_URL },- ...overrides,-});--const seedClientQueries = ({- calendarEventNodesById = {},- callRecordingNodesByCalendarEventId = {},- hasExistingPolicyManagedCallRecordings = false,-}: {- calendarEventNodesById?: Record<string, CalendarEventNode>;- callRecordingNodesByCalendarEventId?: Record<string, CallRecordingNode[]>;- hasExistingPolicyManagedCallRecordings?: boolean;-} = {}): void => {- queryMock.mockImplementation(async (query: RecordsQuery) => {- if (query.calendarEvents !== undefined) {- const filter = query.calendarEvents.__args.filter;-- if (filter.id !== undefined) {- return {- calendarEvents: buildConnection(- filter.id.in.map(- (calendarEventId) =>- calendarEventNodesById[calendarEventId] ??- buildCalendarEventNode(calendarEventId),- ),- ),- };- }-- return { calendarEvents: buildConnection([]) };- }-- if (query.callRecordings !== undefined) {- const filter = query.callRecordings.__args.filter;-- if (filter.calendarEventId !== undefined) {- return {- callRecordings: buildConnection(- filter.calendarEventId.in.flatMap(- (calendarEventId) =>- callRecordingNodesByCalendarEventId[calendarEventId] ?? [],- ),- ),- };- }-- return {- callRecordings: buildConnection(- hasExistingPolicyManagedCallRecordings- ? (filter.id?.in ?? []).map((callRecordingId) => ({- id: callRecordingId,- status: 'SCHEDULED',- recordingRequestStatus: 'REQUESTED',- }))- : [],- ),- };- }-- throw new Error(`Unhandled query: ${JSON.stringify(query)}`);- });-};--const seedClientMutations = ({- failingCreateCalendarEventId,-}: {- failingCreateCalendarEventId?: string;-} = {}): void => {- mutationMock.mockImplementation(async (mutation: RecordsMutation) => {- if (mutation.createCallRecording !== undefined) {- const data = mutation.createCallRecording.__args.data;-- if (data.calendarEventId === failingCreateCalendarEventId) {- throw new Error('createCallRecording rejected');- }-- return { createCallRecording: { id: data.id } };- }-- if (mutation.updateCallRecording !== undefined) {- return {- updateCallRecording: { id: mutation.updateCallRecording.__args.id },- };- }-- throw new Error(`Unhandled mutation: ${JSON.stringify(mutation)}`);- });-};--const readBatchCalendarEventIdFilters = (): string[][] =>- queryMock.mock.calls- .map(([query]) => query.calendarEvents?.__args.filter.id?.in)- .filter(- (requestedIds): requestedIds is string[] =>- requestedIds !== undefined && requestedIds.length > 1,- );--const buildCalendarEventIds = (count: number): string[] =>- Array.from({ length: count }, (_, index) => `calendar-event-${index + 1}`);--describe('reconcileUpcomingCalendarEventBatches', () => {- beforeEach(() => {- vi.clearAllMocks();- vi.spyOn(console, 'warn').mockImplementation(() => {});- vi.spyOn(console, 'error').mockImplementation(() => {});- vi.stubGlobal('fetch', fetchMock);- vi.stubEnv('TWENTY_FUNCTIONS_URL', 'https://acme.functions.example.com');- vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-access-token');- fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));- seedClientQueries();- seedClientMutations();- });-- afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();- vi.restoreAllMocks();- });-- it('reconciles every batch when the deadline is far away', async () => {- const calendarEventIds = buildCalendarEventIds(30);-- const result = await reconcileUpcomingCalendarEventBatches({- client: CLIENT,- calendarEventIds,- deadlineAtMs: Date.now() + 60_000,- });-- expect(readBatchCalendarEventIdFilters()).toEqual([- [...calendarEventIds.slice(0, 25)].sort(),- [...calendarEventIds.slice(25)].sort(),- ]);- expect(result.reconciledCalendarEventIds).toEqual(calendarEventIds);- expect(result.remainingCalendarEventIds).toEqual([]);- expect(result.actionCounts).toEqual({- created: 2,- updated: 0,- canceled: 0,- skipped: 0,- failed: 0,- });- expect(result.continuationRequested).toBe(false);- expect(fetchMock).not.toHaveBeenCalled();- });-- it('stops at the deadline and requests a continuation with the remaining ids', async () => {- const calendarEventIds = buildCalendarEventIds(30);- // Clock advances 5s per reading: after one batch, 15s + 5s overshoots the deadline.- let nowMs = 0;- const getNowMs = () => {- nowMs += 5_000;-- return nowMs;- };-- const result = await reconcileUpcomingCalendarEventBatches({- client: CLIENT,- calendarEventIds,- deadlineAtMs: 15_000,- getNowMs,- });-- expect(readBatchCalendarEventIdFilters()).toEqual([- [...calendarEventIds.slice(0, 25)].sort(),- ]);- expect(result.reconciledCalendarEventIds).toEqual(- calendarEventIds.slice(0, 25),- );- expect(result.remainingCalendarEventIds).toEqual(- calendarEventIds.slice(25),- );- expect(result.continuationRequested).toBe(true);- expect(fetchMock).toHaveBeenCalledTimes(1);- const [requestUrl, requestInit] = fetchMock.mock.calls[0];- expect(requestUrl).toBe(- `https://acme.functions.example.com${RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH}`,- );- expect(requestInit.method).toBe('POST');- expect(requestInit.body).toBe(- JSON.stringify({ calendarEventIds: calendarEventIds.slice(25) }),- );- });-- it('records a failed batch and keeps processing the next one', async () => {- const calendarEventIds = buildCalendarEventIds(30);-- seedClientQueries({ hasExistingPolicyManagedCallRecordings: true });- queryMock.mockRejectedValueOnce(new Error('core api unavailable'));-- const result = await reconcileUpcomingCalendarEventBatches({- client: CLIENT,- calendarEventIds,- deadlineAtMs: Date.now() + 60_000,- });-- expect(result.failedCalendarEventIds).toEqual(calendarEventIds.slice(0, 25));- expect(result.reconciledCalendarEventIds).toEqual(- calendarEventIds.slice(25),- );- expect(result.remainingCalendarEventIds).toEqual([]);- expect(result.actionCounts).toEqual({- created: 0,- updated: 1,- canceled: 0,- skipped: 0,- failed: 0,- });- expect(result.continuationRequested).toBe(false);- });-- it('tallies every reconciliation action kind', async () => {- seedClientQueries({- calendarEventNodesById: {- 'calendar-event-1': buildCalendarEventNode('calendar-event-1', {- conferenceLink: {- primaryLinkUrl: 'https://meet.google.com/created',- },- }),- 'calendar-event-2': buildCalendarEventNode('calendar-event-2', {- isCanceled: true,- conferenceLink: {- primaryLinkUrl: 'https://meet.google.com/canceled',- },- }),- 'calendar-event-3': buildCalendarEventNode('calendar-event-3', {- isCanceled: true,- conferenceLink: {- primaryLinkUrl: 'https://meet.google.com/skipped',- },- }),- 'calendar-event-4': buildCalendarEventNode('calendar-event-4', {- conferenceLink: {- primaryLinkUrl: 'https://meet.google.com/failed',- },- }),- },- callRecordingNodesByCalendarEventId: {- 'calendar-event-2': [- {- id: 'call-recording-2',- status: 'SCHEDULED',- recordingRequestStatus: 'REQUESTED',- calendarEventId: 'calendar-event-2',- },- ],- },- });- seedClientMutations({- failingCreateCalendarEventId: 'calendar-event-4',- });-- const result = await reconcileUpcomingCalendarEventBatches({- client: CLIENT,- calendarEventIds: buildCalendarEventIds(4),- deadlineAtMs: Date.now() + 60_000,- });-- expect(result.actionCounts).toEqual({- created: 1,- updated: 0,- canceled: 1,- skipped: 1,- failed: 1,- });- });-});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-missing-call-recording-summaries-result.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summaries-for-ids-result.type.tssimilarity index 53%rename from packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-missing-call-recording-summaries-result.type.tsrename to packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summaries-for-ids-result.type.tsindex abc5a72a6f6..732de468699 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-missing-call-recording-summaries-result.type.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summaries-for-ids-result.type.ts@@ -1,8 +1,7 @@-export type GenerateMissingCallRecordingSummariesResult = {+export type GenerateCallRecordingSummariesForIdsResult = {generatedCallRecordingIds: string[];failedCallRecordingIds: string[];erroredCallRecordingIds: string[];skippedCallRecordingIds: string[];- remainingCallRecordingIds: string[];- continuationRequested: boolean;+ unavailableCallRecordingIds: string[];};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summaries-for-ids.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summaries-for-ids.util.tsnew file mode 100644index 00000000000..3279613a660--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summaries-for-ids.util.ts@@ -0,0 +1,61 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { generateCallRecordingSummary } from 'src/logic-functions/flows/generate-call-recording-summary.util';+import { type GenerateCallRecordingSummaryResult } from 'src/logic-functions/flows/generate-call-recording-summary-result.type';+import { type GenerateCallRecordingSummariesForIdsResult } from 'src/logic-functions/flows/generate-call-recording-summaries-for-ids-result.type';++type SummaryOutcome =+ | GenerateCallRecordingSummaryResult['outcome']+ | 'generation-error';++export const generateCallRecordingSummariesForIds = async ({+ client,+ callRecordingIds,+}: {+ client: CoreApiClient;+ callRecordingIds: string[];+}): Promise<GenerateCallRecordingSummariesForIdsResult> => {+ const generatedCallRecordingIds: string[] = [];+ const failedCallRecordingIds: string[] = [];+ const erroredCallRecordingIds: string[] = [];+ const skippedCallRecordingIds: string[] = [];+ const unavailableCallRecordingIds: string[] = [];++ for (const callRecordingId of callRecordingIds) {+ let outcome: SummaryOutcome;++ try {+ ({ outcome } = await generateCallRecordingSummary(client, {+ callRecordingId,+ shouldRegenerateExistingSummary: true,+ }));+ } catch {+ outcome = 'generation-error';+ }++ if (outcome === 'disabled') {+ // The workspace toggle turned off mid-run; stop spending immediately.+ break;+ }++ if (outcome === 'generated') {+ generatedCallRecordingIds.push(callRecordingId);+ } else if (outcome === 'not-summarizable') {+ unavailableCallRecordingIds.push(callRecordingId);+ } else if (outcome === 'empty-summary') {+ failedCallRecordingIds.push(callRecordingId);+ } else if (outcome === 'generation-error' || outcome === 'save-error') {+ erroredCallRecordingIds.push(callRecordingId);+ } else {+ skippedCallRecordingIds.push(callRecordingId);+ }+ }++ return {+ generatedCallRecordingIds,+ failedCallRecordingIds,+ erroredCallRecordingIds,+ skippedCallRecordingIds,+ unavailableCallRecordingIds,+ };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary-result.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary-result.type.tsindex f7c8455f6cd..08cb075de35 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary-result.type.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary-result.type.ts@@ -4,6 +4,8 @@ export type GenerateCallRecordingSummaryResult = {| 'no-transcript'| 'not-app-recording'| 'already-summarized'+ | 'not-summarizable'| 'empty-summary'+ | 'save-error'| 'generated';};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary.util.tsindex f829367b7ae..7312280a82b 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-call-recording-summary.util.ts@@ -5,10 +5,11 @@ import { CALL_RECORDING_SUMMARIZER_AGENT_UNIVERSAL_IDENTIFIER } from 'src/constaimport { findCallRecordingForSummary } from 'src/logic-functions/data/find-call-recording-for-summary.util';import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';import { buildCallRecordingSummaryPrompt } from 'src/logic-functions/domain/build-call-recording-summary-prompt.util';-import { extractCallRecordingSummaryMarkdown } from 'src/logic-functions/domain/extract-call-recording-summary-markdown.util';import { isCallRecordingCreatedByCallRecorder } from 'src/logic-functions/domain/is-call-recording-created-by-call-recorder.util';import { isRealTranscript } from 'src/logic-functions/domain/is-real-transcript.util';+import { parseCallRecordingSummaryAgentResponse } from 'src/logic-functions/domain/parse-call-recording-summary-agent-response.util';import { type GenerateCallRecordingSummaryResult } from 'src/logic-functions/flows/generate-call-recording-summary-result.type';+import { buildStepFailure } from 'src/logic-functions/utils/build-step-failure.util';import { getCallRecorderAdditionalSummaryPrompt } from 'src/logic-functions/utils/get-call-recorder-additional-summary-prompt.util';import { isCallRecordingSummaryEnabled } from 'src/logic-functions/utils/is-call-recording-summary-enabled.util';@@ -17,7 +18,12 @@ export const generateCallRecordingSummary = async ({callRecordingId,requireCreatedByCallRecorder = false,- }: { callRecordingId: string; requireCreatedByCallRecorder?: boolean },+ shouldRegenerateExistingSummary = false,+ }: {+ callRecordingId: string;+ requireCreatedByCallRecorder?: boolean;+ shouldRegenerateExistingSummary?: boolean;+ },): Promise<GenerateCallRecordingSummaryResult> => {if (!isCallRecordingSummaryEnabled()) {return { outcome: 'disabled' };@@ -41,7 +47,10 @@ export const generateCallRecordingSummary = async (return { outcome: 'not-app-recording' };}- if (callRecording.summaryMarkdown !== undefined) {+ if (+ !shouldRegenerateExistingSummary &&+ callRecording.summaryMarkdown !== undefined+ ) {return { outcome: 'already-summarized' };}@@ -61,16 +70,34 @@ export const generateCallRecordingSummary = async (prompt,});- const markdown = extractCallRecordingSummaryMarkdown(agentResult);+ const parsedAgentResponse =+ parseCallRecordingSummaryAgentResponse(agentResult);- if (markdown === undefined) {+ if (parsedAgentResponse === undefined) {return { outcome: 'empty-summary' };}- await updateCallRecording(client, {- id: callRecordingId,- data: { summary: { blocknote: null, markdown } },- });+ const summaryMarkdown =+ parsedAgentResponse.outcome === 'not-summarizable'+ ? `## Summary unavailable\n\n${parsedAgentResponse.reason}`+ : parsedAgentResponse.markdown;++ try {+ await updateCallRecording(client, {+ id: callRecordingId,+ data: { summary: { blocknote: null, markdown: summaryMarkdown } },+ });+ } catch (error) {+ // Not rethrown: a redelivery would re-bill the agent run that already succeeded.+ buildStepFailure('call recording summary save', error);++ return { outcome: 'save-error' };+ }- return { outcome: 'generated' };+ return {+ outcome:+ parsedAgentResponse.outcome === 'not-summarizable'+ ? 'not-summarizable'+ : 'generated',+ };};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-missing-call-recording-summaries.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-missing-call-recording-summaries.util.tsdeleted file mode 100644index 25f810386ab..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/generate-missing-call-recording-summaries.util.ts+++ /dev/null@@ -1,92 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { requestCallRecordingSummariesContinuation } from 'src/logic-functions/data/request-call-recording-summaries-continuation.util';-import { generateCallRecordingSummary } from 'src/logic-functions/flows/generate-call-recording-summary.util';-import { type GenerateCallRecordingSummaryResult } from 'src/logic-functions/flows/generate-call-recording-summary-result.type';-import { type GenerateMissingCallRecordingSummariesResult } from 'src/logic-functions/flows/generate-missing-call-recording-summaries-result.type';--type BatchSummaryOutcome =- | GenerateCallRecordingSummaryResult['outcome']- | 'generation-error';--export const generateMissingCallRecordingSummaries = async ({- client,- callRecordingIds,- deadlineAtMs,- getNowMs = () => Date.now(),-}: {- client: CoreApiClient;- callRecordingIds: string[];- deadlineAtMs: number;- getNowMs?: () => number;-}): Promise<GenerateMissingCallRecordingSummariesResult> => {- const remainingCallRecordingIds = [...callRecordingIds];- const generatedCallRecordingIds: string[] = [];- const failedCallRecordingIds: string[] = [];- const erroredCallRecordingIds: string[] = [];- const skippedCallRecordingIds: string[] = [];- let slowestItemMs = 0;-- // Always process at least one id so the remaining list strictly shrinks —- // otherwise a single slow item would re-invoke with an unshrunk payload- // forever.- while (remainingCallRecordingIds.length > 0) {- const callRecordingId = remainingCallRecordingIds[0];- const itemStartedAtMs = getNowMs();-- let outcome: BatchSummaryOutcome;-- try {- ({ outcome } = await generateCallRecordingSummary(client, {- callRecordingId,- }));- } catch {- outcome = 'generation-error';- }-- remainingCallRecordingIds.shift();- slowestItemMs = Math.max(slowestItemMs, getNowMs() - itemStartedAtMs);-- if (outcome === 'disabled') {- // The workspace toggle turned off mid-run; stop spending immediately.- return {- generatedCallRecordingIds,- failedCallRecordingIds,- erroredCallRecordingIds,- skippedCallRecordingIds,- remainingCallRecordingIds,- continuationRequested: false,- };- }-- if (outcome === 'generated') {- generatedCallRecordingIds.push(callRecordingId);- } else if (outcome === 'empty-summary') {- failedCallRecordingIds.push(callRecordingId);- } else if (outcome === 'generation-error') {- erroredCallRecordingIds.push(callRecordingId);- } else {- skippedCallRecordingIds.push(callRecordingId);- }-- if (getNowMs() + slowestItemMs > deadlineAtMs) {- break;- }- }-- const continuationRequested =- remainingCallRecordingIds.length > 0- ? await requestCallRecordingSummariesContinuation({- callRecordingIds: remainingCallRecordingIds,- })- : false;-- return {- generatedCallRecordingIds,- failedCallRecordingIds,- erroredCallRecordingIds,- skippedCallRecordingIds,- remainingCallRecordingIds,- continuationRequested,- };-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-recall-webhook.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/handle-recall-webhook.util.tsindex d7ce23e95a7..b48413ee663 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@@ -2,8 +2,8 @@ import { isUndefined } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';import { findCallRecordingsByFilter } from 'src/logic-functions/data/find-call-recordings-by-filter.util';-import { requestCallRecordingArtifactsImport } from 'src/logic-functions/data/request-call-recording-artifacts-import.util';import { isCallRecordingStatusDowngrade } from 'src/logic-functions/domain/is-call-recording-status-downgrade.util';import { isRecallRecordingDoneSignal } from 'src/logic-functions/domain/is-recall-recording-done-signal.util';import { mapRecallStatusCodeToCallRecordingStatus } from 'src/logic-functions/domain/map-recall-status-code-to-call-recording-status.util';@@ -138,7 +138,7 @@ const handleRecallStatusEvent = async ({statusCode,})) {- await requestCallRecordingArtifactsImportOrThrow({+ await enqueueCallRecordingArtifactsImport({callRecordingId: callRecording.id,});}@@ -175,7 +175,7 @@ const queueCallRecordingArtifactsImport = async ({};}- await requestCallRecordingArtifactsImportOrThrow({+ await enqueueCallRecordingArtifactsImport({callRecordingId: callRecording.id,});@@ -186,23 +186,6 @@ const queueCallRecordingArtifactsImport = async ({};};-const requestCallRecordingArtifactsImportOrThrow = async ({- callRecordingId,-}: {- callRecordingId: string;-}): Promise<void> => {- const importRequested = await requestCallRecordingArtifactsImport({- callRecordingId,- requestedAt: new Date().toISOString(),- });-- if (!importRequested) {- throw new Error(- `failed to request artifact import for call recording ${callRecordingId}`,- );- }-};-const findMatchingCallRecording = async ({client,webhookEvent,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-artifacts.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/import-call-recording-artifacts.util.tsindex 2384f189634..b4dd18fa766 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@@ -44,7 +44,7 @@ export type ImportCallRecordingArtifactsResult =reason: string;};-// Route callers can forge provider ids, so imports resolve only from the+// Job payloads can carry forged provider ids, so imports resolve only from the// CallRecording's persisted Recall bot.export const importCallRecordingArtifacts = async ({client,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-upcoming-calendar-event-batches-result.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-upcoming-calendar-event-batches-result.type.tsdeleted file mode 100644index ff3e60890df..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-upcoming-calendar-event-batches-result.type.ts+++ /dev/null@@ -1,14 +0,0 @@-import { type CallRecorderReconciliationResult } from 'src/logic-functions/types/call-recorder-reconciliation-result.type';--export type CallRecorderReconciliationActionCounts = Record<- Lowercase<CallRecorderReconciliationResult['action']>,- number->;--export type ReconcileUpcomingCalendarEventBatchesResult = {- reconciledCalendarEventIds: string[];- failedCalendarEventIds: string[];- remainingCalendarEventIds: string[];- actionCounts: CallRecorderReconciliationActionCounts;- continuationRequested: boolean;-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-upcoming-calendar-event-batches.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-upcoming-calendar-event-batches.util.tsdeleted file mode 100644index 65626dbe420..00000000000--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-upcoming-calendar-event-batches.util.ts+++ /dev/null@@ -1,100 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { UPCOMING_CALENDAR_EVENT_RECONCILIATION_BATCH_SIZE } from 'src/logic-functions/constants/upcoming-calendar-event-reconciliation-batch-size';-import { requestUpcomingCalendarEventsReconciliation } from 'src/logic-functions/data/request-upcoming-calendar-events-reconciliation.util';-import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';-import {- type CallRecorderReconciliationActionCounts,- type ReconcileUpcomingCalendarEventBatchesResult,-} from 'src/logic-functions/flows/reconcile-upcoming-calendar-event-batches-result.type';-import { type CallRecorderReconciliationResult } from 'src/logic-functions/types/call-recorder-reconciliation-result.type';--const ACTION_COUNT_KEY_BY_ACTION: {- [Action in CallRecorderReconciliationResult['action']]: Lowercase<Action>;-} = {- CREATED: 'created',- UPDATED: 'updated',- CANCELED: 'canceled',- SKIPPED: 'skipped',- FAILED: 'failed',-};--export const reconcileUpcomingCalendarEventBatches = async ({- client,- calendarEventIds,- deadlineAtMs,- getNowMs = () => Date.now(),-}: {- client: CoreApiClient;- calendarEventIds: string[];- deadlineAtMs: number;- getNowMs?: () => number;-}): Promise<ReconcileUpcomingCalendarEventBatchesResult> => {- const remainingCalendarEventIds = [...calendarEventIds];- const reconciledCalendarEventIds: string[] = [];- const failedCalendarEventIds: string[] = [];- const actionCounts: CallRecorderReconciliationActionCounts = {- created: 0,- updated: 0,- canceled: 0,- skipped: 0,- failed: 0,- };- let slowestBatchMs = 0;-- // Process at least one batch per run so the continuation payload strictly shrinks.- while (remainingCalendarEventIds.length > 0) {- const batchCalendarEventIds = remainingCalendarEventIds.slice(- 0,- UPCOMING_CALENDAR_EVENT_RECONCILIATION_BATCH_SIZE,- );- const batchStartedAtMs = getNowMs();-- try {- const reconciliationResults =- await reconcileCallRecorderForCalendarEventIds({- client,- calendarEventIds: batchCalendarEventIds,- });-- reconciledCalendarEventIds.push(...batchCalendarEventIds);-- for (const reconciliationResult of reconciliationResults) {- const actionCountKey =- ACTION_COUNT_KEY_BY_ACTION[reconciliationResult.action];-- actionCounts[actionCountKey] += 1;- }- } catch (error) {- failedCalendarEventIds.push(...batchCalendarEventIds);-- if (process.env.NODE_ENV !== 'test') {- console.error(- `[call-recorder] upcoming calendar event batch reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,- );- }- }-- remainingCalendarEventIds.splice(0, batchCalendarEventIds.length);- slowestBatchMs = Math.max(slowestBatchMs, getNowMs() - batchStartedAtMs);-- if (getNowMs() + slowestBatchMs > deadlineAtMs) {- break;- }- }-- const continuationRequested =- remainingCalendarEventIds.length > 0- ? await requestUpcomingCalendarEventsReconciliation({- calendarEventIds: remainingCalendarEventIds,- })- : false;-- return {- reconciledCalendarEventIds,- failedCalendarEventIds,- remainingCalendarEventIds,- actionCounts,- continuationRequested,- };-};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/generate-call-recording-summaries.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/generate-call-recording-summaries.tsindex b2a07622154..4db0794258b 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/generate-call-recording-summaries.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/generate-call-recording-summaries.ts@@ -4,30 +4,15 @@ import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';import { GENERATE_CALL_RECORDING_SUMMARIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/generate-call-recording-summaries-logic-function-universal-identifier';import { GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH } from 'src/constants/generate-call-recording-summaries-route-path';import { findCallRecordingIdsForCalendarEvents } from 'src/logic-functions/data/find-call-recording-ids-for-calendar-events.util';-import { findCallRecordingIdsMissingSummary } from 'src/logic-functions/data/find-call-recording-ids-missing-summary.util';-import { generateMissingCallRecordingSummaries } from 'src/logic-functions/flows/generate-missing-call-recording-summaries.util';+import { generateCallRecordingSummariesForIds } from 'src/logic-functions/flows/generate-call-recording-summaries-for-ids.util';import { isCallRecordingSummaryEnabled } from 'src/logic-functions/utils/is-call-recording-summary-enabled.util';-import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';--const TIMEOUT_SECONDS = 900;-const CONTINUATION_RESERVE_MS = 30_000;+import { toIdList } from 'src/logic-functions/utils/to-id-list.util';type GenerateCallRecordingSummariesRouteBody = {callRecordingIds?: string[];calendarEventIds?: string[];};-const hasOwnProperty = <T extends object>(- object: T | null | undefined,- propertyName: keyof GenerateCallRecordingSummariesRouteBody,-): boolean =>- object === undefined || object === null- ? false- : Object.prototype.hasOwnProperty.call(object, propertyName);--const toIdList = (value: unknown): string[] =>- Array.isArray(value) ? value.filter(isNonEmptyString) : [];-export const generateCallRecordingSummariesHandler = async (payload: RoutePayload<GenerateCallRecordingSummariesRouteBody>,): Promise<object> => {@@ -35,33 +20,21 @@ export const generateCallRecordingSummariesHandler = async (return { outcome: 'disabled' };}- const startedAtMs = Date.now();const client = new CoreApiClient();const requestedCallRecordingIds = toIdList(payload.body?.callRecordingIds);const requestedCalendarEventIds = toIdList(payload.body?.calendarEventIds);- const hasRequestedCallRecordingIds = hasOwnProperty(- payload.body,- 'callRecordingIds',- );- const hasRequestedCalendarEventIds = hasOwnProperty(- payload.body,- 'calendarEventIds',- );- const hasRequestedIds =- hasRequestedCallRecordingIds || hasRequestedCalendarEventIds;-- let callRecordingIds = requestedCallRecordingIds;if (- hasRequestedIds &&requestedCallRecordingIds.length === 0 &&requestedCalendarEventIds.length === 0) {return { outcome: 'nothing-selected' };}- if (callRecordingIds.length === 0 && requestedCalendarEventIds.length > 0) {+ let callRecordingIds = requestedCallRecordingIds;++ if (callRecordingIds.length === 0) {callRecordingIds = await findCallRecordingIdsForCalendarEvents(client, {calendarEventIds: requestedCalendarEventIds,});@@ -71,21 +44,9 @@ export const generateCallRecordingSummariesHandler = async (}}- const isSweep = !hasRequestedIds;-- if (isSweep) {- callRecordingIds = await findCallRecordingIdsMissingSummary(client);-- if (callRecordingIds.length === 0) {- return { outcome: 'nothing-to-summarize' };- }- }-- const result = await generateMissingCallRecordingSummaries({+ const result = await generateCallRecordingSummariesForIds({client,callRecordingIds,- deadlineAtMs:- startedAtMs + TIMEOUT_SECONDS * 1000 - CONTINUATION_RESERVE_MS,});return { outcome: 'processed', ...result };@@ -96,8 +57,8 @@ export default defineLogicFunction({GENERATE_CALL_RECORDING_SUMMARIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'generate-call-recording-summaries',description:- 'Generates missing AI summaries for call recordings. Called with explicit call recording or calendar event ids for on-demand generation, or with no ids to sweep this app’s recordings that have a transcript but no summary; re-invokes itself with the remaining ids when a batch approaches the timeout.',- timeoutSeconds: TIMEOUT_SECONDS,+ 'Generates or regenerates AI summaries on demand for the requested call recordings or for the recordings of the requested calendar events.',+ timeoutSeconds: 900,handler: generateCallRecordingSummariesHandler,httpRouteTriggerSettings: {path: GENERATE_CALL_RECORDING_SUMMARIES_ROUTE_PATH,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.tsindex be447e406fe..6a22285decb 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/import-call-recording-artifacts.ts@@ -1,50 +1,42 @@-import { isNull, isUndefined } from '@sniptt/guards';+import { isUndefined } from '@sniptt/guards';import { CoreApiClient } from 'twenty-client-sdk/core';-import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { defineLogicFunction } from 'twenty-sdk/define';import { IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/import-call-recording-artifacts-logic-function-universal-identifier';-import { IMPORT_CALL_RECORDING_ARTIFACTS_ROUTE_PATH } from 'src/constants/import-call-recording-artifacts-route-path';import {importCallRecordingArtifacts,type ImportCallRecordingArtifactsResult,} from 'src/logic-functions/flows/import-call-recording-artifacts.util';-import { type CallRecordingArtifactsImportRequest } from 'src/logic-functions/types/call-recording-artifacts-import-request.type';+import { asRecord } from 'src/logic-functions/utils/as-record.util';+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';import { getString } from 'src/logic-functions/utils/get-string.util';export const importCallRecordingArtifactsHandler = async (- payload: RoutePayload<Partial<CallRecordingArtifactsImportRequest>>,+ payload: unknown,): Promise<ImportCallRecordingArtifactsResult> => {- const request = parseCallRecordingArtifactsImportRequest(payload.body);+ const body = asRecord(payload);+ const callRecordingId = getString(body?.callRecordingId);+ const requestedAt = getString(body?.requestedAt);- if (isUndefined(request)) {+ if (isUndefined(callRecordingId) || isUndefined(requestedAt)) {return {status: 'skipped',- callRecordingId: getString(payload.body?.callRecordingId) ?? 'unknown',+ callRecordingId: callRecordingId ?? 'unknown',reason: 'invalid call recording artifacts import request',};}- return importCallRecordingArtifacts({- client: new CoreApiClient(),- request,- });-};--const parseCallRecordingArtifactsImportRequest = (- body: Partial<CallRecordingArtifactsImportRequest> | null | undefined,-): CallRecordingArtifactsImportRequest | undefined => {- if (isNull(body) || isUndefined(body)) {- return undefined;- }-- const callRecordingId = getString(body.callRecordingId);- const requestedAt = getString(body.requestedAt);-- if (isUndefined(callRecordingId) || isUndefined(requestedAt)) {- return undefined;+ try {+ return await importCallRecordingArtifacts({+ client: new CoreApiClient(),+ request: { callRecordingId, requestedAt },+ });+ } catch (error) {+ throw buildRetryableStepFailure(+ `artifact import for call recording ${callRecordingId}`,+ error,+ );}-- return { callRecordingId, requestedAt };};export default defineLogicFunction({@@ -52,12 +44,7 @@ export default defineLogicFunction({IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'import-call-recording-artifacts',description:- 'Imports recording media and transcript artifacts after a verified Recall webhook resolves the owning CallRecording.',+ 'Imports recording media and transcript artifacts as an enqueued job after a verified Recall webhook resolves the owning CallRecording.',timeoutSeconds: 250,handler: importCallRecordingArtifactsHandler,- httpRouteTriggerSettings: {- path: IMPORT_CALL_RECORDING_ARTIFACTS_ROUTE_PATH,- httpMethod: 'POST',- isAuthRequired: true,- },});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/process-recall-webhook.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/process-recall-webhook.tsindex b78e25eca6f..94b506fa4b4 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/process-recall-webhook.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/process-recall-webhook.ts@@ -4,12 +4,18 @@ import { defineLogicFunction } from 'twenty-sdk/define';import { PROCESS_RECALL_WEBHOOK_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/process-recall-webhook-logic-function-universal-identifier';import { handleRecallWebhook } from 'src/logic-functions/flows/handle-recall-webhook.util';import { type RecallWebhookBody } from 'src/logic-functions/recall-api/parse-recall-webhook-event.util';+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';-export const processRecallWebhookHandler = (body: RecallWebhookBody) =>- handleRecallWebhook({- client: new CoreApiClient(),- body,- });+export const processRecallWebhookHandler = async (body: RecallWebhookBody) => {+ try {+ return await handleRecallWebhook({+ client: new CoreApiClient(),+ body,+ });+ } catch (error) {+ throw buildRetryableStepFailure('Recall webhook processing', error);+ }+};export default defineLogicFunction({universalIdentifier:diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.tsindex 4b976fdb5ef..64329e31192 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-upcoming-calendar-events.ts@@ -1,56 +1,49 @@-import { isUndefined } from '@sniptt/guards';import { CoreApiClient } from 'twenty-client-sdk/core';-import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { defineLogicFunction } from 'twenty-sdk/define';import { RECONCILE_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/reconcile-upcoming-calendar-events-logic-function-universal-identifier';-import { RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH } from 'src/constants/reconcile-upcoming-calendar-events-route-path';-import { fetchUpcomingCalendarEventIds } from 'src/logic-functions/data/fetch-upcoming-calendar-event-ids.util';-import { reconcileUpcomingCalendarEventBatches } from 'src/logic-functions/flows/reconcile-upcoming-calendar-event-batches.util';-import { type ReconcileUpcomingCalendarEventBatchesResult } from 'src/logic-functions/flows/reconcile-upcoming-calendar-event-batches-result.type';-import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';--const TIMEOUT_SECONDS = 900;-const CONTINUATION_RESERVE_MS = 30_000;--type ReconcileUpcomingCalendarEventsRouteBody = {- calendarEventIds?: unknown;-};--type ReconcileUpcomingCalendarEventsRouteResult =+import { countReconciliationActions } from 'src/logic-functions/domain/count-reconciliation-actions.util';+import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';+import { type CallRecorderReconciliationActionCounts } from 'src/logic-functions/types/call-recorder-reconciliation-action-counts.type';+import { asRecord } from 'src/logic-functions/utils/as-record.util';+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';+import { toIdList } from 'src/logic-functions/utils/to-id-list.util';++type ReconcileUpcomingCalendarEventsResult =| { outcome: 'nothing-selected' }- | { outcome: 'nothing-to-reconcile' }- | ({ outcome: 'processed' } & ReconcileUpcomingCalendarEventBatchesResult);--const toIdList = (value: unknown): string[] =>- Array.isArray(value) ? value.filter(isNonEmptyString) : [];+ | {+ outcome: 'processed';+ reconciledCalendarEventIds: string[];+ actionCounts: CallRecorderReconciliationActionCounts;+ };export const reconcileUpcomingCalendarEventsHandler = async (- payload: RoutePayload<ReconcileUpcomingCalendarEventsRouteBody>,-): Promise<ReconcileUpcomingCalendarEventsRouteResult> => {- const startedAtMs = Date.now();- const client = new CoreApiClient();-- const requestedCalendarEventIds = payload.body?.calendarEventIds;- const isSweep = isUndefined(requestedCalendarEventIds);-- const calendarEventIds = isSweep- ? await fetchUpcomingCalendarEventIds(client, new Date(startedAtMs))- : toIdList(requestedCalendarEventIds);+ payload: unknown,+): Promise<ReconcileUpcomingCalendarEventsResult> => {+ const calendarEventIds = toIdList(asRecord(payload)?.calendarEventIds);if (calendarEventIds.length === 0) {- return isSweep- ? { outcome: 'nothing-to-reconcile' }- : { outcome: 'nothing-selected' };+ return { outcome: 'nothing-selected' };}- const result = await reconcileUpcomingCalendarEventBatches({- client,- calendarEventIds,- deadlineAtMs:- startedAtMs + TIMEOUT_SECONDS * 1000 - CONTINUATION_RESERVE_MS,- });-- return { outcome: 'processed', ...result };+ try {+ const reconciliationResults =+ await reconcileCallRecorderForCalendarEventIds({+ client: new CoreApiClient(),+ calendarEventIds,+ });++ return {+ outcome: 'processed',+ reconciledCalendarEventIds: calendarEventIds,+ actionCounts: countReconciliationActions(reconciliationResults),+ };+ } catch (error) {+ throw buildRetryableStepFailure(+ 'upcoming calendar event batch reconciliation',+ error,+ );+ }};export default defineLogicFunction({@@ -58,12 +51,7 @@ export default defineLogicFunction({RECONCILE_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'reconcile-upcoming-calendar-events',description:- 'Sweeps upcoming calendar events through reconciliation, self-continuing with the remaining ids near the timeout.',- timeoutSeconds: TIMEOUT_SECONDS,+ 'Reconciles one enqueued batch of upcoming calendar events so their recording bots match the recording policy.',+ timeoutSeconds: 900,handler: reconcileUpcomingCalendarEventsHandler,- httpRouteTriggerSettings: {- path: RECONCILE_UPCOMING_CALENDAR_EVENTS_ROUTE_PATH,- httpMethod: 'POST',- isAuthRequired: true,- },});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.tsindex e171dd22f87..b2888922d8e 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/start-post-install-backfills.ts@@ -1,55 +1,36 @@-import { isUndefined } from '@sniptt/guards';-import {- definePostInstallLogicFunction,- type InstallPayload,-} from 'twenty-sdk/define';+import { definePostInstallLogicFunction } from 'twenty-sdk/define';import { START_POST_INSTALL_BACKFILLS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/start-post-install-backfills-logic-function-universal-identifier';-import { requestCallRecordingSummariesBackfill } from 'src/logic-functions/data/request-call-recording-summaries-backfill.util';-import { requestUpcomingCalendarEventsReconciliation } from 'src/logic-functions/data/request-upcoming-calendar-events-reconciliation.util';+import { SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/sweep-upcoming-calendar-events-logic-function-universal-identifier';+import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';-// An app is allowed a single post-install hook, so the two backfills share it:-// a fresh install seeds the scheduling window, an upgrade relies on the scheduled sweep and backfills summaries.type StartPostInstallBackfillsResult = {- calendarEventSweepOutcome: 'sweep-requested' | 'skipped-upgrade';- summaryBackfillOutcome: 'skipped-initial-install' | 'backfill-requested';+ calendarEventSweepOutcome: 'sweep-enqueued';};-export const startPostInstallBackfillsHandler = async ({- previousVersion,-}: InstallPayload): Promise<StartPostInstallBackfillsResult> => {- if (isUndefined(previousVersion)) {- if (!(await requestUpcomingCalendarEventsReconciliation())) {- throw new Error(- '[call-recorder] Failed to start post-install backfills: upcoming calendar event sweep',- );+// The async install hook is redelivered only for retryable failures.+export const startPostInstallBackfillsHandler =+ async (): Promise<StartPostInstallBackfillsResult> => {+ try {+ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier:+ SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: [{}],+ });+ } catch (error) {+ throw buildRetryableStepFailure('post-install sweep kickoff', error);}- return {- calendarEventSweepOutcome: 'sweep-requested',- summaryBackfillOutcome: 'skipped-initial-install',- };- }-- if (!(await requestCallRecordingSummariesBackfill())) {- throw new Error(- '[call-recorder] Failed to start post-install backfills: call recording summary backfill',- );- }-- return {- calendarEventSweepOutcome: 'skipped-upgrade',- summaryBackfillOutcome: 'backfill-requested',+ return { calendarEventSweepOutcome: 'sweep-enqueued' };};-};export default definePostInstallLogicFunction({universalIdentifier:START_POST_INSTALL_BACKFILLS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'start-post-install-backfills',description:- 'Schedules recording bots for upcoming meetings on install, and backfills missing call recording summaries on upgrade.',+ 'Schedules recording bots for upcoming meetings when the app is installed.',timeoutSeconds: 30,- shouldRunOnVersionUpgrade: true,handler: startPostInstallBackfillsHandler,});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/summarize-call-recording.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/summarize-call-recording.tsindex abfad0d5092..f461b07feb5 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/summarize-call-recording.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/summarize-call-recording.ts@@ -7,6 +7,7 @@ import {import { SUMMARIZE_CALL_RECORDING_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/summarize-call-recording-logic-function-universal-identifier';import { generateCallRecordingSummary } from 'src/logic-functions/flows/generate-call-recording-summary.util';+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';const CALL_RECORDING_OBJECT_NAME = 'callRecording';const TRANSCRIPT_FIELD_NAME = 'transcript';@@ -35,12 +36,17 @@ export const summarizeCallRecordingHandler = async (}const client = new CoreApiClient();- const result = await generateCallRecordingSummary(client, {- callRecordingId: event.recordId,- requireCreatedByCallRecorder: true,- });- return { callRecordingId: event.recordId, ...result };+ try {+ const result = await generateCallRecordingSummary(client, {+ callRecordingId: event.recordId,+ requireCreatedByCallRecorder: true,+ });++ return { callRecordingId: event.recordId, ...result };+ } catch (error) {+ throw buildRetryableStepFailure('call recording summarization', error);+ }};export default defineLogicFunction({diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/sweep-upcoming-calendar-events.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/sweep-upcoming-calendar-events.tsindex 36da59f112a..0fb02cf0c33 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/sweep-upcoming-calendar-events.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/sweep-upcoming-calendar-events.ts@@ -1,41 +1,61 @@import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction } from 'twenty-sdk/define';+import { RECONCILE_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/reconcile-upcoming-calendar-events-logic-function-universal-identifier';import { SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/sweep-upcoming-calendar-events-logic-function-universal-identifier';+import { UPCOMING_CALENDAR_EVENT_RECONCILIATION_BATCH_SIZE } from 'src/logic-functions/constants/upcoming-calendar-event-reconciliation-batch-size';import { UPCOMING_CALENDAR_EVENTS_SWEEP_CRON_PATTERN } from 'src/logic-functions/constants/upcoming-calendar-events-sweep-cron-pattern';+import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';import { fetchUpcomingCalendarEventIds } from 'src/logic-functions/data/fetch-upcoming-calendar-event-ids.util';-import { reconcileUpcomingCalendarEventBatches } from 'src/logic-functions/flows/reconcile-upcoming-calendar-event-batches.util';-import { type ReconcileUpcomingCalendarEventBatchesResult } from 'src/logic-functions/flows/reconcile-upcoming-calendar-event-batches-result.type';--const TIMEOUT_SECONDS = 900;-const CONTINUATION_RESERVE_MS = 30_000;+import { buildRetryableStepFailure } from 'src/logic-functions/utils/build-step-failure.util';+import { getBatches } from 'src/logic-functions/utils/get-batches.util';type SweepUpcomingCalendarEventsResult =| { outcome: 'nothing-to-reconcile' }- | ({ outcome: 'processed' } & ReconcileUpcomingCalendarEventBatchesResult);+ | {+ outcome: 'batches-enqueued';+ calendarEventCount: number;+ batchCount: number;+ };export const sweepUpcomingCalendarEventsHandler =async (): Promise<SweepUpcomingCalendarEventsResult> => {- const startedAtMs = Date.now();- const client = new CoreApiClient();+ try {+ const client = new CoreApiClient();- const calendarEventIds = await fetchUpcomingCalendarEventIds(- client,- new Date(startedAtMs),- );+ const calendarEventIds = await fetchUpcomingCalendarEventIds(+ client,+ new Date(),+ );- if (calendarEventIds.length === 0) {- return { outcome: 'nothing-to-reconcile' };- }+ if (calendarEventIds.length === 0) {+ return { outcome: 'nothing-to-reconcile' };+ }- const result = await reconcileUpcomingCalendarEventBatches({- client,- calendarEventIds,- deadlineAtMs:- startedAtMs + TIMEOUT_SECONDS * 1000 - CONTINUATION_RESERVE_MS,- });+ const calendarEventIdBatches = getBatches(+ calendarEventIds,+ UPCOMING_CALENDAR_EVENT_RECONCILIATION_BATCH_SIZE,+ );- return { outcome: 'processed', ...result };+ await enqueueLogicFunctionJobs({+ logicFunctionUniversalIdentifier:+ RECONCILE_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ payloads: calendarEventIdBatches.map((batchCalendarEventIds) => ({+ calendarEventIds: batchCalendarEventIds,+ })),+ });++ return {+ outcome: 'batches-enqueued',+ calendarEventCount: calendarEventIds.length,+ batchCount: calendarEventIdBatches.length,+ };+ } catch (error) {+ throw buildRetryableStepFailure(+ 'upcoming calendar events sweep',+ error,+ );+ }};export default defineLogicFunction({@@ -43,8 +63,8 @@ export default defineLogicFunction({SWEEP_UPCOMING_CALENDAR_EVENTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'sweep-upcoming-calendar-events',description:- 'Reconciles upcoming calendar events on a schedule so meetings entering the scheduling horizon get their recording bots.',- timeoutSeconds: TIMEOUT_SECONDS,+ 'Enqueues one reconciliation batch per group of upcoming calendar events on a schedule so meetings entering the scheduling horizon get their recording bots.',+ timeoutSeconds: 900,handler: sweepUpcomingCalendarEventsHandler,cronTriggerSettings: {pattern: UPCOMING_CALENDAR_EVENTS_SWEEP_CRON_PATTERN,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-reconciliation-action-counts.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-reconciliation-action-counts.type.tsnew file mode 100644index 00000000000..a990347aa70--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/call-recorder-reconciliation-action-counts.type.ts@@ -0,0 +1,6 @@+import { type CallRecorderReconciliationResult } from 'src/logic-functions/types/call-recorder-reconciliation-result.type';++export type CallRecorderReconciliationActionCounts = Record<+ Lowercase<CallRecorderReconciliationResult['action']>,+ number+>;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/get-batches.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/get-batches.test.tsnew file mode 100644index 00000000000..2e06c615b87--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/__tests__/get-batches.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { getBatches } from 'src/logic-functions/utils/get-batches.util';++describe('getBatches', () => {+ it('returns no batches for an empty list', () => {+ expect(getBatches([], 3)).toEqual([]);+ });++ it('splits items into batches of the given size with a shorter tail', () => {+ expect(getBatches(['a', 'b', 'c', 'd', 'e'], 2)).toEqual([+ ['a', 'b'],+ ['c', 'd'],+ ['e'],+ ]);+ });++ it('keeps a list at or under the batch size as a single batch', () => {+ expect(getBatches(['a', 'b'], 2)).toEqual([['a', 'b']]);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/build-step-failure.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/build-step-failure.util.tsindex b467a838dea..fc4bb2befd6 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/build-step-failure.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/build-step-failure.util.ts@@ -1,14 +1,26 @@+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+export type StepFailure = { error: string };+const formatStepFailureMessage = (stepLabel: string, error: unknown): string =>+ `[call-recorder] ${stepLabel} failed: ${+ error instanceof Error ? error.message : String(error)+ }`;+export const buildStepFailure = (stepLabel: string,error: unknown,): StepFailure => {- const errorMessage = error instanceof Error ? error.message : String(error);-if (process.env.NODE_ENV !== 'test') {- console.error(`[call-recorder] ${stepLabel} failed: ${errorMessage}`);+ console.error(formatStepFailureMessage(stepLabel, error));}return { error: `${stepLabel} failed` };};++// Only RetryableLogicFunctionError makes the job runner redeliver an enqueued job.+export const buildRetryableStepFailure = (+ stepLabel: string,+ error: unknown,+): RetryableLogicFunctionError =>+ new RetryableLogicFunctionError(formatStepFailureMessage(stepLabel, error));diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/get-batches.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/get-batches.util.tsnew file mode 100644index 00000000000..29e2f4f6837--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/get-batches.util.ts@@ -0,0 +1,12 @@+export const getBatches = <TItem>(+ items: TItem[],+ batchSize: number,+): TItem[][] => {+ const batches: TItem[][] = [];++ for (let batchStart = 0; batchStart < items.length; batchStart += batchSize) {+ batches.push(items.slice(batchStart, batchStart + batchSize));+ }++ return batches;+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/to-id-list.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/to-id-list.util.tsnew file mode 100644index 00000000000..596c0c0fe15--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/to-id-list.util.ts@@ -0,0 +1,4 @@+import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';++export const toIdList = (value: unknown): string[] =>+ Array.isArray(value) ? value.filter(isNonEmptyString) : [];diff --git a/packages/twenty-apps/public/call-recorder/yarn.lock b/packages/twenty-apps/public/call-recorder/yarn.lockindex bff2b73dd99..04b20647355 100644--- a/packages/twenty-apps/public/call-recorder/yarn.lock+++ b/packages/twenty-apps/public/call-recorder/yarn.lock@@ -973,8 +973,8 @@ __metadata:react: "npm:^19.0.0"react-dom: "npm:^19.0.0"sharp: "npm:^0.35.3"- twenty-client-sdk: "npm:2.31.0-alpha.1"- twenty-sdk: "npm:2.31.0-alpha.1"+ twenty-client-sdk: "npm:2.35.0"+ twenty-sdk: "npm:2.35.0"typescript: "npm:^5.9.3"vite-tsconfig-paths: "npm:^4.2.1"vitest: "npm:^4.1.9"@@ -2841,22 +2841,22 @@ __metadata:languageName: nodelinkType: hard-"twenty-client-sdk@npm:2.31.0-alpha.1":- version: 2.31.0-alpha.1- resolution: "twenty-client-sdk@npm:2.31.0-alpha.1"+"twenty-client-sdk@npm:2.35.0":+ version: 2.35.0+ resolution: "twenty-client-sdk@npm:2.35.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/f396b04dc99eb7e224de2a6295a326fdf274a17a49db5398ee74026d9ead0202e02090cd81e95e5e3c8987268beee9de273d68fc194e5c046d6274f7ddb16c4d+ checksum: 10c0/2ce66e4647c6c6f4b4897896858f8abab3dd8aa6112b8c5c6387082ce484b6a2fb9b90060526601b13329c207ae530d25a6ba80197868a8653156505e0736f5dlanguageName: nodelinkType: hard-"twenty-sdk@npm:2.31.0-alpha.1":- version: 2.31.0-alpha.1- resolution: "twenty-sdk@npm:2.31.0-alpha.1"+"twenty-sdk@npm:2.35.0":+ version: 2.35.0+ resolution: "twenty-sdk@npm:2.35.0"dependencies:"@sniptt/guards": "npm:^0.2.0"axios: "npm:^1.16.0"@@ -2875,12 +2875,12 @@ __metadata:semver: "npm:7.6.3"sharp: "npm:^0.35.3"tinyglobby: "npm:^0.2.15"- twenty-client-sdk: "npm:2.31.0-alpha.1"+ twenty-client-sdk: "npm:2.35.0"typescript: "npm:^5.9.3"uuid: "npm:^13.0.2"bin:twenty: dist/cli.cjs- checksum: 10c0/a66ad73824532886b2cca1afe096698b226201d92bcb20eacdfb2f739d34e0a13d45fe75f5272e0dec309c2b6bbe06ee1eaa0196cd2126af19d0a44e50e821a2+ checksum: 10c0/4cb27d3b449b2fbe692516cc29b2689232e4f40de1181132ea3d9743a1fc1c9284204ddf50632fc737d06748ff9c6903630124c02382b4f61eec120beaa9f9d5languageName: nodelinkType: hard