The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Granola 5/8: Import Granola history and recover missed updates (#25574)
nitinb523a208504b
diff --git a/packages/twenty-apps/public/granola/src/constants/granola-api.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola-api.constant.tsindex da9f8880424..731d3e2da0d 100644--- a/packages/twenty-apps/public/granola/src/constants/granola-api.constant.ts+++ b/packages/twenty-apps/public/granola/src/constants/granola-api.constant.ts@@ -1 +1,2 @@export const GRANOLA_NOTE_ID_PATTERN = /^not_[a-zA-Z0-9]{14}$/;+export const GRANOLA_MAX_PAGE_SIZE = 30;diff --git a/packages/twenty-apps/public/granola/src/constants/granola-backfill-route-path.ts b/packages/twenty-apps/public/granola/src/constants/granola-backfill-route-path.tsnew file mode 100644index 00000000000..8f300d1dfe1--- /dev/null+++ b/packages/twenty-apps/public/granola/src/constants/granola-backfill-route-path.ts@@ -0,0 +1 @@+export const GRANOLA_BACKFILL_ROUTE_PATH = '/granola/backfill';diff --git a/packages/twenty-apps/public/granola/src/constants/granola-history.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola-history.constant.tsnew file mode 100644index 00000000000..b68231bd688--- /dev/null+++ b/packages/twenty-apps/public/granola/src/constants/granola-history.constant.ts@@ -0,0 +1,7 @@+export const GRANOLA_HISTORY_IMPORT_INTERVAL_MILLISECONDS = 4_000;+export const GRANOLA_HISTORY_MAX_PAGES = 1000;+export const GRANOLA_HISTORY_MAX_IMPORT_DAYS = 3_650;+export const GRANOLA_INITIAL_IMPORT_DAYS = 31;+export const GRANOLA_CATCH_UP_WINDOW_DAYS = 2;+export const GRANOLA_JOB_RETRY_LIMIT = 3;+export const GRANOLA_MILLISECONDS_PER_DAY = 86_400_000;diff --git a/packages/twenty-apps/public/granola/src/constants/granola.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola.constant.tsindex e610e4bbb3e..454a8ac437f 100644--- a/packages/twenty-apps/public/granola/src/constants/granola.constant.ts+++ b/packages/twenty-apps/public/granola/src/constants/granola.constant.ts@@ -1,2 +1,3 @@export const GRANOLA_WEBHOOK_REGISTRATION_KEY = 'granola-webhook-registration';export const GRANOLA_PENDING_REGISTRATION_KEY = 'granola-pending-registration';+export const GRANOLA_HISTORY_SCHEDULE_KEY = 'granola-history-schedule';diff --git a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.tsindex 1f4d2bc3f66..5ca52c8f241 100644--- a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts@@ -21,7 +21,7 @@ export const GRANOLA_BACKFILL_UNIVERSAL_IDENTIFIER ='ace20bc6-95c7-4e5b-8c7a-eacd5a85315c';export const GRANOLA_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER ='0a66fe57-1fda-47ed-b759-a5f2f55e70d9';-export const GRANOLA_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER =+export const GRANOLA_BACKFILL_NOTE_UNIVERSAL_IDENTIFIER ='87da64cb-14a5-482b-99de-4b12ff2d3557';export const GRANOLA_DAILY_CATCH_UP_UNIVERSAL_IDENTIFIER ='a054a421-50cc-4cb5-819d-7ce5f8e22595';diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaImportHistorySection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaImportHistorySection.tsxnew file mode 100644index 00000000000..69c899e4374--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaImportHistorySection.tsx@@ -0,0 +1,135 @@+import styled from '@emotion/styled';+import { useId, useState } from 'react';+import { t } from 'twenty-sdk/front-component';+import { isDefined } from 'twenty-sdk/utils';+import { Button } from 'twenty-ui/input';+import { Section } from 'twenty-ui/layout';+import { themeCssVariables } from 'twenty-ui/theme-constants';+import { H2Title } from 'twenty-ui/typography';++import { GRANOLA_BACKFILL_ROUTE_PATH } from 'src/constants/granola-backfill-route-path';+import { GRANOLA_HISTORY_MAX_IMPORT_DAYS } from 'src/constants/granola-history.constant';+import { StyledSettingsError } from 'src/front-components/components/StyledSettingsError';+import { StyledSettingsHint } from 'src/front-components/components/StyledSettingsHint';+import { StyledSettingsSectionStack } from 'src/front-components/components/StyledSettingsSectionStack';+import { StyledSettingsTextInput } from 'src/front-components/components/StyledSettingsTextInput';+import { DEFAULT_GRANOLA_HISTORY_IMPORT_DAYS } from 'src/front-components/constants/default-granola-history-import-days.constant';+import { parseHistoryImportDays } from 'src/front-components/utils/parse-history-import-days.util';+import { postGranolaSettingsRouteOrThrow } from 'src/front-components/utils/post-granola-settings-route-or-throw.util';++const StyledRow = styled.form`+ align-items: center;+ display: flex;+ gap: ${() => themeCssVariables.spacing[2]};+`;++const StyledDaysInputContainer = styled.div`+ display: flex;+ width: ${() => themeCssVariables.spacing[20]};+`;++const StyledRowLabel = styled.label`+ color: ${() => themeCssVariables.font.color.secondary};+ font-family: ${() => themeCssVariables.font.family};+ font-size: ${() => themeCssVariables.font.size.md};+`;++type ImportFeedback = { kind: 'success' | 'error'; message: string };++export const GranolaImportHistorySection = () => {+ const inputId = useId();+ const [daysDraft, setDaysDraft] = useState(+ String(DEFAULT_GRANOLA_HISTORY_IMPORT_DAYS),+ );+ const [isImporting, setIsImporting] = useState(false);+ const [feedback, setFeedback] = useState<ImportFeedback | undefined>(+ undefined,+ );++ const days = parseHistoryImportDays(daysDraft);++ const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {+ event.preventDefault();++ if (!isDefined(days)) {+ return;+ }++ setIsImporting(true);+ setFeedback(undefined);++ try {+ await postGranolaSettingsRouteOrThrow({+ routePath: GRANOLA_BACKFILL_ROUTE_PATH,+ body: { days },+ });+ setFeedback({+ kind: 'success',+ message: t(+ 'Import started. Notes from the last {days} days will appear in Call Recordings over the next few hours.',+ { days },+ ),+ });+ } catch (error) {+ setFeedback({+ kind: 'error',+ message:+ error instanceof Error+ ? error.message+ : t('Could not start the import. Try again.'),+ });+ } finally {+ setIsImporting(false);+ }+ };++ return (+ <Section>+ <H2Title+ title={t('Import history')}+ description={t(+ 'Bring older notes from the synced folders into Call Recordings. Recordings you deleted in Twenty stay deleted.',+ )}+ />+ <StyledSettingsSectionStack>+ <StyledRow onSubmit={handleSubmit}>+ <StyledRowLabel htmlFor={inputId}>+ {t('Import the last')}+ </StyledRowLabel>+ <StyledDaysInputContainer>+ <StyledSettingsTextInput+ id={inputId}+ type="number"+ min={1}+ max={GRANOLA_HISTORY_MAX_IMPORT_DAYS}+ step={1}+ value={daysDraft}+ disabled={isImporting}+ onChange={(event) => setDaysDraft(event.target.value)}+ />+ </StyledDaysInputContainer>+ <StyledRowLabel htmlFor={inputId}>{t('days')}</StyledRowLabel>+ <Button+ type="submit"+ title={t('Import')}+ isLoading={isImporting}+ disabled={isImporting || !isDefined(days)}+ />+ </StyledRow>+ {!isDefined(days) && (+ <StyledSettingsError>+ {t('Enter a whole number of days between 1 and {max}.', {+ max: GRANOLA_HISTORY_MAX_IMPORT_DAYS,+ })}+ </StyledSettingsError>+ )}+ {feedback?.kind === 'success' && (+ <StyledSettingsHint>{feedback.message}</StyledSettingsHint>+ )}+ {feedback?.kind === 'error' && (+ <StyledSettingsError>{feedback.message}</StyledSettingsError>+ )}+ </StyledSettingsSectionStack>+ </Section>+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsxindex 0f303ef9329..8f3b20e18e0 100644--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx@@ -15,12 +15,15 @@ import {type ThemeType,} from 'twenty-ui/theme-constants';+import { GranolaImportHistorySection } from 'src/front-components/components/GranolaImportHistorySection';+import { GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH } from 'src/constants/granola-webhook-registration-route-path';+import { GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH } from 'src/constants/granola-webhook-removal-route-path';import { GranolaConnectionSection } from 'src/front-components/components/GranolaConnectionSection';import { OnMountEffect } from 'src/front-components/components/OnMountEffect';import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';import { fetchGranolaConnectionStatusOrThrow } from 'src/front-components/utils/fetch-granola-connection-status-or-throw.util';-import { registerGranolaWebhookOrThrow } from 'src/front-components/utils/register-granola-webhook-or-throw.util';-import { removeGranolaWebhookOrThrow } from 'src/front-components/utils/remove-granola-webhook-or-throw.util';+import { isGranolaConnectionReady } from 'src/front-components/utils/is-granola-connection-ready.util';+import { postGranolaSettingsRouteOrThrow } from 'src/front-components/utils/post-granola-settings-route-or-throw.util';import { setGranolaApiKeyOrThrow } from 'src/front-components/utils/set-granola-api-key-or-throw.util';const StyledContainer = styled.div`@@ -88,7 +91,10 @@ export const GranolaSettings = () => {setRegistrationError(undefined);try {- await registerGranolaWebhookOrThrow();+ await postGranolaSettingsRouteOrThrow({+ routePath: GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH,+ body: {},+ });} catch {setRegistrationError(t('Could not connect to Granola. Try again.'));}@@ -134,7 +140,10 @@ export const GranolaSettings = () => {setRemoveError(undefined);try {- await removeGranolaWebhookOrThrow();+ await postGranolaSettingsRouteOrThrow({+ routePath: GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH,+ body: {},+ });await setGranolaApiKeyOrThrow({ frontComponentId, apiKey: '' });setConnectError(undefined);setRegistrationError(undefined);@@ -170,20 +179,27 @@ export const GranolaSettings = () => {</StyledNotice>)}{state.step === 'ready' && (- <GranolaConnectionSection- status={state.status}- isConnecting={isConnecting || isRegistering}- isRemoving={isRemoving}- connectError={connectError ?? registrationError}- removeError={removeError}- onConnect={handleConnect}- onRemove={handleRemove}- onRetry={- state.status.isConnected && state.status.canManage- ? registerLiveSync- : loadConnectionStatus- }- />+ <>+ <GranolaConnectionSection+ status={state.status}+ isConnecting={isConnecting || isRegistering}+ isRemoving={isRemoving}+ connectError={connectError ?? registrationError}+ removeError={removeError}+ onConnect={handleConnect}+ onRemove={handleRemove}+ onRetry={+ state.status.isConnected && state.status.canManage+ ? registerLiveSync+ : loadConnectionStatus+ }+ />+ {state.status.canManage &&+ isGranolaConnectionReady(state.status) &&+ !isConnecting &&+ !isRegistering &&+ !isDefined(registrationError) && <GranolaImportHistorySection />}+ </>)}</StyledContainer></ThemeContext.Provider>diff --git a/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsHint.tsx b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsHint.tsxnew file mode 100644index 00000000000..0d767f4c3e1--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsHint.tsx@@ -0,0 +1,9 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++export const StyledSettingsHint = styled.div`+ color: ${() => themeCssVariables.font.color.tertiary};+ font-family: ${() => themeCssVariables.font.family};+ font-size: ${() => themeCssVariables.font.size.sm};+ line-height: ${() => themeCssVariables.text.lineHeight.lg};+`;diff --git a/packages/twenty-apps/public/granola/src/front-components/constants/default-granola-history-import-days.constant.ts b/packages/twenty-apps/public/granola/src/front-components/constants/default-granola-history-import-days.constant.tsnew file mode 100644index 00000000000..ff1a8a83198--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/constants/default-granola-history-import-days.constant.ts@@ -0,0 +1 @@+export const DEFAULT_GRANOLA_HISTORY_IMPORT_DAYS = 90;diff --git a/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx b/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsxindex f47062f065f..ba6b5c03108 100644--- a/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx+++ b/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx@@ -5,6 +5,6 @@ import { GranolaSettings } from 'src/front-components/components/GranolaSettingsexport default defineSettingsFrontComponent({universalIdentifier: GRANOLA_SETTINGS_UNIVERSAL_IDENTIFIER,name: 'granola-settings',- description: 'Granola account connection settings.',+ description: 'Granola account connection and history import settings.',component: GranolaSettings,});diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/parse-history-import-days.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/parse-history-import-days.test.tsnew file mode 100644index 00000000000..190f9183f75--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/parse-history-import-days.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { parseHistoryImportDays } from 'src/front-components/utils/parse-history-import-days.util';++describe('parseHistoryImportDays', () => {+ it.each([+ { text: '1', days: 1 },+ { text: '3650', days: 3650 },+ { text: ' 31 ', days: 31 },+ ])('accepts $text as $days days', ({ text, days }) => {+ expect(parseHistoryImportDays(text)).toBe(days);+ });++ it.each([+ '',+ ' ',+ '0',+ '-1',+ '3651',+ '1.5',+ '31days',+ '1e2',+ '0x1f',+ 'Infinity',+ ])('rejects %j instead of silently importing another date range', (text) => {+ expect(parseHistoryImportDays(text)).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/parse-history-import-days.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/parse-history-import-days.util.tsnew file mode 100644index 00000000000..9b5142dae22--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/parse-history-import-days.util.ts@@ -0,0 +1,13 @@+import { GRANOLA_HISTORY_MAX_IMPORT_DAYS } from 'src/constants/granola-history.constant';++export const parseHistoryImportDays = (value: string): number | undefined => {+ if (!/^\d+$/.test(value.trim())) {+ return undefined;+ }++ const days = Number(value);++ return days >= 1 && days <= GRANOLA_HISTORY_MAX_IMPORT_DAYS+ ? days+ : undefined;+};diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-settings-route-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-settings-route-or-throw.util.tsnew file mode 100644index 00000000000..62fb169e7f5--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-settings-route-or-throw.util.ts@@ -0,0 +1,23 @@+import { RestApiClient } from 'twenty-client-sdk/rest';+import { z } from 'zod';++const GRANOLA_SETTINGS_ROUTE_RESULT_SCHEMA = z.discriminatedUnion('success', [+ z.object({ success: z.literal(true) }),+ z.object({ success: z.literal(false), error: z.string() }),+]);++export const postGranolaSettingsRouteOrThrow = async ({+ routePath,+ body,+}: {+ routePath: string;+ body: Record<string, unknown>;+}): Promise<void> => {+ const result = GRANOLA_SETTINGS_ROUTE_RESULT_SCHEMA.parse(+ await new RestApiClient().post(`/s${routePath}`, body),+ );++ if (!result.success) {+ throw new Error(result.error);+ }+};diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-webhook-action-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-webhook-action-or-throw.util.tsdeleted file mode 100644index 5105040d773..00000000000--- a/packages/twenty-apps/public/granola/src/front-components/utils/post-granola-webhook-action-or-throw.util.ts+++ /dev/null@@ -1,19 +0,0 @@-import { RestApiClient } from 'twenty-client-sdk/rest';-import { z } from 'zod';--const ACTION_RESULT_SCHEMA = z.discriminatedUnion('success', [- z.object({ success: z.literal(true) }),- z.object({ success: z.literal(false), error: z.string() }),-]);--export const postGranolaWebhookActionOrThrow = async (- routePath: string,-): Promise<void> => {- const result = ACTION_RESULT_SCHEMA.parse(- await new RestApiClient().post(`/s${routePath}`, {}),- );-- if (!result.success) {- throw new Error(result.error);- }-};diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/register-granola-webhook-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/register-granola-webhook-or-throw.util.tsdeleted file mode 100644index a3aa7f05468..00000000000--- a/packages/twenty-apps/public/granola/src/front-components/utils/register-granola-webhook-or-throw.util.ts+++ /dev/null@@ -1,5 +0,0 @@-import { GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH } from 'src/constants/granola-webhook-registration-route-path';-import { postGranolaWebhookActionOrThrow } from 'src/front-components/utils/post-granola-webhook-action-or-throw.util';--export const registerGranolaWebhookOrThrow = (): Promise<void> =>- postGranolaWebhookActionOrThrow(GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH);diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/remove-granola-webhook-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/remove-granola-webhook-or-throw.util.tsdeleted file mode 100644index eec0018bb2a..00000000000--- a/packages/twenty-apps/public/granola/src/front-components/utils/remove-granola-webhook-or-throw.util.ts+++ /dev/null@@ -1,5 +0,0 @@-import { GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH } from 'src/constants/granola-webhook-removal-route-path';-import { postGranolaWebhookActionOrThrow } from 'src/front-components/utils/post-granola-webhook-action-or-throw.util';--export const removeGranolaWebhookOrThrow = (): Promise<void> =>- postGranolaWebhookActionOrThrow(GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH);diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill-note.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill-note.tsnew file mode 100644index 00000000000..405a37872f7--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill-note.ts@@ -0,0 +1,71 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import { defineLogicFunction } from 'twenty-sdk/define';++import { GRANOLA_BACKFILL_NOTE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';+import { type GranolaBackfillNotePayload } from 'src/logic-functions/types/granola-backfill-note-payload.type';+import { GranolaInvalidResponseError } from 'src/logic-functions/types/granola-invalid-response-error';+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 { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';+import { isGranolaJobInRegistrationScope } from 'src/logic-functions/utils/is-granola-job-in-registration-scope.util';+import { rethrowKnownOrWrapGranolaError } from 'src/logic-functions/utils/rethrow-known-or-wrap-granola-error.util';+import { syncGranolaNoteToCallRecordingOrThrow } from 'src/logic-functions/utils/sync-granola-note-to-call-recording-or-throw.util';++export const granolaBackfillNoteHandler = async (+ payload: GranolaBackfillNotePayload,+) => {+ try {+ const registration = await findGranolaRegistrationForCurrentKey();++ if (+ !isGranolaJobInRegistrationScope({+ registration,+ registrationId: payload.registrationId,+ folderId: payload.folderId,+ })+ ) {+ return { success: true, skipped: true };+ }++ const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const client = createGranolaClientOrThrow();+ try {+ const result = await syncGranolaNoteToCallRecordingOrThrow({+ coreApiClient,+ client,+ noteId: payload.noteId,+ });++ return {+ success: true,+ importedNoteCount: result.skipped ? 0 : 1,+ };+ } catch (error) {+ if (+ error instanceof GranolaInvalidResponseError ||+ error instanceof GranolaTranscriptLimitError ||+ (error instanceof GranolaApiError && [403, 404].includes(error.status))+ ) {+ console.error(+ `[granola] Skipped unreadable note ${payload.noteId}: ${error.message}`,+ );++ return { success: true, importedNoteCount: 0 };+ }++ throw error;+ }+ } catch (error) {+ rethrowKnownOrWrapGranolaError({ operation: 'Note import', error });+ }+};++export default defineLogicFunction({+ universalIdentifier: GRANOLA_BACKFILL_NOTE_UNIVERSAL_IDENTIFIER,+ name: 'granola-backfill-note',+ description:+ 'Imports one paced Granola note while preserving deleted recordings.',+ timeoutSeconds: 900,+ handler: granolaBackfillNoteHandler,+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill-worker.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill-worker.tsnew file mode 100644index 00000000000..92bdeaa674a--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill-worker.ts@@ -0,0 +1,133 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import { defineLogicFunction } from 'twenty-sdk/define';++import { GRANOLA_MAX_PAGE_SIZE } from 'src/constants/granola-api.constant';+import {+ GRANOLA_BACKFILL_NOTE_UNIVERSAL_IDENTIFIER,+ GRANOLA_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { type GranolaBackfillNotePayload } from 'src/logic-functions/types/granola-backfill-note-payload.type';+import { type GranolaBackfillWorkerPayload } from 'src/logic-functions/types/granola-backfill-worker-payload.type';+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';+import { enqueueGranolaJobOrThrow } from 'src/logic-functions/utils/enqueue-granola-job-or-throw.util';+import { excludeDeletedGranolaNotesOrThrow } from 'src/logic-functions/utils/exclude-deleted-granola-notes-or-throw.util';+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';+import { getGranolaJobId } from 'src/logic-functions/utils/get-granola-job-id.util';+import { getGranolaNextPage } from 'src/logic-functions/utils/get-granola-next-page.util';+import { isGranolaJobInRegistrationScope } from 'src/logic-functions/utils/is-granola-job-in-registration-scope.util';+import { reserveGranolaNoteImportSlotsOrThrow } from 'src/logic-functions/utils/reserve-granola-note-import-slots-or-throw.util';+import { rethrowKnownOrWrapGranolaError } from 'src/logic-functions/utils/rethrow-known-or-wrap-granola-error.util';++export const granolaBackfillWorkerHandler = async (+ payload: GranolaBackfillWorkerPayload,+) => {+ try {+ const registration = await findGranolaRegistrationForCurrentKey();++ if (+ !isGranolaJobInRegistrationScope({+ registration,+ registrationId: payload.registrationId,+ folderId: payload.folderId,+ })+ ) {+ return { success: true, skipped: true };+ }++ const page = await createGranolaClientOrThrow().listNotes({+ created_after: payload.createdAfter,+ updated_after: payload.updatedAfter,+ folder_id: payload.folderId,+ cursor: payload.cursor,+ page_size: GRANOLA_MAX_PAGE_SIZE,+ });+ const noteIds = await excludeDeletedGranolaNotesOrThrow({+ coreApiClient: new CoreApiClient({ runAs: 'application' }),+ noteIds: page.notes.map((note) => note.id),+ });+ const schedule = await reserveGranolaNoteImportSlotsOrThrow(noteIds.length);++ for (const [index, noteId] of noteIds.entries()) {+ const notePayload: GranolaBackfillNotePayload = {+ registrationId: payload.registrationId,+ folderId: payload.folderId,+ noteId,+ };++ await enqueueGranolaJobOrThrow({+ logicFunctionUniversalIdentifier:+ GRANOLA_BACKFILL_NOTE_UNIVERSAL_IDENTIFIER,+ payload: notePayload,+ jobId: getGranolaJobId({+ prefix: 'granola-note',+ identity: {+ ...notePayload,+ createdAfter: payload.createdAfter,+ updatedAfter: payload.updatedAfter,+ },+ }),+ delayMs: schedule.noteDelays[index],+ });+ }++ const nextPage = getGranolaNextPage({+ ...page,+ previousCursor: payload.cursor,+ pageIndex: payload.pageIndex,+ });++ if (nextPage.kind === 'stalled') {+ console.error(+ `[granola] ${nextPage.reason} Registration ${payload.registrationId}, cursor ${page.cursor}.`,+ );++ return {+ success: true,+ discoveredNoteCount: page.notes.length,+ enqueuedNoteCount: noteIds.length,+ hasMore: true,+ stopped: true,+ };+ }++ if (nextPage.kind === 'next') {+ const continuationPayload: GranolaBackfillWorkerPayload = {+ ...payload,+ cursor: nextPage.cursor,+ pageIndex: payload.pageIndex + 1,+ };++ await enqueueGranolaJobOrThrow({+ logicFunctionUniversalIdentifier:+ GRANOLA_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ payload: continuationPayload,+ jobId: getGranolaJobId({+ prefix: 'granola-discovery',+ identity: continuationPayload,+ }),+ delayMs: schedule.continuationDelay,+ });+ }++ return {+ success: true,+ discoveredNoteCount: page.notes.length,+ enqueuedNoteCount: noteIds.length,+ hasMore: nextPage.kind === 'next',+ };+ } catch (error) {+ rethrowKnownOrWrapGranolaError({+ operation: 'History discovery',+ error,+ });+ }+};++export default defineLogicFunction({+ universalIdentifier: GRANOLA_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ name: 'granola-backfill-worker',+ description:+ 'Discovers one page of Granola notes and schedules paced note imports.',+ timeoutSeconds: 120,+ handler: granolaBackfillWorkerHandler,+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill.tsnew file mode 100644index 00000000000..e6656ea943b--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-backfill.ts@@ -0,0 +1,68 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { isDefined } from 'twenty-sdk/utils';+import { z } from 'zod';++import { GRANOLA_BACKFILL_ROUTE_PATH } from 'src/constants/granola-backfill-route-path';+import {+ GRANOLA_HISTORY_MAX_IMPORT_DAYS,+ GRANOLA_MILLISECONDS_PER_DAY,+} from 'src/constants/granola-history.constant';+import { GRANOLA_BACKFILL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';+import { enqueueGranolaBackfillOrThrow } from 'src/logic-functions/utils/enqueue-granola-backfill-or-throw.util';+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';++const GRANOLA_BACKFILL_INPUT_SCHEMA = z.object({+ days: z.number().int().min(1).max(GRANOLA_HISTORY_MAX_IMPORT_DAYS),+});++export const granolaBackfillHandler = async (+ payload: RoutePayload<unknown>,+) => {+ const parsed = GRANOLA_BACKFILL_INPUT_SCHEMA.safeParse(payload.body);++ if (!parsed.success) {+ return {+ success: false,+ error: `Choose a whole number of days between 1 and ${GRANOLA_HISTORY_MAX_IMPORT_DAYS}.`,+ };+ }++ if (!(await currentUserCanManageGranolaOrThrow())) {+ return {+ success: false,+ error: 'Application settings permission is required.',+ };+ }++ const registration = await findGranolaRegistrationForCurrentKey();++ if (!isDefined(registration)) {+ return {+ success: false,+ error: 'Set up live sync before importing notes.',+ };+ }++ const result = await enqueueGranolaBackfillOrThrow({+ createdAfter: new Date(+ Date.now() - parsed.data.days * GRANOLA_MILLISECONDS_PER_DAY,+ ).toISOString(),+ });++ return { success: true, days: parsed.data.days, ...result };+};++export default defineLogicFunction({+ universalIdentifier: GRANOLA_BACKFILL_UNIVERSAL_IDENTIFIER,+ name: 'granola-backfill',+ description:+ 'Starts a paced import of Granola notes in the selected folders.',+ timeoutSeconds: 60,+ handler: granolaBackfillHandler,+ httpRouteTriggerSettings: {+ path: GRANOLA_BACKFILL_ROUTE_PATH,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-daily-catch-up.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-daily-catch-up.tsnew file mode 100644index 00000000000..5899a114138--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-daily-catch-up.ts@@ -0,0 +1,38 @@+import { defineLogicFunction } from 'twenty-sdk/define';+import { isDefined } from 'twenty-sdk/utils';++import {+ GRANOLA_CATCH_UP_WINDOW_DAYS,+ GRANOLA_MILLISECONDS_PER_DAY,+} from 'src/constants/granola-history.constant';+import { GRANOLA_DAILY_CATCH_UP_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { enqueueGranolaBackfillOrThrow } from 'src/logic-functions/utils/enqueue-granola-backfill-or-throw.util';+import { enqueueGranolaInitialBackfillOrThrow } from 'src/logic-functions/utils/enqueue-granola-initial-backfill-or-throw.util';+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';++export const granolaDailyCatchUpHandler = async () => {+ const registration = await findGranolaRegistrationForCurrentKey();++ if (!isDefined(registration)) {+ return { success: true, skipped: true };+ }++ await enqueueGranolaInitialBackfillOrThrow(registration);+ const result = await enqueueGranolaBackfillOrThrow({+ updatedAfter: new Date(+ Date.now() - GRANOLA_CATCH_UP_WINDOW_DAYS * GRANOLA_MILLISECONDS_PER_DAY,+ ).toISOString(),+ });++ return { success: true, ...result };+};++export default defineLogicFunction({+ universalIdentifier: GRANOLA_DAILY_CATCH_UP_UNIVERSAL_IDENTIFIER,+ name: 'granola-daily-catch-up',+ description:+ 'Imports Granola notes updated during the last two days to recover missed webhook deliveries.',+ timeoutSeconds: 120,+ handler: granolaDailyCatchUpHandler,+ cronTriggerSettings: { pattern: '0 4 * * *' },+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-register-webhook.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-register-webhook.tsindex 71f5899107e..44e56b30595 100644--- a/packages/twenty-apps/public/granola/src/logic-functions/granola-register-webhook.ts+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-register-webhook.ts@@ -4,7 +4,9 @@ import { GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH } from 'src/constants/granola-wimport { GRANOLA_REGISTER_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';+import { enqueueGranolaInitialBackfillOrThrow } from 'src/logic-functions/utils/enqueue-granola-initial-backfill-or-throw.util';import { ensureGranolaWebhookRegistrationOrThrow } from 'src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';export const granolaRegisterWebhookHandler = async () => {if (!(await currentUserCanManageGranolaOrThrow())) {@@ -14,7 +16,14 @@ export const granolaRegisterWebhookHandler = async () => {};}try {- await ensureGranolaWebhookRegistrationOrThrow();+ const registration = await ensureGranolaWebhookRegistrationOrThrow();+ try {+ await enqueueGranolaInitialBackfillOrThrow(registration);+ } catch (error) {+ console.error(+ `[granola] Could not queue the initial import for registration ${registration.registrationId}; the daily catch-up will retry. ${toErrorMessage(error)}`,+ );+ }return { success: true };} catch (error) {if (error instanceof GranolaApiError) {@@ -27,7 +36,8 @@ export const granolaRegisterWebhookHandler = async () => {export default defineLogicFunction({universalIdentifier: GRANOLA_REGISTER_WEBHOOK_UNIVERSAL_IDENTIFIER,name: 'granola-register-webhook',- description: 'Registers the Granola webhook for the saved key.',+ description:+ 'Registers the Granola webhook for the saved key and starts the initial history import.',timeoutSeconds: 60,handler: granolaRegisterWebhookHandler,httpRouteTriggerSettings: {diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-uninstall.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-uninstall.tsindex f6b58475200..bd11d26c54f 100644--- a/packages/twenty-apps/public/granola/src/logic-functions/granola-uninstall.ts+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-uninstall.ts@@ -1,5 +1,7 @@import { defineUninstallLogicFunction } from 'twenty-sdk/define';+import { kv } from 'twenty-sdk/logic-function';+import { GRANOLA_HISTORY_SCHEDULE_KEY } from 'src/constants/granola.constant';import { GRANOLA_UNINSTALL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { cleanupPendingGranolaRegistrationOrThrow } from 'src/logic-functions/utils/cleanup-pending-granola-registration-or-throw.util';import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';@@ -22,6 +24,8 @@ export const granolaUninstallHandler = async () => {);}+ await kv.delete(GRANOLA_HISTORY_SCHEDULE_KEY);+return removeGranolaWebhookRegistration({ client });};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-backfill-note-payload.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-backfill-note-payload.type.tsnew file mode 100644index 00000000000..38df43fe21b--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-backfill-note-payload.type.ts@@ -0,0 +1,5 @@+export type GranolaBackfillNotePayload = {+ registrationId: string;+ folderId?: string;+ noteId: string;+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-backfill-worker-payload.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-backfill-worker-payload.type.tsnew file mode 100644index 00000000000..247931d0303--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-backfill-worker-payload.type.ts@@ -0,0 +1,8 @@+export type GranolaBackfillWorkerPayload = {+ registrationId: string;+ createdAfter?: string;+ updatedAfter?: string;+ folderId?: string;+ cursor?: string;+ pageIndex: number;+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-webhook-registration.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-webhook-registration.type.tsindex 61586b83453..d37b39dfd35 100644--- a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-webhook-registration.type.ts+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-webhook-registration.type.ts@@ -7,4 +7,5 @@ export type GranolaWebhookRegistration = {apiKeyFingerprint: string;scopes: GranolaWebhookScope[];folderIds: string[];+ isInitialBackfillEnqueued: boolean;};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-job-id.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-job-id.test.tsnew file mode 100644index 00000000000..89f0317c6ed--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-job-id.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { getGranolaJobId } from 'src/logic-functions/utils/get-granola-job-id.util';++describe('getGranolaJobId', () => {+ it('derives the same queue-safe identifier for the same job identity', () => {+ const identity = {+ registrationId: 'reg-1',+ folderId: 'fol_2mKr8fQxLp7Ta3',+ createdAfter: '2026-09-05T10:00:00+05:30',+ pageIndex: 0,+ };++ const jobId = getGranolaJobId({ prefix: 'granola-discovery', identity });++ expect(jobId).toBe(+ getGranolaJobId({ prefix: 'granola-discovery', identity }),+ );+ expect(jobId).toMatch(/^[\w.-]+$/);+ expect(jobId.length).toBeLessThanOrEqual(128);+ });++ it('separates jobs that import different notes', () => {+ const first = getGranolaJobId({+ prefix: 'granola-note',+ identity: { registrationId: 'reg-1', noteId: 'not_a' },+ });+ const second = getGranolaJobId({+ prefix: 'granola-note',+ identity: { registrationId: 'reg-1', noteId: 'not_b' },+ });++ expect(first).not.toBe(second);+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-next-page.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-next-page.test.tsnew file mode 100644index 00000000000..7f2060d7550--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-next-page.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { getGranolaNextPage } from 'src/logic-functions/utils/get-granola-next-page.util';++describe('getGranolaNextPage', () => {+ it('does not follow a cursor after the final page', () => {+ expect(+ getGranolaNextPage({ hasMore: false, cursor: 'stale', pageIndex: 0 }),+ ).toEqual({ kind: 'complete' });+ });++ it.each([+ { cursor: null, pageIndex: 0 },+ { cursor: 'same', previousCursor: 'same', pageIndex: 0 },+ { cursor: 'next', pageIndex: 999 },+ ])(+ 'reports a stalled import for a repeated, missing, or bounded cursor',+ (parameters) => {+ expect(+ getGranolaNextPage({ hasMore: true, ...parameters }),+ ).toMatchObject({ kind: 'stalled', reason: expect.any(String) });+ },+ );++ it('continues a valid next page', () => {+ expect(+ getGranolaNextPage({+ hasMore: true,+ cursor: 'next',+ previousCursor: 'previous',+ pageIndex: 1,+ }),+ ).toEqual({ kind: 'next', cursor: 'next' });+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-import-schedule.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-import-schedule.test.tsnew file mode 100644index 00000000000..385ff690b9d--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-note-import-schedule.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';++import { getGranolaNoteImportSchedule } from 'src/logic-functions/utils/get-granola-note-import-schedule.util';++describe('getGranolaNoteImportSchedule', () => {+ it('spaces note jobs by four seconds after the existing reservation', () => {+ expect(+ getGranolaNoteImportSchedule({+ now: 1000,+ nextAvailableAt: 11000,+ noteCount: 3,+ }),+ ).toEqual({+ noteDelays: [10000, 14000, 18000],+ continuationDelay: 22000,+ nextNoteAvailableAt: 23000,+ });+ });++ it('does not schedule in the past and paces empty pages', () => {+ expect(+ getGranolaNoteImportSchedule({+ now: 1000,+ nextAvailableAt: 10,+ noteCount: 0,+ }),+ ).toEqual({+ noteDelays: [],+ continuationDelay: 4000,+ nextNoteAvailableAt: 1000,+ });+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/is-granola-job-in-registration-scope.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/is-granola-job-in-registration-scope.test.tsnew file mode 100644index 00000000000..7515289d5a0--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/is-granola-job-in-registration-scope.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';++import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';+import { isGranolaJobInRegistrationScope } from 'src/logic-functions/utils/is-granola-job-in-registration-scope.util';++const registration: Pick<+ GranolaWebhookRegistration,+ 'registrationId' | 'folderIds'+> = {+ registrationId: 'reg-1',+ folderIds: [],+};++describe('isGranolaJobInRegistrationScope', () => {+ it('skips a job without a matching registration', () => {+ expect(+ isGranolaJobInRegistrationScope({+ registration: undefined,+ registrationId: 'reg-1',+ folderId: undefined,+ }),+ ).toBe(false);+ expect(+ isGranolaJobInRegistrationScope({+ registration,+ registrationId: 'reg-2',+ folderId: undefined,+ }),+ ).toBe(false);+ });++ it('accepts any folder while the registration syncs every folder', () => {+ expect(+ isGranolaJobInRegistrationScope({+ registration,+ registrationId: 'reg-1',+ folderId: 'fol_1',+ }),+ ).toBe(true);+ });++ it('requires the job folder to be one of the selected folders', () => {+ const restricted = { ...registration, folderIds: ['fol_1'] };++ expect(+ isGranolaJobInRegistrationScope({+ registration: restricted,+ registrationId: 'reg-1',+ folderId: 'fol_1',+ }),+ ).toBe(true);+ expect(+ isGranolaJobInRegistrationScope({+ registration: restricted,+ registrationId: 'reg-1',+ folderId: 'fol_2',+ }),+ ).toBe(false);+ expect(+ isGranolaJobInRegistrationScope({+ registration: restricted,+ registrationId: 'reg-1',+ folderId: undefined,+ }),+ ).toBe(false);+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/rethrow-known-or-wrap-granola-error.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/rethrow-known-or-wrap-granola-error.test.tsnew file mode 100644index 00000000000..c0b66f1f54f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/rethrow-known-or-wrap-granola-error.test.ts@@ -0,0 +1,40 @@+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { describe, expect, it } from 'vitest';++import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';+import { GranolaInvalidResponseError } from 'src/logic-functions/types/granola-invalid-response-error';+import { rethrowKnownOrWrapGranolaError } from 'src/logic-functions/utils/rethrow-known-or-wrap-granola-error.util';++describe('rethrowKnownOrWrapGranolaError', () => {+ it.each([+ new RetryableLogicFunctionError('retryable'),+ new GranolaApiError({ status: 500 }),+ new GranolaInvalidResponseError(),+ ])('rethrows known errors unchanged', (knownError) => {+ let thrownError: unknown;++ try {+ rethrowKnownOrWrapGranolaError({+ operation: 'History discovery',+ error: knownError,+ });+ } catch (error) {+ thrownError = error;+ }++ expect(thrownError).toBe(knownError);+ });++ it('wraps unknown errors as retryable errors', () => {+ expect(() =>+ rethrowKnownOrWrapGranolaError({+ operation: 'History discovery',+ error: new Error('network interrupted'),+ }),+ ).toThrow(+ new RetryableLogicFunctionError(+ '[granola] History discovery failed: network interrupted',+ ),+ );+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-backfill-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-backfill-or-throw.util.tsnew file mode 100644index 00000000000..cbb22011f9e--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-backfill-or-throw.util.ts@@ -0,0 +1,51 @@+import { isDefined } from 'twenty-sdk/utils';++import { GRANOLA_HISTORY_IMPORT_INTERVAL_MILLISECONDS } from 'src/constants/granola-history.constant';+import { GRANOLA_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type GranolaBackfillWorkerPayload } from 'src/logic-functions/types/granola-backfill-worker-payload.type';+import { enqueueGranolaJobOrThrow } from 'src/logic-functions/utils/enqueue-granola-job-or-throw.util';+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';+import { getGranolaJobId } from 'src/logic-functions/utils/get-granola-job-id.util';++export const enqueueGranolaBackfillOrThrow = async ({+ createdAfter,+ updatedAfter,+ folderIds,+}: {+ createdAfter?: string;+ updatedAfter?: string;+ folderIds?: string[];+}) => {+ const registration = await findGranolaRegistrationForCurrentKey();++ if (!isDefined(registration)) {+ throw new Error('Set up live sync before importing notes.');+ }++ const selectedFolders = folderIds ?? registration.folderIds;+ const discoveryFolders =+ selectedFolders.length > 0 ? [...new Set(selectedFolders)] : [undefined];++ for (const [index, folderId] of discoveryFolders.entries()) {+ const payload: GranolaBackfillWorkerPayload = {+ registrationId: registration.registrationId,+ createdAfter,+ updatedAfter,+ folderId,+ pageIndex: 0,+ };++ await enqueueGranolaJobOrThrow({+ logicFunctionUniversalIdentifier:+ GRANOLA_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ payload,+ jobId: getGranolaJobId({+ prefix: 'granola-discovery',+ identity: payload,+ }),+ delayMs: index * GRANOLA_HISTORY_IMPORT_INTERVAL_MILLISECONDS,+ });+ }++ return { enqueuedDiscoveryCount: discoveryFolders.length };+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-initial-backfill-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-initial-backfill-or-throw.util.tsnew file mode 100644index 00000000000..473d9cf9a73--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-initial-backfill-or-throw.util.ts@@ -0,0 +1,42 @@+import { kv } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { GRANOLA_WEBHOOK_REGISTRATION_KEY } from 'src/constants/granola.constant';+import {+ GRANOLA_INITIAL_IMPORT_DAYS,+ GRANOLA_MILLISECONDS_PER_DAY,+} from 'src/constants/granola-history.constant';+import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';+import { enqueueGranolaBackfillOrThrow } from 'src/logic-functions/utils/enqueue-granola-backfill-or-throw.util';++export const enqueueGranolaInitialBackfillOrThrow = async (+ registration: Pick<+ GranolaWebhookRegistration,+ 'registrationId' | 'folderIds' | 'isInitialBackfillEnqueued'+ >,+): Promise<void> => {+ if (registration.isInitialBackfillEnqueued) {+ return;+ }++ await enqueueGranolaBackfillOrThrow({+ createdAfter: new Date(+ Date.now() - GRANOLA_INITIAL_IMPORT_DAYS * GRANOLA_MILLISECONDS_PER_DAY,+ ).toISOString(),+ folderIds: registration.folderIds,+ });++ const currentRegistration = await kv.get<GranolaWebhookRegistration>(+ GRANOLA_WEBHOOK_REGISTRATION_KEY,+ );++ if (+ isDefined(currentRegistration) &&+ currentRegistration.registrationId === registration.registrationId+ ) {+ await kv.set(GRANOLA_WEBHOOK_REGISTRATION_KEY, {+ ...currentRegistration,+ isInitialBackfillEnqueued: true,+ });+ }+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-job-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-job-or-throw.util.tsnew file mode 100644index 00000000000..8f5f79dea62--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/enqueue-granola-job-or-throw.util.ts@@ -0,0 +1,31 @@+import {+ enqueueJobs,+ RetryableLogicFunctionError,+ type EnqueueJobsInput,+} from 'twenty-sdk/logic-function';++import { GRANOLA_JOB_RETRY_LIMIT } from 'src/constants/granola-history.constant';+import { buildRetryableGranolaError } from 'src/logic-functions/utils/build-retryable-granola-error.util';++export const enqueueGranolaJobOrThrow = async ({+ payload,+ jobId,+ ...options+}: Pick<EnqueueJobsInput, 'logicFunctionUniversalIdentifier' | 'delayMs'> & {+ payload: Record<string, unknown>;+ jobId: string;+}): Promise<void> => {+ const result = await enqueueJobs({+ ...options,+ jobs: [{ payload, jobId }],+ retryLimit: GRANOLA_JOB_RETRY_LIMIT,+ }).catch((error: unknown) => {+ throw buildRetryableGranolaError({ operation: 'Job enqueue', error });+ });++ if (!result.enqueued) {+ throw new RetryableLogicFunctionError(+ 'Could not enqueue the Granola import.',+ );+ }+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util.tsindex e68a6eb0f00..12fa877e844 100644--- a/packages/twenty-apps/public/granola/src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util.ts+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/ensure-granola-webhook-registration-or-throw.util.ts@@ -89,6 +89,8 @@ export const ensureGranolaWebhookRegistrationOrThrow =apiKeyFingerprint,scopes: createdEndpoint.scopes,folderIds: createdEndpoint.folder_ids,+ isInitialBackfillEnqueued:+ isExistingKeyCurrent && existing.isInitialBackfillEnqueued,};try {await kv.set(GRANOLA_WEBHOOK_REGISTRATION_KEY, registration);diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/exclude-deleted-granola-notes-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/exclude-deleted-granola-notes-or-throw.util.tsnew file mode 100644index 00000000000..bbe5c46cabe--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/exclude-deleted-granola-notes-or-throw.util.ts@@ -0,0 +1,35 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { computeCallRecordingIdForGranolaNote } from 'src/logic-functions/utils/compute-call-recording-id-for-granola-note.util';++export const excludeDeletedGranolaNotesOrThrow = async ({+ coreApiClient,+ noteIds,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ noteIds: string[];+}): Promise<string[]> => {+ if (noteIds.length === 0) {+ return [];+ }++ const callRecordingIds = noteIds.map(computeCallRecordingIdForGranolaNote);+ const result: { callRecordings?: { edges?: { node: { id: string } }[] } } =+ await coreApiClient.query({+ callRecordings: {+ __args: {+ filter: {+ id: { in: callRecordingIds },+ deletedAt: { is: 'NOT_NULL' },+ },+ first: callRecordingIds.length,+ },+ edges: { node: { id: true } },+ },+ });+ const deletedIds = new Set(+ result.callRecordings?.edges?.map((edge) => edge.node.id) ?? [],+ );++ return noteIds.filter((_, index) => !deletedIds.has(callRecordingIds[index]));+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-job-id.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-job-id.util.tsnew file mode 100644index 00000000000..250cfb0260d--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-job-id.util.ts@@ -0,0 +1,10 @@+import { createHash } from 'node:crypto';++export const getGranolaJobId = ({+ prefix,+ identity,+}: {+ prefix: 'granola-discovery' | 'granola-note';+ identity: Record<string, unknown>;+}): string =>+ `${prefix}-${createHash('sha256').update(JSON.stringify(identity)).digest('hex').slice(0, 32)}`;diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-next-page.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-next-page.util.tsnew file mode 100644index 00000000000..c9eb1b966e3--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-next-page.util.ts@@ -0,0 +1,37 @@+import { isNonEmptyString } from '@sniptt/guards';++import { GRANOLA_HISTORY_MAX_PAGES } from 'src/constants/granola-history.constant';++export type GranolaNextPage =+ | { kind: 'complete' }+ | { kind: 'stalled'; reason: string }+ | { kind: 'next'; cursor: string };++export const getGranolaNextPage = ({+ hasMore,+ cursor,+ previousCursor,+ pageIndex,+}: {+ hasMore: boolean;+ cursor: string | null;+ previousCursor?: string;+ pageIndex: number;+}): GranolaNextPage => {+ if (!hasMore) {+ return { kind: 'complete' };+ }++ if (+ !isNonEmptyString(cursor) ||+ cursor === previousCursor ||+ pageIndex + 1 >= GRANOLA_HISTORY_MAX_PAGES+ ) {+ return {+ kind: 'stalled',+ reason: 'Granola pagination stopped at a repeated cursor or page limit.',+ };+ }++ return { kind: 'next', cursor };+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-import-schedule.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-import-schedule.util.tsnew file mode 100644index 00000000000..fc199cea3e8--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-note-import-schedule.util.ts@@ -0,0 +1,28 @@+import { GRANOLA_HISTORY_IMPORT_INTERVAL_MILLISECONDS } from 'src/constants/granola-history.constant';++export const getGranolaNoteImportSchedule = ({+ now,+ nextAvailableAt,+ noteCount,+}: {+ now: number;+ nextAvailableAt?: number;+ noteCount: number;+}) => {+ const startsAt = Math.max(now, nextAvailableAt ?? now);+ const nextNoteAvailableAt =+ startsAt + noteCount * GRANOLA_HISTORY_IMPORT_INTERVAL_MILLISECONDS;++ return {+ noteDelays: Array.from(+ { length: noteCount },+ (_, index) =>+ startsAt - now + index * GRANOLA_HISTORY_IMPORT_INTERVAL_MILLISECONDS,+ ),+ continuationDelay: Math.max(+ GRANOLA_HISTORY_IMPORT_INTERVAL_MILLISECONDS,+ nextNoteAvailableAt - now,+ ),+ nextNoteAvailableAt,+ };+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/is-granola-job-in-registration-scope.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/is-granola-job-in-registration-scope.util.tsnew file mode 100644index 00000000000..13b69ef007c--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/is-granola-job-in-registration-scope.util.ts@@ -0,0 +1,19 @@+import { isDefined } from 'twenty-sdk/utils';++import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';++export const isGranolaJobInRegistrationScope = ({+ registration,+ registrationId,+ folderId,+}: {+ registration:+ | Pick<GranolaWebhookRegistration, 'registrationId' | 'folderIds'>+ | undefined;+ registrationId: string;+ folderId: string | undefined;+}): boolean =>+ isDefined(registration) &&+ registration.registrationId === registrationId &&+ (registration.folderIds.length === 0 ||+ (isDefined(folderId) && registration.folderIds.includes(folderId)));diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/reserve-granola-note-import-slots-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/reserve-granola-note-import-slots-or-throw.util.tsnew file mode 100644index 00000000000..21d61cfb959--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/reserve-granola-note-import-slots-or-throw.util.ts@@ -0,0 +1,25 @@+import { kv } from 'twenty-sdk/logic-function';++import { GRANOLA_HISTORY_SCHEDULE_KEY } from 'src/constants/granola.constant';+import { getGranolaNoteImportSchedule } from 'src/logic-functions/utils/get-granola-note-import-schedule.util';++export const reserveGranolaNoteImportSlotsOrThrow = async (+ noteCount: number,+) => {+ const saved = await kv.get<{ nextNoteAvailableAt: number }>(+ GRANOLA_HISTORY_SCHEDULE_KEY,+ );+ const schedule = getGranolaNoteImportSchedule({+ now: Date.now(),+ nextAvailableAt: saved?.nextNoteAvailableAt,+ noteCount,+ });++ if (noteCount > 0) {+ await kv.set(GRANOLA_HISTORY_SCHEDULE_KEY, {+ nextNoteAvailableAt: schedule.nextNoteAvailableAt,+ });+ }++ return schedule;+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/rethrow-known-or-wrap-granola-error.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/rethrow-known-or-wrap-granola-error.util.tsnew file mode 100644index 00000000000..6f4163a963e--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/rethrow-known-or-wrap-granola-error.util.ts@@ -0,0 +1,23 @@+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';++import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';+import { GranolaInvalidResponseError } from 'src/logic-functions/types/granola-invalid-response-error';+import { buildRetryableGranolaError } from 'src/logic-functions/utils/build-retryable-granola-error.util';++export const rethrowKnownOrWrapGranolaError = ({+ operation,+ error,+}: {+ operation: string;+ error: unknown;+}): never => {+ if (+ error instanceof RetryableLogicFunctionError ||+ error instanceof GranolaApiError ||+ error instanceof GranolaInvalidResponseError+ ) {+ throw error;+ }++ throw buildRetryableGranolaError({ operation, error });+};diff --git a/packages/twenty-apps/public/granola/src/utils/__tests__/chunk-into-batches-or-throw.test.ts b/packages/twenty-apps/public/granola/src/utils/__tests__/chunk-into-batches-or-throw.test.tsdeleted file mode 100644index 2857dda99eb..00000000000--- a/packages/twenty-apps/public/granola/src/utils/__tests__/chunk-into-batches-or-throw.test.ts+++ /dev/null@@ -1,29 +0,0 @@-import { describe, expect, it } from 'vitest';--import { chunkIntoBatchesOrThrow } from 'src/utils/chunk-into-batches-or-throw.util';--describe('chunkIntoBatchesOrThrow', () => {- it('keeps every item in order, including a partial last batch', () => {- const items = ['first', 'second', 'third', 'fourth', 'fifth'];-- expect(chunkIntoBatchesOrThrow({ items, batchSize: 2 })).toEqual([- ['first', 'second'],- ['third', 'fourth'],- ['fifth'],- ]);- expect(items).toEqual(['first', 'second', 'third', 'fourth', 'fifth']);- });-- it('does not schedule an empty batch', () => {- expect(chunkIntoBatchesOrThrow({ items: [], batchSize: 5 })).toEqual([]);- });-- it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])(- 'rejects invalid batch size %s',- (batchSize) => {- expect(() =>- chunkIntoBatchesOrThrow({ items: ['note'], batchSize }),- ).toThrow('Batch size must be a positive integer');- },- );-});diff --git a/packages/twenty-apps/public/granola/src/utils/chunk-into-batches-or-throw.util.ts b/packages/twenty-apps/public/granola/src/utils/chunk-into-batches-or-throw.util.tsdeleted file mode 100644index 2d3a76c41d0..00000000000--- a/packages/twenty-apps/public/granola/src/utils/chunk-into-batches-or-throw.util.ts+++ /dev/null@@ -1,17 +0,0 @@-export const chunkIntoBatchesOrThrow = <TItem>({- items,- batchSize,-}: {- items: TItem[];- batchSize: number;-}): TItem[][] => {- if (!Number.isInteger(batchSize) || batchSize <= 0) {- throw new Error('Batch size must be a positive integer');- }-- return Array.from(- { length: Math.ceil(items.length / batchSize) },- (_, batchIndex) =>- items.slice(batchIndex * batchSize, (batchIndex + 1) * batchSize),- );-};