Skip to content

The open alternative to Salesforce, designed for AI.

Call recorder: stop recovery from creating twin Recall bots (#26909)

nitincdd7836fbaec
diff --git a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
index 27a655cf82e..8a89b5feb52 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
@@ -262,7 +262,7 @@ type FakeRecallBotStatusChange = {
type FakeRecallBot = {
id: string;
metadata: Record<string, string>;
- statusCode: string;
+ statusCode?: string;
statusChanges?: FakeRecallBotStatusChange[];
recordings?: Array<{ id: string; started_at: string; completed_at: string }>;
};
@@ -287,6 +287,35 @@ const MP3_FRAME_HEADER_BYTES = Uint8Array.from([
...new Array(412).fill(0),
]);
+const RECALL_METADATA_FILTER_PREFIX = 'metadata__';
+
+const matchesRecallBotListFilters = ({
+ bot,
+ listFilters,
+}: {
+ bot: Pick<FakeRecallBot, 'metadata' | 'statusCode'>;
+ listFilters: URLSearchParams;
+}): boolean => {
+ const statusFilters = listFilters.getAll('status');
+
+ if (
+ statusFilters.length > 0 &&
+ (isUndefined(bot.statusCode) || !statusFilters.includes(bot.statusCode))
+ ) {
+ return false;
+ }
+
+ return [...listFilters.entries()]
+ .filter(([filterKey]) =>
+ filterKey.startsWith(RECALL_METADATA_FILTER_PREFIX),
+ )
+ .every(
+ ([filterKey, filterValue]) =>
+ bot.metadata[filterKey.slice(RECALL_METADATA_FILTER_PREFIX.length)] ===
+ filterValue,
+ );
+};
+
class FakeRecallApi {
bots = new Map<string, FakeRecallBot>();
botIdByIdempotencyKey = new Map<string, string>();
@@ -492,15 +521,19 @@ class FakeRecallApi {
if (method === 'GET' && requestUrl.startsWith(`${RECALL_BASE_URL}/bot/?`)) {
this.listRequestCount += 1;
+ const listFilters = new URL(requestUrl).searchParams;
+
return jsonResponse(200, {
next: null,
- results: [...this.bots.values()].map((bot) => ({
- id: bot.id,
- metadata: bot.metadata,
- status: { code: bot.statusCode },
- status_changes: bot.statusChanges ?? [],
- recordings: bot.recordings ?? [],
- })),
+ results: [...this.bots.values()]
+ .filter((bot) => matchesRecallBotListFilters({ bot, listFilters }))
+ .map((bot) => ({
+ id: bot.id,
+ metadata: bot.metadata,
+ status: { code: bot.statusCode },
+ status_changes: bot.statusChanges ?? [],
+ recordings: bot.recordings ?? [],
+ })),
});
}
@@ -681,7 +714,6 @@ class FakeRecallApi {
const bot: FakeRecallBot = {
id: `recall-bot-${randomUUID()}`,
metadata: body.metadata ?? {},
- statusCode: 'ready',
};
this.bots.set(bot.id, bot);
@@ -3080,7 +3112,7 @@ describe('call recorder app lifecycle (integration)', () => {
const calendarEventId = await createCalendarEvent();
const callRecordingId = await createPendingCallRecording({
calendarEventId,
- botScheduleAttemptedAt: hoursAgo(1),
+ botScheduleAttemptedAt: hoursAgo(0.25),
botScheduleIdempotencyKey: 'key-from-before-the-meeting-moved',
});
@@ -3098,6 +3130,26 @@ describe('call recorder app lifecycle (integration)', () => {
expect(recall.listRequestCount).toBe(1);
});
+ it('attaches a scheduled bot that has no status yet instead of creating a twin', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const callRecordingId = await createPendingCallRecording({
+ calendarEventId,
+ botScheduleAttemptedAt: hoursAgo(24),
+ });
+
+ recall.seedBot({
+ id: 'recall-bot-scheduled-before-lost-write-back',
+ metadata: buildBotMetadata(callRecordingId, workspaceId),
+ });
+
+ await runPendingRecoveryCron();
+
+ expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(
+ 'recall-bot-scheduled-before-lost-write-back',
+ );
+ expect(recall.bots.size).toBe(1);
+ });
+
it('fails a recording whose meeting ended before any bot creation was attempted', async () => {
const calendarEventId = await createCalendarEvent({
startsAt: hoursAgo(3),
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/can-reschedule-call-recording-without-recall-lookup.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/can-reschedule-call-recording-without-recall-lookup.test.ts
new file mode 100644
index 00000000000..00beb3e607b
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/can-reschedule-call-recording-without-recall-lookup.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
+import { buildRecallRoutingMetadata } from 'src/logic-functions/domain/build-recall-routing-metadata.util';
+import { canRescheduleCallRecordingWithoutRecallLookup } from 'src/logic-functions/domain/can-reschedule-call-recording-without-recall-lookup.util';
+import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';
+import { computeRecallBotCreationIdempotencyKey } from 'src/logic-functions/recall-api/schedule-recall-bot.util';
+
+const NOW = new Date('2026-01-01T12:00:00.000Z');
+const WORKSPACE_ID = 'workspace-1';
+const CALL_RECORDING_ID = 'call-recording-1';
+const MEETING_URL = 'https://meet.example.com/customer-sync';
+const MEETING_STARTS_AT = '2026-01-01T13:00:00.000Z';
+
+const canRescheduleAttemptMadeMinutesAgo = (minutesAgo: number): boolean => {
+ const botScheduleAttemptedAt = new Date(
+ NOW.getTime() - minutesAgo * MILLISECONDS_PER_MINUTE,
+ ).toISOString();
+
+ return canRescheduleCallRecordingWithoutRecallLookup({
+ callRecording: {
+ id: CALL_RECORDING_ID,
+ botScheduleAttemptedAt,
+ botScheduleIdempotencyKey: computeRecallBotCreationIdempotencyKey({
+ meetingUrl: MEETING_URL,
+ joinAt: computeRecallBotJoinAt(MEETING_STARTS_AT),
+ metadata: buildRecallRoutingMetadata({
+ callRecordingId: CALL_RECORDING_ID,
+ workspaceId: WORKSPACE_ID,
+ }),
+ attemptedAt: botScheduleAttemptedAt,
+ }),
+ },
+ calendarEvent: {
+ startsAt: MEETING_STARTS_AT,
+ conferenceLinkUrl: MEETING_URL,
+ },
+ workspaceId: WORKSPACE_ID,
+ now: NOW,
+ });
+};
+
+describe('canRescheduleCallRecordingWithoutRecallLookup', () => {
+ it('trusts re-sending an unchanged attempt made 44 minutes ago', () => {
+ expect(canRescheduleAttemptMadeMinutesAgo(44)).toBe(true);
+ });
+
+ it('requires a Recall lookup for an attempt made 46 minutes ago', () => {
+ expect(canRescheduleAttemptMadeMinutesAgo(46)).toBe(false);
+ });
+
+ it('requires a Recall lookup for an attempt timestamped in the future', () => {
+ expect(canRescheduleAttemptMadeMinutesAgo(-5)).toBe(false);
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/can-reschedule-call-recording-without-recall-lookup.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/can-reschedule-call-recording-without-recall-lookup.util.ts
index 989fa646687..07087e300d5 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/can-reschedule-call-recording-without-recall-lookup.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/can-reschedule-call-recording-without-recall-lookup.util.ts
@@ -1,14 +1,12 @@
import { isUndefined } from '@sniptt/guards';
+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';
import { type CalendarEventRecord } from 'src/logic-functions/types/calendar-event-record.type';
import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';
import { hasUnchangedBotScheduleIdempotencyKey } from 'src/logic-functions/domain/has-unchanged-bot-schedule-idempotency-key.util';
-// Recall does not document how long idempotency keys are retained (24h is
-// the industry minimum), so re-sends are only trusted while the recorded
-// attempt is clearly fresh; a stale key would create a twin bot instead of
-// deduping. Recovery normally runs within minutes of the attempt.
-const IDEMPOTENT_RESEND_WINDOW_HOURS = 12;
+// Recall forgets idempotency keys after 1 hour, and a re-send after that creates a twin bot.
+const IDEMPOTENT_RESEND_WINDOW_MINUTES = 45;
// Rows without a schedule-attempt marker never reached Recall, so no bot can
// exist for them. Rows whose stored idempotency key still matches the current
@@ -19,8 +17,11 @@ export const canRescheduleCallRecordingWithoutRecallLookup = ({
workspaceId,
now,
}: {
- callRecording: CallRecordingRecord;
- calendarEvent: CalendarEventRecord;
+ callRecording: Pick<
+ CallRecordingRecord,
+ 'id' | 'botScheduleAttemptedAt' | 'botScheduleIdempotencyKey'
+ >;
+ calendarEvent: Pick<CalendarEventRecord, 'conferenceLinkUrl' | 'startsAt'>;
workspaceId: string | undefined;
now: Date;
}): boolean =>
@@ -49,6 +50,7 @@ const isWithinIdempotentResendWindow = (
// untrustworthy rather than fresh.
return (
elapsedMilliseconds >= 0 &&
- elapsedMilliseconds < IDEMPOTENT_RESEND_WINDOW_HOURS * 60 * 60 * 1000
+ elapsedMilliseconds <
+ IDEMPOTENT_RESEND_WINDOW_MINUTES * MILLISECONDS_PER_MINUTE
);
};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-unchanged-bot-schedule-idempotency-key.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-unchanged-bot-schedule-idempotency-key.util.ts
index c9c82935a89..a6aeff8554b 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-unchanged-bot-schedule-idempotency-key.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-unchanged-bot-schedule-idempotency-key.util.ts
@@ -15,8 +15,11 @@ export const hasUnchangedBotScheduleIdempotencyKey = ({
calendarEvent,
workspaceId,
}: {
- callRecording: CallRecordingRecord;
- calendarEvent: CalendarEventRecord;
+ callRecording: Pick<
+ CallRecordingRecord,
+ 'id' | 'botScheduleAttemptedAt' | 'botScheduleIdempotencyKey'
+ >;
+ calendarEvent: Pick<CalendarEventRecord, 'conferenceLinkUrl' | 'startsAt'>;
workspaceId: string;
}): boolean => {
const storedIdempotencyKey = callRecording.botScheduleIdempotencyKey;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/retry-failed-recall-cancellations.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/retry-failed-recall-cancellations.test.ts
index c86228eddb3..3c1bf650418 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/retry-failed-recall-cancellations.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/retry-failed-recall-cancellations.test.ts
@@ -251,93 +251,6 @@ describe('retryFailedRecallCancellations', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
- it('recovers and cancels a provider bot when endsAt is missing after the meeting starts', async () => {
- const client = new FakeCoreApiClient(
- [
- {
- id: 'call-recording-1',
- recordingRequestStatus: 'CANCELED',
- status: 'SCHEDULED',
- calendarEventId: 'calendar-event-1',
- externalBotId: null,
- },
- ],
- [
- {
- id: 'calendar-event-1',
- startsAt: '2026-01-01T11:00:00.000Z',
- endsAt: null,
- },
- ],
- );
- fetchMock.mockImplementation(
- async (requestUrl: string, requestInit?: { method?: string }) => {
- if (requestInit?.method === 'DELETE') {
- return buildJsonResponse(204);
- }
-
- if (requestUrl.startsWith(`${BASE_URL}/bot/?`)) {
- return {
- ...buildJsonResponse(200),
- json: async () => ({
- next: null,
- results: [
- {
- id: 'recall-bot-recovered',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- },
- ],
- }),
- };
- }
-
- throw new Error(`Unhandled fetch: ${requestUrl}`);
- },
- );
-
- const result = await retryFailedRecallCancellations({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- const listRequestUrl = fetchMock.mock.calls.find(
- ([requestUrl]) =>
- typeof requestUrl === 'string' && requestUrl.includes('/bot/?'),
- )?.[0];
- const listRequestParameters = new URL(listRequestUrl).searchParams;
-
- expect(listRequestParameters.get('metadata__twentyWorkspaceId')).toBe(
- WORKSPACE_ID,
- );
- expect(listRequestParameters.has('metadata__twentyCallRecordingId')).toBe(
- false,
- );
- expect(fetchMock).toHaveBeenCalledWith(
- `${BASE_URL}/bot/recall-bot-recovered/`,
- expect.objectContaining({ method: 'DELETE' }),
- );
- expect(client.mutations).toEqual([
- {
- id: 'call-recording-1',
- data: { externalBotId: 'recall-bot-recovered' },
- },
- {
- id: 'call-recording-1',
- data: {
- externalBotId: null,
- botScheduleAttemptedAt: null,
- botScheduleIdempotencyKey: null,
- },
- },
- ]);
- expect(result.canceledExternalBotCallRecordingIds).toEqual([
- 'call-recording-1',
- ]);
- });
-
it('persists a metadata-recovered bot id when cancellation fails after its calendar event was deleted', async () => {
const client = new FakeCoreApiClient([
{
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bots-for-pending-call-recordings.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bots-for-pending-call-recordings.test.ts
index a079cf526cd..d4b397ff09c 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bots-for-pending-call-recordings.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/schedule-recall-bots-for-pending-call-recordings.test.ts
@@ -183,11 +183,9 @@ const buildCalendarEvent = (
});
const stubRecallApi = ({
- listedBots = [],
listStatus = 200,
createBotStatus = 201,
}: {
- listedBots?: unknown[];
listStatus?: number;
createBotStatus?: number;
} = {}) => {
@@ -199,10 +197,9 @@ const stubRecallApi = ({
method === 'GET' &&
requestUrl.startsWith(RECALL_LIST_BOTS_URL_PREFIX)
) {
- return new Response(
- JSON.stringify({ next: null, results: listedBots }),
- { status: listStatus },
- );
+ return new Response(JSON.stringify({ next: null, results: [] }), {
+ status: listStatus,
+ });
}
if (method === 'POST' && requestUrl === RECALL_CREATE_BOT_URL) {
@@ -290,106 +287,6 @@ describe('scheduleRecallBotsForPendingCallRecordings', () => {
expect(client.callRecordings[0].externalBotId).toBe('recall-bot-1');
});
- it('attaches an existing bot claiming the recording instead of scheduling a duplicate', async () => {
- stubRecallApi({
- listedBots: [
- {
- id: 'recall-bot-existing',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- },
- ],
- });
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2026-01-01T11:55:00.000Z',
- }),
- ],
- calendarEvents: [buildCalendarEvent()],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(result.attachedCallRecordingIds).toEqual(['call-recording-1']);
- expect(result.scheduledCallRecordingIds).toEqual([]);
- expect(createBotCalls()).toHaveLength(0);
- expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({
- jobs: [
- {
- jobId: `credit-check.call-recording-1.recall-bot-existing.${new Date(computeRecallBotJoinAt(UPCOMING_STARTS_AT)).getTime()}`,
- payload: { callRecordingId: 'call-recording-1' },
- },
- ],
- }),
- );
- const lookupParameters = new URL(listBotRequestUrls()[0]).searchParams;
- expect(lookupParameters.get('metadata__twentyWorkspaceId')).toBe(
- WORKSPACE_ID,
- );
- expect(lookupParameters.has('metadata__twentyCallRecordingId')).toBe(
- false,
- );
- expect(lookupParameters.has('join_at_after')).toBe(false);
- expect(lookupParameters.has('join_at_before')).toBe(false);
- expect(lookupParameters.getAll('status')).toEqual([
- 'ready',
- 'joining_call',
- 'in_waiting_room',
- 'in_call_not_recording',
- 'recording_permission_allowed',
- 'recording_permission_denied',
- 'in_call_recording',
- ]);
- expect(client.callRecordings[0].externalBotId).toBe('recall-bot-existing');
- });
-
- it('looks up existing bots once for the whole run instead of per recording', async () => {
- stubRecallApi({
- listedBots: [
- {
- id: 'recall-bot-existing',
- metadata: {
- twentyWorkspaceId: WORKSPACE_ID,
- twentyCallRecordingId: 'call-recording-1',
- },
- },
- ],
- });
- const client = new FakeCoreApiClient({
- callRecordings: [
- buildPendingCallRecording({
- botScheduleAttemptedAt: '2026-01-01T11:55:00.000Z',
- }),
- buildPendingCallRecording({
- id: 'call-recording-2',
- calendarEventId: 'calendar-event-2',
- botScheduleAttemptedAt: '2026-01-01T11:55:00.000Z',
- }),
- ],
- calendarEvents: [
- buildCalendarEvent(),
- buildCalendarEvent({ id: 'calendar-event-2' }),
- ],
- });
-
- const result = await scheduleRecallBotsForPendingCallRecordings({
- client: client as unknown as CoreApiClient,
- now: NOW,
- });
-
- expect(listBotRequestUrls()).toHaveLength(1);
- expect(result.attachedCallRecordingIds).toEqual(['call-recording-1']);
- expect(result.scheduledCallRecordingIds).toEqual(['call-recording-2']);
- expect(createBotCalls()).toHaveLength(1);
- });
-
it('defers scheduling when the existing-bot lookup fails so no duplicate bot is created', async () => {
stubRecallApi({ listStatus: 400 });
const client = new FakeCoreApiClient({
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts
index e2fb181e389..324910e03f1 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/resume-pending-call-recording.util.ts
@@ -80,9 +80,6 @@ export const resumePendingCallRecording = async ({
return scheduleBot({ client, callRecording, calendarEvent });
}
- // Ambiguous attempts need a Recall bot lookup; doing one per event could
- // burst past the shared list budget, so the recovery cron owns them and
- // amortizes a single lookup across all ambiguous rows.
return {
status: 'deferred',
reason: 'ambiguous prior attempt; the recovery cron will reconcile it',
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts
index 2c495295ac5..dd91bbdae65 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/retry-failed-recall-cancellations.util.ts
@@ -47,32 +47,32 @@ export const retryFailedRecallCancellations = async ({
)
).map((calendarEvent) => [calendarEvent.id, calendarEvent]),
);
- const recoverableCallRecordingIds = new Set(
- canceledCallRecordings
- .filter(
- (callRecording) =>
- isUndefined(callRecording.externalBotId) &&
- isWithinCanceledBotRecoveryWindow({
- callRecording,
- calendarEvent: isUndefined(callRecording.calendarEventId)
- ? undefined
- : calendarEventsById.get(callRecording.calendarEventId),
- now,
- }),
- )
- .map((callRecording) => callRecording.id),
+ const recoverableCallRecordingIds = canceledCallRecordings
+ .filter(
+ (callRecording) =>
+ isUndefined(callRecording.externalBotId) &&
+ isWithinCanceledBotRecoveryWindow({
+ callRecording,
+ calendarEvent: isUndefined(callRecording.calendarEventId)
+ ? undefined
+ : calendarEventsById.get(callRecording.calendarEventId),
+ now,
+ }),
+ )
+ .map((callRecording) => callRecording.id);
+ const lookupResult = await findScheduledRecallBotIdsByCallRecordingId(
+ recoverableCallRecordingIds,
);
- const externalBotIdByCallRecordingId =
- await lookupRecoverableExternalBotIds(recoverableCallRecordingIds);
+ const externalBotIdByCallRecordingId = lookupResult.ok
+ ? lookupResult.externalBotIdByCallRecordingId
+ : new Map<string, string>();
const canceledExternalBotCallRecordingIds: string[] = [];
for (const callRecording of canceledCallRecordings) {
const externalBotId = await recoverRecallBotIdForCanceledCallRecording({
client,
callRecording,
- listedExternalBotId: recoverableCallRecordingIds.has(callRecording.id)
- ? externalBotIdByCallRecordingId?.get(callRecording.id)
- : undefined,
+ listedExternalBotId: externalBotIdByCallRecordingId.get(callRecording.id),
});
if (isUndefined(externalBotId)) {
@@ -95,22 +95,6 @@ export const retryFailedRecallCancellations = async ({
return { canceledExternalBotCallRecordingIds };
};
-// One workspace-wide list request covers every recoverable row; undefined
-// means the lookup failed and recovery must wait for the next run.
-const lookupRecoverableExternalBotIds = async (
- recoverableCallRecordingIds: Set<string>,
-): Promise<Map<string, string> | undefined> => {
- if (recoverableCallRecordingIds.size === 0) {
- return new Map();
- }
-
- const lookupResult = await findScheduledRecallBotIdsByCallRecordingId();
-
- return lookupResult.ok
- ? lookupResult.externalBotIdByCallRecordingId
- : undefined;
-};
-
const isWithinCanceledBotRecoveryWindow = ({
callRecording,
calendarEvent,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util.ts
index 977c9ba5df1..52d8a6fbcc0 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util.ts
@@ -103,11 +103,6 @@ export const scheduleRecallBotsForPendingCallRecordings = async ({
return result;
}
- // Rows without a schedule-attempt marker never reached Recall, so no bot
- // can exist for them. Rows whose stored idempotency key still matches the
- // current scheduling inputs can re-send the creation and let Recall dedupe
- // it. Only attempts whose inputs drifted since the attempt pay for a
- // Recall lookup.
const workspaceId = getCurrentWorkspaceId();
const ambiguousCallRecordings = resumableCallRecordings.filter(
({ callRecording, calendarEvent }) =>
@@ -141,10 +136,9 @@ export const scheduleRecallBotsForPendingCallRecordings = async ({
return result;
}
- // A run that POSTed a bot but died before the id write-back leaves the bot
- // claimable by metadata; one workspace-wide lookup finds them all without a
- // per-recording list call.
- const lookupResult = await findScheduledRecallBotIdsByCallRecordingId();
+ const lookupResult = await findScheduledRecallBotIdsByCallRecordingId(
+ ambiguousCallRecordings.map(({ callRecording }) => callRecording.id),
+ );
// A failed lookup can hide existing bots; creating one now could duplicate
// them, so defer to the next run.
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/has-recall-bot-ended.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/has-recall-bot-ended.test.ts
new file mode 100644
index 00000000000..71f99c76799
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/__tests__/has-recall-bot-ended.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { hasRecallBotEnded } from 'src/logic-functions/recall-api/has-recall-bot-ended.util';
+import { type RecallBotStatusChange } from 'src/logic-functions/recall-api/recall-bot-snapshot.type';
+
+const buildStatusChanges = (statusCodes: string[]): RecallBotStatusChange[] =>
+ statusCodes.map((code) => ({ code, createdAt: undefined }));
+
+describe('hasRecallBotEnded', () => {
+ it('treats a bot that is only scheduled as not ended', () => {
+ expect(hasRecallBotEnded({ statusChanges: [] })).toBe(false);
+ });
+
+ it('treats a bot that is joining or in the call as not ended', () => {
+ expect(
+ hasRecallBotEnded({
+ statusChanges: buildStatusChanges([
+ 'ready',
+ 'joining_call',
+ 'in_call_recording',
+ ]),
+ }),
+ ).toBe(false);
+ });
+
+ it('treats a bot that left the call or failed as ended', () => {
+ expect(
+ hasRecallBotEnded({
+ statusChanges: buildStatusChanges([
+ 'joining_call',
+ 'in_call_recording',
+ 'call_ended',
+ ]),
+ }),
+ ).toBe(true);
+ expect(
+ hasRecallBotEnded({
+ statusChanges: buildStatusChanges(['joining_call', 'fatal']),
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util.ts
index 3d6372dba6b..f4d3118100f 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/find-scheduled-recall-bot-ids-by-call-recording-id.util.ts
@@ -1,28 +1,29 @@
import { isUndefined } from '@sniptt/guards';
-import { ACTIVE_RECALL_BOT_STATUSES } from 'src/logic-functions/constants/active-recall-bot-statuses';
import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';
+import { buildRecallRoutingMetadata } from 'src/logic-functions/domain/build-recall-routing-metadata.util';
+import { hasRecallBotEnded } from 'src/logic-functions/recall-api/has-recall-bot-ended.util';
import { listScheduledRecallBots } from 'src/logic-functions/recall-api/list-scheduled-recall-bots.util';
-import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';
export type FindScheduledRecallBotIdsByCallRecordingIdResult =
| { ok: true; externalBotIdByCallRecordingId: Map<string, string> }
| { ok: false };
-// One workspace-wide list request covers every pending recording; Recall's
-// list endpoint has the tightest rate budget, so per-recording lookups must
-// not fan out.
-export const findScheduledRecallBotIdsByCallRecordingId =
- async (): Promise<FindScheduledRecallBotIdsByCallRecordingIdResult> => {
- const workspaceId = getCurrentWorkspaceId();
+export const findScheduledRecallBotIdsByCallRecordingId = async (
+ callRecordingIds: string[],
+): Promise<FindScheduledRecallBotIdsByCallRecordingIdResult> => {
+ const workspaceId = getCurrentWorkspaceId();
- if (isUndefined(workspaceId)) {
- return { ok: true, externalBotIdByCallRecordingId: new Map() };
- }
+ if (isUndefined(workspaceId)) {
+ return { ok: true, externalBotIdByCallRecordingId: new Map() };
+ }
+
+ const externalBotIdByCallRecordingId = new Map<string, string>();
+ for (const callRecordingId of callRecordingIds) {
+ // No status filter: a bot scheduled for later has no status until it starts joining.
const listResult = await listScheduledRecallBots({
- metadata: { twentyWorkspaceId: workspaceId },
- statuses: ACTIVE_RECALL_BOT_STATUSES,
+ metadata: buildRecallRoutingMetadata({ callRecordingId, workspaceId }),
});
if (!listResult.ok) {
@@ -43,20 +44,16 @@ export const findScheduledRecallBotIdsByCallRecordingId =
return { ok: false };
}
- const externalBotIdByCallRecordingId = new Map<string, string>();
-
- for (const bot of listResult.bots) {
- const callRecordingId = bot.metadata.twentyCallRecordingId;
-
- if (
- !isNonEmptyString(callRecordingId) ||
- externalBotIdByCallRecordingId.has(callRecordingId)
- ) {
- continue;
- }
+ const scheduledBot = listResult.bots.find(
+ (bot) =>
+ bot.metadata.twentyCallRecordingId === callRecordingId &&
+ !hasRecallBotEnded(bot),
+ );
- externalBotIdByCallRecordingId.set(callRecordingId, bot.id);
+ if (!isUndefined(scheduledBot)) {
+ externalBotIdByCallRecordingId.set(callRecordingId, scheduledBot.id);
}
+ }
- return { ok: true, externalBotIdByCallRecordingId };
- };
+ return { ok: true, externalBotIdByCallRecordingId };
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/has-recall-bot-ended.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/has-recall-bot-ended.util.ts
new file mode 100644
index 00000000000..c1d19153e03
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/recall-api/has-recall-bot-ended.util.ts
@@ -0,0 +1,9 @@
+import { ACTIVE_RECALL_BOT_STATUSES } from 'src/logic-functions/constants/active-recall-bot-statuses';
+import { type RecallBotSnapshot } from 'src/logic-functions/recall-api/recall-bot-snapshot.type';
+
+export const hasRecallBotEnded = (
+ bot: Pick<RecallBotSnapshot, 'statusChanges'>,
+): boolean =>
+ bot.statusChanges.some(
+ (statusChange) => !ACTIVE_RECALL_BOT_STATUSES.includes(statusChange.code),
+ );