The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Give the Teams assistant the earlier turns of the conversation (#28833)
Abdul Rahman65a35e7e36b0
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-history-turn-limit.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-history-turn-limit.tsnew file mode 100644index 00000000000..bf3c3e161c4--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/constants/teams-assistant-history-turn-limit.ts@@ -0,0 +1 @@+export const TEAMS_ASSISTANT_HISTORY_TURN_LIMIT = 10;diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/__tests__/find-teams-assistant-history.test.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/__tests__/find-teams-assistant-history.test.tsnew file mode 100644index 00000000000..49734c7fa3c--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/__tests__/find-teams-assistant-history.test.ts@@ -0,0 +1,112 @@+import { 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 { findTeamsAssistantHistory } from 'src/features/chat/logic-functions/data/find-teams-assistant-history';++const buildClient = (+ nodes: {+ status: string;+ requestText?: string | null;+ responseText?: string | null;+ }[],+) => ({+ query: vi.fn().mockResolvedValue({+ teamsAssistantRequests: {+ edges: nodes.map(({ status, requestText, responseText }) => ({+ node: {+ status,+ requestText: { markdown: requestText },+ responseText: { markdown: responseText },+ },+ })),+ },+ }),+});++const INPUT = {+ teamsConversationId: 'a:personal-conversation',+ workspaceMemberId: 'workspace-member-1',+};++describe('findTeamsAssistantHistory', () => {+ it('should return the latest answered turns of the member in chronological order', async () => {+ const client = buildClient([+ {+ status: TEAMS_ASSISTANT_REQUEST_STATUS.DONE,+ requestText: 'and their open deals?',+ responseText: '**Acme** has 3 open deals.',+ },+ {+ status: TEAMS_ASSISTANT_REQUEST_STATUS.DONE,+ requestText: 'list my companies',+ responseText: '**Acme**',+ },+ ]);++ await expect(+ findTeamsAssistantHistory({ client, ...INPUT }),+ ).resolves.toEqual([+ { requestText: 'list my companies', responseText: '**Acme**' },+ {+ requestText: 'and their open deals?',+ responseText: '**Acme** has 3 open deals.',+ },+ ]);+ expect(client.query).toHaveBeenCalledWith({+ teamsAssistantRequests: expect.objectContaining({+ __args: expect.objectContaining({+ filter: {+ teamsConversationId: { eq: INPUT.teamsConversationId },+ workspaceMemberId: { eq: INPUT.workspaceMemberId },+ status: {+ in: [+ TEAMS_ASSISTANT_REQUEST_STATUS.DONE,+ TEAMS_ASSISTANT_REQUEST_STATUS.FAILED,+ ],+ },+ },+ orderBy: [{ createdAt: 'DescNullsLast' }],+ }),+ }),+ });+ });++ it('should replay a failed turn with the failure reply the member saw', async () => {+ const client = buildClient([+ {+ status: TEAMS_ASSISTANT_REQUEST_STATUS.FAILED,+ requestText: 'list my companies',+ responseText: null,+ },+ ]);++ await expect(+ findTeamsAssistantHistory({ client, ...INPUT }),+ ).resolves.toEqual([+ {+ requestText: 'list my companies',+ responseText: TEAMS_ASSISTANT_FAILURE_TEXT,+ },+ ]);+ });++ it('should skip turns missing either side of the exchange', async () => {+ const client = buildClient([+ {+ status: TEAMS_ASSISTANT_REQUEST_STATUS.DONE,+ requestText: 'hi',+ responseText: '',+ },+ {+ status: TEAMS_ASSISTANT_REQUEST_STATUS.DONE,+ requestText: null,+ responseText: 'Hi!',+ },+ ]);++ await expect(+ findTeamsAssistantHistory({ client, ...INPUT }),+ ).resolves.toEqual([]);+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/find-teams-assistant-history.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/find-teams-assistant-history.tsnew file mode 100644index 00000000000..3cd175992bd--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/data/find-teams-assistant-history.ts@@ -0,0 +1,59 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { TEAMS_ASSISTANT_FAILURE_TEXT } from 'src/features/chat/logic-functions/constants/teams-assistant-failure-text';+import { TEAMS_ASSISTANT_HISTORY_TURN_LIMIT } from 'src/features/chat/logic-functions/constants/teams-assistant-history-turn-limit';+import { TEAMS_ASSISTANT_REQUEST_STATUS } from 'src/features/chat/logic-functions/constants/teams-assistant-request-status';+import { type TeamsAssistantTurn } from 'src/features/chat/logic-functions/types/teams-assistant-turn.type';++export const findTeamsAssistantHistory = async ({+ client,+ teamsConversationId,+ workspaceMemberId,+}: {+ client: Pick<CoreApiClient, 'query'>;+ teamsConversationId: string;+ workspaceMemberId: string;+}): Promise<TeamsAssistantTurn[]> => {+ const queryResult = await client.query({+ teamsAssistantRequests: {+ __args: {+ filter: {+ teamsConversationId: { eq: teamsConversationId },+ workspaceMemberId: { eq: workspaceMemberId },+ status: {+ in: [+ TEAMS_ASSISTANT_REQUEST_STATUS.DONE,+ TEAMS_ASSISTANT_REQUEST_STATUS.FAILED,+ ],+ },+ },+ orderBy: [{ createdAt: 'DescNullsLast' }],+ first: TEAMS_ASSISTANT_HISTORY_TURN_LIMIT,+ },+ edges: {+ node: {+ status: true,+ requestText: { markdown: true },+ responseText: { markdown: true },+ },+ },+ },+ });++ const history: TeamsAssistantTurn[] = [];++ for (const { node } of queryResult.teamsAssistantRequests?.edges ?? []) {+ const requestText = node.requestText?.markdown;+ const responseText =+ node.status === TEAMS_ASSISTANT_REQUEST_STATUS.FAILED+ ? TEAMS_ASSISTANT_FAILURE_TEXT+ : node.responseText?.markdown;++ if (isNonEmptyString(requestText) && isNonEmptyString(responseText)) {+ history.unshift({ requestText, responseText });+ }+ }++ return history;+};diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-turn.type.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-turn.type.tsnew file mode 100644index 00000000000..6239d7fba1a--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/types/teams-assistant-turn.type.ts@@ -0,0 +1,4 @@+export type TeamsAssistantTurn = {+ requestText: string;+ responseText: string;+};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.tsindex b0dd6e19502..d7cfa26908c 100644--- 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@@ -11,12 +11,14 @@ const {resolveSenderMock,runAgentMock,sendActivityMock,+ findHistoryMock,} = vi.hoisted(() => ({claimMock: vi.fn(),updateMock: vi.fn(),resolveSenderMock: vi.fn(),runAgentMock: vi.fn(),sendActivityMock: vi.fn(),+ findHistoryMock: vi.fn(),}));vi.mock('twenty-client-sdk/core', () => ({@@ -30,6 +32,11 @@ vi.mock(() => ({ claimTeamsAssistantRequest: claimMock }),);+vi.mock(+ 'src/features/chat/logic-functions/data/find-teams-assistant-history',+ () => ({ findTeamsAssistantHistory: findHistoryMock }),+);+vi.mock('src/features/chat/logic-functions/data/update-teams-assistant-request',() => ({ updateTeamsAssistantRequest: updateMock }),@@ -88,6 +95,7 @@ describe('answerTeamsAssistantRequest', () => {sendActivityMock.mockResolvedValue({ id: 'activity-1' });resolveSenderMock.mockResolvedValue('workspace-member-1');runAgentMock.mockResolvedValue('Acme has 3 open deals.');+ findHistoryMock.mockResolvedValue([]);});it('should answer as the matched workspace member and mark the request done', async () => {@@ -110,6 +118,38 @@ describe('answerTeamsAssistantRequest', () => {);});+ it('should pass the earlier turns of the sender in this conversation to the agent', async () => {+ const history = [{ requestText: 'hi', responseText: 'Hi!' }];+ findHistoryMock.mockResolvedValue(history);++ await answer();++ expect(findHistoryMock).toHaveBeenCalledWith(+ expect.objectContaining({+ teamsConversationId: REQUEST.teamsConversationId,+ workspaceMemberId: 'workspace-member-1',+ }),+ );+ expect(runAgentMock).toHaveBeenCalledWith(+ expect.objectContaining({ history }),+ );+ });++ it('should still answer without history when it cannot be loaded', async () => {+ const warnSpy = vi+ .spyOn(console, 'warn')+ .mockImplementation(() => undefined);+ findHistoryMock.mockRejectedValue(new Error('Core API unavailable'));++ await expect(answer()).resolves.toEqual({ status: 'answered' });+ expect(runAgentMock).toHaveBeenCalledWith(+ expect.objectContaining({ history: [] }),+ );+ expect(warnSpy).toHaveBeenCalledTimes(1);++ warnSpy.mockRestore();+ });+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) {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.tsindex c2b7d414f0e..0f072b5a9c9 100644--- 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@@ -11,6 +11,7 @@ vi.mock('twenty-sdk/logic-function', () => ({const INPUT = {requestText: 'how many open deals does Acme have?',workspaceMemberId: 'workspace-member-1',+ history: [],};describe('runTeamsAssistantAgentOrThrow', () => {@@ -50,6 +51,23 @@ describe('runTeamsAssistantAgentOrThrow', () => {);});+ it('should replay earlier turns of the conversation before the request', async () => {+ await runTeamsAssistantAgentOrThrow({+ ...INPUT,+ history: [{ requestText: 'list my companies', responseText: '**Acme**' }],+ deadlineAtMs: Date.now() + 60_000,+ });++ expect(runAgentMock.mock.calls[0][0].messages).toEqual([+ { role: 'user', content: 'list my companies' },+ { role: 'assistant', content: '**Acme**' },+ 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 }),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.tsindex 3507fefbbab..2bfc95476ab 100644--- 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@@ -6,6 +6,7 @@ import { TEAMS_ASSISTANT_FAILURE_TEXT } from 'src/features/chat/logic-functions/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 { findTeamsAssistantHistory } from 'src/features/chat/logic-functions/data/find-teams-assistant-history';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';@@ -88,8 +89,22 @@ export const answerTeamsAssistantRequest = async ({workspaceMemberId,});+ const history = await findTeamsAssistantHistory({+ client,+ teamsConversationId,+ workspaceMemberId,+ }).catch((error: unknown) => {+ console.warn(+ `[teams] could not load the history of ${teamsConversationId}`,+ error,+ );++ return [];+ });+const responseText = await runTeamsAssistantAgentOrThrow({requestText,+ history,workspaceMemberId,deadlineAtMs: agentDeadlineAtMs,});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.tsindex 10083080bb1..c294600eb5b 100644--- 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@@ -1,17 +1,24 @@import { isNonEmptyString } from '@sniptt/guards';-import { runAgent } from 'twenty-sdk/logic-function';+import { type RunAgentInput, runAgent } from 'twenty-sdk/logic-function';import { TEAMS_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';+import { type TeamsAssistantTurn } from 'src/features/chat/logic-functions/types/teams-assistant-turn.type';++type TeamsAssistantAgentMessage = NonNullable<+ RunAgentInput['messages']+>[number];const hasResponseText = (result: object): result is { response: string } =>'response' in result && typeof result.response === 'string';export const runTeamsAssistantAgentOrThrow = async ({requestText,+ history,workspaceMemberId,deadlineAtMs,}: {requestText: string;+ history: TeamsAssistantTurn[];workspaceMemberId: string;deadlineAtMs: number;}): Promise<string> => {@@ -35,6 +42,10 @@ export const runTeamsAssistantAgentOrThrow = async ({agentUniversalIdentifier: TEAMS_ASSISTANT_AGENT_UNIVERSAL_IDENTIFIER,runAsWorkspaceMemberId: workspaceMemberId,messages: [+ ...history.flatMap((turn): TeamsAssistantAgentMessage[] => [+ { role: 'user', content: turn.requestText },+ { role: 'assistant', content: turn.responseText },+ ]),{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}`,