The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(call-recorder): cancel open recording requests and upcoming Recall bots on uninstall (#24361)
nitindf8c5455a013
diff --git a/packages/twenty-apps/public/call-recorder/package.json b/packages/twenty-apps/public/call-recorder/package.jsonindex b29e2393175..47b214f6486 100644--- a/packages/twenty-apps/public/call-recorder/package.json+++ b/packages/twenty-apps/public/call-recorder/package.json@@ -1,6 +1,6 @@{"name": "@twentyhq/call-recorder",- "version": "1.7.2",+ "version": "1.8.0","license": "MIT","engines": {"node": "^24.5.0",diff --git a/packages/twenty-apps/public/call-recorder/src/constants/cancel-recall-bots-on-uninstall-logic-function-universal-identifier.ts b/packages/twenty-apps/public/call-recorder/src/constants/cancel-recall-bots-on-uninstall-logic-function-universal-identifier.tsnew file mode 100644index 00000000000..d3eae980898--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/constants/cancel-recall-bots-on-uninstall-logic-function-universal-identifier.ts@@ -0,0 +1,2 @@+export const CANCEL_RECALL_BOTS_ON_UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =+ '8f00ec95-38f0-4dc7-816a-78374affa32a';diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/cancel-recall-bots-on-uninstall.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/cancel-recall-bots-on-uninstall.test.tsnew file mode 100644index 00000000000..7f9ad16b010--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/__tests__/cancel-recall-bots-on-uninstall.test.ts@@ -0,0 +1,157 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ cancelOpenScheduledCallRecordingRequests: vi.fn(),+ cancelWorkspaceRecallBots: vi.fn(),+ findOpenScheduledCallRecordings: vi.fn(),+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class CoreApiClient {},+}));++vi.mock(+ 'src/logic-functions/data/cancel-open-scheduled-call-recording-requests.util',+ () => ({+ cancelOpenScheduledCallRecordingRequests:+ mocks.cancelOpenScheduledCallRecordingRequests,+ }),+);++vi.mock(+ 'src/logic-functions/data/find-open-scheduled-call-recordings.util',+ () => ({+ findOpenScheduledCallRecordings: mocks.findOpenScheduledCallRecordings,+ }),+);++vi.mock('src/logic-functions/flows/cancel-workspace-recall-bots.util', () => ({+ cancelWorkspaceRecallBots: mocks.cancelWorkspaceRecallBots,+}));++import uninstallLogicFunction, {+ cancelRecallBotsOnUninstallHandler,+} from 'src/logic-functions/cancel-recall-bots-on-uninstall';++const UNINSTALL_EXECUTION_TIME = new Date('2026-01-01T08:00:00.000Z');+const RECORD_CLEANUP_REQUEST_START_CUTOFF = new Date(+ '2026-01-01T08:00:05.000Z',+);++describe('cancel-recall-bots-on-uninstall', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ vi.setSystemTime(UNINSTALL_EXECUTION_TIME);+ mocks.findOpenScheduledCallRecordings.mockResolvedValue([+ { id: 'call-recording-1', externalBotId: 'known-bot' },+ { id: 'call-recording-2' },+ { id: 'call-recording-3', externalBotId: 'known-bot' },+ ]);+ mocks.cancelOpenScheduledCallRecordingRequests.mockResolvedValue(3);+ mocks.cancelWorkspaceRecallBots.mockResolvedValue({+ scannedBotCount: 1,+ canceledExternalBotIds: ['known-bot'],+ failedExternalBotIds: [],+ truncatedBotList: false,+ cutoffReached: false,+ });+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('uses a request-compatible 30 second uninstall timeout', () => {+ expect(uninstallLogicFunction.config).toEqual(+ expect.objectContaining({+ name: 'cancel-recall-bots-on-uninstall',+ timeoutSeconds: 30,+ }),+ );+ });++ it('cancels open records by id then passes their bot ids to one 25-hour safety scan', async () => {+ const uninstallCleanupResult = await cancelRecallBotsOnUninstallHandler();++ expect(mocks.cancelOpenScheduledCallRecordingRequests).toHaveBeenCalledWith(+ expect.anything(),+ ['call-recording-1', 'call-recording-2', 'call-recording-3'],+ expect.any(Function),+ );+ expect(mocks.cancelWorkspaceRecallBots).toHaveBeenCalledWith({+ knownExternalBotIds: ['known-bot'],+ joinAtAfter: '2025-12-31T07:00:00.000Z',+ cancellationCutoffEpochMs: new Date('2026-01-01T08:00:15.000Z').getTime(),+ });+ expect(uninstallCleanupResult).toEqual({+ canceledCallRecordingRequestCount: 3,+ scannedBotCount: 1,+ canceledExternalBotIds: ['known-bot'],+ failedExternalBotIds: [],+ truncatedBotList: false,+ cutoffReached: false,+ });+ });++ it('reserves the remaining cancellation window when record reads consume their budget', async () => {+ mocks.findOpenScheduledCallRecordings.mockImplementationOnce(+ async (+ _coreApiClient: unknown,+ shouldStartPageRequest: () => boolean,+ ) => {+ expect(shouldStartPageRequest()).toBe(true);+ vi.setSystemTime(RECORD_CLEANUP_REQUEST_START_CUTOFF);++ return [{ id: 'call-recording-1', externalBotId: 'known-bot' }];+ },+ );++ await expect(cancelRecallBotsOnUninstallHandler()).rejects.toThrow(+ 'record cleanup request cutoff reached before updates started',+ );+ expect(+ mocks.cancelOpenScheduledCallRecordingRequests,+ ).not.toHaveBeenCalled();+ expect(mocks.cancelWorkspaceRecallBots).toHaveBeenCalledWith({+ knownExternalBotIds: ['known-bot'],+ joinAtAfter: '2025-12-31T07:00:00.000Z',+ cancellationCutoffEpochMs: new Date('2026-01-01T08:00:15.000Z').getTime(),+ });+ });++ it('still attempts Recall cleanup and then fails loudly when record updates fail', async () => {+ mocks.cancelOpenScheduledCallRecordingRequests.mockRejectedValue(+ new Error('Cannot update records'),+ );++ await expect(cancelRecallBotsOnUninstallHandler()).rejects.toThrow(+ 'failed to cancel open call recording requests: Cannot update records',+ );+ expect(mocks.cancelWorkspaceRecallBots).toHaveBeenCalledWith({+ knownExternalBotIds: ['known-bot'],+ joinAtAfter: '2025-12-31T07:00:00.000Z',+ cancellationCutoffEpochMs: new Date('2026-01-01T08:00:15.000Z').getTime(),+ });+ });++ it('runs the Recall safety scan and fails loudly when open records cannot be read', async () => {+ mocks.findOpenScheduledCallRecordings.mockRejectedValue(+ new Error('Cannot read records'),+ );++ await expect(cancelRecallBotsOnUninstallHandler()).rejects.toThrow(+ 'failed to read open call recording requests: Cannot read records',+ );+ expect(+ mocks.cancelOpenScheduledCallRecordingRequests,+ ).not.toHaveBeenCalled();+ expect(mocks.cancelWorkspaceRecallBots).toHaveBeenCalledWith({+ knownExternalBotIds: [],+ joinAtAfter: '2025-12-31T07:00:00.000Z',+ cancellationCutoffEpochMs: new Date('2026-01-01T08:00:15.000Z').getTime(),+ });+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/cancel-recall-bots-on-uninstall.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/cancel-recall-bots-on-uninstall.tsnew file mode 100644index 00000000000..51b9291c7c4--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/cancel-recall-bots-on-uninstall.ts@@ -0,0 +1,116 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import { defineUninstallLogicFunction } from 'twenty-sdk/define';++import { CANCEL_RECALL_BOTS_ON_UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/cancel-recall-bots-on-uninstall-logic-function-universal-identifier';+import { RECALL_API_MAX_IN_PROCESS_RETRY_WAIT_MS } from 'src/logic-functions/constants/recall-api-max-in-process-retry-wait-ms';+import { cancelOpenScheduledCallRecordingRequests } from 'src/logic-functions/data/cancel-open-scheduled-call-recording-requests.util';+import { findOpenScheduledCallRecordings } from 'src/logic-functions/data/find-open-scheduled-call-recordings.util';+import {+ cancelWorkspaceRecallBots,+ type CancelWorkspaceRecallBotsResult,+} from 'src/logic-functions/flows/cancel-workspace-recall-bots.util';+import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';++const UNINSTALL_TIMEOUT_SECONDS = 30;+const RECALL_BOT_JOIN_AT_LOOKBACK_HOURS = 25;+const RECORD_CLEANUP_REQUEST_START_BUDGET_MS = 5_000;+const UNINSTALL_RESPONSE_HEADROOM_MS = 5_000;+const RECALL_CANCELLATION_START_HEADROOM_MS =+ RECALL_API_MAX_IN_PROCESS_RETRY_WAIT_MS + UNINSTALL_RESPONSE_HEADROOM_MS;++type UninstallCleanupSummary = CancelWorkspaceRecallBotsResult & {+ canceledCallRecordingRequestCount: number;+};++export const cancelRecallBotsOnUninstallHandler =+ async (): Promise<UninstallCleanupSummary> => {+ const coreApiClient = new CoreApiClient();+ const uninstallStartedAt = new Date();+ let canceledCallRecordingRequestCount = 0;+ let knownExternalBotIds: string[] = [];+ let recordCleanupError: Error | undefined;+ const recordCleanupRequestStartCutoffEpochMs =+ uninstallStartedAt.getTime() + RECORD_CLEANUP_REQUEST_START_BUDGET_MS;+ const shouldStartRecordCleanupRequest = () =>+ Date.now() < recordCleanupRequestStartCutoffEpochMs;++ try {+ const openCallRecordings = await findOpenScheduledCallRecordings(+ coreApiClient,+ shouldStartRecordCleanupRequest,+ );++ knownExternalBotIds = getUniqueSortedIds(+ openCallRecordings.map((callRecording) => callRecording.externalBotId),+ );++ if (openCallRecordings.length > 0 && !shouldStartRecordCleanupRequest()) {+ recordCleanupError = buildRecordCleanupError(+ 'failed to cancel open call recording requests',+ 'record cleanup request cutoff reached before updates started',+ );+ } else {+ try {+ canceledCallRecordingRequestCount =+ await cancelOpenScheduledCallRecordingRequests(+ coreApiClient,+ openCallRecordings.map((callRecording) => callRecording.id),+ shouldStartRecordCleanupRequest,+ );+ } catch (error) {+ recordCleanupError = buildRecordCleanupError(+ 'failed to cancel open call recording requests',+ error,+ );+ }+ }+ } catch (error) {+ recordCleanupError = buildRecordCleanupError(+ 'failed to read open call recording requests',+ error,+ );+ }++ if (recordCleanupError !== undefined) {+ console.warn(+ `[call-recorder] uninstall record cleanup incomplete: ${recordCleanupError.message}`,+ );+ }++ const workspaceRecallBotCancellationResult =+ await cancelWorkspaceRecallBots({+ knownExternalBotIds,+ joinAtAfter: new Date(+ uninstallStartedAt.getTime() -+ RECALL_BOT_JOIN_AT_LOOKBACK_HOURS * 60 * 60 * 1000,+ ).toISOString(),+ cancellationCutoffEpochMs:+ uninstallStartedAt.getTime() ++ UNINSTALL_TIMEOUT_SECONDS * 1_000 -+ RECALL_CANCELLATION_START_HEADROOM_MS,+ });++ if (recordCleanupError !== undefined) {+ throw recordCleanupError;+ }++ return {+ canceledCallRecordingRequestCount,+ ...workspaceRecallBotCancellationResult,+ };+ };++const buildRecordCleanupError = (message: string, error: unknown): Error =>+ new Error(+ `${message}: ${error instanceof Error ? error.message : String(error)}`,+ );++export default defineUninstallLogicFunction({+ universalIdentifier:+ CANCEL_RECALL_BOTS_ON_UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ name: 'cancel-recall-bots-on-uninstall',+ description:+ 'Cancels open call recording requests and the workspace Recall bots discoverable within the uninstall request budget.',+ timeoutSeconds: UNINSTALL_TIMEOUT_SECONDS,+ handler: cancelRecallBotsOnUninstallHandler,+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/cancel-open-scheduled-call-recording-requests.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/cancel-open-scheduled-call-recording-requests.test.tsnew file mode 100644index 00000000000..ef05ecea931--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/cancel-open-scheduled-call-recording-requests.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it, vi } from 'vitest';++import { cancelOpenScheduledCallRecordingRequests } from 'src/logic-functions/data/cancel-open-scheduled-call-recording-requests.util';++const shouldAlwaysStartRequest = () => true;++describe('cancelOpenScheduledCallRecordingRequests', () => {+ it('cancels explicit recording ids in batches of at most 200', async () => {+ const capturedMutationArguments: Array<{+ filter: unknown;+ data: unknown;+ }> = [];+ const mutation = vi.fn(async (mutationArgument: any) => {+ const updateCallRecordingsArguments =+ mutationArgument.updateCallRecordings.__args;++ capturedMutationArguments.push(updateCallRecordingsArguments);++ return {+ updateCallRecordings: updateCallRecordingsArguments.filter.id.in.map(+ (id: string) => ({ id }),+ ),+ };+ });+ const callRecordingIds = Array.from(+ { length: 201 },+ (_, index) => `call-recording-${index + 1}`,+ );++ const canceledCallRecordingRequestCount =+ await cancelOpenScheduledCallRecordingRequests(+ { mutation } as never,+ callRecordingIds,+ shouldAlwaysStartRequest,+ );++ expect(canceledCallRecordingRequestCount).toBe(201);+ expect(mutation).toHaveBeenCalledTimes(2);+ expect(capturedMutationArguments[0]?.filter).toEqual({+ id: { in: callRecordingIds.slice(0, 200) },+ recordingRequestStatus: { eq: 'REQUESTED' },+ status: { eq: 'SCHEDULED' },+ });+ expect(capturedMutationArguments[1]?.filter).toEqual({+ id: { in: callRecordingIds.slice(200) },+ recordingRequestStatus: { eq: 'REQUESTED' },+ status: { eq: 'SCHEDULED' },+ });+ expect(capturedMutationArguments[0]?.data).toEqual({+ recordingRequestStatus: 'CANCELED',+ });+ });++ it('returns zero without issuing a mutation when no id is provided', async () => {+ const mutation = vi.fn(async () => ({ updateCallRecordings: [] }));++ const canceledCallRecordingRequestCount =+ await cancelOpenScheduledCallRecordingRequests(+ { mutation } as never,+ [],+ shouldAlwaysStartRequest,+ );++ expect(canceledCallRecordingRequestCount).toBe(0);+ expect(mutation).not.toHaveBeenCalled();+ });++ it('counts an omitted result list as zero for its batch', async () => {+ const mutation = vi.fn(async () => ({}));++ const canceledCallRecordingRequestCount =+ await cancelOpenScheduledCallRecordingRequests(+ { mutation } as never,+ ['call-recording-1'],+ shouldAlwaysStartRequest,+ );++ expect(canceledCallRecordingRequestCount).toBe(0);+ });++ it('attempts later batches before surfacing an earlier batch failure', async () => {+ const mutation = vi+ .fn()+ .mockResolvedValueOnce({ updateCallRecordings: [] })+ .mockRejectedValueOnce(new Error('Second batch failed'))+ .mockResolvedValueOnce({ updateCallRecordings: [] });+ const callRecordingIds = Array.from(+ { length: 401 },+ (_, index) => `call-recording-${index + 1}`,+ );++ await expect(+ cancelOpenScheduledCallRecordingRequests(+ { mutation } as never,+ callRecordingIds,+ shouldAlwaysStartRequest,+ ),+ ).rejects.toThrow('1 of 3 call recording update batches failed');+ expect(mutation).toHaveBeenCalledTimes(3);+ });++ it('stops starting update batches at the request cutoff', async () => {+ const mutation = vi.fn(async (mutationArgument: any) => ({+ updateCallRecordings:+ mutationArgument.updateCallRecordings.__args.filter.id.in.map(+ (id: string) => ({ id }),+ ),+ }));+ const shouldStartBatchRequest = vi+ .fn()+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false);+ const callRecordingIds = Array.from(+ { length: 201 },+ (_, index) => `call-recording-${index + 1}`,+ );++ await expect(+ cancelOpenScheduledCallRecordingRequests(+ { mutation } as never,+ callRecordingIds,+ shouldStartBatchRequest,+ ),+ ).rejects.toThrow(+ 'call recording update request cutoff reached before all batches were attempted',+ );+ expect(mutation).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/fetch-all-nodes.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/fetch-all-nodes.test.tsindex c82576d67fe..04e34d9ee5f 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/fetch-all-nodes.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/fetch-all-nodes.test.ts@@ -40,4 +40,23 @@ describe('fetchAllNodes', () => {'Pagination query returned no connection',);});++ it('stops starting page requests when the request policy closes', async () => {+ const fetchPage = vi.fn().mockResolvedValue({+ pageInfo: { hasNextPage: true, endCursor: 'cursor-1' },+ edges: [{ node: 'node-1' }],+ });+ const shouldStartPageRequest = vi+ .fn()+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false);++ const nodes = await fetchAllNodes<string>(+ fetchPage,+ shouldStartPageRequest,+ );++ expect(nodes).toEqual(['node-1']);+ expect(fetchPage).toHaveBeenCalledTimes(1);+ });});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/cancel-open-scheduled-call-recording-requests.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/cancel-open-scheduled-call-recording-requests.util.tsnew file mode 100644index 00000000000..8c81dae4916--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/cancel-open-scheduled-call-recording-requests.util.ts@@ -0,0 +1,78 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';++const CALL_RECORDING_UPDATE_BATCH_SIZE = 200;++export const cancelOpenScheduledCallRecordingRequests = async (+ coreApiClient: CoreApiClient,+ callRecordingIds: string[],+ shouldStartBatchRequest: () => boolean,+): Promise<number> => {+ const uniqueCallRecordingIds = [...new Set(callRecordingIds)];+ let canceledCallRecordingRequestCount = 0;+ const batchErrors: unknown[] = [];++ for (+ let batchStartIndex = 0;+ batchStartIndex < uniqueCallRecordingIds.length;+ batchStartIndex += CALL_RECORDING_UPDATE_BATCH_SIZE+ ) {+ if (!shouldStartBatchRequest()) {+ batchErrors.push(+ new Error(+ 'call recording update request cutoff reached before all batches were attempted',+ ),+ );++ break;+ }++ const callRecordingIdBatch = uniqueCallRecordingIds.slice(+ batchStartIndex,+ batchStartIndex + CALL_RECORDING_UPDATE_BATCH_SIZE,+ );+ try {+ const updateCallRecordingsResult = await coreApiClient.mutation({+ updateCallRecordings: {+ __args: {+ filter: {+ id: { in: callRecordingIdBatch },+ recordingRequestStatus: {+ eq: CallRecordingRequestStatus.REQUESTED,+ },+ status: { eq: CallRecordingStatus.SCHEDULED },+ },+ data: {+ recordingRequestStatus: CallRecordingRequestStatus.CANCELED,+ },+ },+ id: true,+ },+ });++ canceledCallRecordingRequestCount += (+ updateCallRecordingsResult.updateCallRecordings ?? []+ ).length;+ } catch (error) {+ batchErrors.push(error);+ }+ }++ if (batchErrors.length > 0) {+ const totalBatchCount = Math.ceil(+ uniqueCallRecordingIds.length / CALL_RECORDING_UPDATE_BATCH_SIZE,+ );++ throw new Error(+ `${batchErrors.length} of ${totalBatchCount} call recording update batches failed: ${batchErrors+ .map((batchError) =>+ batchError instanceof Error ? batchError.message : String(batchError),+ )+ .join('; ')}`,+ );+ }++ return canceledCallRecordingRequestCount;+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/fetch-all-nodes.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/fetch-all-nodes.util.tsindex ce16ce4fe80..5bcbb311d04 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/fetch-all-nodes.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/fetch-all-nodes.util.ts@@ -12,12 +12,13 @@ export const fetchAllNodes = async <TNode>(fetchPage: (afterCursor: string | undefined,) => Promise<ConnectionPage<TNode> | undefined>,+ shouldStartPageRequest: () => boolean = () => true,): Promise<TNode[]> => {const nodes: TNode[] = [];let hasNextPage = true;let afterCursor: string | undefined;- while (hasNextPage) {+ while (hasNextPage && shouldStartPageRequest()) {const connection = await fetchPage(afterCursor);if (isUndefined(connection)) {diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recordings-by-filter.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recordings-by-filter.util.tsindex a44e14c3135..6709335392b 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recordings-by-filter.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-call-recordings-by-filter.util.ts@@ -30,6 +30,7 @@ type CallRecordingNode = {export const findCallRecordingsByFilter = async (client: CoreApiClient,filter: Record<string, unknown>,+ shouldStartPageRequest: () => boolean = () => true,): Promise<CallRecordingRecord[]> => {const callRecordingNodes = await fetchAllNodes<CallRecordingNode>(async (afterCursor) => {@@ -69,6 +70,7 @@ export const findCallRecordingsByFilter = async (| ConnectionPage<CallRecordingNode>| undefined;},+ shouldStartPageRequest,);return callRecordingNodes.map((callRecording) => ({diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-open-scheduled-call-recordings.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-open-scheduled-call-recordings.util.tsindex 5bd855c6f44..e0bef891265 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-open-scheduled-call-recordings.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/find-open-scheduled-call-recordings.util.ts@@ -7,8 +7,13 @@ import { findCallRecordingsByFilter } from 'src/logic-functions/data/find-call-rexport const findOpenScheduledCallRecordings = async (client: CoreApiClient,+ shouldStartPageRequest: () => boolean = () => true,): Promise<CallRecordingRecord[]> =>- findCallRecordingsByFilter(client, {- recordingRequestStatus: { eq: CallRecordingRequestStatus.REQUESTED },- status: { eq: CallRecordingStatus.SCHEDULED },- });+ findCallRecordingsByFilter(+ client,+ {+ recordingRequestStatus: { eq: CallRecordingRequestStatus.REQUESTED },+ status: { eq: CallRecordingStatus.SCHEDULED },+ },+ shouldStartPageRequest,+ );diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/cancel-workspace-recall-bots.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/cancel-workspace-recall-bots.test.tsnew file mode 100644index 00000000000..06adbbea328--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/cancel-workspace-recall-bots.test.ts@@ -0,0 +1,328 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cancelWorkspaceRecallBots } from 'src/logic-functions/flows/cancel-workspace-recall-bots.util';++const JOIN_AT_AFTER = '2025-12-31T07:00:00.000Z';+const CANCELLATION_CUTOFF_EPOCH_MS = Number.MAX_SAFE_INTEGER;+const CURRENT_WORKSPACE_ID = '123e4567-e89b-12d3-a456-426614174000';+const OTHER_WORKSPACE_ID = '123e4567-e89b-12d3-a456-426614174999';+const ENVIRONMENT_VARIABLE_NAMES = [+ 'RECALL_API_KEY',+ 'RECALL_REGION',+ 'TWENTY_APP_ACCESS_TOKEN',+] as const;+const ORIGINAL_ENVIRONMENT_VALUES = ENVIRONMENT_VARIABLE_NAMES.map(+ (environmentVariableName) =>+ [environmentVariableName, process.env[environmentVariableName]] as const,+);++const buildAccessToken = (payload: Record<string, unknown>): string =>+ [+ Buffer.from(JSON.stringify({ alg: 'none' })).toString('base64url'),+ Buffer.from(JSON.stringify(payload)).toString('base64url'),+ 'signature',+ ].join('.');++const buildBot = ({+ id,+ twentyWorkspaceId,+}: {+ id: string;+ twentyWorkspaceId?: string;+}) => ({+ id,+ metadata: twentyWorkspaceId === undefined ? {} : { twentyWorkspaceId },+});++describe('cancelWorkspaceRecallBots', () => {+ const fetchMock = vi.fn();++ const buildJsonResponse = (status: number) => ({+ ok: status < 400,+ status,+ json: async () => ({}),+ });++ const stubRecallApi = ({+ bots,+ cancelStatusByBotId = {},+ listStatus = 200,+ }: {+ bots: unknown[];+ cancelStatusByBotId?: Record<string, number>;+ listStatus?: number;+ }) => {+ fetchMock.mockImplementation(+ async (url: string, requestInitialization: RequestInit) => {+ if (requestInitialization.method === 'DELETE') {+ const pathSegments = new URL(url).pathname.split('/');+ const botId = pathSegments[pathSegments.length - 2] ?? '';++ return buildJsonResponse(cancelStatusByBotId[botId] ?? 204);+ }++ if (listStatus >= 400) {+ return buildJsonResponse(listStatus);+ }++ return {+ ok: true,+ status: 200,+ json: async () => ({ next: null, results: bots }),+ };+ },+ );+ };++ const getCallsByMethod = (method: string) =>+ fetchMock.mock.calls.filter(+ ([, requestInitialization]) => requestInitialization.method === method,+ );++ beforeEach(() => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ process.env.RECALL_API_KEY = 'recall-api-key';+ process.env.RECALL_REGION = 'us-east-1';+ process.env.TWENTY_APP_ACCESS_TOKEN = buildAccessToken({+ workspaceId: CURRENT_WORKSPACE_ID,+ });+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ });++ afterEach(() => {+ ORIGINAL_ENVIRONMENT_VALUES.forEach(+ ([environmentVariableName, originalValue]) => {+ if (originalValue === undefined) {+ delete process.env[environmentVariableName];+ } else {+ process.env[environmentVariableName] = originalValue;+ }+ },+ );+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it('cancels known record bot ids before one workspace-filtered list pass', async () => {+ stubRecallApi({+ bots: [+ buildBot({ id: 'orphan-bot', twentyWorkspaceId: CURRENT_WORKSPACE_ID }),+ ],+ });++ const workspaceRecallBotCleanupResult = await cancelWorkspaceRecallBots({+ knownExternalBotIds: ['known-bot'],+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ expect(workspaceRecallBotCleanupResult).toEqual({+ scannedBotCount: 1,+ canceledExternalBotIds: ['known-bot', 'orphan-bot'],+ failedExternalBotIds: [],+ truncatedBotList: false,+ cutoffReached: false,+ });+ expect(+ fetchMock.mock.calls.map(+ ([, requestInitialization]) => requestInitialization.method,+ ),+ ).toEqual(['DELETE', 'GET', 'DELETE']);+ const [listRequestUrl] = getCallsByMethod('GET')[0];+ const listRequestParameters = new URL(listRequestUrl).searchParams;+ expect(listRequestParameters.get('join_at_after')).toBe(JOIN_AT_AFTER);+ expect(listRequestParameters.get('join_at_before')).toBeNull();+ expect(listRequestParameters.get('metadata__twentyWorkspaceId')).toBe(+ CURRENT_WORKSPACE_ID,+ );+ expect(listRequestParameters.getAll('status')).toEqual(['ready']);+ });++ it('cancels known bots five at a time', async () => {+ let releaseRecallBotCancellations: () => void = () => {};+ const recallBotCancellationsReleased = new Promise<void>((resolve) => {+ releaseRecallBotCancellations = resolve;+ });+ fetchMock.mockImplementation(+ async (_url: string, requestInitialization: RequestInit) => {+ if (requestInitialization.method === 'DELETE') {+ await recallBotCancellationsReleased;++ return buildJsonResponse(204);+ }++ return {+ ok: true,+ status: 200,+ json: async () => ({ next: null, results: [] }),+ };+ },+ );+ const knownExternalBotIds = Array.from(+ { length: 6 },+ (_, index) => `known-bot-${index + 1}`,+ );++ const workspaceRecallBotCleanupPromise = cancelWorkspaceRecallBots({+ knownExternalBotIds,+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ expect(getCallsByMethod('DELETE')).toHaveLength(5);+ releaseRecallBotCancellations();+ const workspaceRecallBotCleanupResult =+ await workspaceRecallBotCleanupPromise;++ expect(getCallsByMethod('DELETE')).toHaveLength(6);+ expect(workspaceRecallBotCleanupResult.canceledExternalBotIds).toEqual(+ knownExternalBotIds,+ );+ });++ it('does not cancel a known bot twice when the safety list also returns it', async () => {+ stubRecallApi({+ bots: [+ buildBot({ id: 'known-bot', twentyWorkspaceId: CURRENT_WORKSPACE_ID }),+ ],+ });++ const workspaceRecallBotCleanupResult = await cancelWorkspaceRecallBots({+ knownExternalBotIds: ['known-bot', 'known-bot'],+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ expect(workspaceRecallBotCleanupResult.canceledExternalBotIds).toEqual([+ 'known-bot',+ ]);+ expect(getCallsByMethod('DELETE')).toHaveLength(1);+ expect(getCallsByMethod('GET')).toHaveLength(1);+ });++ it('skips safety-list bots that are not claimed by the current workspace', async () => {+ stubRecallApi({+ bots: [+ buildBot({ id: 'other-bot', twentyWorkspaceId: OTHER_WORKSPACE_ID }),+ buildBot({ id: 'unclaimed-bot' }),+ ],+ });++ const workspaceRecallBotCleanupResult = await cancelWorkspaceRecallBots({+ knownExternalBotIds: [],+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ expect(workspaceRecallBotCleanupResult.scannedBotCount).toBe(2);+ expect(workspaceRecallBotCleanupResult.canceledExternalBotIds).toEqual([]);+ expect(getCallsByMethod('DELETE')).toHaveLength(0);+ });++ it('exposes the three retry attempts made for a joined bot returning 409', async () => {+ vi.useFakeTimers();+ stubRecallApi({ bots: [], cancelStatusByBotId: { 'joined-bot': 409 } });++ const workspaceRecallBotCleanupPromise = cancelWorkspaceRecallBots({+ knownExternalBotIds: ['joined-bot'],+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ await vi.runAllTimersAsync();+ const workspaceRecallBotCleanupResult =+ await workspaceRecallBotCleanupPromise;++ expect(workspaceRecallBotCleanupResult.failedExternalBotIds).toEqual([+ 'joined-bot',+ ]);+ expect(getCallsByMethod('DELETE')).toHaveLength(3);+ expect(getCallsByMethod('POST')).toHaveLength(0);+ });++ it('does not re-attempt a failed known bot returned by the safety list', async () => {+ stubRecallApi({+ bots: [+ buildBot({+ id: 'failing-bot',+ twentyWorkspaceId: CURRENT_WORKSPACE_ID,+ }),+ ],+ cancelStatusByBotId: { 'failing-bot': 400 },+ });++ const workspaceRecallBotCleanupResult = await cancelWorkspaceRecallBots({+ knownExternalBotIds: ['failing-bot'],+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ expect(workspaceRecallBotCleanupResult.failedExternalBotIds).toEqual([+ 'failing-bot',+ ]);+ expect(getCallsByMethod('DELETE')).toHaveLength(1);+ expect(getCallsByMethod('GET')).toHaveLength(1);+ });++ it('keeps direct cancellations when the safety list fails', async () => {+ stubRecallApi({ bots: [], listStatus: 400 });++ const workspaceRecallBotCleanupResult = await cancelWorkspaceRecallBots({+ knownExternalBotIds: ['known-bot'],+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ expect(workspaceRecallBotCleanupResult).toEqual({+ scannedBotCount: 0,+ canceledExternalBotIds: ['known-bot'],+ failedExternalBotIds: [],+ truncatedBotList: false,+ cutoffReached: false,+ });+ expect(console.warn).toHaveBeenCalledWith(+ expect.stringContaining('failed to list Recall bots'),+ );+ });++ it('stops starting Recall calls at the cancellation cutoff', async () => {+ stubRecallApi({ bots: [] });+ vi.spyOn(Date, 'now').mockReturnValueOnce(0).mockReturnValueOnce(1);+ const knownExternalBotIds = Array.from(+ { length: 6 },+ (_, index) => `known-bot-${index + 1}`,+ );++ const workspaceRecallBotCleanupResult = await cancelWorkspaceRecallBots({+ knownExternalBotIds,+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: 1,+ });++ expect(workspaceRecallBotCleanupResult.canceledExternalBotIds).toEqual(+ knownExternalBotIds.slice(0, 5),+ );+ expect(workspaceRecallBotCleanupResult.cutoffReached).toBe(true);+ expect(getCallsByMethod('DELETE')).toHaveLength(5);+ expect(getCallsByMethod('GET')).toHaveLength(0);+ });++ it('cancels known bots even when the workspace id is unavailable', async () => {+ delete process.env.TWENTY_APP_ACCESS_TOKEN;+ stubRecallApi({ bots: [] });++ const workspaceRecallBotCleanupResult = await cancelWorkspaceRecallBots({+ knownExternalBotIds: ['known-bot'],+ joinAtAfter: JOIN_AT_AFTER,+ cancellationCutoffEpochMs: CANCELLATION_CUTOFF_EPOCH_MS,+ });++ expect(workspaceRecallBotCleanupResult.canceledExternalBotIds).toEqual([+ 'known-bot',+ ]);+ expect(getCallsByMethod('DELETE')).toHaveLength(1);+ expect(getCallsByMethod('GET')).toHaveLength(0);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-workspace-recall-bots.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-workspace-recall-bots.util.tsnew file mode 100644index 00000000000..4631a57c451--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cancel-workspace-recall-bots.util.ts@@ -0,0 +1,181 @@+import { isUndefined } from '@sniptt/guards';++import { cancelRecallBot } from 'src/logic-functions/recall-api/cancel-recall-bot.util';+import { getClaimedWorkspaceId } from 'src/logic-functions/recall-api/get-claimed-workspace-id.util';+import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';+import { listScheduledRecallBotsBeforeRequestCutoff } from 'src/logic-functions/recall-api/list-scheduled-recall-bots.util';++const RECALL_BOT_CANCELLATION_CONCURRENCY = 5;++export type CancelWorkspaceRecallBotsResult = {+ scannedBotCount: number;+ canceledExternalBotIds: string[];+ failedExternalBotIds: string[];+ truncatedBotList: boolean;+ cutoffReached: boolean;+};++export const cancelWorkspaceRecallBots = async ({+ knownExternalBotIds,+ joinAtAfter,+ cancellationCutoffEpochMs,+}: {+ knownExternalBotIds: string[];+ joinAtAfter: string;+ cancellationCutoffEpochMs: number;+}): Promise<CancelWorkspaceRecallBotsResult> => {+ const attemptedCancellationExternalBotIds = new Set<string>();+ const canceledExternalBotIds: string[] = [];+ const failedExternalBotIds: string[] = [];+ let cutoffReached = false;++ const cancelBotsUntilCutoff = async (+ externalBotIds: string[],+ ): Promise<boolean> => {+ const unattemptedExternalBotIds = [...new Set(externalBotIds)].filter(+ (externalBotId) =>+ !attemptedCancellationExternalBotIds.has(externalBotId),+ );++ if (unattemptedExternalBotIds.length === 0) {+ return Date.now() >= cancellationCutoffEpochMs;+ }++ for (+ let batchStartIndex = 0;+ batchStartIndex < unattemptedExternalBotIds.length;+ batchStartIndex += RECALL_BOT_CANCELLATION_CONCURRENCY+ ) {+ if (Date.now() >= cancellationCutoffEpochMs) {+ return true;+ }++ const externalBotIdBatch = unattemptedExternalBotIds.slice(+ batchStartIndex,+ batchStartIndex + RECALL_BOT_CANCELLATION_CONCURRENCY,+ );++ externalBotIdBatch.forEach((externalBotId) =>+ attemptedCancellationExternalBotIds.add(externalBotId),+ );++ const recallBotCancellationResults = await Promise.all(+ externalBotIdBatch.map(async (externalBotId) => ({+ externalBotId,+ result: await cancelRecallBot({ externalBotId }),+ })),+ );++ for (const recallBotCancellationResult of recallBotCancellationResults) {+ if (recallBotCancellationResult.result.ok) {+ canceledExternalBotIds.push(+ recallBotCancellationResult.externalBotId,+ );+ } else {+ console.warn(+ `[call-recorder] uninstall bot cleanup incomplete: failed to cancel Recall bot ${recallBotCancellationResult.externalBotId}: ${recallBotCancellationResult.result.errorMessage}`,+ );+ failedExternalBotIds.push(recallBotCancellationResult.externalBotId);+ }+ }+ }++ return false;+ };++ cutoffReached = await cancelBotsUntilCutoff(knownExternalBotIds);++ if (cutoffReached) {+ console.warn(+ '[call-recorder] uninstall bot cleanup incomplete: cancellation cutoff reached before Recall safety scan',+ );++ return {+ scannedBotCount: 0,+ canceledExternalBotIds,+ failedExternalBotIds,+ truncatedBotList: false,+ cutoffReached: true,+ };+ }++ const currentWorkspaceId = getCurrentWorkspaceId();++ if (isUndefined(currentWorkspaceId)) {+ console.warn(+ '[call-recorder] uninstall bot cleanup incomplete: workspace id unavailable for Recall safety scan',+ );++ return {+ scannedBotCount: 0,+ canceledExternalBotIds,+ failedExternalBotIds,+ truncatedBotList: false,+ cutoffReached: false,+ };+ }++ if (Date.now() >= cancellationCutoffEpochMs) {+ console.warn(+ '[call-recorder] uninstall bot cleanup incomplete: cancellation cutoff reached before Recall safety scan',+ );++ return {+ scannedBotCount: 0,+ canceledExternalBotIds,+ failedExternalBotIds,+ truncatedBotList: false,+ cutoffReached: true,+ };+ }++ const scheduledRecallBotsResult =+ await listScheduledRecallBotsBeforeRequestCutoff({+ joinAtAfter,+ metadata: { twentyWorkspaceId: currentWorkspaceId },+ statuses: ['ready'],+ requestStartCutoffEpochMs: cancellationCutoffEpochMs,+ });++ if (!scheduledRecallBotsResult.ok) {+ console.warn(+ `[call-recorder] uninstall bot cleanup incomplete: failed to list Recall bots: ${scheduledRecallBotsResult.errorMessage}`,+ );++ return {+ scannedBotCount: 0,+ canceledExternalBotIds,+ failedExternalBotIds,+ truncatedBotList: false,+ cutoffReached: false,+ };+ }++ cutoffReached = await cancelBotsUntilCutoff(+ scheduledRecallBotsResult.bots.flatMap((scheduledRecallBot) =>+ getClaimedWorkspaceId(scheduledRecallBot) === currentWorkspaceId+ ? [scheduledRecallBot.id]+ : [],+ ),+ );++ if (cutoffReached) {+ console.warn(+ '[call-recorder] uninstall bot cleanup incomplete: cancellation cutoff reached',+ );+ }++ if (scheduledRecallBotsResult.truncated) {+ console.warn(+ '[call-recorder] uninstall bot cleanup incomplete: Recall safety scan was truncated',+ );+ }++ return {+ scannedBotCount: scheduledRecallBotsResult.bots.length,+ canceledExternalBotIds,+ failedExternalBotIds,+ truncatedBotList: scheduledRecallBotsResult.truncated,+ cutoffReached,+ };+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cleanup-orphaned-recall-bots.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cleanup-orphaned-recall-bots.util.tsindex 7511e6209ae..58295429151 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cleanup-orphaned-recall-bots.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/cleanup-orphaned-recall-bots.util.ts@@ -5,6 +5,7 @@ import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-rimport { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';import { cancelOrEjectRecallBot } from 'src/logic-functions/recall-api/cancel-or-eject-recall-bot.util';import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';+import { getClaimedWorkspaceId } from 'src/logic-functions/recall-api/get-claimed-workspace-id.util';import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';@@ -119,12 +120,6 @@ const getClaimedCallRecordingId = (return normalizeOptionalString(claimedCallRecordingId);};-const getClaimedWorkspaceId = (bot: RecallScheduledBot): string | undefined => {- const claimedWorkspaceId = bot.metadata.twentyWorkspaceId;-- return normalizeOptionalString(claimedWorkspaceId);-};-const isCurrentWorkspaceManagedBot = ({bot,currentWorkspaceId,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.tsindex 2b9aa958672..8b24085c2bf 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/recall-bot-api.test.ts@@ -6,7 +6,10 @@ import { createAsyncRecallTranscript } from 'src/logic-functions/recall-api/creaimport { ejectRecallBot } from 'src/logic-functions/recall-api/eject-recall-bot.util';import { getRecallBot } from 'src/logic-functions/recall-api/get-recall-bot.util';import { listRecallTranscripts } from 'src/logic-functions/recall-api/list-recall-transcripts.util';-import { listScheduledRecallBots } from 'src/logic-functions/recall-api/list-scheduled-recall-bots.util';+import {+ listScheduledRecallBots,+ listScheduledRecallBotsBeforeRequestCutoff,+} from 'src/logic-functions/recall-api/list-scheduled-recall-bots.util';import { rescheduleRecallBot } from 'src/logic-functions/recall-api/reschedule-recall-bot.util';import { retrieveRecallTranscript } from 'src/logic-functions/recall-api/retrieve-recall-transcript.util';import { scheduleRecallBot } from 'src/logic-functions/recall-api/schedule-recall-bot.util';@@ -331,6 +334,35 @@ describe('recall bot api', () => {expect(fetchMock).toHaveBeenCalledTimes(10);});+ it('stops starting list page requests at the request cutoff', async () => {+ const requestStartCutoffEpochMs = NOW.getTime() + 1_000;+ fetchMock.mockImplementationOnce(async () => {+ vi.setSystemTime(requestStartCutoffEpochMs);++ return {+ ok: true,+ status: 200,+ json: async () => ({+ next: 'https://ap-northeast-1.recall.ai/api/v1/bot/?cursor=page-2',+ results: [{ id: 'bot-1' }],+ }),+ };+ });++ const scheduledRecallBotsResult =+ await listScheduledRecallBotsBeforeRequestCutoff({+ joinAtAfter: '2026-01-01T08:00:00.000Z',+ requestStartCutoffEpochMs,+ });++ expect(scheduledRecallBotsResult).toEqual({+ ok: true,+ bots: [{ id: 'bot-1', metadata: {}, statusChanges: [], recordings: [] }],+ truncated: true,+ });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+it('stops paginating when the next link points outside the configured region', async () => {fetchMock.mockResolvedValue({ok: true,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.tsindex 98206e32e0f..b88aa2770ec 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/fetch-recall-list-pages.util.ts@@ -13,12 +13,14 @@ export const fetchRecallListPages = async <TItem>({config,initialPath,maxPages,+ shouldStartPageRequest,extractPageItems,malformedErrorMessage,}: {config: RecallApiConfig;initialPath: string;maxPages: number;+ shouldStartPageRequest: () => boolean;extractPageItems: (response: RecallListResponse | undefined,) => TItem[] | undefined;@@ -34,6 +36,10 @@ export const fetchRecallListPages = async <TItem>({!isUndefined(path) && pageIndex < maxPages;pageIndex++) {+ if (!shouldStartPageRequest()) {+ break;+ }+const result = await recallBotApiRequest<RecallListResponse>({config,path,diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-claimed-workspace-id.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-claimed-workspace-id.util.tsnew file mode 100644index 00000000000..cd792633bd2--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/get-claimed-workspace-id.util.ts@@ -0,0 +1,12 @@+import { type RecallScheduledBot } from 'src/logic-functions/recall-api/list-scheduled-recall-bots.util';+import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';++export const getClaimedWorkspaceId = (+ bot: RecallScheduledBot,+): string | undefined => {+ const claimedWorkspaceId = bot.metadata.twentyWorkspaceId;++ return isNonEmptyString(claimedWorkspaceId)+ ? claimedWorkspaceId.trim()+ : undefined;+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.tsindex 5c2ae2da6ae..a613ea4f5e6 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-recall-transcripts.util.ts@@ -34,6 +34,7 @@ export const listRecallTranscripts = async ({config: configResult.config,initialPath: `/transcript/?${searchParams.toString()}`,maxPages: RECALL_TRANSCRIPT_LIST_MAX_PAGES,+ shouldStartPageRequest: () => true,extractPageItems: extractRecallTranscriptSummaries,malformedErrorMessage: 'Recall API returned malformed transcript list',});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-scheduled-recall-bots.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-scheduled-recall-bots.util.tsindex 7b7a8fb100b..b35b69f27c3 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-scheduled-recall-bots.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/list-scheduled-recall-bots.util.ts@@ -20,16 +20,43 @@ type ListScheduledRecallBotsResult =const RECALL_BOT_LIST_MAX_PAGES = 10;-export const listScheduledRecallBots = async ({- joinAtAfter,- joinAtBefore,- metadata,- statuses,-}: {+type ListScheduledRecallBotsArguments = {joinAtAfter?: string;joinAtBefore?: string;metadata?: Record<string, string>;statuses?: string[];+};++export const listScheduledRecallBots = async (+ listScheduledRecallBotsArguments: ListScheduledRecallBotsArguments,+): Promise<ListScheduledRecallBotsResult> =>+ listScheduledRecallBotsWithPageRequestPolicy({+ listScheduledRecallBotsArguments,+ shouldStartPageRequest: () => true,+ });++export const listScheduledRecallBotsBeforeRequestCutoff = async ({+ requestStartCutoffEpochMs,+ ...listScheduledRecallBotsArguments+}: ListScheduledRecallBotsArguments & {+ requestStartCutoffEpochMs: number;+}): Promise<ListScheduledRecallBotsResult> =>+ listScheduledRecallBotsWithPageRequestPolicy({+ listScheduledRecallBotsArguments,+ shouldStartPageRequest: () => Date.now() < requestStartCutoffEpochMs,+ });++const listScheduledRecallBotsWithPageRequestPolicy = async ({+ listScheduledRecallBotsArguments: {+ joinAtAfter,+ joinAtBefore,+ metadata,+ statuses,+ },+ shouldStartPageRequest,+}: {+ listScheduledRecallBotsArguments: ListScheduledRecallBotsArguments;+ shouldStartPageRequest: () => boolean;}): Promise<ListScheduledRecallBotsResult> => {const configResult = getRecallApiConfig();@@ -59,6 +86,7 @@ export const listScheduledRecallBots = async ({config: configResult.config,initialPath: `/bot/?${searchParameters.toString()}`,maxPages: RECALL_BOT_LIST_MAX_PAGES,+ shouldStartPageRequest,extractPageItems: extractRecallBots,malformedErrorMessage: 'Recall API returned malformed bot list',});