The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Granola 3/8: Map Granola notes into Call Recordings (#25572)
nitin21ac93d5d66b
diff --git a/packages/twenty-apps/public/granola/README.md b/packages/twenty-apps/public/granola/README.mdindex 6e75d729644..63677f3a192 100644--- a/packages/twenty-apps/public/granola/README.md+++ b/packages/twenty-apps/public/granola/README.md@@ -1,3 +1,7 @@# Granola for TwentyImplementation in progress. Sync meeting transcripts and shared summaries into Call Recordings, import history, and use notes in workflows and AI. Requires Granola Business or Enterprise and an API key. Private notes are excluded.++## Limitations++When a Granola note matches multiple calendar event copies, the recording is imported without a calendar link because the app cannot determine which copy belongs to the note's owner.diff --git a/packages/twenty-apps/public/granola/src/__tests__/utils/build-granola-transcript-item.util.ts b/packages/twenty-apps/public/granola/src/__tests__/utils/build-granola-transcript-item.util.tsnew file mode 100644index 00000000000..de8e8d0b325--- /dev/null+++ b/packages/twenty-apps/public/granola/src/__tests__/utils/build-granola-transcript-item.util.ts@@ -0,0 +1,11 @@+import { type GranolaTranscriptItem } from 'src/logic-functions/types/granola-api.type';++export const buildGranolaTranscriptItem = (+ overrides: Partial<GranolaTranscriptItem> = {},+): GranolaTranscriptItem => ({+ speaker: { source: 'microphone', attribution: 'me' },+ text: 'Hello',+ start_time: '2026-09-05T10:00:05Z',+ end_time: '2026-09-05T10:00:07Z',+ ...overrides,+});diff --git a/packages/twenty-apps/public/granola/src/constants/granola-transcript.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola-transcript.constant.tsnew file mode 100644index 00000000000..9d87b2bb8c4--- /dev/null+++ b/packages/twenty-apps/public/granola/src/constants/granola-transcript.constant.ts@@ -0,0 +1,5 @@+export const GRANOLA_TRANSCRIPT_MAX_PAGES = 1_000;+export const GRANOLA_TRANSCRIPT_PAGE_SIZE = 100;+export const GRANOLA_TRANSCRIPT_PAGE_INTERVAL_MILLISECONDS = 250;+export const GRANOLA_TRANSCRIPT_TIMEOUT_MILLISECONDS = 800_000;+export const GRANOLA_UNKNOWN_SPEAKER_LABEL = 'Participant';diff --git a/packages/twenty-apps/public/granola/src/default-role.ts b/packages/twenty-apps/public/granola/src/default-role.tsindex 976a4a075c5..3b2d6874a8c 100644--- a/packages/twenty-apps/public/granola/src/default-role.ts+++ b/packages/twenty-apps/public/granola/src/default-role.ts@@ -23,6 +23,15 @@ export default defineApplicationRole({canBeAssignedToUsers: false,canBeAssignedToApiKeys: false,objectPermissions: [+ {+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.calendarEventParticipant+ .universalIdentifier,+ canReadObjectRecords: true,+ canUpdateObjectRecords: false,+ canSoftDeleteObjectRecords: false,+ canDestroyObjectRecords: false,+ },{objectUniversalIdentifier:STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.calendarEvent.universalIdentifier,diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/call-recording-sync-fields.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/call-recording-sync-fields.type.tsnew file mode 100644index 00000000000..1fa479646eb--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/call-recording-sync-fields.type.ts@@ -0,0 +1,13 @@+import { type TranscriptEntry } from 'src/logic-functions/types/transcript-entry.type';++export type CallRecordingSyncFields = {+ title?: string;+ status?: 'PROCESSING' | 'COMPLETED';+ recordingRequestStatus?: 'REQUESTED';+ externalRecordingId?: string;+ startedAt?: string;+ endedAt?: string;+ transcript?: TranscriptEntry[];+ summary?: { markdown: string; blocknote: null };+ calendarEventId?: string;+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-transcript-limit-error.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-transcript-limit-error.tsnew file mode 100644index 00000000000..081249d5a3e--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-transcript-limit-error.ts@@ -0,0 +1,33 @@+import {+ GRANOLA_TRANSCRIPT_MAX_PAGES,+ GRANOLA_TRANSCRIPT_TIMEOUT_MILLISECONDS,+} from 'src/constants/granola-transcript.constant';++type GranolaTranscriptLimitErrorOptions =+ | { reason: 'page-limit' | 'time-limit' }+ | {+ reason: 'non-advancing-cursor';+ noteId: string;+ cursor: string | null;+ };++export class GranolaTranscriptLimitError extends Error {+ constructor(options: GranolaTranscriptLimitErrorOptions) {+ super(GranolaTranscriptLimitError.getMessage(options));+ this.name = 'GranolaTranscriptLimitError';+ }++ private static getMessage(+ options: GranolaTranscriptLimitErrorOptions,+ ): string {+ if (options.reason === 'non-advancing-cursor') {+ return `Granola transcript pagination did not advance for note ${options.noteId} at cursor ${options.cursor ?? 'none'}.`;+ }++ if (options.reason === 'page-limit') {+ return `Granola transcript exceeded the ${GRANOLA_TRANSCRIPT_MAX_PAGES.toLocaleString('en-US')}-page import limit.`;+ }++ return `Granola transcript exceeded the ${GRANOLA_TRANSCRIPT_TIMEOUT_MILLISECONDS / 1_000}-second import limit.`;+ }+}diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/transcript-entry.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/transcript-entry.type.tsnew file mode 100644index 00000000000..73bdeba7718--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/transcript-entry.type.ts@@ -0,0 +1,7 @@+export type TranscriptEntry = {+ participant: { name: string };+ words: Array<{+ text: string;+ start_timestamp: { relative: number };+ }>;+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/compute-call-recording-id-for-granola-note.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/compute-call-recording-id-for-granola-note.test.tsnew file mode 100644index 00000000000..a43d4f5f11d--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/compute-call-recording-id-for-granola-note.test.ts@@ -0,0 +1,16 @@+import { expect, it } from 'vitest';++import { computeCallRecordingIdForGranolaNote } from 'src/logic-functions/utils/compute-call-recording-id-for-granola-note.util';++it('derives stable UUID v4 identities from the Granola namespace', () => {+ const noteId = 'not_1d3tmYTlCICgjy';+ const recordingId = computeCallRecordingIdForGranolaNote(noteId);++ expect(recordingId).toMatch(+ /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,+ );+ expect(computeCallRecordingIdForGranolaNote(noteId)).toBe(recordingId);+ expect(computeCallRecordingIdForGranolaNote('not_another')).not.toBe(+ recordingId,+ );+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/fetch-granola-note-with-transcript-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/fetch-granola-note-with-transcript-or-throw.test.tsnew file mode 100644index 00000000000..bdee18b9d15--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/fetch-granola-note-with-transcript-or-throw.test.ts@@ -0,0 +1,181 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { buildGranolaNote } from 'src/__tests__/utils/build-granola-note.util';+import { buildGranolaTranscriptItem } from 'src/__tests__/utils/build-granola-transcript-item.util';+import { GranolaTranscriptLimitError } from 'src/logic-functions/types/granola-transcript-limit-error';+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';+import { fetchGranolaNoteWithTranscriptOrThrow } from 'src/logic-functions/utils/fetch-granola-note-with-transcript-or-throw.util';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('fetchGranolaNoteWithTranscriptOrThrow', () => {+ it('stops a slow transcript before the worker exhausts its execution budget', async () => {+ vi.useFakeTimers();+ const mockedFetch = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(new Response(null, { status: 413 }))+ .mockResolvedValueOnce(Response.json(buildGranolaNote()))+ .mockImplementation(async () => {+ vi.setSystemTime(Date.now() + 800_000);+ return Response.json({ transcript: [], hasMore: true, cursor: 'next' });+ });+ vi.stubGlobal('fetch', mockedFetch);++ const pendingNote = fetchGranolaNoteWithTranscriptOrThrow({+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),+ noteId: 'not_1d3tmYTlCICgjy',+ });+ const rejection = expect(pendingNote).rejects.toBeInstanceOf(+ GranolaTranscriptLimitError,+ );+ await vi.advanceTimersByTimeAsync(250);+ await rejection;+ expect(mockedFetch).toHaveBeenCalledTimes(3);+ });++ it('retrieves a large transcript whose pacing exceeds one minute', async () => {+ vi.useFakeTimers();+ const transcriptItem = buildGranolaTranscriptItem();+ const mockedFetch = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(new Response(null, { status: 413 }))+ .mockResolvedValueOnce(Response.json(buildGranolaNote()))+ .mockImplementation(async (url) => {+ const pageIndex = Number(+ new URL(String(url)).searchParams.get('cursor') ?? 0,+ );+ return Response.json({+ transcript: [transcriptItem],+ hasMore: pageIndex < 241,+ cursor: pageIndex < 241 ? String(pageIndex + 1) : null,+ });+ });+ vi.stubGlobal('fetch', mockedFetch);++ const pendingNote = fetchGranolaNoteWithTranscriptOrThrow({+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),+ noteId: 'not_1d3tmYTlCICgjy',+ });+ await vi.advanceTimersByTimeAsync(60_000);+ expect(mockedFetch).toHaveBeenCalledTimes(243);+ await vi.advanceTimersByTimeAsync(250);+ const note = await pendingNote;+ expect(note.transcript).toHaveLength(242);+ });++ it('paces transcript pages below the sustained provider request limit', async () => {+ vi.useFakeTimers();+ const mockedFetch = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(new Response(null, { status: 413 }))+ .mockResolvedValueOnce(Response.json(buildGranolaNote()))+ .mockResolvedValueOnce(+ Response.json({ transcript: [], hasMore: true, cursor: 'next' }),+ )+ .mockResolvedValueOnce(+ Response.json({ transcript: [], hasMore: false, cursor: null }),+ );+ vi.stubGlobal('fetch', mockedFetch);++ const pendingNote = fetchGranolaNoteWithTranscriptOrThrow({+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),+ noteId: 'not_1d3tmYTlCICgjy',+ });+ await vi.advanceTimersByTimeAsync(249);+ expect(mockedFetch).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(1);+ await pendingNote;+ expect(mockedFetch).toHaveBeenCalledTimes(4);+ });++ it('recovers a 413 through paginated transcript retrieval', async () => {+ const firstItem = buildGranolaTranscriptItem();+ const lastItem = buildGranolaTranscriptItem({ text: 'Goodbye' });+ const mockedFetch = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(new Response(null, { status: 413 }))+ .mockResolvedValueOnce(Response.json(buildGranolaNote()))+ .mockResolvedValueOnce(+ Response.json({+ transcript: [firstItem],+ hasMore: true,+ cursor: 'next/page+',+ }),+ )+ .mockResolvedValueOnce(+ Response.json({ transcript: [lastItem], hasMore: false, cursor: null }),+ );+ vi.stubGlobal('fetch', mockedFetch);++ const result = await fetchGranolaNoteWithTranscriptOrThrow({+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),+ noteId: 'not_1d3tmYTlCICgjy',+ });++ expect(result.transcript).toEqual([firstItem, lastItem]);+ expect(String(mockedFetch.mock.calls[0][0])).toContain(+ 'include=transcript',+ );+ expect(String(mockedFetch.mock.calls[1][0])).not.toContain('include=');+ expect(String(mockedFetch.mock.calls[3][0])).toContain(+ 'cursor=next%2Fpage%2B',+ );+ });++ it.each(['loop', null])(+ 'rejects a non-advancing cursor (%s) with a typed error',+ async (cursor) => {+ const mockedFetch = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(new Response(null, { status: 413 }))+ .mockResolvedValueOnce(Response.json(buildGranolaNote()))+ .mockImplementation(async () =>+ Response.json({ transcript: [], hasMore: true, cursor }),+ );+ vi.stubGlobal('fetch', mockedFetch);++ const pendingNote = fetchGranolaNoteWithTranscriptOrThrow({+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),+ noteId: 'not_1d3tmYTlCICgjy',+ });++ await expect(pendingNote).rejects.toBeInstanceOf(+ GranolaTranscriptLimitError,+ );+ await expect(pendingNote).rejects.toThrow(+ `did not advance for note not_1d3tmYTlCICgjy at cursor ${cursor ?? 'none'}`,+ );+ expect(mockedFetch).toHaveBeenCalledTimes(cursor === null ? 3 : 4);+ },+ );++ it('stops at the page limit when the transcript never reports completion', async () => {+ vi.useFakeTimers();+ let pageIndex = 0;+ const mockedFetch = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(new Response(null, { status: 413 }))+ .mockResolvedValueOnce(Response.json(buildGranolaNote()))+ .mockImplementation(async () => {+ pageIndex += 1;+ return Response.json({+ transcript: [],+ hasMore: true,+ cursor: String(pageIndex),+ });+ });+ vi.stubGlobal('fetch', mockedFetch);++ const pendingNote = fetchGranolaNoteWithTranscriptOrThrow({+ client: createGranolaClientOrThrow({ apiKey: 'grn_test' }),+ noteId: 'not_1d3tmYTlCICgjy',+ });+ const rejection = expect(pendingNote).rejects.toThrow('1,000-page');+ await vi.advanceTimersByTimeAsync(1_000 * 250);+ await rejection;+ expect(mockedFetch).toHaveBeenCalledTimes(1_002);+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.tsnew file mode 100644index 00000000000..069d8009820--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.ts@@ -0,0 +1,166 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { describe, expect, it, vi } from 'vitest';++import { buildGranolaNote } from 'src/__tests__/utils/build-granola-note.util';+import { findMatchingCalendarEventOrThrow } from 'src/logic-functions/utils/find-matching-calendar-event-or-throw.util';++const buildConnection = ({+ calendarEventIds,+ hasNextPage = false,+}: {+ calendarEventIds: (string | null)[];+ hasNextPage?: boolean;+}) => ({+ edges: calendarEventIds.map((calendarEventId) => ({+ node: { calendarEventId },+ })),+ pageInfo: { hasNextPage },+});++const buildCoreApiClient = ({+ associations,+ participants,+}: {+ associations?: ReturnType<typeof buildConnection>;+ participants?: ReturnType<typeof buildConnection>;+}): Pick<CoreApiClient, 'query'> => ({+ query: vi+ .fn()+ .mockImplementation(async (query: object) =>+ 'calendarChannelEventAssociations' in query+ ? { calendarChannelEventAssociations: associations }+ : { calendarEventParticipants: participants },+ ),+});++const buildNote = (+ overrides: Partial<+ NonNullable<ReturnType<typeof buildGranolaNote>['calendar_event']>+ > = {},+) =>+ buildGranolaNote({+ calendar_event: {+ event_title: 'Customer call',+ invitees: [{ email: '[email protected] ' }, { email: '[email protected]' }],+ organiser: null,+ calendar_event_id: null,+ scheduled_start_time: '2026-09-05T10:00:00Z',+ scheduled_end_time: null,+ ...overrides,+ },+ });++describe('findMatchingCalendarEventOrThrow', () => {+ it('links by the provider event id without touching participants', async () => {+ const coreApiClient = buildCoreApiClient({+ associations: buildConnection({+ calendarEventIds: ['event-1', 'event-1'],+ }),+ });++ await expect(+ findMatchingCalendarEventOrThrow({+ coreApiClient,+ note: buildNote({ calendar_event_id: 'google-123' }),+ }),+ ).resolves.toBe('event-1');+ expect(coreApiClient.query).toHaveBeenCalledTimes(1);+ });++ it.each([+ [+ 'ambiguous',+ buildConnection({ calendarEventIds: ['event-1', 'event-2'] }),+ ],+ [+ 'paged-out',+ buildConnection({ calendarEventIds: ['event-1'], hasNextPage: true }),+ ],+ ])(+ 'refuses a %s provider id match without falling back',+ async (_, associations) => {+ const coreApiClient = buildCoreApiClient({+ associations,+ participants: buildConnection({ calendarEventIds: ['fallback-event'] }),+ });++ await expect(+ findMatchingCalendarEventOrThrow({+ coreApiClient,+ note: buildNote({ calendar_event_id: 'google-123' }),+ }),+ ).resolves.toBeUndefined();+ expect(coreApiClient.query).toHaveBeenCalledTimes(1);+ },+ );++ it('falls back to invitee emails at the scheduled start when no provider id matches', async () => {+ const coreApiClient = buildCoreApiClient({+ associations: buildConnection({ calendarEventIds: [] }),+ participants: buildConnection({+ calendarEventIds: ['event-7', null, 'event-7'],+ }),+ });++ await expect(+ findMatchingCalendarEventOrThrow({+ coreApiClient,+ note: buildNote({ calendar_event_id: 'google-123' }),+ }),+ ).resolves.toBe('event-7');+ expect(coreApiClient.query).toHaveBeenCalledTimes(2);+ expect(vi.mocked(coreApiClient.query).mock.calls[1][0]).toMatchObject({+ calendarEventParticipants: {+ __args: {+ filter: {+ calendarEvent: {+ startsAt: { eq: '2026-09-05T10:00:00Z' },+ isCanceled: { eq: false },+ },+ or: [+ { handle: { ilike: '[email protected]' } },+ { handle: { ilike: '[email protected]' } },+ ],+ },+ },+ },+ });+ });++ it('escapes ilike wildcards in invitee emails', async () => {+ const coreApiClient = buildCoreApiClient({+ participants: buildConnection({ calendarEventIds: [] }),+ });++ await findMatchingCalendarEventOrThrow({+ coreApiClient,+ note: buildNote({ invitees: [{ email: 'a_b%[email protected]' }] }),+ });++ expect(vi.mocked(coreApiClient.query).mock.calls[0][0]).toMatchObject({+ calendarEventParticipants: {+ __args: {+ filter: { or: [{ handle: { ilike: 'a\\_b\\%[email protected]' } }] },+ },+ },+ });+ });++ it('does not query without a scheduled start or invitees', async () => {+ const coreApiClient = buildCoreApiClient({});++ await expect(+ findMatchingCalendarEventOrThrow({+ coreApiClient,+ note: buildNote({ scheduled_start_time: null }),+ }),+ ).resolves.toBeUndefined();+ await expect(+ findMatchingCalendarEventOrThrow({+ coreApiClient,+ note: buildNote({ invitees: [] }),+ }),+ ).resolves.toBeUndefined();+ expect(coreApiClient.query).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/format-granola-summary.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/format-granola-summary.test.tsnew file mode 100644index 00000000000..e2f3c90355f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/format-granola-summary.test.ts@@ -0,0 +1,21 @@+import { expect, it } from 'vitest';++import { formatGranolaSummary } from 'src/logic-functions/utils/format-granola-summary.util';++it('prefers shared markdown and falls back when it is absent or blank', () => {+ expect(+ formatGranolaSummary({+ summary_markdown: ' ## Decisions ',+ summary_text: 'Decisions',+ }),+ ).toBe('## Decisions');+ expect(+ formatGranolaSummary({+ summary_markdown: null,+ summary_text: ' Decisions ',+ }),+ ).toBe('Decisions');+ expect(+ formatGranolaSummary({ summary_markdown: ' ', summary_text: '' }),+ ).toBe('');+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-time-range.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-time-range.test.tsnew file mode 100644index 00000000000..379949eb663--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-time-range.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { buildGranolaNote } from 'src/__tests__/utils/build-granola-note.util';+import { buildGranolaTranscriptItem } from 'src/__tests__/utils/build-granola-transcript-item.util';+import { getGranolaNoteTimeRange } from 'src/logic-functions/utils/get-granola-note-time-range.util';++describe('getGranolaNoteTimeRange', () => {+ it('does not end a scheduled note without a transcript before its start', () => {+ const note = buildGranolaNote({+ created_at: '2026-09-04T10:00:00Z',+ calendar_event: {+ event_title: null,+ invitees: [],+ organiser: null,+ calendar_event_id: null,+ scheduled_start_time: '2026-09-05T10:00:00Z',+ scheduled_end_time: null,+ },+ });++ expect(getGranolaNoteTimeRange(note)).toEqual({+ startedAt: '2026-09-05T10:00:00Z',+ endedAt: '2026-09-05T10:00:00Z',+ });+ });++ it('uses creation time for a note with no scheduled times or transcript', () => {+ const note = buildGranolaNote();+ expect(getGranolaNoteTimeRange(note)).toEqual({+ startedAt: note.created_at,+ endedAt: note.created_at,+ });+ });++ it('prefers transcript boundaries over scheduled times so offsets start at zero', () => {+ const note = buildGranolaNote({+ transcript: [buildGranolaTranscriptItem()],+ calendar_event: {+ event_title: null,+ invitees: [],+ organiser: null,+ calendar_event_id: null,+ scheduled_start_time: '2026-09-05T10:00:00Z',+ scheduled_end_time: null,+ },+ });+ expect(getGranolaNoteTimeRange(note)).toEqual({+ startedAt: '2026-09-05T10:00:05Z',+ endedAt: '2026-09-05T10:00:07Z',+ });+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-title.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-title.test.tsnew file mode 100644index 00000000000..e7b6f5cdf93--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-title.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import { buildGranolaNote } from 'src/__tests__/utils/build-granola-note.util';+import { getGranolaNoteTitle } from 'src/logic-functions/utils/get-granola-note-title.util';++describe('getGranolaNoteTitle', () => {+ it.each([+ {+ title: ' Note title ',+ calendarTitle: 'Calendar title',+ expected: 'Note title',+ },+ {+ title: ' ',+ calendarTitle: ' Calendar title ',+ expected: 'Calendar title',+ },+ {+ title: null,+ calendarTitle: 'Calendar title',+ expected: 'Calendar title',+ },+ { title: ' ', calendarTitle: ' ', expected: undefined },+ ])(+ 'chooses $expected for note title $title and calendar title $calendarTitle',+ ({ title, calendarTitle, expected }) => {+ expect(+ getGranolaNoteTitle(+ buildGranolaNote({+ title,+ calendar_event: {+ event_title: calendarTitle,+ invitees: [],+ organiser: null,+ calendar_event_id: null,+ scheduled_start_time: null,+ scheduled_end_time: null,+ },+ }),+ ),+ ).toBe(expected);+ },+ );++ it('leaves an untitled note without a calendar event untitled', () => {+ expect(+ getGranolaNoteTitle(buildGranolaNote({ title: null })),+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-single-distinct-calendar-event-id.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-single-distinct-calendar-event-id.test.tsnew file mode 100644index 00000000000..b179f2514a6--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-single-distinct-calendar-event-id.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { getSingleDistinctCalendarEventId } from 'src/logic-functions/utils/get-single-distinct-calendar-event-id.util';++describe('getSingleDistinctCalendarEventId', () => {+ it('accepts multiple synchronized calendar associations for the same event', () => {+ expect(getSingleDistinctCalendarEventId(['event-1', 'event-1', null])).toBe(+ 'event-1',+ );+ });++ it('leaves competing event matches unlinked', () => {+ expect(+ getSingleDistinctCalendarEventId(['event-1', 'event-2']),+ ).toBeUndefined();+ });++ it('leaves absent matches unlinked', () => {+ expect(getSingleDistinctCalendarEventId([null, ''])).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/map-granola-transcript-to-entries.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/map-granola-transcript-to-entries.test.tsnew file mode 100644index 00000000000..e94439462f3--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/map-granola-transcript-to-entries.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';++import { buildGranolaNote } from 'src/__tests__/utils/build-granola-note.util';+import { buildGranolaTranscriptItem } from 'src/__tests__/utils/build-granola-transcript-item.util';+import { getGranolaNoteTimeRange } from 'src/logic-functions/utils/get-granola-note-time-range.util';+import { mapGranolaTranscriptToEntries } from 'src/logic-functions/utils/map-granola-transcript-to-entries.util';++describe('mapGranolaTranscriptToEntries', () => {+ it('anchors early speech at zero instead of the scheduled meeting start', () => {+ const note = buildGranolaNote({+ transcript: [+ buildGranolaTranscriptItem({+ start_time: '2026-09-05T09:55:00Z',+ end_time: '2026-09-05T09:55:02Z',+ }),+ buildGranolaTranscriptItem({+ start_time: '2026-09-05T09:55:05.250Z',+ end_time: '2026-09-05T09:55:07Z',+ }),+ ],+ calendar_event: {+ event_title: null,+ invitees: [],+ organiser: null,+ calendar_event_id: null,+ scheduled_start_time: '2026-09-05T10:00:00Z',+ scheduled_end_time: null,+ },+ });++ expect(+ mapGranolaTranscriptToEntries({+ transcript: note.transcript,+ owner: note.owner,+ startedAt: getGranolaNoteTimeRange(note).startedAt,+ }).map((entry) => entry.words[0].start_timestamp.relative),+ ).toEqual([0, 5.25]);+ });++ it('resolves identified speakers, owner attribution, anonymous iOS labels and unknown speakers', () => {+ const transcript = [+ buildGranolaTranscriptItem({+ speaker: { source: 'speaker', name: ' Bob ', attribution: 'me' },+ }),+ buildGranolaTranscriptItem(),+ buildGranolaTranscriptItem({+ speaker: { source: 'microphone', diarization_label: 'Speaker A' },+ }),+ buildGranolaTranscriptItem({ speaker: { source: 'speaker' } }),+ ];++ expect(+ mapGranolaTranscriptToEntries({+ transcript,+ owner: { name: null, email: '[email protected]' },+ startedAt: '2026-09-05T10:00:00Z',+ }).map((entry) => entry.participant.name),+ ).toEqual(['Bob', '[email protected]', 'Speaker A', 'Participant']);+ });++ it('preserves fractional offsets and skips whitespace-only speech', () => {+ const transcript = [+ buildGranolaTranscriptItem({+ text: ' Hello ',+ start_time: '2026-09-05T10:00:05.250Z',+ }),+ buildGranolaTranscriptItem({ text: ' ' }),+ ];++ expect(+ mapGranolaTranscriptToEntries({+ transcript,+ owner: { name: 'Alice', email: '[email protected]' },+ startedAt: '2026-09-05T10:00:00Z',+ }),+ ).toEqual([+ {+ participant: { name: 'Alice' },+ words: [{ text: 'Hello', start_timestamp: { relative: 5.25 } }],+ },+ ]);+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/upsert-call-recording-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/upsert-call-recording-or-throw.test.tsnew file mode 100644index 00000000000..4d1688838d3--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/upsert-call-recording-or-throw.test.ts@@ -0,0 +1,130 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { describe, expect, it, vi } from 'vitest';++import { upsertCallRecordingOrThrow } from 'src/logic-functions/utils/upsert-call-recording-or-throw.util';++const CALL_RECORDING_ID = 'c4c893ca-3099-4b11-8c50-0c823bb24f36';+const EMPTY_RECORDINGS = { callRecordings: { edges: [] } };+const EXISTING_RECORDINGS = {+ callRecordings: { edges: [{ node: { id: CALL_RECORDING_ID } }] },+};++const buildCoreApiClient = (): Pick<CoreApiClient, 'query' | 'mutation'> => ({+ query: vi.fn().mockResolvedValue(EMPTY_RECORDINGS),+ mutation: vi.fn().mockResolvedValue({}),+});++describe('upsertCallRecordingOrThrow', () => {+ it.each([+ new Error('Duplicate recording'),+ new Error('Response lost after the server committed the recording'),+ ])('recovers a newly visible record after $message', async (error) => {+ const coreApiClient = buildCoreApiClient();++ vi.mocked(coreApiClient.query)+ .mockResolvedValueOnce(EMPTY_RECORDINGS)+ .mockResolvedValueOnce(EMPTY_RECORDINGS)+ .mockResolvedValueOnce(EXISTING_RECORDINGS);+ vi.mocked(coreApiClient.mutation).mockRejectedValueOnce(error);++ await expect(+ upsertCallRecordingOrThrow({+ coreApiClient,+ callRecordingId: CALL_RECORDING_ID,+ fields: { title: 'Customer call' },+ }),+ ).resolves.toEqual({ callRecordingId: CALL_RECORDING_ID, created: false });+ expect(coreApiClient.mutation).toHaveBeenNthCalledWith(2, {+ updateCallRecording: {+ __args: { id: CALL_RECORDING_ID, data: { title: 'Customer call' } },+ id: true,+ },+ });+ });++ it('propagates a failed create when no record exists', async () => {+ const coreApiClient = buildCoreApiClient();+ const error = new Error('Create failed');+ vi.mocked(coreApiClient.mutation).mockRejectedValueOnce(error);+ await expect(+ upsertCallRecordingOrThrow({+ coreApiClient,+ callRecordingId: CALL_RECORDING_ID,+ fields: { title: 'Customer call' },+ }),+ ).rejects.toBe(error);+ expect(coreApiClient.mutation).toHaveBeenCalledTimes(1);+ });++ it('propagates a failed recovery update instead of reporting success', async () => {+ const coreApiClient = buildCoreApiClient();+ const updateError = new Error('Invalid fields');++ vi.mocked(coreApiClient.query)+ .mockResolvedValueOnce(EMPTY_RECORDINGS)+ .mockResolvedValueOnce(EMPTY_RECORDINGS)+ .mockResolvedValueOnce(EXISTING_RECORDINGS);+ vi.mocked(coreApiClient.mutation).mockRejectedValueOnce(+ new Error('Duplicate recording'),+ );+ vi.mocked(coreApiClient.mutation).mockRejectedValueOnce(updateError);++ await expect(+ upsertCallRecordingOrThrow({+ coreApiClient,+ callRecordingId: CALL_RECORDING_ID,+ fields: { title: 'Customer call' },+ }),+ ).rejects.toBe(updateError);+ });++ it.each([false, true])(+ 'preserves transcript arrays on writes (existing: %s)',+ async (isExisting) => {+ const coreApiClient = buildCoreApiClient();+ const transcript = [{ participant: { name: 'Alice' }, words: [] }];+ vi.mocked(coreApiClient.query)+ .mockResolvedValueOnce(EMPTY_RECORDINGS)+ .mockResolvedValueOnce(+ isExisting ? EXISTING_RECORDINGS : EMPTY_RECORDINGS,+ );+ await expect(+ upsertCallRecordingOrThrow({+ coreApiClient,+ callRecordingId: CALL_RECORDING_ID,+ fields: { transcript },+ }),+ ).resolves.toEqual({+ callRecordingId: CALL_RECORDING_ID,+ created: !isExisting,+ });+ const mutationName = isExisting+ ? 'updateCallRecording'+ : 'createCallRecording';+ const argumentsForMutation = isExisting+ ? { id: CALL_RECORDING_ID, data: { transcript } }+ : { data: { id: CALL_RECORDING_ID, transcript } };++ expect(coreApiClient.mutation).toHaveBeenCalledExactlyOnceWith({+ [mutationName]: { __args: argumentsForMutation, id: true },+ });+ },+ );++ it('skips a soft-deleted recording without writing', async () => {+ const coreApiClient = buildCoreApiClient();+ vi.mocked(coreApiClient.query).mockResolvedValueOnce(EXISTING_RECORDINGS);+ await expect(+ upsertCallRecordingOrThrow({+ coreApiClient,+ callRecordingId: CALL_RECORDING_ID,+ fields: { title: 'Customer call' },+ }),+ ).resolves.toEqual({+ callRecordingId: CALL_RECORDING_ID,+ created: false,+ skipped: true,+ });+ expect(coreApiClient.mutation).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/compute-call-recording-id-for-granola-note.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/compute-call-recording-id-for-granola-note.util.tsnew file mode 100644index 00000000000..a5a23471329--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/compute-call-recording-id-for-granola-note.util.ts@@ -0,0 +1,14 @@+import { createHash } from 'crypto';++export const computeCallRecordingIdForGranolaNote = (+ noteId: string,+): string => {+ const bytes = createHash('sha256').update(`granola:${noteId}`).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/granola/src/logic-functions/utils/does-call-recording-exist-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/does-call-recording-exist-or-throw.util.tsnew file mode 100644index 00000000000..ad4bfc3d16f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/does-call-recording-exist-or-throw.util.ts@@ -0,0 +1,15 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { doesCallRecordingMatchFilterOrThrow } from 'src/logic-functions/utils/does-call-recording-match-filter-or-throw.util';++export const doesCallRecordingExistOrThrow = async ({+ coreApiClient,+ callRecordingId,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ callRecordingId: string;+}): Promise<boolean> =>+ doesCallRecordingMatchFilterOrThrow({+ coreApiClient,+ filter: { id: { eq: callRecordingId } },+ });diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/does-call-recording-match-filter-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/does-call-recording-match-filter-or-throw.util.tsnew file mode 100644index 00000000000..a183272e787--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/does-call-recording-match-filter-or-throw.util.ts@@ -0,0 +1,22 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'twenty-sdk/utils';++export const doesCallRecordingMatchFilterOrThrow = 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);+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/escape-ilike-pattern.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/escape-ilike-pattern.util.tsnew file mode 100644index 00000000000..e4a02a197c3--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/escape-ilike-pattern.util.ts@@ -0,0 +1,2 @@+export const escapeIlikePattern = (value: string): string =>+ value.replace(/[\\%_]/g, '\\$&');diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/fetch-granola-note-with-transcript-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/fetch-granola-note-with-transcript-or-throw.util.tsnew file mode 100644index 00000000000..088c805e518--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/fetch-granola-note-with-transcript-or-throw.util.ts@@ -0,0 +1,73 @@+import {+ GRANOLA_TRANSCRIPT_MAX_PAGES,+ GRANOLA_TRANSCRIPT_PAGE_INTERVAL_MILLISECONDS,+ GRANOLA_TRANSCRIPT_PAGE_SIZE,+ GRANOLA_TRANSCRIPT_TIMEOUT_MILLISECONDS,+} from 'src/constants/granola-transcript.constant';+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';+import { GranolaTranscriptLimitError } from 'src/logic-functions/types/granola-transcript-limit-error';+import { type GranolaTranscriptItem } from 'src/logic-functions/types/granola-api.type';+import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';+import { isDefined } from 'twenty-sdk/utils';++export const fetchGranolaNoteWithTranscriptOrThrow = async ({+ client,+ noteId,+}: {+ client: Pick<+ ReturnType<typeof createGranolaClientOrThrow>,+ 'getNote' | 'listTranscriptPage'+ >;+ noteId: string;+}) => {+ try {+ return await client.getNote({ noteId, includeTranscript: true });+ } catch (error) {+ if (!(error instanceof GranolaApiError) || error.status !== 413) {+ throw error;+ }+ }++ const note = await client.getNote({ noteId });+ const transcript: GranolaTranscriptItem[] = [];+ const seenCursors = new Set<string>();+ const startedAt = Date.now();+ let cursor: string | undefined;++ for (+ let pageIndex = 0;+ pageIndex < GRANOLA_TRANSCRIPT_MAX_PAGES;+ pageIndex+++ ) {+ if (Date.now() - startedAt >= GRANOLA_TRANSCRIPT_TIMEOUT_MILLISECONDS) {+ throw new GranolaTranscriptLimitError({ reason: 'time-limit' });+ }+ const page = await client.listTranscriptPage({+ noteId,+ cursor,+ page_size: GRANOLA_TRANSCRIPT_PAGE_SIZE,+ });++ transcript.push(...page.transcript);++ if (!page.hasMore) {+ return { ...note, transcript };+ }++ if (!isDefined(page.cursor) || seenCursors.has(page.cursor)) {+ throw new GranolaTranscriptLimitError({+ reason: 'non-advancing-cursor',+ noteId,+ cursor: page.cursor,+ });+ }++ seenCursors.add(page.cursor);+ cursor = page.cursor;+ await new Promise((resolve) =>+ setTimeout(resolve, GRANOLA_TRANSCRIPT_PAGE_INTERVAL_MILLISECONDS),+ );+ }++ throw new GranolaTranscriptLimitError({ reason: 'page-limit' });+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/find-matching-calendar-event-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/find-matching-calendar-event-or-throw.util.tsnew file mode 100644index 00000000000..36fc12fbfd8--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/find-matching-calendar-event-or-throw.util.ts@@ -0,0 +1,105 @@+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'twenty-sdk/utils';++import { type GranolaNote } from 'src/logic-functions/types/granola-api.type';+import { escapeIlikePattern } from 'src/logic-functions/utils/escape-ilike-pattern.util';+import { getSingleDistinctCalendarEventId } from 'src/logic-functions/utils/get-single-distinct-calendar-event-id.util';++type CalendarEventMatches = {+ pageInfo: { hasNextPage: boolean };+ edges: { node: { calendarEventId: string | null } }[];+};++export const findMatchingCalendarEventOrThrow = async ({+ coreApiClient,+ note,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ note: Pick<GranolaNote, 'calendar_event'>;+}): Promise<string | undefined> => {+ const granolaCalendarEvent = note.calendar_event;++ if (!isDefined(granolaCalendarEvent)) {+ return undefined;+ }++ if (isNonEmptyString(granolaCalendarEvent.calendar_event_id)) {+ const result = await coreApiClient.query({+ calendarChannelEventAssociations: {+ __args: {+ filter: {+ eventExternalId: { eq: granolaCalendarEvent.calendar_event_id },+ },+ first: 100,+ },+ edges: { node: { calendarEventId: true } },+ pageInfo: { hasNextPage: true },+ },+ });+ const calendarChannelEventAssociations: CalendarEventMatches | undefined =+ result.calendarChannelEventAssociations;++ if (calendarChannelEventAssociations?.pageInfo.hasNextPage) {+ return undefined;+ }++ if (isNonEmptyArray(calendarChannelEventAssociations?.edges)) {+ const matchingCalendarEventIds =+ calendarChannelEventAssociations.edges.map(+ ({ node }) => node.calendarEventId,+ );++ return getSingleDistinctCalendarEventId(matchingCalendarEventIds);+ }+ }++ const inviteeEmails = [+ ...new Set(+ granolaCalendarEvent.invitees+ .map(({ email }) => email.trim())+ .filter(isNonEmptyString),+ ),+ ];++ if (+ !isNonEmptyString(granolaCalendarEvent.scheduled_start_time) ||+ !isNonEmptyArray(inviteeEmails)+ ) {+ return undefined;+ }++ const result = await coreApiClient.query({+ calendarEventParticipants: {+ __args: {+ filter: {+ calendarEvent: {+ startsAt: { eq: granolaCalendarEvent.scheduled_start_time },+ isCanceled: { eq: false },+ },+ or: inviteeEmails.map((email) => ({+ handle: { ilike: escapeIlikePattern(email) },+ })),+ },+ first: 100,+ },+ edges: { node: { calendarEventId: true } },+ pageInfo: { hasNextPage: true },+ },+ });+ const calendarEventParticipants: CalendarEventMatches | undefined =+ result.calendarEventParticipants;++ if (+ !isDefined(calendarEventParticipants) ||+ calendarEventParticipants.pageInfo.hasNextPage+ ) {+ return undefined;+ }++ const matchingCalendarEventIds = calendarEventParticipants.edges.map(+ ({ node }) => node.calendarEventId,+ );++ return getSingleDistinctCalendarEventId(matchingCalendarEventIds);+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/format-granola-summary.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/format-granola-summary.util.tsnew file mode 100644index 00000000000..96323d3c408--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/format-granola-summary.util.ts@@ -0,0 +1,11 @@+import { isNonEmptyString } from '@sniptt/guards';++import { type GranolaNote } from 'src/logic-functions/types/granola-api.type';++export const formatGranolaSummary = (+ note: Pick<GranolaNote, 'summary_markdown' | 'summary_text'>,+): string => {+ const markdown = note.summary_markdown?.trim();++ return isNonEmptyString(markdown) ? markdown : note.summary_text.trim();+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-time-range.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-time-range.util.tsnew file mode 100644index 00000000000..33fa488b55f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-time-range.util.ts@@ -0,0 +1,18 @@+import { type GranolaNote } from 'src/logic-functions/types/granola-api.type';++export const getGranolaNoteTimeRange = (+ note: Pick<GranolaNote, 'calendar_event' | 'transcript' | 'created_at'>,+): { startedAt: string; endedAt: string } => {+ const startedAt =+ note.transcript?.[0]?.start_time ??+ note.calendar_event?.scheduled_start_time ??+ note.created_at;++ return {+ startedAt,+ endedAt:+ note.transcript?.[note.transcript.length - 1]?.end_time ??+ note.calendar_event?.scheduled_end_time ??+ startedAt,+ };+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-title.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-title.util.tsnew file mode 100644index 00000000000..58050248cf7--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-title.util.ts@@ -0,0 +1,17 @@+import { isNonEmptyString } from '@sniptt/guards';++import { type GranolaNote } from 'src/logic-functions/types/granola-api.type';++export const getGranolaNoteTitle = (+ note: Pick<GranolaNote, 'title' | 'calendar_event'>,+): string | undefined => {+ const title = note.title?.trim();++ if (isNonEmptyString(title)) {+ return title;+ }++ const calendarTitle = note.calendar_event?.event_title?.trim();++ return isNonEmptyString(calendarTitle) ? calendarTitle : undefined;+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-single-distinct-calendar-event-id.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-single-distinct-calendar-event-id.util.tsnew file mode 100644index 00000000000..8b54e2a9a91--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-single-distinct-calendar-event-id.util.ts@@ -0,0 +1,15 @@+import { isNonEmptyString } from '@sniptt/guards';++export const getSingleDistinctCalendarEventId = (+ calendarEventIds: (string | null)[],+): string | undefined => {+ const distinctCalendarEventIds = [+ ...new Set(calendarEventIds.filter(isNonEmptyString)),+ ];++ if (distinctCalendarEventIds.length !== 1) {+ return undefined;+ }++ return distinctCalendarEventIds[0];+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/is-call-recording-soft-deleted-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/is-call-recording-soft-deleted-or-throw.util.tsnew file mode 100644index 00000000000..b0045bfe94f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/is-call-recording-soft-deleted-or-throw.util.ts@@ -0,0 +1,15 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { doesCallRecordingMatchFilterOrThrow } from 'src/logic-functions/utils/does-call-recording-match-filter-or-throw.util';++export const isCallRecordingSoftDeletedOrThrow = async ({+ coreApiClient,+ callRecordingId,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ callRecordingId: string;+}): Promise<boolean> =>+ doesCallRecordingMatchFilterOrThrow({+ coreApiClient,+ filter: { id: { eq: callRecordingId }, deletedAt: { is: 'NOT_NULL' } },+ });diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/map-granola-transcript-to-entries.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/map-granola-transcript-to-entries.util.tsnew file mode 100644index 00000000000..11875052530--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/map-granola-transcript-to-entries.util.ts@@ -0,0 +1,50 @@+import { isNonEmptyString } from '@sniptt/guards';++import { GRANOLA_UNKNOWN_SPEAKER_LABEL } from 'src/constants/granola-transcript.constant';+import { type GranolaNote } from 'src/logic-functions/types/granola-api.type';+import { type TranscriptEntry } from 'src/logic-functions/types/transcript-entry.type';++export const mapGranolaTranscriptToEntries = ({+ transcript,+ owner,+ startedAt,+}: Pick<GranolaNote, 'transcript' | 'owner'> & {+ startedAt: string;+}): TranscriptEntry[] => {+ const ownerName = owner.name?.trim();+ const ownerDisplayName = isNonEmptyString(ownerName)+ ? ownerName+ : owner.email.trim();++ return (transcript ?? []).flatMap((item) => {+ const text = item.text.trim();++ if (!isNonEmptyString(text)) {+ return [];+ }++ const ownerLabel =+ item.speaker.attribution === 'me' ? ownerDisplayName : undefined;+ const name =+ [+ item.speaker.name?.trim(),+ ownerLabel,+ item.speaker.diarization_label?.trim(),+ ].find(isNonEmptyString) ?? GRANOLA_UNKNOWN_SPEAKER_LABEL;++ return [+ {+ participant: { name },+ words: [+ {+ text,+ start_timestamp: {+ relative:+ (Date.parse(item.start_time) - Date.parse(startedAt)) / 1_000,+ },+ },+ ],+ },+ ];+ });+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/to-call-recording-mutation-fields.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/to-call-recording-mutation-fields.util.tsnew file mode 100644index 00000000000..5633a307082--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/to-call-recording-mutation-fields.util.ts@@ -0,0 +1,18 @@+import { isDefined } from 'twenty-sdk/utils';++import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recording-sync-fields.type';++export const toCallRecordingMutationFields = ({+ transcript,+ ...fields+}: CallRecordingSyncFields) => {+ if (!isDefined(transcript)) {+ return fields;+ }++ return {+ ...fields,+ // The SDK's JSON scalar rejects arrays; remove this cast when its typing is fixed.+ transcript: transcript as unknown as Record<string, unknown>,+ };+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/update-call-recording-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/update-call-recording-or-throw.util.tsnew file mode 100644index 00000000000..383ebfea767--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/update-call-recording-or-throw.util.ts@@ -0,0 +1,24 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recording-sync-fields.type';+import { toCallRecordingMutationFields } from 'src/logic-functions/utils/to-call-recording-mutation-fields.util';++export const updateCallRecordingOrThrow = async ({+ coreApiClient,+ callRecordingId,+ fields,+}: {+ coreApiClient: Pick<CoreApiClient, 'mutation'>;+ callRecordingId: string;+ fields: CallRecordingSyncFields;+}): Promise<void> => {+ await coreApiClient.mutation({+ updateCallRecording: {+ __args: {+ id: callRecordingId,+ data: toCallRecordingMutationFields(fields),+ },+ id: true,+ },+ });+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/upsert-call-recording-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/upsert-call-recording-or-throw.util.tsnew file mode 100644index 00000000000..6a021fd1c99--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/upsert-call-recording-or-throw.util.ts@@ -0,0 +1,67 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recording-sync-fields.type';+import { doesCallRecordingExistOrThrow } from 'src/logic-functions/utils/does-call-recording-exist-or-throw.util';+import { isCallRecordingSoftDeletedOrThrow } from 'src/logic-functions/utils/is-call-recording-soft-deleted-or-throw.util';+import { toCallRecordingMutationFields } from 'src/logic-functions/utils/to-call-recording-mutation-fields.util';+import { updateCallRecordingOrThrow } from 'src/logic-functions/utils/update-call-recording-or-throw.util';++export const upsertCallRecordingOrThrow = async ({+ coreApiClient,+ callRecordingId,+ fields,+}: {+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;+ callRecordingId: string;+ fields: CallRecordingSyncFields;+}): Promise<{+ callRecordingId: string;+ created: boolean;+ skipped?: boolean;+}> => {+ if (+ await isCallRecordingSoftDeletedOrThrow({ coreApiClient, callRecordingId })+ ) {+ return { callRecordingId, created: false, skipped: true };+ }++ if (await doesCallRecordingExistOrThrow({ coreApiClient, callRecordingId })) {+ await updateCallRecordingOrThrow({+ coreApiClient,+ callRecordingId,+ fields,+ });++ return { callRecordingId, created: false };+ }++ try {+ await coreApiClient.mutation({+ createCallRecording: {+ __args: {+ data: {+ id: callRecordingId,+ ...toCallRecordingMutationFields(fields),+ },+ },+ id: true,+ },+ });++ return { callRecordingId, created: true };+ } catch (error) {+ if (+ !(await doesCallRecordingExistOrThrow({ coreApiClient, callRecordingId }))+ ) {+ throw error;+ }++ await updateCallRecordingOrThrow({+ coreApiClient,+ callRecordingId,+ fields,+ });++ return { callRecordingId, created: false };+ }+};