The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
LinkedIn app: import history, create and match People (#29285)
martmull72fa1c04e05e
diff --git a/packages/twenty-apps/public/linkedin/README.md b/packages/twenty-apps/public/linkedin/README.mdindex 5c34309a5f8..94efab70bc3 100644--- a/packages/twenty-apps/public/linkedin/README.md+++ b/packages/twenty-apps/public/linkedin/README.md@@ -5,8 +5,6 @@## ✨ What you get- **LinkedIn messages in Twenty**: every message you send or receive lands on the matching Person and Company, next to their emails-- **Private by default**: teammates see who you talked to and when, never what was said-- **Matched on the LinkedIn field**: a conversation links to the Person whose LinkedIn profile URL matches- **One connection per member**: each teammate connects their own LinkedIn account in a few clicks## 💳 Billing@@ -20,8 +18,8 @@## 📌 Heads up-- **Read-only for now.** Messages are imported as they happen; reply from LinkedIn.-- **New messages only.** Conversations from before you connected are not imported yet.-- **No contacts created.** A sender with no matching Person is kept on the message but appears on no record until you add their LinkedIn URL to a Person.+- **Read-only for now.** Messages are imported as they happen; reply from LinkedIn. Marking chats as read on LinkedIn is not available yet.+- **Namesakes are not guessed.** When several People share a participant's name, nobody is linked: add the LinkedIn URL to the right Person and their messages link to it.+- **Settings are per member.** Import, visibility, contact auto-creation and people matching live in **Settings → App preferences → LinkedIn → Sync** and apply to your own connection.Self-hosting or developing the app? See [SETUP.md](./SETUP.md).diff --git a/packages/twenty-apps/public/linkedin/package.json b/packages/twenty-apps/public/linkedin/package.jsonindex c74836ae1b0..c5abbde6e80 100644--- a/packages/twenty-apps/public/linkedin/package.json+++ b/packages/twenty-apps/public/linkedin/package.json@@ -1,6 +1,6 @@{"name": "@twentyhq/linkedin",- "version": "0.1.0",+ "version": "0.2.0","description": "LinkedIn messages in Twenty: each member connects their LinkedIn account through Unipile and their conversations land on People timelines.","license": "MIT","engines": {@@ -33,11 +33,17 @@"@unipile/sdk": "^2.59.0"},"devDependencies": {+ "@emotion/react": "^11.14.0",+ "@emotion/styled": "^11.14.0","@types/node": "^24.7.2",+ "@types/react": "^19.0.0","@typescript/native-preview": "^7.0.0-dev.20260116.1","oxlint": "^0.16.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0","twenty-client-sdk": "2.53.0","twenty-sdk": "2.53.0",+ "twenty-ui": "^2.53.0","typescript": "^5.9.3","vite-tsconfig-paths": "^4.2.1","vitest": "^4.1.12"diff --git a/packages/twenty-apps/public/linkedin/src/constants/default-linkedin-settings.constant.ts b/packages/twenty-apps/public/linkedin/src/constants/default-linkedin-settings.constant.tsnew file mode 100644index 00000000000..551d0a6bf1d--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/constants/default-linkedin-settings.constant.ts@@ -0,0 +1,8 @@+import { type LinkedinSettings } from 'src/types/linkedin-settings.type';++export const DEFAULT_LINKEDIN_SETTINGS: LinkedinSettings = {+ importPolicy: 'ALL',+ areGroupChatsImported: true,+ contactAutoCreationPolicy: 'SENT',+ isNameMatchingEnabled: true,+};diff --git a/packages/twenty-apps/public/linkedin/src/constants/ingest-messages-max-batch-size.constant.ts b/packages/twenty-apps/public/linkedin/src/constants/ingest-messages-max-batch-size.constant.tsnew file mode 100644index 00000000000..9852635b9d3--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/constants/ingest-messages-max-batch-size.constant.ts@@ -0,0 +1 @@+export const INGEST_MESSAGES_MAX_BATCH_SIZE = 100;diff --git a/packages/twenty-apps/public/linkedin/src/constants/linkedin-history-import-chats-per-job.constant.ts b/packages/twenty-apps/public/linkedin/src/constants/linkedin-history-import-chats-per-job.constant.tsnew file mode 100644index 00000000000..da9257a9063--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/constants/linkedin-history-import-chats-per-job.constant.ts@@ -0,0 +1 @@+export const LINKEDIN_HISTORY_IMPORT_CHATS_PER_JOB = 20;diff --git a/packages/twenty-apps/public/linkedin/src/constants/linkedin-import-history-timeout-seconds.constant.ts b/packages/twenty-apps/public/linkedin/src/constants/linkedin-import-history-timeout-seconds.constant.tsnew file mode 100644index 00000000000..489ac5ed068--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/constants/linkedin-import-history-timeout-seconds.constant.ts@@ -0,0 +1 @@+export const LINKEDIN_IMPORT_HISTORY_TIMEOUT_SECONDS = 900;diff --git a/packages/twenty-apps/public/linkedin/src/constants/linkedin-settings-route-paths.constant.ts b/packages/twenty-apps/public/linkedin/src/constants/linkedin-settings-route-paths.constant.tsnew file mode 100644index 00000000000..6108486dc8e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/constants/linkedin-settings-route-paths.constant.ts@@ -0,0 +1,6 @@+export const LINKEDIN_SETTINGS_ROUTE_PATHS = {+ get: '/linkedin/settings',+ update: '/linkedin/settings/update',+ syncHistory: '/linkedin/history/sync',+ cancelHistoryImport: '/linkedin/history/cancel',+} as const;diff --git a/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.tsindex 870e22f7367..737c166c0aa 100644--- a/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.ts@@ -30,3 +30,27 @@ export const LINKEDIN_UNINSTALL_UNIVERSAL_IDENTIFIER =export const LINKEDIN_HEALTH_CHECK_UNIVERSAL_IDENTIFIER ='4d15b952-d4dd-437a-903e-37d5d158aaaa';++export const LINKEDIN_GET_SETTINGS_UNIVERSAL_IDENTIFIER =+ 'a5ea1c3a-acc6-4d54-a49f-ce5c93ff3da6';++export const LINKEDIN_UPDATE_SETTINGS_UNIVERSAL_IDENTIFIER =+ 'ebfd5658-0376-474f-8ba8-2e00da3fb89c';++export const LINKEDIN_IMPORT_HISTORY_UNIVERSAL_IDENTIFIER =+ '643ff3a0-a0a8-49da-9c2a-a2650cb89355';++export const LINKEDIN_SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER =+ '0f517074-7144-400c-8490-c4ebeddb2541';++export const LINKEDIN_SETTINGS_MENU_ITEM_UNIVERSAL_IDENTIFIER =+ '7d48ab00-8e9c-408b-b7ea-8e752c59ee7a';++export const LINKEDIN_SYNC_HISTORY_UNIVERSAL_IDENTIFIER =+ 'ef9f2638-0b4a-4eb8-9251-a0b7b30e2aa7';++export const LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER =+ '40f9ac48-419a-4520-a650-ea5125a1a9fa';++export const LINKEDIN_CANCEL_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER =+ 'ef8af448-c120-43a3-87a0-001d7b3c7f4e';diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/AnimatedCount.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/AnimatedCount.tsxnew file mode 100644index 00000000000..1d6710466be--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/AnimatedCount.tsx@@ -0,0 +1,39 @@+import { keyframes } from '@emotion/react';+import styled from '@emotion/styled';++const rollIn = keyframes`+ from {+ opacity: 0;+ transform: translateY(60%);+ }++ to {+ opacity: 1;+ transform: translateY(0);+ }+`;++const StyledContainer = styled.span`+ display: inline-flex;+ overflow: hidden;+ vertical-align: bottom;+`;++const StyledValue = styled.span`+ animation: ${rollIn} 300ms cubic-bezier(0.2, 0, 0, 1);+ display: inline-block;++ @media (prefers-reduced-motion: reduce) {+ animation: none;+ }+`;++type AnimatedCountProps = {+ count: number;+};++export const AnimatedCount = ({ count }: AnimatedCountProps) => (+ <StyledContainer>+ <StyledValue key={count}>{count.toLocaleString()}</StyledValue>+ </StyledContainer>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinAccountField.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinAccountField.tsxnew file mode 100644index 00000000000..b6b2d7cf702--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinAccountField.tsx@@ -0,0 +1,82 @@+import styled from '@emotion/styled';+import { useId } from 'react';+import { t } from 'twenty-sdk/front-component';+import { InlineBanner } from 'twenty-ui/components/feedback';+import { themeCssVariables } from 'twenty-ui/theme';+import { getPublicAssetUrl } from 'twenty-sdk/utils';++const StyledContainer = styled.div`+ border-bottom: 1px solid ${() => themeCssVariables.border.color.light};+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[1]};+ padding-bottom: ${() => themeCssVariables.spacing[6]};+`;++const StyledLabel = styled.span`+ color: ${() => themeCssVariables.font.color.tertiary};+ font-size: ${() => themeCssVariables.font.size.xs};+ font-weight: ${() => themeCssVariables.font.weight.semiBold};+`;++const StyledValue = styled.div`+ align-items: center;+ background-color: ${() => themeCssVariables.background.transparent.lighter};+ border: 1px solid ${() => themeCssVariables.border.color.medium};+ border-radius: ${() => themeCssVariables.border.radius.sm};+ color: ${() => themeCssVariables.font.color.primary};+ display: flex;+ gap: ${() => themeCssVariables.spacing[2]};+ height: ${() => themeCssVariables.spacing[8]};+ min-width: 0;+ padding: 0 ${() => themeCssVariables.spacing[2]};+`;++const StyledLogo = styled.img`+ flex-shrink: 0;+ height: ${() => themeCssVariables.spacing[4]};+ width: ${() => themeCssVariables.spacing[4]};+`;++const StyledText = styled.span`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+`;++const StyledHandle = styled.span`+ color: ${() => themeCssVariables.font.color.tertiary};+`;++type LinkedinAccountFieldProps = {+ name: string;+ handle: string;+ isAuthFailed: boolean;+};++export const LinkedinAccountField = ({+ name,+ handle,+ isAuthFailed,+}: LinkedinAccountFieldProps) => {+ const labelId = useId();++ return (+ <StyledContainer>+ <StyledLabel id={labelId}>{t('Account')}</StyledLabel>+ <StyledValue aria-labelledby={labelId}>+ <StyledLogo src={getPublicAssetUrl('linkedin-logomark.svg')} alt="" />+ <StyledText>+ {name} <StyledHandle>· {handle}</StyledHandle>+ </StyledText>+ </StyledValue>+ {isAuthFailed && (+ <InlineBanner layout="compact" status="warning">+ {t(+ 'LinkedIn signed you out. Reconnect your account to keep syncing.',+ )}+ </InlineBanner>+ )}+ </StyledContainer>+ );+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinContactAutoCreationIcon.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinContactAutoCreationIcon.tsxnew file mode 100644index 00000000000..1869ac700c8--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinContactAutoCreationIcon.tsx@@ -0,0 +1,57 @@+import styled from '@emotion/styled';+import { IconArrowDown, IconArrowUp } from 'twenty-ui/icon';+import { THEME_COMMON, themeCssVariables } from 'twenty-ui/theme';++const StyledIconContainer = styled.div`+ align-items: stretch;+ border: 2px solid ${() => themeCssVariables.border.color.medium};+ border-radius: ${() => themeCssVariables.border.radius.sm};+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ flex-shrink: 0;+ gap: 2px;+ height: 40px;+ justify-content: center;+ padding: 2px;+ width: 32px;+`;++const StyledDirectionSkeleton = styled.div<{ $isActive: boolean }>`+ align-items: center;+ background-color: ${({ $isActive }) =>+ $isActive+ ? themeCssVariables.accent.accent7+ : themeCssVariables.border.color.medium};+ border-radius: 1px;+ color: ${() => themeCssVariables.font.color.inverted};+ display: flex;+ flex: 1 0 0;+ justify-content: center;+ min-height: 0;+`;++type LinkedinContactAutoCreationIconProps = {+ isSentActive: boolean;+ isReceivedActive: boolean;+};++export const LinkedinContactAutoCreationIcon = ({+ isSentActive,+ isReceivedActive,+}: LinkedinContactAutoCreationIconProps) => (+ <StyledIconContainer>+ <StyledDirectionSkeleton $isActive={isSentActive}>+ <IconArrowUp+ size={THEME_COMMON.icon.size.sm}+ stroke={THEME_COMMON.icon.stroke.md}+ />+ </StyledDirectionSkeleton>+ <StyledDirectionSkeleton $isActive={isReceivedActive}>+ <IconArrowDown+ size={THEME_COMMON.icon.size.sm}+ stroke={THEME_COMMON.icon.stroke.md}+ />+ </StyledDirectionSkeleton>+ </StyledIconContainer>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinContactAutoCreationSection.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinContactAutoCreationSection.tsxnew file mode 100644index 00000000000..c80f570f8fb--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinContactAutoCreationSection.tsx@@ -0,0 +1,61 @@+import { t } from 'twenty-sdk/front-component';+import { Section } from 'twenty-ui/components/layout';++import { LinkedinContactAutoCreationIcon } from 'src/front-components/components/LinkedinContactAutoCreationIcon';+import { SettingsRadioCard } from 'src/front-components/components/SettingsRadioCard';+import { type LinkedinContactAutoCreationPolicy } from 'src/types/linkedin-contact-auto-creation-policy.type';++type LinkedinContactAutoCreationSectionProps = {+ policy: LinkedinContactAutoCreationPolicy;+ onChange: (policy: LinkedinContactAutoCreationPolicy) => void;+};++export const LinkedinContactAutoCreationSection = ({+ policy,+ onChange,+}: LinkedinContactAutoCreationSectionProps) => (+ <Section.Root>+ <Section.Header+ title={t('Contact auto-creation')}+ description={t(+ 'Automatically create People records for the profiles you chat with',+ )}+ />+ <SettingsRadioCard+ value={policy}+ onChange={onChange}+ options={[+ {+ value: 'SENT_AND_RECEIVED',+ cardMedia: (+ <LinkedinContactAutoCreationIcon isSentActive isReceivedActive />+ ),+ title: t('Sent and Received'),+ description: t('People I’ve messaged and received messages from.'),+ },+ {+ value: 'SENT',+ cardMedia: (+ <LinkedinContactAutoCreationIcon+ isSentActive+ isReceivedActive={false}+ />+ ),+ title: t('Sent'),+ description: t('People I’ve messaged.'),+ },+ {+ value: 'NONE',+ cardMedia: (+ <LinkedinContactAutoCreationIcon+ isSentActive={false}+ isReceivedActive={false}+ />+ ),+ title: t('None'),+ description: t('Don’t auto-create contacts.'),+ },+ ]}+ />+ </Section.Root>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportPolicyIcon.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportPolicyIcon.tsxnew file mode 100644index 00000000000..56c2d24ac4b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportPolicyIcon.tsx@@ -0,0 +1,73 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme';++import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';++const StyledCardMedia = styled.div`+ background-color: ${() => themeCssVariables.border.color.medium};+ border-radius: ${() => themeCssVariables.border.radius.sm};+ box-sizing: border-box;+ display: flex;+ flex-shrink: 0;+ height: 40px;+ padding: 2px;+ width: 32px;+`;++const StyledCardMediaContent = styled.div`+ background-color: ${() => themeCssVariables.background.secondary};+ border-radius: ${() => themeCssVariables.border.radius.xs};+ box-sizing: border-box;+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 2px;+ justify-content: center;+ padding: 2px;+`;++const StyledRow = styled.div`+ display: flex;+ flex: 1 0 0;+ gap: 2px;+ min-height: 0;+`;++const StyledBullet = styled.div<{ $isActive: boolean }>`+ background-color: ${({ $isActive }) =>+ $isActive+ ? themeCssVariables.accent.accent7+ : themeCssVariables.border.color.medium};+ border-radius: 1px;+ width: 4.8px;+`;++const StyledLabel = styled(StyledBullet)`+ flex: 1;+ width: auto;+`;++const ROW_IS_ACTIVE_FOR_CONTACTS_ONLY = [false, false, true, false, true];++type LinkedinImportPolicyIconProps = {+ importPolicy: LinkedinImportPolicy;+};++export const LinkedinImportPolicyIcon = ({+ importPolicy,+}: LinkedinImportPolicyIconProps) => (+ <StyledCardMedia>+ <StyledCardMediaContent>+ {ROW_IS_ACTIVE_FOR_CONTACTS_ONLY.map((isActiveForContactsOnly, index) => {+ const isActive = importPolicy === 'ALL' || isActiveForContactsOnly;++ return (+ <StyledRow key={index}>+ <StyledBullet $isActive={isActive} />+ <StyledLabel $isActive={isActive} />+ </StyledRow>+ );+ })}+ </StyledCardMediaContent>+ </StyledCardMedia>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportSection.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportSection.tsxnew file mode 100644index 00000000000..e1f96fa3610--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportSection.tsx@@ -0,0 +1,93 @@+import styled from '@emotion/styled';+import { t } from 'twenty-sdk/front-component';+import { Section } from 'twenty-ui/components/layout';+import { IconUsers } from 'twenty-ui/icon';+import { themeCssVariables } from 'twenty-ui/theme';++import { LinkedinImportPolicyIcon } from 'src/front-components/components/LinkedinImportPolicyIcon';+import { LinkedinSyncButton } from 'src/front-components/components/LinkedinSyncButton';+import { SettingsOptionCardContentToggle } from 'src/front-components/components/SettingsOptionCardContentToggle';+import { SettingsRadioCard } from 'src/front-components/components/SettingsRadioCard';+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';+import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';++const StyledStack = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[4]};+`;++type LinkedinImportSectionProps = {+ importPolicy: LinkedinImportPolicy;+ areGroupChatsImported: boolean;+ historyImport: LinkedinHistoryImportState | null;+ syncProgress: number | undefined;+ isSyncStarting: boolean;+ isSyncCancelling: boolean;+ onChange: (importPolicy: LinkedinImportPolicy) => void;+ onGroupChatsImportChange: (areGroupChatsImported: boolean) => void;+ onSync: () => void;+ onCancelSync: () => void;+};++export const LinkedinImportSection = ({+ importPolicy,+ areGroupChatsImported,+ historyImport,+ syncProgress,+ isSyncStarting,+ isSyncCancelling,+ onChange,+ onGroupChatsImportChange,+ onSync,+ onCancelSync,+}: LinkedinImportSectionProps) => (+ <Section.Root>+ <Section.Header+ title={t('Import')}+ description={t(+ 'Choose which LinkedIn conversations are imported, past ones included.',+ )}+ />+ <StyledStack>+ <SettingsRadioCard+ value={importPolicy}+ onChange={onChange}+ options={[+ {+ value: 'ALL',+ cardMedia: <LinkedinImportPolicyIcon importPolicy="ALL" />,+ title: t('All chats'),+ description: t('Import every conversation'),+ },+ {+ value: 'CONTACTS_ONLY',+ cardMedia: (+ <LinkedinImportPolicyIcon importPolicy="CONTACTS_ONLY" />+ ),+ title: t('Contacts only'),+ description: t('Import chats with people already in Twenty'),+ },+ ]}+ />+ <StyledSettingsCard>+ <SettingsOptionCardContentToggle+ Icon={IconUsers}+ title={t('Import group chats')}+ description={t('Groups where at least one member is a contact')}+ checked={areGroupChatsImported}+ onChange={onGroupChatsImportChange}+ />+ </StyledSettingsCard>+ <LinkedinSyncButton+ historyImport={historyImport}+ progress={syncProgress}+ isStarting={isSyncStarting}+ isCancelling={isSyncCancelling}+ onSync={onSync}+ onCancel={onCancelSync}+ />+ </StyledStack>+ </Section.Root>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinPeopleMatchingSection.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinPeopleMatchingSection.tsxnew file mode 100644index 00000000000..8b71b2d601c--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinPeopleMatchingSection.tsx@@ -0,0 +1,54 @@+import { t } from 'twenty-sdk/front-component';+import { Section } from 'twenty-ui/components/layout';+import { IconBrandLinkedin, IconId } from 'twenty-ui/icon';++import { StyledSettingsCardIcon } from 'src/front-components/components/SettingsCardContentBase';+import { SettingsOptionIconCustomizer } from 'src/front-components/components/SettingsOptionIconCustomizer';+import { SettingsRadioCard } from 'src/front-components/components/SettingsRadioCard';++type LinkedinPeopleMatchingSectionProps = {+ isNameMatchingEnabled: boolean;+ onChange: (isNameMatchingEnabled: boolean) => void;+};++export const LinkedinPeopleMatchingSection = ({+ isNameMatchingEnabled,+ onChange,+}: LinkedinPeopleMatchingSectionProps) => (+ <Section.Root>+ <Section.Header+ title={t('People matching')}+ description={t('How Twenty finds the person behind a LinkedIn profile')}+ />+ <SettingsRadioCard+ value={isNameMatchingEnabled ? 'PROFILE_THEN_NAME' : 'PROFILE'}+ onChange={(value) => onChange(value === 'PROFILE_THEN_NAME')}+ options={[+ {+ value: 'PROFILE',+ cardMedia: (+ <StyledSettingsCardIcon>+ <SettingsOptionIconCustomizer Icon={IconBrandLinkedin} />+ </StyledSettingsCardIcon>+ ),+ title: t('LinkedIn profile'),+ description: t(+ 'Match the profile against the LinkedIn field on People.',+ ),+ },+ {+ value: 'PROFILE_THEN_NAME',+ cardMedia: (+ <StyledSettingsCardIcon>+ <SettingsOptionIconCustomizer Icon={IconId} />+ </StyledSettingsCardIcon>+ ),+ title: t('LinkedIn profile, then name'),+ description: t(+ 'Otherwise link the only person with the same first and last name.',+ ),+ },+ ]}+ />+ </Section.Root>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinReadStatusSection.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinReadStatusSection.tsxnew file mode 100644index 00000000000..b5ef8dc6128--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinReadStatusSection.tsx@@ -0,0 +1,27 @@+import { t } from 'twenty-sdk/front-component';+import { Section } from 'twenty-ui/components/layout';+import { IconCheck } from 'twenty-ui/icon';++import { SettingsOptionCardContentToggle } from 'src/front-components/components/SettingsOptionCardContentToggle';+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';++export const LinkedinReadStatusSection = () => (+ <Section.Root>+ <Section.Header+ title={t('Read status')}+ description={t('Keep LinkedIn and Twenty in sync')}+ />+ <StyledSettingsCard>+ <SettingsOptionCardContentToggle+ Icon={IconCheck}+ title={t('Mark chats as read on LinkedIn')}+ description={t(+ 'Coming soon: opening a chat in Twenty marks it as read on LinkedIn',+ )}+ disabled+ checked={false}+ onChange={() => undefined}+ />+ </StyledSettingsCard>+ </Section.Root>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettings.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettings.tsxnew file mode 100644index 00000000000..892315b6095--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettings.tsx@@ -0,0 +1,269 @@+import 'twenty-ui/style.css';+import 'twenty-ui/theme-dark.css';+import 'twenty-ui/theme-light.css';++import styled from '@emotion/styled';+import { useRef, useState } from 'react';+import { enqueueSnackbar, t, useColorScheme } from 'twenty-sdk/front-component';+import { InlineBanner } from 'twenty-ui/components/feedback';+import { Section } from 'twenty-ui/components/layout';+import {+ THEME_DARK,+ THEME_LIGHT,+ ThemeProvider,+ themeCssVariables,+} from 'twenty-ui/theme';++import { LINKEDIN_SETTINGS_ROUTE_PATHS } from 'src/constants/linkedin-settings-route-paths.constant';+import { LinkedinAccountField } from 'src/front-components/components/LinkedinAccountField';+import { LinkedinContactAutoCreationSection } from 'src/front-components/components/LinkedinContactAutoCreationSection';+import { LinkedinImportSection } from 'src/front-components/components/LinkedinImportSection';+import { LinkedinPeopleMatchingSection } from 'src/front-components/components/LinkedinPeopleMatchingSection';+import { LinkedinSettingsSkeleton } from 'src/front-components/components/LinkedinSettingsSkeleton';+import { LinkedinReadStatusSection } from 'src/front-components/components/LinkedinReadStatusSection';+import { LinkedinVisibilitySection } from 'src/front-components/components/LinkedinVisibilitySection';+import { OnMountEffect } from 'src/front-components/components/OnMountEffect';+import { TimeoutEffect } from 'src/front-components/components/TimeoutEffect';+import { getNextLinkedinSyncProgress } from 'src/front-components/utils/get-next-linkedin-sync-progress.util';+import { notifyLinkedinHistoryImportEnd } from 'src/front-components/utils/notify-linkedin-history-import-end.util';+import { postLinkedinSettingsRouteOrThrow } from 'src/front-components/utils/post-linkedin-settings-route-or-throw.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';+import { type LinkedinSettingsView } from 'src/types/linkedin-settings-view.type';++type LinkedinSettingsValues = Extract<+ LinkedinSettingsView,+ { isConnected: true }+>['settings'];++const HISTORY_IMPORT_POLL_MILLISECONDS = 2000;++const StyledContainer = styled.div`+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[8]};+ width: 100%;++ button svg {+ pointer-events: none;+ }+`;++type LinkedinSettingsState =+ | { step: 'loading' }+ | { step: 'unavailable' }+ | { step: 'ready'; view: LinkedinSettingsView };++export const LinkedinSettings = () => {+ const colorScheme = useColorScheme();+ const [state, setState] = useState<LinkedinSettingsState>({+ step: 'loading',+ });+ const [pollCount, setPollCount] = useState(0);++ const [isSyncStarting, setIsSyncStarting] = useState(false);+ const [isSyncCancelling, setIsSyncCancelling] = useState(false);+ const [syncProgress, setSyncProgress] = useState<{+ runId: string;+ progress: number;+ } | null>(null);+ const lastHistoryImportRef = useRef<LinkedinHistoryImportState | null>(null);+ const settingsSaveQueueRef = useRef<Promise<void>>(Promise.resolve());++ const showView = (view: LinkedinSettingsView) => {+ const historyImport = view.isConnected ? view.historyImport : null;++ notifyLinkedinHistoryImportEnd({+ previous: lastHistoryImportRef.current,+ next: historyImport,+ });+ lastHistoryImportRef.current = historyImport;+ setSyncProgress((current) =>+ getNextLinkedinSyncProgress({ current, historyImport }),+ );+ setState({ step: 'ready', view });+ };++ const loadSettings = async () => {+ try {+ showView(+ await postLinkedinSettingsRouteOrThrow({+ routePath: LINKEDIN_SETTINGS_ROUTE_PATHS.get,+ }),+ );+ } catch {+ setState((current) =>+ current.step === 'ready' ? current : { step: 'unavailable' },+ );+ } finally {+ setPollCount((previousPollCount) => previousPollCount + 1);+ }+ };++ const handleSettingsChange = async (+ update: Partial<LinkedinSettingsValues>,+ ) => {+ setState((current) =>+ current.step === 'ready' && current.view.isConnected+ ? {+ step: 'ready',+ view: {+ ...current.view,+ settings: { ...current.view.settings, ...update },+ },+ }+ : current,+ );++ const save = async () => {+ try {+ showView(+ await postLinkedinSettingsRouteOrThrow({+ routePath: LINKEDIN_SETTINGS_ROUTE_PATHS.update,+ body: update,+ }),+ );+ } catch {+ enqueueSnackbar({+ message: t('Could not save LinkedIn settings. Try again.'),+ variant: 'error',+ });+ await loadSettings();+ }+ };++ settingsSaveQueueRef.current = settingsSaveQueueRef.current.then(save);++ await settingsSaveQueueRef.current;+ };++ const handleSync = async () => {+ setIsSyncStarting(true);++ try {+ showView(+ await postLinkedinSettingsRouteOrThrow({+ routePath: LINKEDIN_SETTINGS_ROUTE_PATHS.syncHistory,+ }),+ );+ } catch {+ enqueueSnackbar({+ message: t('Could not start the LinkedIn sync. Try again.'),+ variant: 'error',+ });+ } finally {+ setIsSyncStarting(false);+ }+ };++ const handleCancelSync = async () => {+ setIsSyncCancelling(true);++ try {+ showView(+ await postLinkedinSettingsRouteOrThrow({+ routePath: LINKEDIN_SETTINGS_ROUTE_PATHS.cancelHistoryImport,+ }),+ );+ } catch {+ enqueueSnackbar({+ message: t('Could not cancel the LinkedIn sync. Try again.'),+ variant: 'error',+ });+ } finally {+ setIsSyncCancelling(false);+ }+ };++ const view = state.step === 'ready' ? state.view : undefined;+ const isImportingHistory =+ view?.isConnected === true && view.historyImport?.status === 'IMPORTING';++ return (+ <ThemeProvider+ colorScheme={colorScheme}+ theme={colorScheme === 'dark' ? THEME_DARK : THEME_LIGHT}+ >+ <StyledContainer>+ <OnMountEffect onMount={loadSettings} />+ {isImportingHistory && (+ <TimeoutEffect+ key={pollCount}+ delayMilliseconds={HISTORY_IMPORT_POLL_MILLISECONDS}+ onTimeout={loadSettings}+ />+ )}+ {state.step === 'loading' && <LinkedinSettingsSkeleton />}+ {state.step === 'unavailable' && (+ <InlineBanner+ layout="compact"+ status="error"+ action={+ <InlineBanner.Action onClick={loadSettings}>+ {t('Retry')}+ </InlineBanner.Action>+ }+ >+ {t('Could not load LinkedIn settings.')}+ </InlineBanner>+ )}+ {view?.isConnected === false && (+ <Section.Root>+ <Section.Header+ title={t('Account')}+ description={t(+ 'Connect your LinkedIn account to choose what gets synced.',+ )}+ />+ </Section.Root>+ )}+ {view?.isConnected === true && (+ <>+ <LinkedinAccountField+ name={view.connection.name}+ handle={view.connection.handle}+ isAuthFailed={view.connection.isAuthFailed}+ />+ <LinkedinImportSection+ importPolicy={view.settings.importPolicy}+ areGroupChatsImported={view.settings.areGroupChatsImported}+ historyImport={view.historyImport}+ syncProgress={+ syncProgress?.runId === view.historyImport?.runId+ ? syncProgress?.progress+ : undefined+ }+ isSyncStarting={isSyncStarting}+ isSyncCancelling={isSyncCancelling}+ onChange={(importPolicy) =>+ handleSettingsChange({ importPolicy })+ }+ onGroupChatsImportChange={(areGroupChatsImported) =>+ handleSettingsChange({ areGroupChatsImported })+ }+ onSync={handleSync}+ onCancelSync={handleCancelSync}+ />+ <LinkedinVisibilitySection+ visibility={view.settings.visibility}+ onChange={(visibility) => handleSettingsChange({ visibility })}+ />+ <LinkedinContactAutoCreationSection+ policy={view.settings.contactAutoCreationPolicy}+ onChange={(contactAutoCreationPolicy) =>+ handleSettingsChange({ contactAutoCreationPolicy })+ }+ />+ <LinkedinPeopleMatchingSection+ isNameMatchingEnabled={view.settings.isNameMatchingEnabled}+ onChange={(isNameMatchingEnabled) =>+ handleSettingsChange({ isNameMatchingEnabled })+ }+ />+ <LinkedinReadStatusSection />+ </>+ )}+ </StyledContainer>+ </ThemeProvider>+ );+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettingsSkeleton.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettingsSkeleton.tsxnew file mode 100644index 00000000000..f089515837f--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettingsSkeleton.tsx@@ -0,0 +1,51 @@+import styled from '@emotion/styled';+import { t } from 'twenty-sdk/front-component';+import { SKELETON_HEIGHT_SIZES, Skeleton } from 'twenty-ui/primitives/feedback';+import { themeCssVariables } from 'twenty-ui/theme';++const TITLE_WIDTH = 140;+const LAST_DESCRIPTION_LINE_WIDTH = '60%';+const ROW_COUNT = 5;++const StyledContainer = styled.div`+ display: flex;+ flex-direction: column;+ width: 100%;+`;++const StyledDescription = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[1]};+ margin-bottom: ${() => themeCssVariables.spacing[6]};+ margin-top: ${() => themeCssVariables.spacing[2]};+`;++const StyledRows = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[2]};+`;++export const LinkedinSettingsSkeleton = () => (+ <StyledContainer aria-busy="true" aria-label={t('Loading')}>+ <Skeleton+ layout="block"+ width={TITLE_WIDTH}+ height={SKELETON_HEIGHT_SIZES.s}+ />+ <StyledDescription>+ <Skeleton layout="block" height={SKELETON_HEIGHT_SIZES.xs} />+ <Skeleton+ layout="block"+ width={LAST_DESCRIPTION_LINE_WIDTH}+ height={SKELETON_HEIGHT_SIZES.xs}+ />+ </StyledDescription>+ <StyledRows>+ {Array.from({ length: ROW_COUNT }, (_, index) => (+ <Skeleton key={index} layout="block" height={SKELETON_HEIGHT_SIZES.l} />+ ))}+ </StyledRows>+ </StyledContainer>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSyncButton.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSyncButton.tsxnew file mode 100644index 00000000000..43abe10e2c2--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSyncButton.tsx@@ -0,0 +1,139 @@+import styled from '@emotion/styled';+import { t } from 'twenty-sdk/front-component';+import { isDefined } from 'twenty-sdk/utils';+import { IconRefresh } from 'twenty-ui/icon';+import { Button } from 'twenty-ui/primitives/input';+import { themeCssVariables } from 'twenty-ui/theme';++import { AnimatedCount } from 'src/front-components/components/AnimatedCount';+import { formatLinkedinSyncProgressLabel } from 'src/front-components/utils/format-linkedin-sync-progress-label.util';+import { getLinkedinHistoryImportErrorReason } from 'src/front-components/utils/get-linkedin-history-import-error-reason.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const StyledContainer = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${() => themeCssVariables.spacing[2]};+`;++const StyledCaption = styled.p`+ color: ${() => themeCssVariables.font.color.tertiary};+ font-size: ${() => themeCssVariables.font.size.sm};+ margin: 0;+ text-align: right;+`;++const StyledRow = styled.div`+ align-items: center;+ display: flex;+ gap: ${() => themeCssVariables.spacing[4]};+ justify-content: flex-end;+`;++const StyledError = styled.p`+ color: ${() => themeCssVariables.color.red};+ flex: 1;+ font-size: ${() => themeCssVariables.font.size.sm};+ margin: 0;+ min-width: 0;+`;++const StyledErrorTitle = styled.span`+ font-weight: ${() => themeCssVariables.font.weight.medium};+`;++type LinkedinSyncButtonProps = {+ historyImport: LinkedinHistoryImportState | null;+ progress: number | undefined;+ isStarting: boolean;+ isCancelling: boolean;+ onSync: () => void;+ onCancel: () => void;+};++export const LinkedinSyncButton = ({+ historyImport,+ progress,+ isStarting,+ isCancelling,+ onSync,+ onCancel,+}: LinkedinSyncButtonProps) => {+ const isRunning = historyImport?.status === 'IMPORTING';+ const hasFailed = historyImport?.status === 'FAILED';++ const isListing =+ isRunning &&+ !isDefined(historyImport.chunkCount) &&+ !isDefined(historyImport.totalConversationCount);++ const label = isRunning+ ? isDefined(progress)+ ? t('Syncing {progress}', {+ progress: formatLinkedinSyncProgressLabel(progress),+ })+ : t('Syncing…')+ : hasFailed+ ? t('Retry')+ : t('Sync now');++ return (+ <StyledContainer>+ <StyledRow>+ {hasFailed && (+ <StyledError role="alert">+ <StyledErrorTitle>+ {t('The import stopped before finishing.')}+ </StyledErrorTitle>{' '}+ {getLinkedinHistoryImportErrorReason(historyImport.error)}+ </StyledError>+ )}+ {isRunning && (+ <Button+ variant="outline"+ size="md"+ onClick={onCancel}+ loading={isCancelling}+ disabled={isCancelling}+ >+ {t('Cancel')}+ </Button>+ )}+ <Button+ startIcon={<IconRefresh />}+ variant="solid"+ color="accent"+ size="md"+ onClick={onSync}+ loading={isRunning || isStarting}+ loadingPosition="end"+ >+ {label}+ </Button>+ </StyledRow>+ {isRunning && isDefined(historyImport.resumeAt) ? (+ <StyledCaption aria-live="polite">+ {t(+ 'LinkedIn limits how much can be imported each day. The sync resumes {resumeAt}.',+ {+ resumeAt: new Date(historyImport.resumeAt).toLocaleString(+ undefined,+ { weekday: 'short', hour: 'numeric', minute: '2-digit' },+ ),+ },+ )}+ </StyledCaption>+ ) : (+ isListing && (+ <StyledCaption aria-live="polite">+ {t('Listing conversations')} (+ <AnimatedCount+ count={historyImport.plannedConversationCount ?? 0}+ />+ )+ </StyledCaption>+ )+ )}+ </StyledContainer>+ );+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinVisibilityIcon.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinVisibilityIcon.tsxnew file mode 100644index 00000000000..5c0c853cb4b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinVisibilityIcon.tsx@@ -0,0 +1,47 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme';++const StyledCardMedia = styled.div`+ align-items: stretch;+ border: 2px solid ${() => themeCssVariables.border.color.medium};+ border-radius: ${() => themeCssVariables.border.radius.sm};+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ flex-shrink: 0;+ gap: 2px;+ height: 40px;+ justify-content: center;+ padding: 2px;+ width: 32px;+`;++const StyledSkeleton = styled.div<{ $isActive: boolean }>`+ background-color: ${({ $isActive }) =>+ $isActive+ ? themeCssVariables.accent.accent7+ : themeCssVariables.background.quaternary};+ border-radius: 1px;+ height: 3px;+`;++const StyledMetadataSkeleton = styled(StyledSkeleton)`+ margin-right: ${() => themeCssVariables.spacing[2]};+`;++const StyledBodySkeleton = styled(StyledSkeleton)`+ flex: 1 0 auto;+`;++type LinkedinVisibilityIconProps = {+ isBodyActive: boolean;+};++export const LinkedinVisibilityIcon = ({+ isBodyActive,+}: LinkedinVisibilityIconProps) => (+ <StyledCardMedia>+ <StyledMetadataSkeleton $isActive />+ <StyledBodySkeleton $isActive={isBodyActive} />+ </StyledCardMedia>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinVisibilitySection.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinVisibilitySection.tsxnew file mode 100644index 00000000000..4a880bdab4e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinVisibilitySection.tsx@@ -0,0 +1,47 @@+import { t } from 'twenty-sdk/front-component';+import { Section } from 'twenty-ui/components/layout';++import { LinkedinVisibilityIcon } from 'src/front-components/components/LinkedinVisibilityIcon';+import { SettingsRadioCard } from 'src/front-components/components/SettingsRadioCard';+import { type LinkedinVisibility } from 'src/types/linkedin-visibility.type';++type LinkedinVisibilitySectionProps = {+ visibility: LinkedinVisibility;+ onChange: (visibility: LinkedinVisibility) => void;+};++export const LinkedinVisibilitySection = ({+ visibility,+ onChange,+}: LinkedinVisibilitySectionProps) => (+ <Section.Root>+ <Section.Header+ title={t('Visibility')}+ description={t(+ 'Specify which part of your conversations other users can see',+ )}+ />+ <SettingsRadioCard+ value={visibility}+ onChange={onChange}+ options={[+ {+ value: 'SHARE_EVERYTHING',+ cardMedia: <LinkedinVisibilityIcon isBodyActive />,+ title: t('Everything'),+ description: t(+ 'Messages and attachments will be shared with your team.',+ ),+ },+ {+ value: 'METADATA',+ cardMedia: <LinkedinVisibilityIcon isBodyActive={false} />,+ title: t('Metadata'),+ description: t(+ 'Timestamp and participants will be shared with your team.',+ ),+ },+ ]}+ />+ </Section.Root>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/OnMountEffect.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/OnMountEffect.tsxnew file mode 100644index 00000000000..5149df78f8e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/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/linkedin/src/front-components/components/Radio.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/Radio.tsxnew file mode 100644index 00000000000..e576744a04b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/Radio.tsx@@ -0,0 +1,83 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme';++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={(event) => {+ event.stopPropagation();+ onSelect();+ }}+ >+ <StyledControl data-checked={checked ? 'true' : 'false'}>+ {checked && <StyledIndicator />}+ </StyledControl>+ </StyledRadio>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/Separator.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/Separator.tsxnew file mode 100644index 00000000000..6d404bb3f4c--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/Separator.tsx@@ -0,0 +1,14 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme';++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/linkedin/src/front-components/components/SettingsCardContentBase.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsCardContentBase.tsxnew file mode 100644index 00000000000..06480b40ff6--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsCardContentBase.tsx@@ -0,0 +1,41 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme';++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/linkedin/src/front-components/components/SettingsOptionCardContentToggle.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionCardContentToggle.tsxnew file mode 100644index 00000000000..3316c83b2c0--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionCardContentToggle.tsx@@ -0,0 +1,100 @@+import styled from '@emotion/styled';+import { useId } from 'react';+import { type IconComponent } from 'twenty-ui/icon';+import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';+import { themeCssVariables } from 'twenty-ui/theme';++import { Separator } from 'src/front-components/components/Separator';+import {+ StyledSettingsCardDescription,+ StyledSettingsCardIcon,+ StyledSettingsCardTextContainer,+ StyledSettingsCardTitle,+} from 'src/front-components/components/SettingsCardContentBase';+import { SettingsOptionIconCustomizer } from 'src/front-components/components/SettingsOptionIconCustomizer';+import { Toggle } from 'src/front-components/components/Toggle';++const StyledSettingsCardToggleContent = styled.div<{ $disabled?: boolean }>`+ align-items: center;+ background-color: ${() => themeCssVariables.background.secondary};+ cursor: ${({ $disabled }) => ($disabled ? 'default' : 'pointer')};+ display: flex;+ gap: ${() => themeCssVariables.spacing[3]};+ padding: ${() => themeCssVariables.spacing[4]};+ pointer-events: ${({ $disabled }) => ($disabled ? 'none' : 'auto')};+ position: relative;++ &:hover {+ background: ${() => themeCssVariables.background.transparent.lighter};+ }+`;++const StyledSettingsCardToggleButtonContainer = styled.span`+ align-items: center;+ display: flex;+ flex-shrink: 0;+ margin-left: auto;+`;++const StyledSettingsCardToggleCover = styled.span`+ cursor: pointer;+ inset: 0;+ position: absolute;+`;++type SettingsOptionCardContentToggleProps = {+ Icon?: IconComponent;+ title: React.ReactNode;+ description?: string;+ divider?: boolean;+ disabled?: boolean;+ checked: boolean;+ onChange: (checked: boolean) => void;+};++export const SettingsOptionCardContentToggle = ({+ Icon,+ title,+ description,+ divider,+ disabled = false,+ checked,+ onChange,+}: SettingsOptionCardContentToggleProps) => {+ const toggleId = useId();++ return (+ <>+ <StyledSettingsCardToggleContent $disabled={disabled}>+ {Icon && (+ <StyledSettingsCardIcon>+ <SettingsOptionIconCustomizer Icon={Icon} />+ </StyledSettingsCardIcon>+ )}+ <StyledSettingsCardTextContainer>+ <StyledSettingsCardTitle>+ <label htmlFor={toggleId}>+ {title}+ <StyledSettingsCardToggleCover />+ </label>+ </StyledSettingsCardTitle>+ {description && (+ <StyledSettingsCardDescription>+ <OverflowingTextWithTooltip text={description} />+ </StyledSettingsCardDescription>+ )}+ </StyledSettingsCardTextContainer>+ <StyledSettingsCardToggleButtonContainer>+ <Toggle+ id={toggleId}+ checked={checked}+ disabled={disabled}+ toggleSize="small"+ onChange={onChange}+ />+ </StyledSettingsCardToggleButtonContainer>+ </StyledSettingsCardToggleContent>+ {divider && <Separator />}+ </>+ );+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionIconCustomizer.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionIconCustomizer.tsxnew file mode 100644index 00000000000..b3d78d96fa3--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionIconCustomizer.tsx@@ -0,0 +1,31 @@+import styled from '@emotion/styled';+import { type IconComponent } from 'twenty-ui/icon';+import { THEME_COMMON, themeCssVariables } from 'twenty-ui/theme';++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={THEME_COMMON.icon.size.lg}+ stroke={THEME_COMMON.icon.stroke.md}+ />+ </StyledIconCustomizer>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsRadioCard.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsRadioCard.tsxnew file mode 100644index 00000000000..af9d9cd58f1--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsRadioCard.tsx@@ -0,0 +1,94 @@+import styled from '@emotion/styled';+import { Fragment, type ReactNode, useId } from 'react';+import { themeCssVariables } from 'twenty-ui/theme';++import { Radio } from 'src/front-components/components/Radio';+import { Separator } from 'src/front-components/components/Separator';+import { StyledSettingsCardTextContainer } from 'src/front-components/components/SettingsCardContentBase';+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';++const StyledOptionRow = styled.div`+ align-items: center;+ background-color: ${() => themeCssVariables.background.secondary};+ cursor: pointer;+ display: flex;+ gap: ${() => themeCssVariables.spacing[4]};+ padding: ${() => themeCssVariables.spacing[4]};++ &:hover {+ background: ${() => themeCssVariables.background.transparent.lighter};+ }+`;++const StyledOptionTitle = styled.div`+ color: ${() => themeCssVariables.font.color.primary};+ font-weight: ${() => themeCssVariables.font.weight.medium};+ margin-bottom: ${() => themeCssVariables.spacing[2]};+`;++const StyledOptionDescription = styled.div`+ color: ${() => themeCssVariables.font.color.tertiary};+ font-size: ${() => themeCssVariables.font.size.sm};+`;++const StyledRadioContainer = styled.span`+ align-items: center;+ display: flex;+ flex-shrink: 0;+ margin-left: auto;+`;++export type SettingsRadioCardOption<TValue extends string> = {+ value: TValue;+ cardMedia: ReactNode;+ title: string;+ description: string;+};++type SettingsRadioCardProps<TValue extends string> = {+ options: SettingsRadioCardOption<TValue>[];+ value: TValue;+ onChange: (value: TValue) => void;+};++export const SettingsRadioCard = <TValue extends string>({+ options,+ value,+ onChange,+}: SettingsRadioCardProps<TValue>) => {+ const groupId = useId();++ return (+ <StyledSettingsCard role="radiogroup">+ {options.map((option, index) => {+ const titleId = `${groupId}-${index}-title`;+ const descriptionId = `${groupId}-${index}-description`;++ return (+ <Fragment key={option.value}>+ <StyledOptionRow onClick={() => onChange(option.value)}>+ {option.cardMedia}+ <StyledSettingsCardTextContainer>+ <StyledOptionTitle id={titleId}>+ {option.title}+ </StyledOptionTitle>+ <StyledOptionDescription id={descriptionId}>+ {option.description}+ </StyledOptionDescription>+ </StyledSettingsCardTextContainer>+ <StyledRadioContainer>+ <Radio+ checked={option.value === value}+ aria-labelledby={titleId}+ aria-describedby={descriptionId}+ onSelect={() => onChange(option.value)}+ />+ </StyledRadioContainer>+ </StyledOptionRow>+ {index < options.length - 1 && <Separator />}+ </Fragment>+ );+ })}+ </StyledSettingsCard>+ );+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/StyledSettingsCard.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/StyledSettingsCard.tsxnew file mode 100644index 00000000000..d14e884d42f--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/StyledSettingsCard.tsx@@ -0,0 +1,20 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme';++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/linkedin/src/front-components/components/TimeoutEffect.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/TimeoutEffect.tsxnew file mode 100644index 00000000000..07dc6570e46--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/TimeoutEffect.tsx@@ -0,0 +1,21 @@+import { useEffect, useState } from 'react';++type TimeoutEffectProps = {+ delayMilliseconds: number;+ onTimeout: () => void;+};++export const TimeoutEffect = ({+ delayMilliseconds,+ onTimeout,+}: TimeoutEffectProps) => {+ const [initialOnTimeout] = useState(() => onTimeout);++ useEffect(() => {+ const timeoutId = setTimeout(initialOnTimeout, delayMilliseconds);++ return () => clearTimeout(timeoutId);+ }, [delayMilliseconds, initialOnTimeout]);++ return null;+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/Toggle.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/Toggle.tsxnew file mode 100644index 00000000000..8b0504a549e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/Toggle.tsx@@ -0,0 +1,108 @@+import styled from '@emotion/styled';+import { themeCssVariables } from 'twenty-ui/theme';++export type ToggleSize = 'small' | 'medium';++type ToggleDimensions = {+ width: number;+ height: number;+ thumbSize: number;+};++const TOGGLE_DIMENSIONS_BY_SIZE: Record<ToggleSize, ToggleDimensions> = {+ small: { width: 24, height: 16, thumbSize: 12 },+ medium: { width: 32, height: 20, thumbSize: 16 },+};++const THUMB_INSET_PIXELS = 2;++const getCheckedThumbOffsetPixels = ({ width, thumbSize }: ToggleDimensions) =>+ width - thumbSize - THUMB_INSET_PIXELS;++const StyledToggle = styled.button<{+ $toggleSize: ToggleSize;+}>`+ align-items: center;+ appearance: none;+ background-color: ${() => themeCssVariables.background.transparent.medium};+ border: none;+ border-radius: ${() => themeCssVariables.border.radius.pill};+ corner-shape: round;+ cursor: pointer;+ display: flex;+ flex-shrink: 0;+ height: ${({ $toggleSize }) => TOGGLE_DIMENSIONS_BY_SIZE[$toggleSize].height}px;+ padding: 0;+ position: relative;+ transition: background-color+ calc(${() => themeCssVariables.animation.duration.normal} * 1s) ease;+ width: ${({ $toggleSize }) => TOGGLE_DIMENSIONS_BY_SIZE[$toggleSize].width}px;++ &[data-checked='true'] {+ background-color: ${() => themeCssVariables.color.blue};+ }++ &:disabled {+ cursor: default;+ opacity: 0.5;+ }+`;++const StyledThumb = styled.span<{+ $toggleSize: ToggleSize;+}>`+ background-color: ${() => themeCssVariables.background.primary};+ border-radius: 50%;+ corner-shape: round;+ display: block;+ height: ${({ $toggleSize }) =>+ TOGGLE_DIMENSIONS_BY_SIZE[$toggleSize].thumbSize}px;+ left: 0;+ position: absolute;+ top: 50%;+ transform: translate(${THUMB_INSET_PIXELS}px, -50%);+ transition: transform+ calc(${() => themeCssVariables.animation.duration.normal} * 1s) ease;+ width: ${({ $toggleSize }) =>+ TOGGLE_DIMENSIONS_BY_SIZE[$toggleSize].thumbSize}px;++ &[data-checked='true'] {+ transform: translate(+ ${({ $toggleSize }) =>+ getCheckedThumbOffsetPixels(TOGGLE_DIMENSIONS_BY_SIZE[$toggleSize])}px,+ -50%+ );+ }+`;++type ToggleProps = {+ id?: string;+ checked: boolean;+ disabled?: boolean;+ toggleSize?: ToggleSize;+ onChange: (checked: boolean) => void;+};++export const Toggle = ({+ id,+ checked,+ disabled = false,+ toggleSize = 'medium',+ onChange,+}: ToggleProps) => (+ <StyledToggle+ type="button"+ role="switch"+ id={id}+ aria-checked={checked ? 'true' : 'false'}+ data-checked={checked ? 'true' : 'false'}+ disabled={disabled}+ $toggleSize={toggleSize}+ onClick={() => onChange(!checked)}+ >+ <StyledThumb+ data-checked={checked ? 'true' : 'false'}+ $toggleSize={toggleSize}+ />+ </StyledToggle>+);diff --git a/packages/twenty-apps/public/linkedin/src/front-components/linkedin-settings.front-component.tsx b/packages/twenty-apps/public/linkedin/src/front-components/linkedin-settings.front-component.tsxnew file mode 100644index 00000000000..2c4f433f334--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/linkedin-settings.front-component.tsx@@ -0,0 +1,12 @@+import { defineFrontComponent } from 'twenty-sdk/define';++import { LINKEDIN_SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { LinkedinSettings } from 'src/front-components/components/LinkedinSettings';++export default defineFrontComponent({+ universalIdentifier: LINKEDIN_SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-settings',+ description:+ 'LinkedIn import, visibility, contact auto-creation and people matching of the member connection.',+ component: LinkedinSettings,+});diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/__tests__/get-linkedin-sync-progress.util.test.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/__tests__/get-linkedin-sync-progress.util.test.tsnew file mode 100644index 00000000000..0a28b4e8ca7--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/__tests__/get-linkedin-sync-progress.util.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { formatLinkedinSyncProgressLabel } from 'src/front-components/utils/format-linkedin-sync-progress-label.util';+import { getLinkedinSyncProgress } from 'src/front-components/utils/get-linkedin-sync-progress.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const buildHistoryImport = (+ overrides: Partial<LinkedinHistoryImportState>,+): LinkedinHistoryImportState => ({+ runId: 'run-1',+ importPolicy: 'ALL',+ status: 'IMPORTING',+ importedConversationCount: 0,+ processedConversationCount: 0,+ startedAt: '2026-10-30T00:00:00.000Z',+ ...overrides,+});++describe('getLinkedinSyncProgress', () => {+ it('returns the share of processed conversations', () => {+ expect(+ getLinkedinSyncProgress(+ buildHistoryImport({+ processedConversationCount: 214,+ totalConversationCount: 510,+ }),+ ),+ ).toBe(41);+ });++ it('never reaches 100% while the run is going', () => {+ expect(+ getLinkedinSyncProgress(+ buildHistoryImport({+ processedConversationCount: 510,+ totalConversationCount: 510,+ }),+ ),+ ).toBe(99);+ });++ it('is unknown when LinkedIn gave no total', () => {+ expect(+ getLinkedinSyncProgress(+ buildHistoryImport({ processedConversationCount: 40 }),+ ),+ ).toBeUndefined();+ });+});++describe('formatLinkedinSyncProgressLabel', () => {+ it('pads single digits so the label keeps its width', () => {+ expect(formatLinkedinSyncProgressLabel(7)).toBe(' (7%)');+ expect(formatLinkedinSyncProgressLabel(42)).toBe('(42%)');+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/__tests__/notify-linkedin-history-import-end.util.test.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/__tests__/notify-linkedin-history-import-end.util.test.tsnew file mode 100644index 00000000000..1686de89032--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/__tests__/notify-linkedin-history-import-end.util.test.ts@@ -0,0 +1,76 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const mocks = vi.hoisted(() => ({ enqueueSnackbar: vi.fn() }));++vi.mock('twenty-sdk/front-component', () => ({+ enqueueSnackbar: mocks.enqueueSnackbar,+ t: (message: string, values: Record<string, unknown> = {}) =>+ message.replace(/\{(\w+)\}/g, (_, key) => String(values[key])),+}));++const { notifyLinkedinHistoryImportEnd } =+ await import('src/front-components/utils/notify-linkedin-history-import-end.util');++const buildHistoryImport = (+ overrides: Partial<LinkedinHistoryImportState>,+): LinkedinHistoryImportState => ({+ runId: 'run-1',+ importPolicy: 'ALL',+ status: 'IMPORTING',+ importedConversationCount: 0,+ processedConversationCount: 0,+ startedAt: '2026-10-30T00:00:00.000Z',+ ...overrides,+});++describe('notifyLinkedinHistoryImportEnd', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('announces the number of conversations a finished run imported', () => {+ notifyLinkedinHistoryImportEnd({+ previous: buildHistoryImport({}),+ next: buildHistoryImport({+ status: 'COMPLETED',+ importedConversationCount: 1180,+ }),+ });++ expect(mocks.enqueueSnackbar).toHaveBeenCalledExactlyOnceWith({+ message: '1180 past conversations imported',+ variant: 'success',+ });+ });++ it('explains why a run failed', () => {+ notifyLinkedinHistoryImportEnd({+ previous: buildHistoryImport({}),+ next: buildHistoryImport({+ status: 'FAILED',+ error: { code: 'UNREACHABLE', message: 'fetch failed' },+ }),+ });++ expect(mocks.enqueueSnackbar).toHaveBeenCalledExactlyOnceWith({+ message:+ 'LinkedIn import failed. LinkedIn could not be reached. Retry in a few minutes.',+ variant: 'error',+ });+ });++ it('stays quiet for a run it never saw going', () => {+ notifyLinkedinHistoryImportEnd({+ previous: null,+ next: buildHistoryImport({ status: 'COMPLETED' }),+ });+ notifyLinkedinHistoryImportEnd({+ previous: buildHistoryImport({ runId: 'run-0' }),+ next: buildHistoryImport({ status: 'COMPLETED' }),+ });++ expect(mocks.enqueueSnackbar).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/format-linkedin-sync-progress-label.util.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/format-linkedin-sync-progress-label.util.tsnew file mode 100644index 00000000000..67934ad12ba--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/format-linkedin-sync-progress-label.util.ts@@ -0,0 +1,8 @@+const FIGURE_SPACE = '\u2007';++export const formatLinkedinSyncProgressLabel = (progress: number): string => {+ const roundedProgress = Math.round(progress);+ const padding = roundedProgress < 10 ? FIGURE_SPACE : '';++ return `${padding}(${roundedProgress}%)`;+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/get-linkedin-history-import-error-reason.util.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/get-linkedin-history-import-error-reason.util.tsnew file mode 100644index 00000000000..220bf707ca8--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/get-linkedin-history-import-error-reason.util.ts@@ -0,0 +1,20 @@+import { t } from 'twenty-sdk/front-component';++import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export const getLinkedinHistoryImportErrorReason = (+ error: LinkedinHistoryImportState['error'],+): string => {+ switch (error?.code) {+ case 'AUTH_FAILED':+ return t(+ 'LinkedIn signed you out. Reconnect your account in the General tab, then retry.',+ );+ case 'STALLED':+ return t('It stopped responding. Retry to start it again.');+ case 'UNREACHABLE':+ return t('LinkedIn could not be reached. Retry in a few minutes.');+ default:+ return error?.message ?? t('Retry to continue from the start.');+ }+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/get-linkedin-sync-progress.util.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/get-linkedin-sync-progress.util.tsnew file mode 100644index 00000000000..d082cf84a26--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/get-linkedin-sync-progress.util.ts@@ -0,0 +1,18 @@+import { isDefined } from 'twenty-sdk/utils';++import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export const getLinkedinSyncProgress = (+ historyImport: LinkedinHistoryImportState,+): number | undefined => {+ const { processedConversationCount, totalConversationCount } = historyImport;++ if (!isDefined(totalConversationCount) || totalConversationCount <= 0) {+ return undefined;+ }++ return Math.min(+ 99,+ Math.floor((processedConversationCount / totalConversationCount) * 100),+ );+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/get-next-linkedin-sync-progress.util.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/get-next-linkedin-sync-progress.util.tsnew file mode 100644index 00000000000..92eca720040--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/get-next-linkedin-sync-progress.util.ts@@ -0,0 +1,32 @@+import { isDefined } from 'twenty-sdk/utils';++import { getLinkedinSyncProgress } from 'src/front-components/utils/get-linkedin-sync-progress.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++type LinkedinSyncProgress = { runId: string; progress: number };++export const getNextLinkedinSyncProgress = ({+ current,+ historyImport,+}: {+ current: LinkedinSyncProgress | null;+ historyImport: LinkedinHistoryImportState | null;+}): LinkedinSyncProgress | null => {+ if (historyImport?.status !== 'IMPORTING') {+ return null;+ }++ const progress = getLinkedinSyncProgress(historyImport);++ if (!isDefined(progress)) {+ return current?.runId === historyImport.runId ? current : null;+ }++ return {+ runId: historyImport.runId,+ progress:+ current?.runId === historyImport.runId+ ? Math.max(current.progress, progress)+ : progress,+ };+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/notify-linkedin-history-import-end.util.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/notify-linkedin-history-import-end.util.tsnew file mode 100644index 00000000000..6bb1026216b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/notify-linkedin-history-import-end.util.ts@@ -0,0 +1,34 @@+import { enqueueSnackbar, t } from 'twenty-sdk/front-component';++import { getLinkedinHistoryImportErrorReason } from 'src/front-components/utils/get-linkedin-history-import-error-reason.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export const notifyLinkedinHistoryImportEnd = ({+ previous,+ next,+}: {+ previous: LinkedinHistoryImportState | null;+ next: LinkedinHistoryImportState | null;+}): void => {+ if (previous?.status !== 'IMPORTING' || previous.runId !== next?.runId) {+ return;+ }++ if (next.status === 'COMPLETED') {+ enqueueSnackbar({+ message: t('{count} past conversations imported', {+ count: next.importedConversationCount,+ }),+ variant: 'success',+ });+ }++ if (next.status === 'FAILED') {+ enqueueSnackbar({+ message: t('LinkedIn import failed. {reason}', {+ reason: getLinkedinHistoryImportErrorReason(next.error),+ }),+ variant: 'error',+ });+ }+};diff --git a/packages/twenty-apps/public/linkedin/src/front-components/utils/post-linkedin-settings-route-or-throw.util.ts b/packages/twenty-apps/public/linkedin/src/front-components/utils/post-linkedin-settings-route-or-throw.util.tsnew file mode 100644index 00000000000..4bcdd24a73b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/utils/post-linkedin-settings-route-or-throw.util.ts@@ -0,0 +1,12 @@+import { RestApiClient } from 'twenty-client-sdk/rest';++import { type LinkedinSettingsView } from 'src/types/linkedin-settings-view.type';++export const postLinkedinSettingsRouteOrThrow = ({+ routePath,+ body = {},+}: {+ routePath: string;+ body?: Record<string, unknown>;+}): Promise<LinkedinSettingsView> =>+ new RestApiClient().post<LinkedinSettingsView>(`/s${routePath}`, body);diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-handle-webhook-event.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-handle-webhook-event.test.tsindex 5227f157f96..2e72cf29dc1 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-handle-webhook-event.test.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-handle-webhook-event.test.ts@@ -12,6 +12,8 @@ const mocks = vi.hoisted(() => ({kvSet: vi.fn(),getUnipileUser: vi.fn(),getUnipileChat: vi.fn(),+ query: vi.fn(),+ mutation: vi.fn(),}));vi.mock('twenty-sdk/define', () => ({@@ -26,6 +28,13 @@ vi.mock('twenty-sdk/logic-function', () => ({kv: { get: mocks.kvGet, set: mocks.kvSet },}));+vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class {+ query = mocks.query;+ mutation = mocks.mutation;+ },+}));+vi.mock('src/unipile/utils/get-unipile-user.util', () => ({getUnipileUser: mocks.getUnipileUser,}));@@ -76,6 +85,15 @@ describe('linkedinHandleWebhookEventHandler', () => {{ id: 'channel-id', handle: CHANNEL_HANDLE },]);mocks.kvGet.mockResolvedValue(null);+ mocks.query.mockResolvedValue({ people: { edges: [] } });+ mocks.getUnipileChat.mockResolvedValue({+ id: 'chat-1',+ name: 'Daphné Müller',+ is_group: false,+ is_1to1: true,+ user: DAPHNE,+ });+ mocks.mutation.mockResolvedValue({ createPerson: { id: 'created-id' } });mocks.getUnipileUser.mockResolvedValue({...DAPHNE,public_identifier: 'daphne-muller',@@ -112,6 +130,55 @@ describe('linkedinHandleWebhookEventHandler', () => {});});+ it('imports a group message from a stranger when another member is a contact', async () => {+ const ada = {+ id: 'ACoADA',+ display_name: 'Ada Lovelace',+ public_identifier: 'ada',+ };++ mocks.getUnipileChat.mockResolvedValue({+ id: 'chat-1',+ name: 'Founders',+ is_group: true,+ is_1to1: false,+ participants: [+ { is_self: false, user: ada },+ { is_self: false, user: DAPHNE },+ ],+ });+ mocks.query.mockImplementation(async (query: unknown) =>+ JSON.stringify(query).includes('in/ada')+ ? {+ people: {+ edges: [+ {+ node: {+ id: 'ada-id',+ linkedinLink: {+ primaryLinkUrl: 'https://www.linkedin.com/in/ada',+ },+ },+ },+ ],+ },+ }+ : { people: { edges: [] } },+ );++ await expect(+ linkedinHandleWebhookEventHandler(+ buildMessageEvent({+ sender_id: DAPHNE.id,+ sender: DAPHNE,+ is_sender: false,+ }),+ ),+ ).resolves.toEqual({ handled: true });++ expect(mocks.ingestMessages).toHaveBeenCalledOnce();+ });+it('ingests a sent message to the chat counterpart public profile URL', async () => {mocks.getUnipileChat.mockResolvedValue({id: 'chat-1',@@ -138,8 +205,25 @@ describe('linkedinHandleWebhookEventHandler', () => {role: 'TO',handle: 'https://www.linkedin.com/in/daphne-muller',displayName: 'Daphné Müller',+ personId: 'created-id',},]);+ expect(mocks.mutation).toHaveBeenCalledExactlyOnceWith({+ createPerson: {+ __args: {+ data: {+ id: expect.stringMatching(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ ),+ name: { firstName: 'Daphné', lastName: 'Müller' },+ linkedinLink: {+ primaryLinkUrl: 'https://www.linkedin.com/in/daphne-muller',+ },+ },+ },+ id: true,+ },+ });});it('ignores events of accounts no connection owns', async () => {diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-import-history.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-import-history.test.tsnew file mode 100644index 00000000000..85123c9dbdb--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-import-history.test.ts@@ -0,0 +1,401 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const mocks = vi.hoisted(() => ({+ getConnection: vi.fn(),+ listMessageChannels: vi.fn(),+ enqueueJobs: vi.fn(),+ kvStore: new Map<string, unknown>(),+ listUnipileChatMessagesPage: vi.fn(),+ getUnipileChat: vi.fn(),+ ingestLinkedinMessages: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ AppConnectionAuthFailedError: class extends Error {},+ RetryableLogicFunctionError: class RetryableLogicFunctionError extends Error {},+ getConnection: mocks.getConnection,+ listMessageChannels: mocks.listMessageChannels,+ enqueueJobs: mocks.enqueueJobs,+ kv: {+ get: async (key: string) => mocks.kvStore.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ mocks.kvStore.set(key, value);+ },+ },+}));++vi.mock('src/unipile/utils/list-unipile-chat-messages-page.util', () => ({+ listUnipileChatMessagesPage: mocks.listUnipileChatMessagesPage,+}));++vi.mock('src/unipile/utils/get-unipile-chat.util', () => ({+ getUnipileChat: mocks.getUnipileChat,+}));++vi.mock('src/logic-functions/utils/ingest-linkedin-messages.util', () => ({+ ingestLinkedinMessages: mocks.ingestLinkedinMessages,+}));++const { UnipileRateLimitError } =+ await import('src/unipile/utils/request-unipile.util');++const { linkedinImportHistoryHandler } =+ await import('src/logic-functions/linkedin-import-history');++const STATE_KEY = 'linkedin-history-import:connection-id';+const PROGRESS_KEY = 'linkedin-history-import-progress:connection-id:run-1';+const getChatsKey = (chunkIndex: number) =>+ `linkedin-history-import-chats:connection-id:run-1:${chunkIndex}`;++const RUNNING_STATE: LinkedinHistoryImportState = {+ runId: 'run-1',+ importPolicy: 'ALL',+ status: 'IMPORTING',+ importedConversationCount: 0,+ processedConversationCount: 0,+ startedAt: '2026-10-30T00:00:00.000Z',+};++const PROGRESS_BEFORE_CHUNK_2 = {+ completedChunkCount: 2,+ completedConversationCount: 40,+ importedConversationCount: 30,+ currentChunkProcessedCount: 0,+};++const PAYLOAD = {+ connectedAccountId: 'connection-id',+ runId: 'run-1',+ chunkIndex: 2,+};++const CURRENT_PROGRESS = {+ ...PROGRESS_BEFORE_CHUNK_2,+ currentJobId: 'linkedin-history-chunk-run-1-2',+ currentResumeIndex: undefined,+};++const LISTED_CHAT_WITH_ATTENDEE = {+ id: 'chat-1',+ user: { id: 'user-1', public_identifier: 'ada' },+};++const LISTED_CHAT_WITHOUT_ATTENDEE = { id: 'chat-2' };++const IMPORTED = {+ ingestedMessageCount: 12,+ matchedPersonCount: 1,+ createdPersonCount: 1,+};++const SKIPPED = {+ ingestedMessageCount: 0,+ matchedPersonCount: 0,+ createdPersonCount: 0,+ skippedReason: 'NO_CONTACT',+};++describe('linkedinImportHistoryHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useRealTimers();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ mocks.kvStore.clear();+ mocks.kvStore.set(STATE_KEY, RUNNING_STATE);+ mocks.kvStore.set(PROGRESS_KEY, PROGRESS_BEFORE_CHUNK_2);+ mocks.kvStore.set(getChatsKey(2), [+ LISTED_CHAT_WITH_ATTENDEE,+ LISTED_CHAT_WITHOUT_ATTENDEE,+ ]);+ mocks.getConnection.mockResolvedValue({ externalAccountId: 'acc_1' });+ mocks.listMessageChannels.mockResolvedValue([+ { id: 'channel-id', handle: 'linkedin.com/in/me' },+ ]);+ mocks.getUnipileChat.mockImplementation(async ({ chatId }) => ({+ id: chatId,+ user: { id: `user-${chatId}`, public_identifier: chatId },+ }));+ mocks.listUnipileChatMessagesPage+ .mockReset()+ .mockResolvedValue({ items: [{ id: 'message' }], nextCursor: undefined });+ mocks.ingestLinkedinMessages+ .mockReset()+ .mockResolvedValueOnce(IMPORTED)+ .mockResolvedValueOnce(SKIPPED);+ });++ it('imports its page and adds it to the run progress', async () => {+ await expect(linkedinImportHistoryHandler(PAYLOAD)).resolves.toEqual({+ status: 'COMPLETED',+ importedConversationCount: 1,+ });++ expect(mocks.getUnipileChat).toHaveBeenCalledExactlyOnceWith({+ accountId: 'acc_1',+ chatId: 'chat-2',+ });+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual({+ completedChunkCount: 3,+ completedConversationCount: 42,+ importedConversationCount: 31,+ currentChunkProcessedCount: 0,+ });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringMatching(+ /chunk 2: 2 chats .*1 conversations imported, 12 messages, 1 people matched, 1 people created, skipped 1 without contact/,+ ),+ );+ });++ it('ingests a long chat page by page and records its cursor', async () => {+ mocks.listUnipileChatMessagesPage+ .mockReset()+ .mockResolvedValueOnce({ items: [{ id: 'm-1' }], nextCursor: 'page-2' })+ .mockImplementationOnce(async ({ cursor }) => {+ expect(cursor).toBe('page-2');+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual({+ ...CURRENT_PROGRESS,+ currentChunkProcessedCount: 0,+ currentChunkImportedCount: 0,+ currentChatCursor: 'page-2',+ isCurrentChatImported: true,+ });++ return { items: [{ id: 'm-2' }], nextCursor: undefined };+ })+ .mockResolvedValue({ items: [{ id: 'm-3' }], nextCursor: undefined });+ mocks.ingestLinkedinMessages.mockReset().mockResolvedValue(IMPORTED);++ await linkedinImportHistoryHandler(PAYLOAD);++ expect(mocks.ingestLinkedinMessages).toHaveBeenCalledTimes(3);+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual(+ expect.objectContaining({+ completedChunkCount: 3,+ importedConversationCount: 32,+ }),+ );+ });++ it('resumes a chat from the page a paused job stopped at', async () => {+ mocks.kvStore.set(PROGRESS_KEY, {+ ...PROGRESS_BEFORE_CHUNK_2,+ currentChatCursor: 'page-7',+ isCurrentChatImported: true,+ });+ mocks.ingestLinkedinMessages.mockReset().mockResolvedValue(SKIPPED);++ await linkedinImportHistoryHandler({ ...PAYLOAD, resumeIndex: 1 });++ expect(mocks.listUnipileChatMessagesPage).toHaveBeenNthCalledWith(1, {+ accountId: 'acc_1',+ chatId: 'chat-1',+ cursor: 'page-7',+ });+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual(+ expect.objectContaining({ importedConversationCount: 31 }),+ );+ });++ it('hands over to a fresh job before its time runs out', async () => {+ vi.useFakeTimers({ now: 0 });+ mocks.listUnipileChatMessagesPage+ .mockReset()+ .mockImplementation(async () => {+ vi.setSystemTime(Date.now() + 11 * 60 * 1000);++ return { items: [{ id: 'message' }], nextCursor: 'page-2' };+ });++ await expect(linkedinImportHistoryHandler(PAYLOAD)).resolves.toEqual({+ status: 'PAUSED',+ });+ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ jobs: [+ {+ jobId: 'linkedin-history-chunk-run-1-2-resume-1',+ payload: { ...PAYLOAD, resumeIndex: 1 },+ },+ ],+ delayMs: 0,+ }),+ );+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual(+ expect.objectContaining({+ currentChatCursor: 'page-2',+ currentJobId: 'linkedin-history-chunk-run-1-2-resume-1',+ currentResumeIndex: 1,+ }),+ );+ });++ it('queues the next page once it is listed', async () => {+ mocks.kvStore.set(getChatsKey(3), [{ id: 'chat-3' }]);++ await linkedinImportHistoryHandler(PAYLOAD);++ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ jobs: [+ {+ jobId: 'linkedin-history-chunk-run-1-3',+ payload: { ...PAYLOAD, chunkIndex: 3 },+ },+ ],+ }),+ );+ });++ it('leaves the next page to the planning job when it is not listed yet', async () => {+ await linkedinImportHistoryHandler(PAYLOAD);++ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });++ it('only hands over to the next page when retried after finishing its own', async () => {+ mocks.kvStore.set(PROGRESS_KEY, {+ ...PROGRESS_BEFORE_CHUNK_2,+ completedChunkCount: 3,+ });+ mocks.kvStore.set(getChatsKey(3), [{ id: 'chat-3' }]);++ await expect(linkedinImportHistoryHandler(PAYLOAD)).resolves.toEqual({+ status: 'SKIPPED',+ });+ expect(mocks.ingestLinkedinMessages).not.toHaveBeenCalled();+ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ jobs: [+ expect.objectContaining({ jobId: 'linkedin-history-chunk-run-1-3' }),+ ],+ }),+ );+ });++ it('skips a page that is not next in line', async () => {+ mocks.kvStore.set(PROGRESS_KEY, {+ ...PROGRESS_BEFORE_CHUNK_2,+ completedChunkCount: 1,+ });++ await expect(linkedinImportHistoryHandler(PAYLOAD)).resolves.toEqual({+ status: 'SKIPPED',+ });+ expect(mocks.ingestLinkedinMessages).not.toHaveBeenCalled();+ });++ it.each([+ ['a cancelled run', { ...RUNNING_STATE, status: 'CANCELLED' }],+ ['a newer run', { ...RUNNING_STATE, runId: 'run-2' }],+ ])('skips its page for %s', async (_, state) => {+ mocks.kvStore.set(STATE_KEY, state);++ await expect(linkedinImportHistoryHandler(PAYLOAD)).resolves.toEqual({+ status: 'CANCELLED',+ });+ expect(mocks.ingestLinkedinMessages).not.toHaveBeenCalled();+ });++ it('asks Twenty to retry when LinkedIn is unreachable', async () => {+ mocks.getUnipileChat.mockRejectedValue({ status: 503, title: 'Busy' });++ await expect(+ linkedinImportHistoryHandler(PAYLOAD, { retryCount: 0, maxRetries: 3 }),+ ).rejects.toSatisfy(+ (error: Error) =>+ error.constructor.name === 'RetryableLogicFunctionError',+ );+ expect(mocks.kvStore.get(PROGRESS_KEY)).not.toHaveProperty('error');+ });++ it('stores the error of a page Twenty will not retry', async () => {+ mocks.getUnipileChat.mockRejectedValue({+ status: 400,+ title: 'Invalid querystring',+ });++ await expect(+ linkedinImportHistoryHandler(PAYLOAD, { retryCount: 0, maxRetries: 3 }),+ ).rejects.toThrow('Invalid querystring');+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual({+ ...CURRENT_PROGRESS,+ currentChunkProcessedCount: 1,+ currentChunkImportedCount: 1,+ isCurrentChatImported: false,+ currentChatCursor: undefined,+ error: { code: 'UNKNOWN', message: 'Invalid querystring' },+ });+ });++ it('pauses until the limit resets when LinkedIn refuses for hours', async () => {+ vi.useFakeTimers({ now: Date.parse('2026-10-30T22:00:00.000Z') });+ mocks.listUnipileChatMessagesPage+ .mockReset()+ .mockResolvedValueOnce({+ items: [{ id: 'message' }],+ nextCursor: undefined,+ })+ .mockRejectedValueOnce(+ new UnipileRateLimitError(+ 'Unipile list chat messages failed (429): We only allow 100 requests. Retry in 22 hours.',+ 22 * 60 * 60 + 1,+ ),+ );++ await expect(linkedinImportHistoryHandler(PAYLOAD)).resolves.toEqual({+ status: 'PAUSED',+ });++ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ jobs: [+ {+ jobId: 'linkedin-history-chunk-run-1-2-resume-1',+ payload: { ...PAYLOAD, resumeIndex: 1 },+ },+ ],+ delayMs: (22 * 60 * 60 + 1) * 1000,+ }),+ );+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual({+ ...CURRENT_PROGRESS,+ currentChunkProcessedCount: 1,+ currentChunkImportedCount: 1,+ isCurrentChatImported: false,+ currentChatCursor: undefined,+ currentJobId: 'linkedin-history-chunk-run-1-2-resume-1',+ currentResumeIndex: 1,+ resumeAt: '2026-10-31T20:00:01.000Z',+ });+ });++ it('resumes after the chats a paused job already imported', async () => {+ mocks.kvStore.set(PROGRESS_KEY, {+ ...PROGRESS_BEFORE_CHUNK_2,+ currentChunkProcessedCount: 1,+ currentChunkImportedCount: 1,+ });+ mocks.ingestLinkedinMessages.mockReset().mockResolvedValue({+ ingestedMessageCount: 3,+ matchedPersonCount: 1,+ createdPersonCount: 0,+ });++ await linkedinImportHistoryHandler({ ...PAYLOAD, resumeIndex: 1 });++ expect(mocks.ingestLinkedinMessages).toHaveBeenCalledTimes(1);+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual({+ completedChunkCount: 3,+ completedConversationCount: 42,+ importedConversationCount: 32,+ currentChunkProcessedCount: 0,+ });+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-on-connect.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-on-connect.test.tsindex 43020fcd569..91541f41574 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-on-connect.test.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-on-connect.test.ts@@ -8,6 +8,8 @@ const mocks = vi.hoisted(() => ({listMessageChannels: vi.fn(),createMessageChannel: vi.fn(),kvSet: vi.fn(),+ kvGet: vi.fn(),+ enqueueJobs: vi.fn(),getUnipileUser: vi.fn(),}));@@ -15,7 +17,8 @@ vi.mock('twenty-sdk/logic-function', () => ({getConnection: mocks.getConnection,listMessageChannels: mocks.listMessageChannels,createMessageChannel: mocks.createMessageChannel,- kv: { set: mocks.kvSet },+ enqueueJobs: mocks.enqueueJobs,+ kv: { get: mocks.kvGet, set: mocks.kvSet },}));vi.mock('src/unipile/utils/get-unipile-user.util', () => ({@@ -42,6 +45,7 @@ describe('linkedinOnConnectHandler', () => {public_identifier: 'ada-lovelace',});mocks.createMessageChannel.mockResolvedValue({ id: 'channel-id' });+ mocks.kvGet.mockResolvedValue(null);});it('keeps a flat copy of the person LinkedIn field id, since deployed functions stub nested SDK constants', () => {@@ -51,7 +55,7 @@ describe('linkedinOnConnectHandler', () => {);});- it('creates a private channel on the member profile and claims the account', async () => {+ it('creates a private channel on the member profile, claims the account and leaves importing to the Sync button', async () => {await expect(linkedinOnConnectHandler(PAYLOAD)).resolves.toEqual({messageChannelId: 'channel-id',});@@ -64,11 +68,12 @@ describe('linkedinOnConnectHandler', () => {participantHandleFieldUniversalIdentifier:PERSON_LINKEDIN_LINK_FIELD_UNIVERSAL_IDENTIFIER,});- expect(mocks.kvSet).toHaveBeenCalledExactlyOnceWith(+ expect(mocks.kvSet).toHaveBeenCalledWith('unipile-account:acc_1',undefined,{ scope: 'SERVER' },);+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();});it('reuses the channel of a reconnected account', async () => {@@ -80,5 +85,6 @@ describe('linkedinOnConnectHandler', () => {messageChannelId: 'existing-channel-id',});expect(mocks.createMessageChannel).not.toHaveBeenCalled();+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();});});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-plan-history-import.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-plan-history-import.test.tsnew file mode 100644index 00000000000..b89181b10b5--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-plan-history-import.test.ts@@ -0,0 +1,298 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const mocks = vi.hoisted(() => ({+ getConnection: vi.fn(),+ enqueueJobs: vi.fn(),+ kvStore: new Map<string, unknown>(),+ listUnipileInboxIds: vi.fn(),+ listUnipileChats: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ AppConnectionAuthFailedError: class extends Error {},+ RetryableLogicFunctionError: class RetryableLogicFunctionError extends Error {},+ getConnection: mocks.getConnection,+ enqueueJobs: mocks.enqueueJobs,+ kv: {+ get: async (key: string) => mocks.kvStore.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ mocks.kvStore.set(key, value);+ },+ },+}));++vi.mock('src/unipile/utils/list-unipile-inbox-ids.util', () => ({+ listUnipileInboxIds: mocks.listUnipileInboxIds,+}));++vi.mock('src/unipile/utils/list-unipile-chats.util', () => ({+ listUnipileChats: mocks.listUnipileChats,+}));++const { UnipileRateLimitError } =+ await import('src/unipile/utils/request-unipile.util');++const { linkedinPlanHistoryImportHandler } =+ await import('src/logic-functions/linkedin-plan-history-import');++const STATE_KEY = 'linkedin-history-import:connection-id';+const PLANNING_KEY = 'linkedin-history-import-planning:connection-id:run-1';++const RUNNING_STATE: LinkedinHistoryImportState = {+ runId: 'run-1',+ importPolicy: 'ALL',+ status: 'IMPORTING',+ importedConversationCount: 0,+ processedConversationCount: 0,+ startedAt: '2026-10-30T00:00:00.000Z',+};++const PAYLOAD = { connectedAccountId: 'connection-id', runId: 'run-1' };++const buildChatIds = (count: number, offset = 0) =>+ Array.from({ length: count }, (_, index) => `chat-${offset + index}`);++const mockChatPages = (pageSizes: number[]) => {+ pageSizes.forEach((pageSize, pageIndex) =>+ mocks.listUnipileChats.mockResolvedValueOnce({+ items: buildChatIds(pageSize, pageIndex * 20).map((id, index) => ({+ id,+ last_message_timestamp: new Date(+ Date.UTC(2026, 0, 1) - (pageIndex * 20 + index) * 60_000,+ ).toISOString(),+ })),+ nextCursor:+ pageIndex < pageSizes.length - 1+ ? `cursor-${pageIndex + 1}`+ : undefined,+ }),+ );+};++const getEnqueuedJobIds = (): string[] =>+ mocks.enqueueJobs.mock.calls.flatMap(([input]) =>+ input.jobs.map((job: { jobId: string }) => job.jobId),+ );++const getStoredChatIds = (chunkIndex: number) =>+ (+ mocks.kvStore.get(+ `linkedin-history-import-chats:connection-id:run-1:${chunkIndex}`,+ ) as { id: string }[] | undefined+ )?.map((chat) => chat.id);++describe('linkedinPlanHistoryImportHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useRealTimers();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ mocks.listUnipileChats.mockReset();+ mocks.kvStore.clear();+ mocks.kvStore.set(STATE_KEY, RUNNING_STATE);+ mocks.getConnection.mockResolvedValue({ externalAccountId: 'acc_1' });+ mocks.listUnipileInboxIds.mockResolvedValue(['inbox-1']);+ });++ it('stores each page of chats for the import jobs, most recent first', async () => {+ mockChatPages([20, 20, 5]);++ await expect(linkedinPlanHistoryImportHandler(PAYLOAD)).resolves.toEqual({+ status: 'PLANNED',+ chunkCount: 3,+ });++ expect(getStoredChatIds(0)).toEqual(buildChatIds(20));+ expect(getStoredChatIds(2)).toEqual(buildChatIds(5, 40));+ expect(mocks.kvStore.get(STATE_KEY)).toEqual(RUNNING_STATE);+ expect(mocks.kvStore.get(PLANNING_KEY)).toEqual({+ plannedChunkCount: 3,+ plannedConversationCount: 45,+ reportedConversationCount: 45,+ chunkCount: 3,+ planJobId: 'linkedin-history-plan-run-1-0',+ });+ });++ it('starts the import chain on the first page only', async () => {+ mockChatPages([20, 20, 5]);++ await linkedinPlanHistoryImportHandler(PAYLOAD);++ expect(getEnqueuedJobIds()).toEqual(['linkedin-history-chunk-run-1-0']);+ });++ it('restarts the import chain when it caught up with the listing', async () => {+ mocks.kvStore.set('linkedin-history-import-progress:connection-id:run-1', {+ completedChunkCount: 1,+ completedConversationCount: 20,+ importedConversationCount: 12,+ currentChunkProcessedCount: 0,+ });+ mockChatPages([20, 20]);++ await linkedinPlanHistoryImportHandler(PAYLOAD);++ expect(getEnqueuedJobIds()).toEqual(['linkedin-history-chunk-run-1-1']);+ });++ it('sorts each page by the date of its last message', async () => {+ mocks.listUnipileChats.mockResolvedValueOnce({+ items: [+ { id: 'older', last_message_timestamp: '2026-01-01T00:00:00.000Z' },+ { id: 'newer', last_message_timestamp: '2026-02-01T00:00:00.000Z' },+ ],+ nextCursor: undefined,+ });++ await linkedinPlanHistoryImportHandler(PAYLOAD);++ expect(getStoredChatIds(0)).toEqual(['newer', 'older']);+ });++ it('shows the total LinkedIn reports while still listing', async () => {+ let stateWhileListing: unknown;++ mocks.listUnipileChats+ .mockResolvedValueOnce({+ items: [{ id: 'chat-0' }],+ nextCursor: 'cursor-1',+ totalCount: 340,+ })+ .mockImplementationOnce(async () => {+ stateWhileListing = mocks.kvStore.get(PLANNING_KEY);++ return { items: [{ id: 'chat-1' }], nextCursor: undefined };+ });++ await linkedinPlanHistoryImportHandler(PAYLOAD);++ expect(stateWhileListing).toEqual({+ plannedChunkCount: 1,+ plannedConversationCount: 1,+ reportedConversationCount: 340,+ planJobId: 'linkedin-history-plan-run-1-0',+ });+ });++ it('hands over to a new planning job when its time runs out', async () => {+ vi.useFakeTimers({ now: 0 });+ mocks.listUnipileChats.mockImplementation(async ({ cursor }) => {+ vi.setSystemTime(Date.now() + 4 * 60 * 1000);++ return {+ items: buildChatIds(20).map((id) => ({ id })),+ nextCursor: `${cursor ?? ''}+`,+ };+ });++ await expect(linkedinPlanHistoryImportHandler(PAYLOAD)).resolves.toEqual({+ status: 'CONTINUED',+ });++ const continuation = mocks.enqueueJobs.mock.lastCall?.[0].jobs[0];++ expect(continuation).toEqual({+ jobId: 'linkedin-history-plan-run-1-1',+ payload: {+ connectedAccountId: 'connection-id',+ runId: 'run-1',+ continuationIndex: 1,+ inboxIndex: 0,+ cursor: '+++',+ plannedChunkCount: 3,+ plannedConversationCount: 60,+ reportedConversationCount: undefined,+ },+ });+ expect(mocks.kvStore.get(PLANNING_KEY)).toEqual({+ plannedChunkCount: 3,+ plannedConversationCount: 60,+ reportedConversationCount: undefined,+ planJobId: 'linkedin-history-plan-run-1-1',+ resumeAt: undefined,+ });+ });++ it('pauses the listing until the limit resets and resumes where it stopped', async () => {+ mocks.listUnipileChats+ .mockResolvedValueOnce({+ items: [{ id: 'chat-0' }],+ nextCursor: 'cursor-1',+ })+ .mockRejectedValueOnce(+ new UnipileRateLimitError('Retry in 2 hours.', 2 * 60 * 60 + 1),+ );++ await expect(linkedinPlanHistoryImportHandler(PAYLOAD)).resolves.toEqual({+ status: 'CONTINUED',+ });++ expect(mocks.enqueueJobs.mock.lastCall?.[0]).toEqual(+ expect.objectContaining({+ jobs: [+ {+ jobId: 'linkedin-history-plan-run-1-1',+ payload: expect.objectContaining({+ inboxIndex: 0,+ cursor: 'cursor-1',+ plannedChunkCount: 1,+ }),+ },+ ],+ delayMs: (2 * 60 * 60 + 1) * 1000,+ }),+ );+ expect(mocks.kvStore.get(PLANNING_KEY)).toEqual(+ expect.objectContaining({+ planJobId: 'linkedin-history-plan-run-1-1',+ resumeAt: expect.any(String),+ }),+ );+ });++ it('records a run with no conversations as fully listed', async () => {+ mockChatPages([0]);++ await linkedinPlanHistoryImportHandler(PAYLOAD);++ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ expect(mocks.kvStore.get(PLANNING_KEY)).toEqual(+ expect.objectContaining({ chunkCount: 0 }),+ );+ });++ it('lists nothing for a cancelled run', async () => {+ mocks.kvStore.set(STATE_KEY, { ...RUNNING_STATE, status: 'CANCELLED' });++ await expect(linkedinPlanHistoryImportHandler(PAYLOAD)).resolves.toEqual({+ status: 'CANCELLED',+ });+ expect(mocks.listUnipileChats).not.toHaveBeenCalled();+ });++ it('records a listing error Twenty will not retry', async () => {+ mocks.listUnipileChats.mockRejectedValue({+ status: 400,+ title: 'Invalid querystring',+ });++ await expect(+ linkedinPlanHistoryImportHandler(PAYLOAD, {+ retryCount: 0,+ maxRetries: 3,+ }),+ ).rejects.toThrow('Invalid querystring');+ expect(mocks.kvStore.get(STATE_KEY)).toEqual(RUNNING_STATE);+ expect(mocks.kvStore.get(PLANNING_KEY)).toEqual(+ expect.objectContaining({+ error: { code: 'UNKNOWN', message: 'Invalid querystring' },+ }),+ );+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-sync-history.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-sync-history.test.tsnew file mode 100644index 00000000000..43cf37e0b54--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-sync-history.test.ts@@ -0,0 +1,130 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ listConnections: vi.fn(),+ listMessageChannels: vi.fn(),+ enqueueJobs: vi.fn(),+ getJobs: vi.fn(),+ kvStore: new Map<string, unknown>(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ listConnections: mocks.listConnections,+ listMessageChannels: mocks.listMessageChannels,+ enqueueJobs: mocks.enqueueJobs,+ getJobs: mocks.getJobs,+ kv: {+ get: async (key: string) => mocks.kvStore.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ mocks.kvStore.set(key, value);+ },+ delete: async (key: string) => mocks.kvStore.delete(key),+ },+}));++const { linkedinSyncHistoryHandler } =+ await import('src/logic-functions/linkedin-sync-history');++const HISTORY_KEY = 'linkedin-history-import:connection-id';++const syncHistory = () =>+ linkedinSyncHistoryHandler({} as never, {+ userWorkspaceId: 'member-user-workspace-id',+ });++const setHistoryImport = (+ status: 'IMPORTING' | 'COMPLETED' | 'FAILED' | 'CANCELLED',+) =>+ mocks.kvStore.set(HISTORY_KEY, {+ runId: 'run-1',+ importPolicy: 'ALL',+ status,+ importedConversationCount: 12,+ processedConversationCount: 20,+ startedAt: '2026-10-01T00:00:00.000Z',+ });++describe('linkedinSyncHistoryHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.kvStore.clear();+ mocks.listConnections.mockResolvedValue([+ {+ id: 'connection-id',+ name: 'Ada Lovelace',+ handle: 'https://www.linkedin.com/in/ada',+ userWorkspaceId: 'member-user-workspace-id',+ authFailedAt: null,+ },+ ]);+ mocks.getJobs.mockImplementation(async (jobIds: string[]) =>+ jobIds.map((jobId) => ({ jobId, state: 'ACTIVE' })),+ );+ mocks.listMessageChannels.mockResolvedValue([+ { id: 'channel-id', visibility: 'METADATA' },+ ]);+ });++ it.each(['COMPLETED', 'FAILED', 'CANCELLED'] as const)(+ 'starts a new run after a %s one',+ async (status) => {+ setHistoryImport(status);++ const view = await syncHistory();++ expect(mocks.enqueueJobs).toHaveBeenCalledTimes(1);+ expect(view).toEqual(+ expect.objectContaining({+ historyImport: expect.objectContaining({+ status: 'IMPORTING',+ processedConversationCount: 0,+ }),+ }),+ );+ expect(+ (mocks.kvStore.get(HISTORY_KEY) as { runId: string }).runId,+ ).not.toBe('run-1');+ },+ );++ it('starts the first run of a connection that never synced', async () => {+ await syncHistory();++ expect(mocks.enqueueJobs).toHaveBeenCalledTimes(1);+ });++ it('leaves a running import alone', async () => {+ setHistoryImport('IMPORTING');++ await syncHistory();++ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ expect((mocks.kvStore.get(HISTORY_KEY) as { runId: string }).runId).toBe(+ 'run-1',+ );+ });++ it('restarts a run whose planning job is gone', async () => {+ setHistoryImport('IMPORTING');+ mocks.getJobs.mockResolvedValue([]);++ await syncHistory();++ expect(mocks.enqueueJobs).toHaveBeenCalledTimes(1);+ expect(+ (mocks.kvStore.get(HISTORY_KEY) as { runId: string }).runId,+ ).not.toBe('run-1');+ });++ it('refuses a member without a LinkedIn connection', async () => {+ mocks.listConnections.mockResolvedValue([]);++ await expect(syncHistory()).rejects.toThrow(+ 'Connect your LinkedIn account first.',+ );+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-update-settings.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-update-settings.test.tsnew file mode 100644index 00000000000..49247435abb--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-update-settings.test.ts@@ -0,0 +1,119 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ listConnections: vi.fn(),+ listMessageChannels: vi.fn(),+ updateMessageChannel: vi.fn(),+ enqueueJobs: vi.fn(),+ kvStore: new Map<string, unknown>(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ listConnections: mocks.listConnections,+ listMessageChannels: mocks.listMessageChannels,+ updateMessageChannel: mocks.updateMessageChannel,+ enqueueJobs: mocks.enqueueJobs,+ kv: {+ get: async (key: string) => mocks.kvStore.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ mocks.kvStore.set(key, value);+ },+ },+}));++const { linkedinUpdateSettingsHandler } =+ await import('src/logic-functions/linkedin-update-settings');++const HISTORY_KEY = 'linkedin-history-import:connection-id';++const updateSettings = (body: Record<string, unknown>) =>+ linkedinUpdateSettingsHandler({ body } as never, {+ userWorkspaceId: 'member-user-workspace-id',+ });++const setHistoryImport = (importPolicy: 'ALL' | 'CONTACTS_ONLY') =>+ mocks.kvStore.set(HISTORY_KEY, {+ runId: 'run-1',+ importPolicy,+ status: 'COMPLETED',+ importedConversationCount: 12,+ startedAt: '2026-10-01T00:00:00.000Z',+ });++describe('linkedinUpdateSettingsHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.kvStore.clear();+ mocks.listConnections.mockResolvedValue([+ {+ id: 'other-connection-id',+ userWorkspaceId: 'other-user-workspace-id',+ },+ {+ id: 'connection-id',+ name: 'Ada Lovelace',+ handle: 'https://www.linkedin.com/in/ada',+ userWorkspaceId: 'member-user-workspace-id',+ authFailedAt: null,+ },+ ]);+ mocks.listMessageChannels.mockResolvedValue([+ { id: 'channel-id', visibility: 'METADATA' },+ ]);+ setHistoryImport('ALL');+ });++ it('saves the valid fields of the member connection and ignores the others', async () => {+ const view = await updateSettings({+ contactAutoCreationPolicy: 'NONE',+ isNameMatchingEnabled: 'yes',+ importPolicy: 'SOME',+ });++ expect(view).toEqual(+ expect.objectContaining({+ isConnected: true,+ settings: {+ importPolicy: 'ALL',+ areGroupChatsImported: true,+ contactAutoCreationPolicy: 'NONE',+ isNameMatchingEnabled: true,+ visibility: 'METADATA',+ },+ }),+ );+ expect(mocks.kvStore.has('linkedin-settings:other-connection-id')).toBe(+ false,+ );+ expect(mocks.updateMessageChannel).not.toHaveBeenCalled();+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });++ it('applies the visibility to the message channel instead of the kv settings', async () => {+ await updateSettings({ visibility: 'SHARE_EVERYTHING' });++ expect(mocks.updateMessageChannel).toHaveBeenCalledExactlyOnceWith({+ id: 'channel-id',+ visibility: 'SHARE_EVERYTHING',+ });+ expect(+ mocks.kvStore.get('linkedin-settings:connection-id'),+ ).not.toHaveProperty('visibility');+ });++ it.each([+ [{ importPolicy: 'ALL' }],+ [{ importPolicy: 'CONTACTS_ONLY' }],+ [{ areGroupChatsImported: true }],+ ])('leaves importing to the Sync button when saving %o', async (update) => {+ setHistoryImport('CONTACTS_ONLY');++ await updateSettings(update);++ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-cancel-history-import.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-cancel-history-import.tsnew file mode 100644index 00000000000..a5d7bdc1c4e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-cancel-history-import.ts@@ -0,0 +1,51 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { LINKEDIN_SETTINGS_ROUTE_PATHS } from 'src/constants/linkedin-settings-route-paths.constant';+import { LINKEDIN_CANCEL_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { buildLinkedinSettingsView } from 'src/logic-functions/utils/build-linkedin-settings-view.util';+import { findOwnLinkedinConnection } from 'src/logic-functions/utils/find-own-linkedin-connection.util';+import { getLinkedinHistoryImportState } from 'src/logic-functions/utils/get-linkedin-history-import-state.util';+import { finishLinkedinHistoryImport } from 'src/logic-functions/utils/refresh-linkedin-history-import-state.util';+import { type LinkedinSettingsView } from 'src/types/linkedin-settings-view.type';++export const linkedinCancelHistoryImportHandler = async (+ _routePayload: RoutePayload,+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<LinkedinSettingsView> => {+ const connection = await findOwnLinkedinConnection(context);++ if (!isDefined(connection)) {+ throw new Error('Connect your LinkedIn account first.');+ }++ const state = await getLinkedinHistoryImportState(connection.id);++ if (state?.status === 'IMPORTING') {+ await finishLinkedinHistoryImport({+ connectedAccountId: connection.id,+ state: {+ ...state,+ status: 'CANCELLED',+ finishedAt: new Date().toISOString(),+ },+ });+ }++ return buildLinkedinSettingsView(connection);+};++export default defineLogicFunction({+ universalIdentifier: LINKEDIN_CANCEL_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-cancel-history-import',+ description:+ 'Cancels the running LinkedIn history import of the requesting member connection; its queued jobs then skip their chunk.',+ timeoutSeconds: 15,+ handler: linkedinCancelHistoryImportHandler,+ httpRouteTriggerSettings: {+ path: LINKEDIN_SETTINGS_ROUTE_PATHS.cancelHistoryImport,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-get-settings.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-get-settings.tsnew file mode 100644index 00000000000..b13db28e744--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-get-settings.ts@@ -0,0 +1,28 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';++import { LINKEDIN_SETTINGS_ROUTE_PATHS } from 'src/constants/linkedin-settings-route-paths.constant';+import { LINKEDIN_GET_SETTINGS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { buildLinkedinSettingsView } from 'src/logic-functions/utils/build-linkedin-settings-view.util';+import { findOwnLinkedinConnection } from 'src/logic-functions/utils/find-own-linkedin-connection.util';+import { type LinkedinSettingsView } from 'src/types/linkedin-settings-view.type';++export const linkedinGetSettingsHandler = async (+ _routePayload: RoutePayload,+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<LinkedinSettingsView> =>+ buildLinkedinSettingsView(await findOwnLinkedinConnection(context));++export default defineLogicFunction({+ universalIdentifier: LINKEDIN_GET_SETTINGS_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-get-settings',+ description:+ 'Returns the LinkedIn sync settings and history import progress of the requesting member connection.',+ timeoutSeconds: 15,+ handler: linkedinGetSettingsHandler,+ httpRouteTriggerSettings: {+ path: LINKEDIN_SETTINGS_ROUTE_PATHS.get,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-handle-webhook-event.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-handle-webhook-event.tsindex 03d45c53670..ad6a58a7086 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-handle-webhook-event.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-handle-webhook-event.ts@@ -1,6 +1,5 @@import { defineLogicFunction } from 'twenty-sdk/define';import {- ingestMessages,listMessageChannels,reportConnectionAuthFailure,} from 'twenty-sdk/logic-function';@@ -9,10 +8,10 @@ import { isDefined } from 'twenty-sdk/utils';import { LINKEDIN_HANDLE_WEBHOOK_EVENT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { findLinkedinConnectionByUnipileAccountId } from 'src/logic-functions/utils/find-linkedin-connection-by-unipile-account-id.util';import { getLinkedinChatCounterparts } from 'src/logic-functions/utils/get-linkedin-chat-counterparts.util';-import { mapUnipileMessageToIngestMessage } from 'src/logic-functions/utils/map-unipile-message-to-ingest-message.util';+import { getLinkedinSettings } from 'src/logic-functions/utils/get-linkedin-settings.util';+import { ingestLinkedinMessages } from 'src/logic-functions/utils/ingest-linkedin-messages.util';import { withLinkedinPublicIdentifier } from 'src/logic-functions/utils/with-linkedin-public-identifier.util';import { type UnipileMessage } from 'src/unipile/types/unipile-message.type';-import { type UnipileUser } from 'src/unipile/types/unipile-user.type';import { type UnipileWebhookEvent } from 'src/unipile/types/unipile-webhook-event.type';import { getUnipileChat } from 'src/unipile/utils/get-unipile-chat.util';@@ -33,40 +32,40 @@ const ingestUnipileMessage = async ({return { handled: false, reason: 'Connection has no message channel' };}- const resolveUser = (user: UnipileUser) =>- withLinkedinPublicIdentifier({ unipileAccountId, user });-- const counterparts = message.is_sender- ? await Promise.all(- getLinkedinChatCounterparts(- await getUnipileChat({- accountId: unipileAccountId,- chatId: message.chat_id,- }),- ).map(resolveUser),- )- : [];-- const sender =- !message.is_sender && isDefined(message.sender)- ? await resolveUser(message.sender)- : message.sender;-- const ingestMessage = mapUnipileMessageToIngestMessage({- message: { ...message, sender },- channelHandle: channel.handle,- counterparts,- });+ const settings = await getLinkedinSettings(connectedAccountId);- if (!isDefined(ingestMessage)) {- return { handled: false, reason: 'Message carries no content' };- }+ const chat = await getUnipileChat({+ accountId: unipileAccountId,+ chatId: message.chat_id,+ });- await ingestMessages({- messageChannelId: channel.id,- messages: [ingestMessage],+ const chatCounterparts = getLinkedinChatCounterparts(chat);+ const counterparts =+ message.is_sender ||+ !isDefined(message.sender) ||+ chatCounterparts.some((user) => user.id === message.sender?.id)+ ? chatCounterparts+ : [...chatCounterparts, message.sender];++ const { ingestedMessageCount } = await ingestLinkedinMessages({+ channel,+ settings,+ chat,+ counterparts: await Promise.all(+ counterparts.map((user) =>+ withLinkedinPublicIdentifier({ unipileAccountId, user }),+ ),+ ),+ messages: [message],});+ if (ingestedMessageCount === 0) {+ return {+ handled: false,+ reason: 'Message carries no content or nobody in it is in Twenty',+ };+ }+return { handled: true };};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-import-history.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-import-history.tsnew file mode 100644index 00000000000..2832603e8c5--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-import-history.ts@@ -0,0 +1,339 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction } from 'twenty-sdk/define';+import {+ type AppMessageChannel,+ getConnection,+ listMessageChannels,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { LINKEDIN_IMPORT_HISTORY_TIMEOUT_SECONDS } from 'src/constants/linkedin-import-history-timeout-seconds.constant';+import { LINKEDIN_IMPORT_HISTORY_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type LinkedinHistoryImportProgress } from 'src/logic-functions/types/linkedin-history-import-progress.type';+import { type LinkedinImportHistoryJobPayload } from 'src/logic-functions/types/linkedin-import-history-job-payload.type';+import { type LinkedinIngestResult } from 'src/logic-functions/types/linkedin-ingest-result.type';+import { enqueueLinkedinImportHistoryJob } from 'src/logic-functions/utils/enqueue-linkedin-import-history-job.util';+import { failLinkedinHistoryImportJob } from 'src/logic-functions/utils/fail-linkedin-history-import-job.util';+import { getActiveLinkedinHistoryImportState } from 'src/logic-functions/utils/get-active-linkedin-history-import-state.util';+import { getLinkedinChatCounterparts } from 'src/logic-functions/utils/get-linkedin-chat-counterparts.util';+import { getLinkedinImportHistoryJobId } from 'src/logic-functions/utils/get-linkedin-history-import-job-id.util';+import { getLinkedinSettings } from 'src/logic-functions/utils/get-linkedin-settings.util';+import { ingestLinkedinMessages } from 'src/logic-functions/utils/ingest-linkedin-messages.util';+import {+ getLinkedinHistoryImportChunkChats,+ getLinkedinHistoryImportProgress,+ saveLinkedinHistoryImportProgress,+} from 'src/logic-functions/utils/linkedin-history-import-kv.util';+import { withLinkedinPublicIdentifier } from 'src/logic-functions/utils/with-linkedin-public-identifier.util';+import { type LinkedinSettings } from 'src/types/linkedin-settings.type';+import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';+import { getUnipileChat } from 'src/unipile/utils/get-unipile-chat.util';+import { listUnipileChatMessagesPage } from 'src/unipile/utils/list-unipile-chat-messages-page.util';+import { UnipileRateLimitError } from 'src/unipile/utils/request-unipile.util';++const LINKEDIN_IMPORT_HISTORY_TIME_BUDGET_MILLISECONDS = 10 * 60 * 1000;++type LinkedinImportHistoryResult = {+ status: 'CANCELLED' | 'SKIPPED' | 'PAUSED' | 'COMPLETED';+ importedConversationCount?: number;+};++type LinkedinImportHistoryTotals = {+ messageCount: number;+ matchedPersonCount: number;+ createdPersonCount: number;+ skippedChatCounts: Record<+ NonNullable<LinkedinIngestResult['skippedReason']>,+ number+ >;+};++class LinkedinImportHistoryHandOff extends Error {}++const handOffToNextChunk = async ({+ connectedAccountId,+ runId,+ chunkIndex,+}: LinkedinImportHistoryJobPayload): Promise<void> => {+ const nextChunk = { connectedAccountId, runId, chunkIndex: chunkIndex + 1 };++ if ((await getLinkedinHistoryImportChunkChats(nextChunk)) !== null) {+ await enqueueLinkedinImportHistoryJob(nextChunk);+ }+};++const saveProgressIfActive = async ({+ payload,+ progress,+}: {+ payload: LinkedinImportHistoryJobPayload;+ progress: LinkedinHistoryImportProgress;+}): Promise<boolean> => {+ if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ return false;+ }++ await saveLinkedinHistoryImportProgress({ ...payload, progress });++ return true;+};++export const linkedinImportHistoryHandler = async (+ payload: LinkedinImportHistoryJobPayload,+ context?: Pick<LogicFunctionExecutionContext, 'retryCount' | 'maxRetries'>,+): Promise<LinkedinImportHistoryResult> => {+ if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ return { status: 'CANCELLED' };+ }++ const { connectedAccountId, runId, chunkIndex } = payload;+ const startProgress = await getLinkedinHistoryImportProgress(payload);++ if (startProgress.completedChunkCount === chunkIndex + 1) {+ await handOffToNextChunk(payload);++ return { status: 'SKIPPED' };+ }++ const chats = await getLinkedinHistoryImportChunkChats(payload);++ if (startProgress.completedChunkCount !== chunkIndex || chats === null) {+ return { status: 'SKIPPED' };+ }++ const startedAt = Date.now();+ const jobId = getLinkedinImportHistoryJobId(payload);+ let importedConversationCount = startProgress.currentChunkImportedCount ?? 0;+ let processedChatCount = startProgress.currentChunkProcessedCount;+ let chatCursor = startProgress.currentChatCursor;+ let isChatImported = startProgress.isCurrentChatImported ?? false;+ const totals: LinkedinImportHistoryTotals = {+ messageCount: 0,+ matchedPersonCount: 0,+ createdPersonCount: 0,+ skippedChatCounts: { GROUP_CHATS_OFF: 0, NO_MESSAGES: 0, NO_CONTACT: 0 },+ };++ const buildCurrentProgress = (): LinkedinHistoryImportProgress => ({+ completedChunkCount: startProgress.completedChunkCount,+ completedConversationCount: startProgress.completedConversationCount,+ importedConversationCount: startProgress.importedConversationCount,+ currentChunkProcessedCount: processedChatCount,+ currentChunkImportedCount: importedConversationCount,+ currentChatCursor: chatCursor,+ isCurrentChatImported: isChatImported,+ currentJobId: jobId,+ currentResumeIndex: payload.resumeIndex,+ });++ const saveCurrentProgress = async (): Promise<void> => {+ if (+ !(await saveProgressIfActive({+ payload,+ progress: buildCurrentProgress(),+ }))+ ) {+ throw new LinkedinImportHistoryHandOff('cancelled');+ }+ };++ const resumeLater = async ({+ delayMs,+ reason,+ }: {+ delayMs: number;+ reason: string;+ }): Promise<LinkedinImportHistoryResult> => {+ const resumePayload = {+ ...payload,+ resumeIndex: (payload.resumeIndex ?? 0) + 1,+ };+ const resumeAt =+ delayMs > 0 ? new Date(Date.now() + delayMs).toISOString() : undefined;++ if (+ !(await saveProgressIfActive({+ payload,+ progress: {+ ...buildCurrentProgress(),+ currentJobId: getLinkedinImportHistoryJobId(resumePayload),+ currentResumeIndex: resumePayload.resumeIndex,+ resumeAt,+ },+ }))+ ) {+ return { status: 'CANCELLED' };+ }++ await enqueueLinkedinImportHistoryJob(resumePayload, delayMs);++ console.log(+ `[linkedin] history run ${runId} chunk ${chunkIndex}: paused after ${processedChatCount} of ${chats.length} chats${isDefined(resumeAt) ? ` until ${resumeAt}` : ''}: ${reason}`,+ );++ return { status: 'PAUSED' };+ };++ const importChat = async ({+ listedChat,+ unipileAccountId,+ channel,+ settings,+ }: {+ listedChat: UnipileChat;+ unipileAccountId: string;+ channel: AppMessageChannel;+ settings: LinkedinSettings;+ }): Promise<void> => {+ const chat =+ getLinkedinChatCounterparts(listedChat).length > 0+ ? listedChat+ : await getUnipileChat({+ accountId: unipileAccountId,+ chatId: listedChat.id,+ });+ const counterparts = await Promise.all(+ getLinkedinChatCounterparts(chat).map((user) =>+ withLinkedinPublicIdentifier({ unipileAccountId, user }),+ ),+ );+ const seenCursors = new Set<string>();++ do {+ if (+ Date.now() - startedAt >+ LINKEDIN_IMPORT_HISTORY_TIME_BUDGET_MILLISECONDS+ ) {+ throw new LinkedinImportHistoryHandOff('time budget reached');+ }++ const page = await listUnipileChatMessagesPage({+ accountId: unipileAccountId,+ chatId: chat.id,+ cursor: chatCursor,+ });+ const ingestResult = await ingestLinkedinMessages({+ channel,+ settings,+ chat,+ counterparts,+ messages: page.items,+ });++ totals.messageCount += ingestResult.ingestedMessageCount;+ totals.matchedPersonCount += ingestResult.matchedPersonCount;+ totals.createdPersonCount += ingestResult.createdPersonCount;+ isChatImported ||= ingestResult.ingestedMessageCount > 0;++ if (isDefined(ingestResult.skippedReason) && !isDefined(chatCursor)) {+ totals.skippedChatCounts[ingestResult.skippedReason] += 1;+ }++ const nextCursor = page.nextCursor;+ const isLastPage =+ page.items.length === 0 ||+ !isNonEmptyString(nextCursor) ||+ seenCursors.has(nextCursor);++ chatCursor = isLastPage ? undefined : nextCursor;++ if (isNonEmptyString(nextCursor)) {+ seenCursors.add(nextCursor);+ }++ if (!isLastPage) {+ await saveCurrentProgress();+ }+ } while (isDefined(chatCursor));++ if (isChatImported) {+ importedConversationCount += 1;+ }++ processedChatCount += 1;+ isChatImported = false;++ await saveCurrentProgress();+ };++ try {+ const connection = await getConnection(connectedAccountId);+ const unipileAccountId = connection.externalAccountId;+ const [channel] = await listMessageChannels({ connectedAccountId });++ if (!isNonEmptyString(unipileAccountId) || !isDefined(channel)) {+ throw new Error(+ `LinkedIn connection ${connectedAccountId} has no Unipile account or message channel`,+ );+ }++ const settings = await getLinkedinSettings(connectedAccountId);++ for (const listedChat of chats.slice(processedChatCount)) {+ await importChat({ listedChat, unipileAccountId, channel, settings });+ }+ } catch (error) {+ if (error instanceof LinkedinImportHistoryHandOff) {+ return error.message === 'cancelled'+ ? { status: 'CANCELLED' }+ : resumeLater({ delayMs: 0, reason: error.message });+ }++ if (error instanceof UnipileRateLimitError) {+ return resumeLater({+ delayMs: error.retryAfterSeconds * 1000,+ reason: error.message,+ });+ }++ return failLinkedinHistoryImportJob({+ error,+ context,+ onFinalFailure: async (importError) => {+ await saveProgressIfActive({+ payload,+ progress: { ...buildCurrentProgress(), error: importError },+ });+ },+ });+ }++ const isActive = await saveProgressIfActive({+ payload,+ progress: {+ completedChunkCount: chunkIndex + 1,+ completedConversationCount:+ startProgress.completedConversationCount + chats.length,+ importedConversationCount:+ startProgress.importedConversationCount + importedConversationCount,+ currentChunkProcessedCount: 0,+ },+ });++ console.log(+ `[linkedin] history run ${runId} chunk ${chunkIndex}: ` ++ `${chats.length} chats (last messages ${chats[0]?.last_message_timestamp ?? '-'} to ${chats[chats.length - 1]?.last_message_timestamp ?? '-'}), ` ++ `${importedConversationCount} conversations imported, ${totals.messageCount} messages, ` ++ `${totals.matchedPersonCount} people matched, ${totals.createdPersonCount} people created, ` ++ `skipped ${totals.skippedChatCounts.NO_CONTACT} without contact, ${totals.skippedChatCounts.GROUP_CHATS_OFF} group chats, ${totals.skippedChatCounts.NO_MESSAGES} without messages, ` ++ `in ${Math.round((Date.now() - startedAt) / 1000)}s`,+ );++ if (!isActive) {+ return { status: 'CANCELLED' };+ }++ await handOffToNextChunk(payload);++ return { status: 'COMPLETED', importedConversationCount };+};++export default defineLogicFunction({+ universalIdentifier: LINKEDIN_IMPORT_HISTORY_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-import-history',+ description:+ 'Imports one page of past LinkedIn conversations of a connection, page of messages by page of messages, then queues the next page once it is listed, so one page is imported at a time.',+ timeoutSeconds: LINKEDIN_IMPORT_HISTORY_TIMEOUT_SECONDS,+ handler: linkedinImportHistoryHandler,+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-on-connect.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-on-connect.tsindex cb375aae11f..67442a92a6d 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-on-connect.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-on-connect.ts@@ -57,7 +57,7 @@ export default defineLogicFunction({universalIdentifier: LINKEDIN_ON_CONNECT_UNIVERSAL_IDENTIFIER,name: 'linkedin-on-connect',description:- 'Creates the message channel of a new LinkedIn connection and routes its Unipile webhooks to this workspace.',+ 'Creates the message channel of a new LinkedIn connection, routes its Unipile webhooks to this workspace.',timeoutSeconds: 30,handler: linkedinOnConnectHandler,});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-plan-history-import.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-plan-history-import.tsnew file mode 100644index 00000000000..0f28feadadb--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-plan-history-import.ts@@ -0,0 +1,329 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction } from 'twenty-sdk/define';+import {+ enqueueJobs,+ getConnection,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { LINKEDIN_HISTORY_IMPORT_CHATS_PER_JOB } from 'src/constants/linkedin-history-import-chats-per-job.constant';+import { LINKEDIN_IMPORT_HISTORY_TIMEOUT_SECONDS } from 'src/constants/linkedin-import-history-timeout-seconds.constant';+import { LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type LinkedinPlanHistoryImportJobPayload } from 'src/logic-functions/types/linkedin-plan-history-import-job-payload.type';+import { enqueueLinkedinImportHistoryJob } from 'src/logic-functions/utils/enqueue-linkedin-import-history-job.util';+import { failLinkedinHistoryImportJob } from 'src/logic-functions/utils/fail-linkedin-history-import-job.util';+import { getActiveLinkedinHistoryImportState } from 'src/logic-functions/utils/get-active-linkedin-history-import-state.util';+import { getLinkedinPlanHistoryImportJobId } from 'src/logic-functions/utils/get-linkedin-history-import-job-id.util';+import {+ getLinkedinHistoryImportPlanning,+ getLinkedinHistoryImportProgress,+ saveLinkedinHistoryImportChunkChats,+ saveLinkedinHistoryImportPlanning,+} from 'src/logic-functions/utils/linkedin-history-import-kv.util';+import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';+import { listUnipileChats } from 'src/unipile/utils/list-unipile-chats.util';+import { UnipileRateLimitError } from 'src/unipile/utils/request-unipile.util';+import { listUnipileInboxIds } from 'src/unipile/utils/list-unipile-inbox-ids.util';+import { sortUnipileChatsByLastMessage } from 'src/unipile/utils/sort-unipile-chats-by-last-message.util';++const LINKEDIN_PLAN_HISTORY_IMPORT_RETRY_LIMIT = 3;++const LINKEDIN_PLAN_HISTORY_IMPORT_TIME_BUDGET_MILLISECONDS = 10 * 60 * 1000;++type LinkedinPlanHistoryImportResult = {+ status: 'CANCELLED' | 'CONTINUED' | 'PLANNED';+ chunkCount?: number;+};++const getCurrentPlanJobId = ({+ runId,+ continuationIndex,+}: LinkedinPlanHistoryImportJobPayload): string =>+ getLinkedinPlanHistoryImportJobId({ runId, continuationIndex });++const continuePlanning = async (+ payload: LinkedinPlanHistoryImportJobPayload,+ delayMs?: number,+): Promise<LinkedinPlanHistoryImportResult> => {+ if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ return { status: 'CANCELLED' };+ }++ const planJobId = getLinkedinPlanHistoryImportJobId({+ runId: payload.runId,+ continuationIndex: payload.continuationIndex,+ });++ await saveLinkedinHistoryImportPlanning({+ ...payload,+ planning: {+ plannedChunkCount: payload.plannedChunkCount ?? 0,+ plannedConversationCount: payload.plannedConversationCount ?? 0,+ reportedConversationCount: payload.reportedConversationCount,+ planJobId,+ resumeAt: isDefined(delayMs)+ ? new Date(Date.now() + delayMs).toISOString()+ : undefined,+ },+ });+ await enqueueJobs({+ logicFunctionUniversalIdentifier:+ LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER,+ jobs: [{ jobId: planJobId, payload }],+ retryLimit: LINKEDIN_PLAN_HISTORY_IMPORT_RETRY_LIMIT,+ delayMs,+ });++ return { status: 'CONTINUED' };+};++const planChunk = async ({+ payload,+ chunkIndex,+ chats,+ conversationCount,+ reportedConversationCount,+}: {+ payload: LinkedinPlanHistoryImportJobPayload;+ chunkIndex: number;+ chats: UnipileChat[];+ conversationCount: number;+ reportedConversationCount: number | undefined;+}): Promise<boolean> => {+ const { connectedAccountId, runId } = payload;++ if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ return false;+ }++ await saveLinkedinHistoryImportChunkChats({+ connectedAccountId,+ runId,+ chunkIndex,+ chats,+ });+ await saveLinkedinHistoryImportPlanning({+ connectedAccountId,+ runId,+ planning: {+ plannedChunkCount: chunkIndex + 1,+ plannedConversationCount: conversationCount,+ reportedConversationCount,+ planJobId: getCurrentPlanJobId(payload),+ },+ });++ const { completedChunkCount } =+ await getLinkedinHistoryImportProgress(payload);++ if (completedChunkCount === chunkIndex) {+ await enqueueLinkedinImportHistoryJob({+ connectedAccountId,+ runId,+ chunkIndex,+ });+ }++ return true;+};++const finishPlanning = async ({+ payload,+ chunkCount,+ conversationCount,+}: {+ payload: LinkedinPlanHistoryImportJobPayload;+ chunkCount: number;+ conversationCount: number;+}): Promise<LinkedinPlanHistoryImportResult> => {+ if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ return { status: 'CANCELLED' };+ }++ await saveLinkedinHistoryImportPlanning({+ ...payload,+ planning: {+ plannedChunkCount: chunkCount,+ plannedConversationCount: conversationCount,+ reportedConversationCount: conversationCount,+ chunkCount,+ planJobId: getCurrentPlanJobId(payload),+ },+ });++ console.log(+ `[linkedin] history run ${payload.runId}: listing done, ${conversationCount} conversations in ${chunkCount} pages`,+ );++ return { status: 'PLANNED', chunkCount };+};++const planHistoryImport = async (+ payload: LinkedinPlanHistoryImportJobPayload,+): Promise<LinkedinPlanHistoryImportResult> => {+ const { connectedAccountId, runId } = payload;+ const startedAt = Date.now();+ const connection = await getConnection(connectedAccountId);+ const unipileAccountId = connection.externalAccountId;++ if (!isNonEmptyString(unipileAccountId)) {+ throw new Error(+ `LinkedIn connection ${connectedAccountId} has no Unipile account`,+ );+ }++ let inboxIndex = payload.inboxIndex ?? 0;+ let cursor = payload.cursor;+ let chunkCount = payload.plannedChunkCount ?? 0;+ let conversationCount = payload.plannedConversationCount ?? 0;+ let reportedConversationCount = payload.reportedConversationCount;++ const continueFromHere = (delayMs?: number) =>+ continuePlanning(+ {+ connectedAccountId,+ runId,+ continuationIndex: (payload.continuationIndex ?? 0) + 1,+ inboxIndex,+ cursor,+ plannedChunkCount: chunkCount,+ plannedConversationCount: conversationCount,+ reportedConversationCount,+ },+ delayMs,+ );++ const pauseOnRateLimit = async <TResult>(+ request: () => Promise<TResult>,+ ): Promise<TResult | LinkedinPlanHistoryImportResult> => {+ try {+ return await request();+ } catch (error) {+ if (!(error instanceof UnipileRateLimitError)) {+ throw error;+ }++ console.log(+ `[linkedin] history run ${runId}: listing paused for ${error.retryAfterSeconds}s: ${error.message}`,+ );++ return continueFromHere(error.retryAfterSeconds * 1000);+ }+ };++ const inboxIds = await pauseOnRateLimit(() =>+ listUnipileInboxIds(unipileAccountId),+ );++ if (!Array.isArray(inboxIds)) {+ return inboxIds;+ }++ while (inboxIndex < inboxIds.length) {+ if (+ Date.now() - startedAt >+ LINKEDIN_PLAN_HISTORY_IMPORT_TIME_BUDGET_MILLISECONDS+ ) {+ return continueFromHere();+ }++ const page = await pauseOnRateLimit(() =>+ listUnipileChats({+ accountId: unipileAccountId,+ inboxId: inboxIds[inboxIndex],+ cursor,+ limit: LINKEDIN_HISTORY_IMPORT_CHATS_PER_JOB,+ }),+ );++ if (!('items' in page)) {+ return page;+ }++ if (+ inboxIds.length === 1 &&+ !isDefined(cursor) &&+ isDefined(page.totalCount)+ ) {+ reportedConversationCount = page.totalCount;+ }++ const chats = sortUnipileChatsByLastMessage(page.items);++ console.log(+ `[linkedin] history run ${runId}: inbox ${inboxIndex + 1} of ${inboxIds.length}, ${chats.length} chats listed (last messages ${chats[0]?.last_message_timestamp ?? '-'} to ${chats[chats.length - 1]?.last_message_timestamp ?? '-'})${isDefined(page.totalCount) ? `, ${page.totalCount} in inbox` : ''}`,+ );++ if (chats.length > 0) {+ conversationCount += chats.length;++ if (+ !(await planChunk({+ payload,+ chunkIndex: chunkCount,+ chats,+ conversationCount,+ reportedConversationCount,+ }))+ ) {+ return { status: 'CANCELLED' };+ }++ chunkCount += 1;+ }++ if (+ page.items.length === 0 ||+ !isNonEmptyString(page.nextCursor) ||+ page.nextCursor === cursor+ ) {+ inboxIndex += 1;+ cursor = undefined;+ } else {+ cursor = page.nextCursor;+ }+ }++ return finishPlanning({ payload, chunkCount, conversationCount });+};++export const linkedinPlanHistoryImportHandler = async (+ payload: LinkedinPlanHistoryImportJobPayload,+ context?: Pick<LogicFunctionExecutionContext, 'retryCount' | 'maxRetries'>,+): Promise<LinkedinPlanHistoryImportResult> => {+ if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ return { status: 'CANCELLED' };+ }++ try {+ return await planHistoryImport(payload);+ } catch (error) {+ return failLinkedinHistoryImportJob({+ error,+ context,+ onFinalFailure: async (importError) => {+ if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ return;+ }++ await saveLinkedinHistoryImportPlanning({+ ...payload,+ planning: {+ ...(await getLinkedinHistoryImportPlanning(payload)),+ error: importError,+ },+ });+ },+ });+ }+};++export default defineLogicFunction({+ universalIdentifier: LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-plan-history-import',+ description:+ 'Lists the past LinkedIn conversations of a connection, most recent first, stores them page by page for the import jobs and starts the import chain; hands over to a new planning job when its time runs out.',+ timeoutSeconds: LINKEDIN_IMPORT_HISTORY_TIMEOUT_SECONDS,+ handler: linkedinPlanHistoryImportHandler,+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-sync-history.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-sync-history.tsnew file mode 100644index 00000000000..8666293fa87--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-sync-history.ts@@ -0,0 +1,50 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { LINKEDIN_SETTINGS_ROUTE_PATHS } from 'src/constants/linkedin-settings-route-paths.constant';+import { LINKEDIN_SYNC_HISTORY_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { buildLinkedinSettingsView } from 'src/logic-functions/utils/build-linkedin-settings-view.util';+import { findOwnLinkedinConnection } from 'src/logic-functions/utils/find-own-linkedin-connection.util';+import { getLinkedinSettings } from 'src/logic-functions/utils/get-linkedin-settings.util';+import { refreshLinkedinHistoryImportState } from 'src/logic-functions/utils/refresh-linkedin-history-import-state.util';+import { startLinkedinHistoryImport } from 'src/logic-functions/utils/start-linkedin-history-import.util';+import { type LinkedinSettingsView } from 'src/types/linkedin-settings-view.type';++export const linkedinSyncHistoryHandler = async (+ _routePayload: RoutePayload,+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<LinkedinSettingsView> => {+ const connection = await findOwnLinkedinConnection(context);++ if (!isDefined(connection)) {+ throw new Error('Connect your LinkedIn account first.');+ }++ const historyImport = await refreshLinkedinHistoryImportState(connection.id);++ if (historyImport?.status !== 'IMPORTING') {+ const { importPolicy } = await getLinkedinSettings(connection.id);++ await startLinkedinHistoryImport({+ connectedAccountId: connection.id,+ importPolicy,+ });+ }++ return buildLinkedinSettingsView(connection);+};++export default defineLogicFunction({+ universalIdentifier: LINKEDIN_SYNC_HISTORY_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-sync-history',+ description:+ 'Starts importing the past LinkedIn conversations of the requesting member connection, most recent first.',+ timeoutSeconds: 15,+ handler: linkedinSyncHistoryHandler,+ httpRouteTriggerSettings: {+ path: LINKEDIN_SETTINGS_ROUTE_PATHS.syncHistory,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-update-settings.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-update-settings.tsnew file mode 100644index 00000000000..759285d0903--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-update-settings.ts@@ -0,0 +1,70 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import {+ kv,+ listMessageChannels,+ type LogicFunctionExecutionContext,+ updateMessageChannel,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { LINKEDIN_SETTINGS_ROUTE_PATHS } from 'src/constants/linkedin-settings-route-paths.constant';+import { LINKEDIN_UPDATE_SETTINGS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { buildLinkedinSettingsView } from 'src/logic-functions/utils/build-linkedin-settings-view.util';+import { findOwnLinkedinConnection } from 'src/logic-functions/utils/find-own-linkedin-connection.util';+import { getLinkedinConnectionKvKey } from 'src/logic-functions/utils/get-linkedin-connection-kv-key.util';+import { getLinkedinSettings } from 'src/logic-functions/utils/get-linkedin-settings.util';+import { parseLinkedinSettingsUpdate } from 'src/logic-functions/utils/parse-linkedin-settings-update.util';+import { type LinkedinSettingsView } from 'src/types/linkedin-settings-view.type';++export const linkedinUpdateSettingsHandler = async (+ routePayload: RoutePayload<Record<string, unknown>>,+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<LinkedinSettingsView> => {+ const connection = await findOwnLinkedinConnection(context);++ if (!isDefined(connection)) {+ throw new Error('Connect your LinkedIn account first.');+ }++ const { visibility, ...settingsUpdate } = parseLinkedinSettingsUpdate(+ routePayload.body,+ );+ const settings = {+ ...(await getLinkedinSettings(connection.id)),+ ...settingsUpdate,+ };++ await kv.set(+ getLinkedinConnectionKvKey({+ kind: 'settings',+ connectedAccountId: connection.id,+ }),+ settings,+ );++ if (isDefined(visibility)) {+ const [channel] = await listMessageChannels({+ connectedAccountId: connection.id,+ });++ if (isDefined(channel)) {+ await updateMessageChannel({ id: channel.id, visibility });+ }+ }++ return buildLinkedinSettingsView(connection);+};++export default defineLogicFunction({+ universalIdentifier: LINKEDIN_UPDATE_SETTINGS_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-update-settings',+ description:+ 'Saves the LinkedIn sync settings of the requesting member connection.',+ timeoutSeconds: 15,+ handler: linkedinUpdateSettingsHandler,+ httpRouteTriggerSettings: {+ path: LINKEDIN_SETTINGS_ROUTE_PATHS.update,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-history-import-planning.type.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-history-import-planning.type.tsnew file mode 100644index 00000000000..4526c32d4ff--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-history-import-planning.type.ts@@ -0,0 +1,11 @@+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export type LinkedinHistoryImportPlanning = {+ plannedChunkCount: number;+ plannedConversationCount: number;+ reportedConversationCount?: number;+ chunkCount?: number;+ planJobId?: string;+ resumeAt?: string;+ error?: LinkedinHistoryImportState['error'];+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-history-import-progress.type.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-history-import-progress.type.tsnew file mode 100644index 00000000000..9a694aeac5d--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-history-import-progress.type.ts@@ -0,0 +1,16 @@+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export type LinkedinHistoryImportProgress = {+ completedChunkCount: number;+ completedConversationCount: number;+ importedConversationCount: number;+ currentChunkProcessedCount: number;+ currentChunkImportedCount?: number;+ currentJobId?: string;+ currentResumeIndex?: number;+ currentChatCursor?: string;+ isCurrentChatImported?: boolean;+ recoveryCount?: number;+ resumeAt?: string;+ error?: LinkedinHistoryImportState['error'];+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-import-history-job-payload.type.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-import-history-job-payload.type.tsnew file mode 100644index 00000000000..c51a0036230--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-import-history-job-payload.type.ts@@ -0,0 +1,6 @@+export type LinkedinImportHistoryJobPayload = {+ connectedAccountId: string;+ runId: string;+ chunkIndex: number;+ resumeIndex?: number;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-ingest-result.type.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-ingest-result.type.tsnew file mode 100644index 00000000000..e47b231b482--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-ingest-result.type.ts@@ -0,0 +1,6 @@+export type LinkedinIngestResult = {+ ingestedMessageCount: number;+ matchedPersonCount: number;+ createdPersonCount: number;+ skippedReason?: 'GROUP_CHATS_OFF' | 'NO_MESSAGES' | 'NO_CONTACT';+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-plan-history-import-job-payload.type.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-plan-history-import-job-payload.type.tsnew file mode 100644index 00000000000..32435b0ed2f--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-plan-history-import-job-payload.type.ts@@ -0,0 +1,10 @@+export type LinkedinPlanHistoryImportJobPayload = {+ connectedAccountId: string;+ runId: string;+ continuationIndex?: number;+ inboxIndex?: number;+ cursor?: string;+ plannedChunkCount?: number;+ plannedConversationCount?: number;+ reportedConversationCount?: number;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/build-linkedin-chat-subject.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/build-linkedin-chat-subject.util.test.tsnew file mode 100644index 00000000000..bee371b1ec2--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/build-linkedin-chat-subject.util.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { buildLinkedinChatSubject } from 'src/logic-functions/utils/build-linkedin-chat-subject.util';++const buildUser = (name: string) => ({ id: name, display_name: name });++const buildGroup = (names: string[], name = '') => ({+ id: 'chat',+ name,+ is_group: true,+ is_1to1: false,+ participants: names.map((participantName) => ({+ is_self: false,+ user: buildUser(participantName),+ })),+});++describe('buildLinkedinChatSubject', () => {+ it('uses the other person in a one-to-one chat', () => {+ expect(+ buildLinkedinChatSubject({+ id: 'chat',+ name: 'ignored',+ is_group: false,+ is_1to1: true,+ user: buildUser('Daphné Müller'),+ }),+ ).toBe('Daphné Müller');+ });++ it('uses the name LinkedIn gives a group', () => {+ expect(+ buildLinkedinChatSubject(buildGroup(['Ada', 'Bob'], ' Q4 hiring ')),+ ).toBe('Q4 hiring');+ });++ it('lists the members of an unnamed group', () => {+ expect(buildLinkedinChatSubject(buildGroup(['Ada', 'Bob']))).toBe(+ 'Ada, Bob',+ );+ expect(+ buildLinkedinChatSubject(buildGroup(['Ada', 'Bob', 'Cleo', 'Dan'])),+ ).toBe('Ada, Bob +2');+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/create-linkedin-person.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/create-linkedin-person.util.test.tsnew file mode 100644index 00000000000..d619147c474--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/create-linkedin-person.util.test.ts@@ -0,0 +1,74 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ mutation: vi.fn(), query: vi.fn() }));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class {+ mutation = mocks.mutation;+ query = mocks.query;+ },+}));++const { createLinkedinPerson } =+ await import('src/logic-functions/utils/create-linkedin-person.util');++const DAPHNE = {+ firstName: 'Daphné',+ lastName: 'Müller',+ handle: 'https://www.linkedin.com/in/daphne-muller',+};++const getCreatedPersonId = () =>+ mocks.mutation.mock.calls[0][0].createPerson.__args.data.id;++describe('createLinkedinPerson', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.mutation.mockImplementation(async (input) => ({+ createPerson: { id: input.createPerson.__args.data.id },+ }));+ });++ it('gives the same profile the same person id, whatever the link format', async () => {+ await createLinkedinPerson(DAPHNE);+ await createLinkedinPerson({+ ...DAPHNE,+ handle: 'linkedin.com/in/Daphne-Muller/',+ });++ const [firstId, secondId] = mocks.mutation.mock.calls.map(+ ([input]) => input.createPerson.__args.data.id,+ );++ expect(firstId).toBe(secondId);+ expect(firstId).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ );+ });++ it('reuses the person another job created first for the same profile', async () => {+ mocks.mutation.mockRejectedValue(new Error('duplicate key value'));+ mocks.query.mockResolvedValue({+ people: {+ edges: [+ {+ node: {+ id: 'existing-id',+ linkedinLink: { primaryLinkUrl: DAPHNE.handle },+ },+ },+ ],+ },+ });++ await expect(createLinkedinPerson(DAPHNE)).resolves.toBe('existing-id');+ });++ it('rethrows when nobody was created for the profile', async () => {+ mocks.mutation.mockRejectedValue(new Error('Forbidden'));+ mocks.query.mockResolvedValue({ people: { edges: [] } });++ await expect(createLinkedinPerson(DAPHNE)).rejects.toThrow('Forbidden');+ expect(getCreatedPersonId()).toBeDefined();+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/find-person-ids-by-linkedin-handle.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/find-person-ids-by-linkedin-handle.util.test.tsnew file mode 100644index 00000000000..2ad6fdc7395--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/find-person-ids-by-linkedin-handle.util.test.ts@@ -0,0 +1,74 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ query: vi.fn() }));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class {+ query = mocks.query;+ },+}));++const { findPersonIdsByLinkedinHandle } =+ await import('src/logic-functions/utils/find-person-ids-by-linkedin-handle.util');++const mockStoredLinks = (links: string[]) =>+ mocks.query.mockResolvedValue({+ people: {+ edges: links.map((primaryLinkUrl, index) => ({+ node: { id: `person-${index}`, linkedinLink: { primaryLinkUrl } },+ })),+ },+ });++describe('findPersonIdsByLinkedinHandle', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it.each([+ 'https://www.linkedin.com/in/daphn%C3%A9-m%C3%BCller',+ 'linkedin.com/in/Daphné-Müller/',+ 'https://www.linkedin.com/in/daphné-müller',+ ])('finds a person stored as %s', async (storedLink) => {+ mockStoredLinks([storedLink]);++ await expect(+ findPersonIdsByLinkedinHandle(+ 'https://www.linkedin.com/in/daphné-müller',+ ),+ ).resolves.toEqual(['person-0']);+ });++ it('searches the exact decoded, decomposed and encoded forms of an accented slug', async () => {+ mockStoredLinks([]);++ await findPersonIdsByLinkedinHandle(+ 'https://www.linkedin.com/in/daphn%C3%A9-m%C3%BCller',+ );++ const patterns = mocks.query.mock.calls[0][0].people.__args.filter.or.map(+ (condition: { linkedinLink: { primaryLinkUrl: { ilike: string } } }) =>+ condition.linkedinLink.primaryLinkUrl.ilike,+ );++ expect(patterns).toEqual(+ expect.arrayContaining([+ '%linkedin.com/in/daphné-müller',+ '%linkedin.com/in/daphné-müller/%',+ '%linkedin.com/in/daphn\\%C3\\%A9-m\\%C3\\%BCller',+ '%linkedin.com/in/daphne\\%CC\\%81-mu\\%CC\\%88ller?%',+ ]),+ );+ expect(patterns).not.toContain('%linkedin.com/in/daphné-müller%');+ });++ it('ignores people whose link only contains the slug', async () => {+ mockStoredLinks(['https://www.linkedin.com/in/daphné-müller-2']);++ await expect(+ findPersonIdsByLinkedinHandle(+ 'https://www.linkedin.com/in/daphné-müller',+ ),+ ).resolves.toEqual([]);+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/get-linkedin-history-import-error.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/get-linkedin-history-import-error.util.test.tsnew file mode 100644index 00000000000..f3671d5f35b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/get-linkedin-history-import-error.util.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it, vi } from 'vitest';++class AppConnectionAuthFailedError extends Error {}++vi.mock('twenty-sdk/logic-function', () => ({ AppConnectionAuthFailedError }));++const { getLinkedinHistoryImportError } =+ await import('src/logic-functions/utils/get-linkedin-history-import-error.util');++describe('getLinkedinHistoryImportError', () => {+ it.each([+ {+ error: new AppConnectionAuthFailedError('Connection auth failed'),+ code: 'AUTH_FAILED',+ message: 'Connection auth failed',+ },+ {+ error: {+ status: 401,+ title: 'Unauthorized',+ detail: 'Account disconnected',+ },+ code: 'AUTH_FAILED',+ message: 'Account disconnected',+ },+ {+ error: Object.assign(new TypeError('fetch failed'), {}),+ code: 'UNREACHABLE',+ message: 'fetch failed',+ },+ {+ error: { status: 503, title: 'Service unavailable' },+ code: 'UNREACHABLE',+ message: 'Service unavailable',+ },+ {+ error: {+ status: 501,+ title: 'Use List inbox Chats endpoint for this provider.',+ },+ code: 'UNKNOWN',+ message: 'Use List inbox Chats endpoint for this provider.',+ },+ {+ error: { status: 422, title: 'Invalid cursor' },+ code: 'UNKNOWN',+ message: 'Invalid cursor',+ },+ ])('classifies $message as $code', ({ error, code, message }) => {+ expect(getLinkedinHistoryImportError(error)).toEqual({ code, message });+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/ingest-linkedin-messages.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/ingest-linkedin-messages.util.test.tsnew file mode 100644index 00000000000..87b6c876539--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/ingest-linkedin-messages.util.test.ts@@ -0,0 +1,183 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DEFAULT_LINKEDIN_SETTINGS } from 'src/constants/default-linkedin-settings.constant';+import { type UnipileUser } from 'src/unipile/types/unipile-user.type';+import { type UnipileMessage } from 'src/unipile/types/unipile-message.type';++const mocks = vi.hoisted(() => ({+ ingestMessages: vi.fn(),+ matchLinkedinParticipantPersonId: vi.fn(),+ createLinkedinPerson: vi.fn(),+}));++vi.mock('twenty-sdk/logic-function', () => ({+ ingestMessages: mocks.ingestMessages,+}));++vi.mock(+ 'src/logic-functions/utils/match-linkedin-participant-person-id.util',+ () => ({+ matchLinkedinParticipantPersonId: mocks.matchLinkedinParticipantPersonId,+ }),+);++vi.mock('src/logic-functions/utils/create-linkedin-person.util', () => ({+ createLinkedinPerson: mocks.createLinkedinPerson,+}));++const { ingestLinkedinMessages } =+ await import('src/logic-functions/utils/ingest-linkedin-messages.util');++const PRIYA = {+ id: 'ACoPRIYA',+ display_name: 'Priya Nair',+ public_identifier: 'priya-nair',+};++const buildMessage = (isSender: boolean): UnipileMessage => ({+ id: `message-${isSender ? 'sent' : 'received'}`,+ chat_id: 'chat-1',+ sender_id: isSender ? 'ACoME' : PRIYA.id,+ text: 'Hello',+ timestamp: '2026-10-29T07:44:08.382Z',+ is_sender: isSender,+ is_deleted: false,+ is_event: false,+ provider: 'linkedin',+});++const ONE_TO_ONE_CHAT = {+ id: 'chat-1',+ name: 'Priya Nair',+ is_group: false,+ is_1to1: true,+ user: PRIYA,+};++const GROUP_CHAT = {+ id: 'chat-2',+ name: 'Q4 hiring',+ is_group: true,+ is_1to1: false,+ participants: [{ is_self: false, user: PRIYA }],+};++const ingest = ({+ settings = DEFAULT_LINKEDIN_SETTINGS,+ messages = [buildMessage(true)],+ chat = ONE_TO_ONE_CHAT,+ counterparts = [PRIYA],+}: {+ counterparts?: UnipileUser[];+ settings?: typeof DEFAULT_LINKEDIN_SETTINGS;+ messages?: UnipileMessage[];+ chat?: typeof ONE_TO_ONE_CHAT | typeof GROUP_CHAT;+} = {}) =>+ ingestLinkedinMessages({+ channel: { id: 'channel-id', handle: 'https://www.linkedin.com/in/me' },+ settings,+ chat,+ counterparts,+ messages,+ });++const ingestedParticipantPersonIds = () =>+ mocks.ingestMessages.mock.calls[0][0].messages[0].participants.map(+ (participant: { personId?: string }) => participant.personId,+ );++describe('ingestLinkedinMessages', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.matchLinkedinParticipantPersonId.mockResolvedValue(undefined);+ mocks.createLinkedinPerson.mockResolvedValue('created-id');+ });++ it('attaches the matched person to the participant', async () => {+ mocks.matchLinkedinParticipantPersonId.mockResolvedValue('priya-id');++ await expect(ingest()).resolves.toMatchObject({ ingestedMessageCount: 1 });+ expect(ingestedParticipantPersonIds()).toEqual([undefined, 'priya-id']);+ expect(mocks.createLinkedinPerson).not.toHaveBeenCalled();+ });++ it('names the conversation after the other person', async () => {+ await ingest();++ expect(mocks.ingestMessages.mock.calls[0][0].messages[0].subject).toBe(+ 'Priya Nair',+ );+ });++ it('imports a group chat with a known member under its name', async () => {+ mocks.matchLinkedinParticipantPersonId.mockResolvedValue('priya-id');++ await expect(ingest({ chat: GROUP_CHAT })).resolves.toMatchObject({+ ingestedMessageCount: 1,+ });+ expect(mocks.ingestMessages.mock.calls[0][0].messages[0].subject).toBe(+ 'Q4 hiring',+ );+ });++ it('skips a group chat where nobody is in Twenty, even with All chats', async () => {+ await expect(ingest({ chat: GROUP_CHAT })).resolves.toMatchObject({+ ingestedMessageCount: 0,+ });+ expect(mocks.createLinkedinPerson).not.toHaveBeenCalled();+ });++ it('skips group chats when they are not imported', async () => {+ mocks.matchLinkedinParticipantPersonId.mockResolvedValue('priya-id');++ await expect(+ ingest({+ chat: GROUP_CHAT,+ settings: {+ ...DEFAULT_LINKEDIN_SETTINGS,+ areGroupChatsImported: false,+ },+ }),+ ).resolves.toMatchObject({ ingestedMessageCount: 0 });+ expect(mocks.matchLinkedinParticipantPersonId).not.toHaveBeenCalled();+ });++ it('creates a person for an unknown profile the member messaged', async () => {+ await ingest();++ expect(mocks.createLinkedinPerson).toHaveBeenCalledExactlyOnceWith({+ firstName: 'Priya',+ lastName: 'Nair',+ handle: 'https://www.linkedin.com/in/priya-nair',+ });+ expect(ingestedParticipantPersonIds()).toEqual([undefined, 'created-id']);+ });++ it('creates nobody when the public profile URL is unknown', async () => {+ await ingest({+ counterparts: [{ ...PRIYA, public_identifier: undefined }],+ });++ expect(mocks.createLinkedinPerson).not.toHaveBeenCalled();+ });++ it('imports without creating anyone when the policy does not allow it', async () => {+ await ingest({ messages: [buildMessage(false)] });++ expect(mocks.createLinkedinPerson).not.toHaveBeenCalled();+ expect(mocks.ingestMessages).toHaveBeenCalledTimes(1);+ });++ it('skips chats with nobody already in Twenty with Contacts only', async () => {+ await expect(+ ingest({+ settings: {+ ...DEFAULT_LINKEDIN_SETTINGS,+ importPolicy: 'CONTACTS_ONLY',+ },+ }),+ ).resolves.toMatchObject({ ingestedMessageCount: 0 });+ expect(mocks.createLinkedinPerson).not.toHaveBeenCalled();+ expect(mocks.ingestMessages).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/match-linkedin-participant-person-id.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/match-linkedin-participant-person-id.util.test.tsnew file mode 100644index 00000000000..dd475a6a0ca--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/match-linkedin-participant-person-id.util.test.ts@@ -0,0 +1,149 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ query: vi.fn(),+ mutation: vi.fn(),+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class {+ query = mocks.query;+ mutation = mocks.mutation;+ },+}));++const { matchLinkedinParticipantPersonId } =+ await import('src/logic-functions/utils/match-linkedin-participant-person-id.util');++const JULIE = {+ id: 'ACoJULIE',+ display_name: 'Julie Martin',+ public_identifier: 'juliemartin',+};++const HANDLE = 'https://www.linkedin.com/in/juliemartin';++const buildPeople = (+ people: { id: string; primaryLinkUrl?: string | null }[],+) => ({+ people: {+ edges: people.map(({ id, primaryLinkUrl = null }) => ({+ node: { id, linkedinLink: { primaryLinkUrl } },+ })),+ },+});++describe('matchLinkedinParticipantPersonId', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('matches the person whose LinkedIn link has the same profile slug', async () => {+ mocks.query.mockResolvedValueOnce(+ buildPeople([+ { id: 'other-id', primaryLinkUrl: 'linkedin.com/in/juliemartin-2' },+ {+ id: 'julie-id',+ primaryLinkUrl: 'https://linkedin.com/in/JulieMartin/',+ },+ ]),+ );++ await expect(+ matchLinkedinParticipantPersonId({+ user: JULIE,+ isNameMatchingEnabled: true,+ }),+ ).resolves.toBe('julie-id');+ expect(mocks.mutation).not.toHaveBeenCalled();+ });++ it('links the only unlinked namesake and stores the profile link on it', async () => {+ mocks.query+ .mockResolvedValueOnce(buildPeople([]))+ .mockResolvedValueOnce(buildPeople([{ id: 'namesake-id' }]));+ mocks.mutation.mockResolvedValueOnce({+ updatePeople: [{ id: 'namesake-id' }],+ });++ await expect(+ matchLinkedinParticipantPersonId({+ user: JULIE,+ isNameMatchingEnabled: true,+ }),+ ).resolves.toBe('namesake-id');+ expect(mocks.mutation).toHaveBeenCalledExactlyOnceWith({+ updatePeople: {+ __args: {+ filter: {+ and: [+ { id: { eq: 'namesake-id' } },+ expect.objectContaining({ or: expect.any(Array) }),+ ],+ },+ data: { linkedinLink: { primaryLinkUrl: HANDLE } },+ },+ id: true,+ },+ });+ });++ it('matches again when another job linked the namesake first', async () => {+ mocks.query+ .mockResolvedValueOnce(buildPeople([]))+ .mockResolvedValueOnce(buildPeople([{ id: 'namesake-id' }]))+ .mockResolvedValueOnce(+ buildPeople([{ id: 'namesake-id', primaryLinkUrl: HANDLE }]),+ );+ mocks.mutation.mockResolvedValueOnce({ updatePeople: [] });++ await expect(+ matchLinkedinParticipantPersonId({+ user: JULIE,+ isNameMatchingEnabled: true,+ }),+ ).resolves.toBe('namesake-id');+ expect(mocks.query).toHaveBeenCalledTimes(3);+ });++ it('never matches by name without the public profile URL', async () => {+ mocks.query.mockResolvedValueOnce(buildPeople([]));++ await expect(+ matchLinkedinParticipantPersonId({+ user: { ...JULIE, public_identifier: undefined },+ isNameMatchingEnabled: true,+ }),+ ).resolves.toBeUndefined();+ expect(mocks.query).toHaveBeenCalledTimes(1);+ expect(mocks.mutation).not.toHaveBeenCalled();+ });++ it('links nobody when several namesakes match', async () => {+ mocks.query+ .mockResolvedValueOnce(buildPeople([]))+ .mockResolvedValueOnce(+ buildPeople([{ id: 'acme-julie-id' }, { id: 'globex-julie-id' }]),+ );++ await expect(+ matchLinkedinParticipantPersonId({+ user: JULIE,+ isNameMatchingEnabled: true,+ }),+ ).resolves.toBeUndefined();+ expect(mocks.mutation).not.toHaveBeenCalled();+ });++ it('only matches on the profile link when name matching is off', async () => {+ mocks.query.mockResolvedValueOnce(buildPeople([]));++ await expect(+ matchLinkedinParticipantPersonId({+ user: JULIE,+ isNameMatchingEnabled: false,+ }),+ ).resolves.toBeUndefined();+ expect(mocks.query).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/refresh-linkedin-history-import-state.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/refresh-linkedin-history-import-state.util.test.tsnew file mode 100644index 00000000000..3cf1a9fbaf3--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/refresh-linkedin-history-import-state.util.test.ts@@ -0,0 +1,265 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const mocks = vi.hoisted(() => ({+ getJobs: vi.fn(),+ enqueueJobs: vi.fn(),+ kvStore: new Map<string, unknown>(),+}));++vi.mock('twenty-sdk/logic-function', () => ({+ getJobs: mocks.getJobs,+ enqueueJobs: mocks.enqueueJobs,+ kv: {+ get: async (key: string) => mocks.kvStore.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ mocks.kvStore.set(key, value);+ },+ delete: async (key: string) => mocks.kvStore.delete(key),+ },+}));++const { refreshLinkedinHistoryImportState } =+ await import('src/logic-functions/utils/refresh-linkedin-history-import-state.util');++const STATE_KEY = 'linkedin-history-import:connection-id';+const PROGRESS_KEY = 'linkedin-history-import-progress:connection-id:run-1';+const PLANNING_KEY = 'linkedin-history-import-planning:connection-id:run-1';++const RUNNING_STATE: LinkedinHistoryImportState = {+ runId: 'run-1',+ importPolicy: 'ALL',+ status: 'IMPORTING',+ importedConversationCount: 0,+ processedConversationCount: 0,+ startedAt: '2026-10-30T00:00:00.000Z',+};++const LISTING_PLANNING = {+ plannedChunkCount: 3,+ plannedConversationCount: 60,+ planJobId: 'linkedin-history-plan-run-1-0',+};++const LISTED_PLANNING = {+ ...LISTING_PLANNING,+ plannedConversationCount: 45,+ reportedConversationCount: 45,+ chunkCount: 3,+};++const mockJobStates = (states: Record<string, string>) =>+ mocks.getJobs.mockImplementation(async (jobIds: string[]) =>+ jobIds+ .filter((jobId) => jobId in states)+ .map((jobId) => ({+ jobId,+ state: states[jobId],+ failedReason: states[jobId] === 'FAILED' ? 'Boom' : null,+ })),+ );++const setProgress = (progress: Record<string, unknown>) =>+ mocks.kvStore.set(PROGRESS_KEY, {+ completedChunkCount: 0,+ completedConversationCount: 0,+ importedConversationCount: 0,+ currentChunkProcessedCount: 0,+ ...progress,+ });++const getEnqueuedJobIds = (): string[] =>+ mocks.enqueueJobs.mock.calls.flatMap(([input]) =>+ input.jobs.map((job: { jobId: string }) => job.jobId),+ );++describe('refreshLinkedinHistoryImportState', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.kvStore.clear();+ mocks.kvStore.set(STATE_KEY, RUNNING_STATE);+ mocks.kvStore.set(PLANNING_KEY, LISTING_PLANNING);+ mockJobStates({+ 'linkedin-history-plan-run-1-0': 'ACTIVE',+ 'linkedin-history-chunk-run-1-1': 'ACTIVE',+ });+ });++ it('shows the listing and the chats imported so far', async () => {+ setProgress({+ completedChunkCount: 1,+ completedConversationCount: 20,+ importedConversationCount: 14,+ currentChunkProcessedCount: 7,+ currentChunkImportedCount: 3,+ currentJobId: 'linkedin-history-chunk-run-1-1',+ });++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual({+ ...RUNNING_STATE,+ processedConversationCount: 27,+ importedConversationCount: 17,+ plannedChunkCount: 3,+ plannedConversationCount: 60,+ totalConversationCount: undefined,+ chunkCount: undefined,+ resumeAt: undefined,+ });+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });++ it('completes the run once every listed page is imported and clears its data', async () => {+ mocks.kvStore.set(PLANNING_KEY, LISTED_PLANNING);+ mocks.kvStore.set(+ 'linkedin-history-import-chats:connection-id:run-1:2',+ [],+ );+ setProgress({+ completedChunkCount: 3,+ completedConversationCount: 45,+ importedConversationCount: 31,+ });++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual(+ expect.objectContaining({+ status: 'COMPLETED',+ importedConversationCount: 31,+ processedConversationCount: 45,+ }),+ );+ expect(mocks.kvStore.get(STATE_KEY)).toEqual(+ expect.objectContaining({ status: 'COMPLETED' }),+ );+ expect(mocks.kvStore.has(PROGRESS_KEY)).toBe(false);+ expect(mocks.kvStore.has(PLANNING_KEY)).toBe(false);+ expect(+ mocks.kvStore.has('linkedin-history-import-chats:connection-id:run-1:2'),+ ).toBe(false);+ });++ it('fails the run with the error a page stored', async () => {+ setProgress({+ completedChunkCount: 1,+ error: { code: 'AUTH_FAILED', message: 'Signed out' },+ });++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual(+ expect.objectContaining({+ status: 'FAILED',+ error: { code: 'AUTH_FAILED', message: 'Signed out' },+ }),+ );+ });++ it('fails the run with the error the listing stored', async () => {+ mocks.kvStore.set(PLANNING_KEY, {+ ...LISTING_PLANNING,+ error: { code: 'UNKNOWN', message: 'Invalid querystring' },+ });++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual(+ expect.objectContaining({+ status: 'FAILED',+ error: { code: 'UNKNOWN', message: 'Invalid querystring' },+ }),+ );+ });++ it('fails the run when the page being imported failed', async () => {+ setProgress({ completedChunkCount: 1 });+ mockJobStates({+ 'linkedin-history-plan-run-1-0': 'ACTIVE',+ 'linkedin-history-chunk-run-1-1': 'FAILED',+ });++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual(+ expect.objectContaining({+ status: 'FAILED',+ error: { code: 'UNKNOWN', message: 'Boom' },+ }),+ );+ });++ it('queues the listed page again when its job is missing', async () => {+ setProgress({ completedChunkCount: 2, completedConversationCount: 40 });++ await refreshLinkedinHistoryImportState('connection-id');++ expect(getEnqueuedJobIds()).toEqual(['linkedin-history-chunk-run-1-2']);+ });++ it('resumes a page whose job ended without finishing it', async () => {+ mocks.kvStore.set(PLANNING_KEY, LISTED_PLANNING);+ setProgress({+ completedChunkCount: 1,+ currentJobId: 'linkedin-history-chunk-run-1-1',+ });+ mockJobStates({ 'linkedin-history-chunk-run-1-1': 'COMPLETED' });++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual(expect.objectContaining({ status: 'IMPORTING' }));+ expect(getEnqueuedJobIds()).toEqual([+ 'linkedin-history-chunk-run-1-1-resume-1',+ ]);+ expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual(+ expect.objectContaining({+ currentJobId: 'linkedin-history-chunk-run-1-1-resume-1',+ currentResumeIndex: 1,+ recoveryCount: 1,+ }),+ );+ });++ it('gives up on a page that keeps ending without progress', async () => {+ mocks.kvStore.set(PLANNING_KEY, LISTED_PLANNING);+ setProgress({+ completedChunkCount: 1,+ currentJobId: 'linkedin-history-chunk-run-1-1-resume-3',+ currentResumeIndex: 3,+ recoveryCount: 3,+ });+ mockJobStates({ 'linkedin-history-chunk-run-1-1-resume-3': 'COMPLETED' });++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual(+ expect.objectContaining({+ status: 'FAILED',+ error: expect.objectContaining({ code: 'STALLED' }),+ }),+ );+ });++ it('fails a run whose planning job is gone', async () => {+ mockJobStates({});++ await expect(+ refreshLinkedinHistoryImportState('connection-id'),+ ).resolves.toEqual(+ expect.objectContaining({+ status: 'FAILED',+ error: expect.objectContaining({ code: 'STALLED' }),+ }),+ );+ });++ it('leaves a finished run as it is', async () => {+ mocks.kvStore.set(STATE_KEY, { ...RUNNING_STATE, status: 'CANCELLED' });++ await refreshLinkedinHistoryImportState('connection-id');++ expect(mocks.getJobs).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/remove-linkedin-connection-resources.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/remove-linkedin-connection-resources.util.test.tsindex d240d49ff5c..60afbe46eb6 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/remove-linkedin-connection-resources.util.test.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/remove-linkedin-connection-resources.util.test.ts@@ -4,13 +4,14 @@ const mocks = vi.hoisted(() => ({listMessageChannels: vi.fn(),deleteMessageChannel: vi.fn(),kvDelete: vi.fn(),+ kvGet: vi.fn(),deleteUnipileAccountOrThrow: vi.fn(),}));vi.mock('twenty-sdk/logic-function', () => ({listMessageChannels: mocks.listMessageChannels,deleteMessageChannel: mocks.deleteMessageChannel,- kv: { delete: mocks.kvDelete },+ kv: { delete: mocks.kvDelete, get: mocks.kvGet },}));vi.mock('src/unipile/utils/delete-unipile-account-or-throw.util', () => ({@@ -24,9 +25,36 @@ describe('removeLinkedinConnectionResources', () => {beforeEach(() => {vi.clearAllMocks();mocks.listMessageChannels.mockResolvedValue([{ id: 'channel-id' }]);+ mocks.kvGet.mockResolvedValue(null);});- it('deletes the channel, the Unipile account and the routing claim', async () => {+ it('clears the pages and progress of the last import run', async () => {+ mocks.kvGet.mockImplementation(async (key: string) => {+ if (key === 'linkedin-history-import:connection-id') {+ return { runId: 'run-1' };+ }++ return key.startsWith('linkedin-history-import-planning:')+ ? { plannedChunkCount: 2, plannedConversationCount: 40 }+ : null;+ });++ await removeLinkedinConnectionResources({+ connectedAccountId: 'connection-id',+ unipileAccountId: null,+ });++ expect(mocks.kvDelete.mock.calls.map(([key]) => key)).toEqual(+ expect.arrayContaining([+ 'linkedin-history-import-progress:connection-id:run-1',+ 'linkedin-history-import-planning:connection-id:run-1',+ 'linkedin-history-import-chats:connection-id:run-1:0',+ 'linkedin-history-import-chats:connection-id:run-1:1',+ ]),+ );+ });++ it('deletes the channel, the sync state, the Unipile account and the routing claim', async () => {await removeLinkedinConnectionResources({connectedAccountId: 'connection-id',unipileAccountId: 'acc_1',@@ -38,13 +66,14 @@ describe('removeLinkedinConnectionResources', () => {expect(mocks.deleteUnipileAccountOrThrow).toHaveBeenCalledExactlyOnceWith('acc_1',);- expect(mocks.kvDelete).toHaveBeenCalledExactlyOnceWith(- 'unipile-account:acc_1',- { scope: 'SERVER' },- );+ expect(mocks.kvDelete.mock.calls).toEqual([+ ['linkedin-settings:connection-id'],+ ['linkedin-history-import:connection-id'],+ ['unipile-account:acc_1', { scope: 'SERVER' }],+ ]);});- it('only deletes the channel when the Unipile account is unknown', async () => {+ it('only deletes the channel and the sync state when the Unipile account is unknown', async () => {await removeLinkedinConnectionResources({connectedAccountId: 'connection-id',unipileAccountId: null,@@ -54,6 +83,10 @@ describe('removeLinkedinConnectionResources', () => {'channel-id',);expect(mocks.deleteUnipileAccountOrThrow).not.toHaveBeenCalled();- expect(mocks.kvDelete).not.toHaveBeenCalled();+ expect(mocks.kvDelete).toHaveBeenCalledTimes(2);+ expect(mocks.kvDelete).not.toHaveBeenCalledWith(+ 'unipile-account:acc_1',+ expect.anything(),+ );});});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/with-linkedin-public-identifier.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/with-linkedin-public-identifier.util.test.tsindex b9be071d1af..c77933d1b23 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/with-linkedin-public-identifier.util.test.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/with-linkedin-public-identifier.util.test.ts@@ -14,6 +14,9 @@ vi.mock('src/unipile/utils/get-unipile-user.util', () => ({getUnipileUser: mocks.getUnipileUser,}));+const { UnipileRequestError } =+ await import('src/unipile/utils/request-unipile.util');+const { withLinkedinPublicIdentifier } =await import('src/logic-functions/utils/with-linkedin-public-identifier.util');@@ -71,8 +74,20 @@ describe('withLinkedinPublicIdentifier', () => {);});- it('falls back to the user as received when the profile lookup fails', async () => {- mocks.getUnipileUser.mockRejectedValue(new Error('429 too many requests'));+ it('fails on a temporary lookup error rather than linking a member id URL', async () => {+ mocks.getUnipileUser.mockRejectedValue(+ new UnipileRequestError('Unipile get user profile failed (429)', 429),+ );++ await expect(+ withLinkedinPublicIdentifier({ unipileAccountId: 'acc_1', user: DAPHNE }),+ ).rejects.toThrow('(429)');+ });++ it('falls back to the user as received when the profile is gone', async () => {+ mocks.getUnipileUser.mockRejectedValue(+ new UnipileRequestError('Unipile get user profile failed (404)', 404),+ );await expect(withLinkedinPublicIdentifier({ unipileAccountId: 'acc_1', user: DAPHNE }),diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-linkedin-chat-subject.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-linkedin-chat-subject.util.tsnew file mode 100644index 00000000000..004c9c2d336--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-linkedin-chat-subject.util.ts@@ -0,0 +1,37 @@+import { isNonEmptyString } from '@sniptt/guards';++import { getLinkedinChatCounterparts } from 'src/logic-functions/utils/get-linkedin-chat-counterparts.util';+import { isLinkedinGroupChat } from 'src/logic-functions/utils/is-linkedin-group-chat.util';+import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';++const NAMED_PARTICIPANT_COUNT = 2;++export const buildLinkedinChatSubject = (+ chat: UnipileChat,+): string | undefined => {+ const counterpartNames = getLinkedinChatCounterparts(chat)+ .map((counterpart) => counterpart.display_name?.trim())+ .filter(isNonEmptyString);++ if (!isLinkedinGroupChat(chat)) {+ return counterpartNames[0] ?? (chat.name?.trim() || undefined);+ }++ if (isNonEmptyString(chat.name?.trim())) {+ return chat.name.trim();+ }++ if (counterpartNames.length === 0) {+ return undefined;+ }++ const namedParticipants = counterpartNames+ .slice(0, NAMED_PARTICIPANT_COUNT)+ .join(', ');+ const otherParticipantCount =+ counterpartNames.length - NAMED_PARTICIPANT_COUNT;++ return otherParticipantCount > 0+ ? `${namedParticipants} +${otherParticipantCount}`+ : namedParticipants;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-linkedin-settings-view.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-linkedin-settings-view.util.tsnew file mode 100644index 00000000000..b1d4da067cb--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-linkedin-settings-view.util.ts@@ -0,0 +1,40 @@+import {+ type AppConnection,+ listMessageChannels,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { getLinkedinSettings } from 'src/logic-functions/utils/get-linkedin-settings.util';+import { refreshLinkedinHistoryImportState } from 'src/logic-functions/utils/refresh-linkedin-history-import-state.util';+import { type LinkedinSettingsView } from 'src/types/linkedin-settings-view.type';++export const buildLinkedinSettingsView = async (+ connection: AppConnection | undefined,+): Promise<LinkedinSettingsView> => {+ if (!isDefined(connection)) {+ return { isConnected: false };+ }++ const [settings, historyImport, [channel]] = await Promise.all([+ getLinkedinSettings(connection.id),+ refreshLinkedinHistoryImportState(connection.id),+ listMessageChannels({ connectedAccountId: connection.id }),+ ]);++ return {+ isConnected: true,+ connection: {+ name: connection.name,+ handle: connection.handle,+ isAuthFailed: isDefined(connection.authFailedAt),+ },+ settings: {+ ...settings,+ visibility:+ channel?.visibility === 'SHARE_EVERYTHING'+ ? 'SHARE_EVERYTHING'+ : 'METADATA',+ },+ historyImport,+ };+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/create-linkedin-person.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/create-linkedin-person.util.tsnew file mode 100644index 00000000000..a6a634cca14--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/create-linkedin-person.util.ts@@ -0,0 +1,63 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'twenty-sdk/utils';++import { findPersonIdsByLinkedinHandle } from 'src/logic-functions/utils/find-person-ids-by-linkedin-handle.util';+import { getLinkedinPersonId } from 'src/logic-functions/utils/get-linkedin-person-id.util';+import { getLinkedinProfileSlug } from 'src/logic-functions/utils/get-linkedin-profile-slug.util';++export const createLinkedinPerson = async ({+ firstName,+ lastName,+ handle,+}: {+ firstName: string;+ lastName: string;+ handle: string;+}): Promise<string> => {+ const slug = getLinkedinProfileSlug(handle);++ if (slug === null) {+ throw new Error(`Could not create the person for ${handle}`);+ }++ const id = await getLinkedinPersonId(slug);++ try {+ const { createPerson } = await new CoreApiClient({+ runAs: 'application',+ }).mutation({+ createPerson: {+ __args: {+ data: {+ id,+ name: { firstName, lastName },+ linkedinLink: { primaryLinkUrl: handle },+ },+ },+ id: true,+ },+ });++ if (isDefined(createPerson)) {+ console.log(+ `[linkedin] created person ${createPerson.id} for ${handle} (slug ${slug}, requested id ${id})`,+ );++ return createPerson.id;+ }+ } catch (error) {+ const [existingPersonId] = await findPersonIdsByLinkedinHandle(handle);++ if (isDefined(existingPersonId)) {+ console.log(+ `[linkedin] reused person ${existingPersonId} for ${handle} after create failed: ${error instanceof Error ? error.message : String(error)}`,+ );++ return existingPersonId;+ }++ throw error;+ }++ throw new Error(`Could not create the person for ${handle}`);+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/enqueue-linkedin-import-history-job.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/enqueue-linkedin-import-history-job.util.tsnew file mode 100644index 00000000000..5cc5bf4375e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/enqueue-linkedin-import-history-job.util.ts@@ -0,0 +1,20 @@+import { enqueueJobs } from 'twenty-sdk/logic-function';++import { LINKEDIN_IMPORT_HISTORY_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type LinkedinImportHistoryJobPayload } from 'src/logic-functions/types/linkedin-import-history-job-payload.type';+import { getLinkedinImportHistoryJobId } from 'src/logic-functions/utils/get-linkedin-history-import-job-id.util';++const LINKEDIN_IMPORT_HISTORY_RETRY_LIMIT = 3;++export const enqueueLinkedinImportHistoryJob = async (+ payload: LinkedinImportHistoryJobPayload,+ delayMs?: number,+): Promise<void> => {+ await enqueueJobs({+ logicFunctionUniversalIdentifier:+ LINKEDIN_IMPORT_HISTORY_UNIVERSAL_IDENTIFIER,+ jobs: [{ jobId: getLinkedinImportHistoryJobId(payload), payload }],+ retryLimit: LINKEDIN_IMPORT_HISTORY_RETRY_LIMIT,+ delayMs,+ });+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/escape-sql-like-pattern.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/escape-sql-like-pattern.util.tsnew file mode 100644index 00000000000..a763bfcce4f--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/escape-sql-like-pattern.util.ts@@ -0,0 +1,2 @@+export const escapeSqlLikePattern = (value: string): string =>+ value.replace(/[\\%_]/g, (wildcard) => `\\${wildcard}`);diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/fail-linkedin-history-import-job.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/fail-linkedin-history-import-job.util.tsnew file mode 100644index 00000000000..0be467d20c7--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/fail-linkedin-history-import-job.util.ts@@ -0,0 +1,34 @@+import {+ type LogicFunctionExecutionContext,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { getLinkedinHistoryImportError } from 'src/logic-functions/utils/get-linkedin-history-import-error.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export const failLinkedinHistoryImportJob = async ({+ error,+ context,+ onFinalFailure,+}: {+ error: unknown;+ context?: Pick<LogicFunctionExecutionContext, 'retryCount' | 'maxRetries'>;+ onFinalFailure: (+ importError: NonNullable<LinkedinHistoryImportState['error']>,+ ) => Promise<void>;+}): Promise<never> => {+ const importError = getLinkedinHistoryImportError(error);++ if (+ importError.code === 'UNREACHABLE' &&+ isDefined(context) &&+ context.retryCount < context.maxRetries+ ) {+ throw new RetryableLogicFunctionError(importError.message);+ }++ await onFinalFailure(importError);++ throw error instanceof Error ? error : new Error(importError.message);+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-own-linkedin-connection.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-own-linkedin-connection.util.tsnew file mode 100644index 00000000000..6df2973c67c--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-own-linkedin-connection.util.ts@@ -0,0 +1,24 @@+import {+ type AppConnection,+ listConnections,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { LINKEDIN_PROVIDER_NAME } from 'src/constants/linkedin-provider-name.constant';++export const findOwnLinkedinConnection = async (+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<AppConnection | undefined> => {+ if (!isDefined(context.userWorkspaceId)) {+ return undefined;+ }++ const connections = await listConnections({+ providerName: LINKEDIN_PROVIDER_NAME,+ });++ return connections.find(+ (connection) => connection.userWorkspaceId === context.userWorkspaceId,+ );+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-person-ids-by-linkedin-handle.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-person-ids-by-linkedin-handle.util.tsnew file mode 100644index 00000000000..f33ecfc8ce6--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-person-ids-by-linkedin-handle.util.ts@@ -0,0 +1,55 @@+import { CoreApiClient } from 'twenty-client-sdk/core';++import { escapeSqlLikePattern } from 'src/logic-functions/utils/escape-sql-like-pattern.util';+import { getLinkedinProfileSlug } from 'src/logic-functions/utils/get-linkedin-profile-slug.util';+import { type LinkedinPersonRecord } from 'src/types/linkedin-person-record.type';++const STORED_SLUG_ENDINGS = ['', '/%', '?%', '#%'];++const getStoredSlugForms = (slug: string): string[] => [+ ...new Set([+ slug,+ slug.normalize('NFD'),+ encodeURIComponent(slug),+ encodeURIComponent(slug.normalize('NFD')),+ ]),+];++export const findPersonIdsByLinkedinHandle = async (+ handle: string,+): Promise<string[]> => {+ const slug = getLinkedinProfileSlug(handle);++ if (slug === null) {+ return [];+ }++ const { people } = await new CoreApiClient({ runAs: 'application' }).query({+ people: {+ __args: {+ filter: {+ or: getStoredSlugForms(slug).flatMap((storedSlug) =>+ STORED_SLUG_ENDINGS.map((ending) => ({+ linkedinLink: {+ primaryLinkUrl: {+ ilike: `%linkedin.com/in/${escapeSqlLikePattern(storedSlug)}${ending}`,+ },+ },+ })),+ ),+ },+ first: 50,+ },+ edges: { node: { id: true, linkedinLink: { primaryLinkUrl: true } } },+ },+ });++ return (people?.edges ?? [])+ .map((edge: { node: LinkedinPersonRecord }) => edge.node)+ .filter(+ (person: LinkedinPersonRecord) =>+ getLinkedinProfileSlug(person.linkedinLink?.primaryLinkUrl ?? '') ===+ slug,+ )+ .map((person: LinkedinPersonRecord) => person.id);+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-unlinked-person-ids-by-name.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-unlinked-person-ids-by-name.util.tsnew file mode 100644index 00000000000..b6d1aefb408--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/find-unlinked-person-ids-by-name.util.ts@@ -0,0 +1,46 @@+import { isNonEmptyString } from '@sniptt/guards';+import { CoreApiClient } from 'twenty-client-sdk/core';++import { UNLINKED_PERSON_FILTER } from 'src/logic-functions/utils/unlinked-person-filter.constant';+import { escapeSqlLikePattern } from 'src/logic-functions/utils/escape-sql-like-pattern.util';+import { type LinkedinPersonRecord } from 'src/types/linkedin-person-record.type';++export const findUnlinkedPersonIdsByName = async ({+ firstName,+ lastName,+}: {+ firstName: string;+ lastName: string;+}): Promise<string[]> => {+ if (!isNonEmptyString(firstName) || !isNonEmptyString(lastName)) {+ return [];+ }++ const { people } = await new CoreApiClient({ runAs: 'application' }).query({+ people: {+ __args: {+ filter: {+ and: [+ {+ name: {+ firstName: { ilike: escapeSqlLikePattern(firstName) },+ lastName: { ilike: escapeSqlLikePattern(lastName) },+ },+ },+ UNLINKED_PERSON_FILTER,+ ],+ },+ first: 2,+ },+ edges: { node: { id: true, linkedinLink: { primaryLinkUrl: true } } },+ },+ });++ return (people?.edges ?? [])+ .map((edge: { node: LinkedinPersonRecord }) => edge.node)+ .filter(+ (person: LinkedinPersonRecord) =>+ !isNonEmptyString(person.linkedinLink?.primaryLinkUrl),+ )+ .map((person: LinkedinPersonRecord) => person.id);+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-active-linkedin-history-import-state.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-active-linkedin-history-import-state.util.tsnew file mode 100644index 00000000000..336592fc7ce--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-active-linkedin-history-import-state.util.ts@@ -0,0 +1,14 @@+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';+import { getLinkedinHistoryImportState } from 'src/logic-functions/utils/get-linkedin-history-import-state.util';++export const getActiveLinkedinHistoryImportState = async ({+ connectedAccountId,+ runId,+}: {+ connectedAccountId: string;+ runId: string;+}): Promise<LinkedinHistoryImportState | null> => {+ const state = await getLinkedinHistoryImportState(connectedAccountId);++ return state?.runId === runId && state.status === 'IMPORTING' ? state : null;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-connection-kv-key.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-connection-kv-key.util.tsnew file mode 100644index 00000000000..af2ebdcd9bd--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-connection-kv-key.util.ts@@ -0,0 +1,7 @@+export const getLinkedinConnectionKvKey = ({+ kind,+ connectedAccountId,+}: {+ kind: 'settings' | 'history-import';+ connectedAccountId: string;+}): string => `linkedin-${kind}:${connectedAccountId}`;diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-error.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-error.util.tsnew file mode 100644index 00000000000..9c3ca9656a7--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-error.util.ts@@ -0,0 +1,53 @@+import { isNumber, isObject, isString } from '@sniptt/guards';+import { AppConnectionAuthFailedError } from 'twenty-sdk/logic-function';++import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const TRANSIENT_HTTP_STATUSES = [429, 500, 502, 503, 504];++const getErrorMessage = (error: unknown): string => {+ if (error instanceof Error) {+ return error.message;+ }++ if (isObject(error)) {+ const { detail, title } = error as { detail?: unknown; title?: unknown };++ if (isString(detail)) {+ return detail;+ }++ if (isString(title)) {+ return title;+ }+ }++ return String(error);+};++export const getLinkedinHistoryImportError = (+ error: unknown,+): NonNullable<LinkedinHistoryImportState['error']> => {+ const message = getErrorMessage(error);+ const status = isObject(error)+ ? (error as { status?: unknown }).status+ : undefined;++ if (+ error instanceof AppConnectionAuthFailedError ||+ status === 401 ||+ status === 403+ ) {+ return { code: 'AUTH_FAILED', message };+ }++ if (+ (error instanceof Error &&+ (error.name === 'TypeError' || error.name === 'AbortError')) ||+ (isNumber(status) && TRANSIENT_HTTP_STATUSES.includes(status))+ ) {+ return { code: 'UNREACHABLE', message };+ }++ return { code: 'UNKNOWN', message };+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-job-id.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-job-id.util.tsnew file mode 100644index 00000000000..7953c1a7e0e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-job-id.util.ts@@ -0,0 +1,18 @@+export const getLinkedinPlanHistoryImportJobId = ({+ runId,+ continuationIndex = 0,+}: {+ runId: string;+ continuationIndex?: number;+}): string => `linkedin-history-plan-${runId}-${continuationIndex}`;++export const getLinkedinImportHistoryJobId = ({+ runId,+ chunkIndex,+ resumeIndex = 0,+}: {+ runId: string;+ chunkIndex: number;+ resumeIndex?: number;+}): string =>+ `linkedin-history-chunk-${runId}-${chunkIndex}${resumeIndex > 0 ? `-resume-${resumeIndex}` : ''}`;diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-state.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-state.util.tsnew file mode 100644index 00000000000..25e552bcdba--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-history-import-state.util.ts@@ -0,0 +1,11 @@+import { kv } from 'twenty-sdk/logic-function';++import { getLinkedinConnectionKvKey } from 'src/logic-functions/utils/get-linkedin-connection-kv-key.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export const getLinkedinHistoryImportState = (+ connectedAccountId: string,+): Promise<LinkedinHistoryImportState | null> =>+ kv.get<LinkedinHistoryImportState>(+ getLinkedinConnectionKvKey({ kind: 'history-import', connectedAccountId }),+ );diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-person-id.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-person-id.util.tsnew file mode 100644index 00000000000..4ddd9636467--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-person-id.util.ts@@ -0,0 +1,17 @@+export const getLinkedinPersonId = async (slug: string): Promise<string> => {+ const digest = new Uint8Array(+ await crypto.subtle.digest(+ 'SHA-256',+ new TextEncoder().encode(`linkedin-person:${slug}`),+ ),+ ).slice(0, 16);++ digest[6] = (digest[6] & 0x0f) | 0x40;+ digest[8] = (digest[8] & 0x3f) | 0x80;++ const hex = [...digest]+ .map((byte) => byte.toString(16).padStart(2, '0'))+ .join('');++ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-profile-slug.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-profile-slug.util.tsnew file mode 100644index 00000000000..29498ce03b6--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-profile-slug.util.ts@@ -0,0 +1,15 @@+const LINKEDIN_PROFILE_SLUG_PATTERN = /linkedin\.com\/in\/([^/?#]+)/i;++const decodeSlug = (slug: string): string => {+ try {+ return decodeURIComponent(slug);+ } catch {+ return slug;+ }+};++export const getLinkedinProfileSlug = (url: string): string | null => {+ const slug = LINKEDIN_PROFILE_SLUG_PATTERN.exec(url)?.[1];++ return slug ? decodeSlug(slug).normalize('NFC').toLowerCase() : null;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-settings.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-settings.util.tsnew file mode 100644index 00000000000..e2ab12964d4--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/get-linkedin-settings.util.ts@@ -0,0 +1,15 @@+import { kv } from 'twenty-sdk/logic-function';++import { DEFAULT_LINKEDIN_SETTINGS } from 'src/constants/default-linkedin-settings.constant';+import { getLinkedinConnectionKvKey } from 'src/logic-functions/utils/get-linkedin-connection-kv-key.util';+import { type LinkedinSettings } from 'src/types/linkedin-settings.type';++export const getLinkedinSettings = async (+ connectedAccountId: string,+): Promise<LinkedinSettings> => {+ const storedSettings = await kv.get<Partial<LinkedinSettings>>(+ getLinkedinConnectionKvKey({ kind: 'settings', connectedAccountId }),+ );++ return { ...DEFAULT_LINKEDIN_SETTINGS, ...storedSettings };+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/ingest-linkedin-messages.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/ingest-linkedin-messages.util.tsnew file mode 100644index 00000000000..1d1097a86c8--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/ingest-linkedin-messages.util.ts@@ -0,0 +1,191 @@+import { isNonEmptyString } from '@sniptt/guards';+import {+ type AppMessageChannel,+ ingestMessages,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { INGEST_MESSAGES_MAX_BATCH_SIZE } from 'src/constants/ingest-messages-max-batch-size.constant';+import { buildLinkedinChatSubject } from 'src/logic-functions/utils/build-linkedin-chat-subject.util';+import { buildLinkedinProfileHandle } from 'src/logic-functions/utils/build-linkedin-profile-handle.util';+import { createLinkedinPerson } from 'src/logic-functions/utils/create-linkedin-person.util';+import { isLinkedinContactCreationAllowed } from 'src/logic-functions/utils/is-linkedin-contact-creation-allowed.util';+import { isLinkedinGroupChat } from 'src/logic-functions/utils/is-linkedin-group-chat.util';+import { mapUnipileMessageToIngestMessage } from 'src/logic-functions/utils/map-unipile-message-to-ingest-message.util';+import { matchLinkedinParticipantPersonId } from 'src/logic-functions/utils/match-linkedin-participant-person-id.util';+import { splitLinkedinUserName } from 'src/logic-functions/utils/split-linkedin-user-name.util';+import { type LinkedinIngestResult } from 'src/logic-functions/types/linkedin-ingest-result.type';+import { type LinkedinSettings } from 'src/types/linkedin-settings.type';+import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';+import { type UnipileMessage } from 'src/unipile/types/unipile-message.type';+import { type UnipileUser } from 'src/unipile/types/unipile-user.type';++const resolvePersonIdByHandle = async ({+ settings,+ counterparts,+ hasUserSentMessage,+ isGroupChat,+}: {+ settings: LinkedinSettings;+ counterparts: UnipileUser[];+ hasUserSentMessage: boolean;+ isGroupChat: boolean;+}): Promise<+ | {+ personIdByHandle: Map<string, string>;+ matchedPersonCount: number;+ createdPersonCount: number;+ }+ | undefined+> => {+ const personIdByHandle = new Map<string, string>();+ const unmatchedCounterparts: UnipileUser[] = [];++ for (const counterpart of counterparts) {+ const personId = await matchLinkedinParticipantPersonId({+ user: counterpart,+ isNameMatchingEnabled: settings.isNameMatchingEnabled,+ });++ if (isDefined(personId)) {+ personIdByHandle.set(buildLinkedinProfileHandle(counterpart), personId);+ } else {+ unmatchedCounterparts.push(counterpart);+ }+ }++ if (+ (settings.importPolicy === 'CONTACTS_ONLY' || isGroupChat) &&+ personIdByHandle.size === 0+ ) {+ return undefined;+ }++ const matchedPersonCount = personIdByHandle.size;++ if (+ !isLinkedinContactCreationAllowed({+ policy: settings.contactAutoCreationPolicy,+ hasUserSentMessage,+ })+ ) {+ return { personIdByHandle, matchedPersonCount, createdPersonCount: 0 };+ }++ for (const counterpart of unmatchedCounterparts) {+ const { firstName, lastName } = splitLinkedinUserName(counterpart);++ if (+ isNonEmptyString(firstName) &&+ isNonEmptyString(counterpart.public_identifier)+ ) {+ const handle = buildLinkedinProfileHandle(counterpart);++ personIdByHandle.set(+ handle,+ await createLinkedinPerson({ firstName, lastName, handle }),+ );+ }+ }++ return {+ personIdByHandle,+ matchedPersonCount,+ createdPersonCount: personIdByHandle.size - matchedPersonCount,+ };+};++export const ingestLinkedinMessages = async ({+ channel,+ settings,+ chat,+ counterparts,+ messages,+}: {+ channel: Pick<AppMessageChannel, 'id' | 'handle'>;+ settings: LinkedinSettings;+ chat: UnipileChat;+ counterparts: UnipileUser[];+ messages: UnipileMessage[];+}): Promise<LinkedinIngestResult> => {+ const isGroupChat = isLinkedinGroupChat(chat);++ const emptyResult = {+ ingestedMessageCount: 0,+ matchedPersonCount: 0,+ createdPersonCount: 0,+ };++ if (isGroupChat && !settings.areGroupChatsImported) {+ return { ...emptyResult, skippedReason: 'GROUP_CHATS_OFF' };+ }++ const ingestableMessages = messages.filter(+ (message) => !message.is_event && !message.is_deleted,+ );++ if (ingestableMessages.length === 0) {+ return { ...emptyResult, skippedReason: 'NO_MESSAGES' };+ }++ const resolvedPersons = await resolvePersonIdByHandle({+ settings,+ counterparts,+ hasUserSentMessage: ingestableMessages.some((message) => message.is_sender),+ isGroupChat,+ });++ if (!isDefined(resolvedPersons)) {+ return { ...emptyResult, skippedReason: 'NO_CONTACT' };+ }++ const { personIdByHandle, matchedPersonCount, createdPersonCount } =+ resolvedPersons;++ const subject = buildLinkedinChatSubject(chat);+ const ingestMessagesInput = ingestableMessages+ .map((message) =>+ mapUnipileMessageToIngestMessage({+ message: {+ ...message,+ sender: message.is_sender+ ? message.sender+ : (counterparts.find(+ (counterpart) => counterpart.id === message.sender_id,+ ) ?? message.sender),+ },+ channelHandle: channel.handle,+ counterparts,+ }),+ )+ .filter(isDefined)+ .map((ingestMessage) => ({+ ...ingestMessage,+ subject,+ participants: ingestMessage.participants.map((participant) => {+ const personId = personIdByHandle.get(participant.handle);++ return isDefined(personId) ? { ...participant, personId } : participant;+ }),+ }));++ for (+ let batchStart = 0;+ batchStart < ingestMessagesInput.length;+ batchStart += INGEST_MESSAGES_MAX_BATCH_SIZE+ ) {+ await ingestMessages({+ messageChannelId: channel.id,+ messages: ingestMessagesInput.slice(+ batchStart,+ batchStart + INGEST_MESSAGES_MAX_BATCH_SIZE,+ ),+ });+ }++ return {+ ingestedMessageCount: ingestMessagesInput.length,+ matchedPersonCount,+ createdPersonCount,+ };+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/is-linkedin-contact-creation-allowed.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/is-linkedin-contact-creation-allowed.util.tsnew file mode 100644index 00000000000..ab7f4a42f8b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/is-linkedin-contact-creation-allowed.util.ts@@ -0,0 +1,10 @@+import { type LinkedinContactAutoCreationPolicy } from 'src/types/linkedin-contact-auto-creation-policy.type';++export const isLinkedinContactCreationAllowed = ({+ policy,+ hasUserSentMessage,+}: {+ policy: LinkedinContactAutoCreationPolicy;+ hasUserSentMessage: boolean;+}): boolean =>+ policy === 'SENT_AND_RECEIVED' || (policy === 'SENT' && hasUserSentMessage);diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/is-linkedin-group-chat.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/is-linkedin-group-chat.util.tsnew file mode 100644index 00000000000..3a2a049a0dc--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/is-linkedin-group-chat.util.ts@@ -0,0 +1,5 @@+import { getLinkedinChatCounterparts } from 'src/logic-functions/utils/get-linkedin-chat-counterparts.util';+import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';++export const isLinkedinGroupChat = (chat: UnipileChat): boolean =>+ chat.is_group || getLinkedinChatCounterparts(chat).length > 1;diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/linkedin-history-import-kv.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/linkedin-history-import-kv.util.tsnew file mode 100644index 00000000000..458ecf739cd--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/linkedin-history-import-kv.util.ts@@ -0,0 +1,92 @@+import { kv } from 'twenty-sdk/logic-function';++import { type LinkedinHistoryImportPlanning } from 'src/logic-functions/types/linkedin-history-import-planning.type';+import { type LinkedinHistoryImportProgress } from 'src/logic-functions/types/linkedin-history-import-progress.type';+import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';++type LinkedinHistoryImportRun = { connectedAccountId: string; runId: string };++const EMPTY_PROGRESS: LinkedinHistoryImportProgress = {+ completedChunkCount: 0,+ completedConversationCount: 0,+ importedConversationCount: 0,+ currentChunkProcessedCount: 0,+};++const EMPTY_PLANNING: LinkedinHistoryImportPlanning = {+ plannedChunkCount: 0,+ plannedConversationCount: 0,+};++const getPlanningKey = ({+ connectedAccountId,+ runId,+}: LinkedinHistoryImportRun): string =>+ `linkedin-history-import-planning:${connectedAccountId}:${runId}`;++export const getLinkedinHistoryImportPlanning = async (+ run: LinkedinHistoryImportRun,+): Promise<LinkedinHistoryImportPlanning> =>+ (await kv.get<LinkedinHistoryImportPlanning>(getPlanningKey(run))) ??+ EMPTY_PLANNING;++export const saveLinkedinHistoryImportPlanning = ({+ planning,+ ...run+}: LinkedinHistoryImportRun & {+ planning: LinkedinHistoryImportPlanning;+}): Promise<void> => kv.set(getPlanningKey(run), planning);++const getChunkChatsKey = ({+ connectedAccountId,+ runId,+ chunkIndex,+}: LinkedinHistoryImportRun & { chunkIndex: number }): string =>+ `linkedin-history-import-chats:${connectedAccountId}:${runId}:${chunkIndex}`;++const getProgressKey = ({+ connectedAccountId,+ runId,+}: LinkedinHistoryImportRun): string =>+ `linkedin-history-import-progress:${connectedAccountId}:${runId}`;++export const getLinkedinHistoryImportChunkChats = (+ chunk: LinkedinHistoryImportRun & { chunkIndex: number },+): Promise<UnipileChat[] | null> =>+ kv.get<UnipileChat[]>(getChunkChatsKey(chunk));++export const saveLinkedinHistoryImportChunkChats = ({+ chats,+ ...chunk+}: LinkedinHistoryImportRun & {+ chunkIndex: number;+ chats: UnipileChat[];+}): Promise<void> => kv.set(getChunkChatsKey(chunk), chats);++export const getLinkedinHistoryImportProgress = async (+ run: LinkedinHistoryImportRun,+): Promise<LinkedinHistoryImportProgress> =>+ (await kv.get<LinkedinHistoryImportProgress>(getProgressKey(run))) ??+ EMPTY_PROGRESS;++export const saveLinkedinHistoryImportProgress = ({+ progress,+ ...run+}: LinkedinHistoryImportRun & {+ progress: LinkedinHistoryImportProgress;+}): Promise<void> => kv.set(getProgressKey(run), progress);++export const deleteLinkedinHistoryImportData = async (+ run: LinkedinHistoryImportRun,+): Promise<void> => {+ const planning = await getLinkedinHistoryImportPlanning(run);+ const chunkCount = planning.chunkCount ?? planning.plannedChunkCount;++ await Promise.all([+ kv.delete(getProgressKey(run)),+ kv.delete(getPlanningKey(run)),+ ...Array.from({ length: chunkCount }, (_, chunkIndex) =>+ kv.delete(getChunkChatsKey({ ...run, chunkIndex })),+ ),+ ]);+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/match-linkedin-participant-person-id.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/match-linkedin-participant-person-id.util.tsnew file mode 100644index 00000000000..b21392dc3e3--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/match-linkedin-participant-person-id.util.ts@@ -0,0 +1,59 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';++import { buildLinkedinProfileHandle } from 'src/logic-functions/utils/build-linkedin-profile-handle.util';+import { findPersonIdsByLinkedinHandle } from 'src/logic-functions/utils/find-person-ids-by-linkedin-handle.util';+import { findUnlinkedPersonIdsByName } from 'src/logic-functions/utils/find-unlinked-person-ids-by-name.util';+import { setUnlinkedPersonLinkedinLink } from 'src/logic-functions/utils/set-person-linkedin-link.util';+import { splitLinkedinUserName } from 'src/logic-functions/utils/split-linkedin-user-name.util';+import { type UnipileUser } from 'src/unipile/types/unipile-user.type';++const findLinkedPersonId = async (+ handle: string,+): Promise<string | undefined> => {+ const linkedPersonIds = await findPersonIdsByLinkedinHandle(handle);++ console.log(+ `[linkedin] ${handle}: ${linkedPersonIds.length} person(s) linked${linkedPersonIds.length > 0 ? ` (${linkedPersonIds.join(', ')})` : ''}`,+ );++ return linkedPersonIds[0];+};++export const matchLinkedinParticipantPersonId = async ({+ user,+ isNameMatchingEnabled,+}: {+ user: UnipileUser;+ isNameMatchingEnabled: boolean;+}): Promise<string | undefined> => {+ const handle = buildLinkedinProfileHandle(user);+ const linkedPersonId = await findLinkedPersonId(handle);++ if (+ isDefined(linkedPersonId) ||+ !isNameMatchingEnabled ||+ !isNonEmptyString(user.public_identifier)+ ) {+ return linkedPersonId;+ }++ const namesakePersonIds = await findUnlinkedPersonIdsByName(+ splitLinkedinUserName(user),+ );++ if (namesakePersonIds.length !== 1) {+ return undefined;+ }++ if (+ await setUnlinkedPersonLinkedinLink({+ personId: namesakePersonIds[0],+ handle,+ })+ ) {+ return namesakePersonIds[0];+ }++ return findLinkedPersonId(handle);+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/parse-linkedin-settings-update.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/parse-linkedin-settings-update.util.tsnew file mode 100644index 00000000000..c8b01eb7259--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/parse-linkedin-settings-update.util.ts@@ -0,0 +1,53 @@+import { isBoolean } from '@sniptt/guards';++import { type LinkedinContactAutoCreationPolicy } from 'src/types/linkedin-contact-auto-creation-policy.type';+import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';+import { type LinkedinSettings } from 'src/types/linkedin-settings.type';+import { type LinkedinVisibility } from 'src/types/linkedin-visibility.type';++const IMPORT_POLICIES: LinkedinImportPolicy[] = ['ALL', 'CONTACTS_ONLY'];++const CONTACT_AUTO_CREATION_POLICIES: LinkedinContactAutoCreationPolicy[] = [+ 'SENT_AND_RECEIVED',+ 'SENT',+ 'NONE',+];++const VISIBILITIES: LinkedinVisibility[] = ['SHARE_EVERYTHING', 'METADATA'];++const isOneOf = <TValue extends string>(+ values: TValue[],+ value: unknown,+): value is TValue => values.some((candidate) => candidate === value);++export const parseLinkedinSettingsUpdate = (+ body: Record<string, unknown> | null | undefined,+): Partial<LinkedinSettings> & { visibility?: LinkedinVisibility } => {+ const update: Partial<LinkedinSettings> & {+ visibility?: LinkedinVisibility;+ } = {};++ if (isOneOf(IMPORT_POLICIES, body?.importPolicy)) {+ update.importPolicy = body.importPolicy;+ }++ if (+ isOneOf(CONTACT_AUTO_CREATION_POLICIES, body?.contactAutoCreationPolicy)+ ) {+ update.contactAutoCreationPolicy = body.contactAutoCreationPolicy;+ }++ if (isBoolean(body?.areGroupChatsImported)) {+ update.areGroupChatsImported = body.areGroupChatsImported;+ }++ if (isBoolean(body?.isNameMatchingEnabled)) {+ update.isNameMatchingEnabled = body.isNameMatchingEnabled;+ }++ if (isOneOf(VISIBILITIES, body?.visibility)) {+ update.visibility = body.visibility;+ }++ return update;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/refresh-linkedin-history-import-state.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/refresh-linkedin-history-import-state.util.tsnew file mode 100644index 00000000000..a415ae20bbc--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/refresh-linkedin-history-import-state.util.ts@@ -0,0 +1,226 @@+import { getJobs, type JobStatusResult } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { type LinkedinHistoryImportPlanning } from 'src/logic-functions/types/linkedin-history-import-planning.type';+import { type LinkedinHistoryImportProgress } from 'src/logic-functions/types/linkedin-history-import-progress.type';+import { enqueueLinkedinImportHistoryJob } from 'src/logic-functions/utils/enqueue-linkedin-import-history-job.util';+import {+ getLinkedinImportHistoryJobId,+ getLinkedinPlanHistoryImportJobId,+} from 'src/logic-functions/utils/get-linkedin-history-import-job-id.util';+import { getLinkedinHistoryImportState } from 'src/logic-functions/utils/get-linkedin-history-import-state.util';+import {+ deleteLinkedinHistoryImportData,+ getLinkedinHistoryImportPlanning,+ getLinkedinHistoryImportProgress,+ saveLinkedinHistoryImportProgress,+} from 'src/logic-functions/utils/linkedin-history-import-kv.util';+import { saveLinkedinHistoryImportState } from 'src/logic-functions/utils/save-linkedin-history-import-state.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++const LINKEDIN_HISTORY_IMPORT_MAX_RECOVERIES = 3;++const STALLED_ERROR = {+ code: 'STALLED' as const,+ message: 'The import stopped making progress.',+};++export const finishLinkedinHistoryImport = async ({+ connectedAccountId,+ state,+}: {+ connectedAccountId: string;+ state: LinkedinHistoryImportState;+}): Promise<LinkedinHistoryImportState> => {+ await saveLinkedinHistoryImportState({ connectedAccountId, state });+ await deleteLinkedinHistoryImportData({+ connectedAccountId,+ runId: state.runId,+ });++ return state;+};++const getJobStatus = async (+ jobId: string,+): Promise<JobStatusResult | undefined> =>+ (await getJobs([jobId])).find((status) => status.jobId === jobId);++const getPlanningError = async (+ planning: LinkedinHistoryImportPlanning,+ runId: string,+): Promise<LinkedinHistoryImportState['error']> => {+ if (isDefined(planning.error)) {+ return planning.error;+ }++ if (isDefined(planning.chunkCount)) {+ return undefined;+ }++ const planJob = await getJobStatus(+ planning.planJobId ?? getLinkedinPlanHistoryImportJobId({ runId }),+ );++ if (!isDefined(planJob)) {+ return STALLED_ERROR;+ }++ return planJob.state === 'FAILED'+ ? { code: 'UNKNOWN', message: planJob.failedReason ?? '' }+ : undefined;+};++const getCurrentChunkError = async ({+ connectedAccountId,+ runId,+ planning,+ progress,+}: {+ connectedAccountId: string;+ runId: string;+ planning: LinkedinHistoryImportPlanning;+ progress: LinkedinHistoryImportProgress;+}): Promise<LinkedinHistoryImportState['error']> => {+ if (isDefined(progress.error)) {+ return progress.error;+ }++ const chunkIndex = progress.completedChunkCount;++ if (planning.plannedChunkCount <= chunkIndex) {+ return undefined;+ }++ const currentJobId =+ progress.currentJobId ??+ getLinkedinImportHistoryJobId({ runId, chunkIndex });+ const currentJob = await getJobStatus(currentJobId);++ if (currentJob?.state === 'FAILED') {+ return { code: 'UNKNOWN', message: currentJob.failedReason ?? '' };+ }++ const hasEndedWithoutFinishing =+ currentJob?.state === 'COMPLETED' ||+ (!isDefined(currentJob) && isDefined(progress.currentJobId));++ if (!isDefined(currentJob) && !isDefined(progress.currentJobId)) {+ await enqueueLinkedinImportHistoryJob({+ connectedAccountId,+ runId,+ chunkIndex,+ });++ return undefined;+ }++ if (!hasEndedWithoutFinishing) {+ return undefined;+ }++ const recoveryCount = (progress.recoveryCount ?? 0) + 1;++ if (recoveryCount > LINKEDIN_HISTORY_IMPORT_MAX_RECOVERIES) {+ return STALLED_ERROR;+ }++ const resumePayload = {+ connectedAccountId,+ runId,+ chunkIndex,+ resumeIndex: (progress.currentResumeIndex ?? 0) + 1,+ };++ await saveLinkedinHistoryImportProgress({+ connectedAccountId,+ runId,+ progress: {+ ...progress,+ currentJobId: getLinkedinImportHistoryJobId(resumePayload),+ currentResumeIndex: resumePayload.resumeIndex,+ recoveryCount,+ },+ });+ await enqueueLinkedinImportHistoryJob(resumePayload);++ return undefined;+};++export const refreshLinkedinHistoryImportState = async (+ connectedAccountId: string,+): Promise<LinkedinHistoryImportState | null> => {+ const state = await getLinkedinHistoryImportState(connectedAccountId);++ if (!isDefined(state) || state.status !== 'IMPORTING') {+ return state;+ }++ const run = { connectedAccountId, runId: state.runId };+ const [planning, progress] = await Promise.all([+ getLinkedinHistoryImportPlanning(run),+ getLinkedinHistoryImportProgress(run),+ ]);+ const resumeAt = progress.resumeAt ?? planning.resumeAt;+ const currentState: LinkedinHistoryImportState = {+ ...state,+ importedConversationCount:+ progress.importedConversationCount ++ (progress.currentChunkImportedCount ?? 0),+ processedConversationCount:+ progress.completedConversationCount + progress.currentChunkProcessedCount,+ plannedChunkCount: planning.plannedChunkCount,+ plannedConversationCount: planning.plannedConversationCount,+ totalConversationCount: planning.reportedConversationCount,+ chunkCount: planning.chunkCount,+ resumeAt:+ isDefined(resumeAt) && Date.parse(resumeAt) > Date.now()+ ? resumeAt+ : undefined,+ };++ if (+ isDefined(planning.chunkCount) &&+ progress.completedChunkCount >= planning.chunkCount+ ) {+ return finishLinkedinHistoryImport({+ connectedAccountId,+ state: {+ ...currentState,+ status: 'COMPLETED',+ finishedAt: new Date().toISOString(),+ },+ });+ }++ const error =+ (await getPlanningError(planning, state.runId)) ??+ (await getCurrentChunkError({+ ...run,+ planning,+ progress,+ }));++ if (!isDefined(error)) {+ return currentState;+ }++ const latestState = await getLinkedinHistoryImportState(connectedAccountId);++ if (+ latestState?.runId !== state.runId ||+ latestState.status !== 'IMPORTING'+ ) {+ return latestState;+ }++ return finishLinkedinHistoryImport({+ connectedAccountId,+ state: {+ ...currentState,+ status: 'FAILED',+ finishedAt: new Date().toISOString(),+ error,+ },+ });+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/remove-linkedin-connection-resources.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/remove-linkedin-connection-resources.util.tsindex 6638dda2668..7f64697c4d2 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/remove-linkedin-connection-resources.util.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/remove-linkedin-connection-resources.util.ts@@ -5,6 +5,11 @@ import {listMessageChannels,} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { getLinkedinHistoryImportState } from 'src/logic-functions/utils/get-linkedin-history-import-state.util';+import { deleteLinkedinHistoryImportData } from 'src/logic-functions/utils/linkedin-history-import-kv.util';+import { getLinkedinConnectionKvKey } from 'src/logic-functions/utils/get-linkedin-connection-kv-key.util';import { deleteUnipileAccountOrThrow } from 'src/unipile/utils/delete-unipile-account-or-throw.util';import { getUnipileAccountClaimKey } from 'src/unipile/utils/get-unipile-account-claim-key.util';@@ -21,6 +26,21 @@ export const removeLinkedinConnectionResources = async ({channels.map((channel) => deleteMessageChannel(channel.id)),);+ const historyImport = await getLinkedinHistoryImportState(connectedAccountId);++ if (isDefined(historyImport)) {+ await deleteLinkedinHistoryImportData({+ connectedAccountId,+ runId: historyImport.runId,+ });+ }++ await Promise.all(+ (['settings', 'history-import'] as const).map((kind) =>+ kv.delete(getLinkedinConnectionKvKey({ kind, connectedAccountId })),+ ),+ );+if (isNonEmptyString(unipileAccountId)) {await deleteUnipileAccountOrThrow(unipileAccountId);await kv.delete(getUnipileAccountClaimKey(unipileAccountId), {diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/save-linkedin-history-import-state.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/save-linkedin-history-import-state.util.tsnew file mode 100644index 00000000000..34665159386--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/save-linkedin-history-import-state.util.ts@@ -0,0 +1,16 @@+import { kv } from 'twenty-sdk/logic-function';++import { getLinkedinConnectionKvKey } from 'src/logic-functions/utils/get-linkedin-connection-kv-key.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';++export const saveLinkedinHistoryImportState = ({+ connectedAccountId,+ state,+}: {+ connectedAccountId: string;+ state: LinkedinHistoryImportState;+}): Promise<void> =>+ kv.set(+ getLinkedinConnectionKvKey({ kind: 'history-import', connectedAccountId }),+ state,+ );diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/set-person-linkedin-link.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/set-person-linkedin-link.util.tsnew file mode 100644index 00000000000..682e960ffc7--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/set-person-linkedin-link.util.ts@@ -0,0 +1,25 @@+import { CoreApiClient } from 'twenty-client-sdk/core';++import { UNLINKED_PERSON_FILTER } from 'src/logic-functions/utils/unlinked-person-filter.constant';++export const setUnlinkedPersonLinkedinLink = async ({+ personId,+ handle,+}: {+ personId: string;+ handle: string;+}): Promise<boolean> => {+ const { updatePeople } = await new CoreApiClient({+ runAs: 'application',+ }).mutation({+ updatePeople: {+ __args: {+ filter: { and: [{ id: { eq: personId } }, UNLINKED_PERSON_FILTER] },+ data: { linkedinLink: { primaryLinkUrl: handle } },+ },+ id: true,+ },+ });++ return (updatePeople ?? []).length > 0;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/split-linkedin-user-name.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/split-linkedin-user-name.util.tsnew file mode 100644index 00000000000..28483088b21--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/split-linkedin-user-name.util.ts@@ -0,0 +1,20 @@+import { isNonEmptyString } from '@sniptt/guards';++import { type UnipileUser } from 'src/unipile/types/unipile-user.type';++export const splitLinkedinUserName = (+ user: Pick<UnipileUser, 'display_name' | 'first_name' | 'last_name'>,+): { firstName: string; lastName: string } => {+ if (isNonEmptyString(user.first_name) || isNonEmptyString(user.last_name)) {+ return {+ firstName: user.first_name?.trim() ?? '',+ lastName: user.last_name?.trim() ?? '',+ };+ }++ const [firstName = '', ...lastNameParts] = (user.display_name ?? '')+ .trim()+ .split(/\s+/);++ return { firstName, lastName: lastNameParts.join(' ') };+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/start-linkedin-history-import.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/start-linkedin-history-import.util.tsnew file mode 100644index 00000000000..aa4c4dc6f73--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/start-linkedin-history-import.util.ts@@ -0,0 +1,41 @@+import { enqueueJobs } from 'twenty-sdk/logic-function';++import { LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { getLinkedinPlanHistoryImportJobId } from 'src/logic-functions/utils/get-linkedin-history-import-job-id.util';+import { saveLinkedinHistoryImportState } from 'src/logic-functions/utils/save-linkedin-history-import-state.util';+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';+import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';++const LINKEDIN_PLAN_HISTORY_IMPORT_RETRY_LIMIT = 3;++export const startLinkedinHistoryImport = async ({+ connectedAccountId,+ importPolicy,+}: {+ connectedAccountId: string;+ importPolicy: LinkedinImportPolicy;+}): Promise<LinkedinHistoryImportState> => {+ const state: LinkedinHistoryImportState = {+ runId: crypto.randomUUID(),+ importPolicy,+ status: 'IMPORTING',+ importedConversationCount: 0,+ processedConversationCount: 0,+ startedAt: new Date().toISOString(),+ };++ await saveLinkedinHistoryImportState({ connectedAccountId, state });+ await enqueueJobs({+ logicFunctionUniversalIdentifier:+ LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER,+ jobs: [+ {+ jobId: getLinkedinPlanHistoryImportJobId({ runId: state.runId }),+ payload: { connectedAccountId, runId: state.runId },+ },+ ],+ retryLimit: LINKEDIN_PLAN_HISTORY_IMPORT_RETRY_LIMIT,+ });++ return state;+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/unlinked-person-filter.constant.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/unlinked-person-filter.constant.tsnew file mode 100644index 00000000000..517900fe325--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/unlinked-person-filter.constant.ts@@ -0,0 +1,6 @@+export const UNLINKED_PERSON_FILTER = {+ or: [+ { linkedinLink: { primaryLinkUrl: { is: 'NULL' as const } } },+ { linkedinLink: { primaryLinkUrl: { eq: '' } } },+ ],+};diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/with-linkedin-public-identifier.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/with-linkedin-public-identifier.util.tsindex ce594092ce5..3587ffc4623 100644--- a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/with-linkedin-public-identifier.util.ts+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/with-linkedin-public-identifier.util.ts@@ -1,9 +1,18 @@import { isNonEmptyString } from '@sniptt/guards';import { kv } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';import { getLinkedinPublicIdentifierKey } from 'src/logic-functions/utils/get-linkedin-public-identifier-key.util';import { type UnipileUser } from 'src/unipile/types/unipile-user.type';import { getUnipileUser } from 'src/unipile/utils/get-unipile-user.util';+import { UnipileRequestError } from 'src/unipile/utils/request-unipile.util';++const isPermanentUnipileError = (error: unknown): boolean =>+ error instanceof UnipileRequestError &&+ isDefined(error.status) &&+ error.status >= 400 &&+ error.status < 500 &&+ error.status !== 429;export const withLinkedinPublicIdentifier = async ({unipileAccountId,@@ -37,6 +46,10 @@ export const withLinkedinPublicIdentifier = async ({return { ...user, public_identifier: publicIdentifier };} catch (error) {+ if (!isPermanentUnipileError(error)) {+ throw error;+ }+console.warn(`[linkedin] could not resolve the public identifier of ${user.id}: ${error instanceof Error ? error.message : String(error)}`,);diff --git a/packages/twenty-apps/public/linkedin/src/roles/default-function.role.ts b/packages/twenty-apps/public/linkedin/src/roles/default-function.role.tsindex 638e3a68f88..1db85898d31 100644--- a/packages/twenty-apps/public/linkedin/src/roles/default-function.role.ts+++ b/packages/twenty-apps/public/linkedin/src/roles/default-function.role.ts@@ -1,11 +1,15 @@-import { defineApplicationRole } from 'twenty-sdk/define';+import {+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,+ defineApplicationRole,+} from 'twenty-sdk/define';import { DEFAULT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';export default defineApplicationRole({universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,label: 'LinkedIn function role',- description: 'No-op role for LinkedIn logic functions',+ description:+ 'Matches LinkedIn participants to People by profile link or name, creates People for new contacts and reads company names to tell namesakes apart.',canReadAllObjectRecords: false,canUpdateAllObjectRecords: false,canSoftDeleteAllObjectRecords: false,@@ -14,7 +18,24 @@ export default defineApplicationRole({canBeAssignedToAgents: false,canBeAssignedToUsers: false,canBeAssignedToApiKeys: false,- objectPermissions: [],+ objectPermissions: [+ {+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,+ canReadObjectRecords: true,+ canUpdateObjectRecords: true,+ canSoftDeleteObjectRecords: false,+ canDestroyObjectRecords: false,+ },+ {+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,+ canReadObjectRecords: true,+ canUpdateObjectRecords: false,+ canSoftDeleteObjectRecords: false,+ canDestroyObjectRecords: false,+ },+ ],fieldPermissions: [],permissionFlagUniversalIdentifiers: [],});diff --git a/packages/twenty-apps/public/linkedin/src/settings-menu-items/linkedin-sync-settings.ts b/packages/twenty-apps/public/linkedin/src/settings-menu-items/linkedin-sync-settings.tsnew file mode 100644index 00000000000..268da5e33be--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/settings-menu-items/linkedin-sync-settings.ts@@ -0,0 +1,15 @@+import { defineSettingsMenuItem } from 'twenty-sdk/define';++import {+ LINKEDIN_SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ LINKEDIN_SETTINGS_MENU_ITEM_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++export default defineSettingsMenuItem({+ universalIdentifier: LINKEDIN_SETTINGS_MENU_ITEM_UNIVERSAL_IDENTIFIER,+ frontComponentUniversalIdentifier:+ LINKEDIN_SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ title: 'Sync',+ icon: 'IconRefresh',+ scope: 'USER',+});diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-contact-auto-creation-policy.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-contact-auto-creation-policy.type.tsnew file mode 100644index 00000000000..abe265ada97--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-contact-auto-creation-policy.type.ts@@ -0,0 +1,2 @@+export type LinkedinContactAutoCreationPolicy =+ 'SENT_AND_RECEIVED' | 'SENT' | 'NONE';diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-history-import-error-code.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-history-import-error-code.type.tsnew file mode 100644index 00000000000..88480108640--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-history-import-error-code.type.ts@@ -0,0 +1,2 @@+export type LinkedinHistoryImportErrorCode =+ 'AUTH_FAILED' | 'UNREACHABLE' | 'STALLED' | 'UNKNOWN';diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-history-import-state.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-history-import-state.type.tsnew file mode 100644index 00000000000..45943be453e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-history-import-state.type.ts@@ -0,0 +1,18 @@+import { type LinkedinHistoryImportErrorCode } from 'src/types/linkedin-history-import-error-code.type';+import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';++export type LinkedinHistoryImportState = {+ runId: string;+ importPolicy: LinkedinImportPolicy;+ status: 'IMPORTING' | 'COMPLETED' | 'FAILED' | 'CANCELLED';+ importedConversationCount: number;+ processedConversationCount: number;+ totalConversationCount?: number;+ chunkCount?: number;+ plannedChunkCount?: number;+ plannedConversationCount?: number;+ startedAt: string;+ resumeAt?: string;+ finishedAt?: string;+ error?: { code: LinkedinHistoryImportErrorCode; message: string };+};diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-import-policy.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-import-policy.type.tsnew file mode 100644index 00000000000..7051feefa66--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-import-policy.type.ts@@ -0,0 +1 @@+export type LinkedinImportPolicy = 'ALL' | 'CONTACTS_ONLY';diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-person-record.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-person-record.type.tsnew file mode 100644index 00000000000..9caa959148a--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-person-record.type.ts@@ -0,0 +1,6 @@+export type LinkedinPersonRecord = {+ id: string;+ name?: { firstName?: string | null; lastName?: string | null } | null;+ linkedinLink?: { primaryLinkUrl?: string | null } | null;+ company?: { name?: string | null } | null;+};diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-settings-view.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-settings-view.type.tsnew file mode 100644index 00000000000..6751c830303--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-settings-view.type.ts@@ -0,0 +1,12 @@+import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';+import { type LinkedinSettings } from 'src/types/linkedin-settings.type';+import { type LinkedinVisibility } from 'src/types/linkedin-visibility.type';++export type LinkedinSettingsView =+ | { isConnected: false }+ | {+ isConnected: true;+ connection: { name: string; handle: string; isAuthFailed: boolean };+ settings: LinkedinSettings & { visibility: LinkedinVisibility };+ historyImport: LinkedinHistoryImportState | null;+ };diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-settings.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-settings.type.tsnew file mode 100644index 00000000000..b3f193aea9e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-settings.type.ts@@ -0,0 +1,9 @@+import { type LinkedinContactAutoCreationPolicy } from 'src/types/linkedin-contact-auto-creation-policy.type';+import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';++export type LinkedinSettings = {+ importPolicy: LinkedinImportPolicy;+ areGroupChatsImported: boolean;+ contactAutoCreationPolicy: LinkedinContactAutoCreationPolicy;+ isNameMatchingEnabled: boolean;+};diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-visibility.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-visibility.type.tsnew file mode 100644index 00000000000..2ae97082d72--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-visibility.type.ts@@ -0,0 +1 @@+export type LinkedinVisibility = 'SHARE_EVERYTHING' | 'METADATA';diff --git a/packages/twenty-apps/public/linkedin/src/unipile/types/unipile-chat.type.ts b/packages/twenty-apps/public/linkedin/src/unipile/types/unipile-chat.type.tsindex 716217f6fbd..45c9ea76ee2 100644--- a/packages/twenty-apps/public/linkedin/src/unipile/types/unipile-chat.type.ts+++ b/packages/twenty-apps/public/linkedin/src/unipile/types/unipile-chat.type.ts@@ -6,6 +6,7 @@ export type UnipileChat = {name: string;is_group: boolean;is_1to1: boolean;+ last_message_timestamp?: string;user_id?: string;user?: UnipileUser;participants?: UnipileChatParticipant[];diff --git a/packages/twenty-apps/public/linkedin/src/unipile/types/unipile-page.type.ts b/packages/twenty-apps/public/linkedin/src/unipile/types/unipile-page.type.tsnew file mode 100644index 00000000000..ff2a265c9e2--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/types/unipile-page.type.ts@@ -0,0 +1,5 @@+export type UnipilePage<TItem> = {+ items: TItem[];+ nextCursor: string | undefined;+ totalCount?: number;+};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/__tests__/request-unipile.util.test.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/__tests__/request-unipile.util.test.tsnew file mode 100644index 00000000000..e4498d33fc3--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/__tests__/request-unipile.util.test.ts@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ wait: vi.fn() }));++vi.mock('src/utils/wait.util', () => ({ wait: mocks.wait }));++const { UnipileRequestError, requestUnipile } =+ await import('src/unipile/utils/request-unipile.util');++const RATE_LIMITED_ERROR = {+ status: 429,+ title: 'We only allow 10 requests. Retry in 37 seconds.',+};++describe('requestUnipile', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('waits as long as Unipile asks when rate limited, then retries', async () => {+ const request = vi+ .fn()+ .mockRejectedValueOnce(RATE_LIMITED_ERROR)+ .mockResolvedValueOnce('chats');++ await expect(requestUnipile('list inbox chats', request)).resolves.toBe(+ 'chats',+ );+ expect(mocks.wait).toHaveBeenCalledExactlyOnceWith(38_000);+ });++ it('hands a long rate limit back to the caller with its wait', async () => {+ const request = vi.fn().mockRejectedValue({+ status: 429,+ title: 'We only allow 100 requests. Retry in 22 hours.',+ });++ await expect(+ requestUnipile('list chat messages', request),+ ).rejects.toMatchObject({+ name: 'UnipileRateLimitError',+ retryAfterSeconds: 22 * 60 * 60 + 1,+ });+ expect(mocks.wait).not.toHaveBeenCalled();+ });++ it('gives up after 5 waits', async () => {+ const request = vi.fn().mockRejectedValue(RATE_LIMITED_ERROR);++ await expect(requestUnipile('list inbox chats', request)).rejects.toThrow(+ 'Unipile list inbox chats failed (429): We only allow 10 requests. Retry in 37 seconds.',+ );+ expect(mocks.wait).toHaveBeenCalledTimes(5);+ expect(request).toHaveBeenCalledTimes(6);+ });++ it('turns the Unipile JSON error body into an error naming the request', async () => {+ const promise = requestUnipile('list inbox chats', () =>+ Promise.reject({+ status: 400,+ title: 'Invalid querystring',+ detail: 'limit must be <= 50',+ }),+ );++ await expect(promise).rejects.toThrow(+ 'Unipile list inbox chats failed (400): Invalid querystring: limit must be <= 50',+ );+ await expect(promise).rejects.toBeInstanceOf(UnipileRequestError);+ await expect(promise).rejects.toMatchObject({ status: 400 });+ });++ it('rethrows network errors unchanged', async () => {+ const networkError = new TypeError('fetch failed');++ await expect(+ requestUnipile('list inboxes', () => Promise.reject(networkError)),+ ).rejects.toBe(networkError);+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-chat.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-chat.util.tsindex 8735e4e1611..97f359c7bb4 100644--- a/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-chat.util.ts+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-chat.util.ts@@ -1,6 +1,7 @@import { UnipileMessaging } from '@unipile/sdk';import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';+import { requestUnipile } from 'src/unipile/utils/request-unipile.util';import { getUnipileRequestOptions } from 'src/unipile/utils/get-unipile-request-options.util';export const getUnipileChat = async ({@@ -10,10 +11,12 @@ export const getUnipileChat = async ({accountId: string;chatId: string;}): Promise<UnipileChat> => {- const { data } = await new UnipileMessaging().getChat({- ...getUnipileRequestOptions(),- path: { account_id: accountId, chat_id: chatId },- });+ const { data } = await requestUnipile('get chat', () =>+ new UnipileMessaging().getChat({+ ...getUnipileRequestOptions(),+ path: { account_id: accountId, chat_id: chatId },+ }),+ );return data;};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-user.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-user.util.tsindex 09a4249129f..c463612d808 100644--- a/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-user.util.ts+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/get-unipile-user.util.ts@@ -1,6 +1,7 @@import { UnipileUsers } from '@unipile/sdk';import { type UnipileUser } from 'src/unipile/types/unipile-user.type';+import { requestUnipile } from 'src/unipile/utils/request-unipile.util';import { getUnipileRequestOptions } from 'src/unipile/utils/get-unipile-request-options.util';export const getUnipileUser = async ({@@ -10,10 +11,12 @@ export const getUnipileUser = async ({accountId: string;userId: string;}): Promise<UnipileUser> => {- const { data } = await new UnipileUsers().getUserProfile({- ...getUnipileRequestOptions(),- path: { account_id: accountId, user_id: userId },- });+ const { data } = await requestUnipile('get user profile', () =>+ new UnipileUsers().getUserProfile({+ ...getUnipileRequestOptions(),+ path: { account_id: accountId, user_id: userId },+ }),+ );return data;};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-chat-messages-page.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-chat-messages-page.util.tsnew file mode 100644index 00000000000..712c54c1ff2--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-chat-messages-page.util.ts@@ -0,0 +1,28 @@+import { UnipileMessaging } from '@unipile/sdk';++import { type UnipileMessage } from 'src/unipile/types/unipile-message.type';+import { type UnipilePage } from 'src/unipile/types/unipile-page.type';+import { getUnipileRequestOptions } from 'src/unipile/utils/get-unipile-request-options.util';+import { requestUnipile } from 'src/unipile/utils/request-unipile.util';++const UNIPILE_MESSAGES_PAGE_SIZE = 20;++export const listUnipileChatMessagesPage = async ({+ accountId,+ chatId,+ cursor,+}: {+ accountId: string;+ chatId: string;+ cursor?: string;+}): Promise<UnipilePage<UnipileMessage>> => {+ const { data } = await requestUnipile('list chat messages', () =>+ new UnipileMessaging().getMessagesList({+ ...getUnipileRequestOptions(),+ path: { account_id: accountId, chat_id: chatId },+ query: { cursor, limit: UNIPILE_MESSAGES_PAGE_SIZE },+ }),+ );++ return { items: data.data, nextCursor: data.next_cursor };+};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-chats.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-chats.util.tsnew file mode 100644index 00000000000..c9fb017b325--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-chats.util.ts@@ -0,0 +1,32 @@+import { UnipileMessaging } from '@unipile/sdk';++import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';+import { type UnipilePage } from 'src/unipile/types/unipile-page.type';+import { requestUnipile } from 'src/unipile/utils/request-unipile.util';+import { getUnipileRequestOptions } from 'src/unipile/utils/get-unipile-request-options.util';++export const listUnipileChats = async ({+ accountId,+ inboxId,+ cursor,+ limit,+}: {+ accountId: string;+ inboxId: string;+ cursor?: string;+ limit: number;+}): Promise<UnipilePage<UnipileChat>> => {+ const { data } = await requestUnipile('list inbox chats', () =>+ new UnipileMessaging().getInboxChatsList({+ ...getUnipileRequestOptions(),+ path: { account_id: accountId, inbox_id: inboxId },+ query: { cursor, limit },+ }),+ );++ return {+ items: data.data,+ nextCursor: data.next_cursor,+ totalCount: data.total_count,+ };+};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-inbox-ids.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-inbox-ids.util.tsnew file mode 100644index 00000000000..75eec8aea90--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-unipile-inbox-ids.util.ts@@ -0,0 +1,17 @@+import { UnipileMessaging } from '@unipile/sdk';++import { requestUnipile } from 'src/unipile/utils/request-unipile.util';+import { getUnipileRequestOptions } from 'src/unipile/utils/get-unipile-request-options.util';++export const listUnipileInboxIds = async (+ accountId: string,+): Promise<string[]> => {+ const { data } = await requestUnipile('list inboxes', () =>+ new UnipileMessaging().getInboxesList({+ ...getUnipileRequestOptions(),+ path: { account_id: accountId },+ }),+ );++ return data.data.filter((inbox) => !inbox.disabled).map((inbox) => inbox.id);+};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/request-unipile.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/request-unipile.util.tsnew file mode 100644index 00000000000..4a1ac368c5e--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/request-unipile.util.ts@@ -0,0 +1,101 @@+import { isNumber, isObject, isString } from '@sniptt/guards';++import { wait } from 'src/utils/wait.util';++const UNIPILE_RATE_LIMITED_STATUS = 429;++const UNIPILE_RATE_LIMIT_MAX_WAITS = 5;++const UNIPILE_RATE_LIMIT_DEFAULT_WAIT_SECONDS = 60;++const UNIPILE_RATE_LIMIT_MAX_WAIT_SECONDS = 120;++export class UnipileRequestError extends Error {+ readonly status: number | undefined;++ constructor(message: string, status: number | undefined) {+ super(message);+ this.name = 'UnipileRequestError';+ this.status = status;+ }+}++const toUnipileRequestError = (+ requestName: string,+ error: object,+): UnipileRequestError => {+ const { status, title, detail } = error as {+ status?: unknown;+ title?: unknown;+ detail?: unknown;+ };+ const reason = [title, detail].filter(isString).join(': ');++ return new UnipileRequestError(+ `Unipile ${requestName} failed${isNumber(status) ? ` (${status})` : ''}: ${reason || JSON.stringify(error)}`,+ isNumber(status) ? status : undefined,+ );+};++export class UnipileRateLimitError extends UnipileRequestError {+ readonly retryAfterSeconds: number;++ constructor(message: string, retryAfterSeconds: number) {+ super(message, UNIPILE_RATE_LIMITED_STATUS);+ this.name = 'UnipileRateLimitError';+ this.retryAfterSeconds = retryAfterSeconds;+ }+}++const SECONDS_BY_UNIT: Record<string, number> = {+ second: 1,+ minute: 60,+ hour: 60 * 60,+ day: 24 * 60 * 60,+};++const getRateLimitWaitSeconds = (error: UnipileRequestError): number => {+ const [, amount, unit] =+ /retry in (\d+) (second|minute|hour|day)s?/i.exec(error.message) ?? [];+ const retryAfterSeconds =+ Number(amount) * (SECONDS_BY_UNIT[unit?.toLowerCase() ?? ''] ?? NaN);++ return Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0+ ? retryAfterSeconds + 1+ : UNIPILE_RATE_LIMIT_DEFAULT_WAIT_SECONDS;+};++export const requestUnipile = async <TResult>(+ requestName: string,+ request: () => Promise<TResult>,+): Promise<TResult> => {+ for (let waitCount = 0; ; waitCount++) {+ try {+ return await request();+ } catch (error) {+ if (error instanceof Error || !isObject(error)) {+ throw error;+ }++ const requestError = toUnipileRequestError(requestName, error);+ const waitSeconds = getRateLimitWaitSeconds(requestError);++ if (requestError.status !== UNIPILE_RATE_LIMITED_STATUS) {+ throw requestError;+ }++ if (+ waitCount >= UNIPILE_RATE_LIMIT_MAX_WAITS ||+ waitSeconds > UNIPILE_RATE_LIMIT_MAX_WAIT_SECONDS+ ) {+ throw new UnipileRateLimitError(requestError.message, waitSeconds);+ }++ console.log(+ `[linkedin] Unipile ${requestName} rate limited, retrying in ${waitSeconds}s`,+ );++ await wait(waitSeconds * 1000);+ }+ }+};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/sort-unipile-chats-by-last-message.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/sort-unipile-chats-by-last-message.util.tsnew file mode 100644index 00000000000..d298f2299fb--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/sort-unipile-chats-by-last-message.util.ts@@ -0,0 +1,10 @@+import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';++export const sortUnipileChatsByLastMessage = (+ chats: UnipileChat[],+): UnipileChat[] =>+ [...chats].sort((chat, otherChat) =>+ (otherChat.last_message_timestamp ?? '').localeCompare(+ chat.last_message_timestamp ?? '',+ ),+ );diff --git a/packages/twenty-apps/public/linkedin/src/utils/wait.util.ts b/packages/twenty-apps/public/linkedin/src/utils/wait.util.tsnew file mode 100644index 00000000000..7d40d0ae071--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/utils/wait.util.ts@@ -0,0 +1,2 @@+export const wait = (milliseconds: number): Promise<void> =>+ new Promise((resolve) => setTimeout(resolve, milliseconds));diff --git a/packages/twenty-apps/public/linkedin/tsconfig.json b/packages/twenty-apps/public/linkedin/tsconfig.jsonindex 58d1334ffb2..bef7f68fbde 100644--- a/packages/twenty-apps/public/linkedin/tsconfig.json+++ b/packages/twenty-apps/public/linkedin/tsconfig.json@@ -22,6 +22,7 @@"skipLibCheck": true,"skipDefaultLibCheck": true,"resolveJsonModule": true,+ "noUncheckedSideEffectImports": false,"paths": {"src/*": ["./src/*"],"~/*": ["./*"]diff --git a/packages/twenty-apps/public/linkedin/yarn.lock b/packages/twenty-apps/public/linkedin/yarn.lockindex cc1509ad3c1..8370af9af05 100644--- a/packages/twenty-apps/public/linkedin/yarn.lock+++ b/packages/twenty-apps/public/linkedin/yarn.lock@@ -5,6 +5,313 @@ __metadata:version: 10cacheKey: 10c0+"@babel/code-frame@npm:^7.0.0, @babel/code-frame@npm:^7.29.7":+ version: 7.29.7+ resolution: "@babel/code-frame@npm:7.29.7"+ dependencies:+ "@babel/helper-validator-identifier": "npm:^7.29.7"+ js-tokens: "npm:^4.0.0"+ picocolors: "npm:^1.1.1"+ checksum: 10c0/169fc2080169a40c1760155eaaaf739bcb882df0bec76a83adbda5493645bc17270a3434b8848c494b1933e96fe1d147370001e3cda09a39f43ae30f08ef2069+ languageName: node+ linkType: hard++"@babel/generator@npm:^7.29.8":+ version: 7.29.8+ resolution: "@babel/generator@npm:7.29.8"+ dependencies:+ "@babel/parser": "npm:^7.29.8"+ "@babel/types": "npm:^7.29.8"+ "@jridgewell/gen-mapping": "npm:^0.3.12"+ "@jridgewell/trace-mapping": "npm:^0.3.28"+ jsesc: "npm:^3.0.2"+ checksum: 10c0/7b896696314a659652393b76d78276e236acd0f7fae40a9a1af7f01c76aeafc630dd0966aad6f9386d35d7c674a8e6e2d8e217c44d25fb11460e68afa9ba8441+ languageName: node+ linkType: hard++"@babel/helper-globals@npm:^7.29.7":+ version: 7.29.7+ resolution: "@babel/helper-globals@npm:7.29.7"+ checksum: 10c0/f38417c40b1129a1b2b519ca961b9040c8827d1444fd74068702286b91b77089431dc76b6b9d5c1496e5da2a4f3ad329c6946e688ba3fa0d1d0b3d2b4f34f36a+ languageName: node+ linkType: hard++"@babel/helper-module-imports@npm:^7.16.7":+ version: 7.29.7+ resolution: "@babel/helper-module-imports@npm:7.29.7"+ dependencies:+ "@babel/traverse": "npm:^7.29.7"+ "@babel/types": "npm:^7.29.7"+ checksum: 10c0/6adf60d97356027413342a092f818d9678c4f5caff716a33e3284b5ae14e47a9e88059d421dde4ee4894691260039a12602c0e7becadc175602194b40dfa345d+ languageName: node+ linkType: hard++"@babel/helper-string-parser@npm:^7.29.11":+ version: 7.29.11+ resolution: "@babel/helper-string-parser@npm:7.29.11"+ checksum: 10c0/673a309056c593af89296464ff149d0478889e3f5a577add33f1d4d38c54e44d0381cf232f744965ee71534489ebaa4d5c45ba5f87e1d2ce9bf54a67d2d0d72d+ languageName: node+ linkType: hard++"@babel/helper-validator-identifier@npm:^7.29.7":+ version: 7.29.7+ resolution: "@babel/helper-validator-identifier@npm:7.29.7"+ checksum: 10c0/4795354e7ae0dcafa72de1cd04ec51252dc1498517170beaf019e03effc5b7bf13c6b21a3949a77e07b8125be7f106ed1131350d8ebd4566ae874094a726d62b+ languageName: node+ linkType: hard++"@babel/parser@npm:^7.29.7, @babel/parser@npm:^7.29.8, @babel/parser@npm:^7.29.9":+ version: 7.29.11+ resolution: "@babel/parser@npm:7.29.11"+ dependencies:+ "@babel/types": "npm:^7.29.11"+ bin:+ parser: ./bin/babel-parser.js+ checksum: 10c0/4bf9d2e8520627c20bfefe34a0117348bf62a002fb1fdbeeee82a08ee02ff71767e079ac4e728a76da2e0db48cabf50121b3bdac0831ed4a9a6d8aa12765846d+ languageName: node+ linkType: hard++"@babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.18.3":+ version: 7.29.10+ resolution: "@babel/runtime@npm:7.29.10"+ checksum: 10c0/32f975da8e9c2cae6b33e1a477f8fe8bbff6722c982b5ce35f99affaf3a7a1b612c8272b43afa0e51d3000928d6f3ba38f9296301115db5640264907c027b0cd+ languageName: node+ linkType: hard++"@babel/runtime@npm:^7.29.7 || ^8.0.0":+ version: 8.0.8+ resolution: "@babel/runtime@npm:8.0.8"+ checksum: 10c0/059934f37971e24c5cd4505a2e0f63a039051935c0a9fcebd31fb7d0a0c05acd7915ba2f06db5197c97a31755862330232253b9a2cefa5bf37fdc9e521b4d6dc+ languageName: node+ linkType: hard++"@babel/template@npm:^7.29.7":+ version: 7.29.7+ resolution: "@babel/template@npm:7.29.7"+ dependencies:+ "@babel/code-frame": "npm:^7.29.7"+ "@babel/parser": "npm:^7.29.7"+ "@babel/types": "npm:^7.29.7"+ checksum: 10c0/8bb7f900dcab0e9e1c5ffbc33ca10e0d26b7b2e2ca804becb73ee771b9c4ed6e2908a4ae4a14c08560febb45d2b6b9a173955e42ad404d05f8b04840a14d9c58+ languageName: node+ linkType: hard++"@babel/traverse@npm:^7.29.7":+ version: 7.29.10+ resolution: "@babel/traverse@npm:7.29.10"+ dependencies:+ "@babel/code-frame": "npm:^7.29.7"+ "@babel/generator": "npm:^7.29.8"+ "@babel/helper-globals": "npm:^7.29.7"+ "@babel/parser": "npm:^7.29.9"+ "@babel/template": "npm:^7.29.7"+ "@babel/types": "npm:^7.29.8"+ debug: "npm:^4.3.1"+ checksum: 10c0/dc97fc5ac9778ba3fa7df2dcff0811bca4466173ad710d9be94ffd82c9944cfa962df33d144fd59b6256fc7ab895aad30d830aade8a8a96327c8f49fbb487fda+ languageName: node+ linkType: hard++"@babel/types@npm:^7.29.11, @babel/types@npm:^7.29.7, @babel/types@npm:^7.29.8":+ version: 7.29.11+ resolution: "@babel/types@npm:7.29.11"+ dependencies:+ "@babel/helper-string-parser": "npm:^7.29.11"+ "@babel/helper-validator-identifier": "npm:^7.29.7"+ checksum: 10c0/d0d4edd2fbff0a8e79af1fea3c3c056de86bc0e01ed734d00062287638379933a232f087959c6eb67365c2f4fb44d57b88793cd1e87f0aad568f1c8b3b94da80+ languageName: node+ linkType: hard++"@base-ui/react@npm:^1.9.0":+ version: 1.9.0+ resolution: "@base-ui/react@npm:1.9.0"+ dependencies:+ "@babel/runtime": "npm:^7.29.7 || ^8.0.0"+ "@base-ui/utils": "npm:0.5.0"+ "@floating-ui/react-dom": "npm:^2.1.9"+ "@floating-ui/utils": "npm:^0.2.12"+ use-sync-external-store: "npm:^1.7.0"+ peerDependencies:+ "@date-fns/tz": ^1.2.0+ "@types/react": ^17 || ^18 || ^19+ date-fns: ^4.0.0+ react: ^17 || ^18 || ^19+ react-dom: ^17 || ^18 || ^19+ peerDependenciesMeta:+ "@date-fns/tz":+ optional: true+ "@types/react":+ optional: true+ date-fns:+ optional: true+ checksum: 10c0/0495ec9026ad2f5f04580865a1b40c2899b2475d77472d3dcb8b688b1a2a949e14493cc50adb4dd7d33970caef7845ef4a0b93184a8299ed78bda7ff7c288847+ languageName: node+ linkType: hard++"@base-ui/utils@npm:0.5.0":+ version: 0.5.0+ resolution: "@base-ui/utils@npm:0.5.0"+ dependencies:+ "@babel/runtime": "npm:^7.29.7 || ^8.0.0"+ "@floating-ui/utils": "npm:^0.2.12"+ reselect: "npm:^5.3.0"+ use-sync-external-store: "npm:^1.7.0"+ peerDependencies:+ "@types/react": ^17 || ^18 || ^19+ react: ^17 || ^18 || ^19+ react-dom: ^17 || ^18 || ^19+ peerDependenciesMeta:+ "@types/react":+ optional: true+ checksum: 10c0/864b572ea60ea557bfdc63ff056026ed585cce4f35e4996c63e86503944befa3d9bc41e8f1da847e1273d8ac0b2f55210eecff936c3cfb1e0ea7ba9bfc5c5b5b+ languageName: node+ linkType: hard++"@emotion/babel-plugin@npm:^11.13.5":+ version: 11.13.5+ resolution: "@emotion/babel-plugin@npm:11.13.5"+ dependencies:+ "@babel/helper-module-imports": "npm:^7.16.7"+ "@babel/runtime": "npm:^7.18.3"+ "@emotion/hash": "npm:^0.9.2"+ "@emotion/memoize": "npm:^0.9.0"+ "@emotion/serialize": "npm:^1.3.3"+ babel-plugin-macros: "npm:^3.1.0"+ convert-source-map: "npm:^1.5.0"+ escape-string-regexp: "npm:^4.0.0"+ find-root: "npm:^1.1.0"+ source-map: "npm:^0.5.7"+ stylis: "npm:4.2.0"+ checksum: 10c0/8ccbfec7defd0e513cb8a1568fa179eac1e20c35fda18aed767f6c59ea7314363ebf2de3e9d2df66c8ad78928dc3dceeded84e6fa8059087cae5c280090aeeeb+ languageName: node+ linkType: hard++"@emotion/cache@npm:^11.14.0":+ version: 11.14.0+ resolution: "@emotion/cache@npm:11.14.0"+ dependencies:+ "@emotion/memoize": "npm:^0.9.0"+ "@emotion/sheet": "npm:^1.4.0"+ "@emotion/utils": "npm:^1.4.2"+ "@emotion/weak-memoize": "npm:^0.4.0"+ stylis: "npm:4.2.0"+ checksum: 10c0/3fa3e7a431ab6f8a47c67132a00ac8358f428c1b6c8421d4b20de9df7c18e95eec04a5a6ff5a68908f98d3280044f247b4965ac63df8302d2c94dba718769724+ languageName: node+ linkType: hard++"@emotion/hash@npm:^0.9.2":+ version: 0.9.2+ resolution: "@emotion/hash@npm:0.9.2"+ checksum: 10c0/0dc254561a3cc0a06a10bbce7f6a997883fd240c8c1928b93713f803a2e9153a257a488537012efe89dbe1246f2abfe2add62cdb3471a13d67137fcb808e81c2+ languageName: node+ linkType: hard++"@emotion/is-prop-valid@npm:^1.3.0":+ version: 1.4.0+ resolution: "@emotion/is-prop-valid@npm:1.4.0"+ dependencies:+ "@emotion/memoize": "npm:^0.9.0"+ checksum: 10c0/5f857814ec7d8c7e727727346dfb001af6b1fb31d621a3ce9c3edf944a484d8b0d619546c30899ae3ade2f317c76390ba4394449728e9bf628312defc2c41ac3+ languageName: node+ linkType: hard++"@emotion/memoize@npm:^0.9.0":+ version: 0.9.0+ resolution: "@emotion/memoize@npm:0.9.0"+ checksum: 10c0/13f474a9201c7f88b543e6ea42f55c04fb2fdc05e6c5a3108aced2f7e7aa7eda7794c56bba02985a46d8aaa914fcdde238727a98341a96e2aec750d372dadd15+ languageName: node+ linkType: hard++"@emotion/react@npm:^11.14.0":+ version: 11.14.0+ resolution: "@emotion/react@npm:11.14.0"+ dependencies:+ "@babel/runtime": "npm:^7.18.3"+ "@emotion/babel-plugin": "npm:^11.13.5"+ "@emotion/cache": "npm:^11.14.0"+ "@emotion/serialize": "npm:^1.3.3"+ "@emotion/use-insertion-effect-with-fallbacks": "npm:^1.2.0"+ "@emotion/utils": "npm:^1.4.2"+ "@emotion/weak-memoize": "npm:^0.4.0"+ hoist-non-react-statics: "npm:^3.3.1"+ peerDependencies:+ react: ">=16.8.0"+ peerDependenciesMeta:+ "@types/react":+ optional: true+ checksum: 10c0/d0864f571a9f99ec643420ef31fde09e2006d3943a6aba079980e4d5f6e9f9fecbcc54b8f617fe003c00092ff9d5241179149ffff2810cb05cf72b4620cfc031+ languageName: node+ linkType: hard++"@emotion/serialize@npm:^1.3.3":+ version: 1.3.3+ resolution: "@emotion/serialize@npm:1.3.3"+ dependencies:+ "@emotion/hash": "npm:^0.9.2"+ "@emotion/memoize": "npm:^0.9.0"+ "@emotion/unitless": "npm:^0.10.0"+ "@emotion/utils": "npm:^1.4.2"+ csstype: "npm:^3.0.2"+ checksum: 10c0/b28cb7de59de382021de2b26c0c94ebbfb16967a1b969a56fdb6408465a8993df243bfbd66430badaa6800e1834724e84895f5a6a9d97d0d224de3d77852acb4+ languageName: node+ linkType: hard++"@emotion/sheet@npm:^1.4.0":+ version: 1.4.0+ resolution: "@emotion/sheet@npm:1.4.0"+ checksum: 10c0/3ca72d1650a07d2fbb7e382761b130b4a887dcd04e6574b2d51ce578791240150d7072a9bcb4161933abbcd1e38b243a6fb4464a7fe991d700c17aa66bb5acc7+ languageName: node+ linkType: hard++"@emotion/styled@npm:^11.14.0":+ version: 11.14.1+ resolution: "@emotion/styled@npm:11.14.1"+ dependencies:+ "@babel/runtime": "npm:^7.18.3"+ "@emotion/babel-plugin": "npm:^11.13.5"+ "@emotion/is-prop-valid": "npm:^1.3.0"+ "@emotion/serialize": "npm:^1.3.3"+ "@emotion/use-insertion-effect-with-fallbacks": "npm:^1.2.0"+ "@emotion/utils": "npm:^1.4.2"+ peerDependencies:+ "@emotion/react": ^11.0.0-rc.0+ react: ">=16.8.0"+ peerDependenciesMeta:+ "@types/react":+ optional: true+ checksum: 10c0/2bbf8451df49c967e41fbcf8111a7f6dafe6757f0cc113f2f6e287206c45ac1d54dc8a95a483b7c0cee8614b8a8d08155bded6453d6721de1f8cc8d5b9216963+ languageName: node+ linkType: hard++"@emotion/unitless@npm:^0.10.0":+ version: 0.10.0+ resolution: "@emotion/unitless@npm:0.10.0"+ checksum: 10c0/150943192727b7650eb9a6851a98034ddb58a8b6958b37546080f794696141c3760966ac695ab9af97efe10178690987aee4791f9f0ad1ff76783cdca83c1d49+ languageName: node+ linkType: hard++"@emotion/use-insertion-effect-with-fallbacks@npm:^1.2.0":+ version: 1.2.0+ resolution: "@emotion/use-insertion-effect-with-fallbacks@npm:1.2.0"+ peerDependencies:+ react: ">=16.8.0"+ checksum: 10c0/074dbc92b96bdc09209871070076e3b0351b6b47efefa849a7d9c37ab142130767609ca1831da0055988974e3b895c1de7606e4c421fecaa27c3e56a2afd3b08+ languageName: node+ linkType: hard++"@emotion/utils@npm:^1.4.2":+ version: 1.4.2+ resolution: "@emotion/utils@npm:1.4.2"+ checksum: 10c0/7d0010bf60a2a8c1a033b6431469de4c80e47aeb8fd856a17c1d1f76bbc3a03161a34aeaa78803566e29681ca551e7bf9994b68e9c5f5c796159923e44f78d9a+ languageName: node+ linkType: hard++"@emotion/weak-memoize@npm:^0.4.0":+ version: 0.4.0+ resolution: "@emotion/weak-memoize@npm:0.4.0"+ checksum: 10c0/64376af11f1266042d03b3305c30b7502e6084868e33327e944b539091a472f089db307af69240f7188f8bc6b319276fd7b141a36613f1160d73d12a60f6ca1a+ languageName: node+ linkType: hard+"@esbuild/aix-ppc64@npm:0.28.2":version: 0.28.2resolution: "@esbuild/aix-ppc64@npm:0.28.2"@@ -187,6 +494,58 @@ __metadata:languageName: nodelinkType: hard+"@floating-ui/core@npm:^1.8.0":+ version: 1.8.0+ resolution: "@floating-ui/core@npm:1.8.0"+ dependencies:+ "@floating-ui/utils": "npm:^0.2.12"+ checksum: 10c0/cece958f6fab0f8cd7740cd57988c4f8bc5356dca39dd4c093433d44c91952c3a02c7a54d93d7ed6c078b6544d531a29f66621d2839c8bfbb4467dca6aed7df0+ languageName: node+ linkType: hard++"@floating-ui/dom@npm:^1.8.0":+ version: 1.8.0+ resolution: "@floating-ui/dom@npm:1.8.0"+ dependencies:+ "@floating-ui/core": "npm:^1.8.0"+ "@floating-ui/utils": "npm:^0.2.12"+ checksum: 10c0/c32b2de7a596b69cfffa909c7028825e14f6319be1b45da529f8943c89fe16b75a49c214e800c87ded3f172353d3b99163d50072f11410488e756961b7b629cc+ languageName: node+ linkType: hard++"@floating-ui/react-dom@npm:^2.1.9":+ version: 2.1.9+ resolution: "@floating-ui/react-dom@npm:2.1.9"+ dependencies:+ "@floating-ui/dom": "npm:^1.8.0"+ peerDependencies:+ react: ">=16.8.0"+ react-dom: ">=16.8.0"+ checksum: 10c0/9fa9851069738cb9591a1ab2da16e257f193eae5fd2d6d48ad0b1e73f3c049929b6805c5ad43d4af3c1da63c60b215b0ee4651a1fe5caeb80e66d9d423744348+ languageName: node+ linkType: hard++"@floating-ui/react@npm:^0.27.15":+ version: 0.27.20+ resolution: "@floating-ui/react@npm:0.27.20"+ dependencies:+ "@floating-ui/react-dom": "npm:^2.1.9"+ "@floating-ui/utils": "npm:^0.2.12"+ tabbable: "npm:^6.0.0"+ peerDependencies:+ react: ">=17.0.0"+ react-dom: ">=17.0.0"+ checksum: 10c0/5ebeb4c877128e9a274692849ceb2103b370441626e97ade38c25db5d94371dd7274292eda05208cc5d1c92c594a59595a1909799c2ac8ff44f9e651a4fe55b3+ languageName: node+ linkType: hard++"@floating-ui/utils@npm:^0.2.12":+ version: 0.2.12+ resolution: "@floating-ui/utils@npm:0.2.12"+ checksum: 10c0/bb910b90d56991a62011afaf5f8e0c4b7fb6dab69403f4dd17fbd6eb25560b28d533dff9791f270b4f459852e9006a1077b5d73cbedb5e34d9424afc6a828314+ languageName: node+ linkType: hard+"@genql/runtime@npm:^2.10.0":version: 2.10.0resolution: "@genql/runtime@npm:2.10.0"@@ -216,13 +575,40 @@ __metadata:languageName: nodelinkType: hard-"@jridgewell/sourcemap-codec@npm:^1.5.5":+"@jridgewell/gen-mapping@npm:^0.3.12":+ version: 0.3.13+ resolution: "@jridgewell/gen-mapping@npm:0.3.13"+ dependencies:+ "@jridgewell/sourcemap-codec": "npm:^1.5.0"+ "@jridgewell/trace-mapping": "npm:^0.3.24"+ checksum: 10c0/9a7d65fb13bd9aec1fbab74cda08496839b7e2ceb31f5ab922b323e94d7c481ce0fc4fd7e12e2610915ed8af51178bdc61e168e92a8c8b8303b030b03489b13b+ languageName: node+ linkType: hard++"@jridgewell/resolve-uri@npm:^3.1.0":+ version: 3.1.2+ resolution: "@jridgewell/resolve-uri@npm:3.1.2"+ checksum: 10c0/d502e6fb516b35032331406d4e962c21fe77cdf1cbdb49c6142bcbd9e30507094b18972778a6e27cbad756209cfe34b1a27729e6fa08a2eb92b33943f680cf1e+ languageName: node+ linkType: hard++"@jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.5.0, @jridgewell/sourcemap-codec@npm:^1.5.5":version: 1.6.0resolution: "@jridgewell/sourcemap-codec@npm:1.6.0"checksum: 10c0/b5be700e45a775f218589c3466c4ffea630582b4988657652da464e5ab8a7d18bf928ee4fd2363fb346ede4bea9c6ff0bae05a538358c4565ece6199531b5f72languageName: nodelinkType: hard+"@jridgewell/trace-mapping@npm:^0.3.24, @jridgewell/trace-mapping@npm:^0.3.28":+ version: 0.3.31+ resolution: "@jridgewell/trace-mapping@npm:0.3.31"+ dependencies:+ "@jridgewell/resolve-uri": "npm:^3.1.0"+ "@jridgewell/sourcemap-codec": "npm:^1.4.14"+ checksum: 10c0/4b30ec8cd56c5fd9a661f088230af01e0c1a3888d11ffb6b47639700f71225be21d1f7e168048d6d4f9449207b978a235c07c8f15c07705685d16dc06280e9d9+ languageName: node+ linkType: hard+"@oxc-project/types@npm:=0.155.0":version: 0.155.0resolution: "@oxc-project/types@npm:0.155.0"@@ -412,17 +798,41 @@ __metadata:languageName: nodelinkType: hard+"@tabler/icons-react@npm:^3.31.0":+ version: 3.49.0+ resolution: "@tabler/icons-react@npm:3.49.0"+ dependencies:+ "@tabler/icons": "npm:3.49.0"+ peerDependencies:+ react: ">= 16"+ checksum: 10c0/4c50b4f9ff56f6755161896ba4e5271dc97caf4132394e443162bff015e0fc72c109b53bc31436d4350fa2c836a472b304e5761b2a121c18c03f157966ba8025+ languageName: node+ linkType: hard++"@tabler/icons@npm:3.49.0":+ version: 3.49.0+ resolution: "@tabler/icons@npm:3.49.0"+ checksum: 10c0/8540c7182c67efcd7209d0ab2de75dd413eff0f61c5906d0e1b20bc53ef4eaadcd13e301e2e5829dac47ee710bc0d8301d99c1dd0aada683a87addb32742d34a+ languageName: node+ linkType: hard+"@twentyhq/linkedin@workspace:.":version: 0.0.0-use.localresolution: "@twentyhq/linkedin@workspace:."dependencies:+ "@emotion/react": "npm:^11.14.0"+ "@emotion/styled": "npm:^11.14.0""@sniptt/guards": "npm:^0.2.0""@types/node": "npm:^24.7.2"+ "@types/react": "npm:^19.0.0""@typescript/native-preview": "npm:^7.0.0-dev.20260116.1""@unipile/sdk": "npm:^2.59.0"oxlint: "npm:^0.16.0"+ react: "npm:^19.0.0"+ react-dom: "npm:^19.0.0"twenty-client-sdk: "npm:2.53.0"twenty-sdk: "npm:2.53.0"+ twenty-ui: "npm:^2.53.0"typescript: "npm:^5.9.3"vite-tsconfig-paths: "npm:^4.2.1"vitest: "npm:^4.1.12"@@ -471,6 +881,13 @@ __metadata:languageName: nodelinkType: hard+"@types/parse-json@npm:^4.0.0":+ version: 4.0.2+ resolution: "@types/parse-json@npm:4.0.2"+ checksum: 10c0/b1b863ac34a2c2172fbe0807a1ec4d5cb684e48d422d15ec95980b81475fac4fdb3768a8b13eef39130203a7c04340fc167bae057c7ebcafd7dec9fe6c36aeb1+ languageName: node+ linkType: hard+"@types/qs@npm:^6.9.0":version: 6.15.1resolution: "@types/qs@npm:6.15.1"@@ -478,6 +895,15 @@ __metadata:languageName: nodelinkType: hard+"@types/react@npm:^19.0.0":+ version: 19.3.0+ resolution: "@types/react@npm:19.3.0"+ dependencies:+ csstype: "npm:^3.2.2"+ checksum: 10c0/fbcabf303f935ca9f36ed2dcf81751cf84744098c5a683c8a62a0fa7edd31714b48d5c46b12fd0014f7f2dfe4d9ec6de428a850748eec719a70294e51029551b+ languageName: node+ linkType: hard+"@types/ws@npm:^6.0.1":version: 6.0.4resolution: "@types/ws@npm:6.0.4"@@ -678,6 +1104,17 @@ __metadata:languageName: nodelinkType: hard+"babel-plugin-macros@npm:^3.1.0":+ version: 3.1.0+ resolution: "babel-plugin-macros@npm:3.1.0"+ dependencies:+ "@babel/runtime": "npm:^7.12.5"+ cosmiconfig: "npm:^7.0.0"+ resolve: "npm:^1.19.0"+ checksum: 10c0/c6dfb15de96f67871d95bd2e8c58b0c81edc08b9b087dc16755e7157f357dc1090a8dc60ebab955e92587a9101f02eba07e730adc253a1e4cf593ca3ebd3839c+ languageName: node+ linkType: hard+"backo2@npm:^1.0.2":version: 1.0.2resolution: "backo2@npm:1.0.2"@@ -685,6 +1122,13 @@ __metadata:languageName: nodelinkType: hard+"callsites@npm:^3.0.0":+ version: 3.1.0+ resolution: "callsites@npm:3.1.0"+ checksum: 10c0/fff92277400eb06c3079f9e74f3af120db9f8ea03bad0e84d9aede54bbe2d44a56cccb5f6cf12211f93f52306df87077ecec5b712794c5a9b5dac6d615a3f301+ languageName: node+ linkType: hard+"chai@npm:^6.2.2":version: 6.3.0resolution: "chai@npm:6.3.0"@@ -699,6 +1143,20 @@ __metadata:languageName: nodelinkType: hard+"clsx@npm:^2.1.1":+ version: 2.1.1+ resolution: "clsx@npm:2.1.1"+ checksum: 10c0/c4c8eb865f8c82baab07e71bfa8897c73454881c4f99d6bc81585aecd7c441746c1399d08363dc096c550cceaf97bd4ce1e8854e1771e9998d9f94c4fe075839+ languageName: node+ linkType: hard++"convert-source-map@npm:^1.5.0":+ version: 1.9.0+ resolution: "convert-source-map@npm:1.9.0"+ checksum: 10c0/281da55454bf8126cbc6625385928c43479f2060984180c42f3a86c8b8c12720a24eac260624a7d1e090004028d2dee78602330578ceec1a08e27cb8bb0a8a5b+ languageName: node+ linkType: hard+"convert-source-map@npm:^2.0.0":version: 2.0.0resolution: "convert-source-map@npm:2.0.0"@@ -706,7 +1164,34 @@ __metadata:languageName: nodelinkType: hard-"debug@npm:^4.1.1":+"cosmiconfig@npm:^7.0.0":+ version: 7.1.0+ resolution: "cosmiconfig@npm:7.1.0"+ dependencies:+ "@types/parse-json": "npm:^4.0.0"+ import-fresh: "npm:^3.2.1"+ parse-json: "npm:^5.0.0"+ path-type: "npm:^4.0.0"+ yaml: "npm:^1.10.0"+ checksum: 10c0/b923ff6af581638128e5f074a5450ba12c0300b71302398ea38dbeabd33bbcaa0245ca9adbedfcf284a07da50f99ede5658c80bb3e39e2ce770a99d28a21ef03+ languageName: node+ linkType: hard++"csstype@npm:^3.0.2, csstype@npm:^3.2.2":+ version: 3.2.3+ resolution: "csstype@npm:3.2.3"+ checksum: 10c0/cd29c51e70fa822f1cecd8641a1445bed7063697469d35633b516e60fe8c1bde04b08f6c5b6022136bb669b64c63d4173af54864510fbb4ee23281801841a3ce+ languageName: node+ linkType: hard++"date-fns@npm:^4.1.0":+ version: 4.4.0+ resolution: "date-fns@npm:4.4.0"+ checksum: 10c0/988f0a13db183f5dfc85c36bbb6847a9c135a9225888bbea4005876ec15539a8613c21a07370a4e7ea543918d5a1cafb423c528b42cdbbde5fdfddb178126b21+ languageName: node+ linkType: hard++"debug@npm:^4.1.1, debug@npm:^4.3.1":version: 4.4.3resolution: "debug@npm:4.4.3"dependencies:@@ -732,6 +1217,22 @@ __metadata:languageName: nodelinkType: hard+"error-ex@npm:^1.3.1":+ version: 1.3.4+ resolution: "error-ex@npm:1.3.4"+ dependencies:+ is-arrayish: "npm:^0.2.1"+ checksum: 10c0/b9e34ff4778b8f3b31a8377e1c654456f4c41aeaa3d10a1138c3b7635d8b7b2e03eb2475d46d8ae055c1f180a1063e100bffabf64ea7e7388b37735df5328664+ languageName: node+ linkType: hard++"es-errors@npm:^1.3.0":+ version: 1.3.0+ resolution: "es-errors@npm:1.3.0"+ checksum: 10c0/0a61325670072f98d8ae3b914edab3559b6caa980f08054a3b872052640d91da01d38df55df797fcc916389d77fc92b8d5906cf028f4db46d7e3003abecbca85+ languageName: node+ linkType: hard+"es-module-lexer@npm:^2.0.0":version: 2.3.2resolution: "es-module-lexer@npm:2.3.2"@@ -828,6 +1329,13 @@ __metadata:languageName: nodelinkType: hard+"escape-string-regexp@npm:^4.0.0":+ version: 4.0.0+ resolution: "escape-string-regexp@npm:4.0.0"+ checksum: 10c0/9497d4dd307d845bd7f75180d8188bb17ea8c151c1edbf6b6717c100e104d629dc2dfb687686181b0f4b7d732c7dfdc4d5e7a8ff72de1b0ca283a75bbb3a9cd9+ languageName: node+ linkType: hard+"estree-walker@npm:^3.0.3":version: 3.0.3resolution: "estree-walker@npm:3.0.3"@@ -870,6 +1378,13 @@ __metadata:languageName: nodelinkType: hard+"find-root@npm:^1.1.0":+ version: 1.1.0+ resolution: "find-root@npm:1.1.0"+ checksum: 10c0/1abc7f3bf2f8d78ff26d9e00ce9d0f7b32e5ff6d1da2857bcdf4746134c422282b091c672cde0572cac3840713487e0a7a636af9aa1b74cb11894b447a521efa+ languageName: node+ linkType: hard+"fsevents@npm:~2.3.3":version: 2.3.3resolution: "fsevents@npm:2.3.3"@@ -889,6 +1404,13 @@ __metadata:languageName: nodelinkType: hard+"function-bind@npm:^1.1.2":+ version: 1.1.2+ resolution: "function-bind@npm:1.1.2"+ checksum: 10c0/d8680ee1e5fcd4c197e4ac33b2b4dce03c71f4d91717292785703db200f5c21f977c568d28061226f9b5900cbcd2c84463646134fd5337e7925e0942bc3f46d5+ languageName: node+ linkType: hard+"globrex@npm:^0.1.2":version: 0.1.2resolution: "globrex@npm:0.1.2"@@ -917,6 +1439,50 @@ __metadata:languageName: nodelinkType: hard+"hasown@npm:^2.0.4":+ version: 2.0.4+ resolution: "hasown@npm:2.0.4"+ dependencies:+ function-bind: "npm:^1.1.2"+ checksum: 10c0/2d8de939e270b70618f8cebb69746620db10617dbb495bc66ddad326955ea24d3ca4af133aff3eb7c1853e0218f867bc2b050ec26fe02e3aea58f880ffc5e506+ languageName: node+ linkType: hard++"hoist-non-react-statics@npm:^3.3.1":+ version: 3.3.2+ resolution: "hoist-non-react-statics@npm:3.3.2"+ dependencies:+ react-is: "npm:^16.7.0"+ checksum: 10c0/fe0889169e845d738b59b64badf5e55fa3cf20454f9203d1eb088df322d49d4318df774828e789898dcb280e8a5521bb59b3203385662ca5e9218a6ca5820e74+ languageName: node+ linkType: hard++"import-fresh@npm:^3.2.1":+ version: 3.3.1+ resolution: "import-fresh@npm:3.3.1"+ dependencies:+ parent-module: "npm:^1.0.0"+ resolve-from: "npm:^4.0.0"+ checksum: 10c0/bf8cc494872fef783249709385ae883b447e3eb09db0ebd15dcead7d9afe7224dad7bd7591c6b73b0b19b3c0f9640eb8ee884f01cfaf2887ab995b0b36a0cbec+ languageName: node+ linkType: hard++"is-arrayish@npm:^0.2.1":+ version: 0.2.1+ resolution: "is-arrayish@npm:0.2.1"+ checksum: 10c0/e7fb686a739068bb70f860b39b67afc62acc62e36bb61c5f965768abce1873b379c563e61dd2adad96ebb7edf6651111b385e490cf508378959b0ed4cac4e729+ languageName: node+ linkType: hard++"is-core-module@npm:^2.17.0":+ version: 2.17.0+ resolution: "is-core-module@npm:2.17.0"+ dependencies:+ hasown: "npm:^2.0.4"+ checksum: 10c0/3dc7c15ea42f846180cd2cdd57af62270e0a8d0ed31c17c85735d554089d39975e2e82e65fc7c8280a3c476ca3d0d09992d0860b4998abb769a277341feb6698+ languageName: node+ linkType: hard+"isexe@npm:^4.0.0":version: 4.0.0resolution: "isexe@npm:4.0.0"@@ -941,6 +1507,29 @@ __metadata:languageName: nodelinkType: hard+"js-tokens@npm:^4.0.0":+ version: 4.0.0+ resolution: "js-tokens@npm:4.0.0"+ checksum: 10c0/e248708d377aa058eacf2037b07ded847790e6de892bbad3dac0abba2e759cb9f121b00099a65195616badcb6eca8d14d975cb3e89eb1cfda644756402c8aeed+ languageName: node+ linkType: hard++"jsesc@npm:^3.0.2":+ version: 3.1.0+ resolution: "jsesc@npm:3.1.0"+ bin:+ jsesc: bin/jsesc+ checksum: 10c0/531779df5ec94f47e462da26b4cbf05eb88a83d9f08aac2ba04206508fc598527a153d08bd462bae82fc78b3eaa1a908e1a4a79f886e9238641c4cdefaf118b1+ languageName: node+ linkType: hard++"json-parse-even-better-errors@npm:^2.3.0":+ version: 2.3.1+ resolution: "json-parse-even-better-errors@npm:2.3.1"+ checksum: 10c0/140932564c8f0b88455432e0f33c4cb4086b8868e37524e07e723f4eaedb9425bdc2bafd71bd1d9765bd15fd1e2d126972bc83990f55c467168c228c24d665f3+ languageName: node+ linkType: hard+"lightningcss-android-arm64@npm:1.33.0":version: 1.33.0resolution: "lightningcss-android-arm64@npm:1.33.0"@@ -1061,6 +1650,13 @@ __metadata:languageName: nodelinkType: hard+"lines-and-columns@npm:^1.1.6":+ version: 1.2.4+ resolution: "lines-and-columns@npm:1.2.4"+ checksum: 10c0/3da6ee62d4cd9f03f5dc90b4df2540fb85b352081bee77fe4bbcd12c9000ead7f35e0a38b8d09a9bb99b13223446dd8689ff3c4959807620726d788701a83d2d+ languageName: node+ linkType: hard+"lodash@npm:^4.17.20, lodash@npm:^4.17.21":version: 4.18.1resolution: "lodash@npm:4.18.1"@@ -1197,6 +1793,41 @@ __metadata:languageName: nodelinkType: hard+"parent-module@npm:^1.0.0":+ version: 1.0.1+ resolution: "parent-module@npm:1.0.1"+ dependencies:+ callsites: "npm:^3.0.0"+ checksum: 10c0/c63d6e80000d4babd11978e0d3fee386ca7752a02b035fd2435960ffaa7219dc42146f07069fb65e6e8bf1caef89daf9af7535a39bddf354d78bf50d8294f556+ languageName: node+ linkType: hard++"parse-json@npm:^5.0.0":+ version: 5.2.0+ resolution: "parse-json@npm:5.2.0"+ dependencies:+ "@babel/code-frame": "npm:^7.0.0"+ error-ex: "npm:^1.3.1"+ json-parse-even-better-errors: "npm:^2.3.0"+ lines-and-columns: "npm:^1.1.6"+ checksum: 10c0/77947f2253005be7a12d858aedbafa09c9ae39eb4863adf330f7b416ca4f4a08132e453e08de2db46459256fb66afaac5ee758b44fe6541b7cdaf9d252e59585+ languageName: node+ linkType: hard++"path-parse@npm:^1.0.7":+ version: 1.0.7+ resolution: "path-parse@npm:1.0.7"+ checksum: 10c0/11ce261f9d294cc7a58d6a574b7f1b935842355ec66fba3c3fd79e0f036462eaf07d0aa95bb74ff432f9afef97ce1926c720988c6a7451d8a584930ae7de86e1+ languageName: node+ linkType: hard++"path-type@npm:^4.0.0":+ version: 4.0.0+ resolution: "path-type@npm:4.0.0"+ checksum: 10c0/666f6973f332f27581371efaf303fd6c272cc43c2057b37aa99e3643158c7e4b2626549555d88626e99ea9e046f82f32e41bbde5f1508547e9a11b149b52387c+ languageName: node+ linkType: hard+"pathe@npm:^2.0.3":version: 2.0.3resolution: "pathe@npm:2.0.3"@@ -1257,7 +1888,25 @@ __metadata:languageName: nodelinkType: hard-"react-dom@npm:^19.2.0":+"react-datepicker@npm:^9.1.0":+ version: 9.1.0+ resolution: "react-datepicker@npm:9.1.0"+ dependencies:+ "@floating-ui/react": "npm:^0.27.15"+ clsx: "npm:^2.1.1"+ date-fns: "npm:^4.1.0"+ peerDependencies:+ date-fns-tz: ^3.0.0+ react: ^16.9.0 || ^17 || ^18 || ^19 || ^19.0.0-rc+ react-dom: ^16.9.0 || ^17 || ^18 || ^19 || ^19.0.0-rc+ peerDependenciesMeta:+ date-fns-tz:+ optional: true+ checksum: 10c0/43b58b08f9e4f289a31f2a2dbd0e246e396ad44ebfea4ed8d1393de2a6bded2dad9c2002cfcf70dfbe51aabf5f886b12b1aae8463c5bc35d67b1b22733a8a0f9+ languageName: node+ linkType: hard++"react-dom@npm:^19.0.0, react-dom@npm:^19.2.0":version: 19.3.1resolution: "react-dom@npm:19.3.1"dependencies:@@ -1268,13 +1917,62 @@ __metadata:languageName: nodelinkType: hard-"react@npm:^19.2.0":+"react-is@npm:^16.7.0":+ version: 16.13.1+ resolution: "react-is@npm:16.13.1"+ checksum: 10c0/33977da7a5f1a287936a0c85639fec6ca74f4f15ef1e59a6bc20338fc73dc69555381e211f7a3529b8150a1f71e4225525b41b60b52965bda53ce7d47377ada1+ languageName: node+ linkType: hard++"react@npm:^19.0.0, react@npm:^19.2.0":version: 19.3.1resolution: "react@npm:19.3.1"checksum: 10c0/f0ed036d1223562c09c8347858ca712733ea6e27a30db709ee9c3f3f176d3e9e767afce735d59956addf3d030102e256bba82dea635fc1bdb0e01107e98fef10languageName: nodelinkType: hard+"reselect@npm:^5.3.0":+ version: 5.3.0+ resolution: "reselect@npm:5.3.0"+ checksum: 10c0/c79728e4f315152bfb2d82456d35075b705392d9e72c485d7d9b1061bd80af628416216d80f02a42f24dbb24d738aec7fec45806930aaa1d17c32e9875fa1bd6+ languageName: node+ linkType: hard++"resolve-from@npm:^4.0.0":+ version: 4.0.0+ resolution: "resolve-from@npm:4.0.0"+ checksum: 10c0/8408eec31a3112ef96e3746c37be7d64020cda07c03a920f5024e77290a218ea758b26ca9529fd7b1ad283947f34b2291c1c0f6aa0ed34acfdda9c6014c8d190+ languageName: node+ linkType: hard++"resolve@npm:^1.19.0":+ version: 1.22.13+ resolution: "resolve@npm:1.22.13"+ dependencies:+ es-errors: "npm:^1.3.0"+ is-core-module: "npm:^2.17.0"+ path-parse: "npm:^1.0.7"+ supports-preserve-symlinks-flag: "npm:^1.0.0"+ bin:+ resolve: bin/resolve+ checksum: 10c0/8dac5b33a1f9f241500fcaf42f9033cdcaf3738c908a60a50a976ff2f6129063cbc5368b4092e42d2d264ad22aa94aaff207f3efa8d0185c68454439b11a1973+ languageName: node+ linkType: hard++"resolve@patch:resolve@npm%3A^1.19.0#optional!builtin<compat/resolve>":+ version: 1.22.13+ resolution: "resolve@patch:resolve@npm%3A1.22.13#optional!builtin<compat/resolve>::version=1.22.13&hash=9bd1a5"+ dependencies:+ es-errors: "npm:^1.3.0"+ is-core-module: "npm:^2.17.0"+ path-parse: "npm:^1.0.7"+ supports-preserve-symlinks-flag: "npm:^1.0.0"+ bin:+ resolve: bin/resolve+ checksum: 10c0/bc58ee02e647a4250453eeb067796bdc087f6a89d4d5780bfe479f402ec11b9461babc155a6452020b56f3845cf49b1afd9c95fe3fc8347cba6567aa9b10c106+ languageName: node+ linkType: hard+"rolldown@npm:~1.2.14":version: 1.2.15resolution: "rolldown@npm:1.2.15"@@ -1363,6 +2061,13 @@ __metadata:languageName: nodelinkType: hard+"source-map@npm:^0.5.7":+ version: 0.5.7+ resolution: "source-map@npm:0.5.7"+ checksum: 10c0/904e767bb9c494929be013017380cbba013637da1b28e5943b566031e29df04fba57edf3f093e0914be094648b577372bd8ad247fa98cfba9c600794cd16b599+ languageName: node+ linkType: hard+"stackback@npm:0.0.2":version: 0.0.2resolution: "stackback@npm:0.0.2"@@ -1377,6 +2082,13 @@ __metadata:languageName: nodelinkType: hard+"stylis@npm:4.2.0":+ version: 4.2.0+ resolution: "stylis@npm:4.2.0"+ checksum: 10c0/a7128ad5a8ed72652c6eba46bed4f416521bc9745a460ef5741edc725252cebf36ee45e33a8615a7057403c93df0866ab9ee955960792db210bb80abd5ac6543+ languageName: node+ linkType: hard+"subscriptions-transport-ws@npm:^0.9.16":version: 0.9.19resolution: "subscriptions-transport-ws@npm:0.9.19"@@ -1392,6 +2104,13 @@ __metadata:languageName: nodelinkType: hard+"supports-preserve-symlinks-flag@npm:^1.0.0":+ version: 1.0.0+ resolution: "supports-preserve-symlinks-flag@npm:1.0.0"+ checksum: 10c0/6c4032340701a9950865f7ae8ef38578d8d7053f5e10518076e6554a9381fa91bd9c6850193695c141f32b21f979c985db07265a758867bac95de05f7d8aeb39+ languageName: node+ linkType: hard+"symbol-observable@npm:^1.0.4":version: 1.2.0resolution: "symbol-observable@npm:1.2.0"@@ -1399,6 +2118,13 @@ __metadata:languageName: nodelinkType: hard+"tabbable@npm:^6.0.0":+ version: 6.5.1+ resolution: "tabbable@npm:6.5.1"+ checksum: 10c0/702c0ae8ca5b611d0312e3d860abcb6b1e35bd52fd3717a0a6ecb436fb680df39bf73a71009afb139a2316e6e27e300753366a05466b4ff76102d60ce13b0826+ languageName: node+ linkType: hard+"tar@npm:^7.5.7":version: 7.5.22resolution: "tar@npm:7.5.22"@@ -1506,6 +2232,39 @@ __metadata:languageName: nodelinkType: hard+"twenty-ui@npm:^2.53.0":+ version: 2.53.0+ resolution: "twenty-ui@npm:2.53.0"+ dependencies:+ "@base-ui/react": "npm:^1.9.0"+ "@base-ui/utils": "npm:0.5.0"+ "@sniptt/guards": "npm:^0.2.0"+ "@tabler/icons-react": "npm:^3.31.0"+ clsx: "npm:^2.1.1"+ react-datepicker: "npm:^9.1.0"+ type-fest: "npm:^4.10.1"+ zod: "npm:^4.6.6"+ peerDependencies:+ "@monaco-editor/react": ^4.7.0+ monaco-editor: ">= 0.25.0 < 1"+ react: ^19.0.0+ react-dom: ^19.0.0+ peerDependenciesMeta:+ "@monaco-editor/react":+ optional: true+ monaco-editor:+ optional: true+ checksum: 10c0/b063733ce2405350d204c4a4ce711746a8102f2ae960d79e569a146988cbcacae1f19558c1903bc00c436c9f8b31aaaf50b2f85a9d704d438a2b98001d00235a+ languageName: node+ linkType: hard++"type-fest@npm:^4.10.1":+ version: 4.41.0+ resolution: "type-fest@npm:4.41.0"+ checksum: 10c0/f5ca697797ed5e88d33ac8f1fec21921839871f808dc59345c9cf67345bfb958ce41bd821165dbf3ae591cedec2bf6fe8882098dfdd8dc54320b859711a2c1e4+ languageName: node+ linkType: hard+"typescript@npm:^5.9.3":version: 5.9.3resolution: "typescript@npm:5.9.3"@@ -1554,6 +2313,15 @@ __metadata:languageName: nodelinkType: hard+"use-sync-external-store@npm:^1.7.0":+ version: 1.7.0+ resolution: "use-sync-external-store@npm:1.7.0"+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ checksum: 10c0/6bae7cb778ce611131ec830c4e469fbc2872acefc25d2e4cf1c28b8628690689770742a9f2f0642c95134f9c77041fee60f0352f81ca43f96643b0ed01774726+ languageName: node+ linkType: hard+"utility-types@npm:^3.10.0":version: 3.11.0resolution: "utility-types@npm:3.11.0"@@ -1782,6 +2550,13 @@ __metadata:languageName: nodelinkType: hard+"yaml@npm:^1.10.0":+ version: 1.10.3+ resolution: "yaml@npm:1.10.3"+ checksum: 10c0/c309ff85a0a569a981d71ab9cf0fef68672a16b9cdf40639d1c3b30034f6cd16ee428602bd6d64ecf006f8c8bee499023cac236538f79898aa99fb5db529a2ed+ languageName: node+ linkType: hard+"zen-observable-ts@npm:^0.8.21":version: 0.8.21resolution: "zen-observable-ts@npm:0.8.21"@@ -1798,3 +2573,10 @@ __metadata:checksum: 10c0/71cc2f2bbb537300c3f569e25693d37b3bc91f225cefce251a71c30bc6bb3e7f8e9420ca0eb57f2ac9e492b085b8dfa075fd1e8195c40b83c951dd59c6e4fbf8languageName: nodelinkType: hard++"zod@npm:^4.6.6":+ version: 4.6.7+ resolution: "zod@npm:4.6.7"+ checksum: 10c0/4ce2eb14034317b7254e347ca37b5ad591cf8333147030cf05b9b5d31692d45073f7f2747aa50cf8c6b29012194d2b22978cecc89969cf34a0d18e89d0ee7d7b+ languageName: node+ linkType: hard