The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
LinkedIn app: cap the conversations a history sync imports (#29507)
martmull2f59ec6c869a
diff --git a/packages/twenty-apps/public/linkedin/README.md b/packages/twenty-apps/public/linkedin/README.mdindex 94efab70bc3..6d2d32ba1b2 100644--- a/packages/twenty-apps/public/linkedin/README.md+++ b/packages/twenty-apps/public/linkedin/README.md@@ -19,6 +19,7 @@## π Heads up- **Read-only for now.** Messages are imported as they happen; reply from LinkedIn. Marking chats as read on LinkedIn is not available yet.+- **Only recent history is imported.** LinkedIn allows about 100 profile lookups a day per account, so **Sync now** imports only your most recent conversations. Pick 10, 20 (default) or 50 in **Past conversations**, or **None** to skip history and only receive new messages.- **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.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.tsindex 551d0a6bf1d..647071ba968 100644--- 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.ts@@ -3,6 +3,7 @@ import { type LinkedinSettings } from 'src/types/linkedin-settings.type';export const DEFAULT_LINKEDIN_SETTINGS: LinkedinSettings = {importPolicy: 'ALL',areGroupChatsImported: true,+ historyConversationLimit: 20,contactAutoCreationPolicy: 'SENT',isNameMatchingEnabled: true,};diff --git a/packages/twenty-apps/public/linkedin/src/constants/linkedin-history-conversation-limits.constant.ts b/packages/twenty-apps/public/linkedin/src/constants/linkedin-history-conversation-limits.constant.tsnew file mode 100644index 00000000000..8a87c7d01c4--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/constants/linkedin-history-conversation-limits.constant.ts@@ -0,0 +1 @@+export const LINKEDIN_HISTORY_CONVERSATION_LIMITS = [0, 10, 20, 50] as const;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.tsxindex e1f96fa3610..a94e54428e2 100644--- a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportSection.tsx+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinImportSection.tsx@@ -1,14 +1,18 @@import styled from '@emotion/styled';import { t } from 'twenty-sdk/front-component';+import { isDefined } from 'twenty-sdk/utils';import { Section } from 'twenty-ui/components/layout';-import { IconUsers } from 'twenty-ui/icon';+import { IconHistory, IconUsers } from 'twenty-ui/icon';import { themeCssVariables } from 'twenty-ui/theme';+import { LINKEDIN_HISTORY_CONVERSATION_LIMITS } from 'src/constants/linkedin-history-conversation-limits.constant';import { LinkedinImportPolicyIcon } from 'src/front-components/components/LinkedinImportPolicyIcon';import { LinkedinSyncButton } from 'src/front-components/components/LinkedinSyncButton';+import { SettingsOptionCardContentSegmentedControl } from 'src/front-components/components/SettingsOptionCardContentSegmentedControl';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 LinkedinHistoryConversationLimit } from 'src/types/linkedin-history-conversation-limit.type';import { type LinkedinHistoryImportState } from 'src/types/linkedin-history-import-state.type';import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';@@ -21,12 +25,16 @@ const StyledStack = styled.div`type LinkedinImportSectionProps = {importPolicy: LinkedinImportPolicy;areGroupChatsImported: boolean;+ historyConversationLimit: LinkedinHistoryConversationLimit;historyImport: LinkedinHistoryImportState | null;syncProgress: number | undefined;isSyncStarting: boolean;isSyncCancelling: boolean;onChange: (importPolicy: LinkedinImportPolicy) => void;onGroupChatsImportChange: (areGroupChatsImported: boolean) => void;+ onHistoryConversationLimitChange: (+ historyConversationLimit: LinkedinHistoryConversationLimit,+ ) => void;onSync: () => void;onCancelSync: () => void;};@@ -34,12 +42,14 @@ type LinkedinImportSectionProps = {export const LinkedinImportSection = ({importPolicy,areGroupChatsImported,+ historyConversationLimit,historyImport,syncProgress,isSyncStarting,isSyncCancelling,onChange,onGroupChatsImportChange,+ onHistoryConversationLimitChange,onSync,onCancelSync,}: LinkedinImportSectionProps) => (@@ -78,16 +88,39 @@ export const LinkedinImportSection = ({description={t('Groups where at least one member is a contact')}checked={areGroupChatsImported}onChange={onGroupChatsImportChange}+ divider+ />+ <SettingsOptionCardContentSegmentedControl+ Icon={IconHistory}+ title={t('Past conversations')}+ description={t('Most recent conversations imported on sync')}+ options={LINKEDIN_HISTORY_CONVERSATION_LIMITS.map((limit) => ({+ value: String(limit),+ label: limit === 0 ? t('None') : String(limit),+ }))}+ value={String(historyConversationLimit)}+ onChange={(value) => {+ const limit = LINKEDIN_HISTORY_CONVERSATION_LIMITS.find(+ (candidate) => String(candidate) === value,+ );++ if (isDefined(limit)) {+ onHistoryConversationLimitChange(limit);+ }+ }}/></StyledSettingsCard>- <LinkedinSyncButton- historyImport={historyImport}- progress={syncProgress}- isStarting={isSyncStarting}- isCancelling={isSyncCancelling}- onSync={onSync}- onCancel={onCancelSync}- />+ {(historyConversationLimit > 0 ||+ historyImport?.status === 'IMPORTING') && (+ <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/LinkedinSettings.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettings.tsxindex 892315b6095..30da79e9c1a 100644--- a/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettings.tsx+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/LinkedinSettings.tsx@@ -141,6 +141,8 @@ export const LinkedinSettings = () => {setIsSyncStarting(true);try {+ await settingsSaveQueueRef.current;+showView(await postLinkedinSettingsRouteOrThrow({routePath: LINKEDIN_SETTINGS_ROUTE_PATHS.syncHistory,@@ -227,6 +229,7 @@ export const LinkedinSettings = () => {<LinkedinImportSectionimportPolicy={view.settings.importPolicy}areGroupChatsImported={view.settings.areGroupChatsImported}+ historyConversationLimit={view.settings.historyConversationLimit}historyImport={view.historyImport}syncProgress={syncProgress?.runId === view.historyImport?.runId@@ -241,6 +244,9 @@ export const LinkedinSettings = () => {onGroupChatsImportChange={(areGroupChatsImported) =>handleSettingsChange({ areGroupChatsImported })}+ onHistoryConversationLimitChange={(historyConversationLimit) =>+ handleSettingsChange({ historyConversationLimit })+ }onSync={handleSync}onCancelSync={handleCancelSync}/>diff --git a/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionCardContentSegmentedControl.tsx b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionCardContentSegmentedControl.tsxnew file mode 100644index 00000000000..7bc4e2d0b2b--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/front-components/components/SettingsOptionCardContentSegmentedControl.tsx@@ -0,0 +1,71 @@+import styled from '@emotion/styled';+import { useId } from 'react';+import {+ SegmentedControl,+ type SegmentedControlOption,+} from 'twenty-ui/components/input';+import { type IconComponent } from 'twenty-ui/icon';+import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';++import {+ StyledSettingsCardContent,+ StyledSettingsCardDescription,+ StyledSettingsCardIcon,+ StyledSettingsCardTextContainer,+ StyledSettingsCardTitle,+} from 'src/front-components/components/SettingsCardContentBase';+import { SettingsOptionIconCustomizer } from 'src/front-components/components/SettingsOptionIconCustomizer';++const StyledControlContainer = styled.div`+ flex-shrink: 0;+ margin-left: auto;+`;++type SettingsOptionCardContentSegmentedControlProps<TValue extends string> = {+ Icon?: IconComponent;+ title: string;+ description?: string;+ options: SegmentedControlOption<TValue>[];+ value: TValue;+ onChange: (value: TValue) => void;+};++export const SettingsOptionCardContentSegmentedControl = <+ TValue extends string,+>({+ Icon,+ title,+ description,+ options,+ value,+ onChange,+}: SettingsOptionCardContentSegmentedControlProps<TValue>) => {+ const titleId = useId();++ return (+ <StyledSettingsCardContent>+ {Icon && (+ <StyledSettingsCardIcon>+ <SettingsOptionIconCustomizer Icon={Icon} />+ </StyledSettingsCardIcon>+ )}+ <StyledSettingsCardTextContainer>+ <StyledSettingsCardTitle id={titleId}>{title}</StyledSettingsCardTitle>+ {description && (+ <StyledSettingsCardDescription>+ <OverflowingTextWithTooltip text={description} />+ </StyledSettingsCardDescription>+ )}+ </StyledSettingsCardTextContainer>+ <StyledControlContainer>+ <SegmentedControl+ aria-labelledby={titleId}+ size="sm"+ options={options}+ value={value}+ onValueChange={onChange}+ />+ </StyledControlContainer>+ </StyledSettingsCardContent>+ );+};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.tsindex b89181b10b5..85e2600b8df 100644--- 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.ts@@ -256,6 +256,92 @@ describe('linkedinPlanHistoryImportHandler', () => {);});+ it('stores the most recent conversations of a limited run page by page', async () => {+ mocks.kvStore.set(STATE_KEY, { ...RUNNING_STATE, conversationLimit: 50 });+ mockChatPages([20, 20, 5]);++ await expect(linkedinPlanHistoryImportHandler(PAYLOAD)).resolves.toEqual({+ status: 'PLANNED',+ chunkCount: 3,+ });++ expect(+ mocks.listUnipileChats.mock.calls.map(([input]) => input.limit),+ ).toEqual([50, 30, 10]);+ expect(getStoredChatIds(1)).toEqual(buildChatIds(20, 20));+ expect(getStoredChatIds(2)).toEqual(buildChatIds(5, 40));+ expect(getEnqueuedJobIds()).toEqual(['linkedin-history-chunk-run-1-0']);+ expect(mocks.kvStore.get(PLANNING_KEY)).toEqual(+ expect.objectContaining({+ chunkCount: 3,+ plannedConversationCount: 45,+ reportedConversationCount: 45,+ }),+ );+ });++ it('keeps the most recent conversations across every inbox', async () => {+ mocks.kvStore.set(STATE_KEY, { ...RUNNING_STATE, conversationLimit: 10 });+ mocks.listUnipileInboxIds.mockResolvedValue(['inbox-1', 'inbox-2']);+ mocks.listUnipileChats.mockImplementation(async ({ inboxId, limit }) => ({+ items: Array.from({ length: limit }, (_, index) => ({+ id: `${inboxId}-chat-${index}`,+ last_message_timestamp: new Date(+ Date.UTC(2026, 0, inboxId === 'inbox-1' ? 1 : 2) - index * 60_000,+ ).toISOString(),+ })),+ nextCursor: 'more',+ }));++ await linkedinPlanHistoryImportHandler(PAYLOAD);++ expect(+ mocks.listUnipileChats.mock.calls.map(([input]) => input.inboxId),+ ).toEqual(['inbox-1', 'inbox-2']);+ expect(getStoredChatIds(0)).toEqual(+ Array.from({ length: 10 }, (_, index) => `inbox-2-chat-${index}`),+ );+ });++ it('stops waiting on Unipile before the planning job runs out of time', async () => {+ vi.useFakeTimers({ now: 0 });+ mocks.kvStore.set(STATE_KEY, { ...RUNNING_STATE, conversationLimit: 20 });+ mockChatPages([5]);++ await linkedinPlanHistoryImportHandler(PAYLOAD);++ expect(mocks.listUnipileChats).toHaveBeenCalledWith(+ expect.objectContaining({ deadlineAtMs: 10 * 60 * 1000 }),+ );+ });++ it('lists a limited run again once the rate limit resets', async () => {+ mocks.kvStore.set(STATE_KEY, { ...RUNNING_STATE, conversationLimit: 20 });+ mocks.listUnipileChats.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: undefined,+ plannedChunkCount: 0,+ }),+ },+ ],+ delayMs: (2 * 60 * 60 + 1) * 1000,+ }),+ );+ });+it('records a run with no conversations as fully listed', async () => {mockChatPages([0]);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.tsindex 43cf37e0b54..760ed81e36a 100644--- 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.ts@@ -97,6 +97,32 @@ describe('linkedinSyncHistoryHandler', () => {expect(mocks.enqueueJobs).toHaveBeenCalledTimes(1);});+ it('limits the run to the past conversations the member chose', async () => {+ mocks.kvStore.set('linkedin-settings:connection-id', {+ historyConversationLimit: 50,+ });++ await syncHistory();++ expect(mocks.kvStore.get(HISTORY_KEY)).toEqual(+ expect.objectContaining({ status: 'IMPORTING', conversationLimit: 50 }),+ );+ });++ it('imports no past conversation when the member chose none', async () => {+ mocks.kvStore.set('linkedin-settings:connection-id', {+ historyConversationLimit: 0,+ });+ setHistoryImport('COMPLETED');++ await syncHistory();++ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ expect(mocks.kvStore.get(HISTORY_KEY)).toEqual(+ expect.objectContaining({ runId: 'run-1', status: 'COMPLETED' }),+ );+ });+it('leaves a running import alone', async () => {setHistoryImport('IMPORTING');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.tsindex 49247435abb..b9ede5349fb 100644--- 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.ts@@ -72,6 +72,7 @@ describe('linkedinUpdateSettingsHandler', () => {contactAutoCreationPolicy: 'NONE',isNameMatchingEnabled: 'yes',importPolicy: 'SOME',+ historyConversationLimit: 30,});expect(view).toEqual(@@ -80,6 +81,7 @@ describe('linkedinUpdateSettingsHandler', () => {settings: {importPolicy: 'ALL',areGroupChatsImported: true,+ historyConversationLimit: 20,contactAutoCreationPolicy: 'NONE',isNameMatchingEnabled: true,visibility: 'METADATA',@@ -93,6 +95,22 @@ describe('linkedinUpdateSettingsHandler', () => {expect(mocks.enqueueJobs).not.toHaveBeenCalled();});+ it.each([0, 10, 20, 50])(+ 'saves %i past conversations to import',+ async (historyConversationLimit) => {+ const view = await updateSettings({ historyConversationLimit });++ expect(view).toEqual(+ expect.objectContaining({+ settings: expect.objectContaining({ historyConversationLimit }),+ }),+ );+ expect(mocks.kvStore.get('linkedin-settings:connection-id')).toEqual(+ expect.objectContaining({ historyConversationLimit }),+ );+ },+ );+it('applies the visibility to the message channel instead of the kv settings', async () => {await updateSettings({ visibility: 'SHARE_EVERYTHING' });@@ -109,6 +127,7 @@ describe('linkedinUpdateSettingsHandler', () => {[{ importPolicy: 'ALL' }],[{ importPolicy: 'CONTACTS_ONLY' }],[{ areGroupChatsImported: true }],+ [{ historyConversationLimit: 50 }],])('leaves importing to the Sync button when saving %o', async (update) => {setHistoryImport('CONTACTS_ONLY');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.tsindex 0f28feadadb..9e743ecf9b4 100644--- 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.ts@@ -24,6 +24,7 @@ import {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 { listMostRecentUnipileChats } from 'src/unipile/utils/list-most-recent-unipile-chats.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';@@ -159,9 +160,54 @@ const finishPlanning = async ({return { status: 'PLANNED', chunkCount };};-const planHistoryImport = async (- payload: LinkedinPlanHistoryImportJobPayload,-): Promise<LinkedinPlanHistoryImportResult> => {+const planLimitedHistoryImport = async ({+ payload,+ chats,+}: {+ payload: LinkedinPlanHistoryImportJobPayload;+ chats: UnipileChat[];+}): Promise<LinkedinPlanHistoryImportResult> => {+ let chunkCount = 0;++ for (+ let chunkStart = 0;+ chunkStart < chats.length;+ chunkStart += LINKEDIN_HISTORY_IMPORT_CHATS_PER_JOB+ ) {+ const chunkChats = chats.slice(+ chunkStart,+ chunkStart + LINKEDIN_HISTORY_IMPORT_CHATS_PER_JOB,+ );++ if (+ !(await planChunk({+ payload,+ chunkIndex: chunkCount,+ chats: chunkChats,+ conversationCount: chunkStart + chunkChats.length,+ reportedConversationCount: chats.length,+ }))+ ) {+ return { status: 'CANCELLED' };+ }++ chunkCount += 1;+ }++ return finishPlanning({+ payload,+ chunkCount,+ conversationCount: chats.length,+ });+};++const planHistoryImport = async ({+ payload,+ conversationLimit,+}: {+ payload: LinkedinPlanHistoryImportJobPayload;+ conversationLimit: number | undefined;+}): Promise<LinkedinPlanHistoryImportResult> => {const { connectedAccountId, runId } = payload;const startedAt = Date.now();const connection = await getConnection(connectedAccountId);@@ -220,6 +266,22 @@ const planHistoryImport = async (return inboxIds;}+ if (isDefined(conversationLimit)) {+ const chats = await pauseOnRateLimit(() =>+ listMostRecentUnipileChats({+ accountId: unipileAccountId,+ inboxIds,+ limit: conversationLimit,+ deadlineAtMs:+ startedAt + LINKEDIN_PLAN_HISTORY_IMPORT_TIME_BUDGET_MILLISECONDS,+ }),+ );++ return Array.isArray(chats)+ ? planLimitedHistoryImport({ payload, chats })+ : chats;+ }+while (inboxIndex < inboxIds.length) {if (Date.now() - startedAt >@@ -292,12 +354,17 @@ export const linkedinPlanHistoryImportHandler = async (payload: LinkedinPlanHistoryImportJobPayload,context?: Pick<LogicFunctionExecutionContext, 'retryCount' | 'maxRetries'>,): Promise<LinkedinPlanHistoryImportResult> => {- if ((await getActiveLinkedinHistoryImportState(payload)) === null) {+ const state = await getActiveLinkedinHistoryImportState(payload);++ if (state === null) {return { status: 'CANCELLED' };}try {- return await planHistoryImport(payload);+ return await planHistoryImport({+ payload,+ conversationLimit: state.conversationLimit,+ });} catch (error) {return failLinkedinHistoryImportJob({error,@@ -323,7 +390,7 @@ 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.',+ 'Lists the most recent past LinkedIn conversations of a connection across its inboxes, up to the limit of the run, 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.tsindex 8666293fa87..9d8263ba375 100644--- 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.ts@@ -24,12 +24,14 @@ export const linkedinSyncHistoryHandler = async (const historyImport = await refreshLinkedinHistoryImportState(connection.id);if (historyImport?.status !== 'IMPORTING') {- const { importPolicy } = await getLinkedinSettings(connection.id);-- await startLinkedinHistoryImport({- connectedAccountId: connection.id,- importPolicy,- });+ const settings = await getLinkedinSettings(connection.id);++ if (settings.historyConversationLimit > 0) {+ await startLinkedinHistoryImport({+ connectedAccountId: connection.id,+ settings,+ });+ }}return buildLinkedinSettingsView(connection);@@ -39,7 +41,7 @@ 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.',+ 'Starts importing the most recent past LinkedIn conversations of the requesting member connection, up to the number their settings allow.',timeoutSeconds: 15,handler: linkedinSyncHistoryHandler,httpRouteTriggerSettings: {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.tsindex c8b01eb7259..16ef1237d65 100644--- 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.ts@@ -1,5 +1,6 @@import { isBoolean } from '@sniptt/guards';+import { LINKEDIN_HISTORY_CONVERSATION_LIMITS } from 'src/constants/linkedin-history-conversation-limits.constant';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';@@ -15,8 +16,8 @@ const CONTACT_AUTO_CREATION_POLICIES: LinkedinContactAutoCreationPolicy[] = [const VISIBILITIES: LinkedinVisibility[] = ['SHARE_EVERYTHING', 'METADATA'];-const isOneOf = <TValue extends string>(- values: TValue[],+const isOneOf = <TValue extends string | number>(+ values: readonly TValue[],value: unknown,): value is TValue => values.some((candidate) => candidate === value);@@ -41,6 +42,15 @@ export const parseLinkedinSettingsUpdate = (update.areGroupChatsImported = body.areGroupChatsImported;}+ if (+ isOneOf(+ LINKEDIN_HISTORY_CONVERSATION_LIMITS,+ body?.historyConversationLimit,+ )+ ) {+ update.historyConversationLimit = body.historyConversationLimit;+ }+if (isBoolean(body?.isNameMatchingEnabled)) {update.isNameMatchingEnabled = body.isNameMatchingEnabled;}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.tsindex aa4c4dc6f73..0d75004d07a 100644--- 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.ts@@ -4,20 +4,21 @@ import { LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER } from 'src/constantsimport { 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';+import { type LinkedinSettings } from 'src/types/linkedin-settings.type';const LINKEDIN_PLAN_HISTORY_IMPORT_RETRY_LIMIT = 3;export const startLinkedinHistoryImport = async ({connectedAccountId,- importPolicy,+ settings,}: {connectedAccountId: string;- importPolicy: LinkedinImportPolicy;+ settings: Pick<LinkedinSettings, 'importPolicy' | 'historyConversationLimit'>;}): Promise<LinkedinHistoryImportState> => {const state: LinkedinHistoryImportState = {runId: crypto.randomUUID(),- importPolicy,+ importPolicy: settings.importPolicy,+ conversationLimit: settings.historyConversationLimit,status: 'IMPORTING',importedConversationCount: 0,processedConversationCount: 0,diff --git a/packages/twenty-apps/public/linkedin/src/types/linkedin-history-conversation-limit.type.ts b/packages/twenty-apps/public/linkedin/src/types/linkedin-history-conversation-limit.type.tsnew file mode 100644index 00000000000..a4ae011b10f--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-history-conversation-limit.type.ts@@ -0,0 +1,4 @@+import { type LINKEDIN_HISTORY_CONVERSATION_LIMITS } from 'src/constants/linkedin-history-conversation-limits.constant';++export type LinkedinHistoryConversationLimit =+ (typeof LINKEDIN_HISTORY_CONVERSATION_LIMITS)[number];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.tsindex 45943be453e..0e99af4b9d2 100644--- 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.ts@@ -1,9 +1,11 @@+import { type LinkedinHistoryConversationLimit } from 'src/types/linkedin-history-conversation-limit.type';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;+ conversationLimit?: LinkedinHistoryConversationLimit;status: 'IMPORTING' | 'COMPLETED' | 'FAILED' | 'CANCELLED';importedConversationCount: number;processedConversationCount: number;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.tsindex b3f193aea9e..29d4b478c4f 100644--- a/packages/twenty-apps/public/linkedin/src/types/linkedin-settings.type.ts+++ b/packages/twenty-apps/public/linkedin/src/types/linkedin-settings.type.ts@@ -1,9 +1,11 @@import { type LinkedinContactAutoCreationPolicy } from 'src/types/linkedin-contact-auto-creation-policy.type';+import { type LinkedinHistoryConversationLimit } from 'src/types/linkedin-history-conversation-limit.type';import { type LinkedinImportPolicy } from 'src/types/linkedin-import-policy.type';export type LinkedinSettings = {importPolicy: LinkedinImportPolicy;areGroupChatsImported: boolean;+ historyConversationLimit: LinkedinHistoryConversationLimit;contactAutoCreationPolicy: LinkedinContactAutoCreationPolicy;isNameMatchingEnabled: boolean;};diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/list-most-recent-unipile-chats.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-most-recent-unipile-chats.util.tsnew file mode 100644index 00000000000..fa9236404f5--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/list-most-recent-unipile-chats.util.ts@@ -0,0 +1,71 @@+import { isNonEmptyString } from '@sniptt/guards';++import { type UnipileChat } from 'src/unipile/types/unipile-chat.type';+import { listUnipileChats } from 'src/unipile/utils/list-unipile-chats.util';+import { sortUnipileChatsByLastMessage } from 'src/unipile/utils/sort-unipile-chats-by-last-message.util';++const listMostRecentInboxChats = async ({+ accountId,+ inboxId,+ limit,+ deadlineAtMs,+}: {+ accountId: string;+ inboxId: string;+ limit: number;+ deadlineAtMs?: number;+}): Promise<UnipileChat[]> => {+ const chats: UnipileChat[] = [];+ let cursor: string | undefined;++ while (chats.length < limit) {+ const page = await listUnipileChats({+ accountId,+ inboxId,+ cursor,+ limit: limit - chats.length,+ deadlineAtMs,+ });++ chats.push(...page.items);++ if (+ page.items.length === 0 ||+ !isNonEmptyString(page.nextCursor) ||+ page.nextCursor === cursor+ ) {+ break;+ }++ cursor = page.nextCursor;+ }++ return chats;+};++export const listMostRecentUnipileChats = async ({+ accountId,+ inboxIds,+ limit,+ deadlineAtMs,+}: {+ accountId: string;+ inboxIds: string[];+ limit: number;+ deadlineAtMs?: number;+}): Promise<UnipileChat[]> => {+ const chats: UnipileChat[] = [];++ for (const inboxId of inboxIds) {+ chats.push(+ ...(await listMostRecentInboxChats({+ accountId,+ inboxId,+ limit,+ deadlineAtMs,+ })),+ );+ }++ return sortUnipileChatsByLastMessage(chats).slice(0, limit);+};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.tsindex c9fb017b325..1b8b674d25c 100644--- 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.ts@@ -10,18 +10,23 @@ export const listUnipileChats = async ({inboxId,cursor,limit,+ deadlineAtMs,}: {accountId: string;inboxId: string;cursor?: string;limit: number;+ deadlineAtMs?: 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 },- }),+ const { data } = await requestUnipile(+ 'list inbox chats',+ () =>+ new UnipileMessaging().getInboxChatsList({+ ...getUnipileRequestOptions(),+ path: { account_id: accountId, inbox_id: inboxId },+ query: { cursor, limit },+ }),+ { deadlineAtMs },);return {