The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Granola 2/8: Add Granola API access and credential settings (#25571)
nitin422ca0fb115d
diff --git a/packages/twenty-apps/public/granola/src/__tests__/utils/build-granola-note.util.ts b/packages/twenty-apps/public/granola/src/__tests__/utils/build-granola-note.util.tsnew file mode 100644index 00000000000..0ec25e31e18--- /dev/null+++ b/packages/twenty-apps/public/granola/src/__tests__/utils/build-granola-note.util.ts@@ -0,0 +1,20 @@+import { type GranolaNote } from 'src/logic-functions/types/granola-api.type';++export const buildGranolaNote = (+ overrides: Partial<GranolaNote> = {},+): GranolaNote => ({+ id: 'not_1d3tmYTlCICgjy',+ object: 'note',+ title: 'Customer meeting',+ owner: { name: 'Alice', email: '[email protected]' },+ created_at: '2026-09-05T10:00:00Z',+ updated_at: '2026-09-05T11:00:00Z',+ web_url: 'https://notes.granola.ai/d/meeting',+ calendar_event: null,+ attendees: [],+ folder_membership: [],+ summary_text: 'Shared summary',+ summary_markdown: '## Shared summary',+ transcript: null,+ ...overrides,+});diff --git a/packages/twenty-apps/public/granola/src/application-config.ts b/packages/twenty-apps/public/granola/src/application-config.tsindex 974a7013d78..6a7b4a9defc 100644--- a/packages/twenty-apps/public/granola/src/application-config.ts+++ b/packages/twenty-apps/public/granola/src/application-config.ts@@ -1,8 +1,10 @@import { defineApplication } from 'twenty-sdk/define';+import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';import {APP_DESCRIPTION,APP_DISPLAY_NAME,APPLICATION_UNIVERSAL_IDENTIFIER,+ GRANOLA_API_KEY_VARIABLE_UNIVERSAL_IDENTIFIER,} from 'src/constants/universal-identifiers';export default defineApplication({@@ -12,4 +14,13 @@ export default defineApplication({logo: 'public/logo.png',author: 'Twenty',category: 'Productivity',+ applicationVariables: {+ [GRANOLA_API_KEY_ENV_VAR_NAME]: {+ universalIdentifier: GRANOLA_API_KEY_VARIABLE_UNIVERSAL_IDENTIFIER,+ label: 'Granola API key',+ description:+ 'Workspace or personal API key from Granola Settings → Connectors → API keys.',+ isSecret: true,+ },+ },});diff --git a/packages/twenty-apps/public/granola/src/constants/granola-connection-status-route-path.ts b/packages/twenty-apps/public/granola/src/constants/granola-connection-status-route-path.tsnew file mode 100644index 00000000000..e3d29798405--- /dev/null+++ b/packages/twenty-apps/public/granola/src/constants/granola-connection-status-route-path.ts@@ -0,0 +1,2 @@+export const GRANOLA_CONNECTION_STATUS_ROUTE_PATH =+ '/granola/connection-status';diff --git a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.tsindex e8c262a056a..7bd62878b84 100644--- a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts@@ -35,3 +35,5 @@ export const GRANOLA_FOLDERS_UNIVERSAL_IDENTIFIER ='e054fa37-78c9-4f6a-a064-f887b87f1fc5';export const GRANOLA_UPDATE_WEBHOOK_FOLDERS_UNIVERSAL_IDENTIFIER ='5092d8b4-b10d-4fcb-b029-c4e93d5234c5';+export const GRANOLA_API_KEY_VARIABLE_UNIVERSAL_IDENTIFIER =+ 'cbc0f310-d0e9-4033-ae07-0271405195e7';diff --git a/packages/twenty-apps/public/granola/src/default-role.ts b/packages/twenty-apps/public/granola/src/default-role.tsindex 2e2cec6d9af..976a4a075c5 100644--- a/packages/twenty-apps/public/granola/src/default-role.ts+++ b/packages/twenty-apps/public/granola/src/default-role.ts@@ -1,6 +1,7 @@import {STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,defineApplicationRole,+ SystemPermissionFlag,} from 'twenty-sdk/define';import {@@ -49,5 +50,5 @@ export default defineApplicationRole({},],fieldPermissions: [],- permissionFlagUniversalIdentifiers: [],+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.APPLICATIONS],});diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsxnew file mode 100644index 00000000000..0649fe95eb8--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx@@ -0,0 +1,156 @@+import styled from '@emotion/styled';+import { isNonEmptyString } from '@sniptt/guards';+import { useId, useState } from 'react';+import { t } from 'twenty-sdk/front-component';+import { Status } from 'twenty-ui/data-display';+import { IconKey } from 'twenty-ui/icon';+import { Button, LightButton } from 'twenty-ui/input';+import { Section } from 'twenty-ui/layout';+import { themeCssVariables } from 'twenty-ui/theme-constants';+import { H2Title } from 'twenty-ui/typography';++import { LabelledSettingsField } from 'src/front-components/components/LabelledSettingsField';+import { SettingsOptionCardContent } from 'src/front-components/components/SettingsOptionCardContent';+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';+import { StyledSettingsSectionStack } from 'src/front-components/components/StyledSettingsSectionStack';+import { StyledSettingsTextInput } from 'src/front-components/components/StyledSettingsTextInput';+import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';++const StyledKeyForm = styled.form`+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[3]};+`;++const StyledButtonRow = styled.div`+ display: flex;+ gap: ${() => themeCssVariables.spacing[2]};+`;++type GranolaConnectionSectionProps = {+ status: GranolaConnectionStatus;+ isConnecting: boolean;+ connectError: string | undefined;+ onConnect: (apiKey: string) => Promise<boolean>;+ onRetry: () => void;+};++const getConnectionDescription = (status: GranolaConnectionStatus) =>+ status.isConnected+ ? t('Connected to Granola.')+ : (status.error ?? t('Granola rejected the saved key.'));++export const GranolaConnectionSection = ({+ status,+ isConnecting,+ connectError,+ onConnect,+ onRetry,+}: GranolaConnectionSectionProps) => {+ const inputId = useId();+ const [apiKeyDraft, setApiKeyDraft] = useState('');+ const [isReplacingKey, setIsReplacingKey] = useState(false);++ const trimmedApiKeyDraft = apiKeyDraft.trim();+ const isKeyRejected =+ status.isApiKeySet && !status.isConnected && status.isGranolaReachable;+ const isKeyFormVisible =+ !status.isApiKeySet || isKeyRejected || isReplacingKey;+ const isCancelVisible = status.isConnected && isReplacingKey;++ const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {+ event.preventDefault();++ if (!isNonEmptyString(trimmedApiKeyDraft)) {+ return;+ }++ const isSaved = await onConnect(trimmedApiKeyDraft);++ if (isSaved) {+ setApiKeyDraft('');+ setIsReplacingKey(false);+ }+ };++ return (+ <Section>+ <H2Title+ title={t('Granola account')}+ description={t(+ 'Requires Granola Business or Enterprise. Create a key in Granola under Settings → Connectors → API keys.',+ )}+ />+ <StyledSettingsSectionStack>+ {status.isApiKeySet && (+ <StyledSettingsCard>+ <SettingsOptionCardContent+ Icon={IconKey}+ title={t('API key')}+ description={getConnectionDescription(status)}+ >+ {status.isConnected && (+ <Status color="green" text={t('Connected')} />+ )}+ {isKeyRejected && <Status color="red" text={t('Rejected')} />}+ {!status.isGranolaReachable && (+ <>+ <Status color="orange" text={t('Unreachable')} />+ <LightButton title={t('Retry')} onClick={onRetry} />+ </>+ )}+ {status.isConnected && !isReplacingKey && (+ <LightButton+ title={t('Replace')}+ onClick={() => setIsReplacingKey(true)}+ />+ )}+ </SettingsOptionCardContent>+ </StyledSettingsCard>+ )}+ {isKeyFormVisible && (+ <StyledKeyForm onSubmit={handleSubmit}>+ <LabelledSettingsField+ label={status.isApiKeySet ? t('New API key') : t('API key')}+ inputId={inputId}+ errorMessage={connectError}+ hint={t(+ 'Workspace keys sync notes shared with the whole workspace. Personal keys also sync your own notes.',+ )}+ >+ <StyledSettingsTextInput+ id={inputId}+ type="password"+ autoComplete="off"+ placeholder="grn_…"+ value={apiKeyDraft}+ disabled={isConnecting}+ onChange={(event) => setApiKeyDraft(event.target.value)}+ />+ </LabelledSettingsField>+ <StyledButtonRow>+ <Button+ type="submit"+ title={t('Connect')}+ accent="blue"+ isLoading={isConnecting}+ disabled={isConnecting || !isNonEmptyString(trimmedApiKeyDraft)}+ />+ {isCancelVisible && (+ <Button+ title={t('Cancel')}+ variant="secondary"+ disabled={isConnecting}+ onClick={() => {+ setIsReplacingKey(false);+ setApiKeyDraft('');+ }}+ />+ )}+ </StyledButtonRow>+ </StyledKeyForm>+ )}+ </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.tsxnew file mode 100644index 00000000000..9a1f3bb395a--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx@@ -0,0 +1,115 @@+import 'twenty-ui/style.css';++import styled from '@emotion/styled';+import { useState } from 'react';+import {+ t,+ useColorScheme,+ useFrontComponentId,+} from 'twenty-sdk/front-component';+import { THEME_DARK, THEME_LIGHT } from 'twenty-ui/theme';+import {+ ThemeContext,+ themeCssVariables,+ type ThemeType,+} from 'twenty-ui/theme-constants';++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 { saveGranolaApiKeyOrThrow } from 'src/front-components/utils/save-granola-api-key-or-throw.util';++const StyledContainer = styled.div`+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[8]};+ width: 100%;+`;++const StyledNotice = styled.div`+ color: ${() => themeCssVariables.font.color.tertiary};+ font-family: ${() => themeCssVariables.font.family};+ font-size: ${() => themeCssVariables.font.size.md};+ line-height: ${() => themeCssVariables.text.lineHeight.md};+`;++type GranolaSettingsState =+ | { step: 'loading' }+ | { step: 'unavailable' }+ | { step: 'ready'; status: GranolaConnectionStatus };++export const GranolaSettings = () => {+ const colorScheme = useColorScheme();+ const frontComponentId = useFrontComponentId();+ const [state, setState] = useState<GranolaSettingsState>({ step: 'loading' });+ const [isConnecting, setIsConnecting] = useState(false);+ const [connectError, setConnectError] = useState<string | undefined>();++ const loadConnectionStatus = async () => {+ try {+ setState({+ step: 'ready',+ status: await fetchGranolaConnectionStatusOrThrow(),+ });+ } catch {+ setState({ step: 'unavailable' });+ }+ };++ const handleConnect = async (apiKey: string): Promise<boolean> => {+ setIsConnecting(true);+ setConnectError(undefined);++ try {+ await saveGranolaApiKeyOrThrow({ frontComponentId, apiKey });+ } catch {+ setConnectError(t('Could not save the API key. Try again.'));+ setIsConnecting(false);++ return false;+ }++ await loadConnectionStatus();+ setIsConnecting(false);++ return true;+ };++ // twenty-ui components read icon sizes off ThemeContext, and the context+ // default resolves them to var() strings an SVG size attribute cannot use.+ return (+ <ThemeContext.Provider+ value={{+ theme: (colorScheme === 'dark'+ ? THEME_DARK+ : THEME_LIGHT) as unknown as ThemeType,+ colorScheme,+ }}+ >+ <StyledContainer>+ <OnMountEffect onMount={loadConnectionStatus} />+ {state.step === 'loading' && (+ <StyledNotice>{t('Checking your Granola connection…')}</StyledNotice>+ )}+ {state.step === 'unavailable' && (+ <StyledNotice>+ {t(+ 'Could not load Granola settings. Reload the page to try again.',+ )}+ </StyledNotice>+ )}+ {state.step === 'ready' && (+ <GranolaConnectionSection+ status={state.status}+ isConnecting={isConnecting}+ connectError={connectError}+ onConnect={handleConnect}+ onRetry={loadConnectionStatus}+ />+ )}+ </StyledContainer>+ </ThemeContext.Provider>+ );+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/LabelledSettingsField.tsx b/packages/twenty-apps/public/granola/src/front-components/components/LabelledSettingsField.tsxnew file mode 100644index 00000000000..474305a0421--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/LabelledSettingsField.tsx@@ -0,0 +1,52 @@+import styled from '@emotion/styled';+import { isNonEmptyString } from '@sniptt/guards';+import { type ReactNode } from 'react';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { StyledSettingsError } from 'src/front-components/components/StyledSettingsError';++const StyledField = styled.div`+ display: flex;+ flex-direction: column;+`;++// twenty-front hard-codes this size in FieldLabel.module.scss; there is no token.+const StyledLabel = styled.label`+ color: ${() => themeCssVariables.font.color.primary};+ font-family: ${() => themeCssVariables.font.family};+ font-size: 11px;+ font-weight: ${() => themeCssVariables.font.weight.semiBold};+ margin-bottom: ${() => themeCssVariables.spacing[1]};+`;++const StyledHint = styled.span`+ color: ${() => themeCssVariables.font.color.secondary};+ font-family: ${() => themeCssVariables.font.family};+ font-size: ${() => themeCssVariables.font.size.sm};+ margin-top: ${() => themeCssVariables.spacing[3]};+`;++type LabelledSettingsFieldProps = {+ label: string;+ inputId: string;+ hint?: string;+ errorMessage?: string;+ children: ReactNode;+};++export const LabelledSettingsField = ({+ label,+ inputId,+ hint,+ errorMessage,+ children,+}: LabelledSettingsFieldProps) => (+ <StyledField>+ <StyledLabel htmlFor={inputId}>{label}</StyledLabel>+ {children}+ {isNonEmptyString(errorMessage) && (+ <StyledSettingsError>{errorMessage}</StyledSettingsError>+ )}+ {isNonEmptyString(hint) && <StyledHint>{hint}</StyledHint>}+ </StyledField>+);diff --git a/packages/twenty-apps/public/granola/src/front-components/components/OnMountEffect.tsx b/packages/twenty-apps/public/granola/src/front-components/components/OnMountEffect.tsxnew file mode 100644index 00000000000..5149df78f8e--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/OnMountEffect.tsx@@ -0,0 +1,13 @@+import { useEffect } from 'react';++type OnMountEffectProps = {+ onMount: () => void;+};++export const OnMountEffect = ({ onMount }: OnMountEffectProps) => {+ useEffect(() => {+ onMount();+ }, []);++ return null;+};diff --git a/packages/twenty-apps/public/granola/src/front-components/components/SettingsCardContentBase.tsx b/packages/twenty-apps/public/granola/src/front-components/components/SettingsCardContentBase.tsxnew file mode 100644index 00000000000..7557b298f14--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/SettingsCardContentBase.tsx@@ -0,0 +1,41 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++export const StyledSettingsCardContent = styled.div`+ align-items: center;+ background-color: ${() => themeCssVariables.background.secondary};+ display: flex;+ gap: ${() => themeCssVariables.spacing[3]};+ padding: ${() => themeCssVariables.spacing[4]};+`;++export const StyledSettingsCardIcon = styled.div`+ align-items: center;+ background-color: ${() => themeCssVariables.background.primary};+ border: 2px solid ${() => themeCssVariables.border.color.light};+ border-radius: ${() => themeCssVariables.border.radius.sm};+ box-sizing: border-box;+ display: flex;+ height: ${() => themeCssVariables.spacing[8]};+ justify-content: center;+ min-width: ${() => themeCssVariables.spacing[8]};+ width: ${() => themeCssVariables.spacing[8]};+`;++export const StyledSettingsCardTitle = styled.div`+ color: ${() => themeCssVariables.font.color.primary};+ font-weight: ${() => themeCssVariables.font.weight.medium};+ margin-bottom: ${() => themeCssVariables.spacing[1]};+`;++export const StyledSettingsCardTextContainer = styled.div`+ flex: 1;+ min-width: 0;+`;++export const StyledSettingsCardDescription = styled.div`+ color: ${() => themeCssVariables.font.color.secondary};+ font-size: ${() => themeCssVariables.font.size.sm};+ line-height: ${() => themeCssVariables.text.lineHeight.lg};+ overflow: hidden;+`;diff --git a/packages/twenty-apps/public/granola/src/front-components/components/SettingsOptionCardContent.tsx b/packages/twenty-apps/public/granola/src/front-components/components/SettingsOptionCardContent.tsxnew file mode 100644index 00000000000..1cd45d9de72--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/SettingsOptionCardContent.tsx@@ -0,0 +1,52 @@+import styled from '@emotion/styled';+import { type IconComponent } from 'twenty-ui/icon';+import { OverflowingTextWithTooltip } from 'twenty-ui/surfaces';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import {+ StyledSettingsCardContent,+ StyledSettingsCardDescription,+ StyledSettingsCardIcon,+ StyledSettingsCardTextContainer,+ StyledSettingsCardTitle,+} from 'src/front-components/components/SettingsCardContentBase';+import { SettingsOptionIconCustomizer } from 'src/front-components/components/SettingsOptionIconCustomizer';++const StyledTrailingContainer = styled.div`+ align-items: center;+ display: flex;+ flex-shrink: 0;+ gap: ${() => themeCssVariables.spacing[2]};+ margin-left: auto;+`;++type SettingsOptionCardContentProps = {+ Icon?: IconComponent;+ title: React.ReactNode;+ description?: string;+ children?: React.ReactNode;+};++export const SettingsOptionCardContent = ({+ Icon,+ title,+ description,+ children,+}: SettingsOptionCardContentProps) => (+ <StyledSettingsCardContent>+ {Icon && (+ <StyledSettingsCardIcon>+ <SettingsOptionIconCustomizer Icon={Icon} />+ </StyledSettingsCardIcon>+ )}+ <StyledSettingsCardTextContainer>+ <StyledSettingsCardTitle>{title}</StyledSettingsCardTitle>+ {description && (+ <StyledSettingsCardDescription>+ <OverflowingTextWithTooltip text={description} />+ </StyledSettingsCardDescription>+ )}+ </StyledSettingsCardTextContainer>+ <StyledTrailingContainer>{children}</StyledTrailingContainer>+ </StyledSettingsCardContent>+);diff --git a/packages/twenty-apps/public/granola/src/front-components/components/SettingsOptionIconCustomizer.tsx b/packages/twenty-apps/public/granola/src/front-components/components/SettingsOptionIconCustomizer.tsxnew file mode 100644index 00000000000..a1ba17b9101--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/SettingsOptionIconCustomizer.tsx@@ -0,0 +1,33 @@+import styled from '@emotion/styled';+import { type IconComponent } from 'twenty-ui/icon';+import { ICON } from 'twenty-ui/theme';+import { themeCssVariables } from 'twenty-ui/theme-constants';++// twenty-front reads these off ThemeContext, but a front component has no+// ThemeProvider: the context default resolves every value to a var() string,+// which an SVG size attribute cannot use. Sizes come from the numeric ICON+// constants and the colour is inherited through currentColor instead.+const StyledIconCustomizer = styled.div<{ $zoom: number; $rotate: number }>`+ align-items: center;+ color: ${() => themeCssVariables.IllustrationIcon.color.gray};+ display: inline-flex;+ justify-content: center;+ pointer-events: none;+ transform: ${({ $zoom, $rotate }) => `scale(${$zoom}) rotate(${$rotate}deg)`};+`;++type SettingsOptionIconCustomizerProps = {+ Icon: IconComponent;+ zoom?: number;+ rotate?: number;+};++export const SettingsOptionIconCustomizer = ({+ Icon,+ zoom = 1,+ rotate = -4,+}: SettingsOptionIconCustomizerProps) => (+ <StyledIconCustomizer $zoom={zoom} $rotate={rotate}>+ <Icon size={ICON.size.lg} stroke={ICON.stroke.md} />+ </StyledIconCustomizer>+);diff --git a/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsCard.tsx b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsCard.tsxnew file mode 100644index 00000000000..99a22a68a13--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsCard.tsx@@ -0,0 +1,23 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++// Mirrors twenty-ui's Card without its overflow: hidden, which would clip the+// select menus that open inline below their rows. The rows paint their own+// background, so the first and last ones take over the card's corners.+export const StyledSettingsCard = styled.div`+ border: 1px solid ${() => themeCssVariables.border.color.medium};+ border-radius: ${() => themeCssVariables.border.radius.md};+ box-sizing: border-box;+ color: ${() => themeCssVariables.font.color.secondary};+ width: 100%;++ & > :first-child {+ border-top-left-radius: inherit;+ border-top-right-radius: inherit;+ }++ & > :last-child {+ border-bottom-left-radius: inherit;+ border-bottom-right-radius: inherit;+ }+`;diff --git a/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsError.tsx b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsError.tsxnew file mode 100644index 00000000000..ce57512f6c0--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsError.tsx@@ -0,0 +1,9 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++export const StyledSettingsError = styled.div`+ color: ${() => themeCssVariables.font.color.danger};+ font-family: ${() => themeCssVariables.font.family};+ font-size: ${() => themeCssVariables.font.size.xs};+ margin-top: ${() => themeCssVariables.spacing[1]};+`;diff --git a/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsSectionStack.tsx b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsSectionStack.tsxnew file mode 100644index 00000000000..1106c206fd5--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsSectionStack.tsx@@ -0,0 +1,8 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme-constants';++export const StyledSettingsSectionStack = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[4]};+`;diff --git a/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsTextInput.tsx b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsTextInput.tsxnew file mode 100644index 00000000000..77e5812a237--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsTextInput.tsx@@ -0,0 +1,11 @@+import styled from '@emotion/styled';++import { getSettingsControlStyles } from 'src/front-components/utils/get-settings-control-styles.util';++export const StyledSettingsTextInput = styled.input`+ display: flex;+ flex-grow: 1;+ height: 32px;+ text-overflow: ellipsis;+ ${getSettingsControlStyles}+`;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.tsxnew file mode 100644index 00000000000..73d1fa5957d--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/settings.front-component.tsx@@ -0,0 +1,10 @@+import { defineSettingsFrontComponent } from 'twenty-sdk/define';+import { GRANOLA_SETTINGS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { GranolaSettings } from 'src/front-components/components/GranolaSettings';++export default defineSettingsFrontComponent({+ universalIdentifier: GRANOLA_SETTINGS_UNIVERSAL_IDENTIFIER,+ name: 'granola-settings',+ description: 'Granola connection settings.',+ component: GranolaSettings,+});diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.tsnew file mode 100644index 00000000000..0c7ed682afb--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts@@ -0,0 +1,12 @@+import { z } from 'zod';++export const GRANOLA_CONNECTION_STATUS_SCHEMA = z.object({+ isConnected: z.boolean(),+ isApiKeySet: z.boolean(),+ isGranolaReachable: z.boolean().default(true),+ error: z.string().optional(),+});++export type GranolaConnectionStatus = z.infer<+ typeof GRANOLA_CONNECTION_STATUS_SCHEMA+>;diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-connection-status-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-connection-status-or-throw.util.tsnew file mode 100644index 00000000000..78f8451f346--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-connection-status-or-throw.util.ts@@ -0,0 +1,15 @@+import { RestApiClient } from 'twenty-client-sdk/rest';++import { GRANOLA_CONNECTION_STATUS_ROUTE_PATH } from 'src/constants/granola-connection-status-route-path';+import {+ GRANOLA_CONNECTION_STATUS_SCHEMA,+ type GranolaConnectionStatus,+} from 'src/front-components/types/granola-connection-status.type';++export const fetchGranolaConnectionStatusOrThrow =+ async (): Promise<GranolaConnectionStatus> =>+ GRANOLA_CONNECTION_STATUS_SCHEMA.parse(+ await new RestApiClient().get(+ `/s${GRANOLA_CONNECTION_STATUS_ROUTE_PATH}`,+ ),+ );diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/get-settings-control-styles.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/get-settings-control-styles.util.tsnew file mode 100644index 00000000000..7efdcb89ee6--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/get-settings-control-styles.util.ts@@ -0,0 +1,37 @@+import { themeCssVariables } from 'twenty-ui/theme-constants';++// Mirrors the settings inputs twenty-front renders for application variables,+// which cannot be imported here: twenty-ui ships no text, select or textarea+// input, and front components cannot reach into twenty-front internals.+export const getSettingsControlStyles = () => `+ background-color: ${themeCssVariables.background.transparent.light};+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.md};+ box-sizing: border-box;+ color: ${themeCssVariables.font.color.primary};+ font-family: ${themeCssVariables.font.family};+ font-size: ${themeCssVariables.font.size.md};+ font-weight: ${themeCssVariables.font.weight.regular};+ outline: none;+ padding: ${themeCssVariables.spacing[2]};+ width: 100%;++ &::placeholder,+ &::-webkit-input-placeholder {+ color: ${themeCssVariables.font.color.tertiary};+ font-family: ${themeCssVariables.font.family};+ font-weight: ${themeCssVariables.font.weight.medium};+ }++ &:disabled {+ color: ${themeCssVariables.font.color.secondary};+ }++ &[readonly] {+ pointer-events: none;+ }++ &:focus {+ border-color: ${themeCssVariables.color.blue};+ }+`;diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-api-key-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-api-key-or-throw.util.tsnew file mode 100644index 00000000000..b4aa369ce92--- /dev/null+++ b/packages/twenty-apps/public/granola/src/front-components/utils/save-granola-api-key-or-throw.util.ts@@ -0,0 +1,35 @@+import { isNonEmptyString } from '@sniptt/guards';+import { MetadataApiClient } from 'twenty-client-sdk/metadata';++import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';++export const saveGranolaApiKeyOrThrow = async ({+ frontComponentId,+ apiKey,+}: {+ frontComponentId: string;+ apiKey: string;+}): Promise<void> => {+ const client = new MetadataApiClient();+ const result = await client.query({+ frontComponent: {+ __args: { id: frontComponentId },+ applicationId: true,+ },+ });+ const applicationId = result.frontComponent?.applicationId;++ if (!isNonEmptyString(applicationId)) {+ throw new Error('Could not find the Granola application.');+ }++ await client.mutation({+ updateOneApplicationVariable: {+ __args: {+ key: GRANOLA_API_KEY_ENV_VAR_NAME,+ value: apiKey,+ applicationId,+ },+ },+ });+};diff --git a/packages/twenty-apps/public/granola/src/logic-functions/constants/granola-api-key-env-var-name.ts b/packages/twenty-apps/public/granola/src/logic-functions/constants/granola-api-key-env-var-name.tsnew file mode 100644index 00000000000..64c289fcff7--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/constants/granola-api-key-env-var-name.ts@@ -0,0 +1 @@+export const GRANOLA_API_KEY_ENV_VAR_NAME = 'GRANOLA_API_KEY';diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.tsnew file mode 100644index 00000000000..936cefdddb7--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts@@ -0,0 +1,45 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction } from 'twenty-sdk/define';+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';++import { GRANOLA_CONNECTION_STATUS_ROUTE_PATH } from 'src/constants/granola-connection-status-route-path';+import { GRANOLA_CONNECTION_STATUS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';++export const granolaConnectionStatusHandler = async () => {+ if (!isNonEmptyString(process.env[GRANOLA_API_KEY_ENV_VAR_NAME]?.trim())) {+ return { isConnected: false, isApiKeySet: false };+ }+ try {+ await createGranolaClientOrThrow().listFolders({ page_size: 1 });+ return { isConnected: true, isApiKeySet: true };+ } catch (error) {+ if (error instanceof GranolaApiError) {+ return { isConnected: false, isApiKeySet: true, error: error.message };+ }+ if (error instanceof RetryableLogicFunctionError) {+ return {+ isConnected: false,+ isApiKeySet: true,+ isGranolaReachable: false,+ error: error.message,+ };+ }+ throw error;+ }+};++export default defineLogicFunction({+ universalIdentifier: GRANOLA_CONNECTION_STATUS_UNIVERSAL_IDENTIFIER,+ name: 'granola-connection-status',+ description: 'Checks the saved Granola API key.',+ timeoutSeconds: 60,+ handler: granolaConnectionStatusHandler,+ httpRouteTriggerSettings: {+ path: GRANOLA_CONNECTION_STATUS_ROUTE_PATH,+ httpMethod: 'GET',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api-error.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api-error.tsnew file mode 100644index 00000000000..dfebea7a461--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api-error.ts@@ -0,0 +1,35 @@+import { z } from 'zod';++const GRANOLA_ERROR_BODY_SCHEMA = z.object({+ details: z+ .array(z.object({ field: z.string().optional(), issue: z.string() }))+ .optional(),+});++const GRANOLA_API_ERROR_MESSAGE_BY_STATUS: Record<number, string> = {+ 400: 'Granola rejected the request. Check the selected scopes and folders.',+ 401: 'Key rejected by Granola.',+ 403: 'Granola denied access. Check API scopes and workspace permissions.',+ 404: 'Granola resource not found, or webhooks are unavailable for this plan.',+ 413: 'Granola transcript is too large to include inline.',+};++export type GranolaApiErrorDetail = { field?: string; issue: string };++export class GranolaApiError extends Error {+ readonly status: number;+ readonly details: GranolaApiErrorDetail[];++ constructor({ status, body }: { status: number; body?: unknown }) {+ super(+ GRANOLA_API_ERROR_MESSAGE_BY_STATUS[status] ??+ `Granola request failed (HTTP ${status}).`,+ );+ this.name = 'GranolaApiError';+ this.status = status;++ const parsedBody = GRANOLA_ERROR_BODY_SCHEMA.safeParse(body);++ this.details = parsedBody.success ? (parsedBody.data.details ?? []) : [];+ }+}diff --git a/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api.type.ts b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api.type.tsnew file mode 100644index 00000000000..a7a1a87f344--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/types/granola-api.type.ts@@ -0,0 +1,111 @@+import { z } from 'zod';++const GRANOLA_DATE_TIME_SCHEMA = z.string().datetime({ offset: true });+const GRANOLA_USER_SCHEMA = z.object({+ name: z.string().nullable(),+ email: z.string(),+});++export const GRANOLA_FOLDER_SCHEMA = z.object({+ id: z.string(),+ object: z.literal('folder'),+ name: z.string(),+ parent_folder_id: z.string().nullable(),+});++export const GRANOLA_TRANSCRIPT_ITEM_SCHEMA = z.object({+ speaker: z.object({+ source: z.enum(['microphone', 'speaker']),+ attribution: z.enum(['me', 'them']).optional(),+ diarization_label: z.string().optional(),+ name: z.string().optional(),+ }),+ text: z.string(),+ start_time: GRANOLA_DATE_TIME_SCHEMA,+ end_time: GRANOLA_DATE_TIME_SCHEMA,+});++export const GRANOLA_NOTE_SUMMARY_SCHEMA = z.object({+ id: z.string(),+ object: z.literal('note'),+ title: z.string().nullable(),+ owner: GRANOLA_USER_SCHEMA,+ created_at: GRANOLA_DATE_TIME_SCHEMA,+ updated_at: GRANOLA_DATE_TIME_SCHEMA,+});++export const GRANOLA_NOTE_SCHEMA = GRANOLA_NOTE_SUMMARY_SCHEMA.extend({+ web_url: z.string().url(),+ calendar_event: z+ .object({+ event_title: z.string().nullable(),+ invitees: z.array(z.object({ email: z.string() })),+ organiser: z.string().nullable(),+ calendar_event_id: z.string().nullable(),+ scheduled_start_time: GRANOLA_DATE_TIME_SCHEMA.nullable(),+ scheduled_end_time: GRANOLA_DATE_TIME_SCHEMA.nullable(),+ })+ .nullable(),+ attendees: z.array(GRANOLA_USER_SCHEMA),+ folder_membership: z.array(GRANOLA_FOLDER_SCHEMA),+ summary_text: z.string(),+ summary_markdown: z.string().nullable(),+ transcript: z.array(GRANOLA_TRANSCRIPT_ITEM_SCHEMA).nullable(),+});++export const GRANOLA_WEBHOOK_SCOPE_SCHEMA = z.enum([+ 'personal',+ 'public',+ 'workspace',+]);+export const GRANOLA_WEBHOOK_EVENT_SCHEMA = z.enum([+ 'note.access_granted',+ 'note.edited',+ 'note.generated',+]);++export const GRANOLA_WEBHOOK_ENDPOINT_SCHEMA = z.object({+ id: z.string(),+ object: z.literal('webhook_endpoint'),+ url: z.string().url(),+ url_redacted: z.boolean(),+ events: z.array(GRANOLA_WEBHOOK_EVENT_SCHEMA),+ folder_ids: z.array(z.string()),+ scopes: z.array(GRANOLA_WEBHOOK_SCOPE_SCHEMA),+ created_by: GRANOLA_USER_SCHEMA.nullable(),+ enabled: z.boolean(),+ created_at: GRANOLA_DATE_TIME_SCHEMA,+});++export type GranolaNote = z.infer<typeof GRANOLA_NOTE_SCHEMA>;+export type GranolaNoteSummary = z.infer<typeof GRANOLA_NOTE_SUMMARY_SCHEMA>;+export type GranolaTranscriptItem = z.infer<+ typeof GRANOLA_TRANSCRIPT_ITEM_SCHEMA+>;+export type GranolaFolder = z.infer<typeof GRANOLA_FOLDER_SCHEMA>;+export type GranolaWebhookEndpoint = z.infer<+ typeof GRANOLA_WEBHOOK_ENDPOINT_SCHEMA+>;+export type GranolaWebhookScope = z.infer<typeof GRANOLA_WEBHOOK_SCOPE_SCHEMA>;+export type GranolaWebhookEvent = z.infer<typeof GRANOLA_WEBHOOK_EVENT_SCHEMA>;+export type GranolaListNotesParameters = {+ created_after?: string;+ created_before?: string;+ updated_after?: string;+ folder_id?: string;+ cursor?: string;+ page_size?: number;+};+export type GranolaCreateWebhookEndpointParameters = Pick<+ GranolaWebhookEndpoint,+ 'url' | 'scopes'+> &+ Partial<Pick<GranolaWebhookEndpoint, 'events' | 'folder_ids'>>;+export type GranolaUpdateWebhookEndpointParameters = {+ webhookEndpointId: string;+} & Partial<+ Pick<+ GranolaWebhookEndpoint,+ 'url' | 'scopes' | 'events' | 'folder_ids' | 'enabled'+ >+>;diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-client-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-client-or-throw.test.tsnew file mode 100644index 00000000000..76fd901cfae--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/create-granola-client-or-throw.test.ts@@ -0,0 +1,123 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';++import { buildGranolaNote } from 'src/__tests__/utils/build-granola-note.util';+import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';+import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';++const API_KEY = 'grn_test_secret';++afterEach(() => vi.unstubAllGlobals());++describe('createGranolaClientOrThrow', () => {+ it('sends authenticated list filters and opaque cursors without mangling them', async () => {+ const mockedFetch = vi+ .fn<typeof fetch>()+ .mockResolvedValue(+ Response.json({ notes: [], hasMore: false, cursor: null }),+ );+ vi.stubGlobal('fetch', mockedFetch);++ await createGranolaClientOrThrow({ apiKey: API_KEY }).listNotes({+ folder_id: 'fol_example',+ updated_after: '2026-09-05T10:00:00+05:30',+ cursor: 'a+/=',+ page_size: 30,+ });++ const [url, request] = mockedFetch.mock.calls[0];+ expect(url).toBeInstanceOf(URL);+ expect(String(url)).toContain('cursor=a%2B%2F%3D');+ expect(String(url)).toContain(+ 'updated_after=2026-09-05T10%3A00%3A00%2B05%3A30',+ );+ expect(request?.headers).toMatchObject({+ Authorization: `Bearer ${API_KEY}`,+ });+ });++ it('discards private notes at the API boundary', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn<typeof fetch>().mockResolvedValue(+ Response.json({+ ...buildGranolaNote(),+ private_notes_text: 'Private scratchpad',+ private_notes_markdown: '# Private',+ }),+ ),+ );++ const note = await createGranolaClientOrThrow({ apiKey: API_KEY }).getNote({+ noteId: 'not_1d3tmYTlCICgjy',+ });++ expect(note).not.toHaveProperty('private_notes_text');+ expect(note).not.toHaveProperty('private_notes_markdown');+ expect(note.summary_text).toBe('Shared summary');+ });++ it.each([400, 401, 403, 404, 413])(+ 'preserves nonretryable HTTP %s without disclosing the body',+ async (status) => {+ vi.stubGlobal(+ 'fetch',+ vi+ .fn<typeof fetch>()+ .mockResolvedValue(new Response(API_KEY, { status })),+ );+ const promise = createGranolaClientOrThrow({+ apiKey: API_KEY,+ }).listFolders();++ await expect(promise).rejects.toBeInstanceOf(GranolaApiError);+ await expect(promise).rejects.toMatchObject({ status });+ await expect(promise).rejects.not.toThrow(API_KEY);+ },+ );++ it.each([429, 500, 502, 503])('makes HTTP %s retryable', async (status) => {+ vi.stubGlobal(+ 'fetch',+ vi+ .fn<typeof fetch>()+ .mockResolvedValue(new Response(API_KEY, { status })),+ );+ await expect(+ createGranolaClientOrThrow({ apiKey: API_KEY }).listFolders(),+ ).rejects.toBeInstanceOf(RetryableLogicFunctionError);+ });++ it('makes network failure retryable without leaking the underlying error', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn<typeof fetch>().mockRejectedValue(new Error(API_KEY)),+ );+ const promise = createGranolaClientOrThrow({+ apiKey: API_KEY,+ }).listFolders();+ await expect(promise).rejects.toBeInstanceOf(RetryableLogicFunctionError);+ await expect(promise).rejects.not.toThrow(API_KEY);+ });++ it('rejects malformed API data without exposing it', async () => {+ vi.stubGlobal(+ 'fetch',+ vi+ .fn<typeof fetch>()+ .mockResolvedValue(Response.json({ folders: API_KEY })),+ );+ await expect(+ createGranolaClientOrThrow({ apiKey: API_KEY }).listFolders(),+ ).rejects.toThrow('Granola returned an unexpected response.');+ });++ it('rejects blank keys before making a request', () => {+ const mockedFetch = vi.fn<typeof fetch>();+ vi.stubGlobal('fetch', mockedFetch);+ expect(() => createGranolaClientOrThrow({ apiKey: ' ' })).toThrow(+ 'not set',+ );+ expect(mockedFetch).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-client-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-client-or-throw.util.tsnew file mode 100644index 00000000000..aa123e93ec2--- /dev/null+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/create-granola-client-or-throw.util.ts@@ -0,0 +1,186 @@+import { isNonEmptyString } from '@sniptt/guards';+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';+import { z } from 'zod';++import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';+import {+ GRANOLA_FOLDER_SCHEMA,+ GRANOLA_NOTE_SCHEMA,+ GRANOLA_NOTE_SUMMARY_SCHEMA,+ GRANOLA_TRANSCRIPT_ITEM_SCHEMA,+ GRANOLA_WEBHOOK_ENDPOINT_SCHEMA,+ type GranolaCreateWebhookEndpointParameters,+ type GranolaListNotesParameters,+ type GranolaUpdateWebhookEndpointParameters,+} from 'src/logic-functions/types/granola-api.type';+import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';++const GRANOLA_API_BASE_URL = 'https://public-api.granola.ai/v1';+const GRANOLA_REQUEST_TIMEOUT_MILLISECONDS = 15_000;+const GRANOLA_PAGINATION_SCHEMA = z.object({+ hasMore: z.boolean(),+ cursor: z.string().nullable(),+});++export const createGranolaClientOrThrow = ({+ apiKey = process.env[GRANOLA_API_KEY_ENV_VAR_NAME],+}: { apiKey?: string } = {}) => {+ const trimmedApiKey = apiKey?.trim();++ if (!isNonEmptyString(trimmedApiKey)) {+ throw new Error('Granola API key is not set.');+ }++ const requestOrThrow = async <TResponse>({+ path,+ schema,+ method = 'GET',+ parameters = {},+ body,+ }: {+ path: string;+ schema: z.ZodType<TResponse>;+ method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';+ parameters?: Record<string, string | number | undefined>;+ body?:+ | GranolaCreateWebhookEndpointParameters+ | Omit<GranolaUpdateWebhookEndpointParameters, 'webhookEndpointId'>;+ }): Promise<TResponse> => {+ const url = new URL(`${GRANOLA_API_BASE_URL}${path}`);++ for (const [name, value] of Object.entries(parameters)) {+ if (isDefined(value)) {+ url.searchParams.set(name, String(value));+ }+ }++ const response = await fetch(url, {+ method,+ headers: {+ Authorization: `Bearer ${trimmedApiKey}`,+ ...(isDefined(body) ? { 'Content-Type': 'application/json' } : {}),+ },+ ...(isDefined(body) ? { body: JSON.stringify(body) } : {}),+ signal: AbortSignal.timeout(GRANOLA_REQUEST_TIMEOUT_MILLISECONDS),+ }).catch((error: unknown) => {+ throw new RetryableLogicFunctionError(+ error instanceof Error && error.name === 'TimeoutError'+ ? 'Granola did not respond in time. Try again later.'+ : 'Granola is unreachable. Try again later.',+ );+ });++ if (response.status === 429 || response.status >= 500) {+ throw new RetryableLogicFunctionError(+ `Granola is temporarily unavailable (HTTP ${response.status}).`,+ );+ }++ if (!response.ok) {+ throw new GranolaApiError({+ status: response.status,+ body: await response.json().catch(() => undefined),+ });+ }++ const payload: unknown = await response.json().catch(() => {+ throw new RetryableLogicFunctionError(+ 'Granola returned an unreadable response.',+ );+ });+ const result = schema.safeParse(payload);++ if (!result.success) {+ throw new Error('Granola returned an unexpected response.');+ }++ return result.data;+ };++ return {+ listNotes: (parameters: GranolaListNotesParameters = {}) =>+ requestOrThrow({+ path: '/notes',+ parameters,+ schema: GRANOLA_PAGINATION_SCHEMA.extend({+ notes: z.array(GRANOLA_NOTE_SUMMARY_SCHEMA),+ }),+ }),+ getNote: ({+ noteId,+ includeTranscript = false,+ }: {+ noteId: string;+ includeTranscript?: boolean;+ }) =>+ requestOrThrow({+ path: `/notes/${encodeURIComponent(noteId)}`,+ parameters: { include: includeTranscript ? 'transcript' : undefined },+ schema: GRANOLA_NOTE_SCHEMA,+ }),+ listTranscriptPage: ({+ noteId,+ ...parameters+ }: {+ noteId: string;+ cursor?: string;+ page_size?: number;+ }) =>+ requestOrThrow({+ path: `/notes/${encodeURIComponent(noteId)}/transcript`,+ parameters,+ schema: GRANOLA_PAGINATION_SCHEMA.extend({+ transcript: z.array(GRANOLA_TRANSCRIPT_ITEM_SCHEMA),+ }),+ }),+ listFolders: (parameters: { cursor?: string; page_size?: number } = {}) =>+ requestOrThrow({+ path: '/folders',+ parameters,+ schema: GRANOLA_PAGINATION_SCHEMA.extend({+ folders: z.array(GRANOLA_FOLDER_SCHEMA),+ }),+ }),+ createWebhookEndpoint: (body: GranolaCreateWebhookEndpointParameters) =>+ requestOrThrow({+ path: '/webhook-endpoints',+ method: 'POST',+ body,+ schema: GRANOLA_WEBHOOK_ENDPOINT_SCHEMA.extend({+ signing_secret: z.string().startsWith('whsec_'),+ }),+ }),+ listWebhookEndpoints: () =>+ requestOrThrow({+ path: '/webhook-endpoints',+ schema: z.object({+ webhook_endpoints: z.array(GRANOLA_WEBHOOK_ENDPOINT_SCHEMA),+ }),+ }),+ updateWebhookEndpoint: ({+ webhookEndpointId,+ ...body+ }: GranolaUpdateWebhookEndpointParameters) =>+ requestOrThrow({+ path: `/webhook-endpoints/${encodeURIComponent(webhookEndpointId)}`,+ method: 'PATCH',+ body,+ schema: GRANOLA_WEBHOOK_ENDPOINT_SCHEMA,+ }),+ deleteWebhookEndpoint: ({+ webhookEndpointId,+ }: {+ webhookEndpointId: string;+ }) =>+ requestOrThrow({+ path: `/webhook-endpoints/${encodeURIComponent(webhookEndpointId)}`,+ method: 'DELETE',+ schema: z.object({+ id: z.string(),+ object: z.literal('webhook_endpoint'),+ deleted: z.literal(true),+ }),+ }),+ };+};diff --git a/packages/twenty-apps/public/granola/src/types/styles.d.ts b/packages/twenty-apps/public/granola/src/types/styles.d.tsnew file mode 100644index 00000000000..1c8c0694c17--- /dev/null+++ b/packages/twenty-apps/public/granola/src/types/styles.d.ts@@ -0,0 +1 @@+declare module 'twenty-ui/style.css';