Skip to content

The open alternative to Salesforce, designed for AI.

Show ask_questions as a readable Q&A card in the admin chat viewer (#24281)

Raphaël Bosi9335d903d55e
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatAskQuestionsPart.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatAskQuestionsPart.tsx
new file mode 100644
index 00000000000..eb0198c3cc6
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatAskQuestionsPart.tsx
@@ -0,0 +1,107 @@
+import { t } from '@lingui/core/macro';
+import { styled } from '@linaria/react';
+
+import { Tag, type TagColor } from 'twenty-ui/data-display';
+import { IconHelpCircle } from 'twenty-ui/icon';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+import { SettingsAdminChatAskQuestionsQuestion } from '@/settings/admin-panel/components/SettingsAdminChatAskQuestionsQuestion';
+import { SettingsAdminChatToolCallPart } from '@/settings/admin-panel/components/SettingsAdminChatToolCallPart';
+import { type AdminAskQuestionsResult } from '@/settings/admin-panel/types/AdminAskQuestionsResult';
+import { type AdminChatThreadMessagePart } from '@/settings/admin-panel/types/AdminChatThreadMessagePart';
+
+type SettingsAdminChatAskQuestionsPartProps = {
+ part: AdminChatThreadMessagePart;
+ result: AdminAskQuestionsResult;
+};
+
+const StyledContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[2]};
+ width: 100%;
+`;
+
+const StyledCard = styled.div`
+ background-color: ${themeCssVariables.background.transparent.lighter};
+ border: 1px solid ${themeCssVariables.border.color.medium};
+ border-radius: ${themeCssVariables.border.radius.sm};
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[4]};
+ padding: ${themeCssVariables.spacing[3]};
+`;
+
+const StyledCardHeader = styled.div`
+ align-items: center;
+ color: ${themeCssVariables.font.color.tertiary};
+ display: flex;
+ font-size: ${themeCssVariables.font.size.md};
+ font-weight: ${themeCssVariables.font.weight.medium};
+ gap: ${themeCssVariables.spacing[1]};
+
+ svg {
+ flex-shrink: 0;
+ }
+`;
+
+const StyledStatusTag = styled.div`
+ margin-left: auto;
+`;
+
+const getStatusLabel = (status: string) => {
+ switch (status) {
+ case 'answered':
+ return t`Answered`;
+ case 'skipped':
+ return t`Skipped`;
+ case 'pending':
+ return t`Unanswered`;
+ default:
+ return status;
+ }
+};
+
+const getStatusTagColor = (status: string): TagColor => {
+ switch (status) {
+ case 'answered':
+ return 'green';
+ case 'skipped':
+ return 'gray';
+ case 'pending':
+ return 'orange';
+ default:
+ return 'gray';
+ }
+};
+
+export const SettingsAdminChatAskQuestionsPart = ({
+ part,
+ result,
+}: SettingsAdminChatAskQuestionsPartProps) => (
+ <StyledContainer>
+ <StyledCard>
+ <StyledCardHeader>
+ <IconHelpCircle size={14} />
+ {t`Questions`}
+ <StyledStatusTag>
+ <Tag
+ color={getStatusTagColor(result.status)}
+ text={getStatusLabel(result.status)}
+ />
+ </StyledStatusTag>
+ </StyledCardHeader>
+ {result.questions.map((question, questionIndex) => (
+ <SettingsAdminChatAskQuestionsQuestion
+ key={questionIndex}
+ question={question}
+ answer={result.answers?.find(
+ (answer) => answer.questionIndex === questionIndex,
+ )}
+ />
+ ))}
+ </StyledCard>
+ <SettingsAdminChatToolCallPart part={part} />
+ </StyledContainer>
+);
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatAskQuestionsQuestion.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatAskQuestionsQuestion.tsx
new file mode 100644
index 00000000000..854bd11dbc9
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatAskQuestionsQuestion.tsx
@@ -0,0 +1,145 @@
+import { t } from '@lingui/core/macro';
+import { styled } from '@linaria/react';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { type AskQuestionAnswer, type AskQuestionItem } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+import { Tag } from 'twenty-ui/data-display';
+import { IconCheck } from 'twenty-ui/icon';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';
+
+type SettingsAdminChatAskQuestionsQuestionProps = {
+ question: AskQuestionItem;
+ answer: AskQuestionAnswer | undefined;
+};
+
+const StyledContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[2]};
+`;
+
+const StyledHeaderRow = styled.div`
+ align-items: center;
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+`;
+
+const StyledMultiSelectHint = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ font-size: ${themeCssVariables.font.size.xs};
+`;
+
+const StyledQuestionText = styled.p`
+ color: ${themeCssVariables.font.color.primary};
+ font-size: ${themeCssVariables.font.size.md};
+ font-weight: ${themeCssVariables.font.weight.medium};
+ line-height: 1.4;
+ margin: 0;
+ overflow-wrap: anywhere;
+`;
+
+const StyledOptionsList = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing['0.5']};
+`;
+
+const StyledOptionRow = styled.div<{ isSelected: boolean }>`
+ background: ${({ isSelected }) =>
+ isSelected
+ ? themeCssVariables.background.transparent.light
+ : 'transparent'};
+ border-radius: ${themeCssVariables.border.radius.sm};
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing['0.5']};
+ padding: ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[2]};
+`;
+
+const StyledOptionLabelRow = styled.div`
+ align-items: center;
+ color: ${themeCssVariables.font.color.secondary};
+ display: flex;
+ font-size: ${themeCssVariables.font.size.md};
+ gap: ${themeCssVariables.spacing[1]};
+ line-height: 1.4;
+ overflow-wrap: anywhere;
+
+ svg {
+ color: ${themeCssVariables.color.blue};
+ flex-shrink: 0;
+ }
+`;
+
+const StyledRecommended = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ flex-shrink: 0;
+`;
+
+const StyledOptionDescription = styled.span`
+ color: ${themeCssVariables.font.color.tertiary};
+ font-size: ${themeCssVariables.font.size.sm};
+ line-height: 1.4;
+ overflow-wrap: anywhere;
+`;
+
+export const SettingsAdminChatAskQuestionsQuestion = ({
+ question,
+ answer,
+}: SettingsAdminChatAskQuestionsQuestionProps) => {
+ const selectedOptionIndices = new Set(answer?.selectedOptionIndices ?? []);
+ const freeText = answer?.freeText ?? '';
+
+ return (
+ <StyledContainer>
+ <StyledHeaderRow>
+ {isNonEmptyString(question.header) && (
+ <Tag color="transparent" text={question.header} variant="border" />
+ )}
+ {question.allowMultiSelect === true && (
+ <StyledMultiSelectHint>{t`Multiple answers`}</StyledMultiSelectHint>
+ )}
+ </StyledHeaderRow>
+ <StyledQuestionText>
+ <TextWithChatReferences text={question.question} />
+ </StyledQuestionText>
+ <StyledOptionsList>
+ {question.options.map((option, optionIndex) => {
+ const isSelected = selectedOptionIndices.has(optionIndex);
+
+ return (
+ <StyledOptionRow key={optionIndex} isSelected={isSelected}>
+ <StyledOptionLabelRow>
+ {isSelected && <IconCheck size={14} />}
+ <TextWithChatReferences text={option.label} />
+ {option.isRecommended === true && (
+ <StyledRecommended>· {t`Recommended`}</StyledRecommended>
+ )}
+ </StyledOptionLabelRow>
+ {isDefined(option.description) && (
+ <StyledOptionDescription>
+ <TextWithChatReferences text={option.description} />
+ </StyledOptionDescription>
+ )}
+ </StyledOptionRow>
+ );
+ })}
+ {isNonEmptyString(freeText) && (
+ <StyledOptionRow isSelected>
+ <StyledOptionLabelRow>
+ <IconCheck size={14} />
+ {t`Other`}
+ </StyledOptionLabelRow>
+ <StyledOptionDescription>
+ <TextWithChatReferences text={freeText} />
+ </StyledOptionDescription>
+ </StyledOptionRow>
+ )}
+ </StyledOptionsList>
+ </StyledContainer>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatMessagePartRenderer.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatMessagePartRenderer.tsx
index 0a235041783..f4033dbeef2 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatMessagePartRenderer.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminChatMessagePartRenderer.tsx
@@ -2,12 +2,15 @@ import { t } from '@lingui/core/macro';
import { styled } from '@linaria/react';
import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { LazyMarkdownRenderer } from '@/ai/components/LazyMarkdownRenderer';
+import { SettingsAdminChatAskQuestionsPart } from '@/settings/admin-panel/components/SettingsAdminChatAskQuestionsPart';
import { SettingsAdminChatCollapsibleSection } from '@/settings/admin-panel/components/SettingsAdminChatCollapsibleSection';
import { SettingsAdminChatToolCallPart } from '@/settings/admin-panel/components/SettingsAdminChatToolCallPart';
import { type AdminChatThreadMessagePart } from '@/settings/admin-panel/types/AdminChatThreadMessagePart';
+import { parseAdminAskQuestionsResult } from '@/settings/admin-panel/utils/parseAdminAskQuestionsResult';
type SettingsAdminChatMessagePartRendererProps = {
part: AdminChatThreadMessagePart;
@@ -69,5 +72,16 @@ export const SettingsAdminChatMessagePartRenderer = ({
);
}
+ const askQuestionsResult = parseAdminAskQuestionsResult(part);
+
+ if (isDefined(askQuestionsResult)) {
+ return (
+ <SettingsAdminChatAskQuestionsPart
+ part={part}
+ result={askQuestionsResult}
+ />
+ );
+ }
+
return <SettingsAdminChatToolCallPart part={part} />;
};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/__stories__/SettingsAdminChatAskQuestionsPart.stories.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/__stories__/SettingsAdminChatAskQuestionsPart.stories.tsx
new file mode 100644
index 00000000000..32a75028658
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/__stories__/SettingsAdminChatAskQuestionsPart.stories.tsx
@@ -0,0 +1,135 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, within } from 'storybook/test';
+import { type AskQuestionsToolResult } from 'twenty-shared/ai';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { SettingsAdminChatAskQuestionsPart } from '@/settings/admin-panel/components/SettingsAdminChatAskQuestionsPart';
+import { type AdminChatThreadMessagePart } from '@/settings/admin-panel/types/AdminChatThreadMessagePart';
+import { SnackBarDecorator } from '~/testing/decorators/SnackBarDecorator';
+
+const QUESTIONS = [
+ {
+ 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' },
+ ],
+ },
+ {
+ header: 'Channels',
+ question: 'Which channels does your team rely on?',
+ options: [
+ { label: 'Email', description: 'Gmail or Outlook mailboxes.' },
+ { label: 'Calendar' },
+ { label: 'Phone' },
+ ],
+ allowMultiSelect: true,
+ },
+];
+
+const buildPart = (
+ result: AskQuestionsToolResult,
+): AdminChatThreadMessagePart =>
+ ({
+ type: 'tool-ask_questions',
+ orderIndex: 0,
+ toolName: 'ask_questions',
+ toolCallId: 'call-1',
+ toolInput: { questions: result.questions },
+ toolOutput: { success: true, message: 'Questions presented.', result },
+ state: 'output-available',
+ errorMessage: null,
+ textContent: null,
+ reasoningContent: null,
+ }) as AdminChatThreadMessagePart;
+
+const meta: Meta<typeof SettingsAdminChatAskQuestionsPart> = {
+ title: 'Modules/Settings/AdminPanel/SettingsAdminChatAskQuestionsPart',
+ component: SettingsAdminChatAskQuestionsPart,
+ decorators: [SnackBarDecorator, ComponentDecorator],
+ parameters: { container: { width: 700 } },
+ argTypes: { part: { control: false }, result: { control: false } },
+};
+
+export default meta;
+type Story = StoryObj<typeof SettingsAdminChatAskQuestionsPart>;
+
+const answeredResult: AskQuestionsToolResult = {
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [
+ { questionIndex: 0, selectedOptionIndices: [1] },
+ { questionIndex: 1, selectedOptionIndices: [0, 2] },
+ ],
+};
+
+const freeTextResult: AskQuestionsToolResult = {
+ questions: [QUESTIONS[0]],
+ status: 'answered',
+ answers: [
+ {
+ questionIndex: 0,
+ selectedOptionIndices: [],
+ freeText: 'A re-engagement email for churned customers.',
+ },
+ ],
+};
+
+const pendingResult: AskQuestionsToolResult = {
+ questions: [QUESTIONS[0]],
+ status: 'pending',
+};
+
+export const Answered: Story = {
+ args: { part: buildPart(answeredResult), result: answeredResult },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(await canvas.findByText('Answered')).toBeInTheDocument();
+
+ for (const question of QUESTIONS) {
+ expect(await canvas.findByText(question.question)).toBeInTheDocument();
+ expect(await canvas.findByText(question.header)).toBeInTheDocument();
+
+ for (const option of question.options) {
+ expect(await canvas.findByText(option.label)).toBeInTheDocument();
+ }
+ }
+
+ expect(
+ await canvas.findByText('A short, friendly note to introduce yourself.'),
+ ).toBeInTheDocument();
+ expect(await canvas.findByText('· Recommended')).toBeInTheDocument();
+ expect(await canvas.findByText('Multiple answers')).toBeInTheDocument();
+ },
+};
+
+export const AnsweredWithFreeText: Story = {
+ args: { part: buildPart(freeTextResult), result: freeTextResult },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(await canvas.findByText('Other')).toBeInTheDocument();
+ expect(
+ await canvas.findByText('A re-engagement email for churned customers.'),
+ ).toBeInTheDocument();
+ },
+};
+
+export const Unanswered: Story = {
+ args: { part: buildPart(pendingResult), result: pendingResult },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(await canvas.findByText('Unanswered')).toBeInTheDocument();
+ expect(
+ await canvas.findByText('A presentation of Twenty'),
+ ).toBeInTheDocument();
+ },
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/types/AdminAskQuestionsResult.ts b/packages/twenty-front/src/modules/settings/admin-panel/types/AdminAskQuestionsResult.ts
new file mode 100644
index 00000000000..285e791f4d0
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/types/AdminAskQuestionsResult.ts
@@ -0,0 +1,7 @@
+import { type AskQuestionAnswer, type AskQuestionItem } from 'twenty-shared/ai';
+
+export type AdminAskQuestionsResult = {
+ questions: AskQuestionItem[];
+ status: string;
+ answers?: AskQuestionAnswer[];
+};
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
new file mode 100644
index 00000000000..a7a50b2c475
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/parseAdminAskQuestionsResult.test.ts
@@ -0,0 +1,229 @@
+import { type AdminChatThreadMessagePart } from '@/settings/admin-panel/types/AdminChatThreadMessagePart';
+import { parseAdminAskQuestionsResult } from '@/settings/admin-panel/utils/parseAdminAskQuestionsResult';
+
+const QUESTIONS = [
+ {
+ header: 'Email type',
+ question: 'Which mailbox should we sync?',
+ options: [
+ { label: 'Work', description: 'Your company inbox', isRecommended: true },
+ { label: 'Personal' },
+ ],
+ allowMultiSelect: false,
+ },
+];
+
+const buildPart = (
+ part: Partial<AdminChatThreadMessagePart>,
+): AdminChatThreadMessagePart =>
+ ({
+ type: 'tool-ask_questions',
+ toolName: 'ask_questions',
+ toolInput: null,
+ toolOutput: null,
+ ...part,
+ }) as AdminChatThreadMessagePart;
+
+describe('parseAdminAskQuestionsResult', () => {
+ it('should parse an answered tool output', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: {
+ success: true,
+ message: 'User answered the questions.',
+ result: {
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [
+ {
+ questionIndex: 0,
+ selectedOptionIndices: [0],
+ freeText: 'Both',
+ },
+ ],
+ },
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [
+ { questionIndex: 0, selectedOptionIndices: [0], freeText: 'Both' },
+ ],
+ });
+ });
+
+ it('should parse a pending tool output without answers', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
+ }),
+ );
+
+ expect(result?.status).toBe('pending');
+ expect(result?.answers).toBeUndefined();
+ });
+
+ it('should fall back to the tool input when there is no output', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({ toolInput: { questions: QUESTIONS } }),
+ );
+
+ expect(result).toEqual({ questions: QUESTIONS, status: 'pending' });
+ });
+
+ it('should parse a JSON string tool output', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: JSON.stringify({
+ result: { questions: QUESTIONS, status: 'answered', answers: [] },
+ }),
+ }),
+ );
+
+ expect(result?.questions).toEqual(QUESTIONS);
+ });
+
+ it('should preserve an unrecognized status', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: { result: { questions: QUESTIONS, status: 'whatever' } },
+ }),
+ );
+
+ expect(result?.status).toBe('whatever');
+ });
+
+ it('should default to pending when the status is missing', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({ toolOutput: { result: { questions: QUESTIONS } } }),
+ );
+
+ expect(result?.status).toBe('pending');
+ });
+
+ it('should return null when an option index is out of range', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: {
+ result: {
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [{ questionIndex: 0, selectedOptionIndices: [5] }],
+ },
+ },
+ }),
+ );
+
+ expect(result).toBeNull();
+ });
+
+ it('should return null when an option index is not a number', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: {
+ result: {
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [{ questionIndex: 0, selectedOptionIndices: [0, null] }],
+ },
+ },
+ }),
+ );
+
+ expect(result).toBeNull();
+ });
+
+ it('should not fall back to the tool input when the output answers are malformed', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolInput: { questions: QUESTIONS },
+ toolOutput: {
+ result: {
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [{ questionIndex: 0, selectedOptionIndices: [5] }],
+ },
+ },
+ }),
+ );
+
+ expect(result).toBeNull();
+ });
+
+ it('should still fall back to the tool input when the output has no result', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolInput: { questions: QUESTIONS },
+ toolOutput: { success: true, message: 'Questions presented.' },
+ }),
+ );
+
+ expect(result).toEqual({ questions: QUESTIONS, status: 'pending' });
+ });
+
+ it('should return null when an answer references an unknown question', () => {
+ const result = parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: {
+ result: {
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: [{ questionIndex: 7, selectedOptionIndices: [0] }],
+ },
+ },
+ }),
+ );
+
+ expect(result).toBeNull();
+ });
+
+ it('should return null for another tool', () => {
+ expect(
+ parseAdminAskQuestionsResult(
+ buildPart({
+ type: 'tool-load_skills',
+ toolName: 'load_skills',
+ toolOutput: { result: { questions: QUESTIONS, status: 'answered' } },
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it('should return null when no questions can be read', () => {
+ expect(
+ parseAdminAskQuestionsResult(
+ buildPart({ toolOutput: { result: { status: 'answered' } } }),
+ ),
+ ).toBeNull();
+ });
+
+ it('should return null when a question is malformed', () => {
+ expect(
+ parseAdminAskQuestionsResult(
+ buildPart({
+ toolOutput: {
+ result: {
+ questions: [{ question: 'Missing options' }],
+ status: 'answered',
+ },
+ },
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it('should return null when an option is malformed', () => {
+ expect(
+ parseAdminAskQuestionsResult(
+ buildPart({
+ toolInput: {
+ questions: [{ question: 'Pick one', options: [{ label: 42 }] }],
+ },
+ }),
+ ),
+ ).toBeNull();
+ });
+});
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
new file mode 100644
index 00000000000..1305aee34e7
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/parseAdminAskQuestionsResult.ts
@@ -0,0 +1,169 @@
+import { isArray, isBoolean, isNumber, isString } from '@sniptt/guards';
+import {
+ ASK_QUESTIONS_TOOL_NAME,
+ type AskQuestionAnswer,
+ type AskQuestionItem,
+ type AskQuestionOption,
+} from 'twenty-shared/ai';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { type AdminAskQuestionsResult } from '@/settings/admin-panel/types/AdminAskQuestionsResult';
+import { type AdminChatThreadMessagePart } from '@/settings/admin-panel/types/AdminChatThreadMessagePart';
+import { getAdminToolDisplayName } from '@/settings/admin-panel/utils/getAdminToolDisplayName';
+import { parseAdminToolJson } from '@/settings/admin-panel/utils/parseAdminToolJson';
+
+const parseOption = (value: unknown): AskQuestionOption | null => {
+ if (!isPlainObject(value) || !isString(value.label)) {
+ return null;
+ }
+
+ return {
+ label: value.label,
+ description: isString(value.description) ? value.description : undefined,
+ isRecommended: isBoolean(value.isRecommended)
+ ? value.isRecommended
+ : undefined,
+ };
+};
+
+const parseQuestion = (value: unknown): AskQuestionItem | null => {
+ if (
+ !isPlainObject(value) ||
+ !isString(value.question) ||
+ !isArray(value.options)
+ ) {
+ return null;
+ }
+
+ const options = value.options.map(parseOption).filter(isDefined);
+
+ if (options.length !== value.options.length) {
+ return null;
+ }
+
+ return {
+ header: isString(value.header) ? value.header : '',
+ question: value.question,
+ options,
+ allowMultiSelect: isBoolean(value.allowMultiSelect)
+ ? value.allowMultiSelect
+ : undefined,
+ };
+};
+
+const parseAnswer = (
+ value: unknown,
+ questions: AskQuestionItem[],
+): AskQuestionAnswer | null => {
+ if (
+ !isPlainObject(value) ||
+ !isNumber(value.questionIndex) ||
+ !isArray(value.selectedOptionIndices)
+ ) {
+ return null;
+ }
+
+ const question = questions[value.questionIndex];
+
+ if (!isDefined(question)) {
+ return null;
+ }
+
+ const selectedOptionIndices = value.selectedOptionIndices.filter(isNumber);
+
+ if (selectedOptionIndices.length !== value.selectedOptionIndices.length) {
+ return null;
+ }
+
+ const hasOutOfRangeOption = selectedOptionIndices.some(
+ (optionIndex) => optionIndex < 0 || optionIndex >= question.options.length,
+ );
+
+ if (hasOutOfRangeOption) {
+ return null;
+ }
+
+ return {
+ questionIndex: value.questionIndex,
+ selectedOptionIndices,
+ freeText: isString(value.freeText) ? value.freeText : undefined,
+ };
+};
+
+const parseQuestions = (value: unknown): AskQuestionItem[] | null => {
+ if (!isArray(value)) {
+ return null;
+ }
+
+ const questions = value.map(parseQuestion).filter(isDefined);
+
+ return questions.length === value.length ? questions : null;
+};
+
+const parseAnswers = (
+ value: unknown,
+ questions: AskQuestionItem[],
+): AskQuestionAnswer[] | null => {
+ if (!isArray(value)) {
+ return null;
+ }
+
+ const answers = value
+ .map((answer) => parseAnswer(answer, questions))
+ .filter(isDefined);
+
+ return answers.length === value.length ? answers : null;
+};
+
+const getStoredResult = (toolOutput: unknown): Record<string, unknown> | null =>
+ isPlainObject(toolOutput) && isPlainObject(toolOutput.result)
+ ? toolOutput.result
+ : null;
+
+const parseStoredResult = (
+ result: Record<string, unknown>,
+): AdminAskQuestionsResult | null => {
+ const questions = parseQuestions(result.questions);
+
+ if (!isDefined(questions)) {
+ return null;
+ }
+
+ const status = isString(result.status) ? result.status : 'pending';
+
+ if (!isDefined(result.answers)) {
+ return { questions, status };
+ }
+
+ const answers = parseAnswers(result.answers, questions);
+
+ return isDefined(answers) ? { questions, status, answers } : null;
+};
+
+const parsePendingResultFromToolInput = (
+ toolInput: unknown,
+): AdminAskQuestionsResult | null => {
+ if (!isPlainObject(toolInput)) {
+ return null;
+ }
+
+ const questions = parseQuestions(toolInput.questions);
+
+ return isDefined(questions) ? { questions, status: 'pending' } : null;
+};
+
+export const parseAdminAskQuestionsResult = (
+ part: AdminChatThreadMessagePart,
+): AdminAskQuestionsResult | null => {
+ if (getAdminToolDisplayName(part) !== ASK_QUESTIONS_TOOL_NAME) {
+ return null;
+ }
+
+ const storedResult = getStoredResult(parseAdminToolJson(part.toolOutput));
+
+ if (isDefined(storedResult)) {
+ return parseStoredResult(storedResult);
+ }
+
+ return parsePendingResultFromToolInput(parseAdminToolJson(part.toolInput));
+};