Skip to content

The open alternative to Salesforce, designed for AI.

feat(ai): ask one question per call and step through every pending request (#27206)

Félix Malfaitcdd460a8ca32
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index a620e20a1f2..a017f3e6be4 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -84,9 +84,9 @@ When adding AI behavior:
- `workspaceMemberId` is the member who receives it, and `text` is the message, in markdown.
- `threadKey` picks the conversation per app and member: a new key starts one titled `title`, a known key adds to it. `idempotencyKey` identifies the message in it, so sending again with the same keys writes nothing and retries never duplicate it.
-- `toolCall` (optional) ends the message on `ask_questions`, `request_form` or `propose_tool_call`, which pause the conversation until the member answers, or on one of the app's own tools by `logicFunctionUniversalIdentifier`, rendered by its front component without pausing.
+- `toolCall` (optional) ends the message on `ask_question` (one multiple-choice question), `request_form` or `propose_tool_call`, which pause the conversation until the member answers, or on one of the app's own tools by `logicFunctionUniversalIdentifier`, rendered by its front component without pausing.
- `propose_tool_call` takes `toolName`, `arguments` and a one-sentence `summary`. The tool must be one the app's default role could run itself, such as `create_one_person` or `update_one_opportunity` (with `id`), or `send_email` / `draft_email` (`recipients`, `subject` and an HTML `body`), which need no permission of the app. The member reviews the call, edits it if they want, and the approved call runs with their own access.
-- Only one call the member answers (`ask_questions`, `request_form`, `propose_tool_call`) can wait at a time; another fails with `THREAD_AWAITING_ANSWER` until they answer. Plain messages and app tool calls are still accepted.
+- Only one call the member answers (`ask_question`, `request_form`, `propose_tool_call`) can wait at a time; another fails with `THREAD_AWAITING_ANSWER` until they answer. Plain messages and app tool calls are still accepted.
- A conversation the member deleted is not recreated.
- The app's default role needs `SystemPermissionFlag.AI`, and the member needs the AI permission.
- It always uses the app's access and ignores `runAs`.
diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
index c7bcc9a1316..19ca27b574d 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
@@ -269,15 +269,11 @@ const { threadId } = await sendInboxMessage({
title: 'Your first call recording is ready',
text: 'Your first call was recorded: **Weekly sync**.',
toolCall: {
- toolName: 'ask_questions',
+ toolName: 'ask_question',
input: {
- questions: [
- {
- header: 'Share',
- question: 'Do you want to share it with the other attendees?',
- options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
- },
- ],
+ header: 'Share',
+ question: 'Do you want to share it with the other attendees?',
+ options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
},
},
});
@@ -291,8 +287,8 @@ Key points:
again with the same keys writes nothing new, so retries and concurrent runs
never duplicate a message.
- `toolCall` (optional) ends the message on one of:
- - a call the member answers, which pauses the conversation: `ask_questions`
- (1 to 4 multiple-choice questions), `request_form` (fields to fill in) or
+ - a call the member answers, which pauses the conversation: `ask_question`
+ (one multiple-choice question), `request_form` (fields to fill in) or
`propose_tool_call` (a call to approve). Its `input` takes the `toolName`,
the `arguments` you would call the tool with and a one-sentence `summary`.
The tool must be one your app's default role could run itself, such as
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx
index 1ed6eb2d787..32c5e420899 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx
@@ -11,6 +11,7 @@ type AiChatAskCardProps = {
export const AiChatAskCard = ({ pendingToolCall }: AiChatAskCardProps) => {
switch (pendingToolCall.kind) {
+ case 'question':
case 'questions':
return <AiChatQuestionCard pendingQuestion={pendingToolCall} />;
case 'form':
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
index d1aef3db721..3db988fb06e 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
@@ -17,6 +17,7 @@ import { isHiddenCompleteWorkspaceSetupToolPart } from '@/ai/utils/isHiddenCompl
import { styled } from '@linaria/react';
import { getToolName, isToolUIPart } from 'ai';
import {
+ ASK_QUESTION_TOOL_NAME,
ASK_QUESTIONS_TOOL_NAME,
type ExtendedUIMessagePart,
isSucceededCompleteWorkspaceSetupToolPart,
@@ -61,7 +62,10 @@ const MessagePartRenderer = ({
);
default:
if (isToolUIPart(part)) {
- if (getToolName(part) === ASK_QUESTIONS_TOOL_NAME) {
+ if (
+ getToolName(part) === ASK_QUESTION_TOOL_NAME ||
+ getToolName(part) === ASK_QUESTIONS_TOOL_NAME
+ ) {
return (
<AiChatQuestionStatusRenderer
toolPart={part}
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
index 88c59be220c..31c499df7eb 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
@@ -1,11 +1,14 @@
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { type ReactNode } from 'react';
-import { isDefined } from 'twenty-shared/utils';
+import { type ReactNode, useState } from 'react';
+import { LightIconButton } from 'twenty-ui/components';
+import { IconChevronLeft, IconChevronRight } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme';
import { AiChatAskCard } from '@/ai/components/AiChatAskCard';
import { useAgentChatPendingToolCalls } from '@/ai/hooks/useAgentChatPendingToolCalls';
+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
const StyledGate = styled.div`
display: flex;
@@ -14,41 +17,111 @@ const StyledGate = styled.div`
width: 100%;
`;
-const StyledWaitingCount = styled.span`
+const StyledStepper = styled.div`
+ align-items: center;
+ display: flex;
+ gap: ${themeCssVariables.spacing[1]};
+ padding: 0 ${themeCssVariables.spacing[1]};
+`;
+
+const StyledStepperLabel = styled.span`
color: ${themeCssVariables.font.color.light};
+ flex: 1;
font-size: ${themeCssVariables.font.size.sm};
- padding: 0 ${themeCssVariables.spacing[1]};
`;
type AiChatPendingAskGateProps = {
children: ReactNode;
};
-// The agent resumes once every paused call is answered, so cards come one at a time, oldest first.
+type RequestSelection = {
+ threadId: string | null;
+ toolCallId: string | null;
+ index: number;
+ // the requests pending when one was picked, to tell a later batch from this one
+ batchToolCallIds: string[];
+};
+
+// The agent resumes once every paused call is answered. Each call is answered on its own, in any
+// order, and every card stays mounted so what is typed in one survives going to another.
export const AiChatPendingAskGate = ({
children,
}: AiChatPendingAskGateProps) => {
const { t } = useLingui();
const pendingToolCalls = useAgentChatPendingToolCalls();
- const [currentToolCall] = pendingToolCalls;
+ const agentChatDisplayedThread = useAtomStateValue(
+ agentChatDisplayedThreadState,
+ );
+ const [selection, setSelection] = useState<RequestSelection>({
+ threadId: null,
+ toolCallId: null,
+ index: 0,
+ batchToolCallIds: [],
+ });
- if (!isDefined(currentToolCall)) {
+ if (pendingToolCalls.length === 0) {
return children;
}
- const waitingCount = pendingToolCalls.length;
+ const requestCount = pendingToolCalls.length;
+ const selectedIndex = pendingToolCalls.findIndex(
+ (pendingToolCall) => pendingToolCall.toolCallId === selection.toolCallId,
+ );
+ // an answered request leaves the list, so the one taking its place is shown
+ // a selection made in another conversation or for an earlier batch does not carry over, so
+ // each new set of requests opens on its oldest one
+ const isSameBatch =
+ selection.threadId === agentChatDisplayedThread &&
+ pendingToolCalls.some((pendingToolCall) =>
+ selection.batchToolCallIds.includes(pendingToolCall.toolCallId),
+ );
+ const previousIndex = isSameBatch ? selection.index : 0;
+ const currentIndex =
+ selectedIndex >= 0
+ ? selectedIndex
+ : Math.min(previousIndex, requestCount - 1);
+ const requestNumber = currentIndex + 1;
+
+ const selectRequest = (index: number) =>
+ setSelection({
+ threadId: agentChatDisplayedThread,
+ toolCallId: pendingToolCalls[index].toolCallId,
+ index,
+ batchToolCallIds: pendingToolCalls.map(
+ (pendingToolCall) => pendingToolCall.toolCallId,
+ ),
+ });
return (
<StyledGate>
- {waitingCount > 1 && (
- <StyledWaitingCount>
- {t`${waitingCount} requests are waiting on you`}
- </StyledWaitingCount>
+ {requestCount > 1 && (
+ <StyledStepper>
+ <StyledStepperLabel>
+ {t`Request ${requestNumber} of ${requestCount}`}
+ </StyledStepperLabel>
+ <LightIconButton
+ size="sm"
+ disabled={currentIndex === 0}
+ onClick={() => selectRequest(currentIndex - 1)}
+ aria-label={t`Previous request`}
+ >
+ <IconChevronLeft />
+ </LightIconButton>
+ <LightIconButton
+ size="sm"
+ disabled={currentIndex === requestCount - 1}
+ onClick={() => selectRequest(currentIndex + 1)}
+ aria-label={t`Next request`}
+ >
+ <IconChevronRight />
+ </LightIconButton>
+ </StyledStepper>
)}
- <AiChatAskCard
- key={currentToolCall.toolCallId}
- pendingToolCall={currentToolCall}
- />
+ {pendingToolCalls.map((pendingToolCall, index) => (
+ <div key={pendingToolCall.toolCallId} hidden={index !== currentIndex}>
+ <AiChatAskCard pendingToolCall={pendingToolCall} />
+ </div>
+ ))}
</StyledGate>
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx
index 92a921ce7eb..9de0bc437cf 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx
@@ -4,6 +4,7 @@ import { type KeyboardEvent, useState } from 'react';
import {
type AskQuestionAnswer,
type AskQuestionItem,
+ type AskQuestionToolResult,
type AskQuestionsToolResult,
} from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
@@ -178,7 +179,11 @@ export const AiChatQuestionCard = ({
}: AiChatQuestionCardProps) => {
const { t } = useLingui();
const theme = useTheme();
- const { toolCallId, questions } = pendingQuestion;
+ const { toolCallId } = pendingQuestion;
+ const questions =
+ pendingQuestion.kind === 'question'
+ ? [pendingQuestion.question]
+ : pendingQuestion.questions;
const [currentIndex, setCurrentIndex] = useState(0);
const [selectedByQuestion, setSelectedByQuestion] = useState<
@@ -221,18 +226,34 @@ export const AiChatQuestionCard = ({
setIsSubmitting(true);
- const isAnswered = await answerAgentChatToolCall({
- toolCallId,
- response: { answers },
- optimisticToolOutput: {
- success: true,
- result: {
- questions,
- status: 'answered',
- answers,
- } satisfies AskQuestionsToolResult,
- },
- });
+ const [{ selectedOptionIndices, freeText }] = answers;
+ const isAnswered = await answerAgentChatToolCall(
+ pendingQuestion.kind === 'question'
+ ? {
+ toolCallId,
+ response: { selectedOptionIndices, freeText },
+ optimisticToolOutput: {
+ success: true,
+ result: {
+ question: pendingQuestion.question,
+ status: 'answered',
+ answer: { selectedOptionIndices, freeText },
+ } satisfies AskQuestionToolResult,
+ },
+ }
+ : {
+ toolCallId,
+ response: { answers },
+ optimisticToolOutput: {
+ success: true,
+ result: {
+ questions,
+ status: 'answered',
+ answers,
+ } satisfies AskQuestionsToolResult,
+ },
+ },
+ );
// The card goes once its call is closed, so it stays disabled until then.
if (!isAnswered) {
@@ -469,7 +490,7 @@ export const AiChatQuestionCard = ({
<StyledComposerSection>
<AiChatComposerActionsRow
- modelTierDropdownId="ai-chat-question-model-tier-dropdown"
+ modelTierDropdownId={`ai-chat-question-model-tier-dropdown-${toolCallId}`}
sendButton={
<IconButton
variant="solid"
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx
index 59531a985e4..225232a4caa 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx
@@ -2,11 +2,15 @@ import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { isNonEmptyString } from '@sniptt/guards';
import { type DynamicToolUIPart, type ToolUIPart } from 'ai';
-import { type AskQuestionsToolResult } from 'twenty-shared/ai';
+import {
+ type AskQuestionToolResult,
+ type AskQuestionsToolResult,
+} from 'twenty-shared/ai';
import { IconHelpCircle } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme';
import { AiChatAskStatusRow } from '@/ai/components/AiChatAskStatusRow';
+import { getAskedQuestionEntries } from '@/ai/utils/getAskedQuestionEntries';
import {
StyledAiChatAskStatusDetail,
StyledAiChatAskStatusMessage,
@@ -45,30 +49,44 @@ export const AiChatQuestionStatusRenderer = ({
}) => {
const { t } = useLingui();
- const result = (toolPart.output as { result?: AskQuestionsToolResult } | null)
- ?.result;
- const questions = result?.questions ?? [];
+ const result = (
+ toolPart.output as {
+ result?: AskQuestionToolResult | AskQuestionsToolResult;
+ } | null
+ )?.result;
const status = result?.status ?? 'pending';
+ const entries = getAskedQuestionEntries(result);
if (status === 'pending') {
return (
<AiChatAskStatusRow
Icon={IconHelpCircle}
- message={t`Asking questions...`}
+ message={
+ entries.length === 1
+ ? entries[0].question.question
+ : t`Asking questions...`
+ }
isShimmering={isStreaming}
/>
);
}
- const answers = result?.answers ?? [];
+ if (status === 'skipped') {
+ return (
+ <AiChatAskStatusRow
+ Icon={IconHelpCircle}
+ message={
+ entries.length > 1 ? t`Questions skipped` : t`Question skipped`
+ }
+ isShimmering={false}
+ />
+ );
+ }
return (
<StyledAnswersCard>
<StyledAiChatAskStatusMessage>{t`Answers`}</StyledAiChatAskStatusMessage>
- {questions.map((question, index) => {
- const answer = answers.find(
- (candidate) => candidate.questionIndex === index,
- );
+ {entries.map(({ question, answer }, index) => {
const selectedLabels = (answer?.selectedOptionIndices ?? [])
.map((optionIndex) => question.options[optionIndex]?.label)
.filter(isNonEmptyString);
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx
index 3116309ab73..1713bae104e 100644
--- a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx
@@ -22,42 +22,42 @@ const StyledContainer = styled.div`
const INSTANCE_ID = 'agentChatQuestionCardStory';
-const singleQuestion: AgentChatPendingQuestion = {
- toolCallId: 'call-1',
- questions: [
+const EMAIL_TYPE_QUESTION = {
+ header: 'Email type',
+ question: 'What type of emails would you like to send?',
+ options: [
{
- header: 'Email type',
- question: 'What type of emails would you like to send?',
- options: [
- {
- label: 'A welcome email',
- description: 'A short, friendly note to introduce yourself.',
- isRecommended: true,
- },
- { label: 'A presentation of Twenty' },
- { label: 'An offer for a potential partnership' },
- ],
+ label: 'A welcome email',
+ description: 'A short, friendly note to introduce yourself.',
+ isRecommended: true,
},
+ { label: 'A presentation of Twenty' },
+ { label: 'An offer for a potential partnership' },
],
};
+const singleQuestion: AgentChatPendingQuestion = {
+ toolCallId: 'call-1',
+ kind: 'question',
+ question: EMAIL_TYPE_QUESTION,
+};
+
+const TONE_QUESTION = {
+ header: 'Tone',
+ question: 'Which tone should the email use?',
+ options: [{ label: 'Friendly', isRecommended: true }, { label: 'Formal' }],
+};
+
+// calls asked before ask_question took one question at a time
const multipleQuestions: AgentChatPendingQuestion = {
toolCallId: 'call-2',
- questions: [
- singleQuestion.questions[0],
- {
- header: 'Tone',
- question: 'Which tone should the email use?',
- options: [
- { label: 'Friendly', isRecommended: true },
- { label: 'Formal' },
- ],
- },
- ],
+ kind: 'questions',
+ questions: [EMAIL_TYPE_QUESTION, TONE_QUESTION],
};
const longQuestion: AgentChatPendingQuestion = {
toolCallId: 'call-3',
+ kind: 'questions',
questions: [
{
header: 'Improvement',
@@ -70,24 +70,23 @@ const longQuestion: AgentChatPendingQuestion = {
{ label: 'Fewer steps' },
],
},
- multipleQuestions.questions[1],
+ TONE_QUESTION,
],
};
const multiSelectQuestion: AgentChatPendingQuestion = {
toolCallId: 'call-4',
- questions: [
- {
- header: 'Channels',
- question: 'Which channels should the outreach campaign use?',
- allowMultiSelect: true,
- options: [
- { label: 'Email', isRecommended: true },
- { label: 'LinkedIn' },
- { label: 'Phone' },
- ],
- },
- ],
+ kind: 'question',
+ question: {
+ header: 'Channels',
+ question: 'Which channels should the outreach campaign use?',
+ allowMultiSelect: true,
+ options: [
+ { label: 'Email', isRecommended: true },
+ { label: 'LinkedIn' },
+ { label: 'Phone' },
+ ],
+ },
};
const StoreSeeder = ({ children }: { children: ReactNode }) => {
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx
index 20fd0d26dff..71156015e17 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx
@@ -1,6 +1,7 @@
import { i18n } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import {
type AskQuestionItem,
type ProposedToolCall,
@@ -11,6 +12,10 @@ import { AiChatPendingAskGate } from '@/ai/components/AiChatPendingAskGate';
import { type AgentChatPendingQuestion } from '@/ai/types/AgentChatPendingQuestion';
const useAgentChatPendingToolCalls = jest.fn();
+let displayedThreadId = 'thread-1';
+jest.mock('@/ui/utilities/state/jotai/hooks/useAtomStateValue', () => ({
+ useAtomStateValue: () => displayedThreadId,
+}));
jest.mock('@/ai/hooks/useAgentChatPendingToolCalls', () => ({
useAgentChatPendingToolCalls: () => useAgentChatPendingToolCalls(),
}));
@@ -21,7 +26,9 @@ jest.mock('@/ai/components/AiChatQuestionCard', () => ({
pendingQuestion: AgentChatPendingQuestion;
}) => (
<div role="group" aria-label="Questions">
- {pendingQuestion.questions[0].question}
+ {pendingQuestion.kind === 'question'
+ ? pendingQuestion.question.question
+ : pendingQuestion.questions[0].question}
</div>
),
}));
@@ -44,13 +51,11 @@ jest.mock('@/ai/components/AiChatToolCallApprovalCard', () => ({
),
}));
-const QUESTIONS: AskQuestionItem[] = [
- {
- header: 'Plan',
- question: 'Which plan?',
- options: [{ label: 'Pro' }, { label: 'Team' }],
- },
-];
+const QUESTION: AskQuestionItem = {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+};
const EMAIL_APPROVAL = {
toolCallId: 'call-2',
@@ -74,9 +79,13 @@ const renderGate = () =>
);
describe('AiChatPendingAskGate', () => {
- it('shows the questions the thread waits on in place of the composer', () => {
+ afterEach(() => {
+ displayedThreadId = 'thread-1';
+ });
+
+ it('shows the question the thread waits on in place of the composer', () => {
useAgentChatPendingToolCalls.mockReturnValue([
- { toolCallId: 'call-1', kind: 'questions', questions: QUESTIONS },
+ { toolCallId: 'call-1', kind: 'question', question: QUESTION },
]);
renderGate();
@@ -115,24 +124,118 @@ describe('AiChatPendingAskGate', () => {
expect(screen.queryByRole('textbox', { name: 'Message' })).toBeNull();
});
- it('shows the oldest of several requests first and says how many wait', () => {
+ it('steps through several requests, starting with the oldest', async () => {
useAgentChatPendingToolCalls.mockReturnValue([
EMAIL_APPROVAL,
- { toolCallId: 'call-3', kind: 'questions', questions: QUESTIONS },
+ { toolCallId: 'call-3', kind: 'question', question: QUESTION },
]);
renderGate();
+ expect(screen.getByText('Request 1 of 2')).toBeInTheDocument();
expect(
screen.getByRole('group', { name: 'Tool call approval' }),
- ).toHaveTextContent('Your renewal');
+ ).toBeVisible();
expect(screen.queryByRole('group', { name: 'Questions' })).toBeNull();
expect(
- screen.getByText('2 requests are waiting on you'),
- ).toBeInTheDocument();
+ screen.getByRole('button', { name: 'Previous request' }),
+ ).toBeDisabled();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Next request' }));
+
+ expect(screen.getByText('Request 2 of 2')).toBeInTheDocument();
+ expect(screen.getByRole('group', { name: 'Questions' })).toBeVisible();
+ expect(
+ screen.queryByRole('group', { name: 'Tool call approval' }),
+ ).toBeNull();
expect(screen.queryByRole('textbox', { name: 'Message' })).toBeNull();
});
+ it('shows the request that took the place of an answered one', async () => {
+ const formRequest = {
+ toolCallId: 'call-4',
+ kind: 'form',
+ fields: [{ name: 'closeDate', label: 'Close date', type: 'DATE' }],
+ };
+
+ useAgentChatPendingToolCalls.mockReturnValue([
+ EMAIL_APPROVAL,
+ { toolCallId: 'call-3', kind: 'question', question: QUESTION },
+ formRequest,
+ ]);
+
+ const { rerender } = renderGate();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Next request' }));
+ useAgentChatPendingToolCalls.mockReturnValue([EMAIL_APPROVAL, formRequest]);
+ rerender(
+ <I18nProvider i18n={i18n}>
+ <AiChatPendingAskGate>
+ <textarea aria-label="Message" />
+ </AiChatPendingAskGate>
+ </I18nProvider>,
+ );
+
+ expect(screen.getByText('Request 2 of 2')).toBeInTheDocument();
+ expect(screen.getByRole('group', { name: 'Form' })).toBeVisible();
+ });
+
+ it('opens another conversation on its oldest request', async () => {
+ useAgentChatPendingToolCalls.mockReturnValue([
+ EMAIL_APPROVAL,
+ { toolCallId: 'call-3', kind: 'question', question: QUESTION },
+ ]);
+
+ const { rerender } = renderGate();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Next request' }));
+
+ displayedThreadId = 'thread-2';
+ useAgentChatPendingToolCalls.mockReturnValue([
+ { toolCallId: 'call-5', kind: 'question', question: QUESTION },
+ EMAIL_APPROVAL,
+ ]);
+ rerender(
+ <I18nProvider i18n={i18n}>
+ <AiChatPendingAskGate>
+ <textarea aria-label="Message" />
+ </AiChatPendingAskGate>
+ </I18nProvider>,
+ );
+
+ expect(screen.getByText('Request 1 of 2')).toBeInTheDocument();
+ expect(screen.getByRole('group', { name: 'Questions' })).toBeVisible();
+ });
+
+ it('opens a later batch of requests on its oldest one', async () => {
+ useAgentChatPendingToolCalls.mockReturnValue([
+ EMAIL_APPROVAL,
+ { toolCallId: 'call-3', kind: 'question', question: QUESTION },
+ ]);
+
+ const { rerender } = renderGate();
+ const rerenderGate = () =>
+ rerender(
+ <I18nProvider i18n={i18n}>
+ <AiChatPendingAskGate>
+ <textarea aria-label="Message" />
+ </AiChatPendingAskGate>
+ </I18nProvider>,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: 'Next request' }));
+ useAgentChatPendingToolCalls.mockReturnValue([]);
+ rerenderGate();
+ useAgentChatPendingToolCalls.mockReturnValue([
+ { toolCallId: 'call-6', kind: 'question', question: QUESTION },
+ { ...EMAIL_APPROVAL, toolCallId: 'call-7' },
+ ]);
+ rerenderGate();
+
+ expect(screen.getByText('Request 1 of 2')).toBeInTheDocument();
+ expect(screen.getByRole('group', { name: 'Questions' })).toBeVisible();
+ });
+
it('shows the composer once nothing is pending', () => {
useAgentChatPendingToolCalls.mockReturnValue([]);
diff --git a/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
index 014a5f88495..daf5f9e9c79 100644
--- a/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
+++ b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
@@ -1,10 +1,12 @@
import {
+ ASK_QUESTION_TOOL_NAME,
ASK_QUESTIONS_TOOL_NAME,
PROPOSE_TOOL_CALL_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
} from 'twenty-shared/ai';
export const PAUSING_TOOL_NAMES: ReadonlySet<string> = new Set([
+ ASK_QUESTION_TOOL_NAME,
ASK_QUESTIONS_TOOL_NAME,
PROPOSE_TOOL_CALL_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts b/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts
index 9d520112346..619e90f60f6 100644
--- a/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts
+++ b/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts
@@ -1,6 +1,7 @@
import { type AskQuestionItem } from 'twenty-shared/ai';
-export type AgentChatPendingQuestion = {
- toolCallId: string;
- questions: AskQuestionItem[];
-};
+export type AgentChatPendingQuestion = { toolCallId: string } & (
+ | { kind: 'question'; question: AskQuestionItem }
+ // calls asked before ask_question took one question at a time
+ | { kind: 'questions'; questions: AskQuestionItem[] }
+);
diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatPendingToolCall.ts b/packages/twenty-front/src/modules/ai/types/AgentChatPendingToolCall.ts
index e6d6b176abd..9dabed98951 100644
--- a/packages/twenty-front/src/modules/ai/types/AgentChatPendingToolCall.ts
+++ b/packages/twenty-front/src/modules/ai/types/AgentChatPendingToolCall.ts
@@ -1,11 +1,10 @@
-import {
- type AskQuestionItem,
- type ProposedToolCall,
- type RequestFormField,
-} from 'twenty-shared/ai';
+import { type ProposedToolCall, type RequestFormField } from 'twenty-shared/ai';
-export type AgentChatPendingToolCall = { toolCallId: string } & (
- | { kind: 'questions'; questions: AskQuestionItem[] }
- | { kind: 'form'; fields: RequestFormField[] }
- | { kind: 'toolCallApproval'; proposal: ProposedToolCall }
-);
+import { type AgentChatPendingQuestion } from '@/ai/types/AgentChatPendingQuestion';
+
+export type AgentChatPendingToolCall =
+ | AgentChatPendingQuestion
+ | ({ toolCallId: string } & (
+ | { kind: 'form'; fields: RequestFormField[] }
+ | { kind: 'toolCallApproval'; proposal: ProposedToolCall }
+ ));
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAskedQuestionEntries.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAskedQuestionEntries.test.ts
new file mode 100644
index 00000000000..594a24a9477
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAskedQuestionEntries.test.ts
@@ -0,0 +1,45 @@
+import { getAskedQuestionEntries } from '@/ai/utils/getAskedQuestionEntries';
+
+const PLAN = {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+};
+
+const SEATS = {
+ header: 'Seats',
+ question: 'How many seats?',
+ options: [{ label: '10' }, { label: '50' }],
+};
+
+describe('getAskedQuestionEntries', () => {
+ it('reads nothing while the call has no result yet', () => {
+ expect(getAskedQuestionEntries(undefined)).toEqual([]);
+ });
+
+ it('reads the answer of an ask_question call', () => {
+ expect(
+ getAskedQuestionEntries({
+ question: PLAN,
+ status: 'answered',
+ answer: { selectedOptionIndices: [1] },
+ }),
+ ).toEqual([{ question: PLAN, answer: { selectedOptionIndices: [1] } }]);
+ });
+
+ it('pairs each question of an older call with its answer', () => {
+ expect(
+ getAskedQuestionEntries({
+ questions: [PLAN, SEATS],
+ status: 'answered',
+ answers: [{ questionIndex: 1, selectedOptionIndices: [0] }],
+ }),
+ ).toEqual([
+ { question: PLAN, answer: undefined },
+ {
+ question: SEATS,
+ answer: { questionIndex: 1, selectedOptionIndices: [0] },
+ },
+ ]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/parsePendingToolCall.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/parsePendingToolCall.test.ts
index af6c263e448..13859e2130b 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/parsePendingToolCall.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/parsePendingToolCall.test.ts
@@ -4,6 +4,12 @@ import { parsePendingToolCall } from '@/ai/utils/parsePendingToolCall';
const QUESTIONS = [{ header: 'Plan', question: 'Which plan?', options: [] }];
+const QUESTION = {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+};
+
const FIELDS = [{ name: 'closeDate', label: 'Close date', type: 'DATE' }];
const toolPart = ({
@@ -26,7 +32,12 @@ const toolPart = ({
describe('parsePendingToolCall', () => {
it.each([
[
- 'questions',
+ 'a question',
+ toolPart({ toolName: 'ask_question', input: QUESTION }),
+ { toolCallId: 'call-1', kind: 'question', question: QUESTION },
+ ],
+ [
+ 'questions asked before ask_question',
toolPart({ toolName: 'ask_questions', input: { questions: QUESTIONS } }),
{ toolCallId: 'call-1', kind: 'questions', questions: QUESTIONS },
],
@@ -53,6 +64,13 @@ describe('parsePendingToolCall', () => {
'a tool that does not pause',
toolPart({ toolName: 'search_help_center', input: {} }),
],
+ [
+ 'a question without options',
+ toolPart({
+ toolName: 'ask_question',
+ input: { ...QUESTION, options: [] },
+ }),
+ ],
[
'questions without any question',
toolPart({ toolName: 'ask_questions', input: { questions: [] } }),
diff --git a/packages/twenty-front/src/modules/ai/utils/getAskedQuestionEntries.ts b/packages/twenty-front/src/modules/ai/utils/getAskedQuestionEntries.ts
new file mode 100644
index 00000000000..1095015a4a5
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/getAskedQuestionEntries.ts
@@ -0,0 +1,32 @@
+import {
+ type AskQuestionItem,
+ type AskQuestionResponse,
+ type AskQuestionToolResult,
+ type AskQuestionsToolResult,
+} from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+type AskedQuestionEntry = {
+ question: AskQuestionItem;
+ answer?: AskQuestionResponse;
+};
+
+// calls asked before ask_question carry a list of questions and answers
+export const getAskedQuestionEntries = (
+ result: AskQuestionToolResult | AskQuestionsToolResult | undefined,
+): AskedQuestionEntry[] => {
+ if (!isDefined(result)) {
+ return [];
+ }
+
+ if ('question' in result) {
+ return [{ question: result.question, answer: result.answer }];
+ }
+
+ return result.questions.map((question, questionIndex) => ({
+ question,
+ answer: result.answers?.find(
+ (answer) => answer.questionIndex === questionIndex,
+ ),
+ }));
+};
diff --git a/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts b/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts
index f8334fc21c6..c5aaf00283f 100644
--- a/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts
+++ b/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts
@@ -1,6 +1,7 @@
import { isString } from '@sniptt/guards';
import { getToolName, isToolUIPart } from 'ai';
import {
+ ASK_QUESTION_TOOL_NAME,
ASK_QUESTIONS_TOOL_NAME,
type AskQuestionItem,
buildFallbackProposedToolCall,
@@ -32,6 +33,16 @@ export const parsePendingToolCall = (
const { proposal } = part.output.result;
switch (getToolName(part)) {
+ case ASK_QUESTION_TOOL_NAME:
+ return isString(input.question) &&
+ Array.isArray(input.options) &&
+ isNonEmptyArray(input.options)
+ ? {
+ toolCallId,
+ kind: 'question',
+ question: input as AskQuestionItem,
+ }
+ : null;
case ASK_QUESTIONS_TOOL_NAME:
return Array.isArray(input.questions) && isNonEmptyArray(input.questions)
? {
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/parseAdminAskQuestionsResult.test.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/parseAdminAskQuestionsResult.test.ts
index a7a50b2c475..08333bcfe6e 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/parseAdminAskQuestionsResult.test.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/parseAdminAskQuestionsResult.test.ts
@@ -25,6 +25,41 @@ const buildPart = (
}) as AdminChatThreadMessagePart;
describe('parseAdminAskQuestionsResult', () => {
+ it('should read an answered ask_question call as a list of one', () => {
+ expect(
+ parseAdminAskQuestionsResult(
+ buildPart({
+ type: 'tool-ask_question',
+ toolName: 'ask_question',
+ toolOutput: {
+ success: true,
+ result: {
+ question: QUESTIONS[0],
+ status: 'answered',
+ answer: { selectedOptionIndices: [1] },
+ },
+ },
+ }),
+ ),
+ ).toEqual({
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [{ questionIndex: 0, selectedOptionIndices: [1] }],
+ });
+ });
+
+ it('should read a pending ask_question call from its input', () => {
+ expect(
+ parseAdminAskQuestionsResult(
+ buildPart({
+ type: 'tool-ask_question',
+ toolName: 'ask_question',
+ toolInput: QUESTIONS[0],
+ }),
+ ),
+ ).toEqual({ questions: QUESTIONS, status: 'pending' });
+ });
+
it('should parse an answered tool output', () => {
const result = parseAdminAskQuestionsResult(
buildPart({
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/parseAdminAskQuestionsResult.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/parseAdminAskQuestionsResult.ts
index 1305aee34e7..fa0409042c5 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/parseAdminAskQuestionsResult.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/parseAdminAskQuestionsResult.ts
@@ -1,5 +1,6 @@
import { isArray, isBoolean, isNumber, isString } from '@sniptt/guards';
import {
+ ASK_QUESTION_TOOL_NAME,
ASK_QUESTIONS_TOOL_NAME,
type AskQuestionAnswer,
type AskQuestionItem,
@@ -141,29 +142,52 @@ const parseStoredResult = (
};
const parsePendingResultFromToolInput = (
- toolInput: unknown,
+ questionsInput: unknown,
): AdminAskQuestionsResult | null => {
- if (!isPlainObject(toolInput)) {
- return null;
- }
-
- const questions = parseQuestions(toolInput.questions);
+ const questions = parseQuestions(questionsInput);
return isDefined(questions) ? { questions, status: 'pending' } : null;
};
+// an ask_question call holds one question, read as a list of one
+const toQuestionList = (
+ result: Record<string, unknown>,
+): Record<string, unknown> => ({
+ questions: [result.question],
+ status: result.status,
+ answers: isPlainObject(result.answer)
+ ? [{ ...result.answer, questionIndex: 0 }]
+ : undefined,
+});
+
export const parseAdminAskQuestionsResult = (
part: AdminChatThreadMessagePart,
): AdminAskQuestionsResult | null => {
- if (getAdminToolDisplayName(part) !== ASK_QUESTIONS_TOOL_NAME) {
+ const toolName = getAdminToolDisplayName(part);
+
+ if (
+ toolName !== ASK_QUESTION_TOOL_NAME &&
+ toolName !== ASK_QUESTIONS_TOOL_NAME
+ ) {
return null;
}
+ const isSingleQuestion = toolName === ASK_QUESTION_TOOL_NAME;
const storedResult = getStoredResult(parseAdminToolJson(part.toolOutput));
if (isDefined(storedResult)) {
- return parseStoredResult(storedResult);
+ return parseStoredResult(
+ isSingleQuestion ? toQuestionList(storedResult) : storedResult,
+ );
+ }
+
+ const toolInput = parseAdminToolJson(part.toolInput);
+
+ if (isSingleQuestion) {
+ return parsePendingResultFromToolInput([toolInput]);
}
- return parsePendingResultFromToolInput(parseAdminToolJson(part.toolInput));
+ return isPlainObject(toolInput)
+ ? parsePendingResultFromToolInput(toolInput.questions)
+ : null;
};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts
index 1a879451699..03ed64ac3e3 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts
@@ -42,15 +42,11 @@ describe('sendInboxMessage', () => {
title: 'Your first recording is ready',
text: 'Your call was recorded.',
toolCall: {
- toolName: 'ask_questions' as const,
+ toolName: 'ask_question' as const,
input: {
- questions: [
- {
- header: 'Share',
- question: 'Share the recording with the attendees?',
- options: [{ label: 'Draft an email' }, { label: 'Not now' }],
- },
- ],
+ header: 'Share',
+ question: 'Share the recording with the attendees?',
+ options: [{ label: 'Draft an email' }, { label: 'Not now' }],
},
},
};
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts
index 5b192309321..6d90928d15f 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts
@@ -3,7 +3,10 @@ import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migrati
import { Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
-import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
+import {
+ ASK_QUESTION_TOOL_NAME,
+ ASK_QUESTIONS_TOOL_NAME,
+} from 'twenty-shared/ai';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';
import { ADMIN_CHAT_THREADS_MAX_PAGE_SIZE } from 'src/engine/core-modules/admin-panel/constants/admin-chat-threads-max-page-size.constant';
@@ -116,7 +119,7 @@ export class AdminPanelGlobalChatThreadsService {
(SELECT COUNT(*)::int FROM ${table('agentMessage')} message WHERE message."threadId" = thread.id AND message."isHidden" = false) AS "messageCount",
((SELECT COUNT(*) FROM ${table('agentMessage')} message WHERE message."threadId" = thread.id AND message."isHidden" = false AND message.role = 'user')
+ (SELECT COUNT(*) FROM ${table('agentMessagePart')} part JOIN ${table('agentMessage')} message ON message.id = part."messageId"
- WHERE message."threadId" = thread.id AND message."isHidden" = false AND part."toolName" = $3 AND part."toolOutput"->'result'->>'status' = 'answered'))::int AS "userReplyCount"
+ WHERE message."threadId" = thread.id AND message."isHidden" = false AND part."toolName" = ANY($3::text[]) AND part."toolOutput"->'result'->>'status' = 'answered'))::int AS "userReplyCount"
FROM ${table('agentChatThread')} thread
JOIN core.workspace workspace ON workspace.id = ANY($1::uuid[]) AND workspace."allowImpersonation" = true AND workspace."deletedAt" IS NULL
LEFT JOIN ${escapeIdentifier(getWorkspaceSchemaName(workspaceIds[0]))}."workspaceMember" member ON member.id = thread."workspaceMemberId"
@@ -132,7 +135,7 @@ export class AdminPanelGlobalChatThreadsService {
parameters.push(
workspaceIds,
WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE,
- ASK_QUESTIONS_TOOL_NAME,
+ [ASK_QUESTION_TOOL_NAME, ASK_QUESTIONS_TOOL_NAME],
search ? `%${search}%` : null,
args.scope === AdminChatThreadScope.ONBOARDING,
args.hasErrorOnly,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/ask-question.pausing-tool.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/ask-question.pausing-tool.spec.ts
new file mode 100644
index 00000000000..8fbde83c4eb
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/ask-question.pausing-tool.spec.ts
@@ -0,0 +1,81 @@
+import { ASK_QUESTION_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool';
+
+const QUESTION = {
+ header: 'Add-ons',
+ question: 'Which add-ons?',
+ options: [{ label: 'SSO' }, { label: 'Audit log' }],
+ allowMultiSelect: true,
+};
+
+const NO_TOOLS = { executeTool: jest.fn() };
+
+const parseCall = (question: Record<string, unknown> = QUESTION) => {
+ const call = ASK_QUESTION_PAUSING_TOOL.parseCall(question);
+
+ if (call === null) {
+ throw new Error('Expected the call to parse');
+ }
+
+ return call;
+};
+
+describe('ASK_QUESTION_PAUSING_TOOL', () => {
+ it('cannot read a call without options', () => {
+ expect(
+ ASK_QUESTION_PAUSING_TOOL.parseCall({ ...QUESTION, options: [] }),
+ ).toBeNull();
+ expect(ASK_QUESTION_PAUSING_TOOL.parseCall(undefined)).toBeNull();
+ });
+
+ it('turns an answer into the answered result and the answer message', async () => {
+ const answer = { selectedOptionIndices: [0, 1] };
+
+ expect(parseCall().validate(answer)).toEqual({
+ isValid: true,
+ output: answer,
+ });
+ expect(
+ await parseCall().complete({ output: answer, context: NO_TOOLS }),
+ ).toEqual({
+ toolResult: {
+ success: true,
+ message: 'User answered the question.',
+ result: { question: QUESTION, status: 'answered', answer },
+ },
+ answerText: 'Which add-ons?\nSSO, Audit log',
+ });
+ });
+
+ it('prefers free text in the answer message', async () => {
+ const completion = await parseCall().complete({
+ output: { selectedOptionIndices: [0], freeText: ' Both ' },
+ context: NO_TOOLS,
+ });
+
+ expect(completion.answerText).toBe('Which add-ons?\nBoth');
+ });
+
+ it.each([
+ ['an empty answer', { selectedOptionIndices: [], freeText: ' ' }],
+ ['an unknown option', { selectedOptionIndices: [2] }],
+ ['the same option twice', { selectedOptionIndices: [1, 1] }],
+ ])('refuses %s', (_case, answer) => {
+ expect(parseCall().validate(answer).isValid).toBe(false);
+ });
+
+ it('refuses several options for a single-select question', () => {
+ const call = parseCall({ ...QUESTION, allowMultiSelect: false });
+
+ expect(call.validate({ selectedOptionIndices: [0, 1] }).isValid).toBe(
+ false,
+ );
+ });
+
+ it('closes a skipped call with its question', () => {
+ expect(parseCall().toSkippedToolResult()).toEqual({
+ success: true,
+ message: 'User skipped the question and sent another message instead.',
+ result: { question: QUESTION, status: 'skipped' },
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool.ts
new file mode 100644
index 00000000000..8c50f26b01b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool.ts
@@ -0,0 +1,152 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ type AskQuestionResponse,
+ type AskQuestionToolInput,
+ type AskQuestionToolResult,
+} from 'twenty-shared/ai';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { definePausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util';
+
+export const askQuestionInputSchema = z.object({
+ header: z
+ .string()
+ .describe(
+ 'Very short label/tag for the question (≤ ~32 chars), e.g. "Email type".',
+ ),
+ question: z
+ .string()
+ .describe('The full question to ask the user. Be clear and specific.'),
+ options: z
+ .array(
+ z.object({
+ label: z
+ .string()
+ .trim()
+ .min(1)
+ .describe('Concise option the user can pick (1-5 words).'),
+ description: z
+ .string()
+ .optional()
+ .describe(
+ 'Longer explanation shown when the user opens the option info icon.',
+ ),
+ isRecommended: z
+ .boolean()
+ .optional()
+ .describe('Mark the single suggested option, if any.'),
+ }),
+ )
+ .min(2)
+ .max(4)
+ .refine(
+ (options) =>
+ options.filter((option) => option.isRecommended === true).length <= 1,
+ { message: 'At most one option can be marked as recommended.' },
+ )
+ .describe('2-4 mutually exclusive options.'),
+ allowMultiSelect: z
+ .boolean()
+ .optional()
+ .describe('Allow the user to select more than one option.'),
+});
+
+// An application that asks through the inbox writes the same output.
+export const buildAskQuestionPendingOutput = (
+ question: AskQuestionToolInput,
+): {
+ success: true;
+ message: string;
+ result: AskQuestionToolResult;
+} => ({
+ success: true,
+ message: 'Question presented to the user; awaiting their answer.',
+ result: { question, status: 'pending' },
+});
+
+const buildAskQuestionOutputSchema = (
+ question: AskQuestionToolInput,
+): z.ZodType<AskQuestionResponse> =>
+ z
+ .object({
+ selectedOptionIndices: z
+ .array(z.number().int())
+ .refine((indices) => new Set(indices).size === indices.length, {
+ message: 'Each option can be selected only once.',
+ }),
+ freeText: z.string().optional(),
+ })
+ .superRefine(({ selectedOptionIndices, freeText }, context) => {
+ if (
+ selectedOptionIndices.some(
+ (optionIndex) =>
+ optionIndex < 0 || optionIndex >= question.options.length,
+ )
+ ) {
+ context.addIssue({
+ code: 'custom',
+ message: 'The answer references an unknown option.',
+ });
+ }
+
+ if (
+ question.allowMultiSelect !== true &&
+ selectedOptionIndices.length > 1
+ ) {
+ context.addIssue({
+ code: 'custom',
+ message: 'This question allows only one selection.',
+ });
+ }
+
+ if (
+ !isNonEmptyString(freeText?.trim()) &&
+ !isNonEmptyArray(selectedOptionIndices)
+ ) {
+ context.addIssue({ code: 'custom', message: 'Provide an answer.' });
+ }
+ });
+
+const buildAnswerText = ({
+ question,
+ answer,
+}: {
+ question: AskQuestionToolInput;
+ answer: AskQuestionResponse;
+}) => {
+ const freeText = answer.freeText?.trim();
+ const value = isNonEmptyString(freeText)
+ ? freeText
+ : answer.selectedOptionIndices
+ .map((optionIndex) => question.options[optionIndex].label)
+ .join(', ');
+
+ return `${question.question}\n${value}`;
+};
+
+// result shape is read by the chat renderer, the admin panel and seeded runs
+export const ASK_QUESTION_PAUSING_TOOL = definePausingTool<
+ AskQuestionToolInput,
+ AskQuestionResponse
+>({
+ inputSchema: askQuestionInputSchema,
+ outputSchema: buildAskQuestionOutputSchema,
+ complete: async ({ output: answer, input: question }) => ({
+ toolResult: {
+ success: true,
+ message: 'User answered the question.',
+ result: {
+ question,
+ status: 'answered',
+ answer,
+ } satisfies AskQuestionToolResult,
+ },
+ answerText: buildAnswerText({ question, answer }),
+ }),
+ toSkippedToolResult: (question) => ({
+ success: true,
+ message: 'User skipped the question and sent another message instead.',
+ result: { question, status: 'skipped' } satisfies AskQuestionToolResult,
+ }),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
index db0b6cde764..51727c69061 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
@@ -9,7 +9,7 @@ import { z } from 'zod';
import { definePausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util';
-export const askQuestionsInputSchema = z.object({
+const askQuestionsInputSchema = z.object({
questions: z
.array(
z.object({
@@ -61,19 +61,6 @@ export const askQuestionsInputSchema = z.object({
.describe('One to four questions to ask the user.'),
});
-// An application that asks through the inbox writes the same output.
-export const buildAskQuestionsPendingOutput = (
- input: AskQuestionsToolInput,
-): {
- success: true;
- message: string;
- result: AskQuestionsToolResult;
-} => ({
- success: true,
- message: 'Questions presented to the user; awaiting their answer.',
- result: { questions: input.questions, status: 'pending' },
-});
-
type AskQuestionsToolOutput = {
answers: AskQuestionAnswer[];
};
@@ -166,7 +153,8 @@ const buildAnswerText = ({
})
.join('\n\n');
-// result shape is read by the chat renderer, the admin panel and seeded runs
+// the multi-question tool ask_question replaced, kept so calls stored before can still be
+// answered and read
export const ASK_QUESTIONS_PAUSING_TOOL = definePausingTool<
AskQuestionsToolInput,
AskQuestionsToolOutput
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
index 96ff4d3574b..4b9576f9820 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
@@ -1,15 +1,19 @@
import {
+ ASK_QUESTION_TOOL_NAME,
ASK_QUESTIONS_TOOL_NAME,
PROPOSE_TOOL_CALL_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
} from 'twenty-shared/ai';
+import { ASK_QUESTION_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool';
import { ASK_QUESTIONS_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool';
import { PROPOSE_TOOL_CALL_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool';
import { REQUEST_FORM_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool';
import { type PausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type';
export const PAUSING_TOOLS: ReadonlyMap<string, PausingTool> = new Map([
+ [ASK_QUESTION_TOOL_NAME, ASK_QUESTION_PAUSING_TOOL],
+ // no longer offered, but calls asked before can still be answered or closed
[ASK_QUESTIONS_TOOL_NAME, ASK_QUESTIONS_PAUSING_TOOL],
[PROPOSE_TOOL_CALL_TOOL_NAME, PROPOSE_TOOL_CALL_PAUSING_TOOL],
[REQUEST_FORM_TOOL_NAME, REQUEST_FORM_PAUSING_TOOL],
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/close-open-tool-parts.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/close-open-tool-parts.util.spec.ts
index 36c697c54da..5717a9cf57f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/close-open-tool-parts.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/close-open-tool-parts.util.spec.ts
@@ -1,5 +1,5 @@
import {
- ASK_QUESTIONS_TOOL_NAME,
+ ASK_QUESTION_TOOL_NAME,
PROPOSE_TOOL_CALL_TOOL_NAME,
} from 'twenty-shared/ai';
@@ -66,9 +66,9 @@ describe('closeOpenToolParts', () => {
await closeParts([
{
id: 'questions',
- toolName: ASK_QUESTIONS_TOOL_NAME,
- toolInput: { questions: QUESTIONS },
- toolOutput: { result: { status: 'pending', questions: QUESTIONS } },
+ toolName: ASK_QUESTION_TOOL_NAME,
+ toolInput: QUESTIONS[0],
+ toolOutput: { result: { status: 'pending', question: QUESTIONS[0] } },
},
]),
).toEqual([
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
index e4ed5b6d933..d4cc3ede1a2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
@@ -14,7 +14,7 @@ describe('endsOnPausingToolCall', () => {
endsOnPausingToolCall({
steps: [
stepWithResults({ toolName: 'search', output: {} }),
- stepWithResults(awaiting('ask_questions')),
+ stepWithResults(awaiting('ask_question')),
],
}),
).toBe(true);
@@ -24,7 +24,7 @@ describe('endsOnPausingToolCall', () => {
expect(
endsOnPausingToolCall({
steps: [
- stepWithResults(awaiting('ask_questions')),
+ stepWithResults(awaiting('ask_question')),
stepWithResults({ toolName: 'search', output: {} }),
],
}),
@@ -38,11 +38,11 @@ describe('endsOnPausingToolCall', () => {
});
it('only pauses on a pausing tool the run was offered', () => {
- const steps = [stepWithResults(awaiting('ask_questions'))];
+ const steps = [stepWithResults(awaiting('ask_question'))];
expect(endsOnPausingToolCall({ steps, offeredToolNames: [] })).toBe(false);
expect(
- endsOnPausingToolCall({ steps, offeredToolNames: ['ask_questions'] }),
+ endsOnPausingToolCall({ steps, offeredToolNames: ['ask_question'] }),
).toBe(true);
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/find-awaiting-pausing-tool-parts.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/find-awaiting-pausing-tool-parts.util.spec.ts
index 6504c368900..a54c5f9df7a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/find-awaiting-pausing-tool-parts.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/find-awaiting-pausing-tool-parts.util.spec.ts
@@ -10,7 +10,7 @@ const toolPart = ({
toolName,
status,
toolCallId = 'call-1',
- input = { questions: QUESTIONS },
+ input = QUESTIONS[0],
}: {
toolName: string;
status: 'pending' | 'answered';
@@ -22,7 +22,7 @@ const toolPart = ({
toolCallId,
state: 'output-available',
input,
- output: { success: true, result: { questions: QUESTIONS, status } },
+ output: { success: true, result: { question: QUESTIONS[0], status } },
}) as unknown as ExtendedUIMessagePart;
const textPart = { type: 'text', text: 'hello' } as ExtendedUIMessagePart;
@@ -32,10 +32,10 @@ describe('findAwaitingPausingToolParts', () => {
expect(
findAwaitingPausingToolParts([
textPart,
- toolPart({ toolName: 'ask_questions', status: 'pending' }),
+ toolPart({ toolName: 'ask_question', status: 'pending' }),
]),
).toEqual([
- { toolName: 'ask_questions', toolCallId: 'call-1', isAnswerable: true },
+ { toolName: 'ask_question', toolCallId: 'call-1', isAnswerable: true },
]);
});
@@ -43,13 +43,13 @@ describe('findAwaitingPausingToolParts', () => {
expect(
findAwaitingPausingToolParts([
toolPart({
- toolName: 'ask_questions',
+ toolName: 'ask_question',
status: 'pending',
input: { questions: [] },
}),
]),
).toEqual([
- { toolName: 'ask_questions', toolCallId: 'call-1', isAnswerable: false },
+ { toolName: 'ask_question', toolCallId: 'call-1', isAnswerable: false },
]);
});
@@ -57,17 +57,17 @@ describe('findAwaitingPausingToolParts', () => {
expect(
findAwaitingPausingToolParts([
toolPart({
- toolName: 'ask_questions',
+ toolName: 'ask_question',
status: 'pending',
toolCallId: 'call-1',
}),
toolPart({
- toolName: 'ask_questions',
+ toolName: 'ask_question',
status: 'answered',
toolCallId: 'call-2',
}),
toolPart({
- toolName: 'ask_questions',
+ toolName: 'ask_question',
status: 'pending',
toolCallId: 'call-3',
}),
@@ -78,7 +78,7 @@ describe('findAwaitingPausingToolParts', () => {
it('ignores a pausing tool call already answered', () => {
expect(
findAwaitingPausingToolParts([
- toolPart({ toolName: 'ask_questions', status: 'answered' }),
+ toolPart({ toolName: 'ask_question', status: 'answered' }),
]),
).toEqual([]);
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts
index 4e5362d374d..8d852e3eb1b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts
@@ -11,7 +11,7 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
it('should state the two-call reply contract up front', () => {
expect(prompt).toContain(
- 'While the setup runs, every reply of yours ends with one of two tool calls, ask_questions or complete_workspace_setup, as the final section below spells out',
+ 'While the setup runs, every reply of yours ends with ask_question calls, one per question, or with the complete_workspace_setup call, as the final section below spells out',
);
});
@@ -63,10 +63,10 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
expect(prompt).not.toContain('browsing_context');
});
- it('should instruct a text-first first reply with the mandatory ask_questions call', () => {
- expect(prompt).toContain('required ask_questions call');
+ it('should instruct a text-first first reply with the mandatory ask_question call', () => {
+ expect(prompt).toContain('required ask_question call');
expect(prompt).toContain(
- 'reply is unfinished until the ask_questions call is made',
+ 'reply is unfinished until the ask_question call is made',
);
expect(prompt).toContain('needs no skill and no learn_tools step');
expect(prompt).toContain(
@@ -96,14 +96,14 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
it('should open with the migration-or-scratch question as a tool call', () => {
expect(prompt).toContain('moving over from another CRM or starting fresh');
expect(prompt).toContain(
- 'Then stop writing and make the ask_questions call',
+ 'Then stop writing and make the ask_question call',
);
expect(prompt).toContain('leaving any other CRM to the free-text answer');
expect(prompt).toContain('follow the migration path below');
});
it('should request the CRM export in plain text so the upload composer stays available', () => {
- expect(prompt).toContain('end that reply without calling ask_questions');
+ expect(prompt).toContain('end that reply without calling ask_question');
expect(prompt).toContain('cannot take attachments');
expect(prompt).toContain('upload all their CSV exports at once');
expect(prompt).toContain('as separate files');
@@ -134,10 +134,10 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
expect(prompt).not.toContain('under 250 words');
});
- it('should ask about the data model with the ask_questions tool', () => {
+ it('should ask about the data model with the ask_question tool', () => {
expect(prompt).toContain('Never stop after presenting the proposal');
expect(prompt).toContain(
- 'The turn is unfinished until you call ask_questions asking whether to go ahead and build it',
+ 'The turn is unfinished until you call ask_question asking whether to go ahead and build it',
);
expect(prompt).toContain('Ask it even though the answer seems obvious');
});
@@ -161,10 +161,10 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
expect(prompt).not.toContain('navigate_app');
});
- it('should route what comes next through a mandatory ask_questions call', () => {
+ it('should route what comes next through a mandatory ask_question call', () => {
expect(prompt).toContain('## What comes next');
expect(prompt).toContain(
- 'Never stop after that report: the turn is unfinished until you call ask_questions letting them pick what comes next',
+ 'Never stop after that report: the turn is unfinished until you call ask_question letting them pick what comes next',
);
expect(prompt).not.toContain('Nothing after that is a fixed sequence');
expect(prompt).not.toContain('which single capability to propose next');
@@ -256,8 +256,8 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
expect(prompt).toContain('each written as a chip');
});
- it('should carry the ask_questions shape rules the base prompt no longer provides', () => {
- expect(prompt).toContain('Route decisions through ask_questions');
+ it('should carry the ask_question shape rules the base prompt no longer provides', () => {
+ expect(prompt).toContain('Route decisions through ask_question');
expect(prompt).toContain(
'a question mark in your text means the call is missing',
);
@@ -280,14 +280,14 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
it('should end every setup reply on one of the two calls, after its text', () => {
expect(prompt).toContain('## How every reply ends');
expect(prompt).toContain(
- 'ends in exactly one of two ways: the ask_questions call, or the complete_workspace_setup call',
+ 'ends in exactly one of two ways: ask_question calls, one per question, or the complete_workspace_setup call',
);
expect(prompt).toContain('The only exception is the CSV upload request');
expect(prompt).toContain(
'come after the text of that reply, never instead of it',
);
expect(prompt).toContain(
- 'while anything is still worth building, it is the ask_questions call',
+ 'while anything is still worth building, it is ask_question calls',
);
expect(prompt).toContain(
'whether they picked the finishing option or told you so in their own words, it is complete_workspace_setup',
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts
index a330efce505..aa9d2d4dd37 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts
@@ -64,9 +64,9 @@ Intent gate: purely informational dashboard questions (e.g. "what is a dashboard
## Asking the user questions
-- When a decision is genuinely ambiguous or consequential and you cannot infer it from the request or context, call \`ask_questions\` to ask the user one or more multiple-choice questions instead of guessing. The conversation pauses until they answer.
+- When a decision is genuinely ambiguous or consequential and you cannot infer it from the request or context, call \`ask_question\` to ask the user a multiple-choice question instead of guessing, once per question when you have several. The conversation pauses until they answer.
- Each question needs a short \`header\`, the \`question\` text, and 2-4 \`options\` (each with a \`label\` and an optional \`description\`); mark the suggested option with \`isRecommended\`. The user can always type a free-form answer instead of picking an option.
-- Do NOT use \`ask_questions\` for information you can look up with another tool, or for trivial choices that have an obvious default — make the reasonable choice and proceed. Ask at most a few focused questions at once.
+- Do NOT use \`ask_question\` for information you can look up with another tool, or for trivial choices that have an obvious default — make the reasonable choice and proceed. Ask at most a few focused questions per turn, one call per question.
`,
BROWSING_CONTEXT_INSTRUCTION: `A <browsing_context> tag may appear in the user's last message. Only use it when directly relevant to the question.`,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts
index 9f029124ff6..3cd86871212 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts
@@ -2,7 +2,7 @@ export const WORKSPACE_SETUP_SYSTEM_PROMPT = `You are an AI agent integrated int
The first message of this conversation is not from the user: it is hidden context carrying what is known about the company that owns this workspace and the person setting it up, or stating that nothing is, plus the workspace itself and the language to hold the conversation in. It is invisible to the user: never reference or quote it, present what you know about them and their company as your own knowledge rather than as data you were handed, and follow these rules silently instead of narrating your own method back to them.
-While the setup runs, every reply of yours ends with one of two tool calls, ask_questions or complete_workspace_setup, as the final section below spells out.
+While the setup runs, every reply of yours ends with ask_question calls, one per question, or with the complete_workspace_setup call, as the final section below spells out.
## Goal
@@ -22,17 +22,17 @@ Chain tools, using each result to inform the next, and when a tool fails, analyz
## First reply
-Write your text first so it starts streaming immediately: before it, do not call load_skills, learn_tools, execute_tool, or web search. Then close the reply with the required ask_questions call, which needs no skill and no learn_tools step, so make it directly.
+Write your text first so it starts streaming immediately: before it, do not call load_skills, learn_tools, execute_tool, or web search. Then close the reply with the required ask_question call, which needs no skill and no learn_tools step, so make it directly.
-Do not greet them again, the page above already welcomed them by name. Open with one line saying you are an AI agent who will walk them through Twenty and set their workspace up with them. When the first message describes their company, follow with a couple of lines on what you already know about it, tailored to their business and specific enough to show you did your homework rather than reciting data points, written the way a colleague would rather than a form, and invite them to correct anything; when their job title is in your user context, say you see them doing that at the company and shape the setup around it, and when it is missing, do not guess it. Then stop writing and make the ask_questions call: its question is whether they are moving over from another CRM or starting fresh, its options the two CRMs a company like theirs most likely uses, or the two most widely used when you know nothing about them, and starting fresh, leaving any other CRM to the free-text answer. When the first message carries person context, it tells you who they are professionally: fold at most one specific detail from it into how you frame the setup, and never recite their profile back at them.
+Do not greet them again, the page above already welcomed them by name. Open with one line saying you are an AI agent who will walk them through Twenty and set their workspace up with them. When the first message describes their company, follow with a couple of lines on what you already know about it, tailored to their business and specific enough to show you did your homework rather than reciting data points, written the way a colleague would rather than a form, and invite them to correct anything; when their job title is in your user context, say you see them doing that at the company and shape the setup around it, and when it is missing, do not guess it. Then stop writing and make the ask_question call: its question is whether they are moving over from another CRM or starting fresh, its options the two CRMs a company like theirs most likely uses, or the two most widely used when you know nothing about them, and starting fresh, leaving any other CRM to the free-text answer. When the first message carries person context, it tells you who they are professionally: fold at most one specific detail from it into how you frame the setup, and never recite their profile back at them.
-When they name a CRM, follow the migration path below. When they start fresh and the first message described their company, present the data model proposal described below. When they start fresh and you know nothing about them, follow with one more ask_questions to learn what the business does, who its customers are, and what they want to use Twenty for, offering the most likely answers as options, and present the data model proposal described below once they answer.
+When they name a CRM, follow the migration path below. When they start fresh and the first message described their company, present the data model proposal described below. When they start fresh and you know nothing about them, follow with ask_question calls, one per question, to learn what the business does, who its customers are, and what they want to use Twenty for, offering the most likely answers as options, and present the data model proposal described below once they answer.
-This reply is unfinished until the ask_questions call is made. Ask it even though the answer seems obvious, and never give that question a title of its own.
+This reply is unfinished until the ask_question call is made. Ask it even though the answer seems obvious, and never give that question a title of its own.
## Migrating from another CRM
-When they name a CRM, ask them in plain text to upload all their CSV exports at once, contacts, companies, and deals as separate files, saying where the export lives when you know it, and end that reply without calling ask_questions: a pending question replaces the message box with a card that cannot take attachments. Any spreadsheet their CRM produces is fine; if they cannot export, continue as if they had chosen to start fresh.
+When they name a CRM, ask them in plain text to upload all their CSV exports at once, contacts, companies, and deals as separate files, saying where the export lives when you know it, and end that reply without calling ask_question: a pending question replaces the message box with a card that cannot take attachments. Any spreadsheet their CRM produces is fine; if they cannot export, continue as if they had chosen to start fresh.
When files arrive, read them right away with the code_interpreter tool, since they never reach you directly, looking at headers and a few sample rows, then present the proposal described below grounded in what they actually have: one standard object per file where one fits, the columns the team would filter, sort, or report on as its fields, naming the ones you drop, and a custom object only for a file that is none of people, companies, or deals. Say in the proposal that their rows come in as records once the model is built, so one approval covers both.
@@ -42,11 +42,11 @@ Introduce the data model in one line, including that it stays fully customizable
- One line per standard object (People, Companies, Opportunities) mapping it onto their domain, with the custom fields to add, each written as a chip. A field earns its place only if the team would filter, sort, or report on it.
- A custom object only for an entity with its own lifecycle that cannot live as fields on a standard object; most businesses need few, sometimes none. For each: a bold name, a one-line purpose, its key fields with types, and its relations.
-Never stop after presenting the proposal. The turn is unfinished until you call ask_questions asking whether to go ahead and build it. Ask it even though the answer seems obvious.
+Never stop after presenting the proposal. The turn is unfinished until you call ask_question asking whether to go ahead and build it. Ask it even though the answer seems obvious.
## After approval
-Only propose until the user explicitly approves: never create, update, or delete anything before approval. Once something is approved, build it without asking again: ask_questions is for new decisions, not for confirming a choice the user already made. Load a skill before proposing what it builds, so your proposal is the plan it wants confirmed and the answer to your question is that confirmation.
+Only propose until the user explicitly approves: never create, update, or delete anything before approval. Once something is approved, build it without asking again: ask_question is for new decisions, not for confirming a choice the user already made. Load a skill before proposing what it builds, so your proposal is the plan it wants confirmed and the answer to your question is that confirmation.
Build the model first: load the metadata-building skill, then create_many_object_metadata, create_many_field_metadata, create_many_relation_fields. SELECT option values are UPPER_SNAKE_CASE, and never set isNullable false: a required field blocks every record that does not have that value yet. New fields land visible on their object's index view, so no view work is needed.
@@ -56,7 +56,7 @@ When they are migrating, one more step is fixed: as soon as the model is built,
Report what you built in a couple of lines, then give one line to each capability they do not have yet, naming the thing in their business it improves: a workflow that removes a chore they described, a dashboard answering a number they said they watch, a role matching a split in their team. Those lines introduce the capabilities, they are not a menu to restate as choices.
-Never stop after that report: the turn is unfinished until you call ask_questions letting them pick what comes next, which needs no skill and no learn_tools step, so make it directly. Its options are exactly the capabilities they do not have yet plus finishing the setup, with the capability you would do next marked recommended and never the finishing one.
+Never stop after that report: the turn is unfinished until you call ask_question letting them pick what comes next, which needs no skill and no learn_tools step, so make it directly. Its options are exactly the capabilities they do not have yet plus finishing the setup, with the capability you would do next marked recommended and never the finishing one.
Their pick is the approval: load the skill for whichever capability they pick, follow its recipe below, build it without asking again, then report it and ask again the same way with what is left, so each round is shorter than the last. When they answer in free text instead, do what they asked, then come back to the question. Once nothing is left to offer, skip it, since a question with one option is rejected, and end the setup as described below, which is also what you do when they pick finishing it, without asking them to confirm.
@@ -77,12 +77,12 @@ Twenty is new to this admin. Introduce a capability in one plain sentence before
Open each reply with a short plain title, and title each new step you move on to in the same reply. Write objects and fields as chips every time you name them, including the ones you have not created yet, and Workflows and Dashboards themselves; views become chips only after a tool returns their ids, and no reference renders inside a title.
-Route decisions through ask_questions, not plain-text questions, with the one exception of the migration upload described above. Outside that exception, a question mark in your text means the call is missing, and never ask it for information you can look up with a tool. Each takes a short header, its question, and 2 to 4 short options, each a label with an optional description, at most one of them marked recommended, since a second one is rejected and the question is lost. The user can always answer in free text, so never spell the options out in your text.
+Route decisions through ask_question, not plain-text questions, with the one exception of the migration upload described above. Outside that exception, a question mark in your text means the call is missing, and never ask it for information you can look up with a tool. Each takes a short header, its question, and 2 to 4 short options, each a label with an optional description, at most one of them marked recommended, since a second one is rejected and the question is lost. The user can always answer in free text, so never spell the options out in your text.
When creating objects and fields, their names must be in English (camelCase field names, singular English object names), while every user-facing label (labelSingular, labelPlural, field labels, select option labels) must be in the user's language.
## How every reply ends
-While the setup is running, each reply of yours ends in exactly one of two ways: the ask_questions call, or the complete_workspace_setup call. The only exception is the CSV upload request above, which ends with neither. Tool results do not end a reply, and neither does reporting what you just built: after either of those you are still mid-reply, and the way you finish it is one of those two calls. So never write the choices out as a list in your text and never ask in your own words which one they want, since the options reach them only through the call, and a question left in your text gives them nothing to pick and stalls the setup there. Which of the two it is follows from them: while anything is still worth building, it is the ask_questions call, and from the moment they are done, whether they picked the finishing option or told you so in their own words, it is complete_workspace_setup in that same reply.
+While the setup is running, each reply of yours ends in exactly one of two ways: ask_question calls, one per question, or the complete_workspace_setup call. The only exception is the CSV upload request above, which ends with neither. Tool results do not end a reply, and neither does reporting what you just built: after either of those you are still mid-reply, and the way you finish it is one of those two calls. So never write the choices out as a list in your text and never ask in your own words which one they want, since the options reach them only through the call, and a question left in your text gives them nothing to pick and stalls the setup there. Which of the two it is follows from them: while anything is still worth building, it is ask_question calls, and from the moment they are done, whether they picked the finishing option or told you so in their own words, it is complete_workspace_setup in that same reply.
Both of those calls come after the text of that reply, never instead of it: a reply whose only content is one of them arrives as an empty message, so the question card shows up under a blank turn and the setup closes without a word of goodbye.`;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
index 4bd73474a40..4a2dceef709 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
@@ -1,5 +1,5 @@
import { type LanguageModelUsage, type TextStreamPart, type ToolSet } from 'ai';
-import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
+import { ASK_QUESTION_TOOL_NAME } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -88,20 +88,20 @@ const PENDING_QUESTION_PARTS: ModelStreamPart[] = [
{
type: 'tool-input-start',
id: 'tool-call-id',
- toolName: ASK_QUESTIONS_TOOL_NAME,
+ toolName: ASK_QUESTION_TOOL_NAME,
},
{
type: 'tool-call',
toolCallId: 'tool-call-id',
- toolName: ASK_QUESTIONS_TOOL_NAME,
- input: { questions: QUESTIONS },
+ toolName: ASK_QUESTION_TOOL_NAME,
+ input: QUESTIONS[0],
},
{
type: 'tool-result',
toolCallId: 'tool-call-id',
- toolName: ASK_QUESTIONS_TOOL_NAME,
- input: { questions: QUESTIONS },
- output: { result: { questions: QUESTIONS, status: 'pending' } },
+ toolName: ASK_QUESTION_TOOL_NAME,
+ input: QUESTIONS[0],
+ output: { result: { question: QUESTIONS[0], status: 'pending' } },
},
...FINISH_PARTS,
];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts
index 4920c12d5ef..5fab6beba38 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts
@@ -18,9 +18,9 @@ const buildService = ({ claimAffected = 1 } = {}) => {
find: jest.fn().mockResolvedValue([
{
id: 'part-id',
- toolName: 'ask_questions',
- toolInput: { questions: QUESTIONS },
- toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
+ toolName: 'ask_question',
+ toolInput: QUESTIONS[0],
+ toolOutput: { result: { question: QUESTIONS[0], status: 'pending' } },
},
]),
writePart: jest.fn(),
@@ -82,7 +82,7 @@ describe('AgentChatService closePendingToolCalls', () => {
expectedStatus: 'pending',
});
expect(JSON.parse(closedToolOutput).result).toEqual({
- questions: QUESTIONS,
+ question: QUESTIONS[0],
status: 'skipped',
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
index 273bf980e0e..6714a4816ae 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
@@ -14,7 +14,7 @@ import {
type ToolSet,
} from 'ai';
import {
- ASK_QUESTIONS_TOOL_NAME,
+ ASK_QUESTION_TOOL_NAME,
ATTACH_CONVERSATION_TO_RECORD_TOOL_NAME,
COMPLETE_WORKSPACE_SETUP_TOOL_NAME,
type ExtendedUIMessage,
@@ -73,7 +73,7 @@ import { AI_CHAT_TOOL_NAMES_TO_PRELOAD } from 'src/engine/metadata-modules/ai/ai
import { AI_CHAT_WORKSPACE_SETUP_STREAM_FUNCTION_ID } from 'src/engine/metadata-modules/ai/ai-chat/constants/ai-chat-workspace-setup-stream-function-id.constant';
import { AgentChatThreadTargetService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-target.service';
import { MessagePruningService } from 'src/engine/metadata-modules/ai/ai-chat/services/message-pruning.service';
-import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
+import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
import { createAttachConversationToRecordTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/attach-conversation-to-record.tool';
import { createProposeToolCallTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-tool-call.tool';
import { createRequestFormTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';
@@ -287,7 +287,7 @@ export class ChatExecutionService {
const preloadedToolSet: ToolSet = {
...preloadedTools,
...nativeTools,
- [ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({
+ [ASK_QUESTION_TOOL_NAME]: createAskQuestionTool({
isWorkspaceSetupThread,
}),
[REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-question.tool.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-question.tool.spec.ts
new file mode 100644
index 00000000000..720dbd6fe27
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-question.tool.spec.ts
@@ -0,0 +1,78 @@
+import { askQuestionInputSchema } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool';
+import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
+
+const QUESTION = {
+ header: 'Email type',
+ question: 'What type of email?',
+ options: [{ label: 'Welcome' }, { label: 'Offer' }],
+};
+
+describe('ask_question tool', () => {
+ it('drops the obvious-default guidance on workspace setup threads', () => {
+ const standardTool = createAskQuestionTool({
+ isWorkspaceSetupThread: false,
+ });
+ const setupTool = createAskQuestionTool({ isWorkspaceSetupThread: true });
+
+ expect(standardTool.description).toContain(
+ 'trivial choices with an obvious default',
+ );
+ expect(setupTool.description).not.toContain('obvious default');
+ expect(setupTool.description).toContain(
+ 'information you could look up with another tool',
+ );
+ });
+
+ it('tells the model to ask several questions as several calls', () => {
+ const tool = createAskQuestionTool({ isWorkspaceSetupThread: false });
+
+ expect(tool.description).toContain('call it once per question');
+ });
+
+ it('execute echoes the question with a pending status', async () => {
+ const tool = createAskQuestionTool({ isWorkspaceSetupThread: false });
+
+ expect(await tool.execute(QUESTION)).toEqual({
+ success: true,
+ message: expect.any(String),
+ result: { question: QUESTION, status: 'pending' },
+ });
+ });
+
+ it.each([
+ ['fewer than two options', { options: [{ label: 'only one' }] }],
+ ['a blank option label', { options: [{ label: ' ' }, { label: 'b' }] }],
+ [
+ 'more than four options',
+ {
+ options: ['a', 'b', 'c', 'd', 'e'].map((label) => ({ label })),
+ },
+ ],
+ [
+ 'more than one recommended option',
+ {
+ options: [
+ { label: 'a', isRecommended: true },
+ { label: 'b', isRecommended: true },
+ ],
+ },
+ ],
+ ])('rejects %s', (_case, override) => {
+ expect(
+ askQuestionInputSchema.safeParse({ ...QUESTION, ...override }).success,
+ ).toBe(false);
+ });
+
+ it('accepts a multi-select question with a recommended option', () => {
+ expect(
+ askQuestionInputSchema.safeParse({
+ ...QUESTION,
+ options: [
+ { label: 'c', description: 'desc', isRecommended: true },
+ { label: 'd' },
+ ],
+ allowMultiSelect: true,
+ }).success,
+ ).toBe(true);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-questions.tool.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-questions.tool.spec.ts
deleted file mode 100644
index 37a88a4bebb..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-questions.tool.spec.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
-
-import { askQuestionsInputSchema } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool';
-import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
-
-describe('ask_questions tool', () => {
- it('is named ask_questions (plural)', () => {
- expect(ASK_QUESTIONS_TOOL_NAME).toBe('ask_questions');
- });
-
- it('drops the obvious-default guidance on workspace setup threads', () => {
- const standardTool = createAskQuestionsTool({
- isWorkspaceSetupThread: false,
- });
- const setupTool = createAskQuestionsTool({ isWorkspaceSetupThread: true });
-
- expect(standardTool.description).toContain(
- 'trivial choices with an obvious default',
- );
- expect(setupTool.description).not.toContain('obvious default');
- expect(setupTool.description).toContain(
- 'information you could look up with another tool',
- );
- });
-
- it('execute echoes the questions with a pending status', async () => {
- const tool = createAskQuestionsTool({ isWorkspaceSetupThread: false });
- const questions = [
- {
- header: 'Email type',
- question: 'What type of email?',
- options: [{ label: 'Welcome' }, { label: 'Offer' }],
- },
- ];
-
- const output = await tool.execute({ questions });
-
- expect(output).toEqual({
- success: true,
- message: expect.any(String),
- result: { questions, status: 'pending' },
- });
- });
-
- it('rejects fewer than two options', () => {
- const result = askQuestionsInputSchema.safeParse({
- questions: [
- { header: 'h', question: 'q', options: [{ label: 'only one' }] },
- ],
- });
-
- expect(result.success).toBe(false);
- });
-
- it('rejects zero questions', () => {
- const result = askQuestionsInputSchema.safeParse({ questions: [] });
-
- expect(result.success).toBe(false);
- });
-
- it('rejects more than four questions', () => {
- const question = {
- header: 'h',
- question: 'q',
- options: [{ label: 'a' }, { label: 'b' }],
- };
- const result = askQuestionsInputSchema.safeParse({
- questions: [question, question, question, question, question],
- });
-
- expect(result.success).toBe(false);
- });
-
- it('rejects more than four options', () => {
- const result = askQuestionsInputSchema.safeParse({
- questions: [
- {
- header: 'h',
- question: 'q',
- options: [
- { label: 'a' },
- { label: 'b' },
- { label: 'c' },
- { label: 'd' },
- { label: 'e' },
- ],
- },
- ],
- });
-
- expect(result.success).toBe(false);
- });
-
- it('rejects more than one recommended option', () => {
- const result = askQuestionsInputSchema.safeParse({
- questions: [
- {
- header: 'h',
- question: 'q',
- options: [
- { label: 'a', isRecommended: true },
- { label: 'b', isRecommended: true },
- ],
- },
- ],
- });
-
- expect(result.success).toBe(false);
- });
-
- it('accepts a valid multi-question payload', () => {
- const result = askQuestionsInputSchema.safeParse({
- questions: [
- {
- header: 'h1',
- question: 'q1',
- options: [{ label: 'a' }, { label: 'b' }],
- },
- {
- header: 'h2',
- question: 'q2',
- options: [
- { label: 'c', description: 'desc', isRecommended: true },
- { label: 'd' },
- ],
- allowMultiSelect: true,
- },
- ],
- });
-
- expect(result.success).toBe(true);
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool.ts
new file mode 100644
index 00000000000..61d3d94a906
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool.ts
@@ -0,0 +1,37 @@
+import { type AskQuestionToolInput } from 'twenty-shared/ai';
+
+import {
+ askQuestionInputSchema,
+ buildAskQuestionPendingOutput,
+} from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool';
+
+const SEVERAL_QUESTIONS_GUIDANCE =
+ 'To ask several questions, call it once per question in the same step: the user goes ' +
+ 'through them one by one and the conversation continues once all are answered.';
+
+const STANDARD_DESCRIPTION =
+ 'Ask the user a multiple-choice question when you need a decision you cannot infer ' +
+ 'from the request or context and that has no obvious default. The conversation pauses ' +
+ 'until the user answers, then continues with their choice in mind. Prefer this over ' +
+ 'guessing on consequential or ambiguous decisions. Do NOT use it for information you ' +
+ 'could look up with another tool, or for trivial choices with an obvious default. The ' +
+ `user can always type a free-form answer instead of picking an option. ${SEVERAL_QUESTIONS_GUIDANCE}`;
+
+const WORKSPACE_SETUP_DESCRIPTION =
+ 'Ask the user a multiple-choice question when a decision is theirs to make. The ' +
+ 'conversation pauses until the user answers, then continues with their choice in mind. ' +
+ 'Do NOT use it for information you could look up with another tool. The user can always ' +
+ `type a free-form answer instead of picking an option. ${SEVERAL_QUESTIONS_GUIDANCE}`;
+
+export const createAskQuestionTool = ({
+ isWorkspaceSetupThread,
+}: {
+ isWorkspaceSetupThread: boolean;
+}) => ({
+ description: isWorkspaceSetupThread
+ ? WORKSPACE_SETUP_DESCRIPTION
+ : STANDARD_DESCRIPTION,
+ inputSchema: askQuestionInputSchema,
+ execute: async (input: AskQuestionToolInput) =>
+ buildAskQuestionPendingOutput(input),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts
deleted file mode 100644
index 28367ab148c..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { type AskQuestionsToolInput } from 'twenty-shared/ai';
-
-import {
- askQuestionsInputSchema,
- buildAskQuestionsPendingOutput,
-} from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool';
-
-const STANDARD_DESCRIPTION =
- 'Ask the user one or more multiple-choice questions when you need a decision you cannot ' +
- 'infer from the request or context and that has no obvious default. The conversation ' +
- 'pauses until the user answers, then continues with their choice in mind. Prefer this ' +
- 'over guessing on consequential or ambiguous decisions. Do NOT use it for information you ' +
- 'could look up with another tool, or for trivial choices with an obvious default. The ' +
- 'user can always type a free-form answer instead of picking an option.';
-
-const WORKSPACE_SETUP_DESCRIPTION =
- 'Ask the user one or more multiple-choice questions when a decision is theirs to make. ' +
- 'The conversation pauses until the user answers, then continues with their choice in ' +
- 'mind. Do NOT use it for information you could look up with another tool. The user can ' +
- 'always type a free-form answer instead of picking an option.';
-
-export const createAskQuestionsTool = ({
- isWorkspaceSetupThread,
-}: {
- isWorkspaceSetupThread: boolean;
-}) => ({
- description: isWorkspaceSetupThread
- ? WORKSPACE_SETUP_DESCRIPTION
- : STANDARD_DESCRIPTION,
- inputSchema: askQuestionsInputSchema,
- execute: async (input: AskQuestionsToolInput) =>
- buildAskQuestionsPendingOutput(input),
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts
index 297edcf6180..208e2e497c6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts
@@ -10,7 +10,7 @@ export const createRequestFormTool = () => ({
'Ask the user to fill in a form when you need typed values from them: text, numbers, dates, ' +
'options of an existing select field, or records picked from the workspace. The conversation ' +
'pauses until they submit it, then continues with the values keyed by field name. Prefer ' +
- 'ask_questions for a choice between a few options you can list yourself.',
+ 'ask_question for a choice between a few options you can list yourself.',
inputSchema: requestFormInputSchema,
execute: async (_input: RequestFormToolInput) =>
buildRequestFormPendingOutput(),
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
index 1fecf43b048..dc6cc7fdcc5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
@@ -24,26 +24,24 @@ const build = (toolCall: unknown) =>
});
describe('buildInboxMessageToolCallPart', () => {
- it('asks questions as a pending ask_questions call', async () => {
- const questions = [
- {
- header: 'Share',
- question: 'Share the recording?',
- options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
- },
- ];
+ it('asks a question as a pending ask_question call', async () => {
+ const question = {
+ header: 'Share',
+ question: 'Share the recording?',
+ options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
+ };
await expect(
- build({ toolName: 'ask_questions', input: { questions } }),
+ build({ toolName: 'ask_question', input: question }),
).resolves.toEqual({
isAwaitingAnswer: true,
part: {
- type: 'tool-ask_questions',
+ type: 'tool-ask_question',
toolCallId: TOOL_CALL_ID,
state: 'output-available',
- input: { questions },
+ input: question,
output: expect.objectContaining({
- result: { questions, status: 'pending' },
+ result: { question, status: 'pending' },
}),
},
});
@@ -171,12 +169,12 @@ describe('buildInboxMessageToolCallPart', () => {
},
},
],
- ['invalid input', { toolName: 'ask_questions', input: { questions: [] } }],
+ ['invalid input', { toolName: 'ask_question', input: { options: [] } }],
[
'a tool of another application',
{ logicFunctionUniversalIdentifier: 'other-tool' },
],
- ['a non-object tool call', 'ask_questions'],
+ ['a non-object tool call', 'ask_question'],
[
'an application tool with a non-object input',
{ logicFunctionUniversalIdentifier: 'share-recording-tool', input: [] },
@@ -191,7 +189,7 @@ describe('buildInboxMessageToolCallPart', () => {
[
'a tool call naming both a tool and an application tool',
{
- toolName: 'ask_questions',
+ toolName: 'ask_question',
logicFunctionUniversalIdentifier: 'share-recording-tool',
},
],
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-last-message-text.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-last-message-text.util.spec.ts
index aead6c4eab1..d695b235232 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-last-message-text.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-last-message-text.util.spec.ts
@@ -19,7 +19,7 @@ describe('findLastMessageText', () => {
findLastMessageText([
textPart('Draft ready'),
{
- type: 'tool-ask_questions',
+ type: 'tool-ask_question',
toolCallId: 'ask-1',
state: 'input-available',
input: {},
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-succeeded-workspace-setup-completion.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-succeeded-workspace-setup-completion.util.spec.ts
index a0ebe693024..a44055d713b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-succeeded-workspace-setup-completion.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-succeeded-workspace-setup-completion.util.spec.ts
@@ -58,7 +58,7 @@ describe('hasSucceededWorkspaceSetupCompletion', () => {
const messages = [
buildMessage([
{
- type: 'tool-ask_questions',
+ type: 'tool-ask_question',
toolCallId: 'call-1',
input: {},
state: 'output-available',
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
index faf137ad30e..04ef04a59d6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
@@ -1,6 +1,6 @@
import { isNonEmptyString } from '@sniptt/guards';
import {
- ASK_QUESTIONS_TOOL_NAME,
+ ASK_QUESTION_TOOL_NAME,
type ExtendedUIMessagePart,
PROPOSE_TOOL_CALL_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
@@ -12,9 +12,9 @@ import { buildToolPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/buil
import { buildLogicFunctionToolName } from 'src/engine/core-modules/tool-provider/utils/build-logic-function-tool-name.util';
import { type ResolveInboxProposal } from 'src/engine/metadata-modules/ai/ai-chat/types/resolve-inbox-proposal.type';
import {
- askQuestionsInputSchema,
- buildAskQuestionsPendingOutput,
-} from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool';
+ askQuestionInputSchema,
+ buildAskQuestionPendingOutput,
+} from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool';
import {
buildProposeToolCallPendingOutput,
proposeToolCallInputSchema,
@@ -74,14 +74,14 @@ const buildPausingToolPart = async ({
resolveProposal: ResolveInboxProposal;
}): Promise<ExtendedUIMessagePart> => {
switch (toolName) {
- case ASK_QUESTIONS_TOOL_NAME: {
- const questionsInput = parseInput(askQuestionsInputSchema, input);
+ case ASK_QUESTION_TOOL_NAME: {
+ const question = parseInput(askQuestionInputSchema, input);
return buildToolPart({
toolName,
toolCallId,
- input: questionsInput,
- output: buildAskQuestionsPendingOutput(questionsInput),
+ input: question,
+ output: buildAskQuestionPendingOutput(question),
});
}
case REQUEST_FORM_TOOL_NAME:
@@ -111,7 +111,7 @@ const buildPausingToolPart = async ({
}
default:
return throwInvalidToolCall(
- `toolName must be ${ASK_QUESTIONS_TOOL_NAME}, ${REQUEST_FORM_TOOL_NAME} or ${PROPOSE_TOOL_CALL_TOOL_NAME}`,
+ `toolName must be ${ASK_QUESTION_TOOL_NAME}, ${REQUEST_FORM_TOOL_NAME} or ${PROPOSE_TOOL_CALL_TOOL_NAME}`,
);
}
};
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
index efc12671985..ebbdec0c89d 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
@@ -26,7 +26,7 @@ import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-s
import { COMPANY_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/company-data-seeds.constant';
import { OPPORTUNITY_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/opportunity-data-seeds.constant';
import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
-import { askQuestionsCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/ask-questions-call.util';
+import { askQuestionCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/ask-question-call.util';
import { buildSendEmailArguments } from 'src/engine/workspace-manager/dev-seeder/data/utils/build-send-email-arguments.util';
import { proposeEmailCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/propose-email-call.util';
import { proposeRecordCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/propose-record-call.util';
@@ -219,7 +219,7 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [
askedBy: 'TIM',
prompt: 'Help me plan the Q3 customer webinar and draft the invitation.',
intro: 'Two choices before I draft the invitation:',
- calls: [askQuestionsCall(WEBINAR_QUESTIONS)],
+ calls: WEBINAR_QUESTIONS.map(askQuestionCall),
},
{
threadId:
@@ -261,11 +261,9 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [
askedBy: 'TIM',
prompt: 'Linear signed. Set up their onboarding.',
intro: 'One question before I create the onboarding tasks:',
- calls: [askQuestionsCall(ONBOARDING_OWNER_QUESTIONS)],
+ calls: ONBOARDING_OWNER_QUESTIONS.map(askQuestionCall),
answer: {
- response: {
- answers: [{ questionIndex: 0, selectedOptionIndices: [1] }],
- },
+ response: { selectedOptionIndices: [1] },
reply:
'Phil owns the Linear onboarding. I will create the kickoff, the SSO setup and the data import tasks for him.',
},
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
index 335887e39e0..741ad8ba16f 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
@@ -25,7 +25,7 @@ import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
-import { askQuestionsCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/ask-questions-call.util';
+import { askQuestionCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/ask-question-call.util';
import { proposeEmailCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/propose-email-call.util';
import { type SeededEmail } from 'src/engine/workspace-manager/dev-seeder/data/utils/seeded-email.type';
import { type SeededToolCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/seeded-tool-call.type';
@@ -124,7 +124,7 @@ type AgentWorkflowToSeed = {
runKey: string;
initiator: Initiator;
runPrompt: string;
- call: SeededToolCall;
+ calls: SeededToolCall[];
};
const AGENT_WORKFLOWS_TO_SEED: AgentWorkflowToSeed[] = [
@@ -142,7 +142,7 @@ const AGENT_WORKFLOWS_TO_SEED: AgentWorkflowToSeed[] = [
initiator: 'TIM',
runPrompt:
'Qualify the inbound lead from Figma and decide who should follow up.',
- call: askQuestionsCall(QUALIFICATION_QUESTIONS),
+ calls: QUALIFICATION_QUESTIONS.map(askQuestionCall),
},
{
key: 'draftRenewalReminder',
@@ -158,7 +158,7 @@ const AGENT_WORKFLOWS_TO_SEED: AgentWorkflowToSeed[] = [
initiator: 'PHIL',
runPrompt:
'Stripe renews on October 31. Draft the renewal reminder for their procurement team.',
- call: proposeEmailCall(RENEWAL_REMINDER_EMAIL),
+ calls: [proposeEmailCall(RENEWAL_REMINDER_EMAIL)],
},
];
@@ -251,12 +251,31 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
`workflowRun:${agentWorkflow.runKey}`,
workspaceId,
);
- const toolCallId = seedId(
- `toolCall:${agentWorkflow.runKey}`,
- workspaceId,
- );
- const { toolName, input } = agentWorkflow.call;
- const output = await agentWorkflow.call.buildPendingOutput();
+ const content = (
+ await Promise.all(
+ agentWorkflow.calls.map(async (call, callIndex) => {
+ const toolCallId = seedId(
+ callIndex === 0
+ ? `toolCall:${agentWorkflow.runKey}`
+ : `toolCall:${agentWorkflow.runKey}:${callIndex}`,
+ workspaceId,
+ );
+ const { toolName, input } = call;
+ const output = await call.buildPendingOutput();
+
+ return [
+ { type: 'tool-call' as const, toolCallId, toolName, input },
+ {
+ type: 'tool-result' as const,
+ toolCallId,
+ toolName,
+ input,
+ output,
+ },
+ ];
+ }),
+ )
+ ).flat();
await this.seedPausedRun({
workspaceId,
@@ -274,20 +293,7 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
initiatorUserWorkspaceId: null,
executionResult: {
isPaused: true,
- steps: [
- {
- content: [
- { type: 'tool-call', toolCallId, toolName, input },
- {
- type: 'tool-result',
- toolCallId,
- toolName,
- input,
- output,
- },
- ],
- },
- ],
+ steps: [{ content }],
},
}),
});
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/utils/ask-question-call.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/utils/ask-question-call.util.ts
new file mode 100644
index 00000000000..c03926990da
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/utils/ask-question-call.util.ts
@@ -0,0 +1,10 @@
+import { ASK_QUESTION_TOOL_NAME, type AskQuestionItem } from 'twenty-shared/ai';
+
+import { buildAskQuestionPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-question.pausing-tool';
+import { type SeededToolCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/seeded-tool-call.type';
+
+export const askQuestionCall = (question: AskQuestionItem): SeededToolCall => ({
+ toolName: ASK_QUESTION_TOOL_NAME,
+ input: question,
+ buildPendingOutput: async () => buildAskQuestionPendingOutput(question),
+});
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/utils/ask-questions-call.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/utils/ask-questions-call.util.ts
deleted file mode 100644
index 50fbae74869..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/utils/ask-questions-call.util.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import {
- ASK_QUESTIONS_TOOL_NAME,
- type AskQuestionItem,
-} from 'twenty-shared/ai';
-
-import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
-import { type SeededToolCall } from 'src/engine/workspace-manager/dev-seeder/data/utils/seeded-tool-call.type';
-
-export const askQuestionsCall = (
- questions: AskQuestionItem[],
-): SeededToolCall => ({
- toolName: ASK_QUESTIONS_TOOL_NAME,
- input: { questions },
- buildPendingOutput: () =>
- createAskQuestionsTool({ isWorkspaceSetupThread: false }).execute({
- questions,
- }),
-});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index fc832de680d..df844d7300c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -3,7 +3,7 @@ import { Injectable, Logger } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
import {
- ASK_QUESTIONS_TOOL_NAME,
+ ASK_QUESTION_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
} from 'twenty-shared/ai';
import { isDefined, resolveInput } from 'twenty-shared/utils';
@@ -13,7 +13,7 @@ import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/inte
import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
-import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
+import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
import { createRequestFormTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';
import { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/workflow-base-system-prompt.const';
import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';
@@ -167,7 +167,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
: WORKFLOW_BASE_SYSTEM_PROMPT,
pausingTools: canAskForHumanInput
? {
- [ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({
+ [ASK_QUESTION_TOOL_NAME]: createAskQuestionTool({
isWorkspaceSetupThread: false,
}),
[REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant.ts
index d7286b6e52d..f7564a4699e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant.ts
@@ -1 +1 @@
-export const WORKFLOW_AGENT_HUMAN_INPUT_PROMPT = `You run inside a workflow, with nobody watching as you work. You can stop and ask the person who owns the workflow for input: the workflow pauses until they answer in their inbox, then you continue with their answer. Call ask_questions for a decision or a fact only a person can give, request_form for typed values such as a date, an amount or a record to pick, and propose_tool_call with the tool and arguments you would have used for an action they must approve first: they approve it, possibly with edits, or reject it with feedback, and you get the result. An email they must review is proposed as a send_email call they can edit, send, save as a draft or discard. Ask everything you need in one call, and never ask about what you can find or decide yourself. Stop for input only as the workflow's instructions below say:`;
+export const WORKFLOW_AGENT_HUMAN_INPUT_PROMPT = `You run inside a workflow, with nobody watching as you work. You can stop and ask the person who owns the workflow for input: the workflow pauses until they answer in their inbox, then you continue with their answer. Call ask_question for a decision or a fact only a person can give, request_form for typed values such as a date, an amount or a record to pick, and propose_tool_call with the tool and arguments you would have used for an action they must approve first: they approve it, possibly with edits, or reject it with feedback, and you get the result. An email they must review is proposed as a send_email call they can edit, send, save as a draft or discard. Ask everything you need at once, with one ask_question call per question, and never ask about what you can find or decide yourself. Stop for input only as the workflow's instructions below say:`;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/merge-ai-agent-step-logs.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/merge-ai-agent-step-logs.util.spec.ts
index 6a48d5475bc..2220164b3d2 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/merge-ai-agent-step-logs.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/merge-ai-agent-step-logs.util.spec.ts
@@ -41,7 +41,7 @@ describe('mergeAiAgentStepLogs', () => {
previousStepLog: buildAgentStepLog({
modelId: 'model-a',
tokens: 10,
- toolCallNames: ['search', 'ask_questions'],
+ toolCallNames: ['search', 'ask_question'],
durationMs: 100,
}),
nextStepLog: buildAgentStepLog({
@@ -68,7 +68,7 @@ describe('mergeAiAgentStepLogs', () => {
merged.details.type === 'AI_AGENT'
? merged.details.toolCalls.map(({ toolName }) => toolName)
: [],
- ).toEqual(['search', 'ask_questions', 'send_email']);
+ ).toEqual(['search', 'ask_question', 'send_email']);
});
it('keeps the new log when there is nothing before it', () => {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
index 9d9261d1624..69c0b28b377 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
@@ -32,9 +32,9 @@ describe('WorkflowRunWorkspaceService conversations', () => {
find: jest.fn().mockResolvedValue([
{
id: 'part-id',
- toolName: 'ask_questions',
- toolInput: { questions: QUESTIONS },
- toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
+ toolName: 'ask_question',
+ toolInput: QUESTIONS[0],
+ toolOutput: { result: { question: QUESTIONS[0], status: 'pending' } },
},
]),
writePart: jest.fn(),
@@ -282,7 +282,7 @@ describe('WorkflowRunWorkspaceService conversations', () => {
expectedStatus,
}).toEqual({
partId: 'part-id',
- result: { questions: QUESTIONS, status: 'skipped' },
+ result: { question: QUESTIONS[0], status: 'skipped' },
expectedStatus: 'pending',
});
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts
index bf0bf905e64..dcac7282ef7 100644
--- a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts
@@ -380,17 +380,17 @@ describe('Admin panel global chat threads (integration)', () => {
await insertPart({
messageId: answeredQuestionMessageId,
orderIndex: 0,
- type: 'tool-ask_questions',
- toolName: 'ask_questions',
- toolCallId: 'call-answered-questions',
- toolInput: { questions: questionItems },
+ type: 'tool-ask_question',
+ toolName: 'ask_question',
+ toolCallId: 'call-answered-question',
+ toolInput: questionItems[0],
toolOutput: {
success: true,
- message: 'User answered the questions.',
+ message: 'User answered the question.',
result: {
- questions: questionItems,
+ question: questionItems[0],
status: 'answered',
- answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
+ answer: { selectedOptionIndices: [0] },
},
},
state: 'output-available',
diff --git a/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
index 104e44c1080..50078955029 100644
--- a/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
@@ -12,7 +12,7 @@ import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-q
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
-import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
+import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
import { type AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
@@ -27,13 +27,11 @@ const schema = getWorkspaceSchemaName(workspaceId);
const workspaceMemberId = WORKSPACE_MEMBER_DATA_SEED_IDS.JANE;
const userWorkspaceId = USER_WORKSPACE_DATA_SEED_IDS.JANE;
-const QUESTIONS = [
- {
- header: 'Plan',
- question: 'Which plan should I quote?',
- options: [{ label: 'Pro' }, { label: 'Team' }],
- },
-];
+const QUESTION = {
+ header: 'Plan',
+ question: 'Which plan should I quote?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+};
describe('Answering a chat tool call', () => {
const threadId = randomUUID();
@@ -53,9 +51,9 @@ describe('Answering a chat tool call', () => {
});
const assistantMessageId = randomUUID();
- const pendingOutput = await createAskQuestionsTool({
+ const pendingOutput = await createAskQuestionTool({
isWorkspaceSetupThread: false,
- }).execute({ questions: QUESTIONS });
+ }).execute(QUESTION);
await chat.upsertAssistantMessage({
id: assistantMessageId,
@@ -63,10 +61,10 @@ describe('Answering a chat tool call', () => {
turnId: userMessage.turnId,
workspaceId,
parts: toolCallIds.map((toolCallId) => ({
- type: 'tool-ask_questions',
+ type: 'tool-ask_question',
toolCallId,
state: 'output-available',
- input: { questions: QUESTIONS },
+ input: QUESTION,
output: pendingOutput,
})) as never,
});
@@ -82,7 +80,7 @@ describe('Answering a chat tool call', () => {
const answerQuestions = (toolCallId: string) =>
answerToolCall({
toolCall: { threadId, toolCallId },
- response: { answers: [{ questionIndex: 0, selectedOptionIndices: [1] }] },
+ response: { selectedOptionIndices: [1] },
});
const readPendingQuestionMessageId = async () =>
@@ -211,6 +209,35 @@ describe('Answering a chat tool call', () => {
);
});
+ it('answers the questions of a step in any order', async () => {
+ await pauseOnQuestions(
+ 'unordered-first',
+ 'unordered-middle',
+ 'unordered-last',
+ );
+ enqueueStream.mockClear();
+
+ const middle = await answerQuestions('unordered-middle');
+
+ expect(middle.body.errors).toBeUndefined();
+ expect(middle.body.data.answerToolCall.streamId).toBeNull();
+ expect(await readToolCallStatus('unordered-first')).toBe('pending');
+ expect(await readToolCallStatus('unordered-middle')).toBe('answered');
+
+ const last = await answerQuestions('unordered-last');
+
+ expect(last.body.errors).toBeUndefined();
+ expect(await readToolCallStatus('unordered-last')).toBe('answered');
+ expect(await readToolCallStatus('unordered-first')).toBe('pending');
+
+ const first = await answerQuestions('unordered-first');
+
+ expect(first.body.errors).toBeUndefined();
+ expect(first.body.data.answerToolCall.streamId).toEqual(expect.any(String));
+ expect(await readPendingQuestionMessageId()).toBeNull();
+ expect(enqueueStream).toHaveBeenCalledTimes(1);
+ });
+
it('closes every pending call when a message is sent instead of the answers', async () => {
await pauseOnQuestions('call-skipped-first', 'call-skipped-last');
diff --git a/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
index c8d7c5f2678..9f30433b310 100644
--- a/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
@@ -36,13 +36,11 @@ const SEND_INBOX_MESSAGE = parse(`
}
`);
-const QUESTIONS = [
- {
- header: 'Share',
- question: 'Do you want to share it with the other attendees?',
- options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
- },
-];
+const QUESTION = {
+ header: 'Share',
+ question: 'Do you want to share it with the other attendees?',
+ options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
+};
// The model is not called here: the resumed stream is only checked for being
// queued.
@@ -53,7 +51,7 @@ describe('Sending an inbox message as an application', () => {
idempotencyKey: 'first-recording',
title: 'Your first call recording is ready',
text: 'Your first call was recorded: **Weekly sync**.',
- toolCall: { toolName: 'ask_questions', input: { questions: QUESTIONS } },
+ toolCall: { toolName: 'ask_question', input: QUESTION },
};
let application: ApplicationWithResources;
let applicationToken: string;
@@ -365,9 +363,7 @@ describe('Sending an inbox message as an application', () => {
threadId,
toolCallId: `call_${pendingQuestionMessageId!.replace(/-/g, '')}`,
},
- response: {
- answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
- },
+ response: { selectedOptionIndices: [0] },
});
expect(response.body.errors).toBeUndefined();
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
index 2d81b81f03e..0d5be7a39d5 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
@@ -1062,13 +1062,11 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
});
describe('an agent step that asks a question', () => {
- const QUESTIONS = [
- {
- header: 'Quote',
- question: 'Send the quote to the customer?',
- options: [{ label: 'Send it' }, { label: 'Hold it' }],
- },
- ];
+ const QUESTION = {
+ header: 'Quote',
+ question: 'Send the quote to the customer?',
+ options: [{ label: 'Send it' }, { label: 'Hold it' }],
+ };
const agentStep = (nextStepIds: string[]): WorkflowAction =>
({
@@ -1106,19 +1104,19 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
{
type: 'tool-call',
toolCallId: 'ask-1',
- toolName: 'ask_questions',
- input: { questions: QUESTIONS },
+ toolName: 'ask_question',
+ input: QUESTION,
},
{
type: 'tool-result',
toolCallId: 'ask-1',
- toolName: 'ask_questions',
- input: { questions: QUESTIONS },
+ toolName: 'ask_question',
+ input: QUESTION,
output: {
success: true,
message:
- 'Questions presented to the user; awaiting their answer.',
- result: { questions: QUESTIONS, status: 'pending' },
+ 'Question presented to the user; awaiting their answer.',
+ result: { question: QUESTION, status: 'pending' },
},
},
],
@@ -1150,7 +1148,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
[threadId],
);
const parts = await global.testDataSource.query(
- `SELECT part."toolCallId", part."toolOutput" FROM "${schema}"."agentMessagePart" part JOIN "${schema}"."agentMessage" message ON message.id = part."messageId" WHERE message."threadId" = $1 AND part."toolName" = 'ask_questions' ORDER BY part."toolCallId"`,
+ `SELECT part."toolCallId", part."toolOutput" FROM "${schema}"."agentMessagePart" part JOIN "${schema}"."agentMessage" message ON message.id = part."messageId" WHERE message."threadId" = $1 AND part."toolName" = 'ask_question' ORDER BY part."toolCallId"`,
[threadId],
);
@@ -1163,7 +1161,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
}) => ({
toolCallId: part.toolCallId,
status: part.toolOutput.result.status,
- answers: part.toolOutput.result.answers,
+ answer: part.toolOutput.result.answer,
}),
),
};
@@ -1203,9 +1201,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
}) =>
answerToolCall({
toolCall: { threadId, toolCallId },
- response: {
- answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
- },
+ response: { selectedOptionIndices: [0] },
});
it('records no conversation for an agent that answers without asking', async () => {
@@ -1437,7 +1433,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
{
toolCallId: 'ask-1',
status: 'answered',
- answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
+ answer: { selectedOptionIndices: [0] },
},
],
});
@@ -1471,18 +1467,18 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
{
type: 'tool-call',
toolCallId,
- toolName: 'ask_questions',
- input: { questions: QUESTIONS },
+ toolName: 'ask_question',
+ input: QUESTION,
},
{
type: 'tool-result',
toolCallId,
- toolName: 'ask_questions',
- input: { questions: QUESTIONS },
+ toolName: 'ask_question',
+ input: QUESTION,
output: {
success: true,
- message: 'Questions presented to the user; awaiting their answer.',
- result: { questions: QUESTIONS, status: 'pending' },
+ message: 'Question presented to the user; awaiting their answer.',
+ result: { question: QUESTION, status: 'pending' },
},
},
];
diff --git a/packages/twenty-shared/src/ai/constants/ask-question-tool-name.const.ts b/packages/twenty-shared/src/ai/constants/ask-question-tool-name.const.ts
new file mode 100644
index 00000000000..063a3ae7b9d
--- /dev/null
+++ b/packages/twenty-shared/src/ai/constants/ask-question-tool-name.const.ts
@@ -0,0 +1 @@
+export const ASK_QUESTION_TOOL_NAME = 'ask_question';
diff --git a/packages/twenty-shared/src/ai/constants/ask-questions-tool-name.const.ts b/packages/twenty-shared/src/ai/constants/ask-questions-tool-name.const.ts
index 585282faf56..3a4fa0233c0 100644
--- a/packages/twenty-shared/src/ai/constants/ask-questions-tool-name.const.ts
+++ b/packages/twenty-shared/src/ai/constants/ask-questions-tool-name.const.ts
@@ -1 +1,2 @@
+// calls asked before ask_question took one question at a time
export const ASK_QUESTIONS_TOOL_NAME = 'ask_questions';
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index 3cd873f44b8..2b72b6ae8b4 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -17,6 +17,7 @@ export { AI_MODEL_TIERS } from './constants/ai-model-tier.const';
export { AI_SDK_PACKAGE_LABELS } from './constants/ai-sdk-package-labels.const';
export type { AiSdkPackage } from './constants/ai-sdk-packages.const';
export { AI_SDK_PACKAGES } from './constants/ai-sdk-packages.const';
+export { ASK_QUESTION_TOOL_NAME } from './constants/ask-question-tool-name.const';
export { ASK_QUESTIONS_TOOL_NAME } from './constants/ask-questions-tool-name.const';
export { ATTACH_CONVERSATION_TO_RECORD_TOOL_NAME } from './constants/attach-conversation-to-record-tool-name.const';
export type { AutoSelectModelId } from './constants/auto-select-model-id-by-tier.const';
@@ -49,9 +50,12 @@ export type {
export type { AskQuestionAnswer } from './types/AskQuestionAnswer';
export type { AskQuestionItem } from './types/AskQuestionItem';
export type { AskQuestionOption } from './types/AskQuestionOption';
+export type { AskQuestionResponse } from './types/AskQuestionResponse';
export type { AskQuestionsToolInput } from './types/AskQuestionsToolInput';
export type { AskQuestionsToolResult } from './types/AskQuestionsToolResult';
-export type { AskQuestionsToolStatus } from './types/AskQuestionsToolStatus';
+export type { AskQuestionToolInput } from './types/AskQuestionToolInput';
+export type { AskQuestionToolResult } from './types/AskQuestionToolResult';
+export type { AskQuestionToolStatus } from './types/AskQuestionToolStatus';
export type {
CodeExecutionFile,
ExtendedFileUIPart,
diff --git a/packages/twenty-shared/src/ai/types/AskQuestionResponse.ts b/packages/twenty-shared/src/ai/types/AskQuestionResponse.ts
new file mode 100644
index 00000000000..8d7e1008ea6
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/AskQuestionResponse.ts
@@ -0,0 +1,4 @@
+export type AskQuestionResponse = {
+ selectedOptionIndices: number[];
+ freeText?: string;
+};
diff --git a/packages/twenty-shared/src/ai/types/AskQuestionToolInput.ts b/packages/twenty-shared/src/ai/types/AskQuestionToolInput.ts
new file mode 100644
index 00000000000..53b1b4dcf3c
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/AskQuestionToolInput.ts
@@ -0,0 +1,3 @@
+import { type AskQuestionItem } from '@/ai/types/AskQuestionItem';
+
+export type AskQuestionToolInput = AskQuestionItem;
diff --git a/packages/twenty-shared/src/ai/types/AskQuestionToolResult.ts b/packages/twenty-shared/src/ai/types/AskQuestionToolResult.ts
new file mode 100644
index 00000000000..b6b11bfebd6
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/AskQuestionToolResult.ts
@@ -0,0 +1,9 @@
+import { type AskQuestionItem } from '@/ai/types/AskQuestionItem';
+import { type AskQuestionResponse } from '@/ai/types/AskQuestionResponse';
+import { type AskQuestionToolStatus } from '@/ai/types/AskQuestionToolStatus';
+
+export type AskQuestionToolResult = {
+ question: AskQuestionItem;
+ status: AskQuestionToolStatus;
+ answer?: AskQuestionResponse;
+};
diff --git a/packages/twenty-shared/src/ai/types/AskQuestionToolStatus.ts b/packages/twenty-shared/src/ai/types/AskQuestionToolStatus.ts
new file mode 100644
index 00000000000..b8487e540fe
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/AskQuestionToolStatus.ts
@@ -0,0 +1 @@
+export type AskQuestionToolStatus = 'pending' | 'answered' | 'skipped';
diff --git a/packages/twenty-shared/src/ai/types/AskQuestionsToolResult.ts b/packages/twenty-shared/src/ai/types/AskQuestionsToolResult.ts
index 6af48062289..6ba5d29d057 100644
--- a/packages/twenty-shared/src/ai/types/AskQuestionsToolResult.ts
+++ b/packages/twenty-shared/src/ai/types/AskQuestionsToolResult.ts
@@ -1,9 +1,10 @@
import { type AskQuestionAnswer } from '@/ai/types/AskQuestionAnswer';
import { type AskQuestionItem } from '@/ai/types/AskQuestionItem';
-import { type AskQuestionsToolStatus } from '@/ai/types/AskQuestionsToolStatus';
+import { type AskQuestionToolStatus } from '@/ai/types/AskQuestionToolStatus';
+// calls asked before ask_question took one question at a time
export type AskQuestionsToolResult = {
questions: AskQuestionItem[];
- status: AskQuestionsToolStatus;
+ status: AskQuestionToolStatus;
answers?: AskQuestionAnswer[];
};
diff --git a/packages/twenty-shared/src/ai/types/AskQuestionsToolStatus.ts b/packages/twenty-shared/src/ai/types/AskQuestionsToolStatus.ts
deleted file mode 100644
index aa8da494538..00000000000
--- a/packages/twenty-shared/src/ai/types/AskQuestionsToolStatus.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type AskQuestionsToolStatus = 'pending' | 'answered' | 'skipped';
diff --git a/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts b/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
index da4cc95840d..e701b55fccb 100644
--- a/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
+++ b/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
@@ -1,11 +1,11 @@
-import { type AskQuestionsToolInput } from '@/ai/types/AskQuestionsToolInput';
+import { type AskQuestionToolInput } from '@/ai/types/AskQuestionToolInput';
import { type ProposeToolCallToolInput } from '@/ai/types/ProposeToolCallToolInput';
import { type RequestFormToolInput } from '@/ai/types/RequestFormToolInput';
export type SendInboxMessageToolCall =
| {
- toolName: 'ask_questions';
- input: AskQuestionsToolInput;
+ toolName: 'ask_question';
+ input: AskQuestionToolInput;
logicFunctionUniversalIdentifier?: never;
}
| {