The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
LinkedIn app: reply to conversations from Twenty through Unipile (#29526)
martmullf87d09c6f36a
diff --git a/packages/twenty-apps/public/linkedin/README.md b/packages/twenty-apps/public/linkedin/README.mdindex 36e52d9af62..8ef16286674 100644--- a/packages/twenty-apps/public/linkedin/README.md+++ b/packages/twenty-apps/public/linkedin/README.md@@ -5,6 +5,7 @@## ✨ What you get- **LinkedIn messages in Twenty**: every message you send or receive lands on the matching Person and Company, next to their emails+- **Replies from Twenty**: answer a LinkedIn conversation from its thread in Twenty, sent from your own LinkedIn account- **One connection per member**: each teammate connects their own LinkedIn account in a few clicks## 💳 Billing@@ -18,7 +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.+- **Replies only.** You can reply to an imported conversation from Twenty, as text. Starting a new conversation, sending attachments and marking chats as read happen on LinkedIn.- **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.diff --git a/packages/twenty-apps/public/linkedin/SETUP.md b/packages/twenty-apps/public/linkedin/SETUP.mdindex db726b54a3e..fa013a68caf 100644--- a/packages/twenty-apps/public/linkedin/SETUP.md+++ b/packages/twenty-apps/public/linkedin/SETUP.md@@ -35,9 +35,11 @@ LinkedIn accounts are connected through [Unipile](https://www.unipile.com) (API| Step | Logic function | What it does || --- | --- | --- || Connect | `linkedin-authorize`, `linkedin-callback` | Sends the member to Unipile's hosted sign-in, then confirms the account it returns |-| On connect | `linkedin-on-connect` | Creates a private message channel matched on the Person **LinkedIn** field, and routes the Unipile account's webhooks to this workspace |+| On connect | `linkedin-on-connect` | Creates a private message channel matched on the Person **LinkedIn** field and bound to the `linkedin-messaging` provider, and routes the Unipile account's webhooks to this workspace || Webhook | `linkedin-webhook-resolver` | Checks the `unipile-signature` header and dispatches the event to the workspace that connected the account || New message | `linkedin-handle-webhook-event` | Ingests the message into the member's channel; flags the connection when LinkedIn signs the account out |+| Reply | `linkedin-send-message` | Sends a reply written in Twenty to the conversation's Unipile chat; the `message.new` webhook that follows is de-duplicated on the returned message id |+| Install, upgrade | `linkedin-post-install` | Binds channels connected before replies existed to the `linkedin-messaging` provider || Disconnect, uninstall | `linkedin-on-disconnect`, `linkedin-uninstall` | Deletes the channel and the Unipile account, which Unipile bills per connected account |Unipile only exposes internal `ACo…` profile ids on messages, so the app looks up each participant's public profile URL once and caches it. LinkedIn limits profile lookups to roughly 100 a day per account.diff --git a/packages/twenty-apps/public/linkedin/package.json b/packages/twenty-apps/public/linkedin/package.jsonindex c5abbde6e80..7db7dd893cc 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.2.0",+ "version": "0.3.0","description": "LinkedIn messages in Twenty: each member connects their LinkedIn account through Unipile and their conversations land on People timelines.","license": "MIT","engines": {diff --git a/packages/twenty-apps/public/linkedin/src/__tests__/deployed-functions.integration-test.ts b/packages/twenty-apps/public/linkedin/src/__tests__/deployed-functions.integration-test.tsindex deb1b8dab0d..6e1e825e43e 100644--- a/packages/twenty-apps/public/linkedin/src/__tests__/deployed-functions.integration-test.ts+++ b/packages/twenty-apps/public/linkedin/src/__tests__/deployed-functions.integration-test.ts@@ -17,6 +17,15 @@ describe('LinkedIn app deployed functions', () => {});});+ it('binds no channel on install when no LinkedIn account is connected', async () => {+ const execution = await executeDeployedFunctionOrThrow({+ functionName: 'linkedin-post-install',+ });++ expect(execution.status).toBe('SUCCESS');+ expect(execution.data).toEqual({ boundChannelCount: 0 });+ });+it('uninstalls cleanly when no LinkedIn account is connected', async () => {const execution = await executeDeployedFunctionOrThrow({functionName: 'linkedin-uninstall',diff --git a/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.tsindex 737c166c0aa..821deb44d3a 100644--- a/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/linkedin/src/constants/universal-identifiers.ts@@ -54,3 +54,12 @@ export const LINKEDIN_PLAN_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER =export const LINKEDIN_CANCEL_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER ='ef8af448-c120-43a3-87a0-001d7b3c7f4e';++export const LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER =+ '6d643df4-c07e-478f-80c6-ddd2a7bb460d';++export const LINKEDIN_SEND_MESSAGE_UNIVERSAL_IDENTIFIER =+ '949b8452-a7f1-46ee-9df3-4d1564b5dc65';++export const LINKEDIN_POST_INSTALL_UNIVERSAL_IDENTIFIER =+ '7301293c-fed8-4506-bd47-ab698a6e31ff';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 91541f41574..92986bc6d14 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@@ -2,11 +2,13 @@ import { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk/define';import { beforeEach, describe, expect, it, vi } from 'vitest';import { PERSON_LINKEDIN_LINK_FIELD_UNIVERSAL_IDENTIFIER } from 'src/constants/person-linkedin-link-field-universal-identifier.constant';+import { LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';const mocks = vi.hoisted(() => ({getConnection: vi.fn(),listMessageChannels: vi.fn(),createMessageChannel: vi.fn(),+ updateMessageChannel: vi.fn(),kvSet: vi.fn(),kvGet: vi.fn(),enqueueJobs: vi.fn(),@@ -17,6 +19,7 @@ vi.mock('twenty-sdk/logic-function', () => ({getConnection: mocks.getConnection,listMessageChannels: mocks.listMessageChannels,createMessageChannel: mocks.createMessageChannel,+ updateMessageChannel: mocks.updateMessageChannel,enqueueJobs: mocks.enqueueJobs,kv: { get: mocks.kvGet, set: mocks.kvSet },}));@@ -55,7 +58,7 @@ describe('linkedinOnConnectHandler', () => {);});- it('creates a private channel on the member profile, claims the account and leaves importing to the Sync button', async () => {+ it('creates a private channel on the member profile that replies go through, claims the account and leaves importing to the Sync button', async () => {await expect(linkedinOnConnectHandler(PAYLOAD)).resolves.toEqual({messageChannelId: 'channel-id',});@@ -67,6 +70,9 @@ describe('linkedinOnConnectHandler', () => {visibility: 'METADATA',participantHandleFieldUniversalIdentifier:PERSON_LINKEDIN_LINK_FIELD_UNIVERSAL_IDENTIFIER,+ messagingProvider: {+ universalIdentifier: LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ },});expect(mocks.kvSet).toHaveBeenCalledWith('unipile-account:acc_1',@@ -78,13 +84,38 @@ describe('linkedinOnConnectHandler', () => {it('reuses the channel of a reconnected account', async () => {mocks.listMessageChannels.mockResolvedValue([- { id: 'existing-channel-id' },+ {+ id: 'existing-channel-id',+ messagingProviderUniversalIdentifier:+ LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ },]);await expect(linkedinOnConnectHandler(PAYLOAD)).resolves.toEqual({messageChannelId: 'existing-channel-id',});expect(mocks.createMessageChannel).not.toHaveBeenCalled();+ expect(mocks.updateMessageChannel).not.toHaveBeenCalled();expect(mocks.enqueueJobs).not.toHaveBeenCalled();});++ it('lets members reply through a reconnected channel created before replies existed', async () => {+ mocks.listMessageChannels.mockResolvedValue([+ {+ id: 'existing-channel-id',+ messagingProviderUniversalIdentifier: null,+ },+ ]);++ await expect(linkedinOnConnectHandler(PAYLOAD)).resolves.toEqual({+ messageChannelId: 'existing-channel-id',+ });+ expect(mocks.updateMessageChannel).toHaveBeenCalledExactlyOnceWith({+ id: 'existing-channel-id',+ messagingProvider: {+ universalIdentifier: LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ },+ });+ expect(mocks.createMessageChannel).not.toHaveBeenCalled();+ });});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-post-install.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-post-install.test.tsnew file mode 100644index 00000000000..239a5b6068f--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-post-install.test.ts@@ -0,0 +1,57 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++const mocks = vi.hoisted(() => ({+ listMessageChannels: vi.fn(),+ updateMessageChannel: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ definePostInstallLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ listMessageChannels: mocks.listMessageChannels,+ updateMessageChannel: mocks.updateMessageChannel,+}));++const { linkedinPostInstallHandler } =+ await import('src/logic-functions/linkedin-post-install');++describe('linkedinPostInstallHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('lets members reply in the channels connected before replies existed', async () => {+ mocks.listMessageChannels.mockResolvedValue([+ { id: 'channel-1', messagingProviderUniversalIdentifier: null },+ {+ id: 'channel-2',+ messagingProviderUniversalIdentifier:+ LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ },+ ]);++ await expect(linkedinPostInstallHandler()).resolves.toEqual({+ boundChannelCount: 1,+ });+ expect(mocks.listMessageChannels).toHaveBeenCalledExactlyOnceWith();+ expect(mocks.updateMessageChannel).toHaveBeenCalledExactlyOnceWith({+ id: 'channel-1',+ messagingProvider: {+ universalIdentifier: LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ },+ });+ });++ it('changes nothing when no LinkedIn account is connected', async () => {+ mocks.listMessageChannels.mockResolvedValue([]);++ await expect(linkedinPostInstallHandler()).resolves.toEqual({+ boundChannelCount: 0,+ });+ expect(mocks.updateMessageChannel).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-send-message.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-send-message.test.tsnew file mode 100644index 00000000000..32845120784--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/__tests__/linkedin-send-message.test.ts@@ -0,0 +1,74 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getConnection: vi.fn(),+ sendUnipileChatMessage: vi.fn(),+}));++vi.mock('twenty-sdk/logic-function', () => ({+ getConnection: mocks.getConnection,+}));++vi.mock('src/unipile/utils/send-unipile-chat-message.util', () => ({+ sendUnipileChatMessage: mocks.sendUnipileChatMessage,+}));++const { linkedinSendMessageHandler } =+ await import('src/logic-functions/linkedin-send-message');++const PAYLOAD = {+ messagingProviderName: 'linkedin-messaging',+ connectedAccountId: 'connected-account-id',+ messageChannelId: 'channel-id',+ threadExternalId: 'chat-1',+ text: 'Thanks, talk soon',+ idempotencyKey: '3f1c2a4e-5b6d-4e7f-8a9b-0c1d2e3f4a5b',+ recipients: [+ {+ handle: 'https://www.linkedin.com/in/grace-hopper',+ displayName: 'Grace Hopper',+ },+ ],+};++describe('linkedinSendMessageHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getConnection.mockResolvedValue({ externalAccountId: 'acc_1' });+ mocks.sendUnipileChatMessage.mockResolvedValue('message-1');+ });++ it('replies in the Unipile chat of the thread and returns the sent message id', async () => {+ await expect(linkedinSendMessageHandler(PAYLOAD)).resolves.toEqual({+ externalId: 'message-1',+ });++ expect(mocks.getConnection).toHaveBeenCalledExactlyOnceWith(+ 'connected-account-id',+ );+ expect(mocks.sendUnipileChatMessage).toHaveBeenCalledExactlyOnceWith({+ accountId: 'acc_1',+ chatId: 'chat-1',+ text: 'Thanks, talk soon',+ });+ });++ it('refuses to send through a connection without a Unipile account', async () => {+ mocks.getConnection.mockResolvedValue({ externalAccountId: null });++ await expect(linkedinSendMessageHandler(PAYLOAD)).rejects.toThrow(+ 'LinkedIn connection connected-account-id has no Unipile account',+ );+ expect(mocks.sendUnipileChatMessage).not.toHaveBeenCalled();+ });++ it('fails the reply when Unipile does', async () => {+ mocks.sendUnipileChatMessage.mockRejectedValue(+ new Error('Unipile send message failed (403): Forbidden'),+ );++ await expect(linkedinSendMessageHandler(PAYLOAD)).rejects.toThrow(+ 'Unipile send message failed (403): Forbidden',+ );+ });+});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 67442a92a6d..e5d52bc34fe 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@@ -6,10 +6,15 @@ import {kv,listMessageChannels,} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';import { PERSON_LINKEDIN_LINK_FIELD_UNIVERSAL_IDENTIFIER } from 'src/constants/person-linkedin-link-field-universal-identifier.constant';-import { LINKEDIN_ON_CONNECT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import {+ LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ LINKEDIN_ON_CONNECT_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';import { type LinkedinConnectionHookPayload } from 'src/logic-functions/types/linkedin-connection-hook-payload.type';+import { bindLinkedinMessagingProvider } from 'src/logic-functions/utils/bind-linkedin-messaging-provider.util';import { buildLinkedinProfileHandle } from 'src/logic-functions/utils/build-linkedin-profile-handle.util';import { getUnipileAccountClaimKey } from 'src/unipile/utils/get-unipile-account-claim-key.util';import { getUnipileUser } from 'src/unipile/utils/get-unipile-user.util';@@ -28,6 +33,10 @@ export const linkedinOnConnectHandler = async ({const [existingChannel] = await listMessageChannels({ connectedAccountId });+ if (isDefined(existingChannel)) {+ await bindLinkedinMessagingProvider(existingChannel);+ }+const channel =existingChannel ??(await (async () => {@@ -43,6 +52,9 @@ export const linkedinOnConnectHandler = async ({visibility: 'METADATA',participantHandleFieldUniversalIdentifier:PERSON_LINKEDIN_LINK_FIELD_UNIVERSAL_IDENTIFIER,+ messagingProvider: {+ universalIdentifier: LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ },});})());@@ -57,7 +69,7 @@ export default defineLogicFunction({universalIdentifier: LINKEDIN_ON_CONNECT_UNIVERSAL_IDENTIFIER,name: 'linkedin-on-connect',description:- 'Creates the message channel of a new LinkedIn connection, routes its Unipile webhooks to this workspace.',+ 'Creates the message channel of a new LinkedIn connection, lets members reply through it and routes its Unipile webhooks to this workspace.',timeoutSeconds: 30,handler: linkedinOnConnectHandler,});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-post-install.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-post-install.tsnew file mode 100644index 00000000000..b37379a1ed7--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-post-install.ts@@ -0,0 +1,31 @@+import { definePostInstallLogicFunction } from 'twenty-sdk/define';+import { listMessageChannels } from 'twenty-sdk/logic-function';++import { LINKEDIN_POST_INSTALL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { bindLinkedinMessagingProvider } from 'src/logic-functions/utils/bind-linkedin-messaging-provider.util';++export const linkedinPostInstallHandler = async (): Promise<{+ boundChannelCount: number;+}> => {+ const channels = await listMessageChannels();+ let boundChannelCount = 0;++ for (const channel of channels) {+ if (await bindLinkedinMessagingProvider(channel)) {+ boundChannelCount += 1;+ }+ }++ return { boundChannelCount };+};++export default definePostInstallLogicFunction({+ universalIdentifier: LINKEDIN_POST_INSTALL_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-post-install',+ description:+ 'Lets members reply from Twenty in LinkedIn conversations connected before replies existed.',+ timeoutSeconds: 60,+ shouldRunOnVersionUpgrade: true,+ shouldRunSynchronously: false,+ handler: linkedinPostInstallHandler,+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-send-message.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-send-message.tsnew file mode 100644index 00000000000..449a3dad7ea--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-send-message.ts@@ -0,0 +1,43 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction } from 'twenty-sdk/define';+import {+ getConnection,+ type SendAppMessagePayload,+ type SendAppMessageResult,+} from 'twenty-sdk/logic-function';++import { LINKEDIN_SEND_MESSAGE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { sendUnipileChatMessage } from 'src/unipile/utils/send-unipile-chat-message.util';++export const linkedinSendMessageHandler = async ({+ connectedAccountId,+ threadExternalId,+ text,+}: SendAppMessagePayload): Promise<SendAppMessageResult> => {+ const connection = await getConnection(connectedAccountId);+ const unipileAccountId = connection.externalAccountId;++ if (!isNonEmptyString(unipileAccountId)) {+ throw new Error(+ `LinkedIn connection ${connectedAccountId} has no Unipile account`,+ );+ }++ // Threads are ingested under their Unipile chat id, so a reply goes to that chat.+ const externalId = await sendUnipileChatMessage({+ accountId: unipileAccountId,+ chatId: threadExternalId,+ text,+ });++ return { externalId };+};++export default defineLogicFunction({+ universalIdentifier: LINKEDIN_SEND_MESSAGE_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-send-message',+ description:+ 'Sends a reply written in Twenty to its LinkedIn conversation through Unipile.',+ timeoutSeconds: 20,+ handler: linkedinSendMessageHandler,+});diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/bind-linkedin-messaging-provider.util.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/bind-linkedin-messaging-provider.util.tsnew file mode 100644index 00000000000..18e36647301--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/bind-linkedin-messaging-provider.util.ts@@ -0,0 +1,29 @@+import {+ type AppMessageChannel,+ updateMessageChannel,+} from 'twenty-sdk/logic-function';++import { LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++export const bindLinkedinMessagingProvider = async (+ channel: Pick<+ AppMessageChannel,+ 'id' | 'messagingProviderUniversalIdentifier'+ >,+): Promise<boolean> => {+ if (+ channel.messagingProviderUniversalIdentifier ===+ LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER+ ) {+ return false;+ }++ await updateMessageChannel({+ id: channel.id,+ messagingProvider: {+ universalIdentifier: LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ },+ });++ return true;+};diff --git a/packages/twenty-apps/public/linkedin/src/messaging-providers/linkedin-messaging.ts b/packages/twenty-apps/public/linkedin/src/messaging-providers/linkedin-messaging.tsnew file mode 100644index 00000000000..44b4b0e72d4--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/messaging-providers/linkedin-messaging.ts@@ -0,0 +1,19 @@+import { defineMessagingProvider } from 'twenty-sdk/define';++import {+ LINKEDIN_CONNECTION_PROVIDER_UNIVERSAL_IDENTIFIER,+ LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ LINKEDIN_SEND_MESSAGE_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++export default defineMessagingProvider({+ universalIdentifier: LINKEDIN_MESSAGING_PROVIDER_UNIVERSAL_IDENTIFIER,+ name: 'linkedin-messaging',+ displayName: 'LinkedIn Messages',+ connectionProvider: {+ universalIdentifier: LINKEDIN_CONNECTION_PROVIDER_UNIVERSAL_IDENTIFIER,+ },+ sendMessageLogicFunction: {+ universalIdentifier: LINKEDIN_SEND_MESSAGE_UNIVERSAL_IDENTIFIER,+ },+});diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/__tests__/send-unipile-chat-message.util.test.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/__tests__/send-unipile-chat-message.util.test.tsnew file mode 100644index 00000000000..7a867ee7c91--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/__tests__/send-unipile-chat-message.util.test.ts@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { UnipileRateLimitError } from 'src/unipile/utils/request-unipile.util';++const mocks = vi.hoisted(() => ({ sendMessage: vi.fn(), wait: vi.fn() }));++vi.mock('@unipile/sdk', () => ({+ UnipileMessaging: class {+ sendMessage = mocks.sendMessage;+ },+}));++vi.mock('src/unipile/utils/get-unipile-request-options.util', () => ({+ getUnipileRequestOptions: () => ({ auth: 'key', throwOnError: true }),+}));++vi.mock('src/utils/wait.util', () => ({ wait: mocks.wait }));++const { sendUnipileChatMessage } =+ await import('src/unipile/utils/send-unipile-chat-message.util');++const send = () =>+ sendUnipileChatMessage({+ accountId: 'acc_1',+ chatId: 'chat-1',+ text: 'Thanks, talk soon',+ });++describe('sendUnipileChatMessage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('sends the text to the chat and returns the sent message id', async () => {+ mocks.sendMessage.mockResolvedValue({+ data: { object: 'MessageSent', message_id: 'message-1' },+ });++ await expect(send()).resolves.toBe('message-1');+ expect(mocks.sendMessage).toHaveBeenCalledExactlyOnceWith({+ auth: 'key',+ throwOnError: true,+ path: { account_id: 'acc_1', chat_id: 'chat-1' },+ body: { text: 'Thanks, talk soon' },+ });+ });++ it('returns the first id when Unipile reports several', async () => {+ mocks.sendMessage.mockResolvedValue({+ data: { object: 'MessageSent', message_id: ['message-1', 'message-2'] },+ });++ await expect(send()).resolves.toBe('message-1');+ });++ it('fails when Unipile returns no message id', async () => {+ mocks.sendMessage.mockResolvedValue({+ data: { object: 'MessageSent', message_id: null },+ });++ await expect(send()).rejects.toThrow(+ 'Unipile accepted the message to chat chat-1 but returned no message id',+ );+ });++ it('fails a rate-limited send right away instead of waiting', async () => {+ mocks.sendMessage.mockRejectedValue({+ status: 429,+ title: 'Too many requests',+ detail: 'Please retry in 30 seconds',+ });++ await expect(send()).rejects.toBeInstanceOf(UnipileRateLimitError);+ expect(mocks.sendMessage).toHaveBeenCalledOnce();+ expect(mocks.wait).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/linkedin/src/unipile/utils/send-unipile-chat-message.util.ts b/packages/twenty-apps/public/linkedin/src/unipile/utils/send-unipile-chat-message.util.tsnew file mode 100644index 00000000000..83e9af4c7b4--- /dev/null+++ b/packages/twenty-apps/public/linkedin/src/unipile/utils/send-unipile-chat-message.util.ts@@ -0,0 +1,38 @@+import { isNonEmptyString } from '@sniptt/guards';+import { UnipileMessaging } from '@unipile/sdk';++import { getUnipileRequestOptions } from 'src/unipile/utils/get-unipile-request-options.util';+import { requestUnipile } from 'src/unipile/utils/request-unipile.util';++export const sendUnipileChatMessage = async ({+ accountId,+ chatId,+ text,+}: {+ accountId: string;+ chatId: string;+ text: string;+}): Promise<string> => {+ const { data } = await requestUnipile(+ 'send message',+ () =>+ new UnipileMessaging().sendMessage({+ ...getUnipileRequestOptions(),+ path: { account_id: accountId, chat_id: chatId },+ body: { text },+ }),+ // A member is waiting on the send, so a rate limit fails it rather than sleeping.+ { deadlineAtMs: Date.now() },+ );++ // Only attachments split a send into several ids, and this sends text alone.+ const [messageId] = [data.message_id].flat();++ if (!isNonEmptyString(messageId)) {+ throw new Error(+ `Unipile accepted the message to chat ${chatId} but returned no message id`,+ );+ }++ return messageId;+};