Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(web): provider key page facelift (#16485)

Louai Boumediene9792742abc65
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.md
index 6128a2c77df..2222224e89a 100644
--- a/brain/knowledge/ai-intelligence/ai-providers.md
+++ b/brain/knowledge/ai-intelligence/ai-providers.md
@@ -88,6 +88,7 @@ after a file without chat keys it seeds the chat list from the live flow list.
- **A key's model list is enforced when a specific model runs, not only in pickers.** `/v1/ai/execute` checks `aiProviderService.assertModelAllowed` before queueing (the managed Activepieces key is skipped: it allows every model), and the worker's `resolveAiProvider` RPC sends `modelId` so the server checks it again against the key it resolves at run time (a model removed while the job waited fails then). `resolveNamedModelId` refuses any own-key model outside the list with no tier-id exemption: an own key never translates `smart`/`fast`, so a name that looks like a tier is just a customer model id. At platform scope, `rankRows` prefers keys open to every project; at project scope it still prefers the most specific key. Key edits and capability choices both take the `platform` row lock, and a capability save re-reads its key under that lock, so the two cannot interleave. One helper, `aiKeyScope.keyOffersModel`, decides whether a key still offers a model: its model scope, plus its typed-in `config.models` list when it has one. The tier and capability guards on a key edit both use it, and so does the locked re-check when a capability is saved. A key edit that removes a typed-in model a capability uses is refused like a model-scope change.
- **Deleting a platform tier needs a replacement, except the last live tier, and there is no usage count.** Refs to a deleted tier are never rewritten; they reach a live tier through `replacedBy` (flattened to one hop on delete). The last tier may always go with no replacement: without that exit, a platform's last tier and the key it uses could never be removed, because the key guard refuses keys a live tier uses. Tier delete is also deliberately **not** plan-gated (writes are), so a platform that downgrades can still clear its tiers and then remove its key. Its refs then point at a tier with `replacedBy: null`, and the resolver must fail them with a clear "tier removed" error. An exact "used by N flows" count needs a `LIKE` scan over every flow version's `trigger` text, plus agent jsonb and conversations, on the whole platform. We dropped it rather than pay that. If counts come back, add a denormalized `flow_version.modelTierIds` array + GIN index (the `connectionIds` pattern) instead of scanning. Deleting the last live tier also sets `platform_configuration.aiSpecificModelsVisible = true` in the same transaction, so "hidden needs at least one tier" holds without the client flipping it first (a client-side flip left models visible when the delete then failed, #16116). The other direction holds too: `platformConfigurationService.update` saves every field in one transaction that first calls `platformModelTierService.assertSpecificModelsVisibilityAllowed` (same `platform` row lock, refuses a hide when no live tier is left), so a refused hide changes no other setting either, so a concurrent last-tier delete and hide cannot leave builders with nothing. `PlatformConfigurationSettings` (the infra Configurations form) does **not** carry the flag; only `UpdatePlatformConfigurationRequestBody` does, so saving that form never rewrites it.
- **The Tiers tab re-implements the server's project-scope rule on the client.** `modelMeta.keyServesProject` / `entryRunsIn` mirror `rowAllowsScope` + `scopeAllows`, and power the per-tier "Not available in N projects" lines, the *Preview as project* select and the confirm dialog when a key's projects are narrowed (`modelMeta.keyScopeImpact`). Change one side and change the other, or the admin sees a tier as available where the server refuses it.
+- **The keys page mirrors the tier-model rule above in the UI.** `keyScopeImpact` only checks project scope, so the key's model lists (`KeyModelList`, and `ManualModelList` for typed-in models) lock tier-used rows ("Used by {tier}") and always keeps their ids in the draft; switching *All models* → *Only selected* prefills every listed model plus those ids. Stats come from `AIProviderModel.metadata`; models outside the catalog show `—`.
- **The live-name unique index is `lower("name")`, which `EntitySchema` cannot express.** The entity declares it `synchronize: false` (so `check-migrations` skips it), which means test DBs built by `synchronize` don't have it. The case-insensitive check that tests rely on is the service's `assertNameIsFree`, which is race-free because it runs under the `platform` row lock; the index is the backstop.
- **`lockPlatform` takes `FOR NO KEY UPDATE`, not `FOR UPDATE`.** Every FK insert that references `platform` (projects, users, …) takes `FOR KEY SHARE` on the platform row, which `FOR UPDATE` blocks until commit. `FOR NO KEY UPDATE` serialises tier writes just the same without stalling those inserts.
- **Tier entries go through the same project check as specific picks.** `platformModelTierService.getForRun` takes a `ProviderScope` and applies `aiKeyScope.rowAllowsScope` + `scopeAllows` to every entry; if the stored main entry fails, the whole tier is unavailable (it is checked before the healthy-first sort, so a down main doesn't change the answer). The `configId`s still come from a live tier on the caller's platform, never from the caller. Only the label lookups (`getManyForRun`, `firstCandidates`) use platform scope, because they return no credentials.
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index 0704a453aa3..b8c770d3b7d 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -3269,5 +3269,16 @@
"Couldn't load {key} models": "Couldn't load {key} models",
"Update this step to the latest version to use your tiers.": "Update this step to the latest version to use your tiers.",
"Your chat provider does not support embeddings. Switch it to a provider like OpenAI or Google for knowledge base to work.": "Your chat provider does not support embeddings. Switch it to a provider like OpenAI or Google for knowledge base to work.",
- "Your chat provider does not support knowledge base embeddings.": "Your chat provider does not support knowledge base embeddings."
+ "Your chat provider does not support knowledge base embeddings.": "Your chat provider does not support knowledge base embeddings.",
+ "Access": "Access",
+ "Sort": "Sort",
+ "Newest": "Newest",
+ "Cheapest": "Cheapest",
+ "Biggest context": "Biggest context",
+ "usedByTiersCount": "{count, plural, =1 {Used by 1 tier} other {Used by # tiers}}",
+ "Used by {tiers}": "Used by {tiers}",
+ "Not offered anymore": "Not offered anymore",
+ "New models from {provider} are added automatically.": "New models from {provider} are added automatically.",
+ "{on} of {total} on": "{on} of {total} on",
+ "Image generation": "Image generation"
}
diff --git a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/model-detail-row.tsx b/packages/web/src/app/routes/platform/setup/ai/components/model-detail-row.tsx
similarity index 100%
rename from packages/web/src/app/routes/platform/setup/ai/tiers-tab/model-detail-row.tsx
rename to packages/web/src/app/routes/platform/setup/ai/components/model-detail-row.tsx
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx
index d7052b8073b..005dc395dba 100644
--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx
+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx
@@ -6,6 +6,7 @@ import {
CloudflareGatewayProviderConfig,
formErrors,
OpenAICompatibleProviderConfig,
+ PlatformModelTier,
Project,
ProviderModelConfig,
UpdateAIProviderRequest,
@@ -13,7 +14,7 @@ import {
} from '@activepieces/shared';
import { useQuery } from '@tanstack/react-query';
import { t } from 'i18next';
-import { Activity, KeyRound, Trash2 } from 'lucide-react';
+import { KeyRound, RefreshCw, Trash2 } from 'lucide-react';
import { useRef, useState } from 'react';
import { z } from 'zod';
@@ -30,6 +31,7 @@ import {
LeaveWithoutSavingDialog,
useWarnBeforeLosingChanges,
} from '@/components/custom/leave-without-saving';
+import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -40,6 +42,7 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { AiProviderInfo } from '@/features/agents';
import {
KeyScopeImpact,
@@ -51,9 +54,9 @@ import { platformModelTierQueries } from '@/features/platform-admin/hooks/platfo
import { AdminControl, adminControl } from '@/lib/admin-control';
import { formatUtils } from '@/lib/format-utils';
+import { KeyModelList } from './key-model-list';
import { KeyStatusBadge } from './key-status';
import { ManualModelList } from './manual-model-list';
-import { ModelSelectionPanel } from './model-selection-panel';
import { ProjectSelectionPanel } from './project-selection-panel';
import { providerCredentials } from './provider-credentials';
import { ProviderLogo } from './provider-logo';
@@ -112,6 +115,19 @@ export function ConfigDetail({
type: AIProviderModelType.TEXT,
})),
];
+ const staleIds = draft.modelIds.filter(
+ (modelId) => !models.some((model) => model.id === modelId),
+ );
+ const tiersByModel = tierNamesByModel({
+ tiers: tiers ?? [],
+ configId: config.id,
+ });
+ const usedByTierCount = (tiers ?? []).filter((tier) =>
+ tier.entries.some((entry) => entry.configId === config.id),
+ ).length;
+ const withTierModels = (modelIds: string[]) => [
+ ...new Set([...modelIds, ...tiersByModel.keys()]),
+ ];
const dirty = JSON.stringify(draft) !== JSON.stringify(draftOf(config));
const leaveBlocker = useWarnBeforeLosingChanges({
hasChanges: dirty,
@@ -127,6 +143,14 @@ export function ConfigDetail({
]
.filter(Boolean)
.join(' · ');
+ const metaLine = [
+ info.name,
+ usedByTierCount > 0 && t('usedByTiersCount', { count: usedByTierCount }),
+ config.enabledForChat && t('Chat provider'),
+ statusDetail,
+ ]
+ .filter(Boolean)
+ .join(' · ');
const nameMissing = draft.name.trim().length === 0;
const enabledModelCount = manualModels
? draft.models.length
@@ -204,192 +228,228 @@ export function ConfigDetail({
description={
<span className="flex items-center gap-2">
<ProviderLogo info={info} size="sm" />
- {info.name}
+ {metaLine}
</span>
}
resources={adminPageResources.aiProviders}
- />
-
- <AdminSection
- title={t('General')}
- description={t('How this key is labelled and authorised.')}
>
- <SettingsPanel flush>
- <div className="flex flex-col gap-2 px-5 py-4">
- <Label htmlFor="config-name">{t('Name')}</Label>
- <Input
- id="config-name"
- value={draft.name}
- onChange={(event) =>
- setDraft({ ...draft, name: event.target.value })
- }
- className="max-w-sm"
- aria-invalid={nameMissing}
- />
- {nameMissing && (
- <p className="text-sm text-danger-11">{t(formErrors.required)}</p>
- )}
- </div>
- <SettingsRow
- icon={<KeyRound />}
- title={t('Credentials')}
- description={t('Stored securely')}
- >
- <Button
- variant="outline"
- size="sm"
- onClick={onReplaceCredentials}
- {...adminControl(AdminControl.AI_PROVIDER_KEY_CREDENTIALS_OPEN)}
- >
- {t('Replace')}
- </Button>
- </SettingsRow>
- <SettingsRow
- icon={<Activity />}
- title={t('Status')}
- description={statusDetail || undefined}
- >
- <Button
- variant="outline"
- size="sm"
- loading={isRechecking}
- onClick={onRecheck}
- {...adminControl(AdminControl.AI_PROVIDER_KEY_RECHECK_RUN)}
- >
- {t('Recheck')}
- </Button>
- </SettingsRow>
- </SettingsPanel>
- </AdminSection>
+ <Button
+ variant="outline"
+ size="sm"
+ loading={isRechecking}
+ onClick={onRecheck}
+ {...adminControl(AdminControl.AI_PROVIDER_KEY_RECHECK_RUN)}
+ >
+ <RefreshCw className="size-4" />
+ {t('Recheck')}
+ </Button>
+ </AdminPageHeader>
- <AdminSection
- title={
- <SectionTitle
+ <Tabs defaultValue="models" className="flex flex-col gap-6">
+ <TabsList
+ variant="outline"
+ className="w-full justify-start border-b border-gray-6"
+ >
+ <TabsTrigger variant="outline" value="models">
+ {t('Models')}
+ {!isLoadingModels && <TabCount count={enabledModelCount} />}
+ </TabsTrigger>
+ <TabsTrigger variant="outline" value="access">
+ {t('Access')}
+ <TabCount count={allowedProjectCount} />
+ </TabsTrigger>
+ <TabsTrigger variant="outline" value="settings">
+ {t('Settings')}
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent
+ value="models"
+ forceMount
+ className="mt-0 data-[state=inactive]:hidden"
+ >
+ <AdminSection
title={t('Models')}
- count={isLoadingModels ? undefined : enabledModelCount}
- />
- }
- description={
- manualModels
- ? t('Model ids exposed through this key.')
- : t('Which of this key’s models the platform may use.')
- }
- action={
- manualModels ? undefined : (
- <ScopeTabs
- value={draft.modelScope}
- onChange={(value) =>
- setDraft({
- ...draft,
- modelScope: value === 'all' ? 'all' : 'selected',
- modelIds: value === 'all' ? [] : draft.modelIds,
- })
- }
- options={[
- { value: 'all', label: t('All models') },
- { value: 'selected', label: t('Only selected') },
- ]}
- />
- )
- }
- >
- {manualModels ? (
- <ManualModelList
- models={draft.models}
- suggestedModelIds={suggestedModelIds}
- onChange={(models) => setDraft({ ...draft, models })}
- />
- ) : (
- draft.modelScope === 'selected' && (
- <ModelSelectionPanel
- models={selectableModels}
- selectedIds={draft.modelIds}
- isLoading={isLoadingModels}
- onChange={(modelIds) => setDraft({ ...draft, modelIds })}
- />
- )
- )}
- </AdminSection>
+ description={
+ manualModels
+ ? t('Model ids exposed through this key.')
+ : t('Which of this key’s models the platform may use.')
+ }
+ action={
+ manualModels ? undefined : (
+ <ScopeTabs
+ value={draft.modelScope}
+ disabled={isLoadingModels}
+ onChange={(value) =>
+ setDraft({
+ ...draft,
+ modelScope: value === 'all' ? 'all' : 'selected',
+ modelIds:
+ value === 'all'
+ ? []
+ : withTierModels(models.map((model) => model.id)),
+ })
+ }
+ options={[
+ { value: 'all', label: t('All models') },
+ { value: 'selected', label: t('Only selected') },
+ ]}
+ />
+ )
+ }
+ >
+ {manualModels ? (
+ <ManualModelList
+ models={draft.models}
+ suggestedModelIds={suggestedModelIds}
+ tiersByModel={tiersByModel}
+ onChange={(models) => setDraft({ ...draft, models })}
+ />
+ ) : (
+ <KeyModelList
+ config={config}
+ models={draft.modelScope === 'all' ? models : selectableModels}
+ staleIds={staleIds}
+ tiersByModel={tiersByModel}
+ allModels={draft.modelScope === 'all'}
+ selectedIds={draft.modelIds}
+ isLoading={isLoadingModels}
+ onChange={(modelIds) =>
+ setDraft({ ...draft, modelIds: withTierModels(modelIds) })
+ }
+ />
+ )}
+ </AdminSection>
+ </TabsContent>
- <AdminSection
- title={
- <SectionTitle
+ <TabsContent
+ value="access"
+ forceMount
+ className="mt-0 data-[state=inactive]:hidden"
+ >
+ <AdminSection
title={t('Project access')}
- count={allowedProjectCount}
- />
- }
- description={
- draft.projectScope === 'except'
- ? t(
- 'Every project except these — new projects get access automatically.',
- )
- : draft.projectScope === 'selected'
- ? t('Only these projects can use this key.')
- : t('Every project on this platform can use it.')
- }
- action={
- <ScopeTabs
- value={draft.projectScope}
- onChange={(value) =>
- setDraft({
- ...draft,
- projectScope:
- value === 'all'
- ? 'all'
- : value === 'except'
- ? 'except'
- : 'selected',
- projectIds: value === 'all' ? [] : draft.projectIds,
- })
+ description={
+ draft.projectScope === 'except'
+ ? t(
+ 'Every project except these — new projects get access automatically.',
+ )
+ : draft.projectScope === 'selected'
+ ? t('Only these projects can use this key.')
+ : t('Every project on this platform can use it.')
}
- options={[
- { value: 'all', label: t('All') },
- { value: 'selected', label: t('Only selected') },
- { value: 'except', label: t('All except') },
- ]}
- />
- }
- >
- {draft.projectScope !== 'all' && (
- <ProjectSelectionPanel
- projects={projects}
- selectedIds={draft.projectIds}
- onChange={(projectIds) => setDraft({ ...draft, projectIds })}
- />
- )}
- </AdminSection>
+ action={
+ <ScopeTabs
+ value={draft.projectScope}
+ onChange={(value) =>
+ setDraft({
+ ...draft,
+ projectScope:
+ value === 'all'
+ ? 'all'
+ : value === 'except'
+ ? 'except'
+ : 'selected',
+ projectIds: value === 'all' ? [] : draft.projectIds,
+ })
+ }
+ options={[
+ { value: 'all', label: t('All') },
+ { value: 'selected', label: t('Only selected') },
+ { value: 'except', label: t('All except') },
+ ]}
+ />
+ }
+ >
+ {draft.projectScope !== 'all' && (
+ <ProjectSelectionPanel
+ projects={projects}
+ selectedIds={draft.projectIds}
+ onChange={(projectIds) => setDraft({ ...draft, projectIds })}
+ />
+ )}
+ </AdminSection>
+ </TabsContent>
- <DangerZone>
- <SettingsRow
- title={t('Delete this key')}
- description={t('Flows and agents that use it will fail.')}
+ <TabsContent
+ value="settings"
+ forceMount
+ className="mt-0 flex flex-col gap-8 data-[state=inactive]:hidden"
>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => setDeleteOpen(true)}
- {...adminControl(AdminControl.AI_PROVIDER_KEY_DELETE_OPEN)}
+ <AdminSection
+ title={t('General')}
+ description={t('How this key is labelled and authorised.')}
>
- <Trash2 className="size-4" />
- {t('Delete')}
- </Button>
- </SettingsRow>
- <ConfirmationDeleteDialog
- open={deleteOpen}
- onOpenChange={setDeleteOpen}
- title={t('Delete {name}', { name: config.name })}
- message={t('Flows and agents that use this key will fail.')}
- entityName={config.name}
- showToast={true}
- onError={() => undefined}
- controlId={AdminControl.AI_PROVIDER_KEY_DELETE_CONFIRM}
- mutationFn={async () => {
- await onDelete();
- leavingOnPurpose.current = true;
- onBack();
- }}
- />
- </DangerZone>
+ <SettingsPanel flush>
+ <div className="flex flex-col gap-2 px-5 py-4">
+ <Label htmlFor="config-name">{t('Name')}</Label>
+ <Input
+ id="config-name"
+ value={draft.name}
+ onChange={(event) =>
+ setDraft({ ...draft, name: event.target.value })
+ }
+ className="max-w-sm"
+ aria-invalid={nameMissing}
+ />
+ {nameMissing && (
+ <p className="text-sm text-danger-11">
+ {t(formErrors.required)}
+ </p>
+ )}
+ </div>
+ <SettingsRow
+ icon={<KeyRound />}
+ title={t('Credentials')}
+ description={t('Stored securely')}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onReplaceCredentials}
+ {...adminControl(
+ AdminControl.AI_PROVIDER_KEY_CREDENTIALS_OPEN,
+ )}
+ >
+ {t('Replace')}
+ </Button>
+ </SettingsRow>
+ </SettingsPanel>
+ </AdminSection>
+
+ <DangerZone>
+ <SettingsRow
+ title={t('Delete this key')}
+ description={t('Flows and agents that use it will fail.')}
+ >
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => setDeleteOpen(true)}
+ {...adminControl(AdminControl.AI_PROVIDER_KEY_DELETE_OPEN)}
+ >
+ <Trash2 className="size-4" />
+ {t('Delete')}
+ </Button>
+ </SettingsRow>
+ <ConfirmationDeleteDialog
+ open={deleteOpen}
+ onOpenChange={setDeleteOpen}
+ title={t('Delete {name}', { name: config.name })}
+ message={t('Flows and agents that use this key will fail.')}
+ entityName={config.name}
+ showToast={true}
+ onError={() => undefined}
+ controlId={AdminControl.AI_PROVIDER_KEY_DELETE_CONFIRM}
+ mutationFn={async () => {
+ await onDelete();
+ leavingOnPurpose.current = true;
+ onBack();
+ }}
+ />
+ </DangerZone>
+ </TabsContent>
+ </Tabs>
{dirty && (
<div className="sticky bottom-4 z-20 mt-auto flex justify-center px-4">
@@ -454,19 +514,34 @@ export function ConfigDetail({
);
}
-function SectionTitle({ title, count }: { title: string; count?: number }) {
+function TabCount({ count }: { count: number }) {
return (
- <span className="flex items-baseline gap-2">
- {title}
- {count !== undefined && (
- <span className="text-sm font-normal tabular-nums text-gray-11">
- {count}
- </span>
- )}
- </span>
+ <Badge variant="secondary" className="ml-2 tabular-nums">
+ {count}
+ </Badge>
);
}
+function tierNamesByModel({
+ tiers,
+ configId,
+}: {
+ tiers: PlatformModelTier[];
+ configId: string;
+}): Map<string, string[]> {
+ return tiers.reduce((byModel, tier) => {
+ tier.entries
+ .filter((entry) => entry.configId === configId)
+ .forEach((entry) =>
+ byModel.set(entry.modelId, [
+ ...(byModel.get(entry.modelId) ?? []),
+ tier.name,
+ ]),
+ );
+ return byModel;
+ }, new Map<string, string[]>());
+}
+
function scopeImpactText(impact: KeyScopeImpact): string {
if (impact.lostProjects > 0) {
return t('tierLosesProjects', {
@@ -482,15 +557,17 @@ function scopeImpactText(impact: KeyScopeImpact): string {
function ScopeTabs({
value,
+ disabled = false,
onChange,
options,
}: {
value: string;
+ disabled?: boolean;
onChange: (value: string) => void;
options: { value: string; label: string }[];
}) {
return (
- <Select value={value} onValueChange={onChange}>
+ <Select value={value} onValueChange={onChange} disabled={disabled}>
<SelectTrigger size="sm" className="w-44 shrink-0">
<SelectValue />
</SelectTrigger>
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsx
index 53e9c95a53f..0888d7223d6 100644
--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsx
+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsx
@@ -2,6 +2,7 @@ import { AIProviderName, tryCatch } from '@activepieces/core-utils';
import {
AIProviderWithoutSensitiveData,
PlatformAdminSurface,
+ PlatformModelTier,
Project,
} from '@activepieces/shared';
import { useQueryClient } from '@tanstack/react-query';
@@ -56,6 +57,7 @@ import {
aiProviderMutations,
aiProviderQueries,
} from '@/features/platform-admin';
+import { platformModelTierQueries } from '@/features/platform-admin/hooks/platform-model-tier-hooks';
import { projectCollectionUtils } from '@/features/projects';
import { platformHooks } from '@/hooks/platform-hooks';
import { AdminControl, adminControl } from '@/lib/admin-control';
@@ -88,6 +90,7 @@ export function ProvidersTab() {
refetch,
} = aiProviderQueries.useAiProviderConfigs();
const { data: projects } = projectCollectionUtils.useAllPlatformProjects();
+ const { data: tiers } = platformModelTierQueries.useAdminList();
const configs = (providers ?? []).filter(
(provider) => provider.provider !== AIProviderName.ACTIVEPIECES,
);
@@ -281,6 +284,7 @@ export function ProvidersTab() {
provider={provider}
configs={configs.filter((config) => config.provider === provider)}
projects={projects}
+ tiers={tiers ?? []}
locked={locked}
onAdd={() => openConnect(provider)}
onOpen={openConfig}
@@ -370,6 +374,7 @@ function ProviderGroup({
provider,
configs,
projects,
+ tiers,
locked,
onAdd,
onOpen,
@@ -378,6 +383,7 @@ function ProviderGroup({
provider: AIProviderName;
configs: AIProviderWithoutSensitiveData[];
projects: Project[];
+ tiers: PlatformModelTier[];
locked: boolean;
onAdd: () => void;
onOpen: (id: string) => void;
@@ -418,6 +424,11 @@ function ProviderGroup({
key={config.id}
config={config}
projects={projects}
+ tierCount={
+ tiers.filter((tier) =>
+ tier.entries.some((entry) => entry.configId === config.id),
+ ).length
+ }
locked={locked}
onOpen={() => onOpen(config.id)}
onDelete={() => onDelete(config.id)}
@@ -430,12 +441,14 @@ function ProviderGroup({
function ConfigRow({
config,
projects,
+ tierCount,
locked,
onOpen,
onDelete,
}: {
config: AIProviderWithoutSensitiveData;
projects: Project[];
+ tierCount: number;
locked: boolean;
onOpen: () => void;
onDelete: () => Promise<unknown>;
@@ -494,6 +507,12 @@ function ConfigRow({
{modelsLabel}
<span aria-hidden> · </span>
{projectsLabel}
+ {tierCount > 0 && (
+ <>
+ <span aria-hidden> · </span>
+ {t('usedByTiersCount', { count: tierCount })}
+ </>
+ )}
</p>
</TooltipTrigger>
{config.modelIds.length > 0 && (
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/key-model-filters.ts b/packages/web/src/app/routes/platform/setup/ai/providers-tab/key-model-filters.ts
new file mode 100644
index 00000000000..b3388c4a374
--- /dev/null
+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/key-model-filters.ts
@@ -0,0 +1,109 @@
+import { AIProviderModel, AIProviderModelType } from '@activepieces/shared';
+
+function apply({
+ models,
+ search,
+ capabilities,
+ sort,
+ selectedOnly,
+ selectedIds,
+}: {
+ models: AIProviderModel[];
+ search: string;
+ capabilities: ModelCapabilityFilter[];
+ sort: ModelSort;
+ selectedOnly: boolean;
+ selectedIds: string[];
+}): AIProviderModel[] {
+ const needle = search.trim().toLowerCase();
+ return models
+ .filter(
+ (model) =>
+ needle === '' ||
+ model.name.toLowerCase().includes(needle) ||
+ model.id.toLowerCase().includes(needle),
+ )
+ .filter((model) =>
+ capabilities.every((capability) => hasCapability({ model, capability })),
+ )
+ .filter((model) => !selectedOnly || selectedIds.includes(model.id))
+ .sort((a, b) => compareModels({ a, b, sort }));
+}
+
+function hasCapability({
+ model,
+ capability,
+}: {
+ model: AIProviderModel;
+ capability: ModelCapabilityFilter;
+}): boolean {
+ switch (capability) {
+ case 'toolCalling':
+ return model.metadata?.supportsToolCalling === true;
+ case 'reasoning':
+ return model.metadata?.supportsReasoning === true;
+ case 'vision':
+ return model.metadata?.supportsVision === true;
+ case 'image':
+ return model.type === AIProviderModelType.IMAGE;
+ }
+}
+
+function compareModels({
+ a,
+ b,
+ sort,
+}: {
+ a: AIProviderModel;
+ b: AIProviderModel;
+ sort: ModelSort;
+}): number {
+ const left = sortValueOf({ model: a, sort });
+ const right = sortValueOf({ model: b, sort });
+ if (left === right) {
+ return a.name.localeCompare(b.name);
+ }
+ if (left === undefined) {
+ return 1;
+ }
+ if (right === undefined) {
+ return -1;
+ }
+ return (left < right ? -1 : 1) * SORT_DIRECTION[sort];
+}
+
+function sortValueOf({
+ model,
+ sort,
+}: {
+ model: AIProviderModel;
+ sort: ModelSort;
+}): string | number | undefined {
+ switch (sort) {
+ case 'newest':
+ return model.metadata?.releaseDate;
+ case 'cheapest':
+ return model.metadata?.inputCostPerMillionTokens;
+ case 'context':
+ return model.metadata?.contextTokens;
+ case 'name':
+ return model.name.toLowerCase();
+ }
+}
+
+const SORT_DIRECTION: Record<ModelSort, 1 | -1> = {
+ newest: -1,
+ cheapest: 1,
+ context: -1,
+ name: 1,
+};
+
+export const keyModelFilters = { apply };
+
+export type ModelCapabilityFilter =
+ | 'toolCalling'
+ | 'reasoning'
+ | 'vision'
+ | 'image';
+
+export type ModelSort = 'newest' | 'cheapest' | 'context' | 'name';
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/key-model-list.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/key-model-list.tsx
new file mode 100644
index 00000000000..f06075a8643
--- /dev/null
+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/key-model-list.tsx
@@ -0,0 +1,386 @@
+import {
+ AIProviderModel,
+ AIProviderModelType,
+ AIProviderWithoutSensitiveData,
+} from '@activepieces/shared';
+import { t } from 'i18next';
+import {
+ Brain,
+ Eye,
+ ImageIcon,
+ ListChecks,
+ LucideIcon,
+ Search,
+ Wrench,
+} from 'lucide-react';
+import { useState } from 'react';
+
+import { InputWithIcon } from '@/components/custom/input-with-icon';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Skeleton } from '@/components/ui/skeleton';
+import { modelMeta } from '@/features/agents/ai-model/model-meta';
+import { cn } from '@/lib/utils';
+
+import { ModelDetailRow } from '../components/model-detail-row';
+
+import {
+ keyModelFilters,
+ ModelCapabilityFilter,
+ ModelSort,
+} from './key-model-filters';
+
+export function KeyModelList({
+ config,
+ models,
+ staleIds,
+ tiersByModel,
+ allModels,
+ selectedIds,
+ isLoading,
+ onChange,
+}: KeyModelListProps) {
+ const [search, setSearch] = useState('');
+ const [capabilities, setCapabilities] = useState<ModelCapabilityFilter[]>([]);
+ const [sort, setSort] = useState<ModelSort>('newest');
+ const [selectedOnly, setSelectedOnly] = useState(false);
+ const [shown, setShown] = useState(PAGE_SIZE);
+
+ const isOn = (modelId: string) =>
+ allModels || selectedIds.includes(modelId) || tiersByModel.has(modelId);
+ const filtered = keyModelFilters.apply({
+ models,
+ search,
+ capabilities,
+ sort,
+ selectedOnly: selectedOnly && !allModels,
+ selectedIds,
+ });
+ const page = filtered.slice(0, shown);
+ const filteredIds = filtered.map((model) => model.id);
+ const onCount = allModels
+ ? models.length
+ : models.filter((model) => isOn(model.id)).length;
+ const providerName = modelMeta.providerInfoOf({
+ provider: config.provider,
+ }).name;
+
+ const resetPaging = () => setShown(PAGE_SIZE);
+ const toggleModel = (modelId: string) => {
+ if (allModels || tiersByModel.has(modelId)) {
+ return;
+ }
+ onChange(
+ selectedIds.includes(modelId)
+ ? selectedIds.filter((id) => id !== modelId)
+ : [...selectedIds, modelId],
+ );
+ };
+ const toggleCapability = (capability: ModelCapabilityFilter) => {
+ setCapabilities(
+ capabilities.includes(capability)
+ ? capabilities.filter((current) => current !== capability)
+ : [...capabilities, capability],
+ );
+ resetPaging();
+ };
+
+ return (
+ <div className="flex flex-col overflow-hidden rounded-xl border border-gray-6/60">
+ <div className="flex flex-col gap-3 p-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <InputWithIcon
+ icon={<Search className="size-4 shrink-0 text-gray-11" />}
+ value={search}
+ onChange={(event) => {
+ setSearch(event.target.value);
+ resetPaging();
+ }}
+ placeholder={t('Search models')}
+ className="max-w-xs grow-0"
+ />
+ <Select
+ value={sort}
+ onValueChange={(value) => {
+ setSort(sortOf(value));
+ resetPaging();
+ }}
+ >
+ <SelectTrigger className="w-40 shrink-0" aria-label={t('Sort')}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {SORTS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {sortLabel(option)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {CAPABILITY_CHIPS.map(({ capability, icon }) => (
+ <FilterCheck
+ key={capability}
+ icon={icon}
+ label={capabilityLabel(capability)}
+ checked={capabilities.includes(capability)}
+ onCheckedChange={() => toggleCapability(capability)}
+ />
+ ))}
+ {!allModels && (
+ <FilterCheck
+ icon={ListChecks}
+ label={t('Selected only')}
+ checked={selectedOnly}
+ onCheckedChange={(checked) => {
+ setSelectedOnly(checked);
+ resetPaging();
+ }}
+ />
+ )}
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-gray-6/60 bg-gray-2 px-4 py-2 text-xs text-gray-11">
+ <span className="tabular-nums">
+ {isLoading
+ ? t('Loading models…')
+ : t('{on} of {total} on', { on: onCount, total: models.length })}
+ </span>
+ {allModels ? (
+ <span>
+ {t('New models from {provider} are added automatically.', {
+ provider: providerName,
+ })}
+ </span>
+ ) : (
+ filtered.length > 0 && (
+ <span className="flex items-center gap-1">
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() =>
+ onChange([...new Set([...selectedIds, ...filteredIds])])
+ }
+ >
+ {t('Select all')}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() =>
+ onChange(
+ selectedIds.filter((id) => !filteredIds.includes(id)),
+ )
+ }
+ >
+ {t('Clear')}
+ </Button>
+ </span>
+ )
+ )}
+ </div>
+
+ <div className="flex flex-col border-t border-gray-6/60">
+ {isLoading &&
+ [0, 1, 2].map((row) => (
+ <div
+ key={row}
+ className="flex items-center gap-3 border-b border-gray-6/60 px-4 py-3 last:border-b-0"
+ >
+ <Skeleton className="size-4 rounded-sm" />
+ <div className="flex flex-1 flex-col gap-1.5">
+ <Skeleton className="h-3.5 w-40" />
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </div>
+ ))}
+ {!isLoading && filtered.length === 0 && (
+ <p className="px-4 py-6 text-center text-sm text-gray-11">
+ {models.length === 0
+ ? t('No models found')
+ : selectedOnly
+ ? t('No model is selected yet.')
+ : t('No model matches your search.')}
+ </p>
+ )}
+ {!isLoading &&
+ page.map((model) => {
+ const tierNames = tiersByModel.get(model.id);
+ const locked = allModels || tierNames !== undefined;
+ return (
+ <label
+ key={model.id}
+ className={cn(
+ 'flex items-center gap-3 border-b border-gray-6/60 pl-4 pr-3 last:border-b-0',
+ locked ? 'cursor-default' : 'cursor-pointer hover:bg-gray-2',
+ )}
+ >
+ <Checkbox
+ checked={isOn(model.id)}
+ disabled={locked}
+ onCheckedChange={() => toggleModel(model.id)}
+ aria-label={model.name}
+ />
+ <ModelDetailRow
+ name={model.name}
+ config={config}
+ model={model}
+ nested
+ nameSuffix={
+ <ModelBadges
+ model={model}
+ stale={staleIds.includes(model.id)}
+ tierNames={tierNames}
+ />
+ }
+ />
+ </label>
+ );
+ })}
+ {filtered.length > page.length && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="m-2 self-start"
+ onClick={() => setShown((current) => current + PAGE_SIZE)}
+ >
+ {t('Show {count} more', {
+ count: Math.min(PAGE_SIZE, filtered.length - page.length),
+ })}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function FilterCheck({
+ icon: Icon,
+ label,
+ checked,
+ onCheckedChange,
+}: {
+ icon: LucideIcon;
+ label: string;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+}) {
+ return (
+ <label
+ className={cn(
+ 'inline-flex h-8 cursor-pointer select-none items-center gap-2 rounded-lg border border-gray-6 bg-gray-1 px-2.5 text-xs font-medium text-gray-12 transition-colors hover:bg-gray-2',
+ checked && 'border-gray-8 bg-gray-3 hover:bg-gray-3',
+ )}
+ >
+ <Checkbox
+ checked={checked}
+ onCheckedChange={(value) => onCheckedChange(value === true)}
+ />
+ <Icon className="size-3.5 text-gray-11" />
+ {label}
+ </label>
+ );
+}
+
+function ModelBadges({
+ model,
+ stale,
+ tierNames,
+}: {
+ model: AIProviderModel;
+ stale: boolean;
+ tierNames: string[] | undefined;
+}) {
+ return (
+ <>
+ {model.id !== model.name && (
+ <span className="hidden truncate font-mono text-xs text-gray-10 sm:inline">
+ {model.id}
+ </span>
+ )}
+ {model.type === AIProviderModelType.IMAGE && (
+ <Badge variant="secondary" className="shrink-0">
+ {t('Image')}
+ </Badge>
+ )}
+ {stale && (
+ <Badge variant="warning" className="shrink-0">
+ {t('Not offered anymore')}
+ </Badge>
+ )}
+ {tierNames !== undefined && (
+ <Badge variant="info" className="shrink-0">
+ {t('Used by {tiers}', { tiers: tierNames.join(', ') })}
+ </Badge>
+ )}
+ </>
+ );
+}
+
+function sortOf(value: string): ModelSort {
+ return SORTS.find((option) => option === value) ?? 'newest';
+}
+
+function sortLabel(sort: ModelSort): string {
+ switch (sort) {
+ case 'newest':
+ return t('Newest');
+ case 'cheapest':
+ return t('Cheapest');
+ case 'context':
+ return t('Biggest context');
+ case 'name':
+ return t('Name');
+ }
+}
+
+function capabilityLabel(capability: ModelCapabilityFilter): string {
+ switch (capability) {
+ case 'toolCalling':
+ return t('Tool calling');
+ case 'reasoning':
+ return t('Reasoning');
+ case 'vision':
+ return t('Vision');
+ case 'image':
+ return t('Image generation');
+ }
+}
+
+const PAGE_SIZE = 20;
+
+const SORTS: ModelSort[] = ['newest', 'cheapest', 'context', 'name'];
+
+const CAPABILITY_CHIPS: {
+ capability: ModelCapabilityFilter;
+ icon: LucideIcon;
+}[] = [
+ { capability: 'toolCalling', icon: Wrench },
+ { capability: 'reasoning', icon: Brain },
+ { capability: 'vision', icon: Eye },
+ { capability: 'image', icon: ImageIcon },
+];
+
+type KeyModelListProps = {
+ config: AIProviderWithoutSensitiveData;
+ models: AIProviderModel[];
+ staleIds: string[];
+ tiersByModel: Map<string, string[]>;
+ allModels: boolean;
+ selectedIds: string[];
+ isLoading: boolean;
+ onChange: (modelIds: string[]) => void;
+};
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx
index d5e1f70a61c..5cca3d09e33 100644
--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx
+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx
@@ -3,6 +3,7 @@ import { t } from 'i18next';
import { Plus, X } from 'lucide-react';
import { useId, useState } from 'react';
+import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
@@ -16,10 +17,12 @@ import {
export function ManualModelList({
models,
suggestedModelIds = [],
+ tiersByModel = new Map(),
onChange,
}: {
models: ProviderModelConfig[];
suggestedModelIds?: string[];
+ tiersByModel?: Map<string, string[]>;
onChange: (models: ProviderModelConfig[]) => void;
}) {
const suggestionListId = useId();
@@ -93,13 +96,22 @@ export function ManualModelList({
)}
</p>
) : (
- <div className="flex flex-wrap gap-1.5 border-t border-gray-6/60 p-3">
+ <div className="flex flex-col border-t border-gray-6/60">
{models.map((model) => (
- <span
+ <div
key={model.modelId}
- className="flex items-center gap-1.5 rounded-md bg-gray-3 px-2 py-1 font-mono text-xs"
+ className="flex items-center gap-3 border-b border-gray-6/60 px-4 py-2.5 last:border-b-0"
>
- {model.modelId}
+ <span className="min-w-0 flex-1 truncate font-mono text-sm">
+ {model.modelId}
+ </span>
+ {tiersByModel.has(model.modelId) && (
+ <Badge variant="info" className="shrink-0">
+ {t('Used by {tiers}', {
+ tiers: tiersByModel.get(model.modelId)?.join(', '),
+ })}
+ </Badge>
+ )}
<button
type="button"
title={t('Model Type')}
@@ -112,12 +124,16 @@ export function ManualModelList({
),
)
}
- className="rounded-md bg-gray-1 px-1 py-px font-sans text-xs text-gray-11 transition-colors hover:text-gray-12"
+ className="rounded-md border border-gray-6 px-2 py-0.5 text-xs text-gray-11 transition-colors hover:bg-gray-3 hover:text-gray-12"
>
{modelTypeLabel(model.modelType)}
</button>
- <button
+ <Button
type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('Remove')}
+ disabled={tiersByModel.has(model.modelId)}
onClick={() =>
onChange(
models.filter(
@@ -125,11 +141,10 @@ export function ManualModelList({
),
)
}
- className="text-gray-11 transition-colors hover:text-gray-12"
>
- <X className="size-3" />
- </button>
- </span>
+ <X className="size-3.5" />
+ </Button>
+ </div>
))}
</div>
)}
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/model-selection-panel.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/model-selection-panel.tsx
deleted file mode 100644
index ec9daae25c4..00000000000
--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/model-selection-panel.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import { AIProviderModel } from '@activepieces/shared';
-import { ColumnDef } from '@tanstack/react-table';
-import { t } from 'i18next';
-import { Search, Sparkles } from 'lucide-react';
-import { useState } from 'react';
-
-import { DataTable, RowDataWithActions } from '@/components/custom/data-table';
-import { InputWithIcon } from '@/components/custom/input-with-icon';
-import { Checkbox } from '@/components/ui/checkbox';
-
-import { SelectedOnlyButton } from '../components/selected-only-button';
-import { pageSlice, TablePagination } from '../components/table-pagination';
-
-export function ModelSelectionPanel({
- models,
- selectedIds,
- isLoading,
- onChange,
-}: {
- models: AIProviderModel[];
- selectedIds: string[];
- isLoading: boolean;
- onChange: (modelIds: string[]) => void;
-}) {
- const [search, setSearch] = useState('');
- const [page, setPage] = useState(0);
- const [showSelectedOnly, setShowSelectedOnly] = useState(false);
-
- const filtered = models
- .filter((model) =>
- model.name.toLowerCase().includes(search.trim().toLowerCase()),
- )
- .filter((model) => !showSelectedOnly || selectedIds.includes(model.id));
- const { rows, page: currentPage } = pageSlice({
- items: filtered,
- page,
- pageSize: PAGE_SIZE,
- });
- const allRowsSelected =
- rows.length > 0 && rows.every((model) => selectedIds.includes(model.id));
-
- const toggleModel = (modelId: string) => {
- onChange(
- selectedIds.includes(modelId)
- ? selectedIds.filter((id) => id !== modelId)
- : [...selectedIds, modelId],
- );
- };
- const toggleRows = () => {
- const rowIds = rows.map((model) => model.id);
- onChange(
- allRowsSelected
- ? selectedIds.filter((id) => !rowIds.includes(id))
- : [...new Set([...selectedIds, ...rowIds])],
- );
- };
-
- const columns: ColumnDef<RowDataWithActions<AIProviderModel>>[] = [
- {
- accessorKey: 'name',
- header: () => (
- <div className="flex items-center gap-2.5">
- <Checkbox checked={allRowsSelected} onCheckedChange={toggleRows} />
- <span>{t('Model')}</span>
- </div>
- ),
- cell: ({ row }) => (
- <div className="flex items-center gap-2.5">
- <Checkbox
- checked={selectedIds.includes(row.original.id)}
- className="pointer-events-none"
- />
- <div className="flex flex-col gap-0.5">
- <span className="text-sm font-medium">{row.original.name}</span>
- {row.original.id !== row.original.name && (
- <span className="font-mono text-xs text-gray-11">
- {row.original.id}
- </span>
- )}
- </div>
- </div>
- ),
- },
- ];
-
- return (
- <div className="flex flex-col overflow-hidden rounded-xl border border-gray-6/60">
- <div className="flex flex-wrap items-center gap-2 p-3">
- <InputWithIcon
- icon={<Search className="size-4 shrink-0 text-gray-11" />}
- value={search}
- onChange={(event) => {
- setSearch(event.target.value);
- setPage(0);
- }}
- placeholder={t('Search models')}
- className="max-w-xs grow-0"
- />
- <SelectedOnlyButton
- pressed={showSelectedOnly}
- onToggle={() => {
- setShowSelectedOnly(!showSelectedOnly);
- setPage(0);
- }}
- />
- </div>
- <div className="border-t border-gray-6/60 [&_tbody_tr:last-child]:border-b-0 [&_thead]:border-t-0">
- <DataTable
- columns={columns}
- page={{ data: rows, next: null, previous: null }}
- isLoading={isLoading}
- isError={false}
- errorStateEntity={t('models')}
- hidePagination={true}
- onRowClick={(row) => toggleModel(row.id)}
- emptyStateTextTitle={t('No models found')}
- emptyStateTextDescription={
- showSelectedOnly
- ? t('No model is selected yet.')
- : t('No model matches your search.')
- }
- emptyStateIcon={<Sparkles className="size-10 text-gray-11" />}
- />
- </div>
- <TablePagination
- page={currentPage}
- pageSize={PAGE_SIZE}
- total={filtered.length}
- onPageChange={setPage}
- className="border-t border-gray-6/60 p-3"
- />
- </div>
- );
-}
-
-const PAGE_SIZE = 10;
diff --git a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsx b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsx
index fcc5bdaecdc..bf5f1dbd869 100644
--- a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsx
+++ b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsx
@@ -33,12 +33,11 @@ import { platformModelTierMutations } from '@/features/platform-admin/hooks/plat
import { AdminControl, adminControl } from '@/lib/admin-control';
import { cn } from '@/lib/utils';
+import { ModelDetailRow } from '../components/model-detail-row';
import { SectionHeader } from '../components/section-header';
import { KeyStatusBadge } from '../providers-tab/key-status';
import { ProviderLogo } from '../providers-tab/provider-logo';
-import { ModelDetailRow } from './model-detail-row';
-
export function SpecificModelsSection({
tiers,
ownKeys,
diff --git a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-entry-row.tsx b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-entry-row.tsx
index 63546f55152..f0544d76bdf 100644
--- a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-entry-row.tsx
+++ b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-entry-row.tsx
@@ -21,10 +21,9 @@ import {
import { EntryWarning, modelMeta } from '@/features/agents/ai-model/model-meta';
import { cn } from '@/lib/utils';
+import { ModelDetailRow } from '../components/model-detail-row';
import { keyStatusText } from '../providers-tab/key-status';
-import { ModelDetailRow } from './model-detail-row';
-
export function TierEntryRow({
entry,
index,
diff --git a/packages/web/test/app/routes/platform/setup/ai/config-detail-save.test.tsx b/packages/web/test/app/routes/platform/setup/ai/config-detail-save.test.tsx
index 9869f2a7a0b..5438c7c7a57 100644
--- a/packages/web/test/app/routes/platform/setup/ai/config-detail-save.test.tsx
+++ b/packages/web/test/app/routes/platform/setup/ai/config-detail-save.test.tsx
@@ -88,10 +88,9 @@ vi.mock('@/app/routes/platform/setup/ai/providers-tab/key-status', () => ({
KeyStatusBadge: () => null,
}));
-vi.mock(
- '@/app/routes/platform/setup/ai/providers-tab/model-selection-panel',
- () => ({ ModelSelectionPanel: () => null }),
-);
+vi.mock('@/app/routes/platform/setup/ai/providers-tab/key-model-list', () => ({
+ KeyModelList: () => null,
+}));
vi.mock(
'@/app/routes/platform/setup/ai/providers-tab/project-selection-panel',
@@ -201,11 +200,12 @@ describe('ConfigDetail save (manual models)', () => {
};
const flipTypeBadge = (modelId: string) => {
- const chip = Array.from(container.querySelectorAll('span')).find(
- (candidate) => candidate.textContent?.startsWith(modelId),
- );
- const badge = chip?.querySelector<HTMLButtonElement>(
- 'button[title="Model Type"]',
+ const badge = Array.from(
+ container.querySelectorAll<HTMLButtonElement>(
+ 'button[title="Model Type"]',
+ ),
+ ).find((candidate) =>
+ candidate.parentElement?.textContent?.startsWith(modelId),
);
expect(badge).toBeDefined();
act(() => {
diff --git a/packages/web/test/app/routes/platform/setup/ai/key-model-filters.test.ts b/packages/web/test/app/routes/platform/setup/ai/key-model-filters.test.ts
new file mode 100644
index 00000000000..ee9f431895d
--- /dev/null
+++ b/packages/web/test/app/routes/platform/setup/ai/key-model-filters.test.ts
@@ -0,0 +1,91 @@
+import { AIProviderModel, AIProviderModelType } from '@activepieces/shared';
+import { describe, expect, it } from 'vitest';
+
+import { keyModelFilters } from '@/app/routes/platform/setup/ai/providers-tab/key-model-filters';
+
+const model = (
+ id: string,
+ metadata: AIProviderModel['metadata'] = {},
+ type: AIProviderModelType = AIProviderModelType.TEXT,
+): AIProviderModel => ({ id, name: id.toUpperCase(), type, metadata });
+
+const MODELS: AIProviderModel[] = [
+ model('old-cheap', {
+ releaseDate: '2024-01',
+ inputCostPerMillionTokens: 0.1,
+ contextTokens: 8000,
+ supportsToolCalling: true,
+ }),
+ model('new-pricey', {
+ releaseDate: '2026-05-01',
+ inputCostPerMillionTokens: 15,
+ contextTokens: 1000000,
+ supportsToolCalling: true,
+ supportsReasoning: true,
+ }),
+ model('no-meta', undefined),
+ model('painter', {}, AIProviderModelType.IMAGE),
+];
+
+const ids = (models: AIProviderModel[]) => models.map((entry) => entry.id);
+
+const base = {
+ models: MODELS,
+ search: '',
+ capabilities: [],
+ sort: 'name' as const,
+ selectedOnly: false,
+ selectedIds: [],
+};
+
+describe('keyModelFilters.apply', () => {
+ it('matches the search on the model id, not only the name', () => {
+ expect(ids(keyModelFilters.apply({ ...base, search: 'pricey' }))).toEqual([
+ 'new-pricey',
+ ]);
+ });
+
+ it('keeps only models with every chosen capability', () => {
+ expect(
+ ids(
+ keyModelFilters.apply({
+ ...base,
+ capabilities: ['toolCalling', 'reasoning'],
+ }),
+ ),
+ ).toEqual(['new-pricey']);
+ expect(
+ ids(keyModelFilters.apply({ ...base, capabilities: ['image'] })),
+ ).toEqual(['painter']);
+ });
+
+ it('sorts newest first, mixed date formats, missing values last', () => {
+ expect(ids(keyModelFilters.apply({ ...base, sort: 'newest' }))).toEqual([
+ 'new-pricey',
+ 'old-cheap',
+ 'no-meta',
+ 'painter',
+ ]);
+ });
+
+ it('sorts cheapest first and biggest context first', () => {
+ expect(
+ ids(keyModelFilters.apply({ ...base, sort: 'cheapest' })).slice(0, 2),
+ ).toEqual(['old-cheap', 'new-pricey']);
+ expect(
+ ids(keyModelFilters.apply({ ...base, sort: 'context' })).slice(0, 2),
+ ).toEqual(['new-pricey', 'old-cheap']);
+ });
+
+ it('shows only selected models when asked', () => {
+ expect(
+ ids(
+ keyModelFilters.apply({
+ ...base,
+ selectedOnly: true,
+ selectedIds: ['painter', 'old-cheap'],
+ }),
+ ),
+ ).toEqual(['old-cheap', 'painter']);
+ });
+});
diff --git a/packages/web/test/app/routes/platform/setup/ai/key-model-list.test.tsx b/packages/web/test/app/routes/platform/setup/ai/key-model-list.test.tsx
new file mode 100644
index 00000000000..4e55e153cae
--- /dev/null
+++ b/packages/web/test/app/routes/platform/setup/ai/key-model-list.test.tsx
@@ -0,0 +1,112 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { AIProviderName } from '@activepieces/core-utils';
+import {
+ AIProviderModel,
+ AIProviderModelType,
+ AIProviderWithoutSensitiveData,
+} from '@activepieces/shared';
+import { fireEvent, render, screen } from '@testing-library/react';
+import * as React from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { KeyModelList } from '@/app/routes/platform/setup/ai/providers-tab/key-model-list';
+
+vi.mock('i18next', () => ({
+ t: (key: string, vars?: Record<string, unknown>) =>
+ key.replace(/\{(\w+)\}/g, (_, name) => String(vars?.[name] ?? name)),
+}));
+
+vi.mock('@/app/routes/platform/setup/ai/components/model-detail-row', () => ({
+ ModelDetailRow: ({
+ name,
+ nameSuffix,
+ }: {
+ name: string;
+ nameSuffix: React.ReactNode;
+ }) => (
+ <span>
+ {name}
+ {nameSuffix}
+ </span>
+ ),
+}));
+
+vi.mock('@/components/ui/select', () => ({
+ Select: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ SelectTrigger: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ SelectValue: () => null,
+ SelectContent: () => null,
+ SelectItem: () => null,
+}));
+
+const CONFIG: AIProviderWithoutSensitiveData = {
+ id: 'key-1',
+ name: 'Marketing',
+ provider: AIProviderName.OPENAI,
+ config: {},
+ enabledForChat: false,
+ modelScope: 'selected',
+ modelIds: ['gpt-main'],
+ projectScope: 'all',
+ projectIds: [],
+ status: 'active',
+ statusReason: null,
+ statusUpdated: null,
+};
+
+const MODELS: AIProviderModel[] = [
+ { id: 'gpt-main', name: 'GPT Main', type: AIProviderModelType.TEXT },
+ { id: 'gpt-other', name: 'GPT Other', type: AIProviderModelType.TEXT },
+];
+
+const renderList = (
+ props: Partial<React.ComponentProps<typeof KeyModelList>> = {},
+) => {
+ const onChange = vi.fn();
+ render(
+ <KeyModelList
+ config={CONFIG}
+ models={MODELS}
+ staleIds={[]}
+ tiersByModel={new Map([['gpt-main', ['Smart']]])}
+ allModels={false}
+ selectedIds={['gpt-main']}
+ isLoading={false}
+ onChange={onChange}
+ {...props}
+ />,
+ );
+ return { onChange };
+};
+
+describe('KeyModelList', () => {
+ it('locks a model a tier uses and says which tier', () => {
+ renderList();
+ const main = screen.getByRole('checkbox', { name: 'GPT Main' });
+ expect(main.hasAttribute('disabled')).toBe(true);
+ expect(main.getAttribute('data-state')).toBe('checked');
+ expect(screen.getByText('Used by Smart')).toBeTruthy();
+ });
+
+ it('toggles a free model on', () => {
+ const { onChange } = renderList();
+ fireEvent.click(screen.getByRole('checkbox', { name: 'GPT Other' }));
+ expect(onChange).toHaveBeenCalledWith(['gpt-main', 'gpt-other']);
+ });
+
+ it('shows every model on and locked under All models', () => {
+ renderList({ allModels: true, selectedIds: [] });
+ const other = screen.getByRole('checkbox', { name: 'GPT Other' });
+ expect(other.hasAttribute('disabled')).toBe(true);
+ expect(other.getAttribute('data-state')).toBe('checked');
+ expect(
+ screen.getByText('New models from OpenAI are added automatically.'),
+ ).toBeTruthy();
+ });
+});
diff --git a/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx b/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx
index 1e856931aa9..a91b3e0e3fe 100644
--- a/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx
+++ b/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx
@@ -26,8 +26,13 @@ const selectMock = vi.hoisted(() => ({
vi.mock('i18next', () => ({ t: (key: string) => key }));
vi.mock('@/components/ui/button', () => ({
- Button: ({ children, onClick, title }: any) => (
- <button onClick={onClick} title={title}>
+ Button: ({ children, onClick, title, disabled, ...rest }: any) => (
+ <button
+ onClick={onClick}
+ title={title}
+ disabled={disabled}
+ aria-label={rest['aria-label']}
+ >
{children}
</button>
),
@@ -75,6 +80,7 @@ describe('ManualModelList', () => {
const render = (
models: ProviderModelConfig[],
suggestedModelIds?: string[],
+ tiersByModel?: Map<string, string[]>,
) => {
onChange = vi.fn();
act(() => {
@@ -82,6 +88,7 @@ describe('ManualModelList', () => {
<ManualModelList
models={models}
suggestedModelIds={suggestedModelIds}
+ tiersByModel={tiersByModel}
onChange={onChange}
/>,
);
@@ -188,4 +195,24 @@ describe('ManualModelList', () => {
},
]);
});
+
+ it('keeps a model a tier uses: labelled, and its remove button disabled', () => {
+ render(
+ [
+ {
+ modelId: 'gemini-pro',
+ modelName: 'gemini-pro',
+ modelType: AIProviderModelType.TEXT,
+ },
+ ],
+ undefined,
+ new Map([['gemini-pro', ['Smart']]]),
+ );
+
+ expect(container.textContent).toContain('Used by {tiers}');
+ const remove = container.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Remove"]',
+ );
+ expect(remove?.disabled).toBe(true);
+ });
});
diff --git a/packages/web/test/app/routes/platform/setup/ai/providers-tab-locked.test.tsx b/packages/web/test/app/routes/platform/setup/ai/providers-tab-locked.test.tsx
index 17df16822cc..1e12dba817a 100644
--- a/packages/web/test/app/routes/platform/setup/ai/providers-tab-locked.test.tsx
+++ b/packages/web/test/app/routes/platform/setup/ai/providers-tab-locked.test.tsx
@@ -19,6 +19,10 @@ vi.mock('@tanstack/react-query', () => ({
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
+vi.mock('@/features/platform-admin/hooks/platform-model-tier-hooks', () => ({
+ platformModelTierQueries: { useAdminList: () => ({ data: [] }) },
+}));
+
vi.mock('@/hooks/platform-hooks', () => ({
platformHooks: {
useCurrentPlatform: () => ({
@@ -140,9 +144,9 @@ describe('providers tab on a plan without aiProvidersEnabled', () => {
expect(screen.queryAllByRole('combobox')).toEqual([]);
expect(screen.getByRole('button', { name: 'Delete' })).toBeDefined();
expect(screen.queryAllByRole('button', { name: /Add key/ })).toEqual([]);
- expect(screen.queryAllByRole('button', { name: /Trial Anthropic/ })).toEqual(
- [],
- );
+ expect(
+ screen.queryAllByRole('button', { name: /Trial Anthropic/ }),
+ ).toEqual([]);
expect(screen.queryAllByText('Also available')).toEqual([]);
});
@@ -163,7 +167,9 @@ describe('providers tab on a plan without aiProvidersEnabled', () => {
screen.getByRole('heading', { name: 'Unlock AI Center' }),
).toBeDefined();
expect(
- screen.queryAllByText('Your plan does not include Bring your own AI keys'),
+ screen.queryAllByText(
+ 'Your plan does not include Bring your own AI keys',
+ ),
).toEqual([]);
});
});
@@ -179,7 +185,9 @@ describe('providers tab on a plan with aiProvidersEnabled', () => {
screen.getAllByRole('button', { name: /Add key/ }).length,
).toBeGreaterThan(0);
expect(
- screen.queryAllByText('Your plan does not include Bring your own AI keys'),
+ screen.queryAllByText(
+ 'Your plan does not include Bring your own AI keys',
+ ),
).toEqual([]);
expect(
screen.queryAllByRole('heading', { name: 'Unlock AI Center' }),