The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Simplify AI model selection (#29553)
Raphaël Bosi891e98194a7d
diff --git a/packages/twenty-front/src/modules/ai/components/AiModelPicker.tsx b/packages/twenty-front/src/modules/ai/components/AiModelPicker.tsxindex 9bbca83652b..af228283634 100644--- a/packages/twenty-front/src/modules/ai/components/AiModelPicker.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiModelPicker.tsx@@ -1,49 +1,21 @@-import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';-import { useState } from 'react';+import { useId } from 'react';import {AUTO_SELECT_MODEL_ID_BY_TIER,AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,} from 'twenty-shared/ai';-import { isDefined } from 'twenty-shared/utils';-import { LightButton } from 'twenty-ui/components/input';-import { themeCssVariables } from 'twenty-ui/theme';+import { IconWand } from 'twenty-ui/icon';-import { AiModelTierSlider } from '@/ai/components/AiModelTierSlider';+import { AiModelPinSelect } from '@/ai/components/AiModelPinSelect';import { useAiModelTiers } from '@/ai/hooks/useAiModelTiers';import { useWorkspaceAiModelTiers } from '@/ai/hooks/useWorkspaceAiModelTiers';-import { getAiModelTierForAgentModelId } from '@/ai/utils/getAiModelTierForAgentModelId';-import { getNearestAiModelTier } from '@/ai/utils/getNearestAiModelTier';+import { getAiModelTierLabel } from '@/ai/utils/getAiModelTierLabel';+import { getAiModelModeDescription } from '@/ai/utils/getAiModelModeDescription';+import { getModelIcon } from '@/ai/utils/getModelIcon';import { aiModelsState } from '@/client-config/states/aiModelsState';-import { AiModelPinSelect } from '@/ai/components/AiModelPinSelect';import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-const StyledContainer = styled.div`- display: flex;- flex-direction: column;- gap: ${themeCssVariables.spacing[2]};-`;--const StyledSliderCard = styled.div`- background: ${themeCssVariables.background.secondary};- border: 1px solid ${themeCssVariables.border.color.medium};- border-radius: ${themeCssVariables.border.radius.md};- corner-shape: round;- padding: ${themeCssVariables.spacing[3]};-`;--const StyledFooter = styled.div`- align-items: center;- display: flex;- justify-content: space-between;-`;--const StyledHint = styled.span`- color: ${themeCssVariables.font.color.light};- font-size: ${themeCssVariables.font.size.sm};-`;-type AiModelPickerProps = {modelId: string;onModelIdChange: (modelId: string) => void;@@ -56,66 +28,38 @@ export const AiModelPicker = ({disabled = false,}: AiModelPickerProps) => {const { t } = useLingui();+ const dropdownId = useId();const tiers = useAiModelTiers();- const aiModels = useAtomStateValue(aiModelsState);const { agentTier } = useWorkspaceAiModelTiers();-- const isWorkspaceDefault = modelId === AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID;- const tierFromModelId = getAiModelTierForAgentModelId(modelId, agentTier);- const hasPinnedModel = !isDefined(tierFromModelId);- const pinnedModel = hasPinnedModel- ? aiModels.find((model) => model.modelId === modelId)- : undefined;-- const [isAdvancedOpen, setIsAdvancedOpen] = useState(hasPinnedModel);-- const selectedTier =- tierFromModelId ?? getNearestAiModelTier(pinnedModel, tiers);+ const aiModels = useAtomStateValue(aiModelsState);+ const workspaceTierLabel = getAiModelTierLabel(agentTier);return (- <StyledContainer>- <StyledSliderCard>- <AiModelTierSlider- selectedTier={selectedTier}- onTierChange={(tier) =>- onModelIdChange(AUTO_SELECT_MODEL_ID_BY_TIER[tier])- }- title={hasPinnedModel ? (pinnedModel?.label ?? modelId) : undefined}- disabled={disabled}- />- </StyledSliderCard>- <StyledFooter>- <StyledHint>- {isWorkspaceDefault- ? t`Follows the workspace default for agents`- : hasPinnedModel- ? t`Pinned to a specific model`- : t`Set for this agent only`}- </StyledHint>- {!isAdvancedOpen && !disabled && (- <LightButton- emphasis="subtle"- onClick={() => setIsAdvancedOpen(true)}- >{t`Advanced`}</LightButton>- )}- </StyledFooter>- {isAdvancedOpen && (- <AiModelPinSelect- dropdownId="ai-model-picker-pinned-model"- label={t`Pin a specific model`}- description={t`Overrides the mode above until you switch back to automatic`}- modelId={hasPinnedModel ? modelId : null}- onChange={(pinnedModelId) =>- onModelIdChange(- pinnedModelId ?? AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,- )- }- aiModels={aiModels}- emptyOptionLabel={t`Automatic`}- disabled={disabled}- dropdownWidth={GenericDropdownContentWidth.ExtraLarge}- />- )}- </StyledContainer>+ <AiModelPinSelect+ dropdownId={dropdownId}+ label={t`Model`}+ modelId={modelId}+ onChange={(selectedModelId) =>+ onModelIdChange(+ selectedModelId ?? AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ )+ }+ aiModels={aiModels}+ automaticOptions={[+ {+ value: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ label: t`Workspace default · ${workspaceTierLabel}`,+ Icon: IconWand,+ },+ ...tiers.map((tier) => ({+ value: AUTO_SELECT_MODEL_ID_BY_TIER[tier.tier],+ label: tier.label,+ contextualText: getAiModelModeDescription(tier),+ Icon: getModelIcon(tier.model?.modelFamily, tier.model?.providerName),+ })),+ ]}+ disabled={disabled}+ dropdownWidth={GenericDropdownContentWidth.ExtraLarge}+ />);};diff --git a/packages/twenty-front/src/modules/ai/components/AiModelPinSelect.tsx b/packages/twenty-front/src/modules/ai/components/AiModelPinSelect.tsxindex d810db8a463..f508bd3c83c 100644--- a/packages/twenty-front/src/modules/ai/components/AiModelPinSelect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiModelPinSelect.tsx@@ -1,9 +1,11 @@import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';+import { isNonEmptyString } from '@sniptt/guards';import { type ComponentProps } from 'react';import { isAiModelEffort, parseAiModelVariantId } from 'twenty-shared/ai';import { isDefined } from 'twenty-shared/utils';import { IconWand } from 'twenty-ui/icon';+import { type SelectOption } from 'twenty-ui/primitives/input';import { themeCssVariables } from 'twenty-ui/theme';import { AUTOMATIC_MODEL_PIN } from '@/ai/constants/AutomaticModelPin';@@ -30,6 +32,7 @@ type AiModelPinSelectProps = {onChange: (modelId: string | null) => void;aiModels: PinnableAiModel[];emptyOptionLabel?: string;+ automaticOptions?: SelectOption<string>[];label?: string;description?: string;disabled?: boolean;@@ -43,6 +46,7 @@ export const AiModelPinSelect = ({onChange,aiModels,emptyOptionLabel,+ automaticOptions = [],label,description,disabled = false,@@ -51,11 +55,26 @@ export const AiModelPinSelect = ({}: AiModelPinSelectProps) => {const { t } = useLingui();- const { modelId: baseModelId, effort } = parseAiModelVariantId(modelId ?? '');+ const automaticOption = automaticOptions.find(+ (option) => option.value === modelId,+ );+ const pinnedModelId = isDefined(automaticOption) ? undefined : modelId;+ const { modelId: baseModelId, effort } = parseAiModelVariantId(+ pinnedModelId ?? '',+ );const baseModel = aiModels.find((model) => model.modelId === baseModelId);const efforts = (baseModel?.efforts ?? []).filter(isAiModelEffort);+ const selectedModelValue =+ automaticOption?.value ??+ (isNonEmptyString(baseModelId) ? baseModelId : AUTOMATIC_MODEL_PIN);const handleModelChange = (value: string) => {+ if (automaticOptions.some((option) => option.value === value)) {+ onChange(value);++ return;+ }+if (value === AUTOMATIC_MODEL_PIN) {onChange(null);@@ -81,10 +100,12 @@ export const AiModelPinSelect = ({dropdownId={dropdownId}label={label}description={description}- value={isDefined(modelId) ? baseModelId : AUTOMATIC_MODEL_PIN}+ value={selectedModelValue}onChange={handleModelChange}showIconInControl={isDefined(modelId)}+ showContextualTextInControloptions={[+ ...automaticOptions,...(isDefined(emptyOptionLabel)? [{@@ -94,7 +115,10 @@ export const AiModelPinSelect = ({},]: []),- ...getAiModelPinOptions({ aiModels, keepModelId: baseModelId }),+ ...getAiModelPinOptions({+ aiModels,+ keepModelId: isDefined(pinnedModelId) ? baseModelId : undefined,+ }),]}withSearchInputdisabled={disabled}diff --git a/packages/twenty-front/src/modules/ai/components/SettingsAgentModelCapabilities.tsx b/packages/twenty-front/src/modules/ai/components/SettingsAgentModelCapabilities.tsxindex e22145148c0..22c6a7615c5 100644--- a/packages/twenty-front/src/modules/ai/components/SettingsAgentModelCapabilities.tsx+++ b/packages/twenty-front/src/modules/ai/components/SettingsAgentModelCapabilities.tsx@@ -1,48 +1,14 @@-import { useResolvedAiModel } from '@/ai/hooks/useResolvedAiModel';-import { InputLabel } from '@/ui/input/components/internal/InputLabel/InputLabel';-import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';-import { isDefined } from 'twenty-shared/utils';+import {+ type ModelConfiguration,+ parseAiModelVariantId,+} from 'twenty-shared/ai';import { Section } from 'twenty-ui/components/layout';+import { SettingsRow } from 'twenty-ui/components/settings';import { IconBrandX, IconWorld } from 'twenty-ui/icon';-import { Checkbox } from 'twenty-ui/primitives/input';-import { useTheme, themeCssVariables } from 'twenty-ui/theme';--const StyledCheckboxContainer = styled.div<{ disabled: boolean }>`- align-items: center;- border-radius: ${themeCssVariables.border.radius.sm};- cursor: ${({ disabled }) => (disabled ? 'not-allowed' : 'pointer')};- display: flex;- height: ${themeCssVariables.spacing[8]};- justify-content: space-between;- padding-inline: ${themeCssVariables.spacing[2]};- transition: background-color- calc(${themeCssVariables.animation.duration.normal} * 1s) ease;-- &:hover {- background-color: ${({ disabled }) =>- disabled- ? 'transparent'- : themeCssVariables.background.transparent.light};- }-`;--const StyledCheckboxLabel = styled.div`- align-items: center;- display: flex;- gap: ${themeCssVariables.spacing[1]};-`;-type ModelConfiguration = {- webSearch?: {- enabled: boolean;- configuration?: Record<string, unknown>;- };- twitterSearch?: {- enabled: boolean;- configuration?: Record<string, unknown>;- };-};+import { useResolvedAiModel } from '@/ai/hooks/useResolvedAiModel';+import { InputLabel } from '@/ui/input/components/internal/InputLabel/InputLabel';type SettingsAgentModelCapabilitiesProps = {selectedModelId: string;@@ -57,25 +23,23 @@ export const SettingsAgentModelCapabilities = ({onConfigurationChange,disabled = false,}: SettingsAgentModelCapabilitiesProps) => {- const theme = useTheme();- const selectedModel = useResolvedAiModel(selectedModelId);- const nativeCapabilities = selectedModel?.nativeCapabilities;-- if (!isDefined(nativeCapabilities)) {- return null;- }-- const showNativeWebSearch = nativeCapabilities.webSearch;- const showNativeTwitterSearch = nativeCapabilities.twitterSearch;+ const { modelId: baseModelId } = parseAiModelVariantId(selectedModelId);+ const selectedModel = useResolvedAiModel(baseModelId);- if (!showNativeWebSearch && !showNativeTwitterSearch) {+ if (+ !selectedModel?.nativeCapabilities?.webSearch &&+ !selectedModel?.nativeCapabilities?.twitterSearch+ ) {return null;}- const handleCapabilityToggle = (- capability: 'webSearch' | 'twitterSearch',- enabled: boolean,- ) => {+ const handleCapabilityChange = ({+ capability,+ enabled,+ }: {+ capability: 'webSearch' | 'twitterSearch';+ enabled: boolean;+ }) => {if (disabled) {return;}@@ -83,62 +47,40 @@ export const SettingsAgentModelCapabilities = ({onConfigurationChange({...modelConfiguration,[capability]: {+ ...modelConfiguration[capability],enabled,- configuration: modelConfiguration[capability]?.configuration || {},},});};- const capabilities = [- ...(showNativeWebSearch- ? [- {- key: 'webSearch' as const,- label: t`Web Search`,- Icon: IconWorld,- enabled: modelConfiguration.webSearch?.enabled || false,- },- ]- : []),- ...(showNativeTwitterSearch- ? [- {- key: 'twitterSearch' as const,- label: t`Twitter/X Search`,- Icon: IconBrandX,- enabled: modelConfiguration.twitterSearch?.enabled || false,- },- ]- : []),- ];-return (<Section.Root><InputLabel>{t`Enable model-specific features`}</InputLabel><div>- {capabilities.map((capability) => (- <StyledCheckboxContainer+ {selectedModel.nativeCapabilities?.webSearch && (+ <SettingsRow+ startElement={<IconWorld />}+ checked={modelConfiguration.webSearch?.enabled ?? false}+ onCheckedChange={(enabled) =>+ handleCapabilityChange({ capability: 'webSearch', enabled })+ }disabled={disabled}- key={capability.key}- onClick={() =>- handleCapabilityToggle(capability.key, !capability.enabled)+ >+ {t`Web Search`}+ </SettingsRow>+ )}+ {selectedModel.nativeCapabilities?.twitterSearch && (+ <SettingsRow+ startElement={<IconBrandX />}+ checked={modelConfiguration.twitterSearch?.enabled ?? false}+ onCheckedChange={(enabled) =>+ handleCapabilityChange({ capability: 'twitterSearch', enabled })}+ disabled={disabled}>- <StyledCheckboxLabel>- <capability.Icon size={theme.icon.size.sm} />- <span>{capability.label}</span>- </StyledCheckboxLabel>- <Checkbox- aria-label={capability.label}- checked={capability.enabled}- onCheckedChange={(isChecked) => {- handleCapabilityToggle(capability.key, isChecked);- }}- disabled={disabled}- onClick={(event) => event.stopPropagation()}- />- </StyledCheckboxContainer>- ))}+ {t`Twitter/X Search`}+ </SettingsRow>+ )}</div></Section.Root>);diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiModelPicker.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiModelPicker.stories.tsxnew file mode 100644index 00000000000..f10f3c84a4d--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiModelPicker.stories.tsx@@ -0,0 +1,177 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, fn, userEvent, within } from 'storybook/test';+import {+ AUTO_SELECT_MODEL_ID_BY_TIER,+ AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+} from 'twenty-shared/ai';+import { CatalogDecorator } from 'twenty-ui/testing';++import { AiModelPickerExample } from '@/ai/components/__stories__/AiModelPickerExample';++const meta = {+ title: 'Modules/AI/AiModelPicker',+ component: AiModelPickerExample,+ decorators: [CatalogDecorator],+ parameters: {+ catalog: { options: { elementContainer: { width: 400 } } },+ },+ args: {+ onModelIdChange: fn(),+ onConfigurationChange: fn(),+ },+} satisfies Meta<typeof AiModelPickerExample>;++export default meta;++type Story = StoryObj<typeof meta>;++export const SelectModelAndEffort: Story = {+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(+ await canvas.findByRole('button', {+ name: 'Workspace default · Balanced',+ }),+ );+ await userEvent.click(+ await body.findByRole('option', { name: /^Reasoning One/ }),+ );+ await expect(args.onModelIdChange).toHaveBeenCalledTimes(1);+ await expect(args.onModelIdChange).toHaveBeenLastCalledWith(+ 'story/reasoning-one',+ );++ await userEvent.click(+ await canvas.findByRole('button', { name: 'Default' }),+ );+ await userEvent.click(await body.findByRole('option', { name: 'High' }));+ await expect(args.onModelIdChange).toHaveBeenCalledTimes(2);+ await expect(args.onModelIdChange).toHaveBeenLastCalledWith(+ 'story/reasoning-one@high',+ );++ await userEvent.click(+ canvas.getByRole('button', { name: /^Reasoning One/ }),+ );+ await userEvent.click(+ await body.findByRole('option', { name: /^Reasoning Two/ }),+ );+ await expect(args.onModelIdChange).toHaveBeenCalledTimes(3);+ await expect(args.onModelIdChange).toHaveBeenLastCalledWith(+ 'story/reasoning-two@high',+ );+ await expect(canvas.getByRole('button', { name: 'High' })).toBeVisible();++ await userEvent.click(+ canvas.getByRole('button', { name: /^Reasoning Two/ }),+ );+ await userEvent.click(+ await body.findByRole('option', { name: /^Fast Model/ }),+ );+ await expect(args.onModelIdChange).toHaveBeenCalledTimes(4);+ await expect(args.onModelIdChange).toHaveBeenLastCalledWith('story/fast');+ await expect(+ canvas.queryByRole('button', { name: 'High' }),+ ).not.toBeInTheDocument();++ await userEvent.click(canvas.getByRole('button', { name: /^Fast Model/ }));+ await userEvent.click(+ await body.findByRole('option', { name: /^Balanced/ }),+ );+ await expect(args.onModelIdChange).toHaveBeenCalledTimes(5);+ await expect(args.onModelIdChange).toHaveBeenLastCalledWith(+ AUTO_SELECT_MODEL_ID_BY_TIER.balanced,+ );++ await userEvent.click(canvas.getByRole('button', { name: /^Balanced/ }));+ await userEvent.click(+ await body.findByRole('option', {+ name: 'Workspace default · Balanced',+ }),+ );+ await expect(args.onModelIdChange).toHaveBeenCalledTimes(6);+ await expect(args.onModelIdChange).toHaveBeenLastCalledWith(+ AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ );+ },+};++export const MissingPinnedModel: Story = {+ args: { initialModelId: 'story/retired' },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(+ await canvas.findByRole('button', {+ name: 'story/retired (unavailable)',+ }),+ );+ const unavailableModel = await body.findByRole('option', {+ name: 'story/retired (unavailable)',+ });++ await expect(unavailableModel).toBeDisabled();+ await userEvent.click(unavailableModel);+ await expect(args.onModelIdChange).not.toHaveBeenCalled();++ await userEvent.click(+ body.getByRole('option', { name: 'Workspace default · Balanced' }),+ );+ await expect(args.onModelIdChange).toHaveBeenCalledTimes(1);+ await expect(args.onModelIdChange).toHaveBeenCalledWith(+ AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ );+ },+};++export const CapabilitiesForReasoningVariant: Story = {+ args: {+ initialModelId: 'story/reasoning-one@high',+ initialModelConfiguration: {+ webSearch: { enabled: false, configuration: { maximumResults: 3 } },+ twitterSearch: { enabled: true, configuration: { language: 'en' } },+ },+ shouldShowCapabilities: true,+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const webSearch = await canvas.findByRole('switch', { name: 'Web Search' });++ await expect(webSearch).not.toBeChecked();+ await expect(+ canvas.queryByRole('switch', { name: 'Twitter/X Search' }),+ ).not.toBeInTheDocument();+ await userEvent.click(webSearch);+ await expect(webSearch).toBeChecked();+ await expect(args.onConfigurationChange).toHaveBeenCalledTimes(1);+ await expect(args.onConfigurationChange).toHaveBeenCalledWith({+ webSearch: { enabled: true, configuration: { maximumResults: 3 } },+ twitterSearch: { enabled: true, configuration: { language: 'en' } },+ });+ },+};++export const Disabled: Story = {+ args: {+ initialModelId: 'story/reasoning-one@high',+ shouldShowCapabilities: true,+ disabled: true,+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const webSearch = await canvas.findByRole('switch', { name: 'Web Search' });++ await expect(canvas.getByText('Reasoning One · OpenAI')).toBeVisible();+ await expect(canvas.queryByRole('button')).not.toBeInTheDocument();+ await expect(webSearch).toHaveAttribute('aria-disabled', 'true');+ await userEvent.click(canvas.getByText('Web Search'));+ await expect(webSearch).not.toBeChecked();+ await expect(body.queryByRole('option')).not.toBeInTheDocument();+ await expect(args.onModelIdChange).not.toHaveBeenCalled();+ await expect(args.onConfigurationChange).not.toHaveBeenCalled();+ },+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiModelPickerExample.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiModelPickerExample.tsxnew file mode 100644index 00000000000..550e7942d2c--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiModelPickerExample.tsx@@ -0,0 +1,89 @@+import { createStore, Provider } from 'jotai';+import { useState } from 'react';+import {+ AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ type ModelConfiguration,+} from 'twenty-shared/ai';+import { Text } from 'twenty-ui/primitives/typography';++import { AiModelPicker } from '@/ai/components/AiModelPicker';+import { SettingsAgentModelCapabilities } from '@/ai/components/SettingsAgentModelCapabilities';+import { MODEL_STORY_MODELS } from '@/ai/components/__stories__/modelStoryModels';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { aiModelTiersState } from '@/client-config/states/aiModelTiersState';+import { aiModelsState } from '@/client-config/states/aiModelsState';+import { AiModelTier } from '~/generated-metadata/graphql';+import { mockCurrentWorkspace } from '~/testing/mock-data/users';++type AiModelPickerExampleProps = {+ initialModelId?: string;+ initialModelConfiguration?: ModelConfiguration;+ disabled?: boolean;+ shouldShowCapabilities?: boolean;+ onModelIdChange: (modelId: string) => void;+ onConfigurationChange: (configuration: ModelConfiguration) => void;+};++export const AiModelPickerExample = ({+ initialModelId = AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ initialModelConfiguration = {},+ disabled = false,+ shouldShowCapabilities = false,+ onModelIdChange,+ onConfigurationChange,+}: AiModelPickerExampleProps) => {+ const [modelId, setModelId] = useState(initialModelId);+ const [modelConfiguration, setModelConfiguration] = useState(+ initialModelConfiguration,+ );+ const [store] = useState(() => {+ const previewStore = createStore();++ previewStore.set(aiModelsState.atom, MODEL_STORY_MODELS);+ previewStore.set(+ aiModelTiersState.atom,+ Object.values(AiModelTier).map((tier) => ({+ tier,+ modelId: 'story/reasoning-one',+ })),+ );+ previewStore.set(currentWorkspaceState.atom, {+ ...mockCurrentWorkspace,+ aiAgentModelTier: AiModelTier.balanced,+ isAutoModelSelectionEnabled: true,+ });++ return previewStore;+ });++ const handleModelIdChange = (nextModelId: string) => {+ setModelId(nextModelId);+ onModelIdChange(nextModelId);+ };++ const handleConfigurationChange = (configuration: ModelConfiguration) => {+ setModelConfiguration(configuration);+ onConfigurationChange(configuration);+ };++ return (+ <Provider store={store}>+ <AiModelPicker+ modelId={modelId}+ onModelIdChange={handleModelIdChange}+ disabled={disabled}+ />+ {shouldShowCapabilities && (+ <SettingsAgentModelCapabilities+ selectedModelId={modelId}+ modelConfiguration={modelConfiguration}+ onConfigurationChange={handleConfigurationChange}+ disabled={disabled}+ />+ )}+ <Text color="tertiary" size="sm">+ Selected model: {modelId}+ </Text>+ </Provider>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/modelStoryModels.ts b/packages/twenty-front/src/modules/ai/components/__stories__/modelStoryModels.tsnew file mode 100644index 00000000000..36a0092f89d--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/modelStoryModels.ts@@ -0,0 +1,27 @@+import { type ClientAiModelConfig } from '~/generated-metadata/graphql';++export const MODEL_STORY_MODELS: ClientAiModelConfig[] = [+ {+ modelId: 'story/reasoning-one',+ label: 'Reasoning One',+ providerName: 'openai',+ providerLabel: 'OpenAI',+ efforts: ['low', 'high'],+ nativeCapabilities: { webSearch: true, twitterSearch: false },+ },+ {+ modelId: 'story/reasoning-two',+ label: 'Reasoning Two',+ providerName: 'openai',+ providerLabel: 'OpenAI',+ efforts: ['high'],+ nativeCapabilities: { webSearch: true, twitterSearch: false },+ },+ {+ modelId: 'story/fast',+ label: 'Fast Model',+ providerName: 'openai',+ providerLabel: 'OpenAI',+ nativeCapabilities: { webSearch: false, twitterSearch: false },+ },+];diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiModelPinOptions.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiModelPinOptions.test.tsnew file mode 100644index 00000000000..a47b1e6ba86--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiModelPinOptions.test.ts@@ -0,0 +1,40 @@+import { getAiModelPinOptions } from '@/ai/utils/getAiModelPinOptions';++describe('getAiModelPinOptions', () => {+ it('keeps the current deprecated model and excludes other deprecated models and effort variants', () => {+ const options = getAiModelPinOptions({+ aiModels: [+ { modelId: 'story/current', label: 'Current', isDeprecated: true },+ { modelId: 'story/older', label: 'Older', isDeprecated: true },+ { modelId: 'story/available', label: 'Available' },+ {+ modelId: 'story/available@high',+ label: 'Available High',+ effort: 'high',+ },+ ],+ keepModelId: 'story/current',+ });++ expect(options.map(({ value }) => value)).toEqual([+ 'story/available',+ 'story/current',+ ]);+ expect(options.find(({ value }) => value === 'story/current')?.label).toBe(+ 'Current (deprecated)',+ );+ });++ it('preserves a missing current model as an unavailable choice', () => {+ const options = getAiModelPinOptions({+ aiModels: [{ modelId: 'story/available', label: 'Available' }],+ keepModelId: 'story/retired',+ });++ expect(options).toContainEqual({+ value: 'story/retired',+ label: 'story/retired (unavailable)',+ disabled: true,+ });+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getNearestAiModelTier.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getNearestAiModelTier.test.tsdeleted file mode 100644index 5092a82dc98..00000000000--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getNearestAiModelTier.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { type ResolvedAiModelTier } from '@/ai/types/ResolvedAiModelTier';-import { getNearestAiModelTier } from '@/ai/utils/getNearestAiModelTier';-import { type ClientAiModelConfig } from '~/generated-metadata/graphql';--const buildModel = (- modelId: string,- intelligenceIndex?: number,-): ClientAiModelConfig => ({- modelId,- label: modelId,- sdkPackage: null,- intelligenceIndex,-});--const tierModels: Pick<ResolvedAiModelTier, 'tier' | 'model'>[] = [- { tier: 'extraFast', model: buildModel('a/lite', 20) },- { tier: 'fast', model: buildModel('a/fast', 37) },- { tier: 'balanced', model: buildModel('a/balanced', 42) },- { tier: 'smart', model: buildModel('a/smart', 47) },- { tier: 'extraSmart', model: undefined },-];--const tiers: ResolvedAiModelTier[] = tierModels.map((tier) => ({- ...tier,- label: tier.tier,- isPinned: false,- speedDeltaPercent: undefined,- intelligenceDeltaPercent: undefined,- costDeltaPercent: undefined,-}));--describe('getNearestAiModelTier', () => {- it('returns the tier that resolves to the model itself', () => {- expect(getNearestAiModelTier(buildModel('a/smart', 1), tiers)).toBe(- 'smart',- );- });-- it('picks the tier whose model is closest in intelligence', () => {- expect(getNearestAiModelTier(buildModel('b/other', 39), tiers)).toBe(- 'fast',- );- expect(getNearestAiModelTier(buildModel('b/other', 60), tiers)).toBe(- 'smart',- );- });-- it('falls back to balanced without a benchmark', () => {- expect(getNearestAiModelTier(buildModel('b/other'), tiers)).toBe(- 'balanced',- );- expect(getNearestAiModelTier(undefined, tiers)).toBe('balanced');- });-});diff --git a/packages/twenty-front/src/modules/ai/utils/getAiModelPinOptions.ts b/packages/twenty-front/src/modules/ai/utils/getAiModelPinOptions.tsindex f206a84520f..bec668184a6 100644--- a/packages/twenty-front/src/modules/ai/utils/getAiModelPinOptions.ts+++ b/packages/twenty-front/src/modules/ai/utils/getAiModelPinOptions.ts@@ -1,19 +1,20 @@import { t } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';+import { type SelectOption } from 'twenty-ui/primitives/input';import { type PinnableAiModel } from '@/ai/types/PinnableAiModel';import { getDataResidencyDisplay } from '@/ai/utils/getDataResidencyDisplay';import { getModelIcon } from '@/ai/utils/getModelIcon';-// Effort variants are picked via their base model; a deprecated current pin stays listed.export const getAiModelPinOptions = ({aiModels,keepModelId,}: {aiModels: PinnableAiModel[];keepModelId?: string;-}) =>- aiModels+}): SelectOption<string>[] => {+ const options = aiModels.filter((model) =>!isDefined(model.effort) &&@@ -33,3 +34,21 @@ export const getAiModelPinOptions = ({};}).sort((first, second) => first.label.localeCompare(second.label));++ const isCurrentModelMissing =+ isNonEmptyString(keepModelId) &&+ !options.some((option) => option.value === keepModelId);++ if (!isCurrentModelMissing) {+ return options;+ }++ return [+ {+ value: keepModelId,+ label: t`${keepModelId} (unavailable)`,+ disabled: true,+ },+ ...options,+ ];+};diff --git a/packages/twenty-front/src/modules/ai/utils/getNearestAiModelTier.ts b/packages/twenty-front/src/modules/ai/utils/getNearestAiModelTier.tsdeleted file mode 100644index c3b2778595f..00000000000--- a/packages/twenty-front/src/modules/ai/utils/getNearestAiModelTier.ts+++ /dev/null@@ -1,35 +0,0 @@-import { type AiModelTier } from 'twenty-shared/ai';-import { isDefined } from 'twenty-shared/utils';--import { type ResolvedAiModelTier } from '@/ai/types/ResolvedAiModelTier';-import { type ClientAiModelConfig } from '~/generated-metadata/graphql';--// A pinned model sits on its own tier, else on the tier closest in intelligence.-export const getNearestAiModelTier = (- model: ClientAiModelConfig | undefined,- tiers: ResolvedAiModelTier[],-): AiModelTier => {- const exactTier = tiers.find(- (tier) => isDefined(model) && tier.model?.modelId === model.modelId,- );-- if (isDefined(exactTier)) {- return exactTier.tier;- }-- const intelligenceIndex = model?.intelligenceIndex;-- if (!isDefined(intelligenceIndex)) {- return 'balanced';- }-- const rankedTiers = tiers- .filter((tier) => isDefined(tier.model?.intelligenceIndex))- .sort(- (first, second) =>- Math.abs((first.model?.intelligenceIndex ?? 0) - intelligenceIndex) -- Math.abs((second.model?.intelligenceIndex ?? 0) - intelligenceIndex),- );-- return rankedTiers[0]?.tier ?? 'balanced';-};diff --git a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentModelCell.tsx b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentModelCell.tsxindex 3e031ab437a..da67cc74c43 100644--- a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentModelCell.tsx+++ b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentModelCell.tsx@@ -5,6 +5,8 @@ import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';import { themeCssVariables } from 'twenty-ui/theme';import { useResolvedAiModel } from '@/ai/hooks/useResolvedAiModel';+import { getAiModelModeDescription } from '@/ai/utils/getAiModelModeDescription';+import { isDefined } from 'twenty-shared/utils';const StyledContainer = styled.div`color: ${themeCssVariables.font.color.secondary};@@ -24,12 +26,13 @@ export const CoreAgentModelCell = ({ modelId }: CoreAgentModelCellProps) => {modelId === AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID? t`Workspace default`: modelId;+ const modelLabel = isDefined(resolvedModel)+ ? getAiModelModeDescription({ model: resolvedModel, isPinned: true })+ : fallbackLabel;return (<StyledContainer>- <OverflowingTextWithTooltip- text={resolvedModel?.label ?? fallbackLabel}- />+ <OverflowingTextWithTooltip text={modelLabel} /></StyledContainer>);};diff --git a/packages/twenty-front/src/modules/object-core/agents/components/__tests__/CoreAgentModelCell.test.tsx b/packages/twenty-front/src/modules/object-core/agents/components/__tests__/CoreAgentModelCell.test.tsxnew file mode 100644index 00000000000..39e4eba0648--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/agents/components/__tests__/CoreAgentModelCell.test.tsx@@ -0,0 +1,45 @@+import { i18n } from '@lingui/core';+import { I18nProvider } from '@lingui/react';+import { render, screen } from '@testing-library/react';+import { createStore, Provider } from 'jotai';++import { aiModelsState } from '@/client-config/states/aiModelsState';+import { CoreAgentModelCell } from '@/object-core/agents/components/CoreAgentModelCell';++describe('CoreAgentModelCell', () => {+ it.each([+ {+ modelId: 'story/reasoning@high',+ expectedLabel: 'Reasoning Model · High',+ },+ {+ modelId: 'story/reasoning@low',+ expectedLabel: 'story/reasoning@low',+ },+ ])('displays $expectedLabel for $modelId', ({ modelId, expectedLabel }) => {+ const store = createStore();++ store.set(aiModelsState.atom, [+ {+ modelId: 'story/reasoning',+ label: 'Reasoning Model',+ efforts: ['high'],+ },+ {+ modelId: 'story/reasoning@high',+ label: 'Reasoning Model (high reasoning)',+ effort: 'high',+ },+ ]);++ render(+ <I18nProvider i18n={i18n}>+ <Provider store={store}>+ <CoreAgentModelCell modelId={modelId} />+ </Provider>+ </I18nProvider>,+ );++ expect(screen.getByText(expectedLabel)).toBeInTheDocument();+ });+});