Skip to content

The open alternative to Salesforce, designed for AI.

Share the inbox SDK helpers with front components (#29088)

Raphaël Bosia83d07583843
diff --git a/packages/twenty-agent-skills/references/develop-app/front-components.md b/packages/twenty-agent-skills/references/develop-app/front-components.md
index 669e82ea528..f7f21d3d98b 100644
--- a/packages/twenty-agent-skills/references/develop-app/front-components.md
+++ b/packages/twenty-agent-skills/references/develop-app/front-components.md
@@ -41,6 +41,7 @@ Keep imports narrow:
- Use `twenty-sdk/front-component` for front component hooks and host APIs.
- Use `twenty-client-sdk/core` or `twenty-client-sdk/metadata` for data access.
+- Use `sendInboxMessage` and the inbox mention helpers from `twenty-sdk/front-component` to post in members' inbox (see `logic.md`). Open the conversation with `navigate(AppPath.AiChatInbox, { threadId })`: the route is main-page only, and it opens only for the conversation's participants.
- Install `twenty-ui` from npm at the same version as `twenty-sdk` and `twenty-client-sdk` and import Twenty UI components, icons, and theme tokens from its subpaths (`twenty-ui/primitives/input`, `twenty-ui/primitives/data-display`, `twenty-ui/icon`, `twenty-ui/primitives/typography`, `twenty-ui/theme`, and others) before adding external UI libraries.
Keep the SDK packages and `twenty-ui` in `devDependencies`. Import shared components from their family entry point, such as `twenty-ui/components/input` for `MainButton` and `LightButton`, `twenty-ui/components/feedback` for `Callout`, `twenty-ui/components/layout` for `Section`, and `twenty-ui/components/navigation` for `Dropdown`. Use `twenty-ui/primitives/input` for foundational controls such as `Button`, `Field` and `Input`.
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index 5a5987e1d4e..26dfa2d1be9 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -81,7 +81,7 @@ When adding AI behavior:
## Inbox Messages
-`sendInboxMessage` from `twenty-sdk/logic-function` posts a message from the app in the chats of one or more workspace members.
+`sendInboxMessage` posts a message from the app in the chats of one or more workspace members. Import it from `twenty-sdk/logic-function` in a logic function and from `twenty-sdk/front-component` in a front component; the inbox helpers are the same in both.
- `workspaceMemberIds` lists the members who receive it (at least one), and `text` is the message, in markdown. The first member of a new conversation owns it and the others follow it; a later send with the same key that lists new members adds them.
- `threadKey` picks the conversation per app, shared by every member it is sent to: a new key starts one titled `title`, a known key adds to it. `idempotencyKey` identifies the message in it, so sending again with the same keys writes nothing and retries never duplicate it.
@@ -90,7 +90,9 @@ When adding AI behavior:
- Only one call the member answers (`ask_question`, `request_form`, `propose_tool_call`) can wait at a time; another fails with `THREAD_AWAITING_ANSWER` until they answer. Plain messages and app tool calls are still accepted.
- A conversation its owner deleted is gone for every member and is not recreated.
- The app's default role needs `SystemPermissionFlag.AI`, and every member needs the AI permission.
-- It always uses the app's access and ignores `runAs`.
+- The message is always from the app. The call runs like the default clients: as the member who triggered the run or looks at the page, who then needs the AI permission too, or as the app when nobody triggered the run. In a front component an expired token is refreshed once before the call is retried.
+- Write mentions with `await inboxMention({ workspaceMemberId })` and record chips with `await inboxReferenceRecord({ objectNameSingular, recordId })`, never by hand. Both read the label the chip shows (the member's full name or email, the record's label identifier), so the caller needs read access to the member or record. A mention only renders: list every recipient in `workspaceMemberIds`.
+- `INBOX_ASSISTANT_MENTION` is the composer's mention of the assistant.
## Connection Providers
diff --git a/packages/twenty-docs/custom.css b/packages/twenty-docs/custom.css
index 24d5161dc6d..5ab5951a593 100644
--- a/packages/twenty-docs/custom.css
+++ b/packages/twenty-docs/custom.css
@@ -1526,7 +1526,7 @@ div:has(> .sidebar-group a[href$='/user-guide/introduction']) + div {
--page-banner-illustration: url('/images/user-guide/halftone/card-page-connections.svg');
}
-#content-area:has([data-page-banner='card-page-messaging-channels']) {
+#content-area:has([data-page-banner='card-page-messaging-channels'], [data-page-banner='card-page-inbox']) {
--page-banner-illustration: url('/images/user-guide/halftone/card-page-messaging-channels.svg');
}
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
index 3f6729730c7..371873463fa 100644
--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
@@ -458,6 +458,34 @@ try {
}
```
+## Posting to the inbox
+
+`sendInboxMessage` and the [inbox](/developers/extend/apps/logic/inbox) mention helpers are exported from `twenty-sdk/front-component` too, so a component can post a message without a logic function in between. The message is from your app, and the call carries the component's token, so the member looking at the page needs the `AI` permission, like every recipient.
+
+To show the conversation afterwards, navigate to it with the `threadId` the call returns:
+
+```tsx
+import {
+ AppPath,
+ navigate,
+ sendInboxMessage,
+} from 'twenty-sdk/front-component';
+
+const { threadId } = await sendInboxMessage({
+ workspaceMemberIds: [workspaceMemberId],
+ threadKey: 'weekly-digest',
+ idempotencyKey: `weekly-digest-${weekNumber}`,
+ title: 'Your weekly digest',
+ text: 'Three deals moved to negotiation this week.',
+});
+
+await navigate(AppPath.AiChatInbox, { threadId });
+```
+
+- `workspaceMemberIds` takes workspace member ids, not the user id `useUserId()` returns.
+- A conversation opens only for its participants, so navigate to it when the member looking at the page is one of the recipients.
+- The inbox is a main-page route: `navigate` opens it there, and `openSidePanelPage` cannot open it in the side panel.
+
## Accessing runtime context
Inside your component, use SDK hooks to access the current user, record, and component instance:
diff --git a/packages/twenty-docs/developers/extend/apps/logic/inbox.mdx b/packages/twenty-docs/developers/extend/apps/logic/inbox.mdx
new file mode 100644
index 00000000000..e38ea72ccf3
--- /dev/null
+++ b/packages/twenty-docs/developers/extend/apps/logic/inbox.mdx
@@ -0,0 +1,95 @@
+---
+title: Inbox
+description: Post messages from your app in members' inbox, from a logic function or a front component.
+---
+
+import { PageBanner } from "/snippets/page-banner.mdx"
+
+## Overview
+
+Your app can start and continue conversations in the inbox of workspace members, where they also talk with Twenty's assistant. A message can end on a question, a form or a change to approve, which the member answers from the chat before the conversation continues with the assistant.
+
+The inbox helpers are exported from both `twenty-sdk/logic-function` and `twenty-sdk/front-component`, so a scheduled run and a button in your app post the same way.
+
+## Sending a message
+
+`sendInboxMessage()` posts a message from your app in the chats of one or more workspace members and returns the conversation's `threadId`.
+
+```ts src/logic-functions/notify-first-recording.ts
+import { sendInboxMessage } from 'twenty-sdk/logic-function';
+
+const { threadId } = await sendInboxMessage({
+ workspaceMemberIds: [workspaceMemberId],
+ threadKey: 'first-call-recording',
+ idempotencyKey: 'first-call-recording',
+ title: 'Your first call recording is ready',
+ text: 'Your first call was recorded: **Weekly sync**.',
+ toolCall: {
+ toolName: 'ask_question',
+ input: {
+ header: 'Share',
+ question: 'Do you want to share it with the other attendees?',
+ options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
+ },
+ },
+});
+```
+
+Key points:
+
+- `workspaceMemberIds` lists the members who receive the conversation, at least one. The first member of a new conversation owns it, and the others follow it as participants. A later send under the same key that lists new members adds them; members it leaves out keep the conversation.
+- `threadKey` picks the conversation for this app, shared by every member it is sent to. A new key starts a conversation titled `title`; a key you used before adds the message to that conversation.
+- `idempotencyKey` identifies the message within the conversation. Sending again with the same keys writes nothing new, so retries and concurrent runs never duplicate a message.
+- `text` is markdown, and can carry [mentions and record references](#mentions-and-record-references).
+- `toolCall` (optional) ends the message on one of:
+ - a call the member answers, which pauses the conversation: `ask_question` (one multiple-choice question), `request_form` (fields to fill in) or `propose_tool_call` (a call to approve). Its `input` takes the `toolName`, the `arguments` you would call the tool with and a one-sentence `summary`. The tool must be one your app's default role could run itself, such as `create_one_person` or `update_one_opportunity` (with the record `id`); an email (`send_email` or `draft_email`, with `recipients`, `subject` and a `body` in HTML) needs no permission of your app. The member reviews the call in the same card as a call the assistant proposes, edits it if they want, and the approved call runs with their own access;
+ - one of your app's own tools, by `logicFunctionUniversalIdentifier`, rendered by its front component with the `input` and `output` you pass. It does not pause the conversation.
+- Only one call the member answers can wait in a conversation at a time: sending another before they answer fails with `THREAD_AWAITING_ANSWER`. Plain messages and app tool calls are still accepted.
+- Only the member who owns a conversation can delete it, and a deleted conversation is gone for every member: it is not recreated, and nothing is added to it. The other members can unsubscribe to take it out of their own inbox.
+- Every member must have the `AI` permission, and the call fails without writing the message when one of them cannot have the conversation. Your app's [default role](/developers/extend/apps/config/roles) must grant `SystemPermissionFlag.AI`.
+
+### Who sends the message
+
+A message is always written by your app, whatever triggered the call. The call itself runs like the default [API clients](/developers/extend/apps/logic/logic-functions#whose-access-a-call-uses):
+
+- In a logic function, it acts as the person who triggered the run, or as your application when nobody did, such as on a cron schedule.
+- In a front component, it acts as the member looking at the page. When the token has expired, the call refreshes it once through Twenty and retries.
+
+The person behind the call needs the `AI` permission as well, like every recipient.
+
+To post from a front component, import the same helpers from `twenty-sdk/front-component`. [Posting to the inbox](/developers/extend/apps/layout/front-components#posting-to-the-inbox) shows how to open the conversation afterwards.
+
+## Mentions and record references
+
+The inbox renders reference tokens in `text` as chips. Write them with these helpers rather than by hand:
+
+```ts src/logic-functions/flag-idle-deal.ts
+import {
+ inboxMention,
+ inboxReferenceRecord,
+ sendInboxMessage,
+} from 'twenty-sdk/logic-function';
+
+const ownerMention = await inboxMention({ workspaceMemberId: owner.id });
+
+const dealReference = await inboxReferenceRecord({
+ objectNameSingular: 'opportunity',
+ recordId: opportunity.id,
+});
+
+await sendInboxMessage({
+ workspaceMemberIds: [owner.id],
+ threadKey: `idle-deal-${opportunity.id}`,
+ idempotencyKey: `idle-deal-${opportunity.id}-${weekNumber}`,
+ title: `${opportunity.name} is idle`,
+ text: `${ownerMention}, ${dealReference} has had no activity for two weeks.`,
+});
+```
+
+- `inboxMention({ workspaceMemberId })` writes a mention of a workspace member, and `inboxReferenceRecord({ objectNameSingular, recordId })` a chip that links to any record.
+- Both read the label the chip shows, as the composer does: the member's full name, or their email when the name is empty, and the record's label identifier, such as a company name. Brackets become parentheses and line breaks become spaces, so the chip always renders.
+- They read with the same access as the rest of the call, so that access needs to reach the member or record. A record reference makes two requests, one for the object's label field and one for the record.
+- A mention only renders. It does not add the member to the conversation or notify them, so list everyone who should receive the message in `workspaceMemberIds`.
+- `INBOX_ASSISTANT_MENTION` is the text the composer writes when a member mentions the assistant (`@Ada`), so your messages name it the same way.
+
+<PageBanner illustration="card-page-inbox" />
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 4bf26d17eb7..5dc2abea26e 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -623,7 +623,7 @@ Check `context.workspaceMemberId` when a function behaves differently depending
</Note>
-The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), [messaging channels](/developers/extend/apps/logic/messaging-channels), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits). `sendInboxMessage` also uses your application's access and ignores `runAs`, though it writes to the chats of the members you name.
+The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), [messaging channels](/developers/extend/apps/logic/messaging-channels), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits).
#### Exposing a function as an AI tool or workflow action
diff --git a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
index cc261c05770..3985746bcb7 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
@@ -49,6 +49,10 @@ A Twenty app's **logic layer** is the code that *runs* — server-side TypeScrip
<CardTitle>Messaging Channels</CardTitle>
Bring conversations from any provider into Twenty's Message and Message Thread records — threading and de-duplication included.
</Card>
+ <Card href="/developers/extend/apps/logic/inbox" img="/images/user-guide/halftone/card-page-messaging-channels.svg">
+ <CardTitle>Inbox</CardTitle>
+ Post messages in members' inbox from logic functions and front components.
+ </Card>
<Card href="/developers/extend/apps/logic/key-value-store" img="/images/user-guide/halftone/card-page-key-value-store.svg">
<CardTitle>Key-Value Store</CardTitle>
Persist state between logic function runs — caches, cursors, and cross-workspace claims.
diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
index fa1a8875899..8e08303eaf5 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
@@ -300,65 +300,10 @@ name a member at all.
<Accordion title="sendInboxMessage" description="Start or continue a conversation in members' chats">
`sendInboxMessage()` posts a message from your app in the chats of one or more
-workspace members. It can end on a tool call the member answers from the chat, after which
-the conversation continues with Twenty's assistant.
-
-```ts src/logic-functions/notify-first-recording.ts
-import { sendInboxMessage } from 'twenty-sdk/logic-function';
-
-const { threadId } = await sendInboxMessage({
- workspaceMemberIds: [workspaceMemberId],
- threadKey: 'first-call-recording',
- idempotencyKey: 'first-call-recording',
- title: 'Your first call recording is ready',
- text: 'Your first call was recorded: **Weekly sync**.',
- toolCall: {
- toolName: 'ask_question',
- input: {
- header: 'Share',
- question: 'Do you want to share it with the other attendees?',
- options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
- },
- },
-});
-```
-
-Key points:
-- `workspaceMemberIds` lists the members who receive the conversation, at least
- one. The first member of a new conversation owns it, and the others follow it
- as participants. A later send under the same key that lists new members adds
- them; members it leaves out keep the conversation.
-- `threadKey` picks the conversation for this app, shared by every member it is
- sent to. A new key starts a conversation titled `title`; a key you used before
- adds the message to that conversation.
-- `idempotencyKey` identifies the message within the conversation. Sending
- again with the same keys writes nothing new, so retries and concurrent runs
- never duplicate a message.
-- `toolCall` (optional) ends the message on one of:
- - a call the member answers, which pauses the conversation: `ask_question`
- (one multiple-choice question), `request_form` (fields to fill in) or
- `propose_tool_call` (a call to approve). Its `input` takes the `toolName`,
- the `arguments` you would call the tool with and a one-sentence `summary`.
- The tool must be one your app's default role could run itself, such as
- `create_one_person` or `update_one_opportunity` (with the record `id`); an
- email (`send_email` or `draft_email`, with `recipients`, `subject` and a
- `body` in HTML) needs no permission of your app. The member reviews the call
- in the same card as a call the assistant proposes, edits it if they want, and
- the approved call runs with their own access;
- - one of your app's own tools, by `logicFunctionUniversalIdentifier`, rendered
- by its front component with the `input` and `output` you pass. It does not
- pause the conversation.
-- Only one call the member answers can wait in a conversation at a time:
- sending another before they answer fails with `THREAD_AWAITING_ANSWER`. Plain
- messages and app tool calls are still accepted.
-- Only the member who owns a conversation can delete it, and a deleted
- conversation is gone for every member: it is not recreated, and nothing is
- added to it. The other members can unsubscribe to take it out of their own
- inbox.
-- Every member must have the `AI` permission, and the call fails without
- writing the message when one of them cannot have the conversation. Your app's
- [default role](/developers/extend/apps/config/roles) must grant
- `SystemPermissionFlag.AI`.
+workspace members. It can end on a tool call the member answers from the chat,
+after which the conversation continues with Twenty's assistant. See
+[Inbox](/developers/extend/apps/logic/inbox) for its options, the mention
+helpers, and how to post from a front component.
</Accordion>
</AccordionGroup>
diff --git a/packages/twenty-docs/docs.json b/packages/twenty-docs/docs.json
index 5da64458252..6659e6011b6 100644
--- a/packages/twenty-docs/docs.json
+++ b/packages/twenty-docs/docs.json
@@ -462,6 +462,7 @@
"developers/extend/apps/logic/workflows",
"developers/extend/apps/logic/connections",
"developers/extend/apps/logic/messaging-channels",
+ "developers/extend/apps/logic/inbox",
"developers/extend/apps/logic/credits"
]
},
diff --git a/packages/twenty-docs/navigation/base-structure.json b/packages/twenty-docs/navigation/base-structure.json
index 1942b95d277..5cd2cd2cdf7 100644
--- a/packages/twenty-docs/navigation/base-structure.json
+++ b/packages/twenty-docs/navigation/base-structure.json
@@ -456,6 +456,7 @@
"developers/extend/apps/logic/workflows",
"developers/extend/apps/logic/connections",
"developers/extend/apps/logic/messaging-channels",
+ "developers/extend/apps/logic/inbox",
"developers/extend/apps/logic/credits"
]
},
diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-send-inbox-message.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-send-inbox-message.front-component.tsx
new file mode 100644
index 00000000000..cc3a279988b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-send-inbox-message.front-component.tsx
@@ -0,0 +1,53 @@
+import { useState } from 'react';
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { sendInboxMessage } from 'twenty-sdk/front-component';
+
+import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';
+import {
+ BUTTON_STYLE,
+ STATUS_STYLE,
+} from '@/__stories__/shared/front-components/styles';
+
+const HostApiSendInboxMessageFrontComponent = () => {
+ const [status, setStatus] = useState('idle');
+
+ const handleClick = async () => {
+ try {
+ const { threadId } = await sendInboxMessage({
+ workspaceMemberIds: ['20202020-0000-4000-8000-000000000001'],
+ threadKey: 'host-api-send-inbox-message',
+ idempotencyKey: 'host-api-send-inbox-message',
+ title: 'Sent from a front component',
+ text: 'This message was posted by a front component.',
+ });
+ setStatus(`sendInboxMessage:success:${threadId}`);
+ } catch (error) {
+ setStatus(
+ `sendInboxMessage:error:${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ };
+
+ return (
+ <FrontComponentCard title="host-api:send-inbox-message">
+ <button
+ data-testid="subject"
+ type="button"
+ onClick={handleClick}
+ style={BUTTON_STYLE}
+ >
+ Send inbox message
+ </button>
+ <span data-testid="api-status" style={STATUS_STYLE}>
+ {status}
+ </span>
+ </FrontComponentCard>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: 'fc-host-inbox-00000000-0000-0000-0000-000000000020',
+ name: 'host-api-send-inbox-message-front-component',
+ description: 'Front component covering sendInboxMessage',
+ component: HostApiSendInboxMessageFrontComponent,
+});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/send-inbox-message.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/send-inbox-message.stories.tsx
new file mode 100644
index 00000000000..43d47833dd2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/send-inbox-message.stories.tsx
@@ -0,0 +1,87 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, within } from 'storybook/test';
+
+import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';
+import {
+ FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ resetFrontComponentStoryMocks,
+} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
+import { runFrontComponentStory } from '@/__stories__/shared/test-utils/runFrontComponentStory';
+import { HOST_API_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';
+
+const STORY_API_URL = 'https://api.twenty.test';
+const STORY_METADATA_URL = `${STORY_API_URL}/metadata`;
+const STORY_THREAD_ID = '6f1d7c2a-3b4e-4f5a-8b9c-0d1e2f3a4b5c';
+
+const receiveMetadataRequestAuthorization = fn();
+
+const installMetadataFetchStub = () => {
+ const delegateFetch = window.fetch.bind(window);
+
+ window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = new Request(input, init);
+ const isMetadataRequest =
+ request.method === 'POST' && request.url === STORY_METADATA_URL;
+
+ if (!isMetadataRequest) {
+ return delegateFetch(input, init);
+ }
+
+ receiveMetadataRequestAuthorization(request.headers.get('Authorization'));
+
+ return new Response(
+ JSON.stringify({
+ data: { sendInboxMessage: { threadId: STORY_THREAD_ID } },
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ );
+ };
+
+ return () => {
+ window.fetch = delegateFetch;
+ };
+};
+
+const meta: Meta<typeof FrontComponentRenderer> = {
+ title: 'FrontComponent/HostApi/SendInboxMessage',
+ component: FrontComponentRenderer,
+ parameters: { layout: 'centered' },
+ args: { ...FRONT_COMPONENT_STORY_DEFAULT_ARGS, apiUrl: STORY_API_URL },
+ beforeEach: resetFrontComponentStoryMocks,
+};
+
+export default meta;
+
+type Story = StoryObj<typeof FrontComponentRenderer>;
+
+const sendInboxMessageStory = runFrontComponentStory({
+ frontComponentBundleName: 'host-api-send-inbox-message',
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expectFrontComponentMounted(canvas);
+
+ await userEvent.click(await canvas.findByTestId('subject'));
+
+ expect(
+ await canvas.findByText(
+ `sendInboxMessage:success:${STORY_THREAD_ID}`,
+ {},
+ { timeout: HOST_API_TIMEOUT },
+ ),
+ ).toBeVisible();
+ expect(receiveMetadataRequestAuthorization).toHaveBeenCalledWith(
+ `Bearer ${FRONT_COMPONENT_STORY_DEFAULT_ARGS.applicationAccessToken}`,
+ );
+ },
+});
+
+export const SendInboxMessage: Story = {
+ ...sendInboxMessageStory,
+ beforeEach: () => {
+ receiveMetadataRequestAuthorization.mockClear();
+
+ return installMetadataFetchStub();
+ },
+};
diff --git a/packages/twenty-front/src/modules/ai/constants/AgentChatAssistantName.ts b/packages/twenty-front/src/modules/ai/constants/AgentChatAssistantName.ts
index 20c2c84c89f..c6156db7ed3 100644
--- a/packages/twenty-front/src/modules/ai/constants/AgentChatAssistantName.ts
+++ b/packages/twenty-front/src/modules/ai/constants/AgentChatAssistantName.ts
@@ -1,2 +1 @@
-// Fixed until assistants can be named per workspace
-export const AGENT_CHAT_ASSISTANT_NAME = 'Ada';
+export { AGENT_CHAT_ASSISTANT_NAME } from 'twenty-shared/ai';
diff --git a/packages/twenty-sdk/CHANGELOG.md b/packages/twenty-sdk/CHANGELOG.md
index 516b178dee6..8eb87728b82 100644
--- a/packages/twenty-sdk/CHANGELOG.md
+++ b/packages/twenty-sdk/CHANGELOG.md
@@ -32,6 +32,28 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
### Added
+- **`sendInboxMessage` in `twenty-sdk/front-component`.** A front component can post in members' inbox without a logic function in between. The message is still from your app; the call carries the component's token, so the member looking at the page needs the AI permission too, and an expired token is refreshed once before the call is retried. Open the conversation with `navigate`:
+
+ ```tsx
+ import {
+ AppPath,
+ navigate,
+ sendInboxMessage,
+ } from 'twenty-sdk/front-component';
+
+ const { threadId } = await sendInboxMessage(message);
+
+ await navigate(AppPath.AiChatInbox, { threadId });
+ ```
+
+- **Inbox mention helpers in `twenty-sdk/logic-function` and `twenty-sdk/front-component`.** `inboxMention({ workspaceMemberId })` and `inboxReferenceRecord({ objectNameSingular, recordId })` write the tokens the inbox renders as chips, labeled like the composer labels them: the member's full name, or the record's label identifier. `INBOX_ASSISTANT_MENTION` is the composer's mention of the assistant.
+
+ ```ts
+ import { inboxMention } from 'twenty-sdk/logic-function';
+
+ const text = `${await inboxMention({ workspaceMemberId })}, the report is ready.`;
+ ```
+
- **`useSelectedRecordsFilter` in `twenty-sdk/front-component`.** Returns a record filter matching exactly the records the user selected, or `null` when there is no selection context. Under Select all, `useSelectedRecordIds()` is empty because the selection is defined by the view's filters, search and unticked rows; query the records with this filter, or pass it to a logic function. Twenty servers that predate it return `null`.
```tsx
@@ -65,6 +87,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
### Changed
+- **`sendInboxMessage` runs like the default API clients.** It now sends through `MetadataApiClient`, so in a logic function it acts as the person who triggered the run, who then needs the AI permission, and as your application only when nobody did; it used to always use the application's access. A GraphQL error now rejects with the server's message instead of `sendInboxMessage() failed: ...`. Its input and result are unchanged.
- **`twenty app deploy` sends the tarball straight to file storage.** The CLI reserves an upload with `createFileUpload`, PUTs the archive to storage and registers it with `completeAppTarballUpload`, so the tarball no longer transits through the API process. Deploying to a server that predates these mutations fails instead of falling back to the multipart `uploadAppTarball` mutation.
- **`twenty-client-sdk` should now be a dev dependency too.** Although app code imports it (`CoreApiClient`, `MetadataApiClient`, `RestApiClient`), Twenty provides it at runtime — logic functions get it from a generated SDK layer and front components resolve it from server-served modules — so the installed copy is only needed for typechecking and the deploy-time build. Newly scaffolded apps now place it under `devDependencies`. Moving it is recommended (not required: the server already strips it from the deployed runtime), and keeps the installed app leaner:
diff --git a/packages/twenty-sdk/src/sdk/front-component/index.ts b/packages/twenty-sdk/src/sdk/front-component/index.ts
index 21c34c13894..f338e5304a3 100644
--- a/packages/twenty-sdk/src/sdk/front-component/index.ts
+++ b/packages/twenty-sdk/src/sdk/front-component/index.ts
@@ -74,6 +74,13 @@ export type {
CommandProps,
} from './command';
+export { sendInboxMessage } from '@/sdk/inbox/send-inbox-message';
+export { inboxMention } from '@/sdk/inbox/mentions/inbox-mention';
+export { inboxReferenceRecord } from '@/sdk/inbox/mentions/inbox-reference-record';
+export { INBOX_ASSISTANT_MENTION } from '@/sdk/inbox/mentions/inbox-assistant-mention';
+export type { SendInboxMessageInput } from '@/sdk/define/common/types/loose-shared-types.type';
+export type { SendInboxMessageResult } from 'twenty-shared/application';
+
export { AppPath, SidePanelPages } from 'twenty-shared/types';
export type {
EnqueueSnackbarParams,
diff --git a/packages/twenty-sdk/src/sdk/inbox/__tests__/send-inbox-message.spec.ts b/packages/twenty-sdk/src/sdk/inbox/__tests__/send-inbox-message.spec.ts
new file mode 100644
index 00000000000..e3499c61d8f
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/__tests__/send-inbox-message.spec.ts
@@ -0,0 +1,147 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+const THREAD_ID = '6f1d7c2a-3b4e-4f5a-8b9c-0d1e2f3a4b5c';
+
+const importSendInboxMessage = async () => {
+ const module = await import('@/sdk/inbox/send-inbox-message');
+
+ return module.sendInboxMessage;
+};
+
+const graphqlResponse = (body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+const successResponse = () =>
+ graphqlResponse({ data: { sendInboxMessage: { threadId: THREAD_ID } } });
+
+const MESSAGE_INPUT = {
+ workspaceMemberIds: ['20202020-0000-4000-8000-000000000001'],
+ threadKey: 'thread',
+ idempotencyKey: 'key',
+ title: 'Title',
+ text: 'Text',
+};
+
+const getSentAuthorizationHeader = (requestInit: RequestInit | undefined) =>
+ new Headers(requestInit?.headers).get('authorization');
+
+describe('sendInboxMessage', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ vi.resetModules();
+ vi.stubEnv('TWENTY_API_URL', 'https://api.test');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', undefined);
+ vi.stubEnv('TWENTY_APP_APPLICATION_ACCESS_TOKEN', 'app-token');
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ fetchSpy.mockRestore();
+ });
+
+ it('calls the sendInboxMessage mutation on the metadata API and returns the thread', async () => {
+ fetchSpy.mockResolvedValue(successResponse());
+
+ const sendInboxMessage = await importSendInboxMessage();
+
+ const input = {
+ workspaceMemberIds: ['20202020-0000-4000-8000-000000000001'],
+ threadKey: 'first-call-recording',
+ idempotencyKey: 'first-call-recording',
+ title: 'Your first recording is ready',
+ text: 'Your call was recorded.',
+ toolCall: {
+ toolName: 'ask_question' as const,
+ input: {
+ header: 'Share',
+ question: 'Share the recording with the attendees?',
+ options: [{ label: 'Draft an email' }, { label: 'Not now' }],
+ },
+ },
+ };
+
+ const result = await sendInboxMessage(input);
+
+ expect(result).toEqual({ threadId: THREAD_ID });
+
+ const [url, requestInit] = fetchSpy.mock.calls[0];
+
+ expect(url).toBe('https://api.test/metadata');
+
+ const sentBody = JSON.parse(String(requestInit?.body));
+
+ expect(sentBody.query).toContain('sendInboxMessage(input:$v1){threadId}');
+ expect(Object.values(sentBody.variables)).toEqual([input]);
+ });
+
+ it('sends the access token of the person behind the run, like the default clients', async () => {
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'member-token');
+ fetchSpy.mockResolvedValue(successResponse());
+
+ const sendInboxMessage = await importSendInboxMessage();
+
+ await sendInboxMessage(MESSAGE_INPUT);
+
+ const [, requestInit] = fetchSpy.mock.calls[0];
+
+ expect(getSentAuthorizationHeader(requestInit)).toBe('Bearer member-token');
+ });
+
+ it('refreshes an expired front component token once and retries', async () => {
+ vi.stubEnv('TWENTY_APP_APPLICATION_ACCESS_TOKEN', undefined);
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'expired-token');
+ const requestAccessTokenRefresh = vi
+ .fn()
+ .mockResolvedValue('refreshed-token');
+
+ vi.stubGlobal('frontComponentHostCommunicationApi', {
+ requestAccessTokenRefresh,
+ });
+ fetchSpy
+ .mockResolvedValueOnce(
+ new Response('Unauthorized', {
+ status: 401,
+ statusText: 'Unauthorized',
+ }),
+ )
+ .mockResolvedValueOnce(successResponse());
+
+ const sendInboxMessage = await importSendInboxMessage();
+
+ const result = await sendInboxMessage(MESSAGE_INPUT);
+
+ expect(result).toEqual({ threadId: THREAD_ID });
+ expect(requestAccessTokenRefresh).toHaveBeenCalledTimes(1);
+ expect(
+ fetchSpy.mock.calls.map(([, requestInit]) =>
+ getSentAuthorizationHeader(requestInit),
+ ),
+ ).toEqual(['Bearer expired-token', 'Bearer refreshed-token']);
+ });
+
+ it('surfaces GraphQL errors as a rejection', async () => {
+ fetchSpy.mockResolvedValue(
+ graphqlResponse({ errors: [{ message: 'Chat thread not found.' }] }),
+ );
+
+ const sendInboxMessage = await importSendInboxMessage();
+
+ await expect(sendInboxMessage(MESSAGE_INPUT)).rejects.toThrow(
+ /Chat thread not found/,
+ );
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-assistant-mention.spec.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-assistant-mention.spec.ts
new file mode 100644
index 00000000000..1dc35c4dd8e
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-assistant-mention.spec.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from 'vitest';
+
+import { INBOX_ASSISTANT_MENTION } from '@/sdk/inbox/mentions/inbox-assistant-mention';
+
+describe('INBOX_ASSISTANT_MENTION', () => {
+ it('equals the assistant mention the inbox composer writes', () => {
+ expect(INBOX_ASSISTANT_MENTION).toBe('@Ada');
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-mention.spec.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-mention.spec.ts
new file mode 100644
index 00000000000..2538f31b5af
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-mention.spec.ts
@@ -0,0 +1,102 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+const WORKSPACE_MEMBER_ID = '20202020-0000-4000-8000-000000000001';
+
+const importInboxMention = async () => {
+ const module = await import('@/sdk/inbox/mentions/inbox-mention');
+
+ return module.inboxMention;
+};
+
+type WorkspaceMemberFixture = {
+ name: { firstName: string; lastName: string };
+ userEmail: string;
+};
+
+const workspaceMemberResponse = (workspaceMember: WorkspaceMemberFixture) =>
+ new Response(JSON.stringify({ data: { workspaceMember } }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+describe('inboxMention', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ vi.resetModules();
+ vi.stubEnv('TWENTY_API_URL', 'https://api.test');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'access-token');
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ fetchSpy.mockRestore();
+ });
+
+ it('mentions a workspace member by the full name the composer shows', async () => {
+ fetchSpy.mockResolvedValue(
+ workspaceMemberResponse({
+ name: { firstName: 'Jony', lastName: 'Ive' },
+ userEmail: '[email protected]',
+ }),
+ );
+
+ const inboxMention = await importInboxMention();
+
+ await expect(
+ inboxMention({ workspaceMemberId: WORKSPACE_MEMBER_ID }),
+ ).resolves.toBe(
+ `[[record:workspaceMember:${WORKSPACE_MEMBER_ID}:Jony Ive]]`,
+ );
+
+ const [url, requestInit] = fetchSpy.mock.calls[0];
+
+ expect(String(url)).toBe(
+ `https://api.test/rest/workspaceMembers/${WORKSPACE_MEMBER_ID}`,
+ );
+ expect(requestInit?.method).toBe('GET');
+ });
+
+ it('falls back to the email of a member without a name', async () => {
+ fetchSpy.mockResolvedValue(
+ workspaceMemberResponse({
+ name: { firstName: '', lastName: '' },
+ userEmail: '[email protected]',
+ }),
+ );
+
+ const inboxMention = await importInboxMention();
+
+ await expect(
+ inboxMention({ workspaceMemberId: WORKSPACE_MEMBER_ID }),
+ ).resolves.toBe(
+ `[[record:workspaceMember:${WORKSPACE_MEMBER_ID}:[email protected]]]`,
+ );
+ });
+
+ it('keeps the mention renderable when the name has brackets or line breaks', async () => {
+ fetchSpy.mockResolvedValue(
+ workspaceMemberResponse({
+ name: { firstName: 'Jony [Design]', lastName: 'Ive\nJr' },
+ userEmail: '[email protected]',
+ }),
+ );
+
+ const inboxMention = await importInboxMention();
+
+ await expect(
+ inboxMention({ workspaceMemberId: WORKSPACE_MEMBER_ID }),
+ ).resolves.toBe(
+ `[[record:workspaceMember:${WORKSPACE_MEMBER_ID}:Jony (Design) Ive Jr]]`,
+ );
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-reference-record.spec.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-reference-record.spec.ts
new file mode 100644
index 00000000000..b388f2aa3b4
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/__tests__/inbox-reference-record.spec.ts
@@ -0,0 +1,176 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+const RECORD_ID = '20202020-0000-4000-8000-000000000003';
+const LABEL_IDENTIFIER_FIELD_ID = '20202020-0000-4000-8000-000000000004';
+
+type ObjectMetadataNode = {
+ id: string;
+ nameSingular: string;
+ namePlural: string;
+ labelIdentifierFieldMetadataId: string | null;
+};
+
+const importInboxReferenceRecord = async () => {
+ const module = await import('@/sdk/inbox/mentions/inbox-reference-record');
+
+ return module.inboxReferenceRecord;
+};
+
+const jsonResponse = (body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+const respondToMetadataAndRestRequests =
+ ({
+ objects,
+ labelIdentifierField,
+ record,
+ }: {
+ objects: ObjectMetadataNode[];
+ labelIdentifierField?: { name: string; type: string };
+ record: Record<string, unknown>;
+ }) =>
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+
+ if (url.startsWith('https://api.test/rest/')) {
+ return jsonResponse({ data: record });
+ }
+
+ const { query } = JSON.parse(String(init?.body));
+
+ if (query.includes('objects(')) {
+ return jsonResponse({
+ data: { objects: { edges: objects.map((node) => ({ node })) } },
+ });
+ }
+
+ return jsonResponse({
+ data: {
+ object: { fields: { edges: [{ node: labelIdentifierField }] } },
+ },
+ });
+ };
+
+const COMPANY_OBJECT = {
+ id: 'company-object-id',
+ nameSingular: 'company',
+ namePlural: 'companies',
+ labelIdentifierFieldMetadataId: LABEL_IDENTIFIER_FIELD_ID,
+};
+
+describe('inboxReferenceRecord', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ vi.resetModules();
+ vi.stubEnv('TWENTY_API_URL', 'https://api.test');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'access-token');
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ fetchSpy.mockRestore();
+ });
+
+ it('labels the reference with the record label identifier', async () => {
+ fetchSpy.mockImplementation(
+ respondToMetadataAndRestRequests({
+ objects: [COMPANY_OBJECT],
+ labelIdentifierField: { name: 'name', type: 'TEXT' },
+ record: { company: { id: RECORD_ID, name: 'Acme' } },
+ }),
+ );
+
+ const inboxReferenceRecord = await importInboxReferenceRecord();
+
+ await expect(
+ inboxReferenceRecord({
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ }),
+ ).resolves.toBe(`[[record:company:${RECORD_ID}:Acme]]`);
+ expect(fetchSpy.mock.calls.map(([input]) => String(input))).toContain(
+ `https://api.test/rest/companies/${RECORD_ID}`,
+ );
+ });
+
+ it('joins a full name label identifier', async () => {
+ fetchSpy.mockImplementation(
+ respondToMetadataAndRestRequests({
+ objects: [
+ {
+ id: 'person-object-id',
+ nameSingular: 'person',
+ namePlural: 'people',
+ labelIdentifierFieldMetadataId: LABEL_IDENTIFIER_FIELD_ID,
+ },
+ ],
+ labelIdentifierField: { name: 'name', type: 'FULL_NAME' },
+ record: {
+ person: {
+ id: RECORD_ID,
+ name: { firstName: 'Ada', lastName: 'Lovelace' },
+ },
+ },
+ }),
+ );
+
+ const inboxReferenceRecord = await importInboxReferenceRecord();
+
+ await expect(
+ inboxReferenceRecord({
+ objectNameSingular: 'person',
+ recordId: RECORD_ID,
+ }),
+ ).resolves.toBe(`[[record:person:${RECORD_ID}:Ada Lovelace]]`);
+ });
+
+ it('labels the reference with the record id when the object has no label identifier', async () => {
+ fetchSpy.mockImplementation(
+ respondToMetadataAndRestRequests({
+ objects: [{ ...COMPANY_OBJECT, labelIdentifierFieldMetadataId: null }],
+ record: { company: { id: RECORD_ID } },
+ }),
+ );
+
+ const inboxReferenceRecord = await importInboxReferenceRecord();
+
+ await expect(
+ inboxReferenceRecord({
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ }),
+ ).resolves.toBe(`[[record:company:${RECORD_ID}:${RECORD_ID}]]`);
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it('throws for an object the workspace does not have', async () => {
+ fetchSpy.mockImplementation(
+ respondToMetadataAndRestRequests({
+ objects: [COMPANY_OBJECT],
+ record: {},
+ }),
+ );
+
+ const inboxReferenceRecord = await importInboxReferenceRecord();
+
+ await expect(
+ inboxReferenceRecord({
+ objectNameSingular: 'invoice',
+ recordId: RECORD_ID,
+ }),
+ ).rejects.toThrow(/no invoice object/);
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-assistant-mention.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-assistant-mention.ts
new file mode 100644
index 00000000000..74f10f44a9d
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-assistant-mention.ts
@@ -0,0 +1,11 @@
+import {
+ AGENT_CHAT_ASSISTANT_MENTION_OBJECT_NAME_SINGULAR,
+ AGENT_CHAT_ASSISTANT_NAME,
+ formatRecordReference,
+} from 'twenty-shared/ai';
+
+export const INBOX_ASSISTANT_MENTION = formatRecordReference({
+ objectNameSingular: AGENT_CHAT_ASSISTANT_MENTION_OBJECT_NAME_SINGULAR,
+ recordId: AGENT_CHAT_ASSISTANT_MENTION_OBJECT_NAME_SINGULAR,
+ displayName: AGENT_CHAT_ASSISTANT_NAME,
+});
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-mention.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-mention.ts
new file mode 100644
index 00000000000..0d73167a671
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-mention.ts
@@ -0,0 +1,37 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { RestApiClient } from 'twenty-client-sdk/rest';
+import { formatRecordReference } from 'twenty-shared/ai';
+
+import { sanitizeInboxReferenceLabel } from '@/sdk/inbox/mentions/utils/sanitize-inbox-reference-label.util';
+
+type WorkspaceMemberResponse = {
+ data: {
+ workspaceMember: {
+ name: { firstName: string | null; lastName: string | null };
+ userEmail: string;
+ };
+ };
+};
+
+export const inboxMention = async ({
+ workspaceMemberId,
+}: {
+ workspaceMemberId: string;
+}): Promise<string> => {
+ const {
+ data: { workspaceMember },
+ } = await new RestApiClient().get<WorkspaceMemberResponse>(
+ `/rest/workspaceMembers/${workspaceMemberId}`,
+ );
+
+ const fullName =
+ `${workspaceMember.name.firstName ?? ''} ${workspaceMember.name.lastName ?? ''}`.trim();
+
+ return formatRecordReference({
+ objectNameSingular: 'workspaceMember',
+ recordId: workspaceMemberId,
+ displayName: sanitizeInboxReferenceLabel(
+ isNonEmptyString(fullName) ? fullName : workspaceMember.userEmail,
+ ),
+ });
+};
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-reference-record.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-reference-record.ts
new file mode 100644
index 00000000000..39bf833fc01
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/inbox-reference-record.ts
@@ -0,0 +1,41 @@
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+import { RestApiClient } from 'twenty-client-sdk/rest';
+import { formatRecordReference } from 'twenty-shared/ai';
+
+import { computeInboxRecordLabel } from '@/sdk/inbox/mentions/utils/compute-inbox-record-label.util';
+import { findInboxLabelIdentifierField } from '@/sdk/inbox/mentions/utils/find-inbox-label-identifier-field.util';
+import { findInboxObjectMetadataOrThrow } from '@/sdk/inbox/mentions/utils/find-inbox-object-metadata-or-throw.util';
+import { sanitizeInboxReferenceLabel } from '@/sdk/inbox/mentions/utils/sanitize-inbox-reference-label.util';
+
+export const inboxReferenceRecord = async ({
+ objectNameSingular,
+ recordId,
+}: {
+ objectNameSingular: string;
+ recordId: string;
+}): Promise<string> => {
+ const metadataClient = new MetadataApiClient();
+ const objectMetadata = await findInboxObjectMetadataOrThrow({
+ metadataClient,
+ objectNameSingular,
+ });
+
+ const [labelIdentifierField, recordResponse] = await Promise.all([
+ findInboxLabelIdentifierField({ metadataClient, objectMetadata }),
+ new RestApiClient().get<{
+ data: Record<string, Record<string, unknown>>;
+ }>(`/rest/${objectMetadata.namePlural}/${recordId}`),
+ ]);
+
+ return formatRecordReference({
+ objectNameSingular,
+ recordId,
+ displayName: sanitizeInboxReferenceLabel(
+ computeInboxRecordLabel({
+ record: recordResponse.data[objectNameSingular],
+ recordId,
+ labelIdentifierField,
+ }),
+ ),
+ });
+};
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/types/inbox-label-identifier-field.type.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/types/inbox-label-identifier-field.type.ts
new file mode 100644
index 00000000000..8595814d272
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/types/inbox-label-identifier-field.type.ts
@@ -0,0 +1,4 @@
+export type InboxLabelIdentifierField = {
+ name: string;
+ type: string;
+};
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/types/inbox-object-metadata.type.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/types/inbox-object-metadata.type.ts
new file mode 100644
index 00000000000..bb45716160c
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/types/inbox-object-metadata.type.ts
@@ -0,0 +1,5 @@
+export type InboxObjectMetadata = {
+ id: string;
+ namePlural: string;
+ labelIdentifierFieldMetadataId?: string | null;
+};
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/utils/compute-inbox-record-label.util.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/compute-inbox-record-label.util.ts
new file mode 100644
index 00000000000..5704f9c72b4
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/compute-inbox-record-label.util.ts
@@ -0,0 +1,38 @@
+import { isObject, isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type InboxLabelIdentifierField } from '@/sdk/inbox/mentions/types/inbox-label-identifier-field.type';
+
+const getFullNamePart = ({
+ fullName,
+ partName,
+}: {
+ fullName: unknown;
+ partName: 'firstName' | 'lastName';
+}): string => {
+ const part = isObject(fullName) ? Reflect.get(fullName, partName) : undefined;
+
+ return isString(part) ? part : '';
+};
+
+export const computeInboxRecordLabel = ({
+ record,
+ recordId,
+ labelIdentifierField,
+}: {
+ record: Record<string, unknown>;
+ recordId: string;
+ labelIdentifierField: InboxLabelIdentifierField | undefined;
+}): string => {
+ if (!isDefined(labelIdentifierField)) {
+ return recordId;
+ }
+
+ const labelValue = record[labelIdentifierField.name];
+
+ if (labelIdentifierField.type === 'FULL_NAME') {
+ return `${getFullNamePart({ fullName: labelValue, partName: 'firstName' })} ${getFullNamePart({ fullName: labelValue, partName: 'lastName' })}`.trim();
+ }
+
+ return isDefined(labelValue) ? String(labelValue) : '';
+};
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/utils/find-inbox-label-identifier-field.util.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/find-inbox-label-identifier-field.util.ts
new file mode 100644
index 00000000000..38eef268388
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/find-inbox-label-identifier-field.util.ts
@@ -0,0 +1,35 @@
+import { type MetadataApiClient } from 'twenty-client-sdk/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type InboxLabelIdentifierField } from '@/sdk/inbox/mentions/types/inbox-label-identifier-field.type';
+import { type InboxObjectMetadata } from '@/sdk/inbox/mentions/types/inbox-object-metadata.type';
+
+export const findInboxLabelIdentifierField = async ({
+ metadataClient,
+ objectMetadata,
+}: {
+ metadataClient: MetadataApiClient;
+ objectMetadata: Pick<
+ InboxObjectMetadata,
+ 'id' | 'labelIdentifierFieldMetadataId'
+ >;
+}): Promise<InboxLabelIdentifierField | undefined> => {
+ if (!isDefined(objectMetadata.labelIdentifierFieldMetadataId)) {
+ return undefined;
+ }
+
+ const { object } = await metadataClient.query({
+ object: {
+ __args: { id: objectMetadata.id },
+ fields: {
+ __args: {
+ filter: { id: { eq: objectMetadata.labelIdentifierFieldMetadataId } },
+ paging: { first: 1 },
+ },
+ edges: { node: { name: true, type: true } },
+ },
+ },
+ });
+
+ return object.fields.edges[0]?.node;
+};
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/utils/find-inbox-object-metadata-or-throw.util.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/find-inbox-object-metadata-or-throw.util.ts
new file mode 100644
index 00000000000..796f023be8d
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/find-inbox-object-metadata-or-throw.util.ts
@@ -0,0 +1,38 @@
+import { type MetadataApiClient } from 'twenty-client-sdk/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type InboxObjectMetadata } from '@/sdk/inbox/mentions/types/inbox-object-metadata.type';
+
+const OBJECTS_PAGE_SIZE = 1000;
+
+export const findInboxObjectMetadataOrThrow = async ({
+ metadataClient,
+ objectNameSingular,
+}: {
+ metadataClient: MetadataApiClient;
+ objectNameSingular: string;
+}): Promise<InboxObjectMetadata> => {
+ const { objects } = await metadataClient.query({
+ objects: {
+ __args: { filter: {}, paging: { first: OBJECTS_PAGE_SIZE } },
+ edges: {
+ node: {
+ id: true,
+ nameSingular: true,
+ namePlural: true,
+ labelIdentifierFieldMetadataId: true,
+ },
+ },
+ },
+ });
+
+ const objectMetadata = objects.edges.find(
+ ({ node }) => node.nameSingular === objectNameSingular,
+ )?.node;
+
+ if (!isDefined(objectMetadata)) {
+ throw new Error(`This workspace has no ${objectNameSingular} object.`);
+ }
+
+ return objectMetadata;
+};
diff --git a/packages/twenty-sdk/src/sdk/inbox/mentions/utils/sanitize-inbox-reference-label.util.ts b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/sanitize-inbox-reference-label.util.ts
new file mode 100644
index 00000000000..1b01aa0e67b
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/mentions/utils/sanitize-inbox-reference-label.util.ts
@@ -0,0 +1,10 @@
+const OPENING_BRACKET_PATTERN = /\[/g;
+const CLOSING_BRACKET_PATTERN = /\]/g;
+const LINE_BREAK_PATTERN = /\r?\n/g;
+
+export const sanitizeInboxReferenceLabel = (label: string): string =>
+ label
+ .replace(OPENING_BRACKET_PATTERN, '(')
+ .replace(CLOSING_BRACKET_PATTERN, ')')
+ .replace(LINE_BREAK_PATTERN, ' ')
+ .trim();
diff --git a/packages/twenty-sdk/src/sdk/inbox/send-inbox-message.ts b/packages/twenty-sdk/src/sdk/inbox/send-inbox-message.ts
new file mode 100644
index 00000000000..262c94687ba
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/inbox/send-inbox-message.ts
@@ -0,0 +1,19 @@
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+import { type SendInboxMessageResult } from 'twenty-shared/application';
+
+import { type SendInboxMessageInput } from '@/sdk/define/common/types/loose-shared-types.type';
+
+export const sendInboxMessage = async (
+ input: SendInboxMessageInput,
+): Promise<SendInboxMessageResult> => {
+ const client = new MetadataApiClient();
+
+ const { sendInboxMessage: result } = await client.mutation({
+ sendInboxMessage: {
+ __args: { input },
+ threadId: true,
+ },
+ });
+
+ return result;
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts
deleted file mode 100644
index d1b4526f227..00000000000
--- a/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import {
- afterEach,
- beforeEach,
- describe,
- expect,
- it,
- vi,
- type MockInstance,
-} from 'vitest';
-
-import { sendInboxMessage } from '@/sdk/logic-function/inbox/send-inbox-message';
-
-describe('sendInboxMessage', () => {
- let fetchSpy: MockInstance<typeof fetch>;
-
- beforeEach(() => {
- process.env.TWENTY_API_URL = 'https://api.test';
- process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'app-token';
- fetchSpy = vi.spyOn(globalThis, 'fetch');
- });
-
- afterEach(() => {
- delete process.env.TWENTY_API_URL;
- delete process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN;
- fetchSpy.mockRestore();
- });
-
- it('POSTs the sendInboxMessage mutation to /metadata and returns the thread', async () => {
- fetchSpy.mockResolvedValue(
- new Response(
- JSON.stringify({
- data: { sendInboxMessage: { threadId: 'thread-1' } },
- }),
- { status: 200 },
- ),
- );
-
- const input = {
- workspaceMemberIds: ['member-1'],
- threadKey: 'first-call-recording',
- idempotencyKey: 'first-call-recording',
- title: 'Your first recording is ready',
- text: 'Your call was recorded.',
- toolCall: {
- toolName: 'ask_question' as const,
- input: {
- header: 'Share',
- question: 'Share the recording with the attendees?',
- options: [{ label: 'Draft an email' }, { label: 'Not now' }],
- },
- },
- };
-
- const result = await sendInboxMessage(input);
-
- expect(result).toEqual({ threadId: 'thread-1' });
-
- const [url, requestInit] = fetchSpy.mock.calls[0];
-
- expect(url).toBe('https://api.test/metadata');
- expect(requestInit).toEqual(
- expect.objectContaining({
- method: 'POST',
- headers: expect.objectContaining({
- Authorization: 'Bearer app-token',
- }),
- }),
- );
-
- const sentBody = JSON.parse(requestInit?.body as string);
-
- expect(sentBody.query).toContain('sendInboxMessage(input: $input)');
- expect(sentBody.variables).toEqual({ input });
- });
-
- it('surfaces GraphQL errors as a regular Error', async () => {
- fetchSpy.mockResolvedValue(
- new Response(
- JSON.stringify({ errors: [{ message: 'Chat thread not found.' }] }),
- { status: 200 },
- ),
- );
-
- await expect(
- sendInboxMessage({
- workspaceMemberIds: ['member-1'],
- threadKey: 'thread',
- idempotencyKey: 'key',
- title: 'Title',
- text: 'Text',
- }),
- ).rejects.toThrow(/Chat thread not found/);
- });
-});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/inbox/send-inbox-message.ts b/packages/twenty-sdk/src/sdk/logic-function/inbox/send-inbox-message.ts
deleted file mode 100644
index 47b1b406176..00000000000
--- a/packages/twenty-sdk/src/sdk/logic-function/inbox/send-inbox-message.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { type SendInboxMessageResult } from 'twenty-shared/application';
-
-import { type SendInboxMessageInput } from '@/sdk/define/common/types/loose-shared-types.type';
-import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
-
-const SEND_INBOX_MESSAGE_MUTATION = `
- mutation SendInboxMessage($input: SendInboxMessageInput!) {
- sendInboxMessage(input: $input) {
- threadId
- }
- }
-`;
-
-export const sendInboxMessage = async (
- input: SendInboxMessageInput,
-): Promise<SendInboxMessageResult> => {
- const { sendInboxMessage: result } = await postGraphqlRequest<
- { input: SendInboxMessageInput },
- { sendInboxMessage: SendInboxMessageResult }
- >({
- query: SEND_INBOX_MESSAGE_MUTATION,
- variables: { input },
- caller: 'sendInboxMessage',
- });
-
- return result;
-};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index c19b835cbe8..0955c038d25 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -84,7 +84,10 @@ export type { AppMessageFolder } from '@/sdk/logic-function/messaging/types/app-
export { runAgent } from '@/sdk/logic-function/agents/run-agent';
export type { RunAgentInput, RunAgentResult } from 'twenty-shared/application';
-export { sendInboxMessage } from '@/sdk/logic-function/inbox/send-inbox-message';
+export { sendInboxMessage } from '@/sdk/inbox/send-inbox-message';
+export { inboxMention } from '@/sdk/inbox/mentions/inbox-mention';
+export { inboxReferenceRecord } from '@/sdk/inbox/mentions/inbox-reference-record';
+export { INBOX_ASSISTANT_MENTION } from '@/sdk/inbox/mentions/inbox-assistant-mention';
export type { SendInboxMessageInput } from '@/sdk/define/common/types/loose-shared-types.type';
export type { SendInboxMessageResult } from 'twenty-shared/application';
diff --git a/packages/twenty-shared/src/ai/constants/agent-chat-assistant-name.const.ts b/packages/twenty-shared/src/ai/constants/agent-chat-assistant-name.const.ts
new file mode 100644
index 00000000000..4ec664ea8f7
--- /dev/null
+++ b/packages/twenty-shared/src/ai/constants/agent-chat-assistant-name.const.ts
@@ -0,0 +1 @@
+export const AGENT_CHAT_ASSISTANT_NAME = 'Ada';
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index e43014b436a..51fd0ba58cc 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -8,6 +8,7 @@
*/
export { AGENT_CHAT_ASSISTANT_MENTION_OBJECT_NAME_SINGULAR } from './constants/agent-chat-assistant-mention-object-name-singular.const';
+export { AGENT_CHAT_ASSISTANT_NAME } from './constants/agent-chat-assistant-name.const';
export { AGENT_MESSAGE_REACTION_EMOJI_MAX_LENGTH } from './constants/agent-message-reaction-emoji-max-length.const';
export type { AiEvaluationQuestionType } from './constants/ai-evaluation-question-type.const';
export { AI_EVALUATION_QUESTION_TYPES } from './constants/ai-evaluation-question-type.const';
diff --git a/packages/twenty-shared/src/constants/DocumentationPaths.ts b/packages/twenty-shared/src/constants/DocumentationPaths.ts
index c2c9e9585ae..c452fae4695 100644
--- a/packages/twenty-shared/src/constants/DocumentationPaths.ts
+++ b/packages/twenty-shared/src/constants/DocumentationPaths.ts
@@ -66,6 +66,7 @@ export const DOCUMENTATION_PATHS = {
DEVELOPERS_EXTEND_APPS_LOGIC_CONNECTIONS:
'/developers/extend/apps/logic/connections',
DEVELOPERS_EXTEND_APPS_LOGIC_CREDITS: '/developers/extend/apps/logic/credits',
+ DEVELOPERS_EXTEND_APPS_LOGIC_INBOX: '/developers/extend/apps/logic/inbox',
DEVELOPERS_EXTEND_APPS_LOGIC_KEY_VALUE_STORE:
'/developers/extend/apps/logic/key-value-store',
DEVELOPERS_EXTEND_APPS_LOGIC_LOGIC_FUNCTIONS: