Skip to content

The open alternative to Salesforce, designed for AI.

Add Sync Teams Transcript action that imports a transcript into a Call Recording (#26914)

nitin279395e744d4
diff --git a/packages/twenty-apps/public/teams/README.md b/packages/twenty-apps/public/teams/README.md
index f60707e3198..78f61b857f1 100644
--- a/packages/twenty-apps/public/teams/README.md
+++ b/packages/twenty-apps/public/teams/README.md
@@ -6,6 +6,7 @@
- **A Microsoft connection** for your work or school account
- **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
## 📌 Heads up
diff --git a/packages/twenty-apps/public/teams/SETUP.md b/packages/twenty-apps/public/teams/SETUP.md
index c0c53ab317e..3159e4b9375 100644
--- a/packages/twenty-apps/public/teams/SETUP.md
+++ b/packages/twenty-apps/public/teams/SETUP.md
@@ -16,12 +16,12 @@
enable **Microsoft Graph access**. Without it, Graph answers transcript
requests with `GraphAccessToTranscriptsDisabled`.
-| Permission | Purpose |
-| ---------------------------------- | ------------------------------------------------- |
-| `User.Read` | Identify the connected Microsoft account |
-| `Calendars.ReadBasic` | Find the scheduled meetings the account organizes |
-| `OnlineMeetings.Read` | Resolve a calendar event to its online meeting |
-| `OnlineMeetingTranscript.Read.All` | List the transcripts of those meetings |
+| Permission | Purpose |
+| ---------------------------------- | -------------------------------------------------------------- |
+| `User.Read` | Identify the connected Microsoft account |
+| `Calendars.ReadBasic` | Find the scheduled meetings the account organizes |
+| `OnlineMeetings.Read` | Resolve a calendar event to its online meeting and its subject |
+| `OnlineMeetingTranscript.Read.All` | List and download the transcripts of those meetings |
The connection also requests `openid`, `profile`, `email`, and `offline_access`
for account identity and refresh tokens. It uses the authorization code flow
@@ -56,7 +56,7 @@ Connecting an account does not import transcripts or register webhooks. The
transcript release flag and workspace setting remain off. Connecting an account
does not enable them.
-## Test the list action
+## Test the transcript actions
1. For a development build, set `IS_TRANSCRIPT_IMPORT_ENABLED` to `true`, rebuild
and deploy the app, then enable transcripts in the Microsoft Teams settings.
@@ -67,11 +67,19 @@ does not enable them.
**List My Teams Transcripts** action to a workflow. The result carries one
entry per transcript with the meeting subject, the Graph meeting ID, and the
transcript ID.
+4. Ask the assistant to sync one of them, or add **Sync Teams Transcript** to
+ the workflow with that `meetingId` and `transcriptId`. The transcript appears
+ as a Call Recording named after the meeting subject, linked to the meeting's
+ calendar event when Twenty has synced it.
-The action uses your own connection first and falls back to a workspace-shared
+Both actions use your own connection first and fall back to a workspace-shared
one. Optional `startDateTime` and `endDateTime` select the meeting window,
which defaults to the last 31 days; `nextPageUrl` continues a paginated result.
+Syncing the same transcript again updates the same Call Recording. A Call
+Recording deleted in Twenty stays deleted. If Microsoft is still processing the
+transcript, the recording is saved as Processing; sync it again later.
+
References: [Microsoft authorization code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow)
and [transcript permissions](https://learn.microsoft.com/en-us/graph/api/onlinemeeting-list-transcripts?view=graph-rest-1.0),
plus [Teams transcript API access settings](https://learn.microsoft.com/en-us/microsoftteams/meeting-transcript-api-access).
@@ -150,6 +158,9 @@ workspace. Public apps use the monorepo CI workflows.
connection and the workspace has no shared one.
- `GraphAccessToTranscriptsDisabled`: enable Microsoft Graph transcript access
in Teams meeting settings.
+- Call Recording without speaker names: the tenant disallows speaker
+ attribution in Teams meeting settings, so Microsoft only serves the transcript
+ without speakers.
- Empty result: verify that transcription was started during the scheduled
meeting time, give or take 15 minutes, Microsoft has finished processing it,
and the connected account organized the meeting.
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 446b1384fd6..f13161e36b8 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
@@ -6,3 +6,6 @@ export const TEAMS_CONNECTION_PROVIDER_UNIVERSAL_IDENTIFIER =
export const TEAMS_LIST_ORGANIZER_TRANSCRIPTS_UNIVERSAL_IDENTIFIER =
'e76f9ccb-cda3-4bd1-99aa-0e5806b1f4a2';
+
+export const TEAMS_SYNC_TRANSCRIPT_UNIVERSAL_IDENTIFIER =
+ 'c7772775-d871-428f-960e-a43ca365ba22';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-attributed-transcript-format.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-attributed-transcript-format.ts
new file mode 100644
index 00000000000..27c797c8112
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-attributed-transcript-format.ts
@@ -0,0 +1 @@
+export const GRAPH_ATTRIBUTED_TRANSCRIPT_FORMAT = 'text/vtt';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-speaker-attribution-not-allowed-error-code.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-speaker-attribution-not-allowed-error-code.ts
new file mode 100644
index 00000000000..6ed01b9ae1a
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-speaker-attribution-not-allowed-error-code.ts
@@ -0,0 +1,2 @@
+export const GRAPH_SPEAKER_ATTRIBUTION_NOT_ALLOWED_ERROR_CODE =
+ 'SpeakerAttributionNotAllowed';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-unattributed-transcript-format.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-unattributed-transcript-format.ts
new file mode 100644
index 00000000000..5b59f4bbf6f
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-unattributed-transcript-format.ts
@@ -0,0 +1,2 @@
+export const GRAPH_UNATTRIBUTED_TRANSCRIPT_FORMAT =
+ 'application/vnd.microsoft.graph.transcript+text';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts
new file mode 100644
index 00000000000..1f6d49b1571
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts
@@ -0,0 +1,111 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+import { defineLogicFunction } from 'twenty-sdk/define';
+import {
+ type InputJsonSchema,
+ type LogicFunctionExecutionContext,
+ jsonSchemaToInputSchema,
+} from 'twenty-sdk/logic-function';
+
+import { FEATURE_FLAGS } from 'src/constants/feature-flags';
+import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';
+import { TEAMS_SYNC_TRANSCRIPT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
+import { getTeamsConnectionForRequestOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw';
+import { syncTeamsTranscriptToCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw';
+import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
+import { isFeatureEnabled } from 'src/utils/is-feature-enabled';
+
+const teamsSyncTranscriptInputSchema: InputJsonSchema = {
+ type: 'object',
+ properties: {
+ meetingId: {
+ type: 'string',
+ label: 'Meeting ID',
+ description: 'The meetingId returned by List My Teams Transcripts.',
+ },
+ transcriptId: {
+ type: 'string',
+ label: 'Transcript ID',
+ description: 'The transcriptId returned by List My Teams Transcripts.',
+ },
+ },
+ required: ['meetingId', 'transcriptId'],
+ additionalProperties: false,
+};
+
+type TeamsSyncTranscriptResult =
+ | {
+ success: true;
+ callRecordingId: string;
+ calendarEventId?: string;
+ created: boolean;
+ skipped: boolean;
+ }
+ | { success: false; error: string };
+
+export const teamsSyncTranscriptHandler = async (
+ parameters: {
+ meetingId?: unknown;
+ transcriptId?: unknown;
+ },
+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,
+): Promise<TeamsSyncTranscriptResult> => {
+ if (
+ !isFeatureEnabled({
+ isAvailable: FEATURE_FLAGS.IS_TRANSCRIPT_IMPORT_ENABLED,
+ settingValue: process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY],
+ })
+ ) {
+ return { success: false, error: 'Teams transcripts are not enabled.' };
+ }
+
+ const { meetingId, transcriptId } = parameters;
+
+ if (!isNonEmptyString(meetingId) || !isNonEmptyString(transcriptId)) {
+ return {
+ success: false,
+ error: 'meetingId and transcriptId are required.',
+ };
+ }
+
+ try {
+ const connection = await getTeamsConnectionForRequestOrThrow(context);
+ const result = await syncTeamsTranscriptToCallRecordingOrThrow({
+ accessToken: connection.accessToken,
+ coreApiClient: new CoreApiClient({ runAs: 'application' }),
+ meetingId,
+ transcriptId,
+ });
+
+ return { success: true, ...result };
+ } catch (error) {
+ return { success: false, error: toErrorMessage(error) };
+ }
+};
+
+export default defineLogicFunction({
+ universalIdentifier: TEAMS_SYNC_TRANSCRIPT_UNIVERSAL_IDENTIFIER,
+ name: 'teams-sync-transcript',
+ description:
+ 'Sync one Teams meeting transcript from your connected Microsoft account into a Call Recording. Takes the meetingId and transcriptId returned by List My Teams Transcripts, links the recording to the matching calendar event, and leaves recordings deleted in Twenty deleted.',
+ timeoutSeconds: 300,
+ handler: teamsSyncTranscriptHandler,
+ toolTriggerSettings: { inputSchema: teamsSyncTranscriptInputSchema },
+ workflowActionTriggerSettings: {
+ label: 'Sync Teams Transcript',
+ inputSchema: jsonSchemaToInputSchema(teamsSyncTranscriptInputSchema),
+ outputSchema: [
+ {
+ type: 'object',
+ properties: {
+ success: { type: 'boolean' },
+ error: { type: 'string' },
+ callRecordingId: { type: 'string' },
+ calendarEventId: { type: 'string' },
+ created: { type: 'boolean' },
+ skipped: { type: 'boolean' },
+ },
+ },
+ ],
+ },
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/call-recording-sync-fields.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/call-recording-sync-fields.type.ts
new file mode 100644
index 00000000000..b26fd269a16
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/call-recording-sync-fields.type.ts
@@ -0,0 +1,11 @@
+import { type TranscriptEntry } from 'src/features/transcripts/logic-functions/types/transcript-entry.type';
+
+export type CallRecordingSyncFields = {
+ title?: string;
+ status: 'PROCESSING' | 'COMPLETED';
+ externalRecordingId: string;
+ startedAt?: string;
+ endedAt?: string;
+ transcript?: TranscriptEntry[];
+ calendarEventId?: string;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-call-transcript.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-call-transcript.type.ts
index ca581d54420..954c38b27a1 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-call-transcript.type.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-call-transcript.type.ts
@@ -1,4 +1,5 @@
export type GraphCallTranscript = {
id: string;
createdDateTime?: string | null;
+ endDateTime?: string | null;
};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-online-meeting.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-online-meeting.type.ts
index 69a85283568..0aee89117f9 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-online-meeting.type.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-online-meeting.type.ts
@@ -1,4 +1,5 @@
export type GraphOnlineMeeting = {
id: string;
subject: string | null;
+ joinWebUrl?: string | null;
};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-request-error.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-request-error.ts
index 10bc8b984e3..500f4bf40ce 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-request-error.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-request-error.ts
@@ -1,9 +1,19 @@
export class GraphRequestError extends Error {
readonly status: number;
+ readonly innerErrorCode: string | undefined;
- constructor({ message, status }: { message: string; status: number }) {
+ constructor({
+ message,
+ status,
+ innerErrorCode,
+ }: {
+ message: string;
+ status: number;
+ innerErrorCode: string | undefined;
+ }) {
super(message);
this.name = 'GraphRequestError';
this.status = status;
+ this.innerErrorCode = innerErrorCode;
}
}
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/transcript-entry.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/transcript-entry.type.ts
new file mode 100644
index 00000000000..a5537555f4c
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/transcript-entry.type.ts
@@ -0,0 +1,7 @@
+export type TranscriptEntry = {
+ participant: { name: string | null };
+ words: Array<{
+ text: string;
+ start_timestamp: { relative: number };
+ }>;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/build-teams-call-recording-sync-fields.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/build-teams-call-recording-sync-fields.test.ts
new file mode 100644
index 00000000000..2fb133ee8b7
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/build-teams-call-recording-sync-fields.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildTeamsCallRecordingSyncFields } from 'src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields';
+
+const TRANSCRIPT_ENTRY = {
+ participant: { name: 'Alice Martin' },
+ words: [{ text: 'Hello.', start_timestamp: { relative: 0 } }],
+};
+
+describe('buildTeamsCallRecordingSyncFields', () => {
+ it('should build a completed recording linked to its calendar event', () => {
+ expect(
+ buildTeamsCallRecordingSyncFields({
+ meeting: { subject: ' Weekly sync ' },
+ transcript: {
+ id: 'transcript-1',
+ createdDateTime: '2026-09-05T10:02:00Z',
+ endDateTime: '2026-09-05T10:31:00Z',
+ },
+ transcriptEntries: [TRANSCRIPT_ENTRY],
+ calendarEventId: 'event-1',
+ }),
+ ).toEqual({
+ title: 'Weekly sync',
+ status: 'COMPLETED',
+ externalRecordingId: 'transcript-1',
+ startedAt: '2026-09-05T10:02:00Z',
+ endedAt: '2026-09-05T10:31:00Z',
+ transcript: [TRANSCRIPT_ENTRY],
+ calendarEventId: 'event-1',
+ });
+ });
+
+ it('should keep an empty transcript processing and leave missing values unset', () => {
+ expect(
+ buildTeamsCallRecordingSyncFields({
+ meeting: { subject: ' ' },
+ transcript: { id: 'transcript-1' },
+ transcriptEntries: [],
+ }),
+ ).toEqual({
+ status: 'PROCESSING',
+ externalRecordingId: 'transcript-1',
+ });
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/compute-call-recording-id-for-teams-transcript.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/compute-call-recording-id-for-teams-transcript.test.ts
new file mode 100644
index 00000000000..d8f75f8cee6
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/compute-call-recording-id-for-teams-transcript.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';
+
+describe('computeCallRecordingIdForTeamsTranscript', () => {
+ it('should derive one stable UUID v4 per Graph transcript id', () => {
+ const transcriptId =
+ 'MSMjMCMjNzU3ODc2ZDYtOTcwMi00MDhkLWFkNDItOTE2ZDNmZjkwZGY4';
+ const callRecordingId =
+ computeCallRecordingIdForTeamsTranscript(transcriptId);
+
+ expect(callRecordingId).toMatch(
+ /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,
+ );
+ expect(computeCallRecordingIdForTeamsTranscript(transcriptId)).toBe(
+ callRecordingId,
+ );
+ expect(
+ computeCallRecordingIdForTeamsTranscript('MSMjMCMjYW5vdGhlcg=='),
+ ).not.toBe(callRecordingId);
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.ts
new file mode 100644
index 00000000000..2ad936de7a0
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.ts
@@ -0,0 +1,93 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { describe, expect, it, vi } from 'vitest';
+
+import { findMatchingCalendarEventOrThrow } from 'src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw';
+
+const JOIN_WEB_URL =
+ 'https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0';
+
+const buildCoreApiClient = (
+ calendarEventIds: string[],
+): Pick<CoreApiClient, 'query'> => ({
+ query: vi.fn().mockResolvedValue({
+ calendarEvents: {
+ edges: calendarEventIds.map((id) => ({ node: { id } })),
+ },
+ }),
+});
+
+describe('findMatchingCalendarEventOrThrow', () => {
+ it('should link the calendar event with the join URL around the transcript start', async () => {
+ const coreApiClient = buildCoreApiClient(['event-1']);
+
+ await expect(
+ findMatchingCalendarEventOrThrow({
+ coreApiClient,
+ meeting: { joinWebUrl: JOIN_WEB_URL },
+ transcript: { createdDateTime: '2026-09-05T10:02:00Z' },
+ }),
+ ).resolves.toBe('event-1');
+ expect(coreApiClient.query).toHaveBeenCalledWith({
+ calendarEvents: expect.objectContaining({
+ __args: expect.objectContaining({
+ filter: {
+ and: [
+ { conferenceLink: { primaryLinkUrl: { eq: JOIN_WEB_URL } } },
+ { startsAt: { lte: '2026-09-05T10:17:00.000Z' } },
+ { endsAt: { gte: '2026-09-05T09:47:00.000Z' } },
+ { isCanceled: { eq: false } },
+ ],
+ },
+ }),
+ }),
+ });
+ });
+
+ it.each([
+ ['no', []],
+ ['several', ['event-1', 'event-2']],
+ ])(
+ 'should not link when %s calendar events match',
+ async (_, calendarEventIds) => {
+ await expect(
+ findMatchingCalendarEventOrThrow({
+ coreApiClient: buildCoreApiClient(calendarEventIds),
+ meeting: { joinWebUrl: JOIN_WEB_URL },
+ transcript: { createdDateTime: '2026-09-05T10:02:00Z' },
+ }),
+ ).resolves.toBeUndefined();
+ },
+ );
+
+ it.each([
+ [
+ 'join URL',
+ { joinWebUrl: null },
+ { createdDateTime: '2026-09-05T10:02:00Z' },
+ ],
+ [
+ 'transcript start',
+ { joinWebUrl: JOIN_WEB_URL },
+ { createdDateTime: null },
+ ],
+ [
+ 'valid transcript start',
+ { joinWebUrl: JOIN_WEB_URL },
+ { createdDateTime: 'soon' },
+ ],
+ ])(
+ 'should not query calendar events without a %s',
+ async (_, meeting, transcript) => {
+ const coreApiClient = buildCoreApiClient(['event-1']);
+
+ await expect(
+ findMatchingCalendarEventOrThrow({
+ coreApiClient,
+ meeting,
+ transcript,
+ }),
+ ).resolves.toBeUndefined();
+ expect(coreApiClient.query).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/map-teams-transcript-to-entries.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/map-teams-transcript-to-entries.test.ts
new file mode 100644
index 00000000000..800d1491918
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/map-teams-transcript-to-entries.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+
+import { mapTeamsTranscriptToEntries } from 'src/features/transcripts/logic-functions/utils/map-teams-transcript-to-entries';
+
+describe('mapTeamsTranscriptToEntries', () => {
+ it('should merge consecutive cues from the same speaker into one entry', () => {
+ const content = [
+ 'WEBVTT',
+ '',
+ '0f6b1c1e-6c8a-4f5e-9b3a-2d7f0e1a9c4b/17-0',
+ '00:00:06.360 --> 00:00:09.840',
+ "<v Alice Martin>So today we're going to go through the</v>",
+ '',
+ '0f6b1c1e-6c8a-4f5e-9b3a-2d7f0e1a9c4b/17-1',
+ '00:00:09.840 --> 00:00:12.200',
+ '<v Alice Martin>plan for the next quarter.</v>',
+ '',
+ '0f6b1c1e-6c8a-4f5e-9b3a-2d7f0e1a9c4b/21-0',
+ '00:01:02.500 --> 00:01:04.000',
+ '<v Bob Chen>Sounds good.</v>',
+ '',
+ '0f6b1c1e-6c8a-4f5e-9b3a-2d7f0e1a9c4b/24-0',
+ '01:00:03.000 --> 01:00:05.000',
+ '<v Alice Martin>Thanks, everyone.</v>',
+ '',
+ ].join('\n');
+
+ expect(mapTeamsTranscriptToEntries(content)).toEqual([
+ {
+ participant: { name: 'Alice Martin' },
+ words: [
+ {
+ text: "So today we're going to go through the",
+ start_timestamp: { relative: 6.36 },
+ },
+ {
+ text: 'plan for the next quarter.',
+ start_timestamp: { relative: 9.84 },
+ },
+ ],
+ },
+ {
+ participant: { name: 'Bob Chen' },
+ words: [{ text: 'Sounds good.', start_timestamp: { relative: 62.5 } }],
+ },
+ {
+ participant: { name: 'Alice Martin' },
+ words: [
+ { text: 'Thanks, everyone.', start_timestamp: { relative: 3603 } },
+ ],
+ },
+ ]);
+ });
+
+ it('should keep one entry per cue when the transcript has no speaker attribution', () => {
+ const content = [
+ '00:00:01.500 --> 00:00:04.000 ',
+ '',
+ 'Hello, thanks for joining. ',
+ '',
+ '00:00:04.000 --> 00:00:07.200 ',
+ '',
+ 'Glad to be here. ',
+ '',
+ ].join('\r\n');
+
+ expect(mapTeamsTranscriptToEntries(content)).toEqual([
+ {
+ participant: { name: null },
+ words: [
+ {
+ text: 'Hello, thanks for joining.',
+ start_timestamp: { relative: 1.5 },
+ },
+ ],
+ },
+ {
+ participant: { name: null },
+ words: [{ text: 'Glad to be here.', start_timestamp: { relative: 4 } }],
+ },
+ ]);
+ });
+
+ it('should start speech captured before the transcription began at zero', () => {
+ const content = [
+ 'WEBVTT',
+ '',
+ '-00:00:02.000 --> 00:00:01.000',
+ '<v Alice Martin>We can start.</v>',
+ ].join('\n');
+
+ expect(mapTeamsTranscriptToEntries(content)).toEqual([
+ {
+ participant: { name: 'Alice Martin' },
+ words: [{ text: 'We can start.', start_timestamp: { relative: 0 } }],
+ },
+ ]);
+ });
+
+ it('should decode entities and skip notes and cues without words', () => {
+ const content = [
+ 'WEBVTT',
+ '',
+ 'NOTE Generated by Microsoft Teams',
+ '',
+ '00:00:01.000 --> 00:00:02.000',
+ '<v Alice Martin>R&amp;D &lt;3 the &quot;new&quot; plan</v>',
+ '',
+ '00:00:02.000 --> 00:00:03.000',
+ '<v Bob Chen></v>',
+ ].join('\n');
+
+ expect(mapTeamsTranscriptToEntries(content)).toEqual([
+ {
+ participant: { name: 'Alice Martin' },
+ words: [
+ {
+ text: 'R&D <3 the "new" plan',
+ start_timestamp: { relative: 1 },
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('should return no entries when Microsoft has no cues yet', () => {
+ expect(mapTeamsTranscriptToEntries('WEBVTT\n\n')).toEqual([]);
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields.ts
new file mode 100644
index 00000000000..3dfca53ae07
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields.ts
@@ -0,0 +1,37 @@
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-functions/types/call-recording-sync-fields.type';
+import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';
+import { type GraphOnlineMeeting } from 'src/features/transcripts/logic-functions/types/graph-online-meeting.type';
+import { type TranscriptEntry } from 'src/features/transcripts/logic-functions/types/transcript-entry.type';
+
+export const buildTeamsCallRecordingSyncFields = ({
+ meeting,
+ transcript,
+ transcriptEntries,
+ calendarEventId,
+}: {
+ meeting: Pick<GraphOnlineMeeting, 'subject'>;
+ transcript: GraphCallTranscript;
+ transcriptEntries: TranscriptEntry[];
+ calendarEventId?: string;
+}): CallRecordingSyncFields => {
+ const title = meeting.subject?.trim();
+
+ return {
+ ...(isNonEmptyString(title) ? { title } : {}),
+ status: isNonEmptyArray(transcriptEntries) ? 'COMPLETED' : 'PROCESSING',
+ externalRecordingId: transcript.id,
+ ...(isNonEmptyString(transcript.createdDateTime)
+ ? { startedAt: transcript.createdDateTime }
+ : {}),
+ ...(isNonEmptyString(transcript.endDateTime)
+ ? { endedAt: transcript.endDateTime }
+ : {}),
+ ...(isNonEmptyArray(transcriptEntries)
+ ? { transcript: transcriptEntries }
+ : {}),
+ ...(isDefined(calendarEventId) ? { calendarEventId } : {}),
+ };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript.ts
new file mode 100644
index 00000000000..2f8340055c4
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript.ts
@@ -0,0 +1,16 @@
+import { createHash } from 'crypto';
+
+export const computeCallRecordingIdForTeamsTranscript = (
+ transcriptId: string,
+): string => {
+ const bytes = createHash('sha256')
+ .update(`teams-transcript:${transcriptId}`)
+ .digest();
+
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
+
+ const hexadecimalValue = bytes.subarray(0, 16).toString('hex');
+
+ return `${hexadecimalValue.slice(0, 8)}-${hexadecimalValue.slice(8, 12)}-${hexadecimalValue.slice(12, 16)}-${hexadecimalValue.slice(16, 20)}-${hexadecimalValue.slice(20)}`;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/download-meeting-transcript-content.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/download-meeting-transcript-content.ts
new file mode 100644
index 00000000000..c8c88a7c623
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/download-meeting-transcript-content.ts
@@ -0,0 +1,38 @@
+import { GRAPH_ATTRIBUTED_TRANSCRIPT_FORMAT } from 'src/features/transcripts/logic-functions/constants/graph-attributed-transcript-format';
+import { GRAPH_SPEAKER_ATTRIBUTION_NOT_ALLOWED_ERROR_CODE } from 'src/features/transcripts/logic-functions/constants/graph-speaker-attribution-not-allowed-error-code';
+import { GRAPH_UNATTRIBUTED_TRANSCRIPT_FORMAT } from 'src/features/transcripts/logic-functions/constants/graph-unattributed-transcript-format';
+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';
+import { fetchGraphText } from 'src/features/transcripts/logic-functions/utils/fetch-graph-text';
+
+export const downloadMeetingTranscriptContent = async ({
+ accessToken,
+ meetingId,
+ transcriptId,
+}: {
+ accessToken: string;
+ meetingId: string;
+ transcriptId: string;
+}): Promise<string> => {
+ const transcriptContentUrl = `me/onlineMeetings/${encodeURIComponent(meetingId)}/transcripts/${encodeURIComponent(transcriptId)}/content`;
+
+ try {
+ return await fetchGraphText({
+ accessToken,
+ url: transcriptContentUrl,
+ accept: GRAPH_ATTRIBUTED_TRANSCRIPT_FORMAT,
+ });
+ } catch (error) {
+ if (
+ !(error instanceof GraphRequestError) ||
+ error.innerErrorCode !== GRAPH_SPEAKER_ATTRIBUTION_NOT_ALLOWED_ERROR_CODE
+ ) {
+ throw error;
+ }
+
+ return fetchGraphText({
+ accessToken,
+ url: transcriptContentUrl,
+ accept: GRAPH_UNATTRIBUTED_TRANSCRIPT_FORMAT,
+ });
+ }
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts
index 9f1152edfee..6c7989d6945 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts
@@ -1,66 +1,4 @@
-import { isNonEmptyString } from '@sniptt/guards';
-
-import { GRAPH_REQUEST_MAX_ATTEMPTS } from 'src/features/transcripts/logic-functions/constants/graph-request-max-attempts';
-import { GRAPH_REQUEST_RETRY_BASE_DELAY_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/graph-request-retry-base-delay-milliseconds';
-import { GRAPH_RETRYABLE_STATUSES } from 'src/features/transcripts/logic-functions/constants/graph-retryable-statuses';
-import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';
-import { resolveGraphUrlOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-graph-url-or-throw';
-import { sleepForMilliseconds } from 'src/features/transcripts/logic-functions/utils/sleep-for-milliseconds';
-
-type GraphErrorBody = {
- error?: {
- message?: unknown;
- innerError?: { code?: unknown } | null;
- };
-};
-
-const fetchGraphResponse = async ({
- accessToken,
- url,
- attempt,
-}: {
- accessToken: string;
- url: string;
- attempt: number;
-}): Promise<Response> => {
- const response = await fetch(url, {
- redirect: 'error',
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: 'application/json',
- },
- });
-
- if (response.ok) {
- return response;
- }
-
- if (
- GRAPH_RETRYABLE_STATUSES.has(response.status) &&
- attempt + 1 < GRAPH_REQUEST_MAX_ATTEMPTS
- ) {
- const retryAfterSeconds = Number(response.headers.get('Retry-After'));
-
- await sleepForMilliseconds(
- retryAfterSeconds > 0
- ? retryAfterSeconds * 1_000
- : GRAPH_REQUEST_RETRY_BASE_DELAY_MILLISECONDS * 2 ** attempt,
- );
-
- return fetchGraphResponse({ accessToken, url, attempt: attempt + 1 });
- }
-
- const body: GraphErrorBody = await response.json().catch(() => ({}));
- const innerErrorCode = body.error?.innerError?.code;
- const message = isNonEmptyString(body.error?.message)
- ? body.error.message
- : response.statusText;
-
- throw new GraphRequestError({
- message: `Microsoft Graph request failed (${response.status}${isNonEmptyString(innerErrorCode) ? ` ${innerErrorCode}` : ''}): ${message}`,
- status: response.status,
- });
-};
+import { fetchGraphResponse } from 'src/features/transcripts/logic-functions/utils/fetch-graph-response';
export const fetchGraphJson = async <TResponse>({
accessToken,
@@ -71,8 +9,8 @@ export const fetchGraphJson = async <TResponse>({
}): Promise<TResponse> => {
const response = await fetchGraphResponse({
accessToken,
- url: resolveGraphUrlOrThrow(url),
- attempt: 0,
+ url,
+ accept: 'application/json',
});
const body: TResponse = await response.json();
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-response.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-response.ts
new file mode 100644
index 00000000000..56e15113ae9
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-response.ts
@@ -0,0 +1,89 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { GRAPH_REQUEST_MAX_ATTEMPTS } from 'src/features/transcripts/logic-functions/constants/graph-request-max-attempts';
+import { GRAPH_REQUEST_RETRY_BASE_DELAY_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/graph-request-retry-base-delay-milliseconds';
+import { GRAPH_RETRYABLE_STATUSES } from 'src/features/transcripts/logic-functions/constants/graph-retryable-statuses';
+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';
+import { resolveGraphUrlOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-graph-url-or-throw';
+import { sleepForMilliseconds } from 'src/features/transcripts/logic-functions/utils/sleep-for-milliseconds';
+
+type GraphErrorBody = {
+ error?: {
+ message?: unknown;
+ innerError?: { code?: unknown } | null;
+ };
+};
+
+const fetchGraphResponseWithRetries = async ({
+ accessToken,
+ url,
+ accept,
+ attempt,
+}: {
+ accessToken: string;
+ url: string;
+ accept: string;
+ attempt: number;
+}): Promise<Response> => {
+ const response = await fetch(url, {
+ redirect: 'error',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ Accept: accept,
+ },
+ });
+
+ if (response.ok) {
+ return response;
+ }
+
+ if (
+ GRAPH_RETRYABLE_STATUSES.has(response.status) &&
+ attempt + 1 < GRAPH_REQUEST_MAX_ATTEMPTS
+ ) {
+ const retryAfterSeconds = Number(response.headers.get('Retry-After'));
+
+ await sleepForMilliseconds(
+ retryAfterSeconds > 0
+ ? retryAfterSeconds * 1_000
+ : GRAPH_REQUEST_RETRY_BASE_DELAY_MILLISECONDS * 2 ** attempt,
+ );
+
+ return fetchGraphResponseWithRetries({
+ accessToken,
+ url,
+ accept,
+ attempt: attempt + 1,
+ });
+ }
+
+ const body: GraphErrorBody = await response.json().catch(() => ({}));
+ const innerErrorCode = isNonEmptyString(body.error?.innerError?.code)
+ ? body.error.innerError.code
+ : undefined;
+ const message = isNonEmptyString(body.error?.message)
+ ? body.error.message
+ : response.statusText;
+
+ throw new GraphRequestError({
+ message: `Microsoft Graph request failed (${response.status}${isNonEmptyString(innerErrorCode) ? ` ${innerErrorCode}` : ''}): ${message}`,
+ status: response.status,
+ innerErrorCode,
+ });
+};
+
+export const fetchGraphResponse = ({
+ accessToken,
+ url,
+ accept,
+}: {
+ accessToken: string;
+ url: string;
+ accept: string;
+}): Promise<Response> =>
+ fetchGraphResponseWithRetries({
+ accessToken,
+ url: resolveGraphUrlOrThrow(url),
+ accept,
+ attempt: 0,
+ });
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-text.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-text.ts
new file mode 100644
index 00000000000..b75597e9a55
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-text.ts
@@ -0,0 +1,15 @@
+import { fetchGraphResponse } from 'src/features/transcripts/logic-functions/utils/fetch-graph-response';
+
+export const fetchGraphText = async ({
+ accessToken,
+ url,
+ accept,
+}: {
+ accessToken: string;
+ url: string;
+ accept: string;
+}): Promise<string> => {
+ const response = await fetchGraphResponse({ accessToken, url, accept });
+
+ return response.text();
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-teams-transcript-data.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-teams-transcript-data.ts
new file mode 100644
index 00000000000..c3fd661c9db
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-teams-transcript-data.ts
@@ -0,0 +1,27 @@
+import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';
+import { type GraphOnlineMeeting } from 'src/features/transcripts/logic-functions/types/graph-online-meeting.type';
+import { downloadMeetingTranscriptContent } from 'src/features/transcripts/logic-functions/utils/download-meeting-transcript-content';
+import { getMeetingById } from 'src/features/transcripts/logic-functions/utils/get-meeting-by-id';
+import { getMeetingTranscript } from 'src/features/transcripts/logic-functions/utils/get-meeting-transcript';
+
+export const fetchTeamsTranscriptData = async ({
+ accessToken,
+ meetingId,
+ transcriptId,
+}: {
+ accessToken: string;
+ meetingId: string;
+ transcriptId: string;
+}): Promise<{
+ meeting: GraphOnlineMeeting;
+ transcript: GraphCallTranscript;
+ transcriptContent: string;
+}> => {
+ const [meeting, transcript, transcriptContent] = await Promise.all([
+ getMeetingById({ accessToken, meetingId }),
+ getMeetingTranscript({ accessToken, meetingId, transcriptId }),
+ downloadMeetingTranscriptContent({ accessToken, meetingId, transcriptId }),
+ ]);
+
+ return { meeting, transcript, transcriptContent };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw.ts
new file mode 100644
index 00000000000..ab05e864bcf
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw.ts
@@ -0,0 +1,72 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { TEAMS_OCCURRENCE_MARGIN_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-occurrence-margin-milliseconds';
+import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';
+import { type GraphOnlineMeeting } from 'src/features/transcripts/logic-functions/types/graph-online-meeting.type';
+
+type CalendarEventMatches = {
+ edges: { node: { id: string } }[];
+};
+
+export const findMatchingCalendarEventOrThrow = async ({
+ coreApiClient,
+ meeting,
+ transcript,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query'>;
+ meeting: Pick<GraphOnlineMeeting, 'joinWebUrl'>;
+ transcript: Pick<GraphCallTranscript, 'createdDateTime'>;
+}): Promise<string | undefined> => {
+ if (
+ !isNonEmptyString(meeting.joinWebUrl) ||
+ !isNonEmptyString(transcript.createdDateTime)
+ ) {
+ return undefined;
+ }
+
+ const transcriptStartMilliseconds = Date.parse(transcript.createdDateTime);
+
+ if (!Number.isFinite(transcriptStartMilliseconds)) {
+ return undefined;
+ }
+
+ // Every occurrence of a recurring meeting shares one join URL, so the
+ // transcript start picks the occurrence, with the same margin as listing.
+ const result = await coreApiClient.query({
+ calendarEvents: {
+ __args: {
+ filter: {
+ and: [
+ { conferenceLink: { primaryLinkUrl: { eq: meeting.joinWebUrl } } },
+ {
+ startsAt: {
+ lte: new Date(
+ transcriptStartMilliseconds +
+ TEAMS_OCCURRENCE_MARGIN_MILLISECONDS,
+ ).toISOString(),
+ },
+ },
+ {
+ endsAt: {
+ gte: new Date(
+ transcriptStartMilliseconds -
+ TEAMS_OCCURRENCE_MARGIN_MILLISECONDS,
+ ).toISOString(),
+ },
+ },
+ { isCanceled: { eq: false } },
+ ],
+ },
+ first: 2,
+ },
+ edges: { node: { id: true } },
+ },
+ });
+ const calendarEvents: CalendarEventMatches | undefined =
+ result.calendarEvents;
+
+ return calendarEvents?.edges.length === 1
+ ? calendarEvents.edges[0].node.id
+ : undefined;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-meeting-by-id.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-meeting-by-id.ts
new file mode 100644
index 00000000000..a8dde2abb15
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-meeting-by-id.ts
@@ -0,0 +1,14 @@
+import { type GraphOnlineMeeting } from 'src/features/transcripts/logic-functions/types/graph-online-meeting.type';
+import { fetchGraphJson } from 'src/features/transcripts/logic-functions/utils/fetch-graph-json';
+
+export const getMeetingById = ({
+ accessToken,
+ meetingId,
+}: {
+ accessToken: string;
+ meetingId: string;
+}): Promise<GraphOnlineMeeting> =>
+ fetchGraphJson<GraphOnlineMeeting>({
+ accessToken,
+ url: `me/onlineMeetings/${encodeURIComponent(meetingId)}`,
+ });
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-meeting-transcript.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-meeting-transcript.ts
new file mode 100644
index 00000000000..82cbf36ccc7
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-meeting-transcript.ts
@@ -0,0 +1,16 @@
+import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';
+import { fetchGraphJson } from 'src/features/transcripts/logic-functions/utils/fetch-graph-json';
+
+export const getMeetingTranscript = ({
+ accessToken,
+ meetingId,
+ transcriptId,
+}: {
+ accessToken: string;
+ meetingId: string;
+ transcriptId: string;
+}): Promise<GraphCallTranscript> =>
+ fetchGraphJson<GraphCallTranscript>({
+ accessToken,
+ url: `me/onlineMeetings/${encodeURIComponent(meetingId)}/transcripts/${encodeURIComponent(transcriptId)}`,
+ });
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/map-teams-transcript-to-entries.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/map-teams-transcript-to-entries.ts
new file mode 100644
index 00000000000..e0919ebf1ac
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/map-teams-transcript-to-entries.ts
@@ -0,0 +1,143 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type TranscriptEntry } from 'src/features/transcripts/logic-functions/types/transcript-entry.type';
+
+type TeamsTranscriptCue = {
+ startSeconds: number;
+ lines: string[];
+};
+
+type TeamsTranscriptUtterance = {
+ startSeconds: number;
+ speakerName: string | undefined;
+ text: string;
+};
+
+const isCueTimingLine = (line: string): boolean =>
+ /^-?(?:\d+:)?\d{1,2}:\d{2}[.,]\d{1,3}\s+-->\s+-?(?:\d+:)?\d{1,2}:\d{2}[.,]\d{1,3}/.test(
+ line.trim(),
+ );
+
+const isMetadataBlock = (block: string[]): boolean =>
+ /^(WEBVTT|NOTE|STYLE|REGION)\b/.test(block[0].trim());
+
+const parseCueStartSeconds = (timingLine: string): number => {
+ const [startTimestamp] = timingLine.trim().split(/\s+-->/);
+
+ if (startTimestamp.startsWith('-')) {
+ return 0;
+ }
+
+ const [seconds, minutes, hours = 0] = startTimestamp
+ .replace(',', '.')
+ .split(':')
+ .map(Number)
+ .reverse();
+
+ return hours * 3_600 + minutes * 60 + seconds;
+};
+
+const splitIntoBlocks = (content: string): string[][] => {
+ const blocks: string[][] = [[]];
+
+ for (const line of content.replace(/^/, '').split(/\r?\n/)) {
+ if (isNonEmptyString(line.trim())) {
+ blocks[blocks.length - 1].push(line);
+ } else {
+ blocks.push([]);
+ }
+ }
+
+ return blocks.filter((block) => block.length > 0);
+};
+
+const groupBlocksIntoCues = (blocks: string[][]): TeamsTranscriptCue[] => {
+ const cues: TeamsTranscriptCue[] = [];
+
+ for (const block of blocks) {
+ const timingLineIndex = block.findIndex(isCueTimingLine);
+ const lastCue = cues[cues.length - 1];
+
+ if (timingLineIndex !== -1) {
+ cues.push({
+ startSeconds: parseCueStartSeconds(block[timingLineIndex]),
+ lines: block.slice(timingLineIndex + 1),
+ });
+ } else if (!isMetadataBlock(block) && isDefined(lastCue)) {
+ lastCue.lines.push(...block);
+ }
+ }
+
+ return cues;
+};
+
+// Repeats until stable so that removing one tag cannot leave another behind.
+const stripCueTags = (cueText: string): string => {
+ let text = cueText;
+ let previousText: string | undefined;
+
+ while (text !== previousText) {
+ previousText = text;
+ text = text.replace(/<\/?[^>]+>/g, '');
+ }
+
+ return text;
+};
+
+const decodeHtmlEntities = (text: string): string =>
+ text
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;/g, "'")
+ .replace(/&nbsp;/g, ' ')
+ .replace(/&amp;/g, '&');
+
+const toUtterance = ({
+ startSeconds,
+ lines,
+}: TeamsTranscriptCue): TeamsTranscriptUtterance | undefined => {
+ const cueText = lines.join(' ');
+ const speakerName = decodeHtmlEntities(
+ /<v(?:\.[^\s>]*)?\s+([^>]*)>/i.exec(cueText)?.[1] ?? '',
+ ).trim();
+ const text = decodeHtmlEntities(stripCueTags(cueText))
+ .replace(/\s+/g, ' ')
+ .trim();
+
+ if (!isNonEmptyString(text)) {
+ return undefined;
+ }
+
+ return {
+ startSeconds,
+ speakerName: isNonEmptyString(speakerName) ? speakerName : undefined,
+ text,
+ };
+};
+
+export const mapTeamsTranscriptToEntries = (
+ content: string,
+): TranscriptEntry[] => {
+ const entries: TranscriptEntry[] = [];
+ const utterances = groupBlocksIntoCues(splitIntoBlocks(content))
+ .map(toUtterance)
+ .filter(isDefined);
+
+ for (const { startSeconds, speakerName, text } of utterances) {
+ const lastEntry = entries[entries.length - 1];
+ const word = { text, start_timestamp: { relative: startSeconds } };
+
+ if (isDefined(speakerName) && lastEntry?.participant.name === speakerName) {
+ lastEntry.words.push(word);
+ } else {
+ entries.push({
+ participant: { name: speakerName ?? null },
+ words: [word],
+ });
+ }
+ }
+
+ return entries;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts
new file mode 100644
index 00000000000..66c9cf131dd
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts
@@ -0,0 +1,50 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { buildTeamsCallRecordingSyncFields } from 'src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields';
+import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';
+import { fetchTeamsTranscriptData } from 'src/features/transcripts/logic-functions/utils/fetch-teams-transcript-data';
+import { findMatchingCalendarEventOrThrow } from 'src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw';
+import { mapTeamsTranscriptToEntries } from 'src/features/transcripts/logic-functions/utils/map-teams-transcript-to-entries';
+import { upsertCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw';
+
+export const syncTeamsTranscriptToCallRecordingOrThrow = async ({
+ accessToken,
+ coreApiClient,
+ meetingId,
+ transcriptId,
+}: {
+ accessToken: string;
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ meetingId: string;
+ transcriptId: string;
+}): Promise<{
+ callRecordingId: string;
+ calendarEventId?: string;
+ created: boolean;
+ skipped: boolean;
+}> => {
+ const { meeting, transcript, transcriptContent } =
+ await fetchTeamsTranscriptData({ accessToken, meetingId, transcriptId });
+ const transcriptEntries = mapTeamsTranscriptToEntries(transcriptContent);
+ const callRecordingId = computeCallRecordingIdForTeamsTranscript(
+ transcript.id,
+ );
+ const calendarEventId = await findMatchingCalendarEventOrThrow({
+ coreApiClient,
+ meeting,
+ transcript,
+ });
+ const fields = buildTeamsCallRecordingSyncFields({
+ meeting,
+ transcript,
+ transcriptEntries,
+ calendarEventId,
+ });
+ const result = await upsertCallRecordingOrThrow({
+ coreApiClient,
+ callRecordingId,
+ fields,
+ });
+
+ return { callRecordingId, calendarEventId, ...result };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw.ts
new file mode 100644
index 00000000000..ac34cafd419
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw.ts
@@ -0,0 +1,130 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-functions/types/call-recording-sync-fields.type';
+
+const doesCallRecordingMatchOrThrow = async ({
+ coreApiClient,
+ filter,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query'>;
+ filter: {
+ id: { eq: string };
+ deletedAt?: { is: 'NOT_NULL' };
+ };
+}): Promise<boolean> => {
+ const queryResult = await coreApiClient.query({
+ callRecordings: {
+ __args: { filter, first: 1 },
+ edges: { node: { id: true } },
+ },
+ });
+
+ return isDefined(queryResult.callRecordings?.edges?.[0]?.node);
+};
+
+const toCallRecordingData = ({
+ transcript,
+ ...fields
+}: CallRecordingSyncFields) =>
+ isDefined(transcript)
+ ? {
+ ...fields,
+ transcript: transcript as unknown as Record<string, unknown>,
+ }
+ : fields;
+
+const updateCallRecordingOrThrow = async ({
+ coreApiClient,
+ callRecordingId,
+ fields,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'mutation'>;
+ callRecordingId: string;
+ fields: CallRecordingSyncFields;
+}): Promise<void> => {
+ await coreApiClient.mutation({
+ updateCallRecording: {
+ __args: { id: callRecordingId, data: toCallRecordingData(fields) },
+ id: true,
+ },
+ });
+};
+
+const createCallRecordingOrThrow = async ({
+ coreApiClient,
+ callRecordingId,
+ fields,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'mutation'>;
+ callRecordingId: string;
+ fields: CallRecordingSyncFields;
+}): Promise<void> => {
+ await coreApiClient.mutation({
+ createCallRecording: {
+ __args: { data: { id: callRecordingId, ...toCallRecordingData(fields) } },
+ id: true,
+ },
+ });
+};
+
+export const upsertCallRecordingOrThrow = async ({
+ coreApiClient,
+ callRecordingId,
+ fields,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ callRecordingId: string;
+ fields: CallRecordingSyncFields;
+}): Promise<{ created: boolean; skipped: boolean }> => {
+ if (
+ await doesCallRecordingMatchOrThrow({
+ coreApiClient,
+ filter: { id: { eq: callRecordingId }, deletedAt: { is: 'NOT_NULL' } },
+ })
+ ) {
+ return { created: false, skipped: true };
+ }
+
+ if (
+ await doesCallRecordingMatchOrThrow({
+ coreApiClient,
+ filter: { id: { eq: callRecordingId } },
+ })
+ ) {
+ await updateCallRecordingOrThrow({
+ coreApiClient,
+ callRecordingId,
+ fields,
+ });
+
+ return { created: false, skipped: false };
+ }
+
+ try {
+ await createCallRecordingOrThrow({
+ coreApiClient,
+ callRecordingId,
+ fields,
+ });
+
+ return { created: true, skipped: false };
+ } catch (error) {
+ if (
+ !(await doesCallRecordingMatchOrThrow({
+ coreApiClient,
+ filter: { id: { eq: callRecordingId } },
+ }))
+ ) {
+ throw error;
+ }
+
+ await updateCallRecordingOrThrow({
+ coreApiClient,
+ callRecordingId,
+ fields,
+ });
+
+ return { created: false, skipped: false };
+ }
+};
diff --git a/packages/twenty-apps/public/teams/src/roles/default-function.role.ts b/packages/twenty-apps/public/teams/src/roles/default-function.role.ts
index 91ccc964d45..5b2c3e428a0 100644
--- a/packages/twenty-apps/public/teams/src/roles/default-function.role.ts
+++ b/packages/twenty-apps/public/teams/src/roles/default-function.role.ts
@@ -1,4 +1,7 @@
-import { defineApplicationRole } from 'twenty-sdk/define';
+import {
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
+ defineApplicationRole,
+} from 'twenty-sdk/define';
import { DEFAULT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
@@ -6,7 +9,7 @@ export default defineApplicationRole({
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
label: 'Twenty Microsoft Teams tools role',
description:
- 'No CRM data access — tools only forward requests to Microsoft Teams using the configured bot credentials.',
+ 'Reads calendar events to match Teams meetings and writes imported transcripts to Call Recordings. Chat tools only forward requests to Microsoft Teams using the configured bot credentials.',
canReadAllObjectRecords: false,
canUpdateAllObjectRecords: false,
canSoftDeleteAllObjectRecords: false,
@@ -15,7 +18,24 @@ export default defineApplicationRole({
canBeAssignedToAgents: false,
canBeAssignedToUsers: false,
canBeAssignedToApiKeys: false,
- objectPermissions: [],
+ objectPermissions: [
+ {
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.calendarEvent.universalIdentifier,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ },
+ {
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.callRecording.universalIdentifier,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ },
+ ],
fieldPermissions: [],
permissionFlagUniversalIdentifiers: [],
});