Skip to content

The open alternative to Salesforce, designed for AI.

LinkedIn app: skip profile lookups that cannot change the outcome (#29509)

martmull2d301bcf637c
diff --git a/packages/twenty-apps/public/linkedin/README.md b/packages/twenty-apps/public/linkedin/README.md
index 6d2d32ba1b2..36e52d9af62 100644
--- a/packages/twenty-apps/public/linkedin/README.md
+++ b/packages/twenty-apps/public/linkedin/README.md
@@ -20,6 +20,7 @@
- **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.
+- **Contacts only and group chats start from names.** There, a participant's LinkedIn profile is first looked up only when a Person has the same first and last name, so a contact saved under another name is not recognized until their LinkedIn URL is known. Once a contact is found and contact auto-creation applies, the other participants are looked up too, so they can be created.
- **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/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
index e269cb0ec45..018db04bb4e 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
@@ -216,6 +216,7 @@ describe('linkedinHandleWebhookEventHandler', () => {
).resolves.toEqual({ handled: true });
expect(mocks.ingestMessages).toHaveBeenCalledOnce();
+ expect(mocks.getUnipileUser).not.toHaveBeenCalled();
});
it('ingests a sent message to the chat counterpart public profile URL', 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.ts
index 623da976870..65a48c2adf6 100644
--- 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.ts
@@ -143,8 +143,18 @@ describe('linkedinImportHistoryHandler', () => {
chatId: 'chat-2',
});
expect(mocks.ingestLinkedinMessages).toHaveBeenCalledWith(
- expect.objectContaining({ unipileAccountId: 'acc_1' }),
+ expect.objectContaining({
+ unipileAccountId: 'acc_1',
+ counterparts: [LISTED_CHAT_WITH_ATTENDEE.user],
+ }),
);
+ expect(
+ new Set(
+ mocks.ingestLinkedinMessages.mock.calls.map(
+ ([input]) => input.resolveCounterpart,
+ ),
+ ).size,
+ ).toBe(1);
expect(mocks.kvStore.get(PROGRESS_KEY)).toEqual({
completedChunkCount: 3,
completedConversationCount: 42,
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.ts
index 7311775118b..f3cfe39f194 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
@@ -8,11 +8,11 @@ import { isDefined } from 'twenty-sdk/utils';
import { LINKEDIN_ATTACHMENT_DEADLINE_MARGIN_MILLISECONDS } from 'src/constants/linkedin-attachment-deadline-margin-milliseconds.constant';
import { LINKEDIN_HANDLE_WEBHOOK_EVENT_TIMEOUT_SECONDS } from 'src/constants/linkedin-handle-webhook-event-timeout-seconds.constant';
import { LINKEDIN_HANDLE_WEBHOOK_EVENT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { createLinkedinCounterpartResolver } from 'src/logic-functions/utils/create-linkedin-counterpart-resolver.util';
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 { 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 UnipileWebhookEvent } from 'src/unipile/types/unipile-webhook-event.type';
import { getUnipileChat } from 'src/unipile/utils/get-unipile-chat.util';
@@ -57,11 +57,8 @@ const ingestUnipileMessage = async ({
channel,
settings,
chat,
- counterparts: await Promise.all(
- counterparts.map((user) =>
- withLinkedinPublicIdentifier({ unipileAccountId, user }),
- ),
- ),
+ counterparts,
+ resolveCounterpart: createLinkedinCounterpartResolver(unipileAccountId),
messages: [message],
});
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.ts
index f75b8b9e705..4579e35ee6c 100644
--- 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.ts
@@ -11,9 +11,11 @@ import { isDefined } from 'twenty-sdk/utils';
import { LINKEDIN_ATTACHMENT_DEADLINE_MARGIN_MILLISECONDS } from 'src/constants/linkedin-attachment-deadline-margin-milliseconds.constant';
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 LinkedinCounterpartResolver } from 'src/logic-functions/types/linkedin-counterpart-resolver.type';
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 { createLinkedinCounterpartResolver } from 'src/logic-functions/utils/create-linkedin-counterpart-resolver.util';
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';
@@ -26,7 +28,6 @@ import {
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';
@@ -189,11 +190,13 @@ export const linkedinImportHistoryHandler = async (
unipileAccountId,
channel,
settings,
+ resolveCounterpart,
}: {
listedChat: UnipileChat;
unipileAccountId: string;
channel: AppMessageChannel;
settings: LinkedinSettings;
+ resolveCounterpart: LinkedinCounterpartResolver;
}): Promise<void> => {
const chat =
getLinkedinChatCounterparts(listedChat).length > 0
@@ -202,11 +205,7 @@ export const linkedinImportHistoryHandler = async (
accountId: unipileAccountId,
chatId: listedChat.id,
});
- const counterparts = await Promise.all(
- getLinkedinChatCounterparts(chat).map((user) =>
- withLinkedinPublicIdentifier({ unipileAccountId, user }),
- ),
- );
+ const counterparts = getLinkedinChatCounterparts(chat);
const seenCursors = new Set<string>();
do {
@@ -229,6 +228,7 @@ export const linkedinImportHistoryHandler = async (
settings,
chat,
counterparts,
+ resolveCounterpart,
messages: page.items,
});
@@ -281,9 +281,17 @@ export const linkedinImportHistoryHandler = async (
}
const settings = await getLinkedinSettings(connectedAccountId);
+ const resolveCounterpart =
+ createLinkedinCounterpartResolver(unipileAccountId);
for (const listedChat of chats.slice(processedChatCount)) {
- await importChat({ listedChat, unipileAccountId, channel, settings });
+ await importChat({
+ listedChat,
+ unipileAccountId,
+ channel,
+ settings,
+ resolveCounterpart,
+ });
}
} catch (error) {
if (error instanceof LinkedinImportHistoryHandOff) {
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-counterpart-resolver.type.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-counterpart-resolver.type.ts
new file mode 100644
index 00000000000..57f8283a490
--- /dev/null
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/types/linkedin-counterpart-resolver.type.ts
@@ -0,0 +1,6 @@
+import { type UnipileUser } from 'src/unipile/types/unipile-user.type';
+
+export type LinkedinCounterpartResolver = (input: {
+ user: UnipileUser;
+ shouldLookUp?: () => Promise<boolean>;
+}) => Promise<UnipileUser>;
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/create-linkedin-counterpart-resolver.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/create-linkedin-counterpart-resolver.util.test.ts
new file mode 100644
index 00000000000..c7019e01281
--- /dev/null
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/create-linkedin-counterpart-resolver.util.test.ts
@@ -0,0 +1,106 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ withLinkedinPublicIdentifier: vi.fn(),
+}));
+
+vi.mock(
+ 'src/logic-functions/utils/with-linkedin-public-identifier.util',
+ () => ({
+ withLinkedinPublicIdentifier: mocks.withLinkedinPublicIdentifier,
+ }),
+);
+
+const { createLinkedinCounterpartResolver } =
+ await import('src/logic-functions/utils/create-linkedin-counterpart-resolver.util');
+
+const { UnipileRateLimitError } =
+ await import('src/unipile/utils/request-unipile.util');
+
+const DELETED_MEMBER = { id: 'ACoGONE', display_name: 'LinkedIn Member' };
+
+const askBeforeReturning =
+ (result: typeof DELETED_MEMBER) =>
+ async ({ shouldLookUp }: { shouldLookUp?: () => Promise<boolean> }) => {
+ await shouldLookUp?.();
+
+ return result;
+ };
+
+describe('createLinkedinCounterpartResolver', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('looks up each profile once, even one LinkedIn cannot resolve', async () => {
+ mocks.withLinkedinPublicIdentifier.mockResolvedValue(DELETED_MEMBER);
+ const resolveCounterpart = createLinkedinCounterpartResolver('acc_1');
+
+ await resolveCounterpart({ user: DELETED_MEMBER });
+
+ await expect(resolveCounterpart({ user: DELETED_MEMBER })).resolves.toEqual(
+ DELETED_MEMBER,
+ );
+ expect(mocks.withLinkedinPublicIdentifier).toHaveBeenCalledExactlyOnceWith({
+ unipileAccountId: 'acc_1',
+ user: DELETED_MEMBER,
+ shouldLookUp: undefined,
+ });
+ });
+
+ it('looks up a profile whose lookup was declined once it is wanted', async () => {
+ const resolvedMember = { ...DELETED_MEMBER, public_identifier: 'member' };
+
+ mocks.withLinkedinPublicIdentifier
+ .mockImplementationOnce(askBeforeReturning(DELETED_MEMBER))
+ .mockResolvedValueOnce(resolvedMember);
+ const resolveCounterpart = createLinkedinCounterpartResolver('acc_1');
+
+ await resolveCounterpart({
+ user: DELETED_MEMBER,
+ shouldLookUp: async () => false,
+ });
+
+ await expect(resolveCounterpart({ user: DELETED_MEMBER })).resolves.toEqual(
+ resolvedMember,
+ );
+ await expect(resolveCounterpart({ user: DELETED_MEMBER })).resolves.toEqual(
+ resolvedMember,
+ );
+ expect(mocks.withLinkedinPublicIdentifier).toHaveBeenCalledTimes(2);
+ });
+
+ it('looks up once a profile LinkedIn could not resolve after an allowed lookup', async () => {
+ mocks.withLinkedinPublicIdentifier.mockImplementation(
+ askBeforeReturning(DELETED_MEMBER),
+ );
+ const resolveCounterpart = createLinkedinCounterpartResolver('acc_1');
+
+ await resolveCounterpart({
+ user: DELETED_MEMBER,
+ shouldLookUp: async () => true,
+ });
+ await resolveCounterpart({
+ user: DELETED_MEMBER,
+ shouldLookUp: async () => true,
+ });
+
+ expect(mocks.withLinkedinPublicIdentifier).toHaveBeenCalledOnce();
+ });
+
+ it('looks up a profile again after LinkedIn rate limited it', async () => {
+ mocks.withLinkedinPublicIdentifier
+ .mockRejectedValueOnce(
+ new UnipileRateLimitError('Retry in 1 hour.', 3601),
+ )
+ .mockResolvedValueOnce(DELETED_MEMBER);
+ const resolveCounterpart = createLinkedinCounterpartResolver('acc_1');
+
+ await expect(resolveCounterpart({ user: DELETED_MEMBER })).rejects.toThrow(
+ 'Retry in 1 hour.',
+ );
+ await expect(resolveCounterpart({ user: DELETED_MEMBER })).resolves.toEqual(
+ DELETED_MEMBER,
+ );
+ });
+});
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/has-person-named-like-linkedin-user.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/has-person-named-like-linkedin-user.util.test.ts
new file mode 100644
index 00000000000..5cb9e8858bc
--- /dev/null
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/has-person-named-like-linkedin-user.util.test.ts
@@ -0,0 +1,50 @@
+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 { hasPersonNamedLikeLinkedinUser } =
+ await import('src/logic-functions/utils/has-person-named-like-linkedin-user.util');
+
+describe('hasPersonNamedLikeLinkedinUser', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.query.mockResolvedValue({ people: { edges: [] } });
+ });
+
+ it('finds a Person with the first and last name of the user', async () => {
+ mocks.query.mockResolvedValue({
+ people: { edges: [{ node: { id: 'priya-id' } }] },
+ });
+
+ await expect(
+ hasPersonNamedLikeLinkedinUser({ display_name: 'Priya Nair' }),
+ ).resolves.toBe(true);
+ expect(mocks.query.mock.calls[0][0].people.__args.filter).toEqual({
+ name: {
+ firstName: { ilike: 'Priya' },
+ lastName: { ilike: 'Nair' },
+ },
+ });
+ });
+
+ it('finds nobody when no Person has that name', async () => {
+ await expect(
+ hasPersonNamedLikeLinkedinUser({ display_name: 'Priya Nair' }),
+ ).resolves.toBe(false);
+ });
+
+ it('cannot rule anyone out for a user without a last name', async () => {
+ await expect(
+ hasPersonNamedLikeLinkedinUser({ display_name: 'Priya' }),
+ ).resolves.toBe(true);
+ expect(mocks.query).not.toHaveBeenCalled();
+ });
+});
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.ts
index 0a94aef046c..4a5037b3e1b 100644
--- 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.ts
@@ -1,3 +1,4 @@
+import { isDefined } from 'twenty-sdk/utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_LINKEDIN_SETTINGS } from 'src/constants/default-linkedin-settings.constant';
@@ -9,6 +10,8 @@ const mocks = vi.hoisted(() => ({
matchLinkedinParticipantPersonId: vi.fn(),
createLinkedinPerson: vi.fn(),
importLinkedinMessageAttachments: vi.fn(),
+ resolveCounterpart: vi.fn(),
+ hasPersonNamedLikeLinkedinUser: vi.fn(),
}));
vi.mock('twenty-sdk/logic-function', () => ({
@@ -26,6 +29,13 @@ vi.mock('src/logic-functions/utils/create-linkedin-person.util', () => ({
createLinkedinPerson: mocks.createLinkedinPerson,
}));
+vi.mock(
+ 'src/logic-functions/utils/has-person-named-like-linkedin-user.util',
+ () => ({
+ hasPersonNamedLikeLinkedinUser: mocks.hasPersonNamedLikeLinkedinUser,
+ }),
+);
+
vi.mock(
'src/logic-functions/utils/import-linkedin-message-attachments.util',
() => ({
@@ -56,6 +66,34 @@ const buildMessage = (isSender: boolean): UnipileMessage => ({
provider: 'linkedin',
});
+const UNRESOLVED_PRIYA = { id: PRIYA.id, display_name: PRIYA.display_name };
+
+const SAM = { id: 'ACoSAM', display_name: 'Sam Okafor' };
+
+const resolveCounterpartsLikeUnipile = (): string[] => {
+ const lookedUpUserIds: string[] = [];
+
+ mocks.resolveCounterpart.mockImplementation(
+ async ({
+ user,
+ shouldLookUp,
+ }: {
+ user: UnipileUser;
+ shouldLookUp?: () => Promise<boolean>;
+ }) => {
+ if (isDefined(shouldLookUp) && !(await shouldLookUp())) {
+ return user;
+ }
+
+ lookedUpUserIds.push(user.id);
+
+ return { ...user, public_identifier: user.id.toLowerCase() };
+ },
+ );
+
+ return lookedUpUserIds;
+};
+
const ONE_TO_ONE_CHAT = {
id: 'chat-1',
name: 'Priya Nair',
@@ -90,6 +128,7 @@ const ingest = ({
settings,
chat,
counterparts,
+ resolveCounterpart: mocks.resolveCounterpart,
messages,
});
@@ -104,6 +143,114 @@ describe('ingestLinkedinMessages', () => {
mocks.matchLinkedinParticipantPersonId.mockResolvedValue(undefined);
mocks.createLinkedinPerson.mockResolvedValue('created-id');
mocks.importLinkedinMessageAttachments.mockResolvedValue(0);
+ mocks.resolveCounterpart.mockImplementation(
+ async ({ user }: { user: UnipileUser }) => user,
+ );
+ mocks.hasPersonNamedLikeLinkedinUser.mockResolvedValue(false);
+ });
+
+ it('looks up the counterpart of an All chats conversation without checking names', async () => {
+ const lookedUpUserIds = resolveCounterpartsLikeUnipile();
+
+ await ingest({ counterparts: [UNRESOLVED_PRIYA] });
+
+ expect(lookedUpUserIds).toEqual([PRIYA.id]);
+ expect(mocks.hasPersonNamedLikeLinkedinUser).not.toHaveBeenCalled();
+ });
+
+ it('looks up nobody in a Contacts only chat with someone no Person is named after', async () => {
+ const lookedUpUserIds = resolveCounterpartsLikeUnipile();
+
+ await expect(
+ ingest({
+ settings: {
+ ...DEFAULT_LINKEDIN_SETTINGS,
+ importPolicy: 'CONTACTS_ONLY',
+ },
+ counterparts: [UNRESOLVED_PRIYA],
+ }),
+ ).resolves.toMatchObject({ skippedReason: 'NO_CONTACT' });
+ expect(lookedUpUserIds).toEqual([]);
+ });
+
+ it('looks up only the group members a Person is named after', async () => {
+ const lookedUpUserIds = resolveCounterpartsLikeUnipile();
+
+ mocks.hasPersonNamedLikeLinkedinUser.mockImplementation(
+ async (user: UnipileUser) => user.id === PRIYA.id,
+ );
+ mocks.matchLinkedinParticipantPersonId.mockImplementation(
+ async ({ user }: { user: UnipileUser }) =>
+ user.public_identifier === 'acopriya' ? 'priya-id' : undefined,
+ );
+
+ await expect(
+ ingest({
+ chat: GROUP_CHAT,
+ counterparts: [UNRESOLVED_PRIYA, SAM],
+ messages: [buildMessage(false)],
+ }),
+ ).resolves.toMatchObject({ ingestedMessageCount: 1 });
+ expect(lookedUpUserIds).toEqual([PRIYA.id]);
+ });
+
+ it('looks up the other group members to create them once a contact is in the chat', async () => {
+ const lookedUpUserIds = resolveCounterpartsLikeUnipile();
+
+ mocks.hasPersonNamedLikeLinkedinUser.mockImplementation(
+ async (user: UnipileUser) => user.id === PRIYA.id,
+ );
+ mocks.matchLinkedinParticipantPersonId.mockImplementation(
+ async ({ user }: { user: UnipileUser }) =>
+ user.public_identifier === 'acopriya' ? 'priya-id' : undefined,
+ );
+
+ await ingest({ chat: GROUP_CHAT, counterparts: [UNRESOLVED_PRIYA, SAM] });
+
+ expect(lookedUpUserIds).toEqual([PRIYA.id, SAM.id]);
+ expect(mocks.createLinkedinPerson).toHaveBeenCalledExactlyOnceWith({
+ firstName: 'Sam',
+ lastName: 'Okafor',
+ handle: 'https://www.linkedin.com/in/acosam',
+ });
+ });
+
+ it('links a group member found by their profile URL instead of creating them', async () => {
+ resolveCounterpartsLikeUnipile();
+
+ mocks.hasPersonNamedLikeLinkedinUser.mockImplementation(
+ async (user: UnipileUser) => user.id === PRIYA.id,
+ );
+ mocks.matchLinkedinParticipantPersonId.mockImplementation(
+ async ({ user }: { user: UnipileUser }) =>
+ ({ acopriya: 'priya-id', acosam: 'sam-id' })[
+ user.public_identifier ?? ''
+ ],
+ );
+
+ await expect(
+ ingest({ chat: GROUP_CHAT, counterparts: [UNRESOLVED_PRIYA, SAM] }),
+ ).resolves.toMatchObject({ matchedPersonCount: 2, createdPersonCount: 0 });
+ expect(mocks.createLinkedinPerson).not.toHaveBeenCalled();
+ expect(ingestedParticipantPersonIds()).toContain('sam-id');
+ });
+
+ it('ingests under the public profile URL of the resolved counterpart', async () => {
+ mocks.resolveCounterpart.mockResolvedValue(PRIYA);
+
+ await ingest({
+ counterparts: [{ ...PRIYA, public_identifier: undefined }],
+ });
+
+ expect(
+ mocks.ingestMessages.mock.calls[0][0].messages[0].participants[1].handle,
+ ).toBe('https://www.linkedin.com/in/priya-nair');
+ });
+
+ it('looks up no profile for a page with no message to import', async () => {
+ await ingest({ messages: [{ ...buildMessage(false), is_event: true }] });
+
+ expect(mocks.resolveCounterpart).not.toHaveBeenCalled();
});
it('attaches the matched person to the participant', async () => {
@@ -153,6 +300,7 @@ describe('ingestLinkedinMessages', () => {
}),
).resolves.toMatchObject({ ingestedMessageCount: 0 });
expect(mocks.matchLinkedinParticipantPersonId).not.toHaveBeenCalled();
+ expect(mocks.resolveCounterpart).not.toHaveBeenCalled();
});
it('creates a person for an unknown profile the member messaged', async () => {
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.ts
index c77933d1b23..15ae2493221 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
@@ -43,6 +43,35 @@ describe('withLinkedinPublicIdentifier', () => {
expect(mocks.getUnipileUser).not.toHaveBeenCalled();
});
+ it('leaves an uncached user as is when the caller declines the lookup', async () => {
+ const shouldLookUp = vi.fn().mockResolvedValue(false);
+
+ await expect(
+ withLinkedinPublicIdentifier({
+ unipileAccountId: 'acc_1',
+ user: DAPHNE,
+ shouldLookUp,
+ }),
+ ).resolves.toBe(DAPHNE);
+ expect(shouldLookUp).toHaveBeenCalledOnce();
+ expect(mocks.getUnipileUser).not.toHaveBeenCalled();
+ });
+
+ it('uses the cache without asking whether to look up', async () => {
+ const shouldLookUp = vi.fn().mockResolvedValue(false);
+
+ mocks.kvGet.mockResolvedValue('daphne-muller');
+
+ await expect(
+ withLinkedinPublicIdentifier({
+ unipileAccountId: 'acc_1',
+ user: DAPHNE,
+ shouldLookUp,
+ }),
+ ).resolves.toEqual({ ...DAPHNE, public_identifier: 'daphne-muller' });
+ expect(shouldLookUp).not.toHaveBeenCalled();
+ });
+
it('reads a cached public identifier without calling Unipile', async () => {
mocks.kvGet.mockResolvedValue('daphne-muller');
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-person-name-filter.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-person-name-filter.util.ts
new file mode 100644
index 00000000000..c4a0438ff82
--- /dev/null
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/build-person-name-filter.util.ts
@@ -0,0 +1,14 @@
+import { escapeSqlLikePattern } from 'src/logic-functions/utils/escape-sql-like-pattern.util';
+
+export const buildPersonNameFilter = ({
+ firstName,
+ lastName,
+}: {
+ firstName: string;
+ lastName: string;
+}) => ({
+ name: {
+ firstName: { ilike: escapeSqlLikePattern(firstName) },
+ lastName: { ilike: escapeSqlLikePattern(lastName) },
+ },
+});
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/create-linkedin-counterpart-resolver.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/create-linkedin-counterpart-resolver.util.ts
new file mode 100644
index 00000000000..ada7cbfcf27
--- /dev/null
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/create-linkedin-counterpart-resolver.util.ts
@@ -0,0 +1,38 @@
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type LinkedinCounterpartResolver } from 'src/logic-functions/types/linkedin-counterpart-resolver.type';
+import { withLinkedinPublicIdentifier } from 'src/logic-functions/utils/with-linkedin-public-identifier.util';
+import { type UnipileUser } from 'src/unipile/types/unipile-user.type';
+
+export const createLinkedinCounterpartResolver = (
+ unipileAccountId: string,
+): LinkedinCounterpartResolver => {
+ const resolvedCounterpartById = new Map<string, UnipileUser>();
+
+ return async ({ user, shouldLookUp }) => {
+ const resolvedCounterpart = resolvedCounterpartById.get(user.id);
+
+ if (isDefined(resolvedCounterpart)) {
+ return resolvedCounterpart;
+ }
+
+ let isLookupDeclined = false;
+ const counterpart = await withLinkedinPublicIdentifier({
+ unipileAccountId,
+ user,
+ shouldLookUp: isDefined(shouldLookUp)
+ ? async () => {
+ isLookupDeclined = !(await shouldLookUp());
+
+ return !isLookupDeclined;
+ }
+ : undefined,
+ });
+
+ if (!isLookupDeclined) {
+ resolvedCounterpartById.set(user.id, counterpart);
+ }
+
+ return counterpart;
+ };
+};
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.ts
index b6d1aefb408..962b7e364e1 100644
--- 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.ts
@@ -1,8 +1,8 @@
import { isNonEmptyString } from '@sniptt/guards';
import { CoreApiClient } from 'twenty-client-sdk/core';
+import { buildPersonNameFilter } from 'src/logic-functions/utils/build-person-name-filter.util';
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 ({
@@ -21,12 +21,7 @@ export const findUnlinkedPersonIdsByName = async ({
__args: {
filter: {
and: [
- {
- name: {
- firstName: { ilike: escapeSqlLikePattern(firstName) },
- lastName: { ilike: escapeSqlLikePattern(lastName) },
- },
- },
+ buildPersonNameFilter({ firstName, lastName }),
UNLINKED_PERSON_FILTER,
],
},
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/has-person-named-like-linkedin-user.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/has-person-named-like-linkedin-user.util.ts
new file mode 100644
index 00000000000..1c4976c906d
--- /dev/null
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/has-person-named-like-linkedin-user.util.ts
@@ -0,0 +1,28 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+
+import { buildPersonNameFilter } from 'src/logic-functions/utils/build-person-name-filter.util';
+import { splitLinkedinUserName } from 'src/logic-functions/utils/split-linkedin-user-name.util';
+import { type UnipileUser } from 'src/unipile/types/unipile-user.type';
+
+export const hasPersonNamedLikeLinkedinUser = async (
+ user: Pick<UnipileUser, 'display_name' | 'first_name' | 'last_name'>,
+): Promise<boolean> => {
+ const { firstName, lastName } = splitLinkedinUserName(user);
+
+ if (!isNonEmptyString(firstName) || !isNonEmptyString(lastName)) {
+ return true;
+ }
+
+ const { people } = await new CoreApiClient({ runAs: 'application' }).query({
+ people: {
+ __args: {
+ filter: buildPersonNameFilter({ firstName, lastName }),
+ first: 1,
+ },
+ edges: { node: { id: true } },
+ },
+ });
+
+ return (people?.edges ?? []).length > 0;
+};
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.ts
index 012497791ce..06ae05b49fe 100644
--- 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.ts
@@ -9,12 +9,14 @@ import { INGEST_MESSAGES_MAX_BATCH_SIZE } from 'src/constants/ingest-messages-ma
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 { hasPersonNamedLikeLinkedinUser } from 'src/logic-functions/utils/has-person-named-like-linkedin-user.util';
import { importLinkedinMessageAttachments } from 'src/logic-functions/utils/import-linkedin-message-attachments.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 LinkedinCounterpartResolver } from 'src/logic-functions/types/linkedin-counterpart-resolver.type';
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';
@@ -24,25 +26,40 @@ import { type UnipileUser } from 'src/unipile/types/unipile-user.type';
const resolvePersonIdByHandle = async ({
settings,
counterparts,
+ resolveCounterpart,
hasUserSentMessage,
isGroupChat,
}: {
settings: LinkedinSettings;
counterparts: UnipileUser[];
+ resolveCounterpart: LinkedinCounterpartResolver;
hasUserSentMessage: boolean;
isGroupChat: boolean;
}): Promise<
| {
+ counterparts: UnipileUser[];
personIdByHandle: Map<string, string>;
matchedPersonCount: number;
createdPersonCount: number;
}
| undefined
> => {
+ const isContactRequired =
+ settings.importPolicy === 'CONTACTS_ONLY' || isGroupChat;
+ const resolvedCounterparts = await Promise.all(
+ counterparts.map((counterpart) =>
+ resolveCounterpart({
+ user: counterpart,
+ shouldLookUp: isContactRequired
+ ? () => hasPersonNamedLikeLinkedinUser(counterpart)
+ : undefined,
+ }),
+ ),
+ );
const personIdByHandle = new Map<string, string>();
const unmatchedCounterparts: UnipileUser[] = [];
- for (const counterpart of counterparts) {
+ for (const counterpart of resolvedCounterparts) {
const personId = await matchLinkedinParticipantPersonId({
user: counterpart,
isNameMatchingEnabled: settings.isNameMatchingEnabled,
@@ -55,14 +72,11 @@ const resolvePersonIdByHandle = async ({
}
}
- if (
- (settings.importPolicy === 'CONTACTS_ONLY' || isGroupChat) &&
- personIdByHandle.size === 0
- ) {
+ if (isContactRequired && personIdByHandle.size === 0) {
return undefined;
}
- const matchedPersonCount = personIdByHandle.size;
+ let matchedPersonCount = personIdByHandle.size;
if (
!isLinkedinContactCreationAllowed({
@@ -70,29 +84,66 @@ const resolvePersonIdByHandle = async ({
hasUserSentMessage,
})
) {
- return { personIdByHandle, matchedPersonCount, createdPersonCount: 0 };
+ return {
+ counterparts: resolvedCounterparts,
+ personIdByHandle,
+ matchedPersonCount,
+ createdPersonCount: 0,
+ };
}
- for (const counterpart of unmatchedCounterparts) {
+ const creatableCounterparts = await Promise.all(
+ unmatchedCounterparts.map((counterpart) =>
+ isNonEmptyString(counterpart.public_identifier)
+ ? counterpart
+ : resolveCounterpart({ user: counterpart }),
+ ),
+ );
+
+ let createdPersonCount = 0;
+
+ for (const [index, counterpart] of creatableCounterparts.entries()) {
+ const handle = buildLinkedinProfileHandle(counterpart);
+ const personId =
+ counterpart.public_identifier ===
+ unmatchedCounterparts[index].public_identifier
+ ? undefined
+ : await matchLinkedinParticipantPersonId({
+ user: counterpart,
+ isNameMatchingEnabled: settings.isNameMatchingEnabled,
+ });
+
+ if (isDefined(personId)) {
+ personIdByHandle.set(handle, personId);
+ matchedPersonCount += 1;
+
+ continue;
+ }
+
const { firstName, lastName } = splitLinkedinUserName(counterpart);
if (
isNonEmptyString(firstName) &&
isNonEmptyString(counterpart.public_identifier)
) {
- const handle = buildLinkedinProfileHandle(counterpart);
-
personIdByHandle.set(
handle,
await createLinkedinPerson({ firstName, lastName, handle }),
);
+ createdPersonCount += 1;
}
}
return {
+ counterparts: resolvedCounterparts.map(
+ (counterpart) =>
+ creatableCounterparts.find(
+ (creatableCounterpart) => creatableCounterpart.id === counterpart.id,
+ ) ?? counterpart,
+ ),
personIdByHandle,
matchedPersonCount,
- createdPersonCount: personIdByHandle.size - matchedPersonCount,
+ createdPersonCount,
};
};
@@ -103,6 +154,7 @@ export const ingestLinkedinMessages = async ({
settings,
chat,
counterparts,
+ resolveCounterpart,
messages,
}: {
unipileAccountId: string;
@@ -111,6 +163,7 @@ export const ingestLinkedinMessages = async ({
settings: LinkedinSettings;
chat: UnipileChat;
counterparts: UnipileUser[];
+ resolveCounterpart: LinkedinCounterpartResolver;
messages: UnipileMessage[];
}): Promise<LinkedinIngestResult> => {
const isGroupChat = isLinkedinGroupChat(chat);
@@ -137,6 +190,7 @@ export const ingestLinkedinMessages = async ({
const resolvedPersons = await resolvePersonIdByHandle({
settings,
counterparts,
+ resolveCounterpart,
hasUserSentMessage: ingestableMessages.some((message) => message.is_sender),
isGroupChat,
});
@@ -145,8 +199,12 @@ export const ingestLinkedinMessages = async ({
return { ...emptyResult, skippedReason: 'NO_CONTACT' };
}
- const { personIdByHandle, matchedPersonCount, createdPersonCount } =
- resolvedPersons;
+ const {
+ counterparts: resolvedCounterparts,
+ personIdByHandle,
+ matchedPersonCount,
+ createdPersonCount,
+ } = resolvedPersons;
const subject = buildLinkedinChatSubject(chat);
const ingestMessagesInput = ingestableMessages
@@ -156,12 +214,12 @@ export const ingestLinkedinMessages = async ({
...message,
sender: message.is_sender
? message.sender
- : (counterparts.find(
+ : (resolvedCounterparts.find(
(counterpart) => counterpart.id === message.sender_id,
) ?? message.sender),
},
channelHandle: channel.handle,
- counterparts,
+ counterparts: resolvedCounterparts,
}),
)
.filter(isDefined)
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.ts
index 3587ffc4623..d6102f7c0a4 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
@@ -17,9 +17,11 @@ const isPermanentUnipileError = (error: unknown): boolean =>
export const withLinkedinPublicIdentifier = async ({
unipileAccountId,
user,
+ shouldLookUp,
}: {
unipileAccountId: string;
user: UnipileUser;
+ shouldLookUp?: () => Promise<boolean>;
}): Promise<UnipileUser> => {
if (isNonEmptyString(user.public_identifier)) {
return user;
@@ -32,6 +34,10 @@ export const withLinkedinPublicIdentifier = async ({
return { ...user, public_identifier: cachedPublicIdentifier };
}
+ if (isDefined(shouldLookUp) && !(await shouldLookUp())) {
+ return user;
+ }
+
try {
const { public_identifier: publicIdentifier } = await getUnipileUser({
accountId: unipileAccountId,