The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Granola 7/8: Filter Granola synchronization by folder (#25576)
nitin2badd5da7db1
diff --git a/packages/twenty-apps/public/granola/README.md b/packages/twenty-apps/public/granola/README.mdindex 63677f3a192..75bdb7a9274 100644--- a/packages/twenty-apps/public/granola/README.md+++ b/packages/twenty-apps/public/granola/README.md@@ -4,4 +4,6 @@ Implementation in progress. Sync meeting transcripts and shared summaries into C## Limitations+- One Granola API key serves the whole Twenty workspace. Members cannot connect their own Granola accounts, so every recording comes from the notes that key can see. Use a workspace key to cover a team.+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/constants/granola-api.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola-api.constant.tsindex b8a83970c78..181603e05da 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,3 +1,5 @@export const GRANOLA_NOTE_ID_PATTERN = /^not_[a-zA-Z0-9]{14}$/;export const GRANOLA_FOLDER_ID_PATTERN = /^fol_[a-zA-Z0-9]{14}$/;export const GRANOLA_MAX_PAGE_SIZE = 30;+export const GRANOLA_PAGE_INTERVAL_MILLISECONDS = 250;+export const GRANOLA_FOLDER_SELECTION_LIMIT = 100;diff --git a/packages/twenty-apps/public/granola/src/constants/granola-folder-selection-route-path.ts b/packages/twenty-apps/public/granola/src/constants/granola-folder-selection-route-path.tsnew file mode 100644index 00000000000..331e21d64bc--- /dev/null+++ b/packages/twenty-apps/public/granola/src/constants/granola-folder-selection-route-path.ts@@ -0,0 +1,2 @@+export const GRANOLA_FOLDER_SELECTION_ROUTE_PATH =+ '/granola/webhook-registration/folders';diff --git a/packages/twenty-apps/public/granola/src/constants/granola-folders-route-path.ts b/packages/twenty-apps/public/granola/src/constants/granola-folders-route-path.tsnew file mode 100644index 00000000000..b8f5277ca0f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/constants/granola-folders-route-path.ts@@ -0,0 +1 @@+export const GRANOLA_FOLDERS_ROUTE_PATH = '/granola/folders';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.tsindex 9d87b2bb8c4..0c592d4382a 100644--- a/packages/twenty-apps/public/granola/src/constants/granola-transcript.constant.ts+++ b/packages/twenty-apps/public/granola/src/constants/granola-transcript.constant.ts@@ -1,5 +1,4 @@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/constants/granola.constant.ts b/packages/twenty-apps/public/granola/src/constants/granola.constant.tsindex 454a8ac437f..6e06823cb6f 100644--- a/packages/twenty-apps/public/granola/src/constants/granola.constant.ts+++ b/packages/twenty-apps/public/granola/src/constants/granola.constant.ts@@ -1,3 +1,5 @@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';+export const GRANOLA_PENDING_FOLDER_SELECTION_KEY =+ 'granola-pending-folder-selection';diff --git a/packages/twenty-apps/public/granola/src/front-components/components/Checkbox.tsx b/packages/twenty-apps/public/granola/src/front-components/components/Checkbox.tsxnew file mode 100644index 00000000000..636aa24afa2--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/Checkbox.tsx@@ -0,0 +1,101 @@+import styled from '@emotion/styled';+import { IconCheck, IconMinus } from 'twenty-ui/icon';+import { themeCssVariables } from 'twenty-ui/theme-constants';++// twenty-ui's Checkbox dispatches a PointerEvent the front-component sandbox does not provide.+const CHECKBOX_BOX_SIZE_PIXELS = 14;+const CHECKBOX_ICON_SIZE_PIXELS = 12;++const StyledCheckbox = styled.button`+ align-items: center;+ appearance: none;+ background: transparent;+ border: none;+ border-radius: ${() => themeCssVariables.border.radius.md};+ cursor: pointer;+ display: flex;+ flex-shrink: 0;+ justify-content: center;+ padding: 5px;++ &:hover {+ background-color: ${() => themeCssVariables.background.transparent.light};+ }++ &:disabled {+ cursor: not-allowed;+ }++ &:disabled:hover {+ background-color: transparent;+ }+`;++const StyledBox = styled.span`+ align-items: center;+ background: transparent;+ border: 1px solid ${() => themeCssVariables.border.color.inverted};+ border-radius: ${() => themeCssVariables.border.radius.sm};+ box-sizing: border-box;+ color: ${() => themeCssVariables.font.color.inverted};+ display: flex;+ height: ${CHECKBOX_BOX_SIZE_PIXELS}px;+ justify-content: center;+ width: ${CHECKBOX_BOX_SIZE_PIXELS}px;++ &[data-checked='true'] {+ background: ${() => themeCssVariables.color.blue};+ border-color: ${() => themeCssVariables.color.blue};+ }++ &[data-disabled='true'] {+ border-color: ${() => themeCssVariables.border.color.strong};+ }++ &[data-disabled='true'][data-checked='true'] {+ background: ${() => themeCssVariables.color.blue7};+ border-color: ${() => themeCssVariables.color.blue7};+ }+`;++type CheckboxProps = {+ id?: string;+ checked: boolean;+ indeterminate?: boolean;+ disabled?: boolean;+ 'aria-label'?: string;+ onChange: (checked: boolean) => void;+};++export const Checkbox = ({+ id,+ checked,+ indeterminate = false,+ disabled = false,+ 'aria-label': ariaLabel,+ onChange,+}: CheckboxProps) => {+ const isFilled = checked || indeterminate;++ return (+ <StyledCheckbox+ type="button"+ role="checkbox"+ id={id}+ aria-checked={indeterminate ? 'mixed' : checked ? 'true' : 'false'}+ aria-label={ariaLabel}+ disabled={disabled}+ onClick={() => onChange(!checked)}+ >+ <StyledBox+ data-checked={isFilled ? 'true' : 'false'}+ data-disabled={disabled ? 'true' : 'false'}+ >+ {checked && <IconCheck size={CHECKBOX_ICON_SIZE_PIXELS} stroke={3} />}+ {!checked && indeterminate && (+ <IconMinus size={CHECKBOX_ICON_SIZE_PIXELS} stroke={3} />+ )}+ </StyledBox>+ </StyledCheckbox>+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderEmptyState.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderEmptyState.tsxnew file mode 100644index 00000000000..56fd24ff066--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderEmptyState.tsx@@ -0,0 +1,23 @@+import styled from '@emotion/styled';+import { t } from 'twenty-sdk/front-component';+import { IconFolder } from 'twenty-ui/icon';+import { ICON } from 'twenty-ui/theme';+import { themeCssVariables } from 'twenty-ui/theme-constants';++const StyledEmptyState = styled.div`+ align-items: center;+ color: ${() => themeCssVariables.font.color.tertiary};+ display: flex;+ flex-direction: column;+ font-size: ${() => themeCssVariables.font.size.sm};+ gap: ${() => themeCssVariables.spacing[2]};+ padding: ${() => themeCssVariables.spacing[8]};+ text-align: center;+`;++export const GranolaFolderEmptyState = () => (+ <StyledEmptyState>+ <IconFolder size={ICON.size.md} />+ <div>{t('No folders found for this key')}</div>+ </StyledEmptyState>+);diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPolicyIcon.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPolicyIcon.tsxnew file mode 100644index 00000000000..0b3873f5e1f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPolicyIcon.tsx@@ -0,0 +1,92 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { type GranolaFolderPolicy } from 'src/front-components/types/granola-folder-policy.type';++// Mirrors twenty-front's SettingsAccountsMessageFolderIcon, which a front component cannot import.+const StyledCardMedia = styled.div`+ align-items: center;+ background-color: ${() => themeCssVariables.border.color.medium};+ border-radius: ${() => themeCssVariables.border.radius.sm};+ box-sizing: border-box;+ display: flex;+ flex-shrink: 0;+ height: 40px;+ justify-content: center;+ padding: 2px;+ width: 32px;+`;++const StyledCardMediaContent = styled.div`+ align-items: stretch;+ background-color: ${() => themeCssVariables.background.secondary};+ border-radius: ${() => themeCssVariables.border.radius.xs};+ box-sizing: border-box;+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 2px;+ height: 100%;+ justify-content: center;+ min-width: 0;+ padding: 2px;+`;++const StyledFolderRow = styled.div`+ align-items: center;+ display: flex;+ flex: 1 0 0;+ gap: 2px;+ min-height: 0;+`;++const StyledFolderIcon = styled.div<{ $isDisabled: boolean }>`+ background-color: ${({ $isDisabled }) =>+ $isDisabled+ ? themeCssVariables.border.color.medium+ : themeCssVariables.accent.accent7};+ border-radius: 1px;+ height: 100%;+ width: 4.8px;+`;++const StyledFolderLabel = styled.div<{ $isDisabled: boolean }>`+ background-color: ${({ $isDisabled }) =>+ $isDisabled+ ? themeCssVariables.border.color.medium+ : themeCssVariables.accent.accent7};+ border-radius: 1px;+ flex: 1;+ height: 100%;+`;++const ROW_IS_DISABLED_WHEN_SELECTING = [true, true, false, true, false];++type GranolaFolderPolicyIconProps = {+ policy: GranolaFolderPolicy;+};++export const GranolaFolderPolicyIcon = ({+ policy,+}: GranolaFolderPolicyIconProps) => {+ const isSelectedFolders = policy === 'SELECTED_FOLDERS';++ return (+ <StyledCardMedia>+ <StyledCardMediaContent>+ {ROW_IS_DISABLED_WHEN_SELECTING.map(+ (isDisabledWhenSelecting, index) => {+ const isDisabled = isSelectedFolders && isDisabledWhenSelecting;++ return (+ <StyledFolderRow key={index}>+ <StyledFolderIcon $isDisabled={isDisabled} />+ <StyledFolderLabel $isDisabled={isDisabled} />+ </StyledFolderRow>+ );+ },+ )}+ </StyledCardMediaContent>+ </StyledCardMedia>+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderSection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderSection.tsxnew file mode 100644index 00000000000..9a10d4160d8--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderSection.tsx@@ -0,0 +1,202 @@+import { useState } from 'react';+import { t } from 'twenty-sdk/front-component';+import { isDefined } from 'twenty-sdk/utils';+import { Section } from 'twenty-ui/layout';+import { H2Title } from 'twenty-ui/typography';++import { GRANOLA_FOLDER_SELECTION_LIMIT } from 'src/constants/granola-api.constant';+import { GranolaFolderEmptyState } from 'src/front-components/components/GranolaFolderEmptyState';+import { GranolaFolderPolicyIcon } from 'src/front-components/components/GranolaFolderPolicyIcon';+import { GranolaFolderTree } from 'src/front-components/components/GranolaFolderTree';+import { OnMountEffect } from 'src/front-components/components/OnMountEffect';+import { SettingsRadioCard } from 'src/front-components/components/SettingsRadioCard';+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 { useAutosaveGranolaFolderSelection } from 'src/front-components/hooks/use-autosave-granola-folder-selection';+import { type GranolaFolderPolicy } from 'src/front-components/types/granola-folder-policy.type';+import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';+import { fetchGranolaFoldersOrThrow } from 'src/front-components/utils/fetch-granola-folders-or-throw.util';++type FolderSaveState =+ | { kind: 'idle' }+ | { kind: 'saving' }+ | { kind: 'saved' }+ | { kind: 'pending' }+ | { kind: 'error'; message: string };++export const GranolaFolderSection = () => {+ const [folders, setFolders] = useState<GranolaSettingsFolder[] | undefined>(+ undefined,+ );+ const [loadError, setLoadError] = useState<string | undefined>(undefined);+ const [selectedFolderIds, setSelectedFolderIds] = useState<string[]>([]);+ const [policy, setPolicy] = useState<GranolaFolderPolicy>('ALL_FOLDERS');+ const [hasInaccessibleSelection, setHasInaccessibleSelection] =+ useState(false);+ const [saveState, setSaveState] = useState<FolderSaveState>({ kind: 'idle' });++ const { save } = useAutosaveGranolaFolderSelection({+ onSaveStart: () => setSaveState({ kind: 'saving' }),+ onSaveSuccess: (folderIds) => {+ setSaveState({ kind: 'saved' });+ setSelectedFolderIds(folderIds);+ },+ onSaveError: (message) => setSaveState({ kind: 'error', message }),+ });++ const loadFolders = async () => {+ try {+ const result = await fetchGranolaFoldersOrThrow();+ const accessibleIds = new Set(result.folders.map((folder) => folder.id));+ const storedFolderIds =+ result.pendingFolderIds ?? result.selectedFolderIds;+ const accessibleSelectedIds = storedFolderIds.filter((id) =>+ accessibleIds.has(id),+ );++ setFolders(result.folders);+ setSelectedFolderIds(accessibleSelectedIds);+ setPolicy(+ storedFolderIds.length > 0 ? 'SELECTED_FOLDERS' : 'ALL_FOLDERS',+ );+ setHasInaccessibleSelection(+ storedFolderIds.length > 0 && accessibleSelectedIds.length === 0,+ );++ if (isDefined(result.pendingFolderIds)) {+ setSaveState({ kind: 'pending' });+ }+ } catch {+ setLoadError(t('Could not load your Granola folders. Reload to retry.'));+ }+ };++ const handlePolicyChange = (nextPolicy: GranolaFolderPolicy) => {+ setPolicy(nextPolicy);++ if (+ nextPolicy === 'ALL_FOLDERS' &&+ (selectedFolderIds.length > 0 || hasInaccessibleSelection)+ ) {+ setHasInaccessibleSelection(false);+ setSelectedFolderIds([]);+ save([]);+ }+ };++ const handleReplaceSelection = (nextSelectedFolderIds: string[]) => {+ setHasInaccessibleSelection(false);+ setSelectedFolderIds(nextSelectedFolderIds);+ save(nextSelectedFolderIds);+ };++ const handleToggleFolder = (folderId: string, checked: boolean) => {+ handleReplaceSelection(+ checked+ ? [...selectedFolderIds, folderId]+ : selectedFolderIds.filter((id) => id !== folderId),+ );+ };++ const isSelectionFull =+ selectedFolderIds.length >= GRANOLA_FOLDER_SELECTION_LIMIT;+ const hasFolders = isDefined(folders) && folders.length > 0;++ return (+ <Section>+ <OnMountEffect onMount={loadFolders} />+ <H2Title+ title={t('Folders')}+ description={t(+ 'Choose which Granola folders feed live sync and history imports.',+ )}+ />+ <StyledSettingsSectionStack>+ <SettingsRadioCard+ value={policy}+ disabled={!isDefined(folders)}+ onChange={handlePolicyChange}+ options={[+ {+ value: 'ALL_FOLDERS',+ cardMedia: <GranolaFolderPolicyIcon policy="ALL_FOLDERS" />,+ title: t('Everything'),+ description: t('Sync notes from every folder you can access'),+ },+ {+ value: 'SELECTED_FOLDERS',+ cardMedia: <GranolaFolderPolicyIcon policy="SELECTED_FOLDERS" />,+ title: t('Some folders'),+ description: t(+ 'Sync only the folders you pick, including their subfolders',+ ),+ expandedContent: hasFolders ? (+ <GranolaFolderTree+ folders={folders}+ selectedFolderIds={selectedFolderIds}+ selectionLimit={GRANOLA_FOLDER_SELECTION_LIMIT}+ onToggleFolder={handleToggleFolder}+ onReplaceSelection={handleReplaceSelection}+ />+ ) : (+ <GranolaFolderEmptyState />+ ),+ },+ ]}+ />+ {!isDefined(folders) && !isDefined(loadError) && (+ <StyledSettingsHint>{t('Loading folders…')}</StyledSettingsHint>+ )}+ {isDefined(loadError) && (+ <StyledSettingsError>{loadError}</StyledSettingsError>+ )}+ {hasInaccessibleSelection && (+ <StyledSettingsError>+ {t(+ 'The folders you picked are no longer available. Pick folders again, or switch to Everything.',+ )}+ </StyledSettingsError>+ )}+ {policy === 'SELECTED_FOLDERS' &&+ !hasInaccessibleSelection &&+ hasFolders &&+ selectedFolderIds.length === 0 && (+ <StyledSettingsHint>+ {t('Nothing is picked yet, so every folder still syncs.')}+ </StyledSettingsHint>+ )}+ {policy === 'SELECTED_FOLDERS' && selectedFolderIds.length === 1 && (+ <StyledSettingsHint>+ {t('Switch to Everything to stop filtering by folder.')}+ </StyledSettingsHint>+ )}+ {isSelectionFull && (+ <StyledSettingsHint>+ {t('You can pick up to {limit} folders.', {+ limit: GRANOLA_FOLDER_SELECTION_LIMIT,+ })}+ </StyledSettingsHint>+ )}+ {saveState.kind === 'saving' && (+ <StyledSettingsHint>{t('Saving…')}</StyledSettingsHint>+ )}+ {saveState.kind === 'saved' && (+ <StyledSettingsHint>+ {t('Saved. Live sync and imports now follow this selection.')}+ </StyledSettingsHint>+ )}+ {saveState.kind === 'pending' && (+ <StyledSettingsHint>+ {t(+ 'This selection is not applied in Granola yet. It is retried at the next daily catch-up, or change it again to retry now.',+ )}+ </StyledSettingsHint>+ )}+ {saveState.kind === 'error' && (+ <StyledSettingsError>{saveState.message}</StyledSettingsError>+ )}+ </StyledSettingsSectionStack>+ </Section>+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTree.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTree.tsxnew file mode 100644index 00000000000..c5889601cb0--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTree.tsx@@ -0,0 +1,141 @@+import styled from '@emotion/styled';+import { useState } from 'react';+import { t } from 'twenty-sdk/front-component';+import { themeCssVariables } from 'twenty-ui/theme-constants';+import { Label } from 'twenty-ui/typography';++import { Checkbox } from 'src/front-components/components/Checkbox';+import { GranolaFolderTreeItem } from 'src/front-components/components/GranolaFolderTreeItem';+import { StyledSettingsHint } from 'src/front-components/components/StyledSettingsHint';+import { StyledSettingsTextInput } from 'src/front-components/components/StyledSettingsTextInput';+import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';+import { computeGranolaFolderAncestorIds } from 'src/front-components/utils/compute-granola-folder-ancestor-ids.util';+import { computeGranolaFolderTree } from 'src/front-components/utils/compute-granola-folder-tree.util';++const StyledContainer = styled.div`+ display: flex;+ flex-direction: column;+`;++const StyledSearchInputContainer = styled.div`+ margin-bottom: ${() => themeCssVariables.spacing[2]};+`;++const StyledLabelContainer = styled.span`+ align-items: center;+ color: ${() => themeCssVariables.font.color.tertiary};+ display: flex;+ margin-bottom: ${() => themeCssVariables.spacing[2]};+ margin-top: ${() => themeCssVariables.spacing[2]};+`;++const StyledSectionHeader = styled.div`+ align-items: center;+ background-color: ${() => themeCssVariables.background.transparent.lighter};+ border-bottom: 1px solid ${() => themeCssVariables.border.color.light};+ display: flex;+ height: ${() => themeCssVariables.spacing[6]};+ justify-content: space-between;+ padding: 0 ${() => themeCssVariables.spacing[1]};+`;++const StyledTreeList = styled.ul`+ list-style: none;+ margin: 0;+ max-height: 400px;+ overflow-y: auto;+ padding: ${() => themeCssVariables.spacing[2]} 0;+`;++type GranolaFolderTreeProps = {+ folders: GranolaSettingsFolder[];+ selectedFolderIds: string[];+ selectionLimit: number;+ onToggleFolder: (folderId: string, checked: boolean) => void;+ onReplaceSelection: (folderIds: string[]) => void;+};++export const GranolaFolderTree = ({+ folders,+ selectedFolderIds,+ selectionLimit,+ onToggleFolder,+ onReplaceSelection,+}: GranolaFolderTreeProps) => {+ const [search, setSearch] = useState('');++ const selectedFolderIdSet = new Set(selectedFolderIds);+ const ancestorIdsByFolderId = computeGranolaFolderAncestorIds(folders);+ const coveredFolderIds = new Set(+ folders+ .filter((folder) =>+ (ancestorIdsByFolderId.get(folder.id) ?? []).some((ancestorId) =>+ selectedFolderIdSet.has(ancestorId),+ ),+ )+ .map((folder) => folder.id),+ );+ const rootFolderIds = computeGranolaFolderTree(folders).map(+ (node) => node.folder.id,+ );+ const isEveryFolderSelected = rootFolderIds.every((folderId) =>+ selectedFolderIdSet.has(folderId),+ );+ const canSelectEveryFolder = rootFolderIds.length <= selectionLimit;+ const normalizedSearch = search.trim().toLowerCase();+ const tree = computeGranolaFolderTree(+ normalizedSearch === ''+ ? folders+ : folders.filter((folder) =>+ folder.name.toLowerCase().includes(normalizedSearch),+ ),+ );++ const handleToggleAllFolders = () => {+ onReplaceSelection(isEveryFolderSelected ? [] : rootFolderIds);+ };++ return (+ <StyledContainer>+ <StyledSearchInputContainer>+ <StyledSettingsTextInput+ type="text"+ placeholder={t('Search folders...')}+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ />+ </StyledSearchInputContainer>+ <StyledLabelContainer>+ <Label>{t('Folders')}</Label>+ </StyledLabelContainer>+ <StyledSectionHeader>+ <Label>{t('Toggle all folders')}</Label>+ <Checkbox+ checked={isEveryFolderSelected}+ indeterminate={!isEveryFolderSelected && selectedFolderIds.length > 0}+ disabled={!canSelectEveryFolder}+ aria-label={t('Toggle all folders')}+ onChange={handleToggleAllFolders}+ />+ </StyledSectionHeader>+ {tree.length === 0 && (+ <StyledSettingsHint>+ {t('No folder matches your search.')}+ </StyledSettingsHint>+ )}+ <StyledTreeList>+ {tree.map((node, index) => (+ <GranolaFolderTreeItem+ key={node.folder.id}+ node={node}+ isLast={index === tree.length - 1}+ selectedFolderIds={selectedFolderIdSet}+ coveredFolderIds={coveredFolderIds}+ isSelectionFull={selectedFolderIds.length >= selectionLimit}+ onToggleFolder={onToggleFolder}+ />+ ))}+ </StyledTreeList>+ </StyledContainer>+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeBreadcrumb.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeBreadcrumb.tsxnew file mode 100644index 00000000000..c6f5340575f--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeBreadcrumb.tsx@@ -0,0 +1,92 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++export const GRANOLA_FOLDER_TREE_INDENT_PIXELS = 24;+const ROW_HEIGHT_PIXELS = 28;+const ICON_CENTER_OFFSET_PIXELS = 8;++const StyledOverlay = styled.div<{ $depth: number }>`+ height: ${ROW_HEIGHT_PIXELS}px;+ left: 0;+ pointer-events: none;+ position: absolute;+ top: 0;+ width: ${({ $depth }) => $depth * GRANOLA_FOLDER_TREE_INDENT_PIXELS}px;+`;++const StyledAncestorLine = styled.div<{ $index: number; $isVisible: boolean }>`+ background: ${({ $isVisible }) =>+ $isVisible ? themeCssVariables.border.color.strong : 'transparent'};+ height: ${ROW_HEIGHT_PIXELS}px;+ left: ${({ $index }) =>+ $index * GRANOLA_FOLDER_TREE_INDENT_PIXELS + ICON_CENTER_OFFSET_PIXELS}px;+ position: absolute;+ top: 0;+ width: 1px;+`;++const StyledConnector = styled.div<{ $depth: number }>`+ height: ${ROW_HEIGHT_PIXELS}px;+ left: ${({ $depth }) =>+ ($depth - 1) * GRANOLA_FOLDER_TREE_INDENT_PIXELS ++ ICON_CENTER_OFFSET_PIXELS}px;+ position: absolute;+ top: 0;+ width: ${GRANOLA_FOLDER_TREE_INDENT_PIXELS - ICON_CENTER_OFFSET_PIXELS}px;+`;++const StyledVerticalLineTop = styled.div`+ background: ${() => themeCssVariables.border.color.strong};+ height: 12px;+ left: 0;+ position: absolute;+ top: 0;+ width: 1px;+`;++const StyledRoundedCorner = styled.div`+ border-bottom: 1px solid ${() => themeCssVariables.border.color.strong};+ border-bottom-left-radius: 4px;+ border-left: 1px solid ${() => themeCssVariables.border.color.strong};+ height: 8px;+ left: 0;+ position: absolute;+ top: 6px;+ width: 8px;+`;++const StyledVerticalLineBottom = styled.div`+ background: ${() => themeCssVariables.border.color.strong};+ height: 16px;+ left: 0;+ position: absolute;+ top: 12px;+ width: 1px;+`;++type GranolaFolderTreeBreadcrumbProps = {+ depth: number;+ isLast: boolean;+ parentsIsLastList: boolean[];+};++export const GranolaFolderTreeBreadcrumb = ({+ depth,+ isLast,+ parentsIsLastList,+}: GranolaFolderTreeBreadcrumbProps) => (+ <StyledOverlay $depth={depth}>+ {parentsIsLastList.map((parentIsLast, index) => (+ <StyledAncestorLine+ key={index}+ $index={index}+ $isVisible={!parentIsLast}+ />+ ))}+ <StyledConnector $depth={depth}>+ <StyledVerticalLineTop />+ <StyledRoundedCorner />+ {!isLast && <StyledVerticalLineBottom />}+ </StyledConnector>+ </StyledOverlay>+);diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeItem.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeItem.tsxnew file mode 100644index 00000000000..ed2df3b17bd--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeItem.tsx@@ -0,0 +1,224 @@+import styled from '@emotion/styled';+import { useState } from 'react';+import { t } from 'twenty-sdk/front-component';+import {+ IconChevronDown,+ IconChevronUp,+ IconFolder,+ IconFolderRoot,+} from 'twenty-ui/icon';+import { ICON } from 'twenty-ui/theme';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { Checkbox } from 'src/front-components/components/Checkbox';+import {+ GRANOLA_FOLDER_TREE_INDENT_PIXELS,+ GranolaFolderTreeBreadcrumb,+} from 'src/front-components/components/GranolaFolderTreeBreadcrumb';+import { type GranolaFolderTreeNode } from 'src/front-components/utils/compute-granola-folder-tree.util';+import { countNestedGranolaFolders } from 'src/front-components/utils/count-nested-granola-folders.util';+import { hasSelectedGranolaDescendant } from 'src/front-components/utils/has-selected-granola-descendant.util';++const StyledItem = styled.li`+ position: relative;+`;++const StyledNestedList = styled.ul`+ list-style: none;+ margin: 0;+ padding: 0;+`;++const StyledCollapsibleWrapper = styled.div<{ $isExpanded: boolean }>`+ display: grid;+ grid-template-rows: ${({ $isExpanded }) => ($isExpanded ? '1fr' : '0fr')};+ transition: grid-template-rows+ calc(${() => themeCssVariables.animation.duration.fast} * 1s) ease-out;+`;++const StyledCollapsibleContent = styled.div`+ overflow: hidden;+`;++const StyledRow = styled.div<{ $depth: number }>`+ align-items: center;+ border-radius: ${() => themeCssVariables.border.radius.sm};+ cursor: pointer;+ display: flex;+ height: 28px;+ padding-left: ${({ $depth }) => $depth * GRANOLA_FOLDER_TREE_INDENT_PIXELS}px;+ user-select: none;++ &:hover {+ background-color: ${() => themeCssVariables.background.transparent.lighter};+ }+`;++const StyledFolderContent = styled.div`+ align-items: center;+ color: ${() => themeCssVariables.font.color.tertiary};+ display: flex;+ flex: 1;+ gap: ${() => themeCssVariables.spacing[2]};+ min-width: 0;+ padding-left: ${() => themeCssVariables.spacing[1]};+ padding-right: ${() => themeCssVariables.spacing[1]};+`;++const StyledFolderName = styled.span<{ $disabled: boolean }>`+ color: ${({ $disabled }) =>+ $disabled+ ? themeCssVariables.font.color.tertiary+ : themeCssVariables.font.color.primary};+ font-size: ${() => themeCssVariables.font.size.md};+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+`;++const StyledRightSection = styled.div`+ align-items: center;+ display: flex;+ flex-shrink: 0;+ gap: ${() => themeCssVariables.spacing[1]};+ margin-left: auto;+`;++const StyledChildCount = styled.span`+ color: ${() => themeCssVariables.font.color.tertiary};+ font-size: ${() => themeCssVariables.font.size.sm};+ min-width: ${() => themeCssVariables.spacing[3]};+ text-align: right;+`;++const StyledExpandButton = styled.button`+ align-items: center;+ background: none;+ border: none;+ color: ${() => themeCssVariables.font.color.tertiary};+ cursor: pointer;+ display: flex;+ height: ${() => themeCssVariables.spacing[4]};+ justify-content: center;+ padding: 0;+ width: ${() => themeCssVariables.spacing[4]};++ &:hover {+ color: ${() => themeCssVariables.font.color.primary};+ }+`;++type GranolaFolderTreeItemProps = {+ node: GranolaFolderTreeNode;+ depth?: number;+ isLast?: boolean;+ parentsIsLastList?: boolean[];+ selectedFolderIds: Set<string>;+ coveredFolderIds: Set<string>;+ isSelectionFull: boolean;+ onToggleFolder: (folderId: string, checked: boolean) => void;+};++export const GranolaFolderTreeItem = ({+ node,+ depth = 0,+ isLast = false,+ parentsIsLastList = [],+ selectedFolderIds,+ coveredFolderIds,+ isSelectionFull,+ onToggleFolder,+}: GranolaFolderTreeItemProps) => {+ const [isExpanded, setIsExpanded] = useState(true);+ const { folder, children } = node;+ const hasChildren = children.length > 0;+ const isSelected = selectedFolderIds.has(folder.id);+ const isCovered = coveredFolderIds.has(folder.id);+ const isChecked = isSelected || isCovered;+ const isIndeterminate =+ !isChecked && hasSelectedGranolaDescendant(node, selectedFolderIds);+ const isOnlySelectedFolder = isSelected && selectedFolderIds.size === 1;+ const isUnavailable = isCovered || (isSelectionFull && !isChecked);+ const isDisabled = isUnavailable || isOnlySelectedFolder;+ const FolderIcon = depth > 0 ? IconFolderRoot : IconFolder;+ const childParentsIsLastList =+ depth > 0 ? [...parentsIsLastList, isLast] : parentsIsLastList;++ return (+ <StyledItem>+ <StyledRow+ $depth={depth}+ onClick={() => hasChildren && setIsExpanded(!isExpanded)}+ >+ {depth > 0 && (+ <GranolaFolderTreeBreadcrumb+ depth={depth}+ isLast={isLast}+ parentsIsLastList={parentsIsLastList}+ />+ )}+ <StyledFolderContent>+ <FolderIcon size={ICON.size.md} stroke={ICON.stroke.sm} />+ <StyledFolderName $disabled={isUnavailable} title={folder.name}>+ {folder.name}+ </StyledFolderName>+ <StyledRightSection>+ {hasChildren && (+ <>+ <StyledChildCount>+ {countNestedGranolaFolders(node)}+ </StyledChildCount>+ <StyledExpandButton+ type="button"+ aria-label={+ isExpanded ? t('Collapse folder') : t('Expand folder')+ }+ onClick={(event) => {+ event.stopPropagation();+ setIsExpanded(!isExpanded);+ }}+ >+ {isExpanded ? (+ <IconChevronUp size={ICON.size.md} />+ ) : (+ <IconChevronDown size={ICON.size.md} />+ )}+ </StyledExpandButton>+ </>+ )}+ <span onClick={(event) => event.stopPropagation()}>+ <Checkbox+ checked={isChecked}+ indeterminate={isIndeterminate}+ disabled={isDisabled}+ aria-label={folder.name}+ onChange={(checked) => onToggleFolder(folder.id, checked)}+ />+ </span>+ </StyledRightSection>+ </StyledFolderContent>+ </StyledRow>+ {hasChildren && (+ <StyledCollapsibleWrapper $isExpanded={isExpanded}>+ <StyledCollapsibleContent>+ <StyledNestedList>+ {children.map((child, index) => (+ <GranolaFolderTreeItem+ key={child.folder.id}+ node={child}+ depth={depth + 1}+ isLast={index === children.length - 1}+ parentsIsLastList={childParentsIsLastList}+ selectedFolderIds={selectedFolderIds}+ coveredFolderIds={coveredFolderIds}+ isSelectionFull={isSelectionFull}+ onToggleFolder={onToggleFolder}+ />+ ))}+ </StyledNestedList>+ </StyledCollapsibleContent>+ </StyledCollapsibleWrapper>+ )}+ </StyledItem>+ );+};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 8f3b20e18e0..2a0a61d5963 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,6 +15,7 @@ import {type ThemeType,} from 'twenty-ui/theme-constants';+import { GranolaFolderSection } from 'src/front-components/components/GranolaFolderSection';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';@@ -198,7 +199,12 @@ export const GranolaSettings = () => {isGranolaConnectionReady(state.status) &&!isConnecting &&!isRegistering &&- !isDefined(registrationError) && <GranolaImportHistorySection />}+ !isDefined(registrationError) && (+ <>+ <GranolaFolderSection />+ <GranolaImportHistorySection />+ </>+ )}</>)}</StyledContainer>diff --git a/packages/twenty-apps/public/granola/src/front-components/components/Radio.tsx b/packages/twenty-apps/public/granola/src/front-components/components/Radio.tsxnew file mode 100644index 00000000000..63f807d7134--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/Radio.tsx@@ -0,0 +1,82 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++// twenty-ui's Radio is a base-ui control whose click handler constructs a+// PointerEvent, which the front component sandbox does not provide.+const RADIO_CONTROL_SIZE_PIXELS = 16;+const RADIO_INDICATOR_SIZE_PIXELS = 6;++const StyledRadio = styled.button`+ align-items: center;+ appearance: none;+ background: transparent;+ border: none;+ cursor: pointer;+ display: inline-flex;+ justify-content: center;+ padding: 3px;++ &:disabled {+ cursor: not-allowed;+ opacity: 0.32;+ }+`;++const StyledControl = styled.span`+ align-items: center;+ background-color: transparent;+ border: 1px solid ${() => themeCssVariables.font.color.secondary};+ border-radius: 50%;+ box-sizing: border-box;+ corner-shape: round;+ display: inline-flex;+ height: ${RADIO_CONTROL_SIZE_PIXELS}px;+ justify-content: center;+ transition: transform+ calc(${() => themeCssVariables.animation.duration.normal} * 1s) ease;+ width: ${RADIO_CONTROL_SIZE_PIXELS}px;++ &[data-checked='true'] {+ background-color: ${() => themeCssVariables.color.blue};+ border-color: ${() => themeCssVariables.color.blue};+ transform: scale(1.05);+ }+`;++const StyledIndicator = styled.span`+ background-color: ${() => themeCssVariables.background.primary};+ border-radius: 50%;+ corner-shape: round;+ height: ${RADIO_INDICATOR_SIZE_PIXELS}px;+ width: ${RADIO_INDICATOR_SIZE_PIXELS}px;+`;++type RadioProps = {+ checked: boolean;+ disabled?: boolean;+ 'aria-labelledby'?: string;+ 'aria-describedby'?: string;+ onSelect: () => void;+};++export const Radio = ({+ checked,+ disabled = false,+ 'aria-labelledby': ariaLabelledBy,+ 'aria-describedby': ariaDescribedBy,+ onSelect,+}: RadioProps) => (+ <StyledRadio+ type="button"+ role="radio"+ aria-checked={checked ? 'true' : 'false'}+ aria-labelledby={ariaLabelledBy}+ aria-describedby={ariaDescribedBy}+ disabled={disabled}+ onClick={onSelect}+ >+ <StyledControl data-checked={checked ? 'true' : 'false'}>+ {checked && <StyledIndicator />}+ </StyledControl>+ </StyledRadio>+);diff --git a/packages/twenty-apps/public/granola/src/front-components/components/Separator.tsx b/packages/twenty-apps/public/granola/src/front-components/components/Separator.tsxnew file mode 100644index 00000000000..7f83a37289c--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/Separator.tsx@@ -0,0 +1,14 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++const StyledHr = styled.hr`+ border: none;+ border-top: 1px solid ${() => themeCssVariables.border.color.light};+ margin: 0px;+ margin-left: ${() => themeCssVariables.spacing[4]};+ margin-right: ${() => themeCssVariables.spacing[4]};+`;++export const Separator = () => {+ return <StyledHr />;+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/SettingsRadioCard.tsx b/packages/twenty-apps/public/granola/src/front-components/components/SettingsRadioCard.tsxnew file mode 100644index 00000000000..80387435bf8--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/SettingsRadioCard.tsx@@ -0,0 +1,109 @@+import styled from '@emotion/styled';+import { Fragment, useId } from 'react';+import { isDefined } from 'twenty-sdk/utils';+import { OverflowingTextWithTooltip } from 'twenty-ui/surfaces';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { Radio } from 'src/front-components/components/Radio';+import { Separator } from 'src/front-components/components/Separator';+import {+ StyledSettingsCardDescription,+ StyledSettingsCardTextContainer,+ StyledSettingsCardTitle,+} from 'src/front-components/components/SettingsCardContentBase';+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';++const StyledOptionRow = styled.div<{ $disabled: boolean }>`+ align-items: center;+ background-color: ${() => themeCssVariables.background.secondary};+ cursor: ${({ $disabled }) => ($disabled ? 'default' : 'pointer')};+ display: flex;+ gap: ${() => themeCssVariables.spacing[4]};+ padding: ${() => themeCssVariables.spacing[4]};+ pointer-events: ${({ $disabled }) => ($disabled ? 'none' : 'auto')};++ &:hover {+ background: ${() => themeCssVariables.background.transparent.lighter};+ }+`;++const StyledRadioContainer = styled.span`+ align-items: center;+ display: flex;+ flex-shrink: 0;+ margin-left: auto;+`;++const StyledExpandedContent = styled.div`+ background-color: ${() => themeCssVariables.background.secondary};+ padding: 0 ${() => themeCssVariables.spacing[4]}+ ${() => themeCssVariables.spacing[4]};+`;++export type SettingsRadioCardOption<TValue extends string> = {+ value: TValue;+ cardMedia: React.ReactNode;+ title: string;+ description: string;+ expandedContent?: React.ReactNode;+};++type SettingsRadioCardProps<TValue extends string> = {+ options: SettingsRadioCardOption<TValue>[];+ value: TValue;+ disabled?: boolean;+ onChange: (value: TValue) => void;+};++export const SettingsRadioCard = <TValue extends string>({+ options,+ value,+ disabled = false,+ onChange,+}: SettingsRadioCardProps<TValue>) => {+ const groupId = useId();++ return (+ <StyledSettingsCard role="radiogroup">+ {options.map((option, index) => {+ const isSelected = option.value === value;+ const titleId = `${groupId}-${index}-title`;+ const descriptionId = `${groupId}-${index}-description`;++ return (+ <Fragment key={option.value}>+ <StyledOptionRow+ $disabled={disabled}+ onClick={() => onChange(option.value)}+ >+ {option.cardMedia}+ <StyledSettingsCardTextContainer>+ <StyledSettingsCardTitle id={titleId}>+ {option.title}+ </StyledSettingsCardTitle>+ <StyledSettingsCardDescription id={descriptionId}>+ <OverflowingTextWithTooltip text={option.description} />+ </StyledSettingsCardDescription>+ </StyledSettingsCardTextContainer>+ <StyledRadioContainer>+ <Radio+ checked={isSelected}+ disabled={disabled}+ aria-labelledby={titleId}+ aria-describedby={descriptionId}+ onSelect={() => onChange(option.value)}+ />+ </StyledRadioContainer>+ </StyledOptionRow>+ {isSelected && isDefined(option.expandedContent) && (+ <StyledExpandedContent>+ {option.expandedContent}+ </StyledExpandedContent>+ )}+ {index < options.length - 1 && <Separator />}+ </Fragment>+ );+ })}+ </StyledSettingsCard>+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/hooks/use-autosave-granola-folder-selection.ts b/packages/twenty-apps/public/granola/src/front-components/hooks/use-autosave-granola-folder-selection.tsnew file mode 100644index 00000000000..8827976a29a--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/hooks/use-autosave-granola-folder-selection.ts@@ -0,0 +1,44 @@+import { useState } from 'react';+import { t } from 'twenty-sdk/front-component';++import { createSaveQueue } from 'src/front-components/utils/create-save-queue.util';+import { saveGranolaFolderSelectionOrThrow } from 'src/front-components/utils/save-granola-folder-selection-or-throw.util';++type UseAutosaveGranolaFolderSelectionParams = {+ onSaveStart: () => void;+ onSaveSuccess: (folderIds: string[]) => void;+ onSaveError: (message: string) => void;+};++export const useAutosaveGranolaFolderSelection = ({+ onSaveStart,+ onSaveSuccess,+ onSaveError,+}: UseAutosaveGranolaFolderSelectionParams) => {+ const [saveQueue] = useState(() =>+ createSaveQueue<string[]>({+ saveValue: async (folderIds, isSupersededValue) => {+ onSaveStart();++ try {+ const savedFolderIds =+ await saveGranolaFolderSelectionOrThrow(folderIds);++ if (!isSupersededValue()) {+ onSaveSuccess(savedFolderIds);+ }+ } catch (error) {+ if (!isSupersededValue()) {+ onSaveError(+ error instanceof Error+ ? error.message+ : t('Could not save the folder selection. Try again.'),+ );+ }+ }+ },+ }),+ );++ return { save: saveQueue.enqueueSave };+};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 ba6b5c03108..9ee68a15ab9 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,7 @@ import { GranolaSettings } from 'src/front-components/components/GranolaSettingsexport default defineSettingsFrontComponent({universalIdentifier: GRANOLA_SETTINGS_UNIVERSAL_IDENTIFIER,name: 'granola-settings',- description: 'Granola account connection and history import settings.',+ description:+ 'Granola account connection, folder, and history import settings.',component: GranolaSettings,});diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-folder-policy.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-folder-policy.type.tsnew file mode 100644index 00000000000..cae1aa05aee--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-folder-policy.type.ts@@ -0,0 +1 @@+export type GranolaFolderPolicy = 'ALL_FOLDERS' | 'SELECTED_FOLDERS';diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-settings-folder.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-settings-folder.type.tsnew file mode 100644index 00000000000..e864a7f1969--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-settings-folder.type.ts@@ -0,0 +1,11 @@+import { z } from 'zod';++export const GRANOLA_SETTINGS_FOLDER_SCHEMA = z.object({+ id: z.string(),+ name: z.string(),+ parent_folder_id: z.string().nullable(),+});++export type GranolaSettingsFolder = z.infer<+ typeof GRANOLA_SETTINGS_FOLDER_SCHEMA+>;diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-ancestor-ids.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-ancestor-ids.test.tsnew file mode 100644index 00000000000..29f92a86ce2--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-ancestor-ids.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { computeGranolaFolderAncestorIds } from 'src/front-components/utils/compute-granola-folder-ancestor-ids.util';++describe('computeGranolaFolderAncestorIds', () => {+ it('lists ancestors nearest first and stays finite on missing parents and cycles', () => {+ const ancestorIds = computeGranolaFolderAncestorIds([+ { id: 'root', name: 'Sales', parent_folder_id: null },+ { id: 'parent', name: 'Europe', parent_folder_id: 'root' },+ { id: 'child', name: 'Calls', parent_folder_id: 'parent' },+ { id: 'orphan', name: 'Old', parent_folder_id: 'missing' },+ { id: 'cycle', name: 'Team', parent_folder_id: 'cycle' },+ ]);++ expect(ancestorIds.get('child')).toEqual(['parent', 'root']);+ expect(ancestorIds.get('root')).toEqual([]);+ expect(ancestorIds.get('orphan')).toEqual([]);+ expect(ancestorIds.get('cycle')).toEqual([]);+ });+});diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-tree.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-tree.test.tsnew file mode 100644index 00000000000..64f76a0c555--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-tree.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';++import { computeGranolaFolderTree } from 'src/front-components/utils/compute-granola-folder-tree.util';++const toNames = (+ nodes: ReturnType<typeof computeGranolaFolderTree>,+): unknown[] => nodes.map((node) => [node.folder.name, toNames(node.children)]);++describe('computeGranolaFolderTree', () => {+ it('nests children under their parent sorted by name at every level', () => {+ expect(+ toNames(+ computeGranolaFolderTree([+ { id: 'child', name: 'Calls', parent_folder_id: 'parent' },+ { id: 'sibling', name: 'Sales - EMEA', parent_folder_id: null },+ { id: 'root', name: 'Sales', parent_folder_id: null },+ { id: 'parent', name: 'Europe', parent_folder_id: 'root' },+ { id: 'asia', name: 'Asia', parent_folder_id: 'root' },+ ]),+ ),+ ).toEqual([+ [+ 'Sales',+ [+ ['Asia', []],+ ['Europe', [['Calls', []]]],+ ],+ ],+ ['Sales - EMEA', []],+ ]);+ });++ it('lifts folders with an inaccessible parent or cyclic ancestry to the top level', () => {+ expect(+ toNames(+ computeGranolaFolderTree([+ { id: 'orphan', name: 'Calls', parent_folder_id: 'missing' },+ { id: 'self', name: 'Team', parent_folder_id: 'self' },+ { id: 'first', name: 'Loop A', parent_folder_id: 'second' },+ { id: 'second', name: 'Loop B', parent_folder_id: 'first' },+ ]),+ ),+ ).toEqual([+ ['Calls', []],+ ['Team', []],+ ['Loop A', [['Loop B', []]]],+ ]);+ });+});diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/create-save-queue.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/create-save-queue.test.tsnew file mode 100644index 00000000000..5e52b3694de--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/create-save-queue.test.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createSaveQueue } from 'src/front-components/utils/create-save-queue.util';++describe('createSaveQueue', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('serializes saves and replaces pending values with the latest selection', async () => {+ const saveValue = vi.fn(+ async (_value: string[], _isSupersededValue: () => boolean) => {+ await new Promise<void>((resolve) => setTimeout(resolve, 100));+ },+ );+ const { enqueueSave } = createSaveQueue({ saveValue });++ enqueueSave(['first']);++ const isFirstValueSuperseded = saveValue.mock.calls[0][1];++ expect(isFirstValueSuperseded()).toBe(false);++ enqueueSave(['second']);+ enqueueSave(['latest']);++ expect(saveValue).toHaveBeenCalledTimes(1);+ expect(isFirstValueSuperseded()).toBe(true);++ await vi.advanceTimersByTimeAsync(100);++ expect(saveValue.mock.calls.map(([value]) => value)).toEqual([+ ['first'],+ ['latest'],+ ]);+ expect(saveValue.mock.calls[1][1]()).toBe(false);++ await vi.runAllTimersAsync();++ expect(saveValue).toHaveBeenCalledTimes(2);+ });++ it('starts saving again after the queue has drained, including an empty selection', async () => {+ const saveValue = vi.fn(async (_value: string[]) => {});+ const { enqueueSave } = createSaveQueue({ saveValue });++ enqueueSave(['first']);+ await vi.runAllTimersAsync();++ enqueueSave([]);+ await vi.runAllTimersAsync();++ expect(saveValue.mock.calls.map(([value]) => value)).toEqual([+ ['first'],+ [],+ ]);+ });++ it('drains values enqueued from within a save without overlapping saves', async () => {+ const savedValues: string[][] = [];+ const saveValue = vi.fn(+ async (value: string[], isSupersededValue: () => boolean) => {+ if (value.includes('first')) {+ enqueueSave(['next']);+ expect(saveValue).toHaveBeenCalledTimes(1);+ expect(isSupersededValue()).toBe(true);+ }++ await new Promise<void>((resolve) => setTimeout(resolve, 100));+ savedValues.push(value);+ },+ );+ const { enqueueSave } = createSaveQueue({ saveValue });++ enqueueSave(['first']);+ await vi.advanceTimersByTimeAsync(100);++ expect(savedValues).toEqual([['first']]);+ expect(saveValue).toHaveBeenCalledTimes(2);++ await vi.runAllTimersAsync();++ expect(savedValues).toEqual([['first'], ['next']]);+ });+});diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-ancestor-ids.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-ancestor-ids.util.tsnew file mode 100644index 00000000000..7cde413421c--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-ancestor-ids.util.ts@@ -0,0 +1,31 @@+import { isDefined } from 'twenty-sdk/utils';++import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';++export const computeGranolaFolderAncestorIds = (+ folders: GranolaSettingsFolder[],+): Map<string, string[]> => {+ const foldersById = new Map(folders.map((folder) => [folder.id, folder]));++ return new Map(+ folders.map((folder) => {+ const ancestorIds: string[] = [];+ const visitedIds = new Set([folder.id]);+ let parentId = folder.parent_folder_id;++ while (isDefined(parentId) && !visitedIds.has(parentId)) {+ visitedIds.add(parentId);+ const parent = foldersById.get(parentId);++ if (!isDefined(parent)) {+ break;+ }++ ancestorIds.push(parent.id);+ parentId = parent.parent_folder_id;+ }++ return [folder.id, ancestorIds];+ }),+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-tree.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-tree.util.tsnew file mode 100644index 00000000000..0fc1815663b--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-tree.util.ts@@ -0,0 +1,66 @@+import { isDefined } from 'twenty-sdk/utils';++import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';++export type GranolaFolderTreeNode = {+ folder: GranolaSettingsFolder;+ children: GranolaFolderTreeNode[];+};++const compareByName = (+ left: GranolaSettingsFolder,+ right: GranolaSettingsFolder,+) => left.name.localeCompare(right.name);++export const computeGranolaFolderTree = (+ folders: GranolaSettingsFolder[],+): GranolaFolderTreeNode[] => {+ const folderIds = new Set(folders.map((folder) => folder.id));+ const childrenByParentId = new Map<string, GranolaSettingsFolder[]>();+ const rootFolders: GranolaSettingsFolder[] = [];++ for (const folder of folders) {+ const parentId = folder.parent_folder_id;++ if (+ !isDefined(parentId) ||+ parentId === folder.id ||+ !folderIds.has(parentId)+ ) {+ rootFolders.push(folder);+ continue;+ }++ childrenByParentId.set(parentId, [+ ...(childrenByParentId.get(parentId) ?? []),+ folder,+ ]);+ }++ const visitedIds = new Set<string>();++ const buildNode = (folder: GranolaSettingsFolder): GranolaFolderTreeNode => {+ visitedIds.add(folder.id);++ const children = (childrenByParentId.get(folder.id) ?? [])+ .filter((child) => !visitedIds.has(child.id))+ .sort(compareByName);++ return { folder, children: children.map(buildNode) };+ };++ const tree = rootFolders.sort(compareByName).map(buildNode);++ // Folders whose ancestry loops never reach a root, so they surface at the top level.+ const unreachableFolders = folders+ .filter((folder) => !visitedIds.has(folder.id))+ .sort(compareByName);++ for (const folder of unreachableFolders) {+ if (!visitedIds.has(folder.id)) {+ tree.push(buildNode(folder));+ }+ }++ return tree;+};diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/count-nested-granola-folders.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/count-nested-granola-folders.util.tsnew file mode 100644index 00000000000..fa013874832--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/count-nested-granola-folders.util.ts@@ -0,0 +1,9 @@+import { type GranolaFolderTreeNode } from 'src/front-components/utils/compute-granola-folder-tree.util';++export const countNestedGranolaFolders = (+ node: GranolaFolderTreeNode,+): number =>+ node.children.reduce(+ (count, child) => count + 1 + countNestedGranolaFolders(child),+ 0,+ );diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/create-save-queue.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/create-save-queue.util.tsnew file mode 100644index 00000000000..e6807624106--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/create-save-queue.util.ts@@ -0,0 +1,44 @@+import { isUndefined } from '@sniptt/guards';++type CreateSaveQueueParams<TValue> = {+ saveValue: (value: TValue, isSupersededValue: () => boolean) => Promise<void>;+};++export const createSaveQueue = <TValue>({+ saveValue,+}: CreateSaveQueueParams<TValue>) => {+ let queuedValue: TValue | undefined;+ let isSaving = false;++ const persistQueuedValues = async () => {+ if (isSaving) {+ return;+ }++ isSaving = true;++ try {+ while (!isUndefined(queuedValue)) {+ const valueToSave = queuedValue;++ queuedValue = undefined;++ await saveValue(valueToSave, () => !isUndefined(queuedValue));+ }+ } finally {+ isSaving = false;++ if (!isUndefined(queuedValue)) {+ void persistQueuedValues();+ }+ }+ };++ const enqueueSave = (value: TValue) => {+ queuedValue = value;++ void persistQueuedValues();+ };++ return { enqueueSave };+};diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folders-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folders-or-throw.util.tsnew file mode 100644index 00000000000..d37e4ceb5f5--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folders-or-throw.util.ts@@ -0,0 +1,31 @@+import { RestApiClient } from 'twenty-client-sdk/rest';+import { z } from 'zod';++import { GRANOLA_FOLDERS_ROUTE_PATH } from 'src/constants/granola-folders-route-path';+import { GRANOLA_SETTINGS_FOLDER_SCHEMA } from 'src/front-components/types/granola-settings-folder.type';++const FOLDERS_RESULT_SCHEMA = z.discriminatedUnion('success', [+ z.object({+ success: z.literal(true),+ folders: z.array(GRANOLA_SETTINGS_FOLDER_SCHEMA),+ folderIds: z.array(z.string()),+ pendingFolderIds: z.array(z.string()).optional(),+ }),+ z.object({ success: z.literal(false), error: z.string() }),+]);++export const fetchGranolaFoldersOrThrow = async () => {+ const result = FOLDERS_RESULT_SCHEMA.parse(+ await new RestApiClient().get(`/s${GRANOLA_FOLDERS_ROUTE_PATH}`),+ );++ if (!result.success) {+ throw new Error(result.error);+ }++ return {+ folders: result.folders,+ selectedFolderIds: result.folderIds,+ pendingFolderIds: result.pendingFolderIds,+ };+};diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/has-selected-granola-descendant.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/has-selected-granola-descendant.util.tsnew file mode 100644index 00000000000..45d58ea36f9--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/has-selected-granola-descendant.util.ts@@ -0,0 +1,11 @@+import { type GranolaFolderTreeNode } from 'src/front-components/utils/compute-granola-folder-tree.util';++export const hasSelectedGranolaDescendant = (+ node: GranolaFolderTreeNode,+ selectedFolderIds: Set<string>,+): boolean =>+ node.children.some(+ (child) =>+ selectedFolderIds.has(child.folder.id) ||+ hasSelectedGranolaDescendant(child, selectedFolderIds),+ );diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-folder-selection-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-folder-selection-or-throw.util.tsnew file mode 100644index 00000000000..36f1ff69e5a--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-folder-selection-or-throw.util.ts@@ -0,0 +1,25 @@+import { RestApiClient } from 'twenty-client-sdk/rest';+import { z } from 'zod';++import { GRANOLA_FOLDER_SELECTION_ROUTE_PATH } from 'src/constants/granola-folder-selection-route-path';++const SAVE_RESULT_SCHEMA = z.discriminatedUnion('success', [+ z.object({ success: z.literal(true), folderIds: z.array(z.string()) }),+ z.object({ success: z.literal(false), error: z.string() }),+]);++export const saveGranolaFolderSelectionOrThrow = async (+ folderIds: string[],+): Promise<string[]> => {+ const result = SAVE_RESULT_SCHEMA.parse(+ await new RestApiClient().post(`/s${GRANOLA_FOLDER_SELECTION_ROUTE_PATH}`, {+ folderIds,+ }),+ );++ if (!result.success) {+ throw new Error(result.error);+ }++ return result.folderIds;+};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.tsindex 405a37872f7..8aa7d9c0ee1 100644--- 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.ts@@ -6,6 +6,7 @@ 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 { assertGranolaFolderSelectionReadyOrThrow } from 'src/logic-functions/utils/assert-granola-folder-selection-ready-or-throw.util';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';@@ -16,6 +17,7 @@ export const granolaBackfillNoteHandler = async (payload: GranolaBackfillNotePayload,) => {try {+ await assertGranolaFolderSelectionReadyOrThrow();const registration = await findGranolaRegistrationForCurrentKey();if (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.tsindex 92bdeaa674a..522a5e0e2a5 100644--- 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.ts@@ -8,6 +8,7 @@ import {} 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 { assertGranolaFolderSelectionReadyOrThrow } from 'src/logic-functions/utils/assert-granola-folder-selection-ready-or-throw.util';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';@@ -22,6 +23,7 @@ export const granolaBackfillWorkerHandler = async (payload: GranolaBackfillWorkerPayload,) => {try {+ await assertGranolaFolderSelectionReadyOrThrow();const registration = await findGranolaRegistrationForCurrentKey();if (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.tsindex 5899a114138..02821489cb8 100644--- 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.ts@@ -9,6 +9,7 @@ import { GRANOLA_DAILY_CATCH_UP_UNIVERSAL_IDENTIFIER } from 'src/constants/univeimport { 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';+import { reconcileGranolaFolderSelectionOrThrow } from 'src/logic-functions/utils/reconcile-granola-folder-selection-or-throw.util';export const granolaDailyCatchUpHandler = async () => {const registration = await findGranolaRegistrationForCurrentKey();@@ -17,7 +18,8 @@ export const granolaDailyCatchUpHandler = async () => {return { success: true, skipped: true };}- await enqueueGranolaInitialBackfillOrThrow(registration);+ await reconcileGranolaFolderSelectionOrThrow();+ await enqueueGranolaInitialBackfillOrThrow();const result = await enqueueGranolaBackfillOrThrow({updatedAfter: new Date(Date.now() - GRANOLA_CATCH_UP_WINDOW_DAYS * GRANOLA_MILLISECONDS_PER_DAY,diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-folders.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-folders.tsnew file mode 100644index 00000000000..e5097764332--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-folders.ts@@ -0,0 +1,44 @@+import { defineLogicFunction } from 'twenty-sdk/define';+import { kv } from 'twenty-sdk/logic-function';++import { GRANOLA_FOLDERS_ROUTE_PATH } from 'src/constants/granola-folders-route-path';+import { GRANOLA_PENDING_FOLDER_SELECTION_KEY } from 'src/constants/granola.constant';+import { GRANOLA_FOLDERS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type GranolaPendingFolderSelection } from 'src/logic-functions/types/granola-pending-folder-selection.type';+import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';+import { listAllGranolaFoldersOrThrow } from 'src/logic-functions/utils/list-all-granola-folders-or-throw.util';++export const granolaFoldersHandler = async () => {+ if (!(await currentUserCanManageGranolaOrThrow())) {+ return {+ success: false,+ error: 'Application settings permission is required.',+ };+ }++ const registration = await findGranolaRegistrationForCurrentKey();+ const pending = await kv.get<GranolaPendingFolderSelection>(+ GRANOLA_PENDING_FOLDER_SELECTION_KEY,+ );++ return {+ success: true,+ folders: await listAllGranolaFoldersOrThrow(),+ folderIds: registration?.folderIds ?? [],+ pendingFolderIds: pending?.folderIds,+ };+};++export default defineLogicFunction({+ universalIdentifier: GRANOLA_FOLDERS_UNIVERSAL_IDENTIFIER,+ name: 'granola-folders',+ description: 'Lists accessible Granola folders for the settings picker.',+ timeoutSeconds: 60,+ handler: granolaFoldersHandler,+ httpRouteTriggerSettings: {+ path: GRANOLA_FOLDERS_ROUTE_PATH,+ httpMethod: 'GET',+ isAuthRequired: true,+ },+});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 44e56b30595..6c9e79676d7 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@@ -6,6 +6,7 @@ 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 { reconcileGranolaFolderSelectionOrThrow } from 'src/logic-functions/utils/reconcile-granola-folder-selection-or-throw.util';import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';export const granolaRegisterWebhookHandler = async () => {@@ -18,7 +19,14 @@ export const granolaRegisterWebhookHandler = async () => {try {const registration = await ensureGranolaWebhookRegistrationOrThrow();try {- await enqueueGranolaInitialBackfillOrThrow(registration);+ await reconcileGranolaFolderSelectionOrThrow();+ } catch (error) {+ console.error(+ `[granola] Could not apply the pending folder selection for registration ${registration.registrationId}. ${toErrorMessage(error)}`,+ );+ }+ try {+ await enqueueGranolaInitialBackfillOrThrow();} catch (error) {console.error(`[granola] Could not queue the initial import for registration ${registration.registrationId}; the daily catch-up will retry. ${toErrorMessage(error)}`,diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-update-webhook-folders.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-update-webhook-folders.tsnew file mode 100644index 00000000000..2c38983f742--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-update-webhook-folders.ts@@ -0,0 +1,101 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { kv, RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';+import { z } from 'zod';++import {+ GRANOLA_FOLDER_ID_PATTERN,+ GRANOLA_FOLDER_SELECTION_LIMIT,+} from 'src/constants/granola-api.constant';+import { GRANOLA_FOLDER_SELECTION_ROUTE_PATH } from 'src/constants/granola-folder-selection-route-path';+import { GRANOLA_PENDING_FOLDER_SELECTION_KEY } from 'src/constants/granola.constant';+import { GRANOLA_UPDATE_WEBHOOK_FOLDERS_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 { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';+import { getGranolaSelectedParentFolders } from 'src/logic-functions/utils/get-granola-selected-parent-folders.util';+import { listAllGranolaFoldersOrThrow } from 'src/logic-functions/utils/list-all-granola-folders-or-throw.util';+import { reconcileGranolaFolderSelectionOrThrow } from 'src/logic-functions/utils/reconcile-granola-folder-selection-or-throw.util';++const GRANOLA_FOLDER_SELECTION_SCHEMA = z.object({+ folderIds: z+ .array(z.string().regex(GRANOLA_FOLDER_ID_PATTERN))+ .max(GRANOLA_FOLDER_SELECTION_LIMIT),+});++export const granolaUpdateWebhookFoldersHandler = async (+ payload: RoutePayload<unknown>,+) => {+ const parsed = GRANOLA_FOLDER_SELECTION_SCHEMA.safeParse(payload.body);++ if (!parsed.success) {+ return {+ success: false,+ error: `Select up to ${GRANOLA_FOLDER_SELECTION_LIMIT} valid Granola folders.`,+ };+ }++ 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 choosing folders.',+ };+ }++ const folders =+ parsed.data.folderIds.length > 0+ ? await listAllGranolaFoldersOrThrow()+ : [];+ const accessibleIds = new Set(folders.map((folder) => folder.id));++ if (parsed.data.folderIds.some((folderId) => !accessibleIds.has(folderId))) {+ return {+ success: false,+ error: 'A selected folder is not accessible to this key.',+ };+ }++ const folderIds = getGranolaSelectedParentFolders({+ folderIds: parsed.data.folderIds,+ folders,+ });+ await kv.set(GRANOLA_PENDING_FOLDER_SELECTION_KEY, { folderIds });++ try {+ await reconcileGranolaFolderSelectionOrThrow();+ } catch (error) {+ if (+ error instanceof RetryableLogicFunctionError ||+ error instanceof GranolaApiError+ ) {+ return { success: false, error: error.message };+ }++ throw error;+ }++ return { success: true, folderIds };+};++export default defineLogicFunction({+ universalIdentifier: GRANOLA_UPDATE_WEBHOOK_FOLDERS_UNIVERSAL_IDENTIFIER,+ name: 'granola-update-webhook-folders',+ description:+ 'Sets the folders used by both Granola webhook deliveries and history imports.',+ timeoutSeconds: 60,+ handler: granolaUpdateWebhookFoldersHandler,+ httpRouteTriggerSettings: {+ path: GRANOLA_FOLDER_SELECTION_ROUTE_PATH,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook.tsindex 79a753b3202..8853a9783bd 100644--- a/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook.ts+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-webhook.ts@@ -15,6 +15,7 @@ import { GRANOLA_WEBHOOK_PAYLOAD_SCHEMA } from 'src/logic-functions/types/granolimport { GranolaInvalidResponseError } from 'src/logic-functions/types/granola-invalid-response-error';import { GranolaTranscriptLimitError } from 'src/logic-functions/types/granola-transcript-limit-error';import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';+import { assertGranolaFolderSelectionReadyOrThrow } from 'src/logic-functions/utils/assert-granola-folder-selection-ready-or-throw.util';import { buildRetryableGranolaError } from 'src/logic-functions/utils/build-retryable-granola-error.util';import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';import { getGranolaApiKeyFingerprint } from 'src/logic-functions/utils/get-granola-api-key-fingerprint.util';@@ -79,6 +80,7 @@ export const granolaWebhookHandler = async ({if (!parsed.success || parsed.data.event_id !== webhookId) {return { success: false, error: 'Invalid Granola webhook event' };}+ await assertGranolaFolderSelectionReadyOrThrow();const result = await syncGranolaNoteToCallRecordingOrThrow({coreApiClient: new CoreApiClient({ runAs: 'application' }),client: createGranolaClientOrThrow(),diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-pending-folder-selection.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-pending-folder-selection.type.tsnew file mode 100644index 00000000000..42912ec4ef9--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-pending-folder-selection.type.ts@@ -0,0 +1,3 @@+export type GranolaPendingFolderSelection = {+ folderIds: string[];+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-selected-parent-folders.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-selected-parent-folders.test.tsnew file mode 100644index 00000000000..63680589b61--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-selected-parent-folders.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import { getGranolaSelectedParentFolders } from 'src/logic-functions/utils/get-granola-selected-parent-folders.util';++const folders = [+ { id: 'root', parent_folder_id: null },+ { id: 'child', parent_folder_id: 'root' },+ { id: 'grandchild', parent_folder_id: 'child' },+ { id: 'other', parent_folder_id: null },+];++describe('getGranolaSelectedParentFolders', () => {+ it('removes duplicates and descendants already covered by a selected parent', () => {+ expect(+ getGranolaSelectedParentFolders({+ folderIds: ['grandchild', 'root', 'root', 'other'],+ folders,+ }),+ ).toEqual(['root', 'other']);+ });++ it('preserves selected children when their parent was not selected', () => {+ expect(+ getGranolaSelectedParentFolders({ folderIds: ['grandchild'], folders }),+ ).toEqual(['grandchild']);+ });++ it('keeps an empty selection empty to clear the filter', () => {+ expect(getGranolaSelectedParentFolders({ folderIds: [], folders })).toEqual(+ [],+ );+ });++ it('preserves explicit selections when cyclic ancestry would clear the filter', () => {+ expect(+ getGranolaSelectedParentFolders({+ folderIds: ['first', 'second'],+ folders: [+ { id: 'first', parent_folder_id: 'second' },+ { id: 'second', parent_folder_id: 'first' },+ ],+ }),+ ).toEqual(['first', 'second']);+ });++ it('prunes a folder whose selected ancestor sits before a cycle in its chain', () => {+ expect(+ getGranolaSelectedParentFolders({+ folderIds: ['leaf', 'branch'],+ folders: [+ { id: 'leaf', parent_folder_id: 'loop' },+ { id: 'loop', parent_folder_id: 'branch' },+ { id: 'branch', parent_folder_id: 'loop' },+ ],+ }),+ ).toEqual(['branch']);+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/assert-granola-folder-selection-ready-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/assert-granola-folder-selection-ready-or-throw.util.tsnew file mode 100644index 00000000000..fbf70e3aab8--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/assert-granola-folder-selection-ready-or-throw.util.ts@@ -0,0 +1,18 @@+import { kv, RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { GRANOLA_PENDING_FOLDER_SELECTION_KEY } from 'src/constants/granola.constant';+import { type GranolaPendingFolderSelection } from 'src/logic-functions/types/granola-pending-folder-selection.type';++export const assertGranolaFolderSelectionReadyOrThrow =+ async (): Promise<void> => {+ const pending = await kv.get<GranolaPendingFolderSelection>(+ GRANOLA_PENDING_FOLDER_SELECTION_KEY,+ );++ if (isDefined(pending)) {+ throw new RetryableLogicFunctionError(+ 'Granola folder selection is still being saved. Retry saving the selected folders.',+ );+ }+ };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.tsindex cbb22011f9e..c5ee9fbdf3c 100644--- 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.ts@@ -3,6 +3,7 @@ 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 { assertGranolaFolderSelectionReadyOrThrow } from 'src/logic-functions/utils/assert-granola-folder-selection-ready-or-throw.util';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';@@ -16,6 +17,7 @@ export const enqueueGranolaBackfillOrThrow = async ({updatedAfter?: string;folderIds?: string[];}) => {+ await assertGranolaFolderSelectionReadyOrThrow();const registration = await findGranolaRegistrationForCurrentKey();if (!isDefined(registration)) {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.tsindex 473d9cf9a73..db395c61b0a 100644--- 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.ts@@ -8,14 +8,12 @@ import {} 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';+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';-export const enqueueGranolaInitialBackfillOrThrow = async (- registration: Pick<- GranolaWebhookRegistration,- 'registrationId' | 'folderIds' | 'isInitialBackfillEnqueued'- >,-): Promise<void> => {- if (registration.isInitialBackfillEnqueued) {+export const enqueueGranolaInitialBackfillOrThrow = async (): Promise<void> => {+ const registration = await findGranolaRegistrationForCurrentKey();++ if (!isDefined(registration) || registration.isInitialBackfillEnqueued) {return;}@@ -23,7 +21,6 @@ export const enqueueGranolaInitialBackfillOrThrow = async (createdAfter: new Date(Date.now() - GRANOLA_INITIAL_IMPORT_DAYS * GRANOLA_MILLISECONDS_PER_DAY,).toISOString(),- folderIds: registration.folderIds,});const currentRegistration = await kv.get<GranolaWebhookRegistration>(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 12fa877e844..ee798cc47b0 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@@ -4,10 +4,12 @@ import { kv } from 'twenty-sdk/logic-function';import { isDefined } from 'twenty-sdk/utils';import {+ GRANOLA_PENDING_FOLDER_SELECTION_KEY,GRANOLA_PENDING_REGISTRATION_KEY,GRANOLA_WEBHOOK_REGISTRATION_KEY,} from 'src/constants/granola.constant';import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';+import { type GranolaPendingFolderSelection } from 'src/logic-functions/types/granola-pending-folder-selection.type';import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';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';@@ -31,6 +33,9 @@ export const ensureGranolaWebhookRegistrationOrThrow =const existing = await kv.get<GranolaWebhookRegistration>(GRANOLA_WEBHOOK_REGISTRATION_KEY,);+ const pendingFolderSelection = await kv.get<GranolaPendingFolderSelection>(+ GRANOLA_PENDING_FOLDER_SELECTION_KEY,+ );const { webhook_endpoints: endpoints } =await client.listWebhookEndpoints();await cleanupPendingGranolaRegistrationOrThrow({@@ -80,7 +85,7 @@ export const ensureGranolaWebhookRegistrationOrThrow =client,url,preferredScopes: isExistingKeyCurrent ? existing.scopes : undefined,- folderIds: existing?.folderIds ?? [],+ folderIds: pendingFolderSelection?.folderIds ?? existing?.folderIds ?? [],});const registration: GranolaWebhookRegistration = {registrationId,@@ -110,6 +115,9 @@ export const ensureGranolaWebhookRegistrationOrThrow =}throw error;}+ if (isDefined(pendingFolderSelection)) {+ await kv.delete(GRANOLA_PENDING_FOLDER_SELECTION_KEY);+ }await kv.delete(GRANOLA_PENDING_REGISTRATION_KEY);return registration;};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.tsindex 088c805e518..b0d1194bacb 100644--- 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.ts@@ -1,14 +1,15 @@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 { GRANOLA_PAGE_INTERVAL_MILLISECONDS } from 'src/constants/granola-api.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';+import { sleepForMilliseconds } from 'src/logic-functions/utils/sleep-for-milliseconds.util';export const fetchGranolaNoteWithTranscriptOrThrow = async ({client,@@ -64,9 +65,7 @@ export const fetchGranolaNoteWithTranscriptOrThrow = async ({seenCursors.add(page.cursor);cursor = page.cursor;- await new Promise((resolve) =>- setTimeout(resolve, GRANOLA_TRANSCRIPT_PAGE_INTERVAL_MILLISECONDS),- );+ await sleepForMilliseconds(GRANOLA_PAGE_INTERVAL_MILLISECONDS);}throw new GranolaTranscriptLimitError({ reason: 'page-limit' });diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-selected-parent-folders.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-selected-parent-folders.util.tsnew file mode 100644index 00000000000..5570b447acf--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-selected-parent-folders.util.ts@@ -0,0 +1,39 @@+import { isDefined } from 'twenty-sdk/utils';++import { type GranolaFolder } from 'src/logic-functions/types/granola-api.type';++export const getGranolaSelectedParentFolders = ({+ folderIds,+ folders,+}: {+ folderIds: string[];+ folders: Pick<GranolaFolder, 'id' | 'parent_folder_id'>[];+}): string[] => {+ const selectedIds = new Set(folderIds);+ const foldersById = new Map(folders.map((folder) => [folder.id, folder]));++ // A folder inside its own ancestry chain stays selected rather than collapsing the selection to every folder.+ const hasSelectedAncestor = (folderId: string): boolean => {+ const visited = new Set<string>();+ let isSelectedAncestorFound = false;+ let parentId = foldersById.get(folderId)?.parent_folder_id;++ while (isDefined(parentId)) {+ if (parentId === folderId) {+ return false;+ }++ if (visited.has(parentId)) {+ return isSelectedAncestorFound;+ }++ visited.add(parentId);+ isSelectedAncestorFound ||= selectedIds.has(parentId);+ parentId = foldersById.get(parentId)?.parent_folder_id;+ }++ return isSelectedAncestorFound;+ };++ return [...selectedIds].filter((folderId) => !hasSelectedAncestor(folderId));+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/list-all-granola-folders-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/list-all-granola-folders-or-throw.util.tsnew file mode 100644index 00000000000..ccf2db2485e--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/list-all-granola-folders-or-throw.util.ts@@ -0,0 +1,42 @@+import {+ GRANOLA_MAX_PAGE_SIZE,+ GRANOLA_PAGE_INTERVAL_MILLISECONDS,+} from 'src/constants/granola-api.constant';+import { type GranolaFolder } from 'src/logic-functions/types/granola-api.type';+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';+import { getGranolaNextPage } from 'src/logic-functions/utils/get-granola-next-page.util';+import { sleepForMilliseconds } from 'src/logic-functions/utils/sleep-for-milliseconds.util';++export const listAllGranolaFoldersOrThrow = async ({+ client = createGranolaClientOrThrow(),+}: {+ client?: Pick<ReturnType<typeof createGranolaClientOrThrow>, 'listFolders'>;+} = {}): Promise<GranolaFolder[]> => {+ const folders: GranolaFolder[] = [];+ let cursor: string | undefined;++ for (let pageIndex = 0; ; pageIndex++) {+ const page = await client.listFolders({+ cursor,+ page_size: GRANOLA_MAX_PAGE_SIZE,+ });+ folders.push(...page.folders);++ const nextPage = getGranolaNextPage({+ ...page,+ previousCursor: cursor,+ pageIndex,+ });++ if (nextPage.kind === 'complete') {+ return folders;+ }++ if (nextPage.kind === 'stalled') {+ throw new Error(nextPage.reason);+ }++ cursor = nextPage.cursor;+ await sleepForMilliseconds(GRANOLA_PAGE_INTERVAL_MILLISECONDS);+ }+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/reconcile-granola-folder-selection-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/reconcile-granola-folder-selection-or-throw.util.tsnew file mode 100644index 00000000000..562776ea5d6--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/reconcile-granola-folder-selection-or-throw.util.ts@@ -0,0 +1,47 @@+import { kv, RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import {+ GRANOLA_PENDING_FOLDER_SELECTION_KEY,+ GRANOLA_WEBHOOK_REGISTRATION_KEY,+} from 'src/constants/granola.constant';+import { type GranolaPendingFolderSelection } from 'src/logic-functions/types/granola-pending-folder-selection.type';+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';++export const reconcileGranolaFolderSelectionOrThrow =+ async (): Promise<void> => {+ const pending = await kv.get<GranolaPendingFolderSelection>(+ GRANOLA_PENDING_FOLDER_SELECTION_KEY,+ );++ if (!isDefined(pending)) {+ return;+ }++ const registration = await findGranolaRegistrationForCurrentKey();++ if (!isDefined(registration)) {+ throw new Error(+ 'Re-register the webhook after changing the Granola key.',+ );+ }++ const endpoint = await createGranolaClientOrThrow()+ .updateWebhookEndpoint({+ webhookEndpointId: registration.webhookEndpointId,+ folder_ids: pending.folderIds,+ })+ .catch(async (error: unknown) => {+ if (!(error instanceof RetryableLogicFunctionError)) {+ await kv.delete(GRANOLA_PENDING_FOLDER_SELECTION_KEY);+ }+ throw error;+ });++ await kv.set(GRANOLA_WEBHOOK_REGISTRATION_KEY, {+ ...registration,+ folderIds: endpoint.folder_ids,+ });+ await kv.delete(GRANOLA_PENDING_FOLDER_SELECTION_KEY);+ };diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/remove-granola-webhook-registration.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/remove-granola-webhook-registration.util.tsindex 3e29884a7ee..5baec4e9a1b 100644--- a/packages/twenty-apps/public/granola/src/logic-functions/utils/remove-granola-webhook-registration.util.ts+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/remove-granola-webhook-registration.util.ts@@ -1,7 +1,10 @@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_PENDING_FOLDER_SELECTION_KEY,+ GRANOLA_WEBHOOK_REGISTRATION_KEY,+} from 'src/constants/granola.constant';import { type GranolaWebhookRegistration } from 'src/logic-functions/types/granola-webhook-registration.type';import { type createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';import { deleteStaleGranolaWebhookEndpointOrThrow } from 'src/logic-functions/utils/delete-stale-granola-webhook-endpoint-or-throw.util';@@ -20,6 +23,8 @@ export const removeGranolaWebhookRegistration = async ({GRANOLA_WEBHOOK_REGISTRATION_KEY,);+ await kv.delete(GRANOLA_PENDING_FOLDER_SELECTION_KEY);+if (!isDefined(registration)) {return { deletedWebhookCount: 0 };}diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/sleep-for-milliseconds.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/sleep-for-milliseconds.util.tsnew file mode 100644index 00000000000..ddfad0990e3--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/sleep-for-milliseconds.util.ts@@ -0,0 +1,2 @@+export const sleepForMilliseconds = (milliseconds: number): Promise<void> =>+ new Promise((resolve) => setTimeout(resolve, milliseconds));