The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(slack): restrict the assistant to linked members, drop the default role (#27533)
Abdul Rahman2606aabf2bf1
diff --git a/packages/twenty-apps/public/slack/README.md b/packages/twenty-apps/public/slack/README.mdindex 1e173ae21b6..edbfc42dcc3 100644--- a/packages/twenty-apps/public/slack/README.md+++ b/packages/twenty-apps/public/slack/README.md@@ -6,7 +6,7 @@- **A CRM assistant in Slack**: `@twenty how many open opportunities do we have?` It answers as whoever tagged it- **Slack steps for your workflows**: post, update or delete messages, send ephemerals, add reactions, list channels-- **Open by default, restrict when you want**: in the Settings tab, limit the assistant to Slack accounts linked to a workspace member+- **Linked members only**: the assistant answers only Slack accounts linked to a workspace member, and always acts with that member's own permissions## 💳 Billingdiff --git a/packages/twenty-apps/public/slack/SETUP.md b/packages/twenty-apps/public/slack/SETUP.mdindex ccc23b7a322..fc54af3926d 100644--- a/packages/twenty-apps/public/slack/SETUP.md+++ b/packages/twenty-apps/public/slack/SETUP.md@@ -188,14 +188,17 @@ Once both are set, **reconnect** so the token picks up the assistant scopes.### Permissions-The `slack-assistant` agent binds to the app's **Slack Assistant** role-automatically on install and upgrade. That role is the ceiling for everything-the bot can do.--Where a Slack account is linked to a workspace member, the bot also runs with-that member's own permissions, so it can never do more than the person asking.-Accounts with no link act with the Slack Assistant role alone, so keep it scoped-to what you're comfortable exposing to anyone who can message the bot.+Only a Slack account linked to a workspace member can use the assistant. An+account with no link is told to ask an admin for a link, and a linked member+whose message was not addressed to the assistant (for example a reply in a+followed thread from someone who never mentioned it there) is asked to mention+it in a new message.++Every answer runs with the linked member's own permissions, so the assistant can+never do more than the person asking. The app's role only covers what the app's+own functions need: tracking assistant requests, linking Slack accounts, reading+workspace members for the email match and rendering record previews. It is not+an extra ceiling on a member's answer.## Linking Slack accounts to workspace members@@ -403,4 +406,5 @@ Fields use camelCase in the step UI:| Feedback buttons show a warning when clicked | **Interactivity & Shortcuts** is not enabled, or its Request URL is wrong | Enable it and set the `slack-interactivity-resolver` URL above || Connecting is rejected because the Slack team is already claimed | Another Twenty workspace on this server has connected the same Slack team | Remove the connection on that workspace, or uninstall the app there, to release the claim || A manual link stays *Awaiting consent* | The person has not answered the consent DM, or `im:write` was not granted so it was never sent | Resend the request from the **Slack user links** settings section; if nothing arrives, reconnect to grant `im:write` |-| The bot acts with the Slack Assistant role instead of the member's permissions | The Slack account has no link, or its verified email no longer matches the member | Check the link's status in the settings section and link the account by hand if the email cannot match |+| The bot declines a person with *"not linked"* instead of answering | The Slack account has no link, or its verified email no longer matches the member | Check the link's status in the settings section and link the account by hand if the email cannot match |+| The bot asks a linked member to mention it in a new message | The message was not addressed to the assistant, such as a reply in a followed thread from someone who never mentioned it there | Mention the assistant in a new message |diff --git a/packages/twenty-apps/public/slack/package.json b/packages/twenty-apps/public/slack/package.jsonindex c4042c6e396..252a0b6e589 100644--- a/packages/twenty-apps/public/slack/package.json+++ b/packages/twenty-apps/public/slack/package.json@@ -1,6 +1,6 @@{"name": "@twentyhq/slack",- "version": "1.6.0",+ "version": "1.7.0","description": "Slack assistant and workflow steps for Twenty","license": "MIT","engines": {diff --git a/packages/twenty-apps/public/slack/src/__tests__/slack-assistant-worker.integration-test.ts b/packages/twenty-apps/public/slack/src/__tests__/slack-assistant-worker.integration-test.tsindex 83d9f2d1ae8..9e30f3fb408 100644--- a/packages/twenty-apps/public/slack/src/__tests__/slack-assistant-worker.integration-test.ts+++ b/packages/twenty-apps/public/slack/src/__tests__/slack-assistant-worker.integration-test.ts@@ -1,8 +1,11 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';import { afterEach, describe, expect, it } from 'vitest';import { createSlackMessageTimestampSequence } from 'src/__tests__/utils/create-slack-message-timestamp-sequence.util';import { requireDefinedOrThrow } from 'src/__tests__/utils/require-defined-or-throw.util';import { setupSlackIntegrationTest } from 'src/__tests__/utils/setup-slack-integration-test.util';+import { SLACK_ACCESS_DENIED_TEXT } from 'src/logic-functions/constants/slack-access-denied-text';import { SLACK_ASSISTANT_DEADLINE_ERROR } from 'src/logic-functions/constants/slack-assistant-deadline-error';import { SLACK_ASSISTANT_DEADLINE_FAILURE_TEXT } from 'src/logic-functions/constants/slack-assistant-deadline-failure-text';import { SLACK_ASSISTANT_EMPTY_RESPONSE_ERROR } from 'src/logic-functions/constants/slack-assistant-empty-response-error';@@ -18,6 +21,7 @@ import { getSlackThreadKvKey } from 'src/logic-functions/utils/get-slack-thread-const CHANNEL_ID = 'C0WORKERTEST';const DIRECT_MESSAGE_CHANNEL_ID = 'D0WORKERTEST';const REQUESTER_USER_ID = 'U0REQUESTER';+const CONFIRMED_MEMBER_EMAIL = '[email protected]';type SlackAssistantRequestStatus =(typeof SLACK_ASSISTANT_REQUEST_STATUS)[keyof typeof SLACK_ASSISTANT_REQUEST_STATUS];@@ -38,6 +42,19 @@ describe('Slack assistant worker', () => {const createdRequestIds: string[] = [];const nextMessageTimestamp = createSlackMessageTimestampSequence(1);+ const mentionBot = (text: string): string => `<@${slack.botUserId}> ${text}`;++ const addConfirmedRequester = (): void => {+ slack.addUser({+ id: REQUESTER_USER_ID,+ displayName: 'Ada',+ email: CONFIRMED_MEMBER_EMAIL,+ });+ };++ const botMessagesIn = (channelId: string) =>+ slack.messagesIn(channelId).filter((message) => isDefined(message.botId));+const createRequestRecord = async (fields: {slackChannelId: string;slackMessageTimestamp: string;@@ -55,6 +72,11 @@ describe('Slack assistant worker', () => {slackThreadTimestamp: '',slackUserId: REQUESTER_USER_ID,slackEventId: `Ev${fields.slackMessageTimestamp}`,+ createdBy: {+ source: 'APPLICATION',+ workspaceMemberId: null,+ name: 'Slack',+ },...fields,},},@@ -116,11 +138,28 @@ describe('Slack assistant worker', () => {}createdRequestIds.length = 0;++ const linkQuery = await coreClient.query({+ slackUserLinks: {+ __args: { filter: { slackUserId: { eq: REQUESTER_USER_ID } } },+ edges: { node: { id: true } },+ },+ });++ for (const edge of linkQuery.slackUserLinks?.edges ?? []) {+ const linkId = edge?.node?.id;++ if (isNonEmptyString(linkId)) {+ await coreClient.mutation({+ destroySlackUserLink: { __args: { id: linkId }, id: true },+ });+ }+ }});it('should resolve mentions and channel references before the agent sees them', async () => {slack.addChannel({ id: CHANNEL_ID, name: 'sales' });- slack.addUser({ id: REQUESTER_USER_ID, displayName: 'Ada' });+ addConfirmedRequester();slack.addUser({ id: 'U0UNLINKED', displayName: 'Bob Lee' });const slackMessageTimestamp = nextMessageTimestamp();@@ -131,7 +170,7 @@ describe('Slack assistant worker', () => {channelId: CHANNEL_ID,timestamp: slackMessageTimestamp,userId: REQUESTER_USER_ID,- text: requestText,+ text: mentionBot(requestText),});const request = await createRequestRecord({@@ -163,14 +202,14 @@ describe('Slack assistant worker', () => {it('should answer a channel request in its thread, store the answer and subscribe the thread', async () => {slack.addChannel({ id: CHANNEL_ID, name: 'sales' });- slack.addUser({ id: REQUESTER_USER_ID, displayName: 'Ada' });+ addConfirmedRequester();const slackMessageTimestamp = nextMessageTimestamp();slack.addMessage({channelId: CHANNEL_ID,timestamp: slackMessageTimestamp,userId: REQUESTER_USER_ID,- text: 'how many open deals does Acme have?',+ text: mentionBot('how many open deals does Acme have?'),});slack.addMessage({channelId: CHANNEL_ID,@@ -208,9 +247,6 @@ describe('Slack assistant worker', () => {expect(result).toEqual({ done: true });- // The thread is replayed as turns, the bot's own earlier reply as an- // assistant turn without its footer, and the message that triggered this- // run is left out of its own context.expect(appRuntime.lastAgentMessages).toEqual([{role: 'user',@@ -224,17 +260,15 @@ describe('Slack assistant worker', () => {),},]);- // A request record the app did not write earns no run-as, so the agent- // keeps its own role.const agentMessages = appRuntime.lastAgentMessages;const agentRuns = appRuntime.agentRuns;+ const runAsWorkspaceMemberId =+ agentRuns[agentRuns.length - 1]?.runAsWorkspaceMemberId;+ expect(isNonEmptyString(runAsWorkspaceMemberId)).toBe(true);expect(agentMessages[agentMessages.length - 1]?.content).toContain(- "You are answering with the app's own role",+ `You are acting as workspace member ${runAsWorkspaceMemberId}, with that member's own permissions.`,);- expect(- agentRuns[agentRuns.length - 1]?.runAsWorkspaceMemberId,- ).toBeUndefined();expect(slack.assistantStatuses).toEqual([{@@ -249,14 +283,12 @@ describe('Slack assistant worker', () => {.find((message) =>message.threadTimestamp === slackMessageTimestamp &&- message.botId !== undefined &&+ isDefined(message.botId) &&message.blocks !== undefined,);expect(postedAnswer?.blocks).toEqual([{ type: 'markdown', text: 'Acme has 3 open deals.' },- // The feedback buttons carry the request record id, which is how a click- // finds the answer it rates.expect.objectContaining({type: 'context_actions',block_id: request.id,@@ -268,7 +300,6 @@ describe('Slack assistant worker', () => {],}),]);- // Record links in the answer must not turn into Slack previews.expect(slack.lastCallTo('chat.postMessage')?.args).toEqual(expect.objectContaining({ unfurl_links: false, unfurl_media: false }),);@@ -293,8 +324,16 @@ describe('Slack assistant worker', () => {it('should title the assistant thread of a first direct message instead of subscribing it', async () => {slack.addChannel({ id: DIRECT_MESSAGE_CHANNEL_ID, name: 'twenty' });+ addConfirmedRequester();const slackMessageTimestamp = nextMessageTimestamp();+ slack.addMessage({+ channelId: DIRECT_MESSAGE_CHANNEL_ID,+ timestamp: slackMessageTimestamp,+ userId: REQUESTER_USER_ID,+ text: 'list my tasks for today',+ });+const request = await createRequestRecord({slackChannelId: DIRECT_MESSAGE_CHANNEL_ID,slackChannelType: 'im',@@ -332,8 +371,16 @@ describe('Slack assistant worker', () => {it('should post the failure notice and fail the request when the agent errors', async () => {slack.addChannel({ id: CHANNEL_ID, name: 'sales' });+ addConfirmedRequester();const slackMessageTimestamp = nextMessageTimestamp();+ slack.addMessage({+ channelId: CHANNEL_ID,+ timestamp: slackMessageTimestamp,+ userId: REQUESTER_USER_ID,+ text: mentionBot('who owns Acme?'),+ });+appRuntime.setAgentResult({success: false,result: null,@@ -359,7 +406,7 @@ describe('Slack assistant worker', () => {failed: true,reason: 'Agent is not available',});- expect(slack.messagesIn(CHANNEL_ID)).toEqual([+ expect(botMessagesIn(CHANNEL_ID)).toEqual([expect.objectContaining({text: SLACK_ASSISTANT_FAILURE_TEXT,threadTimestamp: slackMessageTimestamp,@@ -375,8 +422,16 @@ describe('Slack assistant worker', () => {it('should tell the member to narrow the request when the answer deadline passes', async () => {slack.addChannel({ id: CHANNEL_ID, name: 'sales' });+ addConfirmedRequester();const slackMessageTimestamp = nextMessageTimestamp();+ slack.addMessage({+ channelId: CHANNEL_ID,+ timestamp: slackMessageTimestamp,+ userId: REQUESTER_USER_ID,+ text: mentionBot('summarize every opportunity we opened this year'),+ });+appRuntime.setAgentResult({success: false,result: null,@@ -402,7 +457,7 @@ describe('Slack assistant worker', () => {failed: true,reason: SLACK_ASSISTANT_DEADLINE_ERROR,});- expect(slack.messagesIn(CHANNEL_ID)).toEqual([+ expect(botMessagesIn(CHANNEL_ID)).toEqual([expect.objectContaining({text: SLACK_ASSISTANT_DEADLINE_FAILURE_TEXT,threadTimestamp: slackMessageTimestamp,@@ -418,8 +473,16 @@ describe('Slack assistant worker', () => {it('should invite the member to ask again when the agent answers with nothing', async () => {slack.addChannel({ id: CHANNEL_ID, name: 'sales' });+ addConfirmedRequester();const slackMessageTimestamp = nextMessageTimestamp();+ slack.addMessage({+ channelId: CHANNEL_ID,+ timestamp: slackMessageTimestamp,+ userId: REQUESTER_USER_ID,+ text: mentionBot('what changed on Acme this week?'),+ });+appRuntime.setAgentResult({success: true,result: null,@@ -445,7 +508,7 @@ describe('Slack assistant worker', () => {failed: true,reason: SLACK_ASSISTANT_EMPTY_RESPONSE_ERROR,});- expect(slack.messagesIn(CHANNEL_ID)).toEqual([+ expect(botMessagesIn(CHANNEL_ID)).toEqual([expect.objectContaining({text: SLACK_ASSISTANT_EMPTY_RESPONSE_FAILURE_TEXT,threadTimestamp: slackMessageTimestamp,@@ -461,9 +524,17 @@ describe('Slack assistant worker', () => {it('should fail the request when Slack refuses to deliver the answer', async () => {slack.addChannel({ id: CHANNEL_ID, name: 'sales' });+ addConfirmedRequester();slack.failNextCall('chat.postMessage', 'channel_not_found');const slackMessageTimestamp = nextMessageTimestamp();+ slack.addMessage({+ channelId: CHANNEL_ID,+ timestamp: slackMessageTimestamp,+ userId: REQUESTER_USER_ID,+ text: mentionBot('summarize the Acme thread'),+ });+const request = await createRequestRecord({slackChannelId: CHANNEL_ID,slackMessageTimestamp,@@ -492,9 +563,17 @@ describe('Slack assistant worker', () => {it('should keep the feedback buttons on an answer too long for a markdown block', async () => {slack.addChannel({ id: CHANNEL_ID, name: 'sales' });+ addConfirmedRequester();const slackMessageTimestamp = nextMessageTimestamp();const longResponse = 'a'.repeat(SLACK_MARKDOWN_BLOCK_MAX_LENGTH + 1);+ slack.addMessage({+ channelId: CHANNEL_ID,+ timestamp: slackMessageTimestamp,+ userId: REQUESTER_USER_ID,+ text: mentionBot('give me the full account history'),+ });+appRuntime.setAgentResult({success: true,result: { response: longResponse },@@ -541,6 +620,49 @@ describe('Slack assistant worker', () => {);});+ it('should decline a requester it cannot tie to a workspace member', async () => {+ slack.addChannel({ id: CHANNEL_ID, name: 'sales' });+ slack.addUser({ id: REQUESTER_USER_ID, displayName: 'Ada' });+ const slackMessageTimestamp = nextMessageTimestamp();++ slack.addMessage({+ channelId: CHANNEL_ID,+ timestamp: slackMessageTimestamp,+ userId: REQUESTER_USER_ID,+ text: mentionBot('who owns Acme?'),+ });++ const request = await createRequestRecord({+ slackChannelId: CHANNEL_ID,+ slackMessageTimestamp,+ requestText: 'who owns Acme?',+ });++ const result = await slackAssistantWorkerHandler(+ buildPendingRequest({+ ...request,+ slackChannelId: CHANNEL_ID,+ slackMessageTimestamp,+ requestText: 'who owns Acme?',+ }),+ );++ expect(result).toEqual({ done: true, declined: true });+ expect(appRuntime.agentRuns).toHaveLength(0);+ expect(botMessagesIn(CHANNEL_ID)).toEqual([+ expect.objectContaining({+ markdownText: SLACK_ACCESS_DENIED_TEXT,+ threadTimestamp: slackMessageTimestamp,+ }),+ ]);+ await expect(readRequest(request.id)).resolves.toEqual(+ expect.objectContaining({+ status: SLACK_ASSISTANT_REQUEST_STATUS.DONE,+ responseText: SLACK_ACCESS_DENIED_TEXT,+ }),+ );+ });+it('should skip a request that another worker already picked up', async () => {const slackMessageTimestamp = nextMessageTimestamp();diff --git a/packages/twenty-apps/public/slack/src/agents/slack-assistant.agent.ts b/packages/twenty-apps/public/slack/src/agents/slack-assistant.agent.tsindex 32741f57e2e..bf1beafa074 100644--- a/packages/twenty-apps/public/slack/src/agents/slack-assistant.agent.ts+++ b/packages/twenty-apps/public/slack/src/agents/slack-assistant.agent.ts@@ -2,8 +2,8 @@ import { defineAgent } from 'twenty-sdk/define';import { DEFAULT_SLACK_ASSISTANT_PROMPT } from 'src/constants/default-slack-assistant-prompt';import {+ DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,SLACK_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER,- SLACK_ASSISTANT_ROLE_UNIVERSAL_IDENTIFIER,} from 'src/constants/universal-identifiers';export default defineAgent({@@ -12,8 +12,8 @@ export default defineAgent({label: 'Slack Assistant',icon: 'IconBrandSlack',description:- 'Conversational CRM assistant reached from Slack. Answers questions and acts on workspace data using the Slack Assistant role.',+ 'Conversational CRM assistant reached from Slack. Answers questions and acts on workspace data as the linked workspace member who made the request.',prompt: DEFAULT_SLACK_ASSISTANT_PROMPT,responseFormat: { type: 'text' },- roleUniversalIdentifier: SLACK_ASSISTANT_ROLE_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,});diff --git a/packages/twenty-apps/public/slack/src/constants/slack-access-mode-route-path.constant.ts b/packages/twenty-apps/public/slack/src/constants/slack-access-mode-route-path.constant.tsdeleted file mode 100644index b5af58c2e74..00000000000--- a/packages/twenty-apps/public/slack/src/constants/slack-access-mode-route-path.constant.ts+++ /dev/null@@ -1,3 +0,0 @@-export const SLACK_ACCESS_MODE_GET_ROUTE_PATH = '/slack-access-mode';--export const SLACK_ACCESS_MODE_SET_ROUTE_PATH = '/slack-access-mode/set';diff --git a/packages/twenty-apps/public/slack/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/slack/src/constants/universal-identifiers.tsindex 032c1996b3a..0cd11ab943e 100644--- a/packages/twenty-apps/public/slack/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/slack/src/constants/universal-identifiers.ts@@ -28,9 +28,6 @@ export const SLACK_LIST_CHANNELS_UNIVERSAL_IDENTIFIER =export const SLACK_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER ='9f3a1c72-6b4e-4d8a-9c1f-2e5b7a8d3c60';-export const SLACK_ASSISTANT_ROLE_UNIVERSAL_IDENTIFIER =- 'a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d';-export const SLACK_EVENTS_ROUTE_UNIVERSAL_IDENTIFIER ='9ad6fa20-dff5-4d3f-ad5f-084f3c8b0b09';@@ -190,11 +187,5 @@ export const SLACK_CONNECTION_STATUS_UNIVERSAL_IDENTIFIER =export const SLACK_DELIVER_MESSAGE_UNIVERSAL_IDENTIFIER ='cc43a728-7b9f-43c6-a9a2-bd1196204822';-export const SLACK_ACCESS_MODE_GET_UNIVERSAL_IDENTIFIER =- 'bc06872e-4978-4476-b655-fc234ce64592';--export const SLACK_ACCESS_MODE_SET_UNIVERSAL_IDENTIFIER =- '34458aca-bf05-4dc6-a002-b1786ca42652';-export const SLACK_HEALTH_CHECK_UNIVERSAL_IDENTIFIER ='7c303a5c-80ff-4e27-9997-c6c14239c0ba';diff --git a/packages/twenty-apps/public/slack/src/front-components/components/SlackAccessModeSection.tsx b/packages/twenty-apps/public/slack/src/front-components/components/SlackAccessModeSection.tsxdeleted file mode 100644index 376de4e377c..00000000000--- a/packages/twenty-apps/public/slack/src/front-components/components/SlackAccessModeSection.tsx+++ /dev/null@@ -1,171 +0,0 @@-import styled from '@emotion/styled';-import { isNonEmptyString } from '@sniptt/guards';-import { useId } from 'react';-import { enqueueSnackbar } from 'twenty-sdk/front-component';-import { IconLock } from 'twenty-ui/icon';-import { Section } from 'twenty-ui/layout';-import { Card } from 'twenty-ui/surfaces';-import { THEME_COMMON } from 'twenty-ui/theme';-import { themeCssVariables } from 'twenty-ui/theme-constants';-import { H2Title } from 'twenty-ui/typography';--import { Toggle } from 'src/front-components/components/Toggle';-import { useSlackAccessMode } from 'src/front-components/hooks/use-slack-access-mode';-import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';--const StyledCardContent = styled.div<{ $disabled: boolean }>`- align-items: center;- background-color: ${() => themeCssVariables.background.secondary};- cursor: ${({ $disabled }) => ($disabled ? 'default' : 'pointer')};- display: flex;- gap: ${() => themeCssVariables.spacing[3]};- padding: ${() => themeCssVariables.spacing[4]};- pointer-events: ${({ $disabled }) => ($disabled ? 'none' : 'auto')};- position: relative;-- &:hover {- background: ${() => themeCssVariables.background.transparent.lighter};- }-`;--const StyledIcon = styled.div`- align-items: center;- background-color: ${() => themeCssVariables.background.primary};- border: 2px solid ${() => themeCssVariables.border.color.light};- border-radius: ${() => themeCssVariables.border.radius.sm};- box-sizing: border-box;- color: ${() => themeCssVariables.font.color.secondary};- display: flex;- height: ${() => themeCssVariables.spacing[8]};- justify-content: center;- min-width: ${() => themeCssVariables.spacing[8]};- width: ${() => themeCssVariables.spacing[8]};-`;--const StyledTextContainer = styled.div`- flex: 1;- min-width: 0;-`;--const StyledTitle = styled.div`- color: ${() => themeCssVariables.font.color.primary};- font-family: ${() => themeCssVariables.font.family};- font-weight: ${() => themeCssVariables.font.weight.medium};- margin-bottom: ${() => themeCssVariables.spacing[1]};-`;--const StyledDescription = styled.div`- color: ${() => themeCssVariables.font.color.secondary};- font-family: ${() => themeCssVariables.font.family};- font-size: ${() => themeCssVariables.font.size.sm};- line-height: ${() => themeCssVariables.text.lineHeight.lg};- overflow-wrap: break-word;-`;--const StyledCover = styled.span`- cursor: pointer;- inset: 0;- position: absolute;-`;--const StyledToggleContainer = styled.span`- align-items: center;- display: flex;- flex-shrink: 0;- margin-left: auto;-`;--const RESTRICTED_DESCRIPTION =- 'Only Slack accounts linked to a workspace member can use it.';--const OPEN_DESCRIPTION =- 'Anyone who can mention the assistant in Slack can use it.';--const UNREADABLE_DESCRIPTION =- 'The current setting could not be loaded. Reload to try again.';--const getDescription = ({- hasAccessModeError,- isRestricted,-}: {- hasAccessModeError: boolean;- isRestricted: boolean;-}): string => {- if (hasAccessModeError) {- return UNREADABLE_DESCRIPTION;- }-- return isRestricted ? RESTRICTED_DESCRIPTION : OPEN_DESCRIPTION;-};--type SlackAccessModeSectionProps = {- canManage: boolean;-};--export const SlackAccessModeSection = ({- canManage,-}: SlackAccessModeSectionProps) => {- const toggleId = useId();- const {- accessMode,- hasAccessModeError,- isAccessModeLoading,- isSavingAccessMode,- saveAccessMode,- } = useSlackAccessMode();-- const isRestricted = accessMode === SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS;-- const isDisabled =- !canManage ||- hasAccessModeError ||- isAccessModeLoading ||- isSavingAccessMode;-- const handleToggle = async (value: boolean) => {- const result = await saveAccessMode(- value ? SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS : SLACK_ACCESS_MODE.ANYONE,- );-- enqueueSnackbar({- message: isNonEmptyString(result.error) ? result.error : result.message,- variant: result.success ? 'success' : 'error',- });- };-- const description = getDescription({ hasAccessModeError, isRestricted });-- return (- <Section>- <H2Title- title="Access"- description="Choose who the assistant answers in Slack."- />- <Card rounded>- <StyledCardContent $disabled={isDisabled}>- <StyledIcon>- <IconLock size={THEME_COMMON.icon.size.md} />- </StyledIcon>- <StyledTextContainer>- <StyledTitle>- <label htmlFor={toggleId}>- Restrict to linked members- <StyledCover />- </label>- </StyledTitle>- <StyledDescription>{description}</StyledDescription>- </StyledTextContainer>- <StyledToggleContainer>- <Toggle- id={toggleId}- checked={isRestricted}- onChange={handleToggle}- disabled={isDisabled}- ariaLabel="Restrict the assistant to linked members"- />- </StyledToggleContainer>- </StyledCardContent>- </Card>- </Section>- );-};diff --git a/packages/twenty-apps/public/slack/src/front-components/components/SlackUserLinksSettings.tsx b/packages/twenty-apps/public/slack/src/front-components/components/SlackUserLinksSettings.tsxindex 6cc8d3f0ddc..b7928badbdb 100644--- a/packages/twenty-apps/public/slack/src/front-components/components/SlackUserLinksSettings.tsx+++ b/packages/twenty-apps/public/slack/src/front-components/components/SlackUserLinksSettings.tsx@@ -13,7 +13,6 @@ import { Section } from 'twenty-ui/layout';import { ThemeProvider, themeCssVariables } from 'twenty-ui/theme-constants';import { H2Title } from 'twenty-ui/typography';-import { SlackAccessModeSection } from 'src/front-components/components/SlackAccessModeSection';import { SlackUserLinkForm } from 'src/front-components/components/SlackUserLinkForm';import { SlackUserLinksList } from 'src/front-components/components/SlackUserLinksList';import { UnlinkedSlackUsersList } from 'src/front-components/components/UnlinkedSlackUsersList';@@ -204,12 +203,11 @@ const SlackUserLinksSettingsContent = () => {description="The last automatic email match failed before linking everyone. Press Auto-link by email below to run it again."/>)}- <SlackAccessModeSection canManage={canManage} />{canManage && (<Section><H2Titletitle="Unlinked Slack users"- description="These Slack users talk to the assistant with its default role. Pick a workspace member on a row to link them in place, or auto-link everyone whose Slack email matches a workspace member."+ description="Only Slack users linked to a workspace member can use the assistant. Pick a workspace member on a row to link them in place, or auto-link everyone whose Slack email matches a workspace member."/>{isUnlinkedSlackUsersLoading && unlinkedSlackUsers.length === 0 ? (<StyledCenteredState>diff --git a/packages/twenty-apps/public/slack/src/front-components/components/Toggle.tsx b/packages/twenty-apps/public/slack/src/front-components/components/Toggle.tsxdeleted file mode 100644index 9e9b16d0733..00000000000--- a/packages/twenty-apps/public/slack/src/front-components/components/Toggle.tsx+++ /dev/null@@ -1,89 +0,0 @@-import styled from '@emotion/styled';-import { themeCssVariables } from 'twenty-ui/theme-constants';--// twenty-ui's Toggle is a base-ui Switch whose click handler constructs a-// PointerEvent, which the front component sandbox does not provide. This is-// the same control as a plain button, styled after twenty-ui's Toggle. The-// host theme squircles every corner, so the capsule and thumb opt out.-const TOGGLE_WIDTH_PIXELS = 32;-const TOGGLE_HEIGHT_PIXELS = 20;-const THUMB_SIZE_PIXELS = 16;-const THUMB_INSET_PIXELS = 2;--const CHECKED_THUMB_OFFSET_PIXELS =- TOGGLE_WIDTH_PIXELS - THUMB_SIZE_PIXELS - THUMB_INSET_PIXELS;--const StyledToggle = styled.button`- align-items: center;- appearance: none;- background-color: ${() => themeCssVariables.background.transparent.medium};- border: none;- border-radius: ${() => themeCssVariables.border.radius.pill};- corner-shape: round;- cursor: pointer;- display: flex;- flex-shrink: 0;- height: ${TOGGLE_HEIGHT_PIXELS}px;- padding: 0;- position: relative;- transition: background-color- calc(${() => themeCssVariables.animation.duration.normal} * 1s) ease;- width: ${TOGGLE_WIDTH_PIXELS}px;-- &[data-checked='true'] {- background-color: ${() => themeCssVariables.color.blue};- }-- &:disabled {- cursor: default;- opacity: 0.5;- }-`;--const StyledThumb = styled.span`- background-color: ${() => themeCssVariables.background.primary};- border-radius: 50%;- corner-shape: round;- display: block;- height: ${THUMB_SIZE_PIXELS}px;- left: 0;- position: absolute;- top: 50%;- transform: translate(${THUMB_INSET_PIXELS}px, -50%);- transition: transform- calc(${() => themeCssVariables.animation.duration.normal} * 1s) ease;- width: ${THUMB_SIZE_PIXELS}px;-- &[data-checked='true'] {- transform: translate(${CHECKED_THUMB_OFFSET_PIXELS}px, -50%);- }-`;--type ToggleProps = {- id?: string;- checked: boolean;- disabled?: boolean;- ariaLabel: string;- onChange: (checked: boolean) => void;-};--export const Toggle = ({- id,- checked,- disabled = false,- ariaLabel,- onChange,-}: ToggleProps) => (- <StyledToggle- type="button"- role="switch"- id={id}- aria-checked={checked ? 'true' : 'false'}- aria-label={ariaLabel}- data-checked={checked ? 'true' : 'false'}- disabled={disabled}- onClick={() => onChange(!checked)}- >- <StyledThumb data-checked={checked ? 'true' : 'false'} />- </StyledToggle>-);diff --git a/packages/twenty-apps/public/slack/src/front-components/hooks/use-slack-access-mode.ts b/packages/twenty-apps/public/slack/src/front-components/hooks/use-slack-access-mode.tsdeleted file mode 100644index 1de7eed5868..00000000000--- a/packages/twenty-apps/public/slack/src/front-components/hooks/use-slack-access-mode.ts+++ /dev/null@@ -1,127 +0,0 @@-import { isBoolean, isString } from '@sniptt/guards';-import { useEffect, useState } from 'react';-import { RestApiClient } from 'twenty-client-sdk/rest';-import { isDefined } from 'twenty-sdk/utils';--import {- SLACK_ACCESS_MODE_GET_ROUTE_PATH,- SLACK_ACCESS_MODE_SET_ROUTE_PATH,-} from 'src/constants/slack-access-mode-route-path.constant';-import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';-import { type SlackAccessMode } from 'src/logic-functions/types/slack-access-mode.type';-import { asRecord } from 'src/logic-functions/utils/as-record.util';-import { isSlackAccessMode } from 'src/logic-functions/utils/is-slack-access-mode';--type SaveAccessModeResult = {- success: boolean;- message: string;- error?: string;-};--type SlackAccessModeState = {- accessMode: SlackAccessMode;- hasAccessModeError: boolean;- isAccessModeLoading: boolean;- isSavingAccessMode: boolean;- saveAccessMode: (- accessMode: SlackAccessMode,- ) => Promise<SaveAccessModeResult>;-};--const GENERIC_ERROR_RESULT: SaveAccessModeResult = {- success: false,- message: 'Could not save the access mode',- error: 'The request failed. Please try again.',-};--export const useSlackAccessMode = (): SlackAccessModeState => {- const [accessMode, setAccessMode] = useState<SlackAccessMode>(- SLACK_ACCESS_MODE.ANYONE,- );- const [hasAccessModeError, setHasAccessModeError] = useState(false);- const [isAccessModeLoading, setIsAccessModeLoading] = useState(true);- const [isSavingAccessMode, setIsSavingAccessMode] = useState(false);-- useEffect(() => {- let cancelled = false;-- const fetchAccessMode = async () => {- try {- const result = await new RestApiClient().get(- `/s${SLACK_ACCESS_MODE_GET_ROUTE_PATH}`,- );-- if (!cancelled) {- const record = asRecord(result);-- const readAccessMode = record?.accessMode;-- if (isSlackAccessMode(readAccessMode)) {- setAccessMode(readAccessMode);- }-- setHasAccessModeError(- record?.isAccessModeReadable === false ||- !isSlackAccessMode(readAccessMode),- );- }- } catch {- if (!cancelled) {- setHasAccessModeError(true);- }- } finally {- if (!cancelled) {- setIsAccessModeLoading(false);- }- }- };-- fetchAccessMode();-- return () => {- cancelled = true;- };- }, []);-- const saveAccessMode = async (- nextAccessMode: SlackAccessMode,- ): Promise<SaveAccessModeResult> => {- setIsSavingAccessMode(true);-- try {- const result = await new RestApiClient().post(- `/s${SLACK_ACCESS_MODE_SET_ROUTE_PATH}`,- { accessMode: nextAccessMode },- );-- const record = asRecord(result);-- if (!isDefined(record) || !isBoolean(record.success)) {- return GENERIC_ERROR_RESULT;- }-- if (record.success) {- setAccessMode(nextAccessMode);- setHasAccessModeError(false);- }-- return {- success: record.success,- message: isString(record.message) ? record.message : '',- error: isString(record.error) ? record.error : undefined,- };- } catch {- return GENERIC_ERROR_RESULT;- } finally {- setIsSavingAccessMode(false);- }- };-- return {- accessMode,- hasAccessModeError,- isAccessModeLoading,- isSavingAccessMode,- saveAccessMode,- };-};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-denied-text-by-reason.ts b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-denied-text-by-reason.tsnew file mode 100644index 00000000000..642a66ef4ce--- /dev/null+++ b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-denied-text-by-reason.ts@@ -0,0 +1,11 @@+import { SLACK_ACCESS_DENIED_TEXT } from 'src/logic-functions/constants/slack-access-denied-text';+import { SLACK_REQUEST_NOT_ATTRIBUTABLE_TEXT } from 'src/logic-functions/constants/slack-request-not-attributable-text';+import { type SlackAccessDenialReason } from 'src/logic-functions/types/slack-access-denial-reason.type';++export const SLACK_ACCESS_DENIED_TEXT_BY_REASON: Record<+ SlackAccessDenialReason,+ string+> = {+ NOT_A_MEMBER: SLACK_ACCESS_DENIED_TEXT,+ REQUEST_NOT_ATTRIBUTABLE: SLACK_REQUEST_NOT_ATTRIBUTABLE_TEXT,+};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-mode-kv-key.ts b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-mode-kv-key.tsdeleted file mode 100644index 42793dbd62b..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-mode-kv-key.ts+++ /dev/null@@ -1 +0,0 @@-export const SLACK_ACCESS_MODE_KV_KEY = 'slack-access-mode';diff --git a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-mode.ts b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-mode.tsdeleted file mode 100644index ae2b2760371..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-access-mode.ts+++ /dev/null@@ -1,4 +0,0 @@-export const SLACK_ACCESS_MODE = {- ANYONE: 'ANYONE',- ONLY_LINKED_MEMBERS: 'ONLY_LINKED_MEMBERS',-} as const;diff --git a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-request-not-attributable-text.ts b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-request-not-attributable-text.tsnew file mode 100644index 00000000000..114ea7c1c73--- /dev/null+++ b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-request-not-attributable-text.ts@@ -0,0 +1,2 @@+export const SLACK_REQUEST_NOT_ATTRIBUTABLE_TEXT =+ "I only act on a request addressed to me, and I couldn't tie this message to one. Mention me in a new message and I'll answer as you.";diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-access-mode-get-handler.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-access-mode-get-handler.test.tsdeleted file mode 100644index afa49096911..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-access-mode-get-handler.test.ts+++ /dev/null@@ -1,38 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { slackAccessModeGetHandler } from 'src/logic-functions/handlers/slack-access-mode-get-handler';--const { readSlackAccessModeMock } = vi.hoisted(() => ({- readSlackAccessModeMock: vi.fn(),-}));--vi.mock('src/logic-functions/utils/read-slack-access-mode', () => ({- readSlackAccessMode: readSlackAccessModeMock,-}));--describe('slackAccessModeGetHandler', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('should return the stored access mode as readable', async () => {- readSlackAccessModeMock.mockResolvedValue({- status: 'READ',- accessMode: 'ONLY_LINKED_MEMBERS',- });-- expect(await slackAccessModeGetHandler()).toEqual({- accessMode: 'ONLY_LINKED_MEMBERS',- isAccessModeReadable: true,- });- });-- it('should report an unreadable store rather than passing the fallback off as stored', async () => {- readSlackAccessModeMock.mockResolvedValue({ status: 'UNREADABLE' });-- expect(await slackAccessModeGetHandler()).toEqual({- accessMode: 'ONLY_LINKED_MEMBERS',- isAccessModeReadable: false,- });- });-});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-access-mode-set-handler.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-access-mode-set-handler.test.tsdeleted file mode 100644index 2809da8fa53..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-access-mode-set-handler.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { slackAccessModeSetHandler } from 'src/logic-functions/handlers/slack-access-mode-set-handler';--const { currentUserHasRolesPermissionMock, kvSetMock } = vi.hoisted(() => ({- currentUserHasRolesPermissionMock: vi.fn(),- kvSetMock: vi.fn(),-}));--vi.mock('src/logic-functions/utils/current-user-has-roles-permission', () => ({- currentUserHasRolesPermission: currentUserHasRolesPermissionMock,-}));--vi.mock('twenty-sdk/logic-function', () => ({- kv: { set: kvSetMock },-}));--const buildPayload = (body: unknown) => ({ body });--describe('slackAccessModeSetHandler', () => {- beforeEach(() => {- vi.clearAllMocks();- currentUserHasRolesPermissionMock.mockResolvedValue(true);- });-- it('should refuse when the user lacks the roles permission', async () => {- currentUserHasRolesPermissionMock.mockResolvedValue(false);-- const result = await slackAccessModeSetHandler(- buildPayload({ accessMode: 'ONLY_LINKED_MEMBERS' }),- );-- expect(result.success).toBe(false);- expect(kvSetMock).not.toHaveBeenCalled();- });-- it('should reject an invalid access mode', async () => {- const result = await slackAccessModeSetHandler(- buildPayload({ accessMode: 'NONSENSE' }),- );-- expect(result.success).toBe(false);- expect(kvSetMock).not.toHaveBeenCalled();- });-- it('should store a valid access mode in the workspace key value store', async () => {- const result = await slackAccessModeSetHandler(- buildPayload({ accessMode: 'ONLY_LINKED_MEMBERS' }),- );-- expect(result.success).toBe(true);- expect(kvSetMock).toHaveBeenCalledWith(- 'slack-access-mode',- 'ONLY_LINKED_MEMBERS',- { scope: 'WORKSPACE' },- );- });-- it('should fail with a structured result when the write errors', async () => {- kvSetMock.mockRejectedValueOnce(new Error('kv down'));-- const result = await slackAccessModeSetHandler(- buildPayload({ accessMode: 'ANYONE' }),- );-- expect(result.success).toBe(false);- expect(result.error).toBe('kv down');- });-});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-assistant-worker-handler.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-assistant-worker-handler.test.tsindex ee6070aa770..1dd9189b983 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-assistant-worker-handler.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-assistant-worker-handler.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { SLACK_ACCESS_DENIED_TEXT } from 'src/logic-functions/constants/slack-access-denied-text';-import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';+import { SLACK_REQUEST_NOT_ATTRIBUTABLE_TEXT } from 'src/logic-functions/constants/slack-request-not-attributable-text';import { SLACK_ASSISTANT_REQUEST_STATUS } from 'src/logic-functions/constants/slack-assistant-request-status';import { SLACK_ASSISTANT_REQUEST_TIMEOUT_SECONDS } from 'src/logic-functions/constants/slack-assistant-request-timeout-seconds';import { slackAssistantWorkerHandler } from 'src/logic-functions/handlers/slack-assistant-worker-handler';@@ -22,7 +22,6 @@ const {finishSlackAssistantRequestWithFailureMock,setSlackAssistantThreadTitleMock,subscribeSlackThreadMock,- getSlackAccessModeMock,resolveSlackAccessDecisionMock,} = vi.hoisted(() => ({callLog: [] as string[],@@ -39,7 +38,6 @@ const {finishSlackAssistantRequestWithFailureMock: vi.fn(),setSlackAssistantThreadTitleMock: vi.fn(),subscribeSlackThreadMock: vi.fn(),- getSlackAccessModeMock: vi.fn(),resolveSlackAccessDecisionMock: vi.fn(),}));@@ -47,10 +45,6 @@ vi.mock('src/logic-functions/utils/resolve-slack-access-decision', () => ({resolveSlackAccessDecision: resolveSlackAccessDecisionMock,}));-vi.mock('src/logic-functions/utils/get-slack-access-mode', () => ({- getSlackAccessMode: getSlackAccessModeMock,-}));-vi.mock('twenty-client-sdk/core', () => ({CoreApiClient: coreApiClientMock,}));@@ -151,9 +145,11 @@ describe('slackAssistantWorkerHandler', () => {claimSlackAssistantRequestMock.mockResolvedValue(true);updateSlackAssistantRequestMock.mockResolvedValue(undefined);fetchWorkspaceBaseUrlsMock.mockResolvedValue(['https://acme.twenty.com']);- resolveSlackRunAsForRequestMock.mockResolvedValue(undefined);- getSlackAccessModeMock.mockResolvedValue(SLACK_ACCESS_MODE.ANYONE);- resolveSlackAccessDecisionMock.mockResolvedValue({ status: 'ALLOWED' });+ resolveSlackRunAsForRequestMock.mockResolvedValue('workspace-member-1');+ resolveSlackAccessDecisionMock.mockResolvedValue({+ status: 'ALLOWED',+ runAsWorkspaceMemberId: 'workspace-member-1',+ });setSlackAssistantThreadTitleMock.mockResolvedValue(undefined);subscribeSlackThreadMock.mockResolvedValue(undefined);@@ -189,8 +185,12 @@ describe('slackAssistantWorkerHandler', () => {);});- it('should decline an unlinked Slack user when access is restricted to linked members', async () => {- resolveSlackAccessDecisionMock.mockResolvedValue({ status: 'DENIED' });+ it('should decline an unlinked Slack user', async () => {+ resolveSlackRunAsForRequestMock.mockResolvedValue(undefined);+ resolveSlackAccessDecisionMock.mockResolvedValue({+ status: 'DENIED',+ reason: 'NOT_A_MEMBER',+ });await expect(slackAssistantWorkerHandler(REQUEST_RECORD)).resolves.toEqual({done: true,@@ -212,8 +212,39 @@ describe('slackAssistantWorkerHandler', () => {);});+ it('should ask a linked member to mention the assistant when the request could not be attributed to them', async () => {+ resolveSlackRunAsForRequestMock.mockResolvedValue(undefined);+ resolveSlackAccessDecisionMock.mockResolvedValue({+ status: 'DENIED',+ reason: 'REQUEST_NOT_ATTRIBUTABLE',+ });++ await expect(slackAssistantWorkerHandler(REQUEST_RECORD)).resolves.toEqual({+ done: true,+ declined: true,+ });++ expect(runSlackAssistantAgentWithDeadlineMock).not.toHaveBeenCalled();+ expect(sendSlackMessageMock).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ messageText: SLACK_REQUEST_NOT_ATTRIBUTABLE_TEXT,+ }),+ );+ expect(updateSlackAssistantRequestMock).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ id: REQUEST_RECORD.id,+ status: SLACK_ASSISTANT_REQUEST_STATUS.DONE,+ responseText: SLACK_REQUEST_NOT_ATTRIBUTABLE_TEXT,+ }),+ );+ });+it('should fail the request when the denial message cannot be delivered', async () => {- resolveSlackAccessDecisionMock.mockResolvedValue({ status: 'DENIED' });+ resolveSlackAccessDecisionMock.mockResolvedValue({+ status: 'DENIED',+ reason: 'NOT_A_MEMBER',+ });sendSlackMessageMock.mockImplementation(async () => {callLog.push('reply:denied');@@ -250,10 +281,7 @@ describe('slackAssistantWorkerHandler', () => {);});- it('should ask for the access decision with the stored mode and the resolved requester', async () => {- getSlackAccessModeMock.mockResolvedValue(- SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS,- );+ it('should ask for the access decision with the resolved requester', async () => {resolveSlackRunAsForRequestMock.mockResolvedValue('workspace-member-1');fetchSlackAssistantContextMock.mockImplementation(async () => {callLog.push('context:fetch');@@ -269,24 +297,24 @@ describe('slackAssistantWorkerHandler', () => {expect(resolveSlackAccessDecisionMock).toHaveBeenCalledWith(expect.objectContaining({- accessMode: SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS,identity: REQUESTER_IDENTITY,runAsWorkspaceMemberId: 'workspace-member-1',}),);});- it('should answer a request access allowed', async () => {- getSlackAccessModeMock.mockResolvedValue(- SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS,- );- resolveSlackRunAsForRequestMock.mockResolvedValue(undefined);+ it('should answer a request from a linked member as that member', async () => {+ resolveSlackRunAsForRequestMock.mockResolvedValue('workspace-member-1');await expect(slackAssistantWorkerHandler(REQUEST_RECORD)).resolves.toEqual({done: true,});- expect(runSlackAssistantAgentWithDeadlineMock).toHaveBeenCalledTimes(1);+ expect(+ runSlackAssistantAgentWithDeadlineMock,+ ).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ runAsWorkspaceMemberId: 'workspace-member-1' }),+ );});it('should show the thinking status before fetching the Slack context', async () => {diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-access-mode-get-handler.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-access-mode-get-handler.tsdeleted file mode 100644index 71b472aa61a..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-access-mode-get-handler.ts+++ /dev/null@@ -1,17 +0,0 @@-import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';-import { type SlackAccessMode } from 'src/logic-functions/types/slack-access-mode.type';-import { readSlackAccessMode } from 'src/logic-functions/utils/read-slack-access-mode';--export const slackAccessModeGetHandler = async (): Promise<{- accessMode: SlackAccessMode;- isAccessModeReadable: boolean;-}> => {- const result = await readSlackAccessMode();-- return result.status === 'READ'- ? { accessMode: result.accessMode, isAccessModeReadable: true }- : {- accessMode: SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS,- isAccessModeReadable: false,- };-};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-access-mode-set-handler.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-access-mode-set-handler.tsdeleted file mode 100644index e4ecf231c81..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-access-mode-set-handler.ts+++ /dev/null@@ -1,54 +0,0 @@-import { kv } from 'twenty-sdk/logic-function';--import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';-import { SLACK_ACCESS_MODE_KV_KEY } from 'src/logic-functions/constants/slack-access-mode-kv-key';-import { type SlackRouteBody } from 'src/logic-functions/types/slack-route-body.type';-import { type SlackToolResult } from 'src/logic-functions/types/slack-tool-result.type';-import { asRecord } from 'src/logic-functions/utils/as-record.util';-import { currentUserHasRolesPermission } from 'src/logic-functions/utils/current-user-has-roles-permission';-import { isSlackAccessMode } from 'src/logic-functions/utils/is-slack-access-mode';--export const slackAccessModeSetHandler = async (- payload: SlackRouteBody,-): Promise<SlackToolResult> => {- const isAllowed = await currentUserHasRolesPermission();-- if (!isAllowed) {- return {- success: false,- message: 'Not allowed',- error:- 'Only members with the roles permission can change the access mode.',- };- }-- const body = asRecord(payload.body) ?? {};-- if (!isSlackAccessMode(body.accessMode)) {- return {- success: false,- message: 'Invalid access mode',- error: 'accessMode must be ANYONE or ONLY_LINKED_MEMBERS.',- };- }-- const accessMode = body.accessMode;-- try {- await kv.set(SLACK_ACCESS_MODE_KV_KEY, accessMode, { scope: 'WORKSPACE' });- } catch (error) {- return {- success: false,- message: 'Could not save the access mode',- error: error instanceof Error ? error.message : String(error),- };- }-- return {- success: true,- message:- accessMode === SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS- ? 'The assistant is now restricted to linked members.'- : 'The assistant is now open to anyone.',- };-};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-assistant-worker-handler.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-assistant-worker-handler.tsindex d6546c55682..c9eac9f6db3 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-assistant-worker-handler.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-assistant-worker-handler.ts@@ -3,7 +3,7 @@ import { CoreApiClient } from 'twenty-client-sdk/core';import { isDefined } from 'twenty-sdk/utils';import { SLACK_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { SLACK_ACCESS_DENIED_TEXT } from 'src/logic-functions/constants/slack-access-denied-text';+import { SLACK_ACCESS_DENIED_TEXT_BY_REASON } from 'src/logic-functions/constants/slack-access-denied-text-by-reason';import { SLACK_ACCESS_UNVERIFIABLE_ERROR } from 'src/logic-functions/constants/slack-access-unverifiable-error';import { SLACK_ASSISTANT_AGENT_BUDGET_SECONDS } from 'src/logic-functions/constants/slack-assistant-agent-budget-seconds';import { SLACK_ASSISTANT_EMPTY_RESPONSE_ERROR } from 'src/logic-functions/constants/slack-assistant-empty-response-error';@@ -22,7 +22,6 @@ import { fetchSlackAssistantContext } from 'src/logic-functions/utils/fetch-slacimport { fetchWorkspaceBaseUrls } from 'src/logic-functions/utils/fetch-workspace-base-urls';import { isSlackAssistantRequestResumable } from 'src/logic-functions/utils/is-slack-assistant-request-resumable';import { finishSlackAssistantRequestWithFailure } from 'src/logic-functions/utils/finish-slack-assistant-request-with-failure';-import { getSlackAccessMode } from 'src/logic-functions/utils/get-slack-access-mode';import { getSlackAssistantParentMessageTimestamp } from 'src/logic-functions/utils/get-slack-assistant-parent-message-timestamp';import { resolveSlackAccessDecision } from 'src/logic-functions/utils/resolve-slack-access-decision';import { resolveSlackAssistantAttachments } from 'src/logic-functions/utils/resolve-slack-assistant-attachments';@@ -130,7 +129,6 @@ export const slackAssistantWorkerHandler = async (}const accessDecision = await resolveSlackAccessDecision({- accessMode: await getSlackAccessMode(),client,slackClient,slackConnectionId,@@ -150,9 +148,12 @@ export const slackAssistantWorkerHandler = async (if (accessDecision.status === 'DENIED') {await stopStatusUpdates();+ const denialText =+ SLACK_ACCESS_DENIED_TEXT_BY_REASON[accessDecision.reason];+const denialDelivery = await sendSlackMessage({slackChannelId,- messageText: SLACK_ACCESS_DENIED_TEXT,+ messageText: denialText,parentMessageTimestamp,messageFormat: 'markdown',unfurlLinks: false,@@ -169,7 +170,7 @@ export const slackAssistantWorkerHandler = async (await updateSlackAssistantRequest(client, {id: record.id,status: SLACK_ASSISTANT_REQUEST_STATUS.DONE,- responseText: SLACK_ACCESS_DENIED_TEXT,+ responseText: denialText,});return { done: true, declined: true };@@ -199,12 +200,12 @@ export const slackAssistantWorkerHandler = async (const agentResult = await runSlackAssistantAgentWithDeadline({agentUniversalIdentifier: SLACK_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER,- runAsWorkspaceMemberId,+ runAsWorkspaceMemberId: accessDecision.runAsWorkspaceMemberId,messages: buildSlackAssistantMessages({requestText: resolvedMentions.requestText,requesterName,conversationMessages: resolvedMentions.conversationMessages,- runAsWorkspaceMemberId,+ runAsWorkspaceMemberId: accessDecision.runAsWorkspaceMemberId,timeoutSeconds: agentBudgetRemainingSeconds,workspaceBaseUrl: workspaceBaseUrls[0],hasMentionedUsers: resolvedMentions.hasMentionedUsers,diff --git a/packages/twenty-apps/public/slack/src/logic-functions/slack-access-mode-get.ts b/packages/twenty-apps/public/slack/src/logic-functions/slack-access-mode-get.tsdeleted file mode 100644index ab94cc460eb..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/slack-access-mode-get.ts+++ /dev/null@@ -1,19 +0,0 @@-import { defineLogicFunction } from 'twenty-sdk/define';--import { SLACK_ACCESS_MODE_GET_ROUTE_PATH } from 'src/constants/slack-access-mode-route-path.constant';-import { SLACK_ACCESS_MODE_GET_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { slackAccessModeGetHandler } from 'src/logic-functions/handlers/slack-access-mode-get-handler';--export default defineLogicFunction({- universalIdentifier: SLACK_ACCESS_MODE_GET_UNIVERSAL_IDENTIFIER,- name: 'slack-access-mode-get',- description:- 'Return whether the Slack assistant is open to anyone or restricted to workspace members with a Slack user link.',- timeoutSeconds: 15,- httpRouteTriggerSettings: {- path: SLACK_ACCESS_MODE_GET_ROUTE_PATH,- httpMethod: 'GET',- isAuthRequired: true,- },- handler: slackAccessModeGetHandler,-});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/slack-access-mode-set.ts b/packages/twenty-apps/public/slack/src/logic-functions/slack-access-mode-set.tsdeleted file mode 100644index 42af137ff78..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/slack-access-mode-set.ts+++ /dev/null@@ -1,19 +0,0 @@-import { defineLogicFunction } from 'twenty-sdk/define';--import { SLACK_ACCESS_MODE_SET_ROUTE_PATH } from 'src/constants/slack-access-mode-route-path.constant';-import { SLACK_ACCESS_MODE_SET_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { slackAccessModeSetHandler } from 'src/logic-functions/handlers/slack-access-mode-set-handler';--export default defineLogicFunction({- universalIdentifier: SLACK_ACCESS_MODE_SET_UNIVERSAL_IDENTIFIER,- name: 'slack-access-mode-set',- description:- 'Set whether the Slack assistant is open to anyone or restricted to workspace members with a Slack user link. Restricted to members with the workspace members permission.',- timeoutSeconds: 15,- httpRouteTriggerSettings: {- path: SLACK_ACCESS_MODE_SET_ROUTE_PATH,- httpMethod: 'POST',- isAuthRequired: true,- },- handler: slackAccessModeSetHandler,-});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-decision.type.ts b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-decision.type.tsindex abce32c5be2..9d7b550fe5b 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-decision.type.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-decision.type.ts@@ -1,4 +1,6 @@+import { type SlackAccessDenialReason } from 'src/logic-functions/types/slack-access-denial-reason.type';+export type SlackAccessDecision =- | { status: 'ALLOWED' }- | { status: 'DENIED' }+ | { status: 'ALLOWED'; runAsWorkspaceMemberId: string }+ | { status: 'DENIED'; reason: SlackAccessDenialReason }| { status: 'UNVERIFIABLE' };diff --git a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-denial-reason.type.ts b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-denial-reason.type.tsnew file mode 100644index 00000000000..593d98d415b--- /dev/null+++ b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-denial-reason.type.ts@@ -0,0 +1,3 @@+export type SlackAccessDenialReason =+ | 'NOT_A_MEMBER'+ | 'REQUEST_NOT_ATTRIBUTABLE';diff --git a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-mode-read.type.ts b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-mode-read.type.tsdeleted file mode 100644index 3ac62624d3c..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-mode-read.type.ts+++ /dev/null@@ -1,5 +0,0 @@-import { type SlackAccessMode } from 'src/logic-functions/types/slack-access-mode.type';--export type SlackAccessModeRead =- | { status: 'READ'; accessMode: SlackAccessMode }- | { status: 'UNREADABLE' };diff --git a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-mode.type.ts b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-mode.type.tsdeleted file mode 100644index 95af0133ce5..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-access-mode.type.ts+++ /dev/null@@ -1,4 +0,0 @@-import { type SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';--export type SlackAccessMode =- (typeof SLACK_ACCESS_MODE)[keyof typeof SLACK_ACCESS_MODE];diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/build-slack-assistant-messages.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/build-slack-assistant-messages.test.tsindex 013ce069e6a..58421bfe585 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/build-slack-assistant-messages.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/build-slack-assistant-messages.test.ts@@ -8,7 +8,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'How many open opportunities does ACME have?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [],@@ -30,7 +30,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'How many open opportunities does ACME have?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [],@@ -47,7 +47,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'What is wrong in this screenshot?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [{ fileId: 'file-id-1', filename: 'screenshot.png' }],@@ -71,7 +71,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'What is in these?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [{ fileId: 'file-id-1', filename: 'screenshot.png' }],@@ -94,7 +94,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'and this one?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [{ fileId: 'file-id-1', filename: 'screenshot.png' }],@@ -116,7 +116,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'what is this?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [{ fileId: 'file-id-1', filename: 'diagram.png' }],@@ -139,7 +139,7 @@ describe('buildSlackAssistantMessages', () => {{ role: 'user', content: '<@U123>: Find the ACME account' },{ role: 'assistant', content: 'ACME is a company record.' },],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [],@@ -171,7 +171,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'How many open opportunities does ACME have?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [],@@ -189,7 +189,7 @@ describe('buildSlackAssistantMessages', () => {'Create a task for @Alice Martin (workspace member member-1)',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [],@@ -264,30 +264,12 @@ describe('buildSlackAssistantMessages', () => {expect(messages[0].content).toContain('never invite the requester');});- it('should say it answers with the app role when nobody is linked', () => {- const messages = buildSlackAssistantMessages({- requestText: 'Which companies were added recently?',- requesterName: 'Jane',- conversationMessages: [],- runAsWorkspaceMemberId: undefined,- timeoutSeconds: 300,- workspaceBaseUrl: 'https://acme.twenty.com',- attachments: [],- attachedFileNames: [],- namesOnlyFileNames: [],- hasMentionedUsers: false,- });-- expect(messages[0].content).toContain("app's own role");- expect(messages[0].content).not.toContain('acting as Jane');- });-it('should tell the agent that shared files are names only', () => {const messages = buildSlackAssistantMessages({requestText: 'log this against ACME',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',namesOnlyFileNames: ['proposal.pdf'],@@ -329,7 +311,7 @@ describe('buildSlackAssistantMessages', () => {requestText: 'who owns ACME?',requesterName: 'Jane',conversationMessages: [],- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',timeoutSeconds: 300,workspaceBaseUrl: 'https://acme.twenty.com',attachments: [],diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/read-slack-access-mode.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/read-slack-access-mode.test.tsdeleted file mode 100644index cedafd3bed0..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/read-slack-access-mode.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { getSlackAccessMode } from 'src/logic-functions/utils/get-slack-access-mode';-import { readSlackAccessMode } from 'src/logic-functions/utils/read-slack-access-mode';--const { kvGetMock } = vi.hoisted(() => ({- kvGetMock: vi.fn(),-}));--vi.mock('twenty-sdk/logic-function', () => ({- kv: { get: kvGetMock },-}));--describe('readSlackAccessMode', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('should read as ANYONE when nothing is stored', async () => {- kvGetMock.mockResolvedValue(null);-- expect(await readSlackAccessMode()).toEqual({- status: 'READ',- accessMode: 'ANYONE',- });- });-- it('should report the read outcome alongside a stored value', async () => {- kvGetMock.mockResolvedValue('ONLY_LINKED_MEMBERS');-- expect(await readSlackAccessMode()).toEqual({- status: 'READ',- accessMode: 'ONLY_LINKED_MEMBERS',- });- });-- it('should report an unreadable store distinctly from a stored value', async () => {- kvGetMock.mockRejectedValue(new Error('kv unavailable'));-- expect(await readSlackAccessMode()).toEqual({ status: 'UNREADABLE' });- });-- it('should report a stored value it cannot interpret as unreadable', async () => {- kvGetMock.mockResolvedValue('SOMETHING_ELSE');-- expect(await readSlackAccessMode()).toEqual({ status: 'UNREADABLE' });- });-});--describe('getSlackAccessMode', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('should default to ANYONE when nothing is stored', async () => {- kvGetMock.mockResolvedValue(null);-- expect(await getSlackAccessMode()).toBe('ANYONE');- });-- it('should return ONLY_LINKED_MEMBERS when stored', async () => {- kvGetMock.mockResolvedValue('ONLY_LINKED_MEMBERS');-- expect(await getSlackAccessMode()).toBe('ONLY_LINKED_MEMBERS');- });-- it('should keep the restriction on when the read throws', async () => {- kvGetMock.mockRejectedValue(new Error('kv unavailable'));-- expect(await getSlackAccessMode()).toBe('ONLY_LINKED_MEMBERS');- });-- it('should keep the restriction on for a stored value it cannot interpret', async () => {- kvGetMock.mockResolvedValue('SOMETHING_ELSE');-- expect(await getSlackAccessMode()).toBe('ONLY_LINKED_MEMBERS');- });-});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-access-decision.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-access-decision.test.tsindex a3b2b74a523..fea7da84ed1 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-access-decision.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-access-decision.test.ts@@ -45,37 +45,21 @@ describe('resolveSlackAccessDecision', () => {vi.clearAllMocks();});- it('should allow everyone when the workspace is open', async () => {- expect(- await resolveSlackAccessDecision({- accessMode: 'ANYONE',- client,- slackClient,- slackConnectionId: SLACK_CONNECTION_ID,- identity: undefined,- runAsWorkspaceMemberId: undefined,- }),- ).toEqual({ status: 'ALLOWED' });-- expect(resolveSlackIdentitiesMock).not.toHaveBeenCalled();- });-it('should allow a request already running as a workspace member without resolving again', async () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,identity,runAsWorkspaceMemberId: 'member-id',}),- ).toEqual({ status: 'ALLOWED' });+ ).toEqual({ status: 'ALLOWED', runAsWorkspaceMemberId: 'member-id' });expect(resolveSlackIdentitiesMock).not.toHaveBeenCalled();});- it('should allow a linked member whose request is not eligible for impersonation', async () => {+ it('should decline a confirmed member whose request could not be attributed to them', async () => {mockResolution({...RESOLUTION_BASE,outcome: 'confirmedMember',@@ -85,14 +69,13 @@ describe('resolveSlackAccessDecision', () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,identity,runAsWorkspaceMemberId: undefined,}),- ).toEqual({ status: 'ALLOWED' });+ ).toEqual({ status: 'DENIED', reason: 'REQUEST_NOT_ATTRIBUTABLE' });});it('should deny an account every lookup agreed is not a member', async () => {@@ -100,14 +83,13 @@ describe('resolveSlackAccessDecision', () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,identity,runAsWorkspaceMemberId: undefined,}),- ).toEqual({ status: 'DENIED' });+ ).toEqual({ status: 'DENIED', reason: 'NOT_A_MEMBER' });});it('should not deny when membership could not be established', async () => {@@ -115,7 +97,6 @@ describe('resolveSlackAccessDecision', () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,@@ -134,7 +115,6 @@ describe('resolveSlackAccessDecision', () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,@@ -151,7 +131,6 @@ describe('resolveSlackAccessDecision', () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,@@ -166,7 +145,6 @@ describe('resolveSlackAccessDecision', () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,@@ -179,7 +157,6 @@ describe('resolveSlackAccessDecision', () => {it('should not deny without a Slack client or an identity to look up', async () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient: undefined,slackConnectionId: SLACK_CONNECTION_ID,@@ -190,7 +167,6 @@ describe('resolveSlackAccessDecision', () => {expect(await resolveSlackAccessDecision({- accessMode: 'ONLY_LINKED_MEMBERS',client,slackClient,slackConnectionId: SLACK_CONNECTION_ID,diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-run-as-for-request.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-run-as-for-request.test.tsindex 58928f6891d..77642e04af4 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-run-as-for-request.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-run-as-for-request.test.ts@@ -148,7 +148,7 @@ describe('resolveSlackRunAsForRequest', () => {expect(await resolve()).toBeUndefined();});- it('should fall back to the agent role when the Slack user is unknown', async () => {+ it('should refuse when the Slack user is unknown', async () => {expect(await resolve({ identity: undefined })).toBeUndefined();expect(findSlackAssistantRequestCreatedByMock).not.toHaveBeenCalled();});diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/run-slack-assistant-agent-with-deadline.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/run-slack-assistant-agent-with-deadline.test.tsindex d7872ecba16..49e67053138 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/run-slack-assistant-agent-with-deadline.test.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/run-slack-assistant-agent-with-deadline.test.ts@@ -11,7 +11,7 @@ vi.mock('twenty-sdk/logic-function', () => ({const BASE_INPUT = {agentUniversalIdentifier: 'agent-uid',- runAsWorkspaceMemberId: undefined,+ runAsWorkspaceMemberId: 'member-1',messages: [{ role: 'user' as const, content: 'hi' }],};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/build-slack-assistant-messages.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/build-slack-assistant-messages.tsindex 89a6da552aa..db7f880a5fe 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/build-slack-assistant-messages.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/build-slack-assistant-messages.ts@@ -22,20 +22,12 @@ const buildRecordReferenceSection = (const buildPermissionSection = ({runAsWorkspaceMemberId,}: {- runAsWorkspaceMemberId: string | undefined;-}): string => {- const missingToolMeaning =- 'Your tools are limited to what is permitted. A tool you need being absent means the action is not allowed, not that the object is missing, that the workspace is misconfigured or that the Slack connection is wrong. Say plainly what cannot be done and who to ask; never invite the requester to name the object, paste a record link or otherwise work around it.';-- if (!isNonEmptyString(runAsWorkspaceMemberId)) {- return `You are answering with the app's own role, not the requester's. ${missingToolMeaning}`;- }-- return [+ runAsWorkspaceMemberId: string;+}): string =>+ [`You are acting as workspace member ${runAsWorkspaceMemberId}, with that member's own permissions. When the request says me, my or mine, it means that member, and you can use their id directly.`,- missingToolMeaning,+ 'Your tools are limited to what is permitted. A tool you need being absent means the action is not allowed, not that the object is missing, that the workspace is misconfigured or that the Slack connection is wrong. Say plainly what cannot be done and who to ask; never invite the requester to name the object, paste a record link or otherwise work around it.',].join('\n\n');-};const buildSharedFilesSection = ({attachedFileNames,@@ -93,7 +85,7 @@ export const buildSlackAssistantMessages = ({requestText: string;requesterName: string | undefined;conversationMessages: SlackAssistantAgentMessage[];- runAsWorkspaceMemberId: string | undefined;+ runAsWorkspaceMemberId: string;timeoutSeconds: number;workspaceBaseUrl: string | undefined;attachments: SlackAssistantAttachment[];diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-access-mode.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-access-mode.tsdeleted file mode 100644index 6d95405e4d2..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/get-slack-access-mode.ts+++ /dev/null@@ -1,13 +0,0 @@-import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';-import { type SlackAccessMode } from 'src/logic-functions/types/slack-access-mode.type';-import { readSlackAccessMode } from 'src/logic-functions/utils/read-slack-access-mode';--export const getSlackAccessMode = async (): Promise<SlackAccessMode> => {- const result = await readSlackAccessMode();-- // An unreadable store is not an open workspace: only a store that answers- // can say the restriction is off, so a failed read keeps it on.- return result.status === 'READ'- ? result.accessMode- : SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS;-};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/is-slack-access-mode.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/is-slack-access-mode.tsdeleted file mode 100644index b5ffa8a0722..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/is-slack-access-mode.ts+++ /dev/null@@ -1,6 +0,0 @@-import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';-import { type SlackAccessMode } from 'src/logic-functions/types/slack-access-mode.type';--export const isSlackAccessMode = (value: unknown): value is SlackAccessMode =>- value === SLACK_ACCESS_MODE.ANYONE ||- value === SLACK_ACCESS_MODE.ONLY_LINKED_MEMBERS;diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/read-slack-access-mode.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/read-slack-access-mode.tsdeleted file mode 100644index 1ac99062f68..00000000000--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/read-slack-access-mode.ts+++ /dev/null@@ -1,29 +0,0 @@-import { isNonEmptyString } from '@sniptt/guards';-import { kv } from 'twenty-sdk/logic-function';--import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';-import { SLACK_ACCESS_MODE_KV_KEY } from 'src/logic-functions/constants/slack-access-mode-kv-key';-import { type SlackAccessModeRead } from 'src/logic-functions/types/slack-access-mode-read.type';-import { isSlackAccessMode } from 'src/logic-functions/utils/is-slack-access-mode';--export const readSlackAccessMode = async (): Promise<SlackAccessModeRead> => {- try {- const stored = await kv.get<string>(SLACK_ACCESS_MODE_KV_KEY, {- scope: 'WORKSPACE',- });-- if (!isNonEmptyString(stored)) {- return { status: 'READ', accessMode: SLACK_ACCESS_MODE.ANYONE };- }-- // A stored value this version cannot interpret is not a deliberate choice- // to open the workspace, so it reads as unreadable rather than as ANYONE.- if (!isSlackAccessMode(stored)) {- return { status: 'UNREADABLE' };- }-- return { status: 'READ', accessMode: stored };- } catch {- return { status: 'UNREADABLE' };- }-};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-access-decision.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-access-decision.tsindex 109db1dfb9e..7c101e5bf17 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-access-decision.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-access-decision.ts@@ -3,33 +3,25 @@ import { isNonEmptyString } from '@sniptt/guards';import { type CoreApiClient } from 'twenty-client-sdk/core';import { isDefined } from 'twenty-sdk/utils';-import { SLACK_ACCESS_MODE } from 'src/logic-functions/constants/slack-access-mode';import { type SlackAccessDecision } from 'src/logic-functions/types/slack-access-decision.type';-import { type SlackAccessMode } from 'src/logic-functions/types/slack-access-mode.type';import { type SlackUserIdentity } from 'src/logic-functions/types/slack-user-identity.type';import { resolveSlackIdentities } from 'src/logic-functions/utils/resolve-slack-identities';export const resolveSlackAccessDecision = async ({- accessMode,client,slackClient,slackConnectionId,identity,runAsWorkspaceMemberId,}: {- accessMode: SlackAccessMode;client: CoreApiClient;slackClient: WebClient | undefined;slackConnectionId: string | undefined;identity: SlackUserIdentity | undefined;runAsWorkspaceMemberId: string | undefined;}): Promise<SlackAccessDecision> => {- if (accessMode === SLACK_ACCESS_MODE.ANYONE) {- return { status: 'ALLOWED' };- }-if (isNonEmptyString(runAsWorkspaceMemberId)) {- return { status: 'ALLOWED' };+ return { status: 'ALLOWED', runAsWorkspaceMemberId };}if (!isDefined(slackClient) || !isDefined(identity)) {@@ -53,12 +45,12 @@ export const resolveSlackAccessDecision = async ({}switch (resolution.outcome) {- case 'confirmedMember':- return { status: 'ALLOWED' };- case 'membershipNotConfirmed':- return { status: 'DENIED' };case 'membershipUnverifiable':case 'unidentified':return { status: 'UNVERIFIABLE' };+ case 'confirmedMember':+ return { status: 'DENIED', reason: 'REQUEST_NOT_ATTRIBUTABLE' };+ case 'membershipNotConfirmed':+ return { status: 'DENIED', reason: 'NOT_A_MEMBER' };}};diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/run-slack-assistant-agent-with-deadline.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/run-slack-assistant-agent-with-deadline.tsindex d61560515c5..3744b755a65 100644--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/run-slack-assistant-agent-with-deadline.ts+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/run-slack-assistant-agent-with-deadline.ts@@ -10,8 +10,9 @@ import { raceSlackAssistantAgentDeadline } from 'src/logic-functions/utils/race-type RunSlackAssistantAgentInput = Pick<RunAgentInput,- 'agentUniversalIdentifier' | 'runAsWorkspaceMemberId'+ 'agentUniversalIdentifier'> & {+ runAsWorkspaceMemberId: string;messages: SlackAssistantAgentMessage[];deadlineAtMs: number;};diff --git a/packages/twenty-apps/public/slack/src/roles/default-function.role.ts b/packages/twenty-apps/public/slack/src/roles/default-function.role.tsindex 71c96e41429..6c0b712c4a1 100644--- a/packages/twenty-apps/public/slack/src/roles/default-function.role.ts+++ b/packages/twenty-apps/public/slack/src/roles/default-function.role.ts@@ -14,13 +14,13 @@ export default defineApplicationRole({universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,label: 'Twenty Slack tools role',description:- 'Everything the Slack app can do in the CRM. Tools only forward requests to Slack using the configured connected account. Tracks assistant requests, links Slack accounts to workspace members (which needs read access on workspace members for the email match), reads CRM records to render record link previews in Slack, and runs the assistant agent, which creates, updates and soft-deletes people, companies, opportunities, notes and tasks through the narrower Slack Assistant role.',+ "Everything the Slack app can do in the CRM. Tools only forward requests to Slack using the configured connected account. Tracks assistant requests, links Slack accounts to workspace members (which needs read access on workspace members for the email match), reads CRM records to render record link previews in Slack, and hosts the assistant agent, which always runs as the linked workspace member who asked and acts with that member's own permissions.",canReadAllObjectRecords: false,canUpdateAllObjectRecords: false,canSoftDeleteAllObjectRecords: false,canDestroyAllObjectRecords: false,canUpdateAllSettings: false,- canBeAssignedToAgents: false,+ canBeAssignedToAgents: true,canBeAssignedToUsers: false,canBeAssignedToApiKeys: false,objectPermissions: [diff --git a/packages/twenty-apps/public/slack/src/roles/slack-assistant.role.ts b/packages/twenty-apps/public/slack/src/roles/slack-assistant.role.tsdeleted file mode 100644index a9ab32f0e30..00000000000--- a/packages/twenty-apps/public/slack/src/roles/slack-assistant.role.ts+++ /dev/null@@ -1,55 +0,0 @@-import {- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,- SystemPermissionFlag,- defineRole,-} from 'twenty-sdk/define';--import { SLACK_ASSISTANT_ROLE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';--const WORKSPACE_MEMBER_UNIVERSAL_IDENTIFIER =- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.workspaceMember.universalIdentifier;--const WRITABLE_CRM_OBJECT_UNIVERSAL_IDENTIFIERS = [- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.note.universalIdentifier,- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.noteTarget.universalIdentifier,- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.task.universalIdentifier,- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.taskTarget.universalIdentifier,-] as const;--export default defineRole({- universalIdentifier: SLACK_ASSISTANT_ROLE_UNIVERSAL_IDENTIFIER,- label: 'Slack Assistant',- description:- 'CRM access for the Slack conversational assistant. Lets the slack-assistant agent read, create, update, and soft-delete people, companies, opportunities, notes, and tasks. Workspace members stay read-only. Bound to the agent via roleUniversalIdentifier on install; tighten this role if you need a narrower bot.',- canReadAllObjectRecords: false,- canUpdateAllObjectRecords: false,- canSoftDeleteAllObjectRecords: false,- canDestroyAllObjectRecords: false,- canUpdateAllSettings: false,- canBeAssignedToAgents: true,- canBeAssignedToUsers: false,- canBeAssignedToApiKeys: false,- objectPermissions: [- ...WRITABLE_CRM_OBJECT_UNIVERSAL_IDENTIFIERS.map(- (objectUniversalIdentifier) => ({- objectUniversalIdentifier,- canReadObjectRecords: true,- canUpdateObjectRecords: true,- canSoftDeleteObjectRecords: true,- canDestroyObjectRecords: false,- }),- ),- {- objectUniversalIdentifier: WORKSPACE_MEMBER_UNIVERSAL_IDENTIFIER,- canReadObjectRecords: true,- canUpdateObjectRecords: false,- canSoftDeleteObjectRecords: false,- canDestroyObjectRecords: false,- },- ],- fieldPermissions: [],- permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],-});