Skip to content

The open alternative to Salesforce, designed for AI.

feat(teams): answer Teams assistant requests (#27811)

Abdul Rahmanf686d616e088
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-agent-budget-seconds.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-agent-budget-seconds.ts
new file mode 100644
index 00000000000..b81e8729dab
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-agent-budget-seconds.ts
@@ -0,0 +1,6 @@
+import { TEAMS_ASSISTANT_REQUEST_TIMEOUT_SECONDS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-timeout-seconds';
+
+const FAILURE_REPLY_RESERVE_SECONDS = 30;
+
+export const TEAMS_ASSISTANT_AGENT_BUDGET_SECONDS =
+ TEAMS_ASSISTANT_REQUEST_TIMEOUT_SECONDS - FAILURE_REPLY_RESERVE_SECONDS;
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-failure-text.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-failure-text.ts
new file mode 100644
index 00000000000..08bb5e0f51e
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-failure-text.ts
@@ -0,0 +1,2 @@
+export const TEAMS_ASSISTANT_FAILURE_TEXT =
+ 'Sorry, I could not complete that request. An admin can check the Teams Assistant Request record in Twenty for details.';
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-unmatched-sender-text.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-unmatched-sender-text.ts
new file mode 100644
index 00000000000..c68d6a54426
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-unmatched-sender-text.ts
@@ -0,0 +1,2 @@
+export const TEAMS_ASSISTANT_UNMATCHED_SENDER_TEXT =
+ 'I could not match your Teams account to a member of this Twenty workspace. Ask an admin to invite you to Twenty with the same email address you use in Teams.';
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-connector-request-timeout-ms.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-connector-request-timeout-ms.ts
new file mode 100644
index 00000000000..8d90b2a8281
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-connector-request-timeout-ms.ts
@@ -0,0 +1 @@
+export const TEAMS_CONNECTOR_REQUEST_TIMEOUT_MS = 10_000;
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/claim-teams-assistant-request.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/claim-teams-assistant-request.ts
new file mode 100644
index 00000000000..854051575c2
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/claim-teams-assistant-request.ts
@@ -0,0 +1,42 @@
+import { isNonEmptyArray } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { TEAMS_ASSISTANT_REQUEST_STATUS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-status';
+import { TEAMS_ASSISTANT_REQUEST_TIMEOUT_SECONDS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-timeout-seconds';
+
+export const claimTeamsAssistantRequest = async ({
+ client,
+ id,
+}: {
+ client: Pick<CoreApiClient, 'mutation'>;
+ id: string;
+}): Promise<boolean> => {
+ const leaseCutoff = new Date(
+ Date.now() - TEAMS_ASSISTANT_REQUEST_TIMEOUT_SECONDS * 1000,
+ ).toISOString();
+
+ const mutationResult = await client.mutation({
+ updateTeamsAssistantRequests: {
+ __args: {
+ data: { status: TEAMS_ASSISTANT_REQUEST_STATUS.PROCESSING },
+ filter: {
+ and: [
+ { id: { eq: id } },
+ {
+ or: [
+ { status: { eq: TEAMS_ASSISTANT_REQUEST_STATUS.PENDING } },
+ {
+ status: { eq: TEAMS_ASSISTANT_REQUEST_STATUS.PROCESSING },
+ updatedAt: { lt: leaseCutoff },
+ },
+ ],
+ },
+ ],
+ },
+ },
+ id: true,
+ },
+ });
+
+ return isNonEmptyArray(mutationResult.updateTeamsAssistantRequests);
+};
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/update-teams-assistant-request.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/update-teams-assistant-request.ts
new file mode 100644
index 00000000000..4621e149c16
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/update-teams-assistant-request.ts
@@ -0,0 +1,37 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type TeamsAssistantRequestStatus } from 'src/features/chat/logic-functions/types/teams-assistant-request-status.type';
+
+export const updateTeamsAssistantRequest = async ({
+ client,
+ id,
+ status,
+ responseText,
+ errorMessage,
+ workspaceMemberId,
+}: {
+ client: Pick<CoreApiClient, 'mutation'>;
+ id: string;
+ status?: TeamsAssistantRequestStatus;
+ responseText?: string;
+ errorMessage?: string;
+ workspaceMemberId?: string;
+}): Promise<void> => {
+ await client.mutation({
+ updateTeamsAssistantRequest: {
+ __args: {
+ id,
+ data: {
+ ...(isDefined(status) ? { status } : {}),
+ ...(isDefined(responseText)
+ ? { responseText: { blocknote: null, markdown: responseText } }
+ : {}),
+ ...(isDefined(errorMessage) ? { errorMessage } : {}),
+ ...(isDefined(workspaceMemberId) ? { workspaceMemberId } : {}),
+ },
+ },
+ id: true,
+ },
+ });
+};
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-activities-enqueue.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-activities-enqueue.ts
index ff6c304fbfa..18bf0663cee 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-activities-enqueue.ts
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-activities-enqueue.ts
@@ -1,14 +1,38 @@
import { defineLogicFunction } from 'twenty-sdk/define';
+import { isDefined } from 'twenty-sdk/utils';
import { TEAMS_ACTIVITIES_ENQUEUE_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';
+import { TEAMS_ASSISTANT_AGENT_BUDGET_SECONDS } from 'src/features/chat/logic-functions/constants/teams-assistant-agent-budget-seconds';
import { TEAMS_ASSISTANT_REQUEST_TIMEOUT_SECONDS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-timeout-seconds';
+import { type TeamsActivitiesDispatchPayload } from 'src/features/chat/logic-functions/types/teams-activities-dispatch-payload.type';
+import { type TeamsActivitiesEnqueueResult } from 'src/features/chat/logic-functions/types/teams-activities-enqueue-result.type';
+import { type TeamsAssistantAnswerResult } from 'src/features/chat/logic-functions/types/teams-assistant-answer-result.type';
+import { answerTeamsAssistantRequest } from 'src/features/chat/logic-functions/utils/answer-teams-assistant-request';
import { enqueueTeamsAssistantRequest } from 'src/features/chat/logic-functions/utils/enqueue-teams-assistant-request';
+export const teamsActivitiesEnqueueHandler = async (
+ payload: TeamsActivitiesDispatchPayload,
+): Promise<TeamsActivitiesEnqueueResult | TeamsAssistantAnswerResult> => {
+ const agentDeadlineAtMs =
+ Date.now() + TEAMS_ASSISTANT_AGENT_BUDGET_SECONDS * 1000;
+
+ const enqueueResult = await enqueueTeamsAssistantRequest(payload);
+
+ if (!isDefined(enqueueResult.request)) {
+ return enqueueResult;
+ }
+
+ return await answerTeamsAssistantRequest({
+ request: enqueueResult.request,
+ agentDeadlineAtMs,
+ });
+};
+
export default defineLogicFunction({
universalIdentifier: TEAMS_ACTIVITIES_ENQUEUE_UNIVERSAL_IDENTIFIER,
name: 'teams-activities-enqueue',
description:
- 'Receives a verified Microsoft Teams message activity from the activities route, in the workspace that claimed its tenant. When chat is enabled, records it as a pending Teams Assistant Request, once per conversation and activity id, and hands the request back for answering.',
+ 'Receives a verified Microsoft Teams message activity from the activities route, in the workspace that claimed its tenant. When chat is enabled, records it as a Teams Assistant Request, once per conversation and activity id, then answers it: matches the sender to a workspace member by email, runs the Teams Assistant agent as that member and posts the answer back to the conversation.',
timeoutSeconds: TEAMS_ASSISTANT_REQUEST_TIMEOUT_SECONDS,
- handler: enqueueTeamsAssistantRequest,
+ handler: teamsActivitiesEnqueueHandler,
});
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-answer-result.type.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-answer-result.type.ts
new file mode 100644
index 00000000000..ff99b3cc0be
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-answer-result.type.ts
@@ -0,0 +1,5 @@
+export type TeamsAssistantAnswerResult =
+ | { status: 'answered' }
+ | { status: 'declined'; reason: string }
+ | { status: 'skipped'; reason: string }
+ | { status: 'failed'; reason: string };
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-request-status.type.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-request-status.type.ts
new file mode 100644
index 00000000000..abdadba18b2
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-request-status.type.ts
@@ -0,0 +1,4 @@
+import { type TEAMS_ASSISTANT_REQUEST_STATUS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-status';
+
+export type TeamsAssistantRequestStatus =
+ (typeof TEAMS_ASSISTANT_REQUEST_STATUS)[keyof typeof TEAMS_ASSISTANT_REQUEST_STATUS];
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/answer-teams-assistant-request.test.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/answer-teams-assistant-request.test.ts
new file mode 100644
index 00000000000..b0dd6e19502
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/answer-teams-assistant-request.test.ts
@@ -0,0 +1,154 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TEAMS_ASSISTANT_FAILURE_TEXT } from 'src/features/chat/logic-functions/constants/teams-assistant-failure-text';
+import { TEAMS_ASSISTANT_REQUEST_STATUS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-status';
+import { TEAMS_ASSISTANT_UNMATCHED_SENDER_TEXT } from 'src/features/chat/logic-functions/constants/teams-assistant-unmatched-sender-text';
+import { answerTeamsAssistantRequest } from 'src/features/chat/logic-functions/utils/answer-teams-assistant-request';
+
+const {
+ claimMock,
+ updateMock,
+ resolveSenderMock,
+ runAgentMock,
+ sendActivityMock,
+} = vi.hoisted(() => ({
+ claimMock: vi.fn(),
+ updateMock: vi.fn(),
+ resolveSenderMock: vi.fn(),
+ runAgentMock: vi.fn(),
+ sendActivityMock: vi.fn(),
+}));
+
+vi.mock('twenty-client-sdk/core', () => ({
+ CoreApiClient: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock(
+ 'src/features/chat/logic-functions/data/claim-teams-assistant-request',
+ () => ({ claimTeamsAssistantRequest: claimMock }),
+);
+
+vi.mock(
+ 'src/features/chat/logic-functions/data/update-teams-assistant-request',
+ () => ({ updateTeamsAssistantRequest: updateMock }),
+);
+
+vi.mock(
+ 'src/features/chat/logic-functions/utils/get-teams-connector-access-token-or-throw',
+ () => ({
+ getTeamsConnectorAccessTokenOrThrow: vi.fn().mockResolvedValue('token'),
+ }),
+);
+
+vi.mock(
+ 'src/features/chat/logic-functions/utils/resolve-teams-sender-workspace-member-id',
+ () => ({ resolveTeamsSenderWorkspaceMemberId: resolveSenderMock }),
+);
+
+vi.mock(
+ 'src/features/chat/logic-functions/utils/run-teams-assistant-agent-or-throw',
+ () => ({ runTeamsAssistantAgentOrThrow: runAgentMock }),
+);
+
+vi.mock('src/features/chat/logic-functions/utils/send-teams-activity', () => ({
+ sendTeamsActivity: sendActivityMock,
+}));
+
+const REQUEST = {
+ id: 'request-1',
+ teamsActivityId: '1700000000000',
+ teamsConversationId: 'a:personal-conversation',
+ teamsConversationType: 'personal',
+ teamsServiceUrl: 'https://smba.trafficmanager.net/amer/',
+ teamsTenantId: 'tenant-id',
+ teamsUserId: '29:user-id',
+ teamsUserAadObjectId: 'aad-user-id',
+ requestText: 'how many open deals does Acme have?',
+};
+
+const answer = () =>
+ answerTeamsAssistantRequest({
+ request: REQUEST,
+ agentDeadlineAtMs: Date.now() + 60_000,
+ });
+
+const sentMessageTexts = () =>
+ sendActivityMock.mock.calls
+ .map(([{ activity }]) => activity)
+ .filter((activity) => activity.type === 'message')
+ .map((activity) => activity.text);
+
+describe('answerTeamsAssistantRequest', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ claimMock.mockResolvedValue(true);
+ updateMock.mockResolvedValue(undefined);
+ sendActivityMock.mockResolvedValue({ id: 'activity-1' });
+ resolveSenderMock.mockResolvedValue('workspace-member-1');
+ runAgentMock.mockResolvedValue('Acme has 3 open deals.');
+ });
+
+ it('should answer as the matched workspace member and mark the request done', async () => {
+ await expect(answer()).resolves.toEqual({ status: 'answered' });
+
+ expect(runAgentMock).toHaveBeenCalledTimes(1);
+ expect(runAgentMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ requestText: REQUEST.requestText,
+ workspaceMemberId: 'workspace-member-1',
+ }),
+ );
+ expect(sentMessageTexts()).toEqual(['Acme has 3 open deals.']);
+ expect(updateMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ id: REQUEST.id,
+ status: TEAMS_ASSISTANT_REQUEST_STATUS.DONE,
+ responseText: 'Acme has 3 open deals.',
+ }),
+ );
+ });
+
+ it('should not send a failure reply when only the status write fails after answering', async () => {
+ updateMock.mockImplementation(async ({ status }) => {
+ if (status === TEAMS_ASSISTANT_REQUEST_STATUS.DONE) {
+ throw new Error('Core API unavailable');
+ }
+ });
+
+ await expect(answer()).resolves.toEqual({ status: 'answered' });
+ expect(sentMessageTexts()).toEqual(['Acme has 3 open deals.']);
+ });
+
+ it('should not answer a request another execution already claimed', async () => {
+ claimMock.mockResolvedValue(false);
+
+ await expect(answer()).resolves.toMatchObject({ status: 'skipped' });
+ expect(sendActivityMock).not.toHaveBeenCalled();
+ });
+
+ it('should decline a sender that matches no workspace member without running the agent', async () => {
+ resolveSenderMock.mockResolvedValue(undefined);
+
+ await expect(answer()).resolves.toMatchObject({ status: 'declined' });
+ expect(runAgentMock).not.toHaveBeenCalled();
+ expect(sentMessageTexts()).toEqual([TEAMS_ASSISTANT_UNMATCHED_SENDER_TEXT]);
+ });
+
+ it('should reply with a generic message and record the error when the agent fails', async () => {
+ runAgentMock.mockRejectedValue(new Error('Agent run failed'));
+
+ await expect(answer()).resolves.toEqual({
+ status: 'failed',
+ reason: 'Agent run failed',
+ });
+ expect(sentMessageTexts()).toEqual([TEAMS_ASSISTANT_FAILURE_TEXT]);
+ expect(updateMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ status: TEAMS_ASSISTANT_REQUEST_STATUS.FAILED,
+ errorMessage: 'Agent run failed',
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/request-teams-connector.test.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/request-teams-connector.test.ts
index 681c882315f..8d49807ccc7 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/request-teams-connector.test.ts
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/request-teams-connector.test.ts
@@ -43,6 +43,7 @@ describe('requestTeamsConnector', () => {
{
method: 'DELETE',
headers: { authorization: `Bearer ${ACCESS_TOKEN}` },
+ signal: expect.any(AbortSignal),
},
);
});
@@ -63,6 +64,7 @@ describe('requestTeamsConnector', () => {
'content-type': 'application/json',
},
body: JSON.stringify({ type: 'message', text: 'Hello' }),
+ signal: expect.any(AbortSignal),
});
});
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/run-teams-assistant-agent-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/run-teams-assistant-agent-or-throw.test.ts
new file mode 100644
index 00000000000..c2b7d414f0e
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/__tests__/run-teams-assistant-agent-or-throw.test.ts
@@ -0,0 +1,117 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { runTeamsAssistantAgentOrThrow } from 'src/features/chat/logic-functions/utils/run-teams-assistant-agent-or-throw';
+
+const runAgentMock = vi.hoisted(() => vi.fn());
+
+vi.mock('twenty-sdk/logic-function', () => ({
+ runAgent: runAgentMock,
+}));
+
+const INPUT = {
+ requestText: 'how many open deals does Acme have?',
+ workspaceMemberId: 'workspace-member-1',
+};
+
+describe('runTeamsAssistantAgentOrThrow', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ runAgentMock.mockResolvedValue({
+ success: true,
+ result: { response: ' Acme has 3 open deals. ' },
+ error: null,
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ it('should run the agent as the member and return the trimmed answer', async () => {
+ await expect(
+ runTeamsAssistantAgentOrThrow({
+ ...INPUT,
+ deadlineAtMs: Date.now() + 60_000,
+ }),
+ ).resolves.toBe('Acme has 3 open deals.');
+
+ expect(runAgentMock).toHaveBeenCalledTimes(1);
+ expect(runAgentMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ runAsWorkspaceMemberId: INPUT.workspaceMemberId,
+ messages: [
+ expect.objectContaining({
+ role: 'user',
+ content: expect.stringContaining(INPUT.requestText),
+ }),
+ ],
+ }),
+ );
+ });
+
+ it('should not start the agent when the deadline has already passed', async () => {
+ await expect(
+ runTeamsAssistantAgentOrThrow({ ...INPUT, deadlineAtMs: Date.now() - 1 }),
+ ).rejects.toThrow('Teams deadline passed before the agent could start');
+
+ expect(runAgentMock).not.toHaveBeenCalled();
+ });
+
+ it('should give up at the deadline while the agent is still running', async () => {
+ let settleAgentRun: (value: unknown) => void = () => undefined;
+
+ runAgentMock.mockReturnValue(
+ new Promise((resolve) => {
+ settleAgentRun = resolve;
+ }),
+ );
+
+ const run = runTeamsAssistantAgentOrThrow({
+ ...INPUT,
+ deadlineAtMs: Date.now() + 1_000,
+ });
+ const expectation = expect(run).rejects.toThrow(
+ 'Agent did not answer before the Teams deadline',
+ );
+
+ await vi.advanceTimersByTimeAsync(1_000);
+ await expectation;
+
+ settleAgentRun({
+ success: true,
+ result: { response: 'late' },
+ error: null,
+ });
+ });
+
+ it('should throw the agent error when the run fails', async () => {
+ runAgentMock.mockResolvedValue({
+ success: false,
+ result: null,
+ error: 'Agent run failed',
+ });
+
+ await expect(
+ runTeamsAssistantAgentOrThrow({
+ ...INPUT,
+ deadlineAtMs: Date.now() + 60_000,
+ }),
+ ).rejects.toThrow('Agent run failed');
+ });
+
+ it('should throw when the agent returns no text', async () => {
+ runAgentMock.mockResolvedValue({
+ success: true,
+ result: { response: ' ' },
+ error: null,
+ });
+
+ await expect(
+ runTeamsAssistantAgentOrThrow({
+ ...INPUT,
+ deadlineAtMs: Date.now() + 60_000,
+ }),
+ ).rejects.toThrow('Agent returned an empty response');
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/answer-teams-assistant-request.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/answer-teams-assistant-request.ts
new file mode 100644
index 00000000000..3507fefbbab
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/answer-teams-assistant-request.ts
@@ -0,0 +1,122 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { TEAMS_ASSISTANT_FAILURE_TEXT } from 'src/features/chat/logic-functions/constants/teams-assistant-failure-text';
+import { TEAMS_ASSISTANT_REQUEST_STATUS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-status';
+import { TEAMS_ASSISTANT_UNMATCHED_SENDER_TEXT } from 'src/features/chat/logic-functions/constants/teams-assistant-unmatched-sender-text';
+import { claimTeamsAssistantRequest } from 'src/features/chat/logic-functions/data/claim-teams-assistant-request';
+import { updateTeamsAssistantRequest } from 'src/features/chat/logic-functions/data/update-teams-assistant-request';
+import { type TeamsActivity } from 'src/features/chat/logic-functions/types/teams-activity.type';
+import { type TeamsAssistantAnswerResult } from 'src/features/chat/logic-functions/types/teams-assistant-answer-result.type';
+import { type TeamsAssistantRequestRecord } from 'src/features/chat/logic-functions/types/teams-assistant-request-record.type';
+import { getTeamsConnectorAccessTokenOrThrow } from 'src/features/chat/logic-functions/utils/get-teams-connector-access-token-or-throw';
+import { resolveTeamsSenderWorkspaceMemberId } from 'src/features/chat/logic-functions/utils/resolve-teams-sender-workspace-member-id';
+import { runTeamsAssistantAgentOrThrow } from 'src/features/chat/logic-functions/utils/run-teams-assistant-agent-or-throw';
+import { sendTeamsActivity } from 'src/features/chat/logic-functions/utils/send-teams-activity';
+import { toErrorMessage } from 'src/utils/to-error-message';
+
+export const answerTeamsAssistantRequest = async ({
+ request,
+ agentDeadlineAtMs,
+}: {
+ request: TeamsAssistantRequestRecord;
+ agentDeadlineAtMs: number;
+}): Promise<TeamsAssistantAnswerResult> => {
+ const {
+ teamsServiceUrl,
+ teamsConversationId,
+ teamsUserId,
+ teamsTenantId,
+ requestText,
+ } = request;
+
+ if (
+ !isNonEmptyString(teamsServiceUrl) ||
+ !isNonEmptyString(teamsConversationId) ||
+ !isNonEmptyString(teamsUserId) ||
+ !isNonEmptyString(teamsTenantId) ||
+ !isNonEmptyString(requestText)
+ ) {
+ return { status: 'skipped', reason: 'Request record is missing fields' };
+ }
+
+ const client = new CoreApiClient();
+
+ if (!(await claimTeamsAssistantRequest({ client, id: request.id }))) {
+ return { status: 'skipped', reason: 'Request is already being processed' };
+ }
+
+ const sendActivity = async (activity: TeamsActivity) =>
+ sendTeamsActivity({
+ serviceUrl: teamsServiceUrl,
+ conversationId: teamsConversationId,
+ accessToken: await getTeamsConnectorAccessTokenOrThrow(),
+ activity,
+ });
+
+ try {
+ await sendActivity({ type: 'typing' }).catch(() => undefined);
+
+ const workspaceMemberId = await resolveTeamsSenderWorkspaceMemberId({
+ client,
+ serviceUrl: teamsServiceUrl,
+ conversationId: teamsConversationId,
+ teamsUserId,
+ teamsTenantId,
+ accessToken: await getTeamsConnectorAccessTokenOrThrow(),
+ });
+
+ if (!isDefined(workspaceMemberId)) {
+ await sendActivity({
+ type: 'message',
+ text: TEAMS_ASSISTANT_UNMATCHED_SENDER_TEXT,
+ });
+ await updateTeamsAssistantRequest({
+ client,
+ id: request.id,
+ status: TEAMS_ASSISTANT_REQUEST_STATUS.DONE,
+ responseText: TEAMS_ASSISTANT_UNMATCHED_SENDER_TEXT,
+ }).catch(() => undefined);
+
+ return { status: 'declined', reason: 'Sender is not a workspace member' };
+ }
+
+ await updateTeamsAssistantRequest({
+ client,
+ id: request.id,
+ workspaceMemberId,
+ });
+
+ const responseText = await runTeamsAssistantAgentOrThrow({
+ requestText,
+ workspaceMemberId,
+ deadlineAtMs: agentDeadlineAtMs,
+ });
+
+ await sendActivity({ type: 'message', text: responseText });
+ await updateTeamsAssistantRequest({
+ client,
+ id: request.id,
+ status: TEAMS_ASSISTANT_REQUEST_STATUS.DONE,
+ responseText,
+ }).catch(() => undefined);
+
+ return { status: 'answered' };
+ } catch (error) {
+ const errorMessage = toErrorMessage(error);
+
+ await sendActivity({
+ type: 'message',
+ text: TEAMS_ASSISTANT_FAILURE_TEXT,
+ }).catch(() => undefined);
+ await updateTeamsAssistantRequest({
+ client,
+ id: request.id,
+ status: TEAMS_ASSISTANT_REQUEST_STATUS.FAILED,
+ errorMessage,
+ }).catch(() => undefined);
+
+ return { status: 'failed', reason: errorMessage };
+ }
+};
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/get-teams-connector-access-token-or-throw.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/get-teams-connector-access-token-or-throw.ts
new file mode 100644
index 00000000000..62374422614
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/get-teams-connector-access-token-or-throw.ts
@@ -0,0 +1,13 @@
+import { getTeamsBotCredentials } from 'src/features/chat/logic-functions/utils/get-teams-bot-credentials';
+import { getTeamsConnectorToken } from 'src/features/chat/logic-functions/utils/get-teams-connector-token';
+
+export const getTeamsConnectorAccessTokenOrThrow =
+ async (): Promise<string> => {
+ const credentialsResult = getTeamsBotCredentials();
+
+ if (!credentialsResult.success) {
+ throw new Error(credentialsResult.error);
+ }
+
+ return await getTeamsConnectorToken(credentialsResult.credentials);
+ };
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/request-teams-connector.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/request-teams-connector.ts
index 5ddf3434727..324dfd5d5cc 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/request-teams-connector.ts
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/request-teams-connector.ts
@@ -1,6 +1,7 @@
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-sdk/utils';
+import { TEAMS_CONNECTOR_REQUEST_TIMEOUT_MS } from 'src/features/chat/logic-functions/constants/teams-connector-request-timeout-ms';
import { type TeamsActivity } from 'src/features/chat/logic-functions/types/teams-activity.type';
import { isTeamsConnectorServiceUrl } from 'src/features/chat/logic-functions/utils/is-teams-connector-service-url';
import { normalizeTeamsServiceUrl } from 'src/features/chat/logic-functions/utils/normalize-teams-service-url';
@@ -33,6 +34,7 @@ export const requestTeamsConnector = async ({
...(isDefined(body) ? { 'content-type': 'application/json' } : {}),
},
...(isDefined(body) ? { body: JSON.stringify(body) } : {}),
+ signal: AbortSignal.timeout(TEAMS_CONNECTOR_REQUEST_TIMEOUT_MS),
});
const responseBody = await response.text();
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/run-teams-assistant-agent-or-throw.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/run-teams-assistant-agent-or-throw.ts
new file mode 100644
index 00000000000..10083080bb1
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/run-teams-assistant-agent-or-throw.ts
@@ -0,0 +1,63 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { runAgent } from 'twenty-sdk/logic-function';
+
+import { TEAMS_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';
+
+const hasResponseText = (result: object): result is { response: string } =>
+ 'response' in result && typeof result.response === 'string';
+
+export const runTeamsAssistantAgentOrThrow = async ({
+ requestText,
+ workspaceMemberId,
+ deadlineAtMs,
+}: {
+ requestText: string;
+ workspaceMemberId: string;
+ deadlineAtMs: number;
+}): Promise<string> => {
+ if (deadlineAtMs <= Date.now()) {
+ throw new Error('Teams deadline passed before the agent could start');
+ }
+
+ let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
+
+ const deadline = new Promise<never>((_, reject) => {
+ deadlineTimer = setTimeout(
+ () => reject(new Error('Agent did not answer before the Teams deadline')),
+ Math.max(deadlineAtMs - Date.now(), 0),
+ );
+ });
+
+ try {
+ // TODO(@abdulrahmancodes): send `input` instead of the deprecated `messages` once the app builds against a twenty-sdk that ships it
+ const agentResult = await Promise.race([
+ runAgent({
+ agentUniversalIdentifier: TEAMS_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER,
+ runAsWorkspaceMemberId: workspaceMemberId,
+ messages: [
+ {
+ role: 'user',
+ content: `You are acting as workspace member ${workspaceMemberId}, with that member's own permissions. "Me", "my" and "mine" refer to that member.\n\nRequest from Teams:\n${requestText}`,
+ },
+ ],
+ }),
+ deadline,
+ ]);
+
+ if (!agentResult.success || agentResult.result === null) {
+ throw new Error(agentResult.error ?? 'Agent run failed');
+ }
+
+ const responseText = hasResponseText(agentResult.result)
+ ? agentResult.result.response.trim()
+ : '';
+
+ if (!isNonEmptyString(responseText)) {
+ throw new Error('Agent returned an empty response');
+ }
+
+ return responseText;
+ } finally {
+ clearTimeout(deadlineTimer);
+ }
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.ts
index 8a8beae41cb..41beedba8a5 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.ts
@@ -18,8 +18,8 @@ import { listMeetingTranscripts } from 'src/features/transcripts/logic-functions
import { listTeamsCalendarPage } from 'src/features/transcripts/logic-functions/utils/list-teams-calendar-page';
import { resolveTeamsCalendarNextPageUrlOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-teams-calendar-next-page-url-or-throw';
import { resolveTeamsMeetingWindowOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-teams-meeting-window-or-throw';
-import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
import { isFeatureEnabled } from 'src/utils/is-feature-enabled';
+import { toErrorMessage } from 'src/utils/to-error-message';
const teamsListOrganizerTranscriptsInputSchema: InputJsonSchema = {
type: 'object',
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts
index b60afd6c5cd..abe3348f156 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts
@@ -13,8 +13,8 @@ import { TEAMS_SYNC_TRANSCRIPT_UNIVERSAL_IDENTIFIER } from 'src/features/transcr
import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-functions/types/call-recording-sync-fields.type';
import { getTeamsConnectionForRequestOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw';
import { syncTeamsTranscriptToCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw';
-import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
import { isFeatureEnabled } from 'src/utils/is-feature-enabled';
+import { toErrorMessage } from 'src/utils/to-error-message';
const teamsSyncTranscriptInputSchema: InputJsonSchema = {
type: 'object',
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts
index 80b322ef02d..55c312604a3 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts
@@ -20,8 +20,8 @@ import { importTeamsTranscriptOrScheduleRetry } from 'src/features/transcripts/l
import { parseTeamsTranscriptResource } from 'src/features/transcripts/logic-functions/utils/parse-teams-transcript-resource';
import { parseTeamsTranscriptSubscriptionNotifications } from 'src/features/transcripts/logic-functions/utils/parse-teams-transcript-subscription-notifications';
import { renewTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription';
-import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
import { isFeatureEnabled } from 'src/utils/is-feature-enabled';
+import { toErrorMessage } from 'src/utils/to-error-message';
type TeamsTranscriptsWebhookResult =
| {
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw.ts
index 2233c38e450..5d2072968c8 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw.ts
@@ -6,7 +6,7 @@ import {
import { TEAMS_IMPORT_TRANSCRIPT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
import { TEAMS_TRANSCRIPT_IMPORT_JOB_RETRY_LIMIT } from 'src/features/transcripts/logic-functions/constants/teams-transcript-import-job-retry-limit';
import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';
-import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
+import { toErrorMessage } from 'src/utils/to-error-message';
export const enqueueTeamsTranscriptImportRetryOrThrow = async ({
connectedAccountId,
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry.ts
index 82e1fe87a5d..3af9ebc996a 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry.ts
@@ -10,7 +10,7 @@ import { GraphRequestError } from 'src/features/transcripts/logic-functions/type
import { type TeamsTranscriptImportOutcome } from 'src/features/transcripts/logic-functions/types/teams-transcript-import-outcome.type';
import { enqueueTeamsTranscriptImportRetryOrThrow } from 'src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw';
import { syncTeamsTranscriptToCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw';
-import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
+import { toErrorMessage } from 'src/utils/to-error-message';
type TeamsTranscriptSyncAttempt =
| { outcome: 'imported' | 'skipped-deleted' | 'failed' }
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription.ts
index 90247786384..501afb0ba51 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription.ts
@@ -5,7 +5,7 @@ import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic
import { buildTeamsTranscriptSubscriptionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key';
import { buildTeamsTranscriptsConnectionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcripts-connection-kv-key';
import { deleteTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/delete-teams-transcript-subscription';
-import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
+import { toErrorMessage } from 'src/utils/to-error-message';
export const unregisterTeamsTranscriptSubscription = async ({
connectedAccountId,
diff --git a/packages/twenty-apps/public/teams/src/roles/default-function.role.ts b/packages/twenty-apps/public/teams/src/roles/default-function.role.ts
index af657534cda..82b5aa32362 100644
--- a/packages/twenty-apps/public/teams/src/roles/default-function.role.ts
+++ b/packages/twenty-apps/public/teams/src/roles/default-function.role.ts
@@ -1,5 +1,6 @@
import {
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
+ SystemPermissionFlag,
defineApplicationRole,
} from 'twenty-sdk/define';
@@ -10,7 +11,7 @@ export default defineApplicationRole({
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
label: 'Twenty Microsoft Teams tools role',
description:
- 'Reads calendar events to match Teams meetings and writes imported transcripts to Call Recordings. Tracks assistant requests received from Teams and reads workspace members to match a Teams sender by email. Chat tools only forward requests to Microsoft Teams using the configured bot credentials.',
+ 'Reads calendar events to match Teams meetings and writes imported transcripts to Call Recordings. Tracks assistant requests received from Teams, reads workspace members to match a Teams sender by email, and runs the Teams Assistant agent as that member, with the permissions of that member. Chat tools only forward requests to Microsoft Teams using the configured bot credentials.',
canReadAllObjectRecords: false,
canUpdateAllObjectRecords: false,
canSoftDeleteAllObjectRecords: false,
@@ -55,5 +56,5 @@ export default defineApplicationRole({
},
],
fieldPermissions: [],
- permissionFlagUniversalIdentifiers: [],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-error-message.ts b/packages/twenty-apps/public/teams/src/utils/to-error-message.ts
similarity index 100%
rename from packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-error-message.ts
rename to packages/twenty-apps/public/teams/src/utils/to-error-message.ts