Skip to content

The open alternative to Salesforce, designed for AI.

feat(slack): surface broken connections and failed auto-link sweeps in the settings tab (#25240)

Abdul Rahman08de7f418a20
diff --git a/packages/twenty-apps/public/slack/README.md b/packages/twenty-apps/public/slack/README.md
index c1f5ce90cbc..a592fa6279b 100644
--- a/packages/twenty-apps/public/slack/README.md
+++ b/packages/twenty-apps/public/slack/README.md
@@ -44,5 +44,5 @@ Answering costs AI credits on top, billed on the model's token usage β€” the who
## πŸ“Œ Heads up
- **You create the Slack app** β€” Twenty connects to a Slack app you own, so an admin has to create it and set its credentials before anyone can connect. The assistant needs a signing secret and event subscriptions on top. See [SETUP.md](https://github.com/twentyhq/twenty/blob/main/packages/twenty-apps/public/slack/SETUP.md).
-- **One Slack workspace per Twenty workspace** β€” connecting claims that Slack team. Removing the last connection using it releases the claim, so another Twenty workspace can then connect the same team.
+- **One Slack workspace per Twenty workspace** β€” connecting claims that Slack team. Removing the last connection using it releases the claim, so another Twenty workspace can then connect the same team. If a connection is broken β€” its Slack team is claimed elsewhere, or Slack no longer accepts its token β€” the Slack settings tab shows what is wrong and how to fix it.
- **Private channels need membership** β€” public channels are covered by `chat:write.public`; anywhere else, invite the bot.
diff --git a/packages/twenty-apps/public/slack/package.json b/packages/twenty-apps/public/slack/package.json
index 39269a9e8d6..ae7ff46a37f 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": "0.7.0",
+ "version": "0.8.0",
"description": "Slack assistant and workflow steps for Twenty",
"license": "MIT",
"engines": {
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.tsx
index c77cc1a4c47..8370b3e1518 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
@@ -14,6 +14,7 @@ import { H2Title } from 'twenty-ui/typography';
import { SlackUserLinkForm } from 'src/front-components/components/SlackUserLinkForm';
import { SlackUserLinksList } from 'src/front-components/components/SlackUserLinksList';
import { UnlinkedSlackUsersList } from 'src/front-components/components/UnlinkedSlackUsersList';
+import { SLACK_CONNECTION_HEALTH_CALLOUTS } from 'src/front-components/constants/slack-connection-health-callouts.constant';
import { useCanManageSlackUserLinks } from 'src/front-components/hooks/use-can-manage-slack-user-links';
import { useMatchSlackUserLinks } from 'src/front-components/hooks/use-match-slack-user-links';
import { useSlackConnectionStatus } from 'src/front-components/hooks/use-slack-connection-status';
@@ -64,8 +65,13 @@ const StyledCenteredState = styled.div`
export const SlackUserLinksSettings = () => {
const { canManage, isPermissionLoading } = useCanManageSlackUserLinks();
- const { isSlackConnected, installedSlackTeamId, isConnectionStatusLoading } =
- useSlackConnectionStatus();
+ const {
+ isSlackConnected,
+ installedSlackTeamId,
+ connectionHealth,
+ hasRosterMatchFailed,
+ isConnectionStatusLoading,
+ } = useSlackConnectionStatus();
const {
slackUserLinks,
isSlackUserLinksLoading,
@@ -86,6 +92,9 @@ export const SlackUserLinksSettings = () => {
const [matchSummary, setMatchSummary] = useState<string | undefined>(
undefined,
);
+ const [hasLastMatchRunFailed, setHasLastMatchRunFailed] = useState<
+ boolean | undefined
+ >(undefined);
const [isManualFormOpen, setIsManualFormOpen] = useState(false);
const handleLinkSaved = async () => {
@@ -102,6 +111,7 @@ export const SlackUserLinksSettings = () => {
if (!result.success) {
setMatchSummary(undefined);
+ setHasLastMatchRunFailed(true);
enqueueSnackbar({
message: isNonEmptyString(result.error) ? result.error : result.message,
variant: 'error',
@@ -111,6 +121,7 @@ export const SlackUserLinksSettings = () => {
}
setMatchSummary(result.message);
+ setHasLastMatchRunFailed(result.failedCount > 0);
await handleLinkSaved();
};
@@ -161,10 +172,29 @@ export const SlackUserLinksSettings = () => {
return null;
}
+ const connectionHealthCallout = isDefined(connectionHealth)
+ ? SLACK_CONNECTION_HEALTH_CALLOUTS[connectionHealth]
+ : undefined;
+
+ if (isDefined(connectionHealthCallout)) {
+ return (
+ <StyledContainer>
+ <Callout
+ variant="error"
+ title={connectionHealthCallout.title}
+ description={connectionHealthCallout.description}
+ />
+ </StyledContainer>
+ );
+ }
+
if (isPermissionLoading) {
return <StyledCenteredState>Loading Slack user links…</StyledCenteredState>;
}
+ const shouldWarnAboutRosterMatch =
+ canManage && (hasLastMatchRunFailed ?? hasRosterMatchFailed);
+
return (
<StyledContainer>
{!canManage && (
@@ -174,6 +204,13 @@ export const SlackUserLinksSettings = () => {
description="Only members with the roles permission can create or change Slack user links. You can review the existing links below."
/>
)}
+ {shouldWarnAboutRosterMatch && (
+ <Callout
+ variant="warning"
+ title="Email auto-link did not finish"
+ description="The last automatic email match failed before linking everyone. Press Auto-link by email below to run it again."
+ />
+ )}
{canManage && (
<Section>
<H2Title
diff --git a/packages/twenty-apps/public/slack/src/front-components/constants/slack-connection-health-callouts.constant.ts b/packages/twenty-apps/public/slack/src/front-components/constants/slack-connection-health-callouts.constant.ts
new file mode 100644
index 00000000000..944199c05dd
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/front-components/constants/slack-connection-health-callouts.constant.ts
@@ -0,0 +1,26 @@
+import { type CalloutProps } from 'twenty-ui/feedback';
+
+import {
+ SLACK_CONNECTION_HEALTH,
+ type SlackConnectionHealth,
+} from 'src/logic-functions/constants/slack-connection-health';
+
+export const SLACK_CONNECTION_HEALTH_CALLOUTS: Partial<
+ Record<SlackConnectionHealth, Pick<CalloutProps, 'title' | 'description'>>
+> = {
+ [SLACK_CONNECTION_HEALTH.TOKEN_REJECTED]: {
+ title: 'Slack connection is no longer valid',
+ description:
+ 'Slack rejected the stored credentials, so the assistant cannot read or send messages. Remove the Slack connection and add it again.',
+ },
+ [SLACK_CONNECTION_HEALTH.TEAM_CLAIMED_BY_ANOTHER_WORKSPACE]: {
+ title: 'Slack workspace already connected elsewhere',
+ description:
+ 'This Slack workspace is registered to another Twenty workspace, so its messages are delivered there. Disconnect Slack in that workspace first, then remove the connection here and add it again.',
+ },
+ [SLACK_CONNECTION_HEALTH.TEAM_UNCLAIMED]: {
+ title: 'Slack connection needs to be registered again',
+ description:
+ 'No Twenty workspace is registered for this Slack workspace, so its messages are not delivered anywhere. Remove the Slack connection and add it again.',
+ },
+};
diff --git a/packages/twenty-apps/public/slack/src/front-components/hooks/use-match-slack-user-links.ts b/packages/twenty-apps/public/slack/src/front-components/hooks/use-match-slack-user-links.ts
index 7c7d8bb972e..758da4166d9 100644
--- a/packages/twenty-apps/public/slack/src/front-components/hooks/use-match-slack-user-links.ts
+++ b/packages/twenty-apps/public/slack/src/front-components/hooks/use-match-slack-user-links.ts
@@ -14,6 +14,7 @@ const buildFailureOutcome = (error: string): SlackRosterMatchOutcome => ({
error,
linkedCount: 0,
unmatchedCount: 0,
+ failedCount: 0,
});
export const useMatchSlackUserLinks = () => {
diff --git a/packages/twenty-apps/public/slack/src/front-components/types/parsed-slack-connection-status.type.ts b/packages/twenty-apps/public/slack/src/front-components/types/parsed-slack-connection-status.type.ts
index d5cd813219b..ba3ec476eb5 100644
--- a/packages/twenty-apps/public/slack/src/front-components/types/parsed-slack-connection-status.type.ts
+++ b/packages/twenty-apps/public/slack/src/front-components/types/parsed-slack-connection-status.type.ts
@@ -1,4 +1,8 @@
+import { type SlackConnectionHealth } from 'src/logic-functions/constants/slack-connection-health';
+
export type ParsedSlackConnectionStatus = {
isSlackConnected: boolean;
installedSlackTeamId: string | undefined;
+ connectionHealth: SlackConnectionHealth | undefined;
+ hasRosterMatchFailed: boolean;
};
diff --git a/packages/twenty-apps/public/slack/src/front-components/types/slack-roster-match-outcome.type.ts b/packages/twenty-apps/public/slack/src/front-components/types/slack-roster-match-outcome.type.ts
index 3af040e50ca..fa3f9fc4c39 100644
--- a/packages/twenty-apps/public/slack/src/front-components/types/slack-roster-match-outcome.type.ts
+++ b/packages/twenty-apps/public/slack/src/front-components/types/slack-roster-match-outcome.type.ts
@@ -4,4 +4,5 @@ export type SlackRosterMatchOutcome = {
error?: string;
linkedCount: number;
unmatchedCount: number;
+ failedCount: number;
};
diff --git a/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-connection-status.util.test.ts b/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-connection-status.util.test.ts
index ffb7d0754ae..7e66e74f7ad 100644
--- a/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-connection-status.util.test.ts
+++ b/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-connection-status.util.test.ts
@@ -3,20 +3,31 @@ import { describe, expect, it } from 'vitest';
import { parseSlackConnectionStatus } from 'src/front-components/utils/parse-slack-connection-status.util';
describe('parseSlackConnectionStatus', () => {
- it('should parse a connected status with its installed team id', () => {
+ it('should parse a healthy connected status with its installed team id', () => {
expect(
parseSlackConnectionStatus({
success: true,
isConnected: true,
installedSlackTeamId: 'T0INSTALLED',
+ connectionHealth: 'ok',
}),
- ).toEqual({ isSlackConnected: true, installedSlackTeamId: 'T0INSTALLED' });
+ ).toEqual({
+ isSlackConnected: true,
+ installedSlackTeamId: 'T0INSTALLED',
+ connectionHealth: 'ok',
+ hasRosterMatchFailed: false,
+ });
});
it('should leave the team id undefined when the payload omits it', () => {
expect(
parseSlackConnectionStatus({ success: true, isConnected: true }),
- ).toEqual({ isSlackConnected: true, installedSlackTeamId: undefined });
+ ).toEqual({
+ isSlackConnected: true,
+ installedSlackTeamId: undefined,
+ connectionHealth: undefined,
+ hasRosterMatchFailed: false,
+ });
});
it('should ignore a team id that is not a non-empty string', () => {
@@ -27,10 +38,59 @@ describe('parseSlackConnectionStatus', () => {
isConnected: true,
installedSlackTeamId,
}),
- ).toEqual({ isSlackConnected: true, installedSlackTeamId: undefined });
+ ).toEqual({
+ isSlackConnected: true,
+ installedSlackTeamId: undefined,
+ connectionHealth: undefined,
+ hasRosterMatchFailed: false,
+ });
}
});
+ it('should parse a broken connection health', () => {
+ expect(
+ parseSlackConnectionStatus({
+ success: true,
+ isConnected: true,
+ connectionHealth: 'team_claimed_by_another_workspace',
+ }),
+ ).toEqual({
+ isSlackConnected: true,
+ installedSlackTeamId: undefined,
+ connectionHealth: 'team_claimed_by_another_workspace',
+ hasRosterMatchFailed: false,
+ });
+ });
+
+ it('should drop an unknown health value', () => {
+ expect(
+ parseSlackConnectionStatus({
+ isConnected: true,
+ connectionHealth: 'exploded',
+ }),
+ ).toEqual({
+ isSlackConnected: true,
+ installedSlackTeamId: undefined,
+ connectionHealth: undefined,
+ hasRosterMatchFailed: false,
+ });
+ });
+
+ it('should surface a recorded roster match failure', () => {
+ expect(
+ parseSlackConnectionStatus({
+ isConnected: true,
+ connectionHealth: 'ok',
+ hasRosterMatchFailed: true,
+ }),
+ ).toEqual({
+ isSlackConnected: true,
+ installedSlackTeamId: undefined,
+ connectionHealth: 'ok',
+ hasRosterMatchFailed: true,
+ });
+ });
+
it('should report a disconnected status', () => {
expect(
parseSlackConnectionStatus({
@@ -38,7 +98,12 @@ describe('parseSlackConnectionStatus', () => {
isConnected: false,
installedSlackTeamId: 'T0INSTALLED',
}),
- ).toEqual({ isSlackConnected: false, installedSlackTeamId: undefined });
+ ).toEqual({
+ isSlackConnected: false,
+ installedSlackTeamId: undefined,
+ connectionHealth: undefined,
+ hasRosterMatchFailed: false,
+ });
});
it('should fall back on a malformed payload', () => {
@@ -46,6 +111,8 @@ describe('parseSlackConnectionStatus', () => {
expect(parseSlackConnectionStatus(value)).toEqual({
isSlackConnected: false,
installedSlackTeamId: undefined,
+ connectionHealth: undefined,
+ hasRosterMatchFailed: false,
});
}
});
diff --git a/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-roster-match-result.util.test.ts b/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-roster-match-result.util.test.ts
index 399932712bd..abdb79294c1 100644
--- a/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-roster-match-result.util.test.ts
+++ b/packages/twenty-apps/public/slack/src/front-components/utils/__tests__/parse-slack-roster-match-result.util.test.ts
@@ -13,6 +13,7 @@ describe('parseSlackRosterMatchResult', () => {
linkedCount: 2,
alreadyLinkedCount: 1,
unmatchedCount: 3,
+ failedCount: 1,
},
fallbackMessage: FALLBACK_MESSAGE,
});
@@ -21,6 +22,7 @@ describe('parseSlackRosterMatchResult', () => {
expect(result.message).toBe('Matched 2 Slack users by email.');
expect(result.linkedCount).toBe(2);
expect(result.unmatchedCount).toBe(3);
+ expect(result.failedCount).toBe(1);
});
it('should default counts to zero when missing', () => {
@@ -31,6 +33,7 @@ describe('parseSlackRosterMatchResult', () => {
expect(result.linkedCount).toBe(0);
expect(result.unmatchedCount).toBe(0);
+ expect(result.failedCount).toBe(0);
});
it('should ignore non-numeric counts', () => {
diff --git a/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-connection-status.util.ts b/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-connection-status.util.ts
index 6218c123b0c..e529391f97b 100644
--- a/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-connection-status.util.ts
+++ b/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-connection-status.util.ts
@@ -1,14 +1,27 @@
import { isNonEmptyString } from '@sniptt/guards';
import { type ParsedSlackConnectionStatus } from 'src/front-components/types/parsed-slack-connection-status.type';
+import {
+ SLACK_CONNECTION_HEALTH,
+ type SlackConnectionHealth,
+} from 'src/logic-functions/constants/slack-connection-health';
import { asRecord } from 'src/logic-functions/utils/as-record.util';
export const DISCONNECTED_SLACK_CONNECTION_STATUS: ParsedSlackConnectionStatus =
{
isSlackConnected: false,
installedSlackTeamId: undefined,
+ connectionHealth: undefined,
+ hasRosterMatchFailed: false,
};
+const KNOWN_HEALTH_VALUES: string[] = Object.values(SLACK_CONNECTION_HEALTH);
+
+const isSlackConnectionHealth = (
+ value: unknown,
+): value is SlackConnectionHealth =>
+ typeof value === 'string' && KNOWN_HEALTH_VALUES.includes(value);
+
export const parseSlackConnectionStatus = (
value: unknown,
): ParsedSlackConnectionStatus => {
@@ -25,5 +38,9 @@ export const parseSlackConnectionStatus = (
installedSlackTeamId: isNonEmptyString(installedSlackTeamId)
? installedSlackTeamId
: undefined,
+ connectionHealth: isSlackConnectionHealth(record.connectionHealth)
+ ? record.connectionHealth
+ : undefined,
+ hasRosterMatchFailed: record.hasRosterMatchFailed === true,
};
};
diff --git a/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-roster-match-result.util.ts b/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-roster-match-result.util.ts
index 387cd3a4663..ad97910ce2d 100644
--- a/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-roster-match-result.util.ts
+++ b/packages/twenty-apps/public/slack/src/front-components/utils/parse-slack-roster-match-result.util.ts
@@ -20,5 +20,6 @@ export const parseSlackRosterMatchResult = ({
unmatchedCount: isNumber(record?.unmatchedCount)
? record.unmatchedCount
: 0,
+ failedCount: isNumber(record?.failedCount) ? record.failedCount : 0,
};
};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-auth-error-codes.ts b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-auth-error-codes.ts
new file mode 100644
index 00000000000..1cfdd7592da
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-auth-error-codes.ts
@@ -0,0 +1,7 @@
+export const SLACK_AUTH_ERROR_CODES = [
+ 'invalid_auth',
+ 'not_authed',
+ 'account_inactive',
+ 'token_revoked',
+ 'token_expired',
+];
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-connection-health.ts b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-connection-health.ts
new file mode 100644
index 00000000000..89f64d7dda5
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-connection-health.ts
@@ -0,0 +1,9 @@
+export const SLACK_CONNECTION_HEALTH = {
+ OK: 'ok',
+ TOKEN_REJECTED: 'token_rejected',
+ TEAM_UNCLAIMED: 'team_unclaimed',
+ TEAM_CLAIMED_BY_ANOTHER_WORKSPACE: 'team_claimed_by_another_workspace',
+} as const;
+
+export type SlackConnectionHealth =
+ (typeof SLACK_CONNECTION_HEALTH)[keyof typeof SLACK_CONNECTION_HEALTH];
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-roster-match-run-outcome-kv-key.ts b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-roster-match-run-outcome-kv-key.ts
new file mode 100644
index 00000000000..488441c7843
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/constants/slack-roster-match-run-outcome-kv-key.ts
@@ -0,0 +1,2 @@
+export const SLACK_ROSTER_MATCH_RUN_OUTCOME_KV_KEY =
+ 'slack-roster-match-run-outcome';
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.ts
index eb311450543..54800f4bb31 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/__tests__/slack-connection-status-handler.test.ts
@@ -1,42 +1,42 @@
+import { type WebClient } from '@slack/web-api';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { SLACK_CONNECTION_STATUS_TIMEOUT_MS } from 'src/logic-functions/constants/slack-connection-status-timeout-ms';
import { slackConnectionStatusHandler } from 'src/logic-functions/handlers/slack-connection-status-handler';
import { getSlackClient } from 'src/logic-functions/utils/get-slack-client';
+import { readSlackRosterMatchRunOutcome } from 'src/logic-functions/utils/read-slack-roster-match-run-outcome';
+import { resolveSlackConnectionHealth } from 'src/logic-functions/utils/resolve-slack-connection-health';
vi.mock('src/logic-functions/utils/get-slack-client', () => ({
getSlackClient: vi.fn(),
}));
-const authTestMock = vi.fn();
+vi.mock('src/logic-functions/utils/resolve-slack-connection-health', () => ({
+ resolveSlackConnectionHealth: vi.fn(),
+}));
-const mockConnectedSlackClient = () => {
- vi.mocked(getSlackClient).mockResolvedValueOnce({
- success: true,
- client: { auth: { test: authTestMock } } as never,
- });
-};
+vi.mock(
+ 'src/logic-functions/utils/read-slack-roster-match-run-outcome',
+ () => ({
+ readSlackRosterMatchRunOutcome: vi.fn(),
+ }),
+);
describe('slackConnectionStatusHandler', () => {
beforeEach(() => {
vi.clearAllMocks();
- });
-
- it('should report a connected workspace with its installed team id', async () => {
- mockConnectedSlackClient();
- authTestMock.mockResolvedValueOnce({ ok: true, team_id: 'T0INSTALLED' });
-
- await expect(slackConnectionStatusHandler()).resolves.toEqual({
+ vi.mocked(getSlackClient).mockResolvedValue({
success: true,
- isConnected: true,
+ client: {} as WebClient,
+ });
+ vi.mocked(resolveSlackConnectionHealth).mockResolvedValue({
+ connectionHealth: 'ok',
installedSlackTeamId: 'T0INSTALLED',
});
+ vi.mocked(readSlackRosterMatchRunOutcome).mockResolvedValue(undefined);
});
it('should bound the Slack call so a hanging Slack cannot exhaust the route budget', async () => {
- mockConnectedSlackClient();
- authTestMock.mockResolvedValueOnce({ ok: true, team_id: 'T0INSTALLED' });
-
await slackConnectionStatusHandler();
expect(getSlackClient).toHaveBeenCalledWith({
@@ -46,7 +46,7 @@ describe('slackConnectionStatusHandler', () => {
});
it('should report a missing connection without failing', async () => {
- vi.mocked(getSlackClient).mockResolvedValueOnce({
+ vi.mocked(getSlackClient).mockResolvedValue({
success: false,
error: 'Slack is not connected.',
});
@@ -56,28 +56,61 @@ describe('slackConnectionStatusHandler', () => {
isConnected: false,
});
- expect(authTestMock).not.toHaveBeenCalled();
+ expect(resolveSlackConnectionHealth).not.toHaveBeenCalled();
});
- it('should stay connected without a team id when Slack does not answer', async () => {
- mockConnectedSlackClient();
- authTestMock.mockRejectedValueOnce(new Error('invalid_auth'));
+ it('should report a healthy connection with its installed team id', async () => {
+ await expect(slackConnectionStatusHandler()).resolves.toEqual({
+ success: true,
+ isConnected: true,
+ installedSlackTeamId: 'T0INSTALLED',
+ connectionHealth: 'ok',
+ hasRosterMatchFailed: false,
+ });
+ });
+
+ it('should report a broken connection', async () => {
+ vi.mocked(resolveSlackConnectionHealth).mockResolvedValue({
+ connectionHealth: 'token_rejected',
+ installedSlackTeamId: undefined,
+ });
await expect(slackConnectionStatusHandler()).resolves.toEqual({
success: true,
isConnected: true,
installedSlackTeamId: undefined,
+ connectionHealth: 'token_rejected',
+ hasRosterMatchFailed: false,
});
});
- it('should ignore an empty team id', async () => {
- mockConnectedSlackClient();
- authTestMock.mockResolvedValueOnce({ ok: true, team_id: '' });
+ it('should report no health when it could not be verified', async () => {
+ vi.mocked(resolveSlackConnectionHealth).mockResolvedValue({
+ connectionHealth: undefined,
+ installedSlackTeamId: undefined,
+ });
await expect(slackConnectionStatusHandler()).resolves.toEqual({
success: true,
isConnected: true,
installedSlackTeamId: undefined,
+ connectionHealth: undefined,
+ hasRosterMatchFailed: false,
+ });
+ });
+
+ it('should flag a recorded roster match failure', async () => {
+ vi.mocked(readSlackRosterMatchRunOutcome).mockResolvedValue({
+ isSuccessful: false,
+ errorMessage: 'kaboom',
+ });
+
+ await expect(slackConnectionStatusHandler()).resolves.toEqual({
+ success: true,
+ isConnected: true,
+ installedSlackTeamId: 'T0INSTALLED',
+ connectionHealth: 'ok',
+ hasRosterMatchFailed: true,
});
});
});
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.ts b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.ts
index c380c2cd0fb..e9d034d7624 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/handlers/slack-connection-status-handler.ts
@@ -1,11 +1,15 @@
+import { type SlackConnectionHealth } from 'src/logic-functions/constants/slack-connection-health';
import { SLACK_CONNECTION_STATUS_TIMEOUT_MS } from 'src/logic-functions/constants/slack-connection-status-timeout-ms';
-import { getInstalledSlackTeamId } from 'src/logic-functions/utils/get-installed-slack-team-id';
import { getSlackClient } from 'src/logic-functions/utils/get-slack-client';
+import { readSlackRosterMatchRunOutcome } from 'src/logic-functions/utils/read-slack-roster-match-run-outcome';
+import { resolveSlackConnectionHealth } from 'src/logic-functions/utils/resolve-slack-connection-health';
type SlackConnectionStatusResult = {
success: true;
isConnected: boolean;
installedSlackTeamId?: string;
+ connectionHealth?: SlackConnectionHealth;
+ hasRosterMatchFailed?: boolean;
};
export const slackConnectionStatusHandler =
@@ -19,9 +23,16 @@ export const slackConnectionStatusHandler =
return { success: true, isConnected: false };
}
- const installedSlackTeamId = await getInstalledSlackTeamId(
- slackClientResult.client,
- );
+ const [connectionHealthReport, rosterMatchRunOutcome] = await Promise.all([
+ resolveSlackConnectionHealth(slackClientResult.client),
+ readSlackRosterMatchRunOutcome(),
+ ]);
- return { success: true, isConnected: true, installedSlackTeamId };
+ return {
+ success: true,
+ isConnected: true,
+ installedSlackTeamId: connectionHealthReport.installedSlackTeamId,
+ connectionHealth: connectionHealthReport.connectionHealth,
+ hasRosterMatchFailed: rosterMatchRunOutcome?.isSuccessful === false,
+ };
};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/slack-connection-status.ts b/packages/twenty-apps/public/slack/src/logic-functions/slack-connection-status.ts
index 99dae59e9cb..5263c91d6d3 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/slack-connection-status.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/slack-connection-status.ts
@@ -8,7 +8,7 @@ export default defineLogicFunction({
universalIdentifier: SLACK_CONNECTION_STATUS_UNIVERSAL_IDENTIFIER,
name: 'slack-connection-status',
description:
- 'Tells the settings tab whether a Slack workspace connection exists, so it can hide the link management tools until Slack is connected.',
+ 'Tells the settings tab whether a Slack workspace connection exists and whether it is healthy: the stored token still passes auth.test, and the installed Slack team is claimed by this Twenty workspace so events route here. The tab hides the link management tools until Slack is connected and shows a repair callout when the connection is broken.',
timeoutSeconds: 30,
httpRouteTriggerSettings: {
path: SLACK_USER_LINKS_CONNECTION_STATUS_ROUTE_PATH,
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/types/slack-roster-match-run-outcome.type.ts b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-roster-match-run-outcome.type.ts
new file mode 100644
index 00000000000..52553565502
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/types/slack-roster-match-run-outcome.type.ts
@@ -0,0 +1,4 @@
+export type SlackRosterMatchRunOutcome = {
+ isSuccessful: boolean;
+ errorMessage?: string;
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/match-slack-roster-by-email.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/match-slack-roster-by-email.test.ts
index 86d0d4baeec..5e8edb05f17 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/match-slack-roster-by-email.test.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/match-slack-roster-by-email.test.ts
@@ -9,11 +9,13 @@ const {
findWorkspaceMemberIdsByEmailsMock,
listLinkedSlackUserIdsMock,
linkSlackRosterCandidatesMock,
+ saveSlackRosterMatchRunOutcomeMock,
} = vi.hoisted(() => ({
coreApiClientMock: vi.fn(),
findWorkspaceMemberIdsByEmailsMock: vi.fn(),
listLinkedSlackUserIdsMock: vi.fn(),
linkSlackRosterCandidatesMock: vi.fn(),
+ saveSlackRosterMatchRunOutcomeMock: vi.fn(),
}));
vi.mock('twenty-client-sdk/core', () => ({
@@ -32,6 +34,13 @@ vi.mock('src/logic-functions/utils/link-slack-roster-candidates', () => ({
linkSlackRosterCandidates: linkSlackRosterCandidatesMock,
}));
+vi.mock(
+ 'src/logic-functions/utils/save-slack-roster-match-run-outcome',
+ () => ({
+ saveSlackRosterMatchRunOutcome: saveSlackRosterMatchRunOutcomeMock,
+ }),
+);
+
const SLACK_TEAM_ID = 'T-installed';
const buildSlackClient = (members: SlackRosterMember[]): WebClient =>
@@ -262,6 +271,53 @@ describe('matchSlackRosterByEmail', () => {
});
});
+ it('should record a completed match as successful', async () => {
+ await matchSlackRosterByEmail({
+ slackClient: buildSlackClient([
+ fullMember({ id: 'U1', email: '[email protected]' }),
+ ]),
+ slackTeamId: SLACK_TEAM_ID,
+ });
+
+ expect(saveSlackRosterMatchRunOutcomeMock).toHaveBeenCalledWith({
+ isSuccessful: true,
+ });
+ });
+
+ it('should record a match with failed writes as unsuccessful', async () => {
+ linkSlackRosterCandidatesMock.mockResolvedValue({
+ linkedCount: 0,
+ failedCount: 1,
+ });
+
+ await matchSlackRosterByEmail({
+ slackClient: buildSlackClient([
+ fullMember({ id: 'U1', email: '[email protected]' }),
+ ]),
+ slackTeamId: SLACK_TEAM_ID,
+ });
+
+ expect(saveSlackRosterMatchRunOutcomeMock).toHaveBeenCalledWith({
+ isSuccessful: false,
+ });
+ });
+
+ it('should record the failure and rethrow when the match blows up', async () => {
+ listLinkedSlackUserIdsMock.mockRejectedValue(new Error('kaboom'));
+
+ await expect(
+ matchSlackRosterByEmail({
+ slackClient: buildSlackClient([]),
+ slackTeamId: SLACK_TEAM_ID,
+ }),
+ ).rejects.toThrow('kaboom');
+
+ expect(saveSlackRosterMatchRunOutcomeMock).toHaveBeenCalledWith({
+ isSuccessful: false,
+ errorMessage: 'kaboom',
+ });
+ });
+
it('should report truncation when the roster exceeds the page cap', async () => {
const usersListMock = vi.fn().mockResolvedValue({
members: [fullMember({ id: 'U1', email: '[email protected]' })],
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/read-slack-roster-match-run-outcome.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/read-slack-roster-match-run-outcome.test.ts
new file mode 100644
index 00000000000..eefc599ff34
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/read-slack-roster-match-run-outcome.test.ts
@@ -0,0 +1,54 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { readSlackRosterMatchRunOutcome } from 'src/logic-functions/utils/read-slack-roster-match-run-outcome';
+
+const { kvGetMock } = vi.hoisted(() => ({ kvGetMock: vi.fn() }));
+
+vi.mock('twenty-sdk/logic-function', () => ({
+ kv: { get: kvGetMock },
+}));
+
+describe('readSlackRosterMatchRunOutcome', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should read a stored failure with its error message', async () => {
+ kvGetMock.mockResolvedValue({
+ isSuccessful: false,
+ errorMessage: 'kaboom',
+ });
+
+ await expect(readSlackRosterMatchRunOutcome()).resolves.toEqual({
+ isSuccessful: false,
+ errorMessage: 'kaboom',
+ });
+ });
+
+ it('should read a stored success', async () => {
+ kvGetMock.mockResolvedValue({ isSuccessful: true });
+
+ await expect(readSlackRosterMatchRunOutcome()).resolves.toEqual({
+ isSuccessful: true,
+ errorMessage: undefined,
+ });
+ });
+
+ it('should return undefined when nothing was recorded', async () => {
+ kvGetMock.mockResolvedValue(null);
+
+ await expect(readSlackRosterMatchRunOutcome()).resolves.toBeUndefined();
+ });
+
+ it('should return undefined for a malformed record', async () => {
+ kvGetMock.mockResolvedValue({ isSuccessful: 'yes' });
+
+ await expect(readSlackRosterMatchRunOutcome()).resolves.toBeUndefined();
+ });
+
+ it('should return undefined when the read fails', async () => {
+ kvGetMock.mockRejectedValue(new Error('kv unavailable'));
+
+ await expect(readSlackRosterMatchRunOutcome()).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-connection-health.test.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-connection-health.test.ts
new file mode 100644
index 00000000000..8f6f3a5dcfa
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/__tests__/resolve-slack-connection-health.test.ts
@@ -0,0 +1,104 @@
+import { type WebClient } from '@slack/web-api';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { fetchCurrentWorkspaceId } from 'src/logic-functions/utils/fetch-current-workspace-id';
+import { findClaimedWorkspaceId } from 'src/logic-functions/utils/find-claimed-workspace-id';
+import { resolveSlackConnectionHealth } from 'src/logic-functions/utils/resolve-slack-connection-health';
+
+vi.mock('src/logic-functions/utils/find-claimed-workspace-id', () => ({
+ findClaimedWorkspaceId: vi.fn(),
+}));
+
+vi.mock('src/logic-functions/utils/fetch-current-workspace-id', () => ({
+ fetchCurrentWorkspaceId: vi.fn(),
+}));
+
+const authTest = vi.fn();
+
+const slackClient = { auth: { test: authTest } } as unknown as WebClient;
+
+describe('resolveSlackConnectionHealth', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ authTest.mockResolvedValue({ ok: true, team_id: 'T1' });
+ vi.mocked(findClaimedWorkspaceId).mockResolvedValue('workspace-1');
+ vi.mocked(fetchCurrentWorkspaceId).mockResolvedValue('workspace-1');
+ });
+
+ it('should report a healthy connection claimed by this workspace', async () => {
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: 'ok',
+ installedSlackTeamId: 'T1',
+ });
+ });
+
+ it('should report a rejected token', async () => {
+ authTest.mockRejectedValue(
+ Object.assign(new Error('An API error occurred: invalid_auth'), {
+ data: { ok: false, error: 'invalid_auth' },
+ }),
+ );
+
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: 'token_rejected',
+ installedSlackTeamId: undefined,
+ });
+ });
+
+ it('should not raise an alarm on a transient auth.test failure', async () => {
+ authTest.mockRejectedValue(new Error('socket hang up'));
+
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: undefined,
+ installedSlackTeamId: undefined,
+ });
+ });
+
+ it('should claim no health when auth.test returns no team id', async () => {
+ authTest.mockResolvedValue({ ok: true });
+
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: undefined,
+ installedSlackTeamId: undefined,
+ });
+ });
+
+ it('should report an unclaimed team', async () => {
+ vi.mocked(findClaimedWorkspaceId).mockResolvedValue(null);
+
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: 'team_unclaimed',
+ installedSlackTeamId: 'T1',
+ });
+ });
+
+ it('should report a team claimed by another workspace', async () => {
+ vi.mocked(findClaimedWorkspaceId).mockResolvedValue('workspace-2');
+
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: 'team_claimed_by_another_workspace',
+ installedSlackTeamId: 'T1',
+ });
+ });
+
+ it('should stay quiet when the claim lookup fails transiently', async () => {
+ vi.mocked(findClaimedWorkspaceId).mockRejectedValue(
+ new Error('kv unavailable'),
+ );
+
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: undefined,
+ installedSlackTeamId: 'T1',
+ });
+ });
+
+ it('should claim no health when the current workspace id is unknown', async () => {
+ vi.mocked(fetchCurrentWorkspaceId).mockResolvedValue(undefined);
+ vi.mocked(findClaimedWorkspaceId).mockResolvedValue('workspace-2');
+
+ await expect(resolveSlackConnectionHealth(slackClient)).resolves.toEqual({
+ connectionHealth: undefined,
+ installedSlackTeamId: 'T1',
+ });
+ });
+});
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/fetch-current-workspace-id.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/fetch-current-workspace-id.ts
new file mode 100644
index 00000000000..4466ad28254
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/fetch-current-workspace-id.ts
@@ -0,0 +1,28 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
+
+const CURRENT_WORKSPACE_ID_TIMEOUT_MS = 5_000;
+
+export const fetchCurrentWorkspaceId = async (): Promise<
+ string | undefined
+> => {
+ try {
+ const { currentWorkspace } = await new MetadataApiClient({
+ signal: AbortSignal.timeout(CURRENT_WORKSPACE_ID_TIMEOUT_MS),
+ }).query({
+ currentWorkspace: { id: true },
+ });
+
+ const workspaceId = currentWorkspace?.id;
+
+ return isNonEmptyString(workspaceId) ? workspaceId : undefined;
+ } catch (error) {
+ console.warn(
+ `[slack] failed to read the current workspace id: ${toErrorMessage(error)}`,
+ );
+
+ return undefined;
+ }
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/match-slack-roster-by-email.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/match-slack-roster-by-email.ts
index 5cf60fdb44c..6423f3d09a4 100644
--- a/packages/twenty-apps/public/slack/src/logic-functions/utils/match-slack-roster-by-email.ts
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/match-slack-roster-by-email.ts
@@ -9,8 +9,10 @@ import { collectSlackRosterMembers } from 'src/logic-functions/utils/collect-sla
import { getVouchedSlackRosterEmail } from 'src/logic-functions/utils/get-vouched-slack-roster-email';
import { linkSlackRosterCandidates } from 'src/logic-functions/utils/link-slack-roster-candidates';
import { planSlackRosterMatch } from 'src/logic-functions/utils/plan-slack-roster-match';
+import { saveSlackRosterMatchRunOutcome } from 'src/logic-functions/utils/save-slack-roster-match-run-outcome';
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
-export const matchSlackRosterByEmail = async ({
+const runSlackRosterMatch = async ({
slackClient,
slackTeamId,
}: {
@@ -60,3 +62,28 @@ export const matchSlackRosterByEmail = async ({
isRosterTruncated: roster.isTruncated,
};
};
+
+export const matchSlackRosterByEmail = async ({
+ slackClient,
+ slackTeamId,
+}: {
+ slackClient: WebClient;
+ slackTeamId: string;
+}): Promise<SlackRosterMatchSummary> => {
+ try {
+ const summary = await runSlackRosterMatch({ slackClient, slackTeamId });
+
+ await saveSlackRosterMatchRunOutcome({
+ isSuccessful: summary.failedCount === 0,
+ });
+
+ return summary;
+ } catch (error) {
+ await saveSlackRosterMatchRunOutcome({
+ isSuccessful: false,
+ errorMessage: toErrorMessage(error),
+ });
+
+ throw error;
+ }
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/read-slack-roster-match-run-outcome.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/read-slack-roster-match-run-outcome.ts
new file mode 100644
index 00000000000..78e9a311220
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/read-slack-roster-match-run-outcome.ts
@@ -0,0 +1,27 @@
+import { kv } from 'twenty-sdk/logic-function';
+
+import { SLACK_ROSTER_MATCH_RUN_OUTCOME_KV_KEY } from 'src/logic-functions/constants/slack-roster-match-run-outcome-kv-key';
+import { type SlackRosterMatchRunOutcome } from 'src/logic-functions/types/slack-roster-match-run-outcome.type';
+import { asRecord } from 'src/logic-functions/utils/as-record.util';
+import { readOptionalString } from 'src/logic-functions/utils/read-optional-string.util';
+
+export const readSlackRosterMatchRunOutcome = async (): Promise<
+ SlackRosterMatchRunOutcome | undefined
+> => {
+ try {
+ const record = asRecord(
+ await kv.get(SLACK_ROSTER_MATCH_RUN_OUTCOME_KV_KEY),
+ );
+
+ if (typeof record?.isSuccessful !== 'boolean') {
+ return undefined;
+ }
+
+ return {
+ isSuccessful: record.isSuccessful,
+ errorMessage: readOptionalString(record.errorMessage),
+ };
+ } catch {
+ return undefined;
+ }
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-connection-health.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-connection-health.ts
new file mode 100644
index 00000000000..5f3a639e5c0
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/resolve-slack-connection-health.ts
@@ -0,0 +1,108 @@
+import { type WebClient } from '@slack/web-api';
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { SLACK_AUTH_ERROR_CODES } from 'src/logic-functions/constants/slack-auth-error-codes';
+import {
+ SLACK_CONNECTION_HEALTH,
+ type SlackConnectionHealth,
+} from 'src/logic-functions/constants/slack-connection-health';
+import { fetchCurrentWorkspaceId } from 'src/logic-functions/utils/fetch-current-workspace-id';
+import { findClaimedWorkspaceId } from 'src/logic-functions/utils/find-claimed-workspace-id';
+import { getSlackApiErrorCode } from 'src/logic-functions/utils/get-slack-api-error-code';
+import { readOptionalString } from 'src/logic-functions/utils/read-optional-string.util';
+
+export type SlackConnectionHealthReport = {
+ connectionHealth: SlackConnectionHealth | undefined;
+ installedSlackTeamId: string | undefined;
+};
+
+type SlackAuthProbe =
+ | { isAuthenticated: true; installedTeamId: string | undefined }
+ | { isAuthenticated: false; isTokenRejected: boolean };
+
+type SlackTeamClaimLookup =
+ | { isReadable: true; claimedWorkspaceId: string | null }
+ | { isReadable: false };
+
+const probeSlackAuth = async (
+ slackClient: WebClient,
+): Promise<SlackAuthProbe> => {
+ try {
+ const authResult = await slackClient.auth.test();
+
+ return {
+ isAuthenticated: true,
+ installedTeamId: readOptionalString(authResult.team_id),
+ };
+ } catch (error) {
+ const slackErrorCode = getSlackApiErrorCode(error);
+
+ return {
+ isAuthenticated: false,
+ isTokenRejected:
+ isNonEmptyString(slackErrorCode) &&
+ SLACK_AUTH_ERROR_CODES.includes(slackErrorCode),
+ };
+ }
+};
+
+const readSlackTeamClaim = (
+ installedTeamId: string,
+): Promise<SlackTeamClaimLookup> =>
+ findClaimedWorkspaceId(installedTeamId).then(
+ (claimedWorkspaceId) => ({ isReadable: true as const, claimedWorkspaceId }),
+ () => ({ isReadable: false as const }),
+ );
+
+// An undefined health means unverified, not healthy: a transient Slack or
+// claim-store failure must never tell an admin to reconnect a working
+// integration.
+export const resolveSlackConnectionHealth = async (
+ slackClient: WebClient,
+): Promise<SlackConnectionHealthReport> => {
+ const authProbe = await probeSlackAuth(slackClient);
+
+ if (!authProbe.isAuthenticated) {
+ return {
+ connectionHealth: authProbe.isTokenRejected
+ ? SLACK_CONNECTION_HEALTH.TOKEN_REJECTED
+ : undefined,
+ installedSlackTeamId: undefined,
+ };
+ }
+
+ const installedSlackTeamId = authProbe.installedTeamId;
+
+ if (!isDefined(installedSlackTeamId)) {
+ return { connectionHealth: undefined, installedSlackTeamId: undefined };
+ }
+
+ const [teamClaim, currentWorkspaceId] = await Promise.all([
+ readSlackTeamClaim(installedSlackTeamId),
+ fetchCurrentWorkspaceId(),
+ ]);
+
+ if (!teamClaim.isReadable) {
+ return { connectionHealth: undefined, installedSlackTeamId };
+ }
+
+ if (!isDefined(teamClaim.claimedWorkspaceId)) {
+ return {
+ connectionHealth: SLACK_CONNECTION_HEALTH.TEAM_UNCLAIMED,
+ installedSlackTeamId,
+ };
+ }
+
+ if (!isNonEmptyString(currentWorkspaceId)) {
+ return { connectionHealth: undefined, installedSlackTeamId };
+ }
+
+ return {
+ connectionHealth:
+ teamClaim.claimedWorkspaceId === currentWorkspaceId
+ ? SLACK_CONNECTION_HEALTH.OK
+ : SLACK_CONNECTION_HEALTH.TEAM_CLAIMED_BY_ANOTHER_WORKSPACE,
+ installedSlackTeamId,
+ };
+};
diff --git a/packages/twenty-apps/public/slack/src/logic-functions/utils/save-slack-roster-match-run-outcome.ts b/packages/twenty-apps/public/slack/src/logic-functions/utils/save-slack-roster-match-run-outcome.ts
new file mode 100644
index 00000000000..9d6497a083a
--- /dev/null
+++ b/packages/twenty-apps/public/slack/src/logic-functions/utils/save-slack-roster-match-run-outcome.ts
@@ -0,0 +1,17 @@
+import { kv } from 'twenty-sdk/logic-function';
+
+import { SLACK_ROSTER_MATCH_RUN_OUTCOME_KV_KEY } from 'src/logic-functions/constants/slack-roster-match-run-outcome-kv-key';
+import { type SlackRosterMatchRunOutcome } from 'src/logic-functions/types/slack-roster-match-run-outcome.type';
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
+
+export const saveSlackRosterMatchRunOutcome = async (
+ outcome: SlackRosterMatchRunOutcome,
+): Promise<void> => {
+ try {
+ await kv.set(SLACK_ROSTER_MATCH_RUN_OUTCOME_KV_KEY, outcome);
+ } catch (error) {
+ console.warn(
+ `[slack] failed to record the roster match outcome: ${toErrorMessage(error)}`,
+ );
+ }
+};