Skip to content

The open alternative to Salesforce, designed for AI.

Add a Generate call summary command for Teams Call Recordings and calendar events (#28228)

nitind5b8f3529ba8
diff --git a/packages/twenty-apps/public/teams/README.md b/packages/twenty-apps/public/teams/README.md
index 572d2b9c55b..5a9e74172b2 100644
--- a/packages/twenty-apps/public/teams/README.md
+++ b/packages/twenty-apps/public/teams/README.md
@@ -8,6 +8,7 @@
- **List My Teams Transcripts**, an AI and workflow action for the meetings you organized
- **Sync Teams Transcript**, an AI and workflow action that imports one of those transcripts into a Call Recording
- **AI summary** of each imported transcript, written on its Call Recording and turned off from the app settings
+- **Generate call summary**, a command on Call Recordings and calendar events that writes or rewrites the summary of their Teams recordings
## 📌 Heads up
diff --git a/packages/twenty-apps/public/teams/SETUP.md b/packages/twenty-apps/public/teams/SETUP.md
index 82bdedafb66..bfbe0d5bc32 100644
--- a/packages/twenty-apps/public/teams/SETUP.md
+++ b/packages/twenty-apps/public/teams/SETUP.md
@@ -112,7 +112,9 @@ Twenty. An occurrence of a recurring meeting links to the series' event.
Each Call Recording that Microsoft Teams imports gets an AI summary, including
the 31-day import on connect. Each summary uses AI credits; turn off **Enable
transcript summaries** in **Settings > Applications > Microsoft Teams >
-Settings** to stop them.
+Settings** to stop them. Run **Generate call summary** on selected Call
+Recordings, or on calendar events for the latest Teams recording of each, to
+write or rewrite their summary, up to 20 calls at a time.
## Test the transcript actions
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/command-menu-items/generate-calendar-event-call-summary.command-menu-item.ts b/packages/twenty-apps/public/teams/src/features/transcripts/command-menu-items/generate-calendar-event-call-summary.command-menu-item.ts
new file mode 100644
index 00000000000..21d7902a75c
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/command-menu-items/generate-calendar-event-call-summary.command-menu-item.ts
@@ -0,0 +1,22 @@
+import {
+ defineCommandMenuItem,
+ isSelectAll,
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
+} from 'twenty-sdk/define';
+
+import {
+ TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER,
+ TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+} from 'src/features/transcripts/constants/universal-identifiers';
+
+export default defineCommandMenuItem({
+ universalIdentifier:
+ TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER,
+ availabilityObjectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.calendarEvent.universalIdentifier,
+ frontComponentUniversalIdentifier:
+ TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+ label: 'Generate call summary',
+ availabilityType: 'RECORD_SELECTION',
+ conditionalAvailabilityExpression: !isSelectAll,
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/command-menu-items/generate-call-recording-call-summary.command-menu-item.ts b/packages/twenty-apps/public/teams/src/features/transcripts/command-menu-items/generate-call-recording-call-summary.command-menu-item.ts
new file mode 100644
index 00000000000..64237ccc43b
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/command-menu-items/generate-call-recording-call-summary.command-menu-item.ts
@@ -0,0 +1,22 @@
+import {
+ defineCommandMenuItem,
+ isSelectAll,
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
+} from 'twenty-sdk/define';
+
+import {
+ TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER,
+ TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+} from 'src/features/transcripts/constants/universal-identifiers';
+
+export default defineCommandMenuItem({
+ universalIdentifier:
+ TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER,
+ availabilityObjectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.callRecording.universalIdentifier,
+ frontComponentUniversalIdentifier:
+ TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+ label: 'Generate call summary',
+ availabilityType: 'RECORD_SELECTION',
+ conditionalAvailabilityExpression: !isSelectAll,
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-generate-call-summaries-route-path.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-generate-call-summaries-route-path.ts
new file mode 100644
index 00000000000..8a1b9ff93d7
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-generate-call-summaries-route-path.ts
@@ -0,0 +1,2 @@
+export const TEAMS_GENERATE_CALL_SUMMARIES_ROUTE_PATH =
+ '/teams/transcripts/summaries/generate';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts
index b2b5dda7175..f0895a9144b 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts
@@ -51,3 +51,18 @@ export const TEAMS_SUMMARIZE_UPDATED_CALL_RECORDINGS_UNIVERSAL_IDENTIFIER =
export const TEAMS_SUMMARIZE_CALL_RECORDING_UNIVERSAL_IDENTIFIER =
'1b25742e-dc84-4a42-bca7-8ad41878f4c5';
+
+export const TEAMS_GENERATE_CALL_SUMMARIES_UNIVERSAL_IDENTIFIER =
+ '32766055-d6b5-474c-9580-8ff962c6c61d';
+
+export const TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER =
+ 'aebd7764-3736-49c9-82cb-05eabc074ffd';
+
+export const TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER =
+ 'c492385f-15b3-4abb-bd2a-3eb1e11affb6';
+
+export const TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER =
+ '09c2ae63-bee7-4651-a4d5-acf50ca2f595';
+
+export const TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER =
+ 'd83422a1-0749-4f1e-a8c5-faaae2661116';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/front-components/generate-calendar-event-call-summary.front-component.tsx b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/generate-calendar-event-call-summary.front-component.tsx
new file mode 100644
index 00000000000..8827c6038bd
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/generate-calendar-event-call-summary.front-component.tsx
@@ -0,0 +1,23 @@
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { Command, useSelectedRecordIds } from 'twenty-sdk/front-component';
+
+import { TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
+import { requestTeamsCallSummaries } from 'src/features/transcripts/front-components/utils/request-teams-call-summaries';
+
+const GenerateCalendarEventCallSummary = () => {
+ const calendarEventIds = useSelectedRecordIds();
+
+ return (
+ <Command execute={() => requestTeamsCallSummaries({ calendarEventIds })} />
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier:
+ TEAMS_GENERATE_CALENDAR_EVENT_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+ name: 'generate-calendar-event-call-summary',
+ description:
+ 'Writes or rewrites the AI summary of the Microsoft Teams Call Recordings of the selected calendar events.',
+ component: GenerateCalendarEventCallSummary,
+ isHeadless: true,
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/front-components/generate-call-recording-call-summary.front-component.tsx b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/generate-call-recording-call-summary.front-component.tsx
new file mode 100644
index 00000000000..2e93e6a854b
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/generate-call-recording-call-summary.front-component.tsx
@@ -0,0 +1,23 @@
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { Command, useSelectedRecordIds } from 'twenty-sdk/front-component';
+
+import { TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
+import { requestTeamsCallSummaries } from 'src/features/transcripts/front-components/utils/request-teams-call-summaries';
+
+const GenerateCallRecordingCallSummary = () => {
+ const callRecordingIds = useSelectedRecordIds();
+
+ return (
+ <Command execute={() => requestTeamsCallSummaries({ callRecordingIds })} />
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier:
+ TEAMS_GENERATE_CALL_RECORDING_CALL_SUMMARY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+ name: 'generate-call-recording-call-summary',
+ description:
+ 'Writes or rewrites the AI summary of the selected Microsoft Teams Call Recordings.',
+ component: GenerateCallRecordingCallSummary,
+ isHeadless: true,
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/__tests__/get-teams-call-summaries-snackbar.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/__tests__/get-teams-call-summaries-snackbar.test.ts
new file mode 100644
index 00000000000..11e0de8a7f5
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/__tests__/get-teams-call-summaries-snackbar.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+
+import { getTeamsCallSummariesSnackbar } from 'src/features/transcripts/front-components/utils/get-teams-call-summaries-snackbar';
+
+const buildProcessedResult = ({
+ summarized = 0,
+ unavailable = 0,
+ failed = 0,
+ skipped = 0,
+}: {
+ summarized?: number;
+ unavailable?: number;
+ failed?: number;
+ skipped?: number;
+}) => ({
+ outcome: 'processed' as const,
+ summarizedCallRecordingIds: Array.from({ length: summarized }, String),
+ unavailableCallRecordingIds: Array.from({ length: unavailable }, String),
+ failedCallRecordingIds: Array.from({ length: failed }, String),
+ skippedCallRecordingIds: Array.from({ length: skipped }, String),
+});
+
+describe('getTeamsCallSummariesSnackbar', () => {
+ it('should confirm generated summaries', () => {
+ expect(
+ getTeamsCallSummariesSnackbar(buildProcessedResult({ summarized: 2 })),
+ ).toEqual({ message: 'Summary generated.', variant: 'success' });
+ });
+
+ it('should report partial and complete failures', () => {
+ expect(
+ getTeamsCallSummariesSnackbar(
+ buildProcessedResult({ summarized: 1, failed: 1 }),
+ ),
+ ).toEqual({
+ message: 'Some summaries generated, some failed.',
+ variant: 'error',
+ });
+ expect(
+ getTeamsCallSummariesSnackbar(buildProcessedResult({ failed: 1 })),
+ ).toEqual({ message: 'Summary generation failed.', variant: 'error' });
+ });
+
+ it('should not report success when some transcripts could not be summarized', () => {
+ expect(
+ getTeamsCallSummariesSnackbar(
+ buildProcessedResult({ summarized: 1, unavailable: 1 }),
+ ),
+ ).toEqual({
+ message:
+ 'Some summaries generated, some transcripts could not be summarized.',
+ variant: 'error',
+ });
+ });
+
+ it('should explain why nothing was summarized', () => {
+ expect(getTeamsCallSummariesSnackbar({ outcome: 'disabled' })).toEqual({
+ message: 'Call summaries are turned off for this workspace.',
+ variant: 'error',
+ });
+ expect(
+ getTeamsCallSummariesSnackbar({ outcome: 'no-teams-call-recordings' }),
+ ).toEqual({
+ message: 'No Microsoft Teams call recording found.',
+ variant: 'error',
+ });
+ expect(
+ getTeamsCallSummariesSnackbar({ outcome: 'too-many-call-recordings' }),
+ ).toEqual({
+ message: 'Select up to 20 calls at a time.',
+ variant: 'error',
+ });
+ expect(
+ getTeamsCallSummariesSnackbar(buildProcessedResult({ unavailable: 1 })),
+ ).toEqual({
+ message: 'The transcript could not be summarized.',
+ variant: 'error',
+ });
+ expect(
+ getTeamsCallSummariesSnackbar(buildProcessedResult({ skipped: 1 })),
+ ).toEqual({ message: 'No usable transcript found.', variant: 'error' });
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/get-teams-call-summaries-snackbar.ts b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/get-teams-call-summaries-snackbar.ts
new file mode 100644
index 00000000000..10e889465f9
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/get-teams-call-summaries-snackbar.ts
@@ -0,0 +1,69 @@
+import { t } from 'twenty-sdk/front-component';
+
+import { TEAMS_GENERATE_CALL_SUMMARIES_MAX_CALL_RECORDINGS } from 'src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-max-call-recordings';
+import { type TeamsGenerateCallSummariesResult } from 'src/features/transcripts/logic-functions/types/teams-generate-call-summaries-result.type';
+
+export const getTeamsCallSummariesSnackbar = (
+ result: TeamsGenerateCallSummariesResult,
+): { message: string; variant: 'success' | 'error' } => {
+ if (result.outcome === 'disabled') {
+ return {
+ message: t('Call summaries are turned off for this workspace.'),
+ variant: 'error',
+ };
+ }
+
+ if (result.outcome === 'too-many-call-recordings') {
+ return {
+ message: t('Select up to {maxCallRecordingCount} calls at a time.', {
+ maxCallRecordingCount:
+ TEAMS_GENERATE_CALL_SUMMARIES_MAX_CALL_RECORDINGS,
+ }),
+ variant: 'error',
+ };
+ }
+
+ if (result.outcome !== 'processed') {
+ return {
+ message: t('No Microsoft Teams call recording found.'),
+ variant: 'error',
+ };
+ }
+
+ const summarizedCount = result.summarizedCallRecordingIds.length;
+ const failedCount = result.failedCallRecordingIds.length;
+ const unavailableCount = result.unavailableCallRecordingIds.length;
+
+ if (summarizedCount > 0 && failedCount > 0) {
+ return {
+ message: t('Some summaries generated, some failed.'),
+ variant: 'error',
+ };
+ }
+
+ if (summarizedCount > 0 && unavailableCount > 0) {
+ return {
+ message: t(
+ 'Some summaries generated, some transcripts could not be summarized.',
+ ),
+ variant: 'error',
+ };
+ }
+
+ if (summarizedCount > 0) {
+ return { message: t('Summary generated.'), variant: 'success' };
+ }
+
+ if (failedCount > 0) {
+ return { message: t('Summary generation failed.'), variant: 'error' };
+ }
+
+ if (unavailableCount > 0) {
+ return {
+ message: t('The transcript could not be summarized.'),
+ variant: 'error',
+ };
+ }
+
+ return { message: t('No usable transcript found.'), variant: 'error' };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/request-teams-call-summaries.ts b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/request-teams-call-summaries.ts
new file mode 100644
index 00000000000..cb9c29ec113
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/front-components/utils/request-teams-call-summaries.ts
@@ -0,0 +1,25 @@
+import { RestApiClient } from 'twenty-client-sdk/rest';
+import { enqueueSnackbar, t } from 'twenty-sdk/front-component';
+
+import { TEAMS_GENERATE_CALL_SUMMARIES_ROUTE_PATH } from 'src/features/transcripts/constants/teams-generate-call-summaries-route-path';
+import { getTeamsCallSummariesSnackbar } from 'src/features/transcripts/front-components/utils/get-teams-call-summaries-snackbar';
+import { type TeamsGenerateCallSummariesResult } from 'src/features/transcripts/logic-functions/types/teams-generate-call-summaries-result.type';
+
+export const requestTeamsCallSummaries = async (
+ selection: { callRecordingIds: string[] } | { calendarEventIds: string[] },
+): Promise<void> => {
+ try {
+ const result =
+ await new RestApiClient().post<TeamsGenerateCallSummariesResult>(
+ `/s${TEAMS_GENERATE_CALL_SUMMARIES_ROUTE_PATH}`,
+ selection,
+ );
+
+ await enqueueSnackbar(getTeamsCallSummariesSnackbar(result));
+ } catch {
+ await enqueueSnackbar({
+ message: t('Summary generation failed.'),
+ variant: 'error',
+ });
+ }
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/__tests__/teams-generate-call-summaries.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/__tests__/teams-generate-call-summaries.test.ts
new file mode 100644
index 00000000000..9304801eff6
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/__tests__/teams-generate-call-summaries.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { teamsGenerateCallSummariesHandler } from 'src/features/transcripts/logic-functions/teams-generate-call-summaries';
+import { findTeamsCallRecordingIdsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-teams-call-recording-ids-or-throw';
+import { regenerateTeamsCallSummaries } from 'src/features/transcripts/logic-functions/utils/regenerate-teams-call-summaries';
+
+vi.mock('twenty-client-sdk/core', () => ({ CoreApiClient: vi.fn() }));
+
+vi.mock(
+ 'src/features/transcripts/logic-functions/utils/is-teams-transcript-summary-enabled',
+ () => ({ isTeamsTranscriptSummaryEnabled: () => true }),
+);
+
+vi.mock(
+ 'src/features/transcripts/logic-functions/utils/find-teams-call-recording-ids-or-throw',
+ () => ({ findTeamsCallRecordingIdsOrThrow: vi.fn() }),
+);
+
+vi.mock(
+ 'src/features/transcripts/logic-functions/utils/regenerate-teams-call-summaries',
+ () => ({ regenerateTeamsCallSummaries: vi.fn() }),
+);
+
+const buildCallRecordingIds = (count: number) =>
+ Array.from({ length: count }, (_, index) => `recording-${index}`);
+
+const buildRoutePayload = (callRecordingIds: string[]) => ({
+ headers: {},
+ queryStringParameters: {},
+ pathParameters: {},
+ body: { callRecordingIds },
+ isBase64Encoded: false,
+ requestContext: { http: { method: 'POST', path: '/' } },
+ userWorkspaceId: null,
+});
+
+describe('teamsGenerateCallSummariesHandler', () => {
+ beforeEach(() => {
+ vi.mocked(findTeamsCallRecordingIdsOrThrow).mockReset();
+ vi.mocked(regenerateTeamsCallSummaries).mockReset();
+ vi.mocked(regenerateTeamsCallSummaries).mockResolvedValue({
+ summarizedCallRecordingIds: [],
+ unavailableCallRecordingIds: [],
+ failedCallRecordingIds: [],
+ skippedCallRecordingIds: [],
+ });
+ });
+
+ it('should regenerate up to 20 Teams call recordings', async () => {
+ const callRecordingIds = buildCallRecordingIds(20);
+
+ vi.mocked(findTeamsCallRecordingIdsOrThrow).mockResolvedValue(
+ callRecordingIds,
+ );
+
+ await expect(
+ teamsGenerateCallSummariesHandler(buildRoutePayload(callRecordingIds)),
+ ).resolves.toMatchObject({ outcome: 'processed' });
+ expect(regenerateTeamsCallSummaries).toHaveBeenCalledWith(
+ expect.objectContaining({ callRecordingIds }),
+ );
+ });
+
+ it('should refuse more than 20 Teams call recordings without running the agent', async () => {
+ const callRecordingIds = buildCallRecordingIds(21);
+
+ vi.mocked(findTeamsCallRecordingIdsOrThrow).mockResolvedValue(
+ callRecordingIds,
+ );
+
+ await expect(
+ teamsGenerateCallSummariesHandler(buildRoutePayload(callRecordingIds)),
+ ).resolves.toEqual({ outcome: 'too-many-call-recordings' });
+ expect(regenerateTeamsCallSummaries).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-max-call-recordings.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-max-call-recordings.ts
new file mode 100644
index 00000000000..f1b3a6f6b4d
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-max-call-recordings.ts
@@ -0,0 +1 @@
+export const TEAMS_GENERATE_CALL_SUMMARIES_MAX_CALL_RECORDINGS = 20;
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-timeout-seconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-timeout-seconds.ts
new file mode 100644
index 00000000000..dbf0a5fb08a
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-timeout-seconds.ts
@@ -0,0 +1 @@
+export const TEAMS_GENERATE_CALL_SUMMARIES_TIMEOUT_SECONDS = 900;
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-generate-call-summaries.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-generate-call-summaries.ts
new file mode 100644
index 00000000000..b5834399475
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-generate-call-summaries.ts
@@ -0,0 +1,81 @@
+import { CoreApiClient } from 'twenty-client-sdk/core';
+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';
+
+import { TEAMS_GENERATE_CALL_SUMMARIES_ROUTE_PATH } from 'src/features/transcripts/constants/teams-generate-call-summaries-route-path';
+import { TEAMS_GENERATE_CALL_SUMMARIES_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
+import { TEAMS_GENERATE_CALL_SUMMARIES_MAX_CALL_RECORDINGS } from 'src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-max-call-recordings';
+import { TEAMS_GENERATE_CALL_SUMMARIES_TIMEOUT_SECONDS } from 'src/features/transcripts/logic-functions/constants/teams-generate-call-summaries-timeout-seconds';
+import { type TeamsGenerateCallSummariesResult } from 'src/features/transcripts/logic-functions/types/teams-generate-call-summaries-result.type';
+import { findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-latest-teams-call-recording-ids-for-calendar-events-or-throw';
+import { findTeamsCallRecordingIdsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-teams-call-recording-ids-or-throw';
+import { isTeamsTranscriptSummaryEnabled } from 'src/features/transcripts/logic-functions/utils/is-teams-transcript-summary-enabled';
+import { parseRecordIds } from 'src/features/transcripts/logic-functions/utils/parse-record-ids';
+import { regenerateTeamsCallSummaries } from 'src/features/transcripts/logic-functions/utils/regenerate-teams-call-summaries';
+
+export const teamsGenerateCallSummariesHandler = async (
+ routePayload: RoutePayload<{
+ callRecordingIds?: unknown;
+ calendarEventIds?: unknown;
+ }>,
+): Promise<TeamsGenerateCallSummariesResult> => {
+ if (!isTeamsTranscriptSummaryEnabled()) {
+ return { outcome: 'disabled' };
+ }
+
+ const callRecordingIds = parseRecordIds(routePayload.body?.callRecordingIds);
+ const calendarEventIds = parseRecordIds(routePayload.body?.calendarEventIds);
+
+ if (callRecordingIds.length === 0 && calendarEventIds.length === 0) {
+ return { outcome: 'nothing-selected' };
+ }
+
+ const coreApiClient = new CoreApiClient();
+ let teamsCallRecordingIds: string[];
+
+ if (callRecordingIds.length > 0) {
+ teamsCallRecordingIds = await findTeamsCallRecordingIdsOrThrow({
+ coreApiClient,
+ callRecordingIds,
+ });
+ } else {
+ teamsCallRecordingIds =
+ await findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow({
+ coreApiClient,
+ calendarEventIds,
+ });
+ }
+
+ if (teamsCallRecordingIds.length === 0) {
+ return { outcome: 'no-teams-call-recordings' };
+ }
+
+ // Agent runs happen one by one as the caller, so the cap keeps a run inside the route timeout.
+ if (
+ teamsCallRecordingIds.length >
+ TEAMS_GENERATE_CALL_SUMMARIES_MAX_CALL_RECORDINGS
+ ) {
+ return { outcome: 'too-many-call-recordings' };
+ }
+
+ return {
+ outcome: 'processed',
+ ...(await regenerateTeamsCallSummaries({
+ coreApiClient,
+ callRecordingIds: teamsCallRecordingIds,
+ })),
+ };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: TEAMS_GENERATE_CALL_SUMMARIES_UNIVERSAL_IDENTIFIER,
+ name: 'teams-generate-call-summaries',
+ description:
+ 'Writes or rewrites the AI summary of the Microsoft Teams Call Recordings selected directly or through their calendar events.',
+ timeoutSeconds: TEAMS_GENERATE_CALL_SUMMARIES_TIMEOUT_SECONDS,
+ handler: teamsGenerateCallSummariesHandler,
+ httpRouteTriggerSettings: {
+ path: TEAMS_GENERATE_CALL_SUMMARIES_ROUTE_PATH,
+ httpMethod: 'POST',
+ isAuthRequired: true,
+ },
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-generate-call-summaries-result.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-generate-call-summaries-result.type.ts
new file mode 100644
index 00000000000..d2b83891b89
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-generate-call-summaries-result.type.ts
@@ -0,0 +1,15 @@
+export type TeamsGenerateCallSummariesResult =
+ | {
+ outcome:
+ | 'disabled'
+ | 'nothing-selected'
+ | 'no-teams-call-recordings'
+ | 'too-many-call-recordings';
+ }
+ | {
+ outcome: 'processed';
+ summarizedCallRecordingIds: string[];
+ unavailableCallRecordingIds: string[];
+ failedCallRecordingIds: string[];
+ skippedCallRecordingIds: string[];
+ };
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-latest-teams-call-recording-ids-for-calendar-events-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-latest-teams-call-recording-ids-for-calendar-events-or-throw.test.ts
new file mode 100644
index 00000000000..10d589e1306
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-latest-teams-call-recording-ids-for-calendar-events-or-throw.test.ts
@@ -0,0 +1,135 @@
+import { isDefined } from 'twenty-sdk/utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-latest-teams-call-recording-ids-for-calendar-events-or-throw';
+
+type CallRecordingNode = { id: string; calendarEventId: string | null };
+
+type QueryRequest = {
+ callRecordings: {
+ __args: { filter: { calendarEventId: { in: string[] } }; after?: string };
+ };
+};
+
+const toConnection = ({
+ nodes,
+ endCursor,
+}: {
+ nodes: CallRecordingNode[];
+ endCursor?: string;
+}) => ({
+ callRecordings: {
+ edges: nodes.map((node) => ({ node })),
+ pageInfo: {
+ hasNextPage: isDefined(endCursor),
+ endCursor: endCursor ?? null,
+ },
+ },
+});
+
+describe('findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow', () => {
+ beforeEach(() => {
+ vi.stubEnv('APPLICATION_ID', 'teams-application');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('should keep the first recording of each event from one query', async () => {
+ const query = vi.fn(async () =>
+ toConnection({
+ nodes: [
+ { id: 'recording-a-latest', calendarEventId: 'event-a' },
+ { id: 'recording-b-latest', calendarEventId: 'event-b' },
+ { id: 'recording-a-older', calendarEventId: 'event-a' },
+ ],
+ }),
+ );
+
+ await expect(
+ findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow({
+ coreApiClient: { query },
+ calendarEventIds: ['event-a', 'event-b'],
+ }),
+ ).resolves.toEqual(['recording-a-latest', 'recording-b-latest']);
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it('should read further pages only until every event has a recording', async () => {
+ const query = vi.fn(async (request: QueryRequest) => {
+ switch (request.callRecordings.__args.after) {
+ case undefined:
+ return toConnection({
+ nodes: [{ id: 'recording-a-1', calendarEventId: 'event-a' }],
+ endCursor: 'cursor-1',
+ });
+ case 'cursor-1':
+ return toConnection({
+ nodes: [
+ { id: 'recording-a-2', calendarEventId: 'event-a' },
+ { id: 'recording-b-1', calendarEventId: 'event-b' },
+ ],
+ endCursor: 'cursor-2',
+ });
+ default:
+ throw new Error('Unexpected page');
+ }
+ });
+
+ await expect(
+ findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow({
+ coreApiClient: { query },
+ calendarEventIds: ['event-a', 'event-b'],
+ }),
+ ).resolves.toEqual(['recording-a-1', 'recording-b-1']);
+ expect(query).toHaveBeenCalledTimes(2);
+ });
+
+ it('should stop on the last page when an event has no Teams recording', async () => {
+ const query = vi.fn(async () =>
+ toConnection({
+ nodes: [{ id: 'recording-a-1', calendarEventId: 'event-a' }],
+ }),
+ );
+
+ await expect(
+ findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow({
+ coreApiClient: { query },
+ calendarEventIds: ['event-a', 'event-without-recording'],
+ }),
+ ).resolves.toEqual(['recording-a-1']);
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it('should query more than 200 events in batches', async () => {
+ const calendarEventIds = Array.from(
+ { length: 201 },
+ (_, index) => `event-${index}`,
+ );
+ const query = vi.fn(async (request: QueryRequest) =>
+ toConnection({
+ nodes: request.callRecordings.__args.filter.calendarEventId.in.map(
+ (calendarEventId) => ({
+ id: `recording-${calendarEventId}`,
+ calendarEventId,
+ }),
+ ),
+ }),
+ );
+
+ const callRecordingIds =
+ await findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow({
+ coreApiClient: { query },
+ calendarEventIds,
+ });
+
+ expect(
+ query.mock.calls.map(
+ ([request]) =>
+ request.callRecordings.__args.filter.calendarEventId.in.length,
+ ),
+ ).toEqual([200, 1]);
+ expect(callRecordingIds).toHaveLength(201);
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-record-ids.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-record-ids.test.ts
new file mode 100644
index 00000000000..161ff72c0bb
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-record-ids.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseRecordIds } from 'src/features/transcripts/logic-functions/utils/parse-record-ids';
+
+describe('parseRecordIds', () => {
+ it('should keep each non-empty string id once', () => {
+ expect(parseRecordIds(['id-1', '', 'id-2', 42, null, 'id-1'])).toEqual([
+ 'id-1',
+ 'id-2',
+ ]);
+ });
+
+ it('should return no ids when the value is not an array', () => {
+ expect(parseRecordIds(undefined)).toEqual([]);
+ expect(parseRecordIds('id-1')).toEqual([]);
+ expect(parseRecordIds({ id: 'id-1' })).toEqual([]);
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-latest-teams-call-recording-ids-for-calendar-events-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-latest-teams-call-recording-ids-for-calendar-events-or-throw.ts
new file mode 100644
index 00000000000..1b2b9e9b123
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-latest-teams-call-recording-ids-for-calendar-events-or-throw.ts
@@ -0,0 +1,101 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { TWENTY_QUERY_MAX_RECORDS } from 'src/features/transcripts/logic-functions/constants/twenty-query-max-records';
+import { chunkIntoBatches } from 'src/features/transcripts/logic-functions/utils/chunk-into-batches';
+
+type CallRecordingConnection = {
+ edges: { node: { id: string; calendarEventId: string | null } }[];
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
+};
+
+const addLatestCallRecordingIdsOrThrow = async ({
+ coreApiClient,
+ applicationId,
+ calendarEventIds,
+ latestCallRecordingIdByCalendarEventId,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query'>;
+ applicationId: string;
+ calendarEventIds: string[];
+ latestCallRecordingIdByCalendarEventId: Map<string, string>;
+}): Promise<void> => {
+ let after: string | undefined;
+
+ // A recurring series links all its recordings to one event, so page until each event has one.
+ while (
+ calendarEventIds.some(
+ (calendarEventId) =>
+ !latestCallRecordingIdByCalendarEventId.has(calendarEventId),
+ )
+ ) {
+ const queryResult: { callRecordings?: CallRecordingConnection } =
+ await coreApiClient.query({
+ callRecordings: {
+ __args: {
+ filter: {
+ calendarEventId: { in: calendarEventIds },
+ applicationId: { eq: applicationId },
+ },
+ orderBy: [{ startedAt: 'DescNullsLast' }],
+ first: TWENTY_QUERY_MAX_RECORDS,
+ ...(isDefined(after) ? { after } : {}),
+ },
+ edges: { node: { id: true, calendarEventId: true } },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ },
+ });
+ const connection = queryResult.callRecordings;
+
+ for (const { node } of connection?.edges ?? []) {
+ if (
+ isNonEmptyString(node.calendarEventId) &&
+ !latestCallRecordingIdByCalendarEventId.has(node.calendarEventId)
+ ) {
+ latestCallRecordingIdByCalendarEventId.set(
+ node.calendarEventId,
+ node.id,
+ );
+ }
+ }
+
+ const endCursor = connection?.pageInfo.endCursor;
+
+ if (!connection?.pageInfo.hasNextPage || !isNonEmptyString(endCursor)) {
+ return;
+ }
+
+ after = endCursor;
+ }
+};
+
+export const findLatestTeamsCallRecordingIdsForCalendarEventsOrThrow = async ({
+ coreApiClient,
+ calendarEventIds,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query'>;
+ calendarEventIds: string[];
+}): Promise<string[]> => {
+ const applicationId = process.env.APPLICATION_ID;
+
+ if (!isNonEmptyString(applicationId)) {
+ return [];
+ }
+
+ const latestCallRecordingIdByCalendarEventId = new Map<string, string>();
+
+ for (const batch of chunkIntoBatches(
+ calendarEventIds,
+ TWENTY_QUERY_MAX_RECORDS,
+ )) {
+ await addLatestCallRecordingIdsOrThrow({
+ coreApiClient,
+ applicationId,
+ calendarEventIds: batch,
+ latestCallRecordingIdByCalendarEventId,
+ });
+ }
+
+ return [...latestCallRecordingIdByCalendarEventId.values()];
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-call-recording-ids-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-call-recording-ids-or-throw.ts
new file mode 100644
index 00000000000..11949d2fe8c
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-call-recording-ids-or-throw.ts
@@ -0,0 +1,47 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { TWENTY_QUERY_MAX_RECORDS } from 'src/features/transcripts/logic-functions/constants/twenty-query-max-records';
+import { chunkIntoBatches } from 'src/features/transcripts/logic-functions/utils/chunk-into-batches';
+
+export const findTeamsCallRecordingIdsOrThrow = async ({
+ coreApiClient,
+ callRecordingIds,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query'>;
+ callRecordingIds: string[];
+}): Promise<string[]> => {
+ const applicationId = process.env.APPLICATION_ID;
+
+ if (!isNonEmptyString(applicationId)) {
+ return [];
+ }
+
+ const teamsCallRecordingIds: string[] = [];
+
+ for (const batch of chunkIntoBatches(
+ callRecordingIds,
+ TWENTY_QUERY_MAX_RECORDS,
+ )) {
+ const queryResult: {
+ callRecordings?: { edges?: { node: { id: string } }[] };
+ } = await coreApiClient.query({
+ callRecordings: {
+ __args: {
+ filter: {
+ id: { in: batch },
+ applicationId: { eq: applicationId },
+ },
+ first: TWENTY_QUERY_MAX_RECORDS,
+ },
+ edges: { node: { id: true } },
+ },
+ });
+
+ teamsCallRecordingIds.push(
+ ...(queryResult.callRecordings?.edges?.map(({ node }) => node.id) ?? []),
+ );
+ }
+
+ return teamsCallRecordingIds;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-record-ids.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-record-ids.ts
new file mode 100644
index 00000000000..e24007e1200
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-record-ids.ts
@@ -0,0 +1,4 @@
+import { isArray, isNonEmptyString } from '@sniptt/guards';
+
+export const parseRecordIds = (value: unknown): string[] =>
+ isArray(value) ? [...new Set(value.filter(isNonEmptyString))] : [];
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/regenerate-teams-call-summaries.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/regenerate-teams-call-summaries.ts
new file mode 100644
index 00000000000..7b61a73da00
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/regenerate-teams-call-summaries.ts
@@ -0,0 +1,74 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { type TeamsCallRecordingSummaryOutcome } from 'src/features/transcripts/logic-functions/types/teams-call-recording-summary-outcome.type';
+import { type TeamsGenerateCallSummariesResult } from 'src/features/transcripts/logic-functions/types/teams-generate-call-summaries-result.type';
+import { summarizeTeamsCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/summarize-teams-call-recording-or-throw';
+import { toErrorMessage } from 'src/utils/to-error-message';
+
+const regenerateTeamsCallSummary = async ({
+ coreApiClient,
+ callRecordingId,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ callRecordingId: string;
+}): Promise<TeamsCallRecordingSummaryOutcome | 'error'> => {
+ try {
+ return await summarizeTeamsCallRecordingOrThrow({
+ coreApiClient,
+ callRecordingId,
+ shouldRegenerateExistingSummary: true,
+ });
+ } catch (error) {
+ console.error(
+ `[teams] failed to regenerate the summary of call recording ${callRecordingId}: ${toErrorMessage(error)}`,
+ );
+
+ return 'error';
+ }
+};
+
+export const regenerateTeamsCallSummaries = async ({
+ coreApiClient,
+ callRecordingIds,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ callRecordingIds: string[];
+}): Promise<
+ Omit<
+ Extract<TeamsGenerateCallSummariesResult, { outcome: 'processed' }>,
+ 'outcome'
+ >
+> => {
+ const summarizedCallRecordingIds: string[] = [];
+ const unavailableCallRecordingIds: string[] = [];
+ const failedCallRecordingIds: string[] = [];
+ const skippedCallRecordingIds: string[] = [];
+
+ for (const callRecordingId of callRecordingIds) {
+ const outcome = await regenerateTeamsCallSummary({
+ coreApiClient,
+ callRecordingId,
+ });
+
+ if (outcome === 'summarized') {
+ summarizedCallRecordingIds.push(callRecordingId);
+ } else if (outcome === 'not-summarizable') {
+ unavailableCallRecordingIds.push(callRecordingId);
+ } else if (
+ outcome === 'agent-failed' ||
+ outcome === 'save-failed' ||
+ outcome === 'error'
+ ) {
+ failedCallRecordingIds.push(callRecordingId);
+ } else {
+ skippedCallRecordingIds.push(callRecordingId);
+ }
+ }
+
+ return {
+ summarizedCallRecordingIds,
+ unavailableCallRecordingIds,
+ failedCallRecordingIds,
+ skippedCallRecordingIds,
+ };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/summarize-teams-call-recording-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/summarize-teams-call-recording-or-throw.ts
index f516aa2ed40..99f1c6df14c 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/summarize-teams-call-recording-or-throw.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/summarize-teams-call-recording-or-throw.ts
@@ -13,9 +13,11 @@ import { toErrorMessage } from 'src/utils/to-error-message';
export const summarizeTeamsCallRecordingOrThrow = async ({
coreApiClient,
callRecordingId,
+ shouldRegenerateExistingSummary = false,
}: {
coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
callRecordingId: string;
+ shouldRegenerateExistingSummary?: boolean;
}): Promise<TeamsCallRecordingSummaryOutcome> => {
if (!isTeamsTranscriptSummaryEnabled()) {
return 'disabled';
@@ -30,7 +32,7 @@ export const summarizeTeamsCallRecordingOrThrow = async ({
return 'not-found';
}
- if (callRecording.hasSummary) {
+ if (callRecording.hasSummary && !shouldRegenerateExistingSummary) {
return 'already-summarized';
}