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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(chat): chat picks from the shared model picker, plus Default AI key and Embeddings key + model (#16533)
Louai Boumediene990780d9cb3b
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.mdindex 7c11cce84c1..2932e5caea9 100644--- a/brain/knowledge/ai-intelligence/ai-providers.md+++ b/brain/knowledge/ai-intelligence/ai-providers.md@@ -75,7 +75,8 @@ after a file without chat keys it seeds the chat list from the live flow list.**Specific model** — a model a builder picks directly from one key (`{provider, configId, model}`), as opposed to a tier. The admin switch `platform_configuration.aiSpecificModelsVisible` (Tiers tab, "Visible to builders") hides them from builders. _Avoid_: "Advanced" (an early mockup word for the same section)### Gotchas-- **`enabledForChat` now means "the Default AI key", not "the key every chat runs on".** Chats pin their own key (see `ai-agents.md`); the flag only seeds the legacy and default paths, knowledge-base embeddings (when no Embeddings capability is set), and platform-wide work. Memory and personalization run on it, else on the Default tier's main model when that key serves every project, else on Credits (`agentHelpers.resolvePlatformWorkModel`). `listForProject` still reports the flag because the pre-7b chat page gates on it.+- **`enabledForChat` now means "the Default AI key", not "the key every chat runs on".** Chats pin their own key (see `ai-agents.md`); the flag only seeds the legacy and default paths, knowledge-base embeddings (when no Embeddings capability is set), and platform-wide work. Memory and personalization run on it, else on the Default tier's main model when that key serves every project, else on Credits (`agentHelpers.resolvePlatformWorkModel`). `listForProject` still reports the flag so a web client from before the 7b deploy keeps working; no current web code reads it.+- **Embedding models are a short curated list per provider (`EMBEDDING_MODELS` in core-piece-types), first entry = default.** The KB column is `vector(768)`, and embeddings are truncated to 768 dims, which is only safe for Matryoshka-trained models, so a live provider listing is not used. Embedding ids are never in a key's chat model scope, so the Embeddings capability skips `keyOffersModel` / `losesModel`. **Changing the Embeddings key or model leaves old files on their old vectors:** search mixes two embedding spaces until those files are re-uploaded. There is no per-file pin and no re-embed.- **The replay eval can't judge a model swap where the new model takes a different tool path.** Two separate things cause it:- **Replay divergence.** Every fixture gets the same tool set from `buildEvalToolSet` (local, display, cross-project and thinking tools). The recording only fixes which results come back and in what order. Calling a registered tool out of the recorded order returns `__evalDivergence`.- **Tools the eval doesn't have.** The flow and table tools (`ap_duplicate_flow`, `ap_build_flow`, `ap_find_records`) aren't in that set at all, so `ap_get_tool_schema` answers "There is no tool named". The tool does exist in production.@@ -113,7 +114,8 @@ after a file without chat keys it seeds the chat list from the live flow list.- **Since the AI steps moved to the worker, the server sees every step's model id, and `ai-execute-controller` is the one place to act on it.** The piece POSTs `/v1/ai/execute` with `provider` and `modelId`, the controller builds the `EXECUTE_AI` job from that body, and the worker runs whatever model id the job carries. So anything that needs to rewrite or validate the model a flow step is about to use belongs there, not in the piece — one server-side edit covers all five AI steps, and an old pinned piece bundle keeps working because it only forwards the string it stored. This is what makes storing a tier id in a step cheap: the bundle never has to understand it. Note the agent step does **not** come through here — it resolves separately over `getAgentConfig`, in `agent-config-rpc`. Two conditions sit under that. **An old bundle only forwards the string from `0.11.0` up** — `AI_PIECE_COST_BILLING_VERSION`, the first version whose `ai-step.ts` POSTs `v1/ai/execute`. A step pinned below it runs the pre-worker code that calls the provider from the sandbox, so a tier id there would reach OpenRouter as the literal string. That case is already closed: `migrate-v26-ai-piece-cost-billing` bumps every saved `piece-ai` step below `0.11.0` up to it, which is why a later migration can rewrite what a step stores without touching `pieceVersion` for the runtime. **And resolve on the API, never in the worker**: `ExecuteAiRequest.modelId` is a bare `z.string()` so a tier id passes validation, `getEffectiveProviderAndModel` and `aiUtils.buildWebSearchToolsOrThrow` both read `data.modelId` as a real model, and the `resolveAiProvider` RPC does not carry the model at all, so using it as the seam would mean widening the worker contract.- **Managed billing can only price an OpenRouter call, and a call it cannot price is simply not billed.** `openRouterCostOf` (`server/utils/activepieces-ai-cost.ts`) reads `providerMetadata['openrouter'].usage.cost`, with one fallback that GETs `openrouter.ai/api/v1/generation?id=` and takes `total_cost`. If neither answers, `createBillingInfo` returns `undefined` and the turn is never reported — it runs, the customer keeps the output, and nothing is charged. Nothing logs "unbilled". This is what actually welds the managed provider to OpenRouter, more than the client does: `create-language-model.ts` shares one branch for `OPENROUTER` and `ACTIVEPIECES`, every tier `modelId` is an OpenRouter id, and `openrouter-api.ts` mints the per-platform key from `OPENROUTER_PROVISION_KEY`. So putting managed credits on any other gateway needs a second cost extractor and a second generation lookup **first**, or every call through it bills zero. For reference, no Vercel AI Gateway code exists here at all — the only gateway in the repo is Cloudflare's (`CLOUDFLARE_GATEWAY`, the `ai-gateway-provider` package), and `@ai-sdk/gateway` appears only as a transitive dep of `ai` that nothing imports. A BYOK user can already reach Vercel's gateway today through `AIProviderName.CUSTOM`, which takes a base URL plus hand-typed model ids.- **A tier id that no longer exists resolves to the default tier of its surface, on every door, with a warning.** `resolveNamedModelId` (the path FLOW_STEP and AGENT take) tells a tier id from a model id by the slash rule: a bare slug is a tier id and goes through `resolveTier`, which returns the surface default for an id the file no longer carries and logs `Tier is no longer published; running the surface default` with the tier id and surface; a slashed id is a managed model id and is still refused with `The model "X" is not available on Activepieces AI credits` unless the release ships it or a published tier on that surface carries it. Every other source goes through `resolveModelIdForProvider` → `resolveTier`, the same default. So removing a tier from the file never fails a flow or an agent; it moves them onto the default until they are re-picked. The console may keep saying that removing a tier is safe. Decided 2026-09-26 with PR 2 of the configurable tiers work.-- **The console's Publish writes the live key directly; there is no draft, no staging and no filter.** `ai-pricing-service.ts` in `ap-analytics` writes `LIVE_PRICING_KEY` on Publish, and its "add tier" row seeds `id: tier-N`, `label: New tier`, so a half-finished experiment is one click from every server's cached tier list, with only the CDN `max-age=300` plus the 15-minute in-process TTL in between. Test against a local file with `AP_MODEL_TIERS_URL` (serve it on `127.0.0.1` and add `127.0.0.1` to `AP_SSRF_ALLOW_LIST`, which takes IPs or CIDRs, not hostnames, so `localhost` is still refused), never by publishing.+- **The console's Publish writes the live key directly; there is no draft, no staging and no filter.** `ai-pricing-service.ts` in `ap-analytics` writes `LIVE_PRICING_KEY` on Publish, and its "add tier" row seeds `id: tier-N`, `label: New tier`, so a half-finished experiment is one click from every server's cached tier list, with only the CDN cache plus the 15-minute in-process TTL in between (see the next bullet: the CDN part can be days, not minutes). Test against a local file with `AP_MODEL_TIERS_URL` (serve it on `127.0.0.1` and add `127.0.0.1` to `AP_SSRF_ALLOW_LIST`, which takes IPs or CIDRs, not hostnames, so `localhost` is still refused), never by publishing.+- **A console Publish can take days to reach servers: the plain `ai/pricing.json` URL is cached far longer than the `max-age=300` the console sets.** On 2026-10-15 origin had v7 (published 10:00 UTC) while `https://cdn.activepieces.com/ai/pricing.json` still served v6 with `cache-control: max-age=604800` and `age` ≈ 28h. The cache is the **DigitalOcean Spaces CDN** (`x-do-cdn-uuid` header), not Cloudflare (`cf-cache-status: DYNAMIC`): its edge cache TTL is 7 days and it overrides the object's own `Cache-Control`. `fetchTiers` fetches the plain URL, so every server keeps refreshing the stale copy. To verify a publish, compare `curl -s https://cdn.activepieces.com/ai/pricing.json | jq .version` with the same URL plus `?cb=$(date +%s)`. To see what a cloud server actually serves, look at `GET /api/v1/ai-providers/tiers` in the browser Network tab. If the versions differ, purge that key (`doctl compute cdn flush 046c3101-e4a3-49bd-a6f7-3dcd29a2a3d5 --files ai/pricing.json`, or Spaces → `activepieces-cdn` → Settings → CDN → Purge cache); re-publishing does not help.- **A console older than the two-list change, or a rollback to one, strips the chat keys on read, and its next Publish drops them with no diff line.** The console parses the live file with a zod object, and zod strips keys it does not declare, so `chatTiers`, `chatDefaultTierId` and `chatFastTierId` vanish from the draft the moment an old console reads it. Publish writes the draft back, and the history diff shows nothing because that console never knew the keys. Activepieces then serves chat from the flow list again, silently, since the chat keys are optional. After any console rollback, republish from a current build and check `curl -s https://cdn.activepieces.com/ai/pricing.json | jq keys` lists all nine keys.- **A managed text step stores a tier id from AI piece 0.12.0 on, and every managed model id stored before that came from a tier pick.** For the managed provider and a text step, `props.ts` (`packages/pieces/community/ai/src/lib/common/props.ts`) reads `GET /v1/ai-providers/tiers` with the engine token and offers the `flow` list as `{ label, value: tier.id }`. On any failure (a server without the route, a network error, an empty list) it offers the release's `ACTIVEPIECES_CHAT_TIERS`, still as tier ids, so a step saved on 0.12.0 always holds a tier id. `/models` is still called for managed image steps (`managedImageModelLabel` filters to `ACTIVEPIECES_IMAGE_TIERS`) and for own-key providers. Up to 0.11.0 the dropdown filtered `/models` to the bundled tier models and stored the concrete id, with no way to pin a model deliberately. So the migration from stored model ids to tier ids (ENG-753) has a trivially complete mapping: each stored id is one of the three bundled tier model ids of the release it was saved on. Until it runs, those steps follow the release, not the file.- **A managed text step on 0.12.0 that still holds a concrete model id shows 'Select AI Model' and keeps running that model.** The options are tier ids now. `searchable-select.tsx` renders the placeholder when the value matches no option and keeps the value, and `dynamic-dropdown-piece-property.tsx` only clears it when a refresher (here `provider`) changes. The run is unaffected, because the slash rule passes a concrete id through. It only happens when something bumps `pieceVersion` in place, as a flow migration does. Options are fetched against the step's saved exact version, so a step left on 0.11.0 keeps its old options, and the update dialog's minor bump resets every input (`getInputAfterVersionChange`, `MINOR_OR_MAJOR`), so the user re-picks the model with everything else.@@ -150,11 +152,11 @@ after a file without chat keys it seeds the chat list from the live flow list.- **Adding a provider compiles fine and still breaks flows, because the two model factories fail differently.** `createLanguageModel` in `@activepieces/ai-providers` ends its switch with `const exhaustiveCheck: never = provider`, so a missing provider is a *compile* error. The deliberately duplicated `buildLanguageModel` inside the AI piece (`pieces/community/ai/.../common/ai-sdk.ts`, kept on ai@6 because a v4 model cannot cross into the engine) ends with `default: throw new Error(...)` — so a provider wired only into the first one type-checks, ships, connects happily in the admin UI, and then throws `Provider <name> is not supported` the moment someone uses it in a flow step. That is the `.claude/rules/self-hosting.md` antipattern exactly. Wire **both** factories, and note `buildNativeImageModel` in that same file is a third switch, and its miss is worse than a throw: `createAIModel` does `if (imageModel) return imageModel` and otherwise **falls through to `buildLanguageModel`**, so a provider absent from that switch answers an image request with a *language* model rather than erroring. `NO_IMAGE_GENERATION_PROVIDERS` is what turns that into the clear `does not support image models` message, so a provider belongs there until images are actually wired — the entry is load bearing, not cosmetic.- **Overriding `fetch` on a provider silently switches off key-health reporting.** `...observed` *is* a `fetch` (`observedProviderFetch`), so any later `fetch` in the same options object replaces it rather than adding to it — spread order decides, and nothing errors or logs. A path that needs its own `fetch` (the Responses header-stripping one, the Cloudflare gateway's `Authorization`-deleting one) must take `observedProviderFetch(options.onOutcome)` as a delegate and call it, not call `globalThis.fetch`. Resolve the delegate at call time rather than capturing it at model-construction time; late binding is both more correct and the only way a test can stub the global. This is the same family as the merge hazard above — the failure is always one provider, or one path within a provider, quietly not reporting.- **A provider branch merges cleanly and still opts out of whatever the switch gained meanwhile.** `createLanguageModel` applies cross-cutting behaviour by spreading it into *every* case — `...observed` (`observedProviderFetch`, added by the key-health work) is the current one. Git treats a long-lived branch's new `case` as an added block, so it lands with none of the spreads its siblings picked up, and the merge reports no conflict: the new provider is simply the one that never reports health. Nothing fails, nothing logs. After merging main into any provider branch, diff your `case` against a neighbouring one and check the spreads match, rather than trusting a clean merge.-- **Only two `Record<AIProviderName, …>` maps are exhaustive, so the enum addition barely fights back.** `AI_PROVIDER_CAPABILITIES` (piece-types) and `aiProviders` (`ai/providers/index.ts`) must gain an entry; `PROVIDER_CREDENTIAL_FIELDS`, `PROVIDER_EMBEDDING_MODELS`, `ALLOWED_CHAT_MODELS_BY_PROVIDER`, `PROVIDER_MAX_CONTEXT_TOKENS`, `DEFAULT_EMBEDDING_MODELS` and `WEB_SEARCH_MODE_BY_PROVIDER` are all `Partial<Record<…>>` and degrade silently to defaults. `grep -rn 'Record<AIProviderName' | grep -v 'Partial<'` is the whole compile-time safety net — every other consequence of a new provider is a runtime question you have to reason about yourself.+- **Only two `Record<AIProviderName, …>` maps are exhaustive, so the enum addition barely fights back.** `AI_PROVIDER_CAPABILITIES` (piece-types) and `aiProviders` (`ai/providers/index.ts`) must gain an entry; `PROVIDER_CREDENTIAL_FIELDS`, `ALLOWED_CHAT_MODELS_BY_PROVIDER`, `PROVIDER_MAX_CONTEXT_TOKENS`, `EMBEDDING_MODELS` and `WEB_SEARCH_MODE_BY_PROVIDER` are all `Partial<Record<…>>` and degrade silently to defaults. `grep -rn 'Record<AIProviderName' | grep -v 'Partial<'` is the whole compile-time safety net — every other consequence of a new provider is a runtime question you have to reason about yourself.- **The repo runs three `@ai-sdk` generations at once, and the vendor package version is what pins you to one.** `@activepieces/ai-providers` is on ai@7 (`@ai-sdk/google` 4.0.29, `openai-compatible` 3.0.18, provider-utils 5.0.16); the AI piece is on ai@6 (google 3.0.65, openai-compatible 2.0.42, provider-utils 4.0.24); older code sits on the ai@5 line (google 2.0.71, provider-utils 3.0.24). A vendor SDK therefore needs a *different release per factory* — `@ai-sdk/google-vertex` is 5.0.36 for ai@7 and 4.0.113 for ai@6 — and taking the newest for both silently mixes `LanguageModelV3`/`V4` and fails at the engine boundary. Match transitive deps rather than guessing: `curl -s https://registry.npmjs.org/@ai-sdk/<pkg>` and pick the version whose `dependencies` equal the target package's own pins. Faster still, `ls node_modules/.bun/ | grep '<pkg>@'` usually already lists every generation bun has resolved.- **The OpenAI-compatible provider can speak the Responses API, and `@ai-sdk/openai-compatible` is not how you get there.** That SDK exposes only `chatModel` (`/chat/completions`) and `completionModel` — no responses model in any version. The route is `@ai-sdk/openai`, which accepts a custom `baseURL` + `headers` and exposes `.responses()`; the Cloudflare gateway's openai branch already did this before the `apiStyle: 'chat' | 'responses'` config field existed. Header precedence is the subtlety: the SDK builds `{ Authorization: Bearer <apiKey>, ...options.headers }`, so a caller header wins on `Authorization` (the Bedrock case, where the key *is* the bearer token) but a custom `apiKeyHeader` such as `x-api-key` leaves the SDK's default `Authorization` riding along. `withUserAgentSuffix` drops `undefined` values, but `OpenAIProviderSettings.headers` is typed `Record<string, string>`, so the way to strip it is the header-stripping `fetch` the Cloudflare branch uses — no cast needed, and worth reaching for straight away rather than writing the duplicate header up as an accepted limitation. Strip only when `apiKeyHeader` is not itself Authorization, compared **case-insensitively**: HTTP header names are, and an admin can type `authorization`. Confirmed shape, since it is easy to assert on the wrong key: the SDK lowercases everything, so a mis-set provider really does emit `{authorization: 'Bearer <key>', 'x-api-key': '<key>'}` — the credential twice.- **AWS's OpenAI-compatible surface is two endpoints, and "Bedrock Mantle" is a real AWS product name, not a customer's nickname.** `bedrock-runtime.{region}.amazonaws.com/openai/v1` (AWS-recommended) and `bedrock-mantle.{region}.api.aws/v1` both serve Chat Completions *and* Responses, both authenticate with a Bedrock API key as `Authorization: Bearer`, and both take an unmodified OpenAI SDK. Mantle alone adds server-side tools and web search, `background=true` async inference, and Projects/Workspaces; bedrock-runtime alone has Guardrails, cross-Region inference and intelligent prompt routing. So a ticket claiming "Mantle only supports responses" is half right — it serves chat/completions too, and the real loss is the Responses-only capabilities.-- **Vertex is a different door onto the same models, not a different vendor.** The `GOOGLE` provider is the Gemini Developer API (`generativelanguage.googleapis.com`, static API key); `VERTEX` is Vertex AI (`{region}-aiplatform.googleapis.com/v1beta1/projects/{project}/locations/{region}/publishers/google`, service-account OAuth2 with ~1h tokens) — the same Gemini models, but billed to the customer's GCP account and inheriting IAM, VPC-SC, CMEK, data residency and audit logs, plus Model Garden's Claude/Llama/Mistral. That rotating token is why the CUSTOM provider can never reach Vertex: `buildOpenAICompatibleHeaders` injects one static header, which is why the workaround used to be a LiteLLM proxy. `@ai-sdk/google-vertex` does the JWT-to-token exchange itself, so the native provider needs no proxy. Vertex models are entered by hand (`MANUAL_MODEL_PROVIDERS`) on purpose: availability is project-, region- and Model-Garden-specific, and a `publishers/google` listing would miss exactly the third-party models that motivate choosing Vertex. **But "same models" only holds for Gemini.** Model Garden also serves Anthropic, Meta, Mistral and xAI, and those do not share Gemini's API surface — `@ai-sdk/google-vertex` ships separate `/anthropic`, `/maas` and `/xai` entry points for exactly that reason, so one `createVertex(...)` call does not cover Vertex. Because models are typed in by hand, a Claude id reaches the factory as an ordinary string and, unrouted, gets built with the Gemini client and fails at the endpoint. `create-language-model.ts` routes ids containing `claude` to `createVertexAnthropic`; `vertexClientFor` picks the client from the id shape, so all three are routed. Because the shapes are unambiguous the check is a lookup, not a tuned heuristic — and note the publisher prefix has to be tested *before* the `claude` one, or a MaaS path containing "claude" routes to the Anthropic client. Routing is cheap because the id shapes are distinct, not because a heuristic was tuned: `gemini-2.5-pro` is bare, Anthropic carries an `@date` (`claude-3-5-sonnet@20241022`), and MaaS is publisher-prefixed and suffixed (`meta/llama-4-scout-17b-16e-instruct-maas`). The publisher prefix is a stronger discriminator than the `includes('claude')` match currently shipped, and it looks like an argument for listing models rather than taking them by hand — but it is not, see below: the listing is scoped to a single publisher, so Model Garden ids stay hand-typed and the string matching stays with them. **Listing was considered and rejected**, and the reason is worth keeping so it does not get reopened, and **the response shape does not need a GCP account to learn** — every Google API publishes an unauthenticated discovery document: `curl -s 'https://aiplatform.googleapis.com/$discovery/rest?version=v1beta1'` returns ~5MB of JSON whose `schemas` are the authoritative request/response types. `publishers.models.list` returns `{ publisherModels: PublisherModel[], nextPageToken }`, and `PublisherModel` is `{ name: 'publishers/google/models/<id>', versionId, versionState (STABLE|UNSTABLE), launchStage (GA|PUBLIC_PREVIEW|PRIVATE_PREVIEW|EXPERIMENTAL), openSourceCategory, supportedActions, predictSchemata, frameworks, parent }`. **There is no `displayName` on it** — the one in `google-vertexai`'s piece comes from `@google/genai`'s `Model` type, which is a different shape, so copying that code gives every row a blank label with nothing failing. `displayName` exists only on the nested `parent`, which is the base model a tuned model derives from. The decisive fact is in that same doc: `publishers.models.list` takes `parent` matching `^publishers/[^/]+$` — **one publisher per call**. Listing everything therefore means hardcoding the set of publishers to enumerate, which is the same shape of hardcoding it was meant to remove, and Model Garden models would still need hand entry, leaving two mechanisms where there is now one. `VERTEX` stays in `MANUAL_MODEL_PROVIDERS` alongside `CUSTOM` and `CLOUDFLARE_GATEWAY`, which fits: Vertex model availability really is per-project. Reach for the discovery doc before a live probe on any `*.googleapis.com` integration; a curl against the real endpoint needs **billing attached to the project even for a read** (`403 BILLING_DISABLED`), so it is the slower path and it is not free to set up. The `x-goog-user-project` header is not optional when probing with a personal login: without it aiplatform answers `403 SERVICE_DISABLED` naming `consumer: projects/32555940559`, which is Google's shared gcloud CLI project rather than yours, and the message talks about quota projects rather than the missing header. This is a user-credential quirk only — a service account carries its own `project_id`, so the provider itself never hits it. **The multi-vendor story is text only.** Vertex's image models are Google's own Imagen (`imagen-3.0-*`, `imagen-4.0-*`), not Model Garden's third parties, and `createVertex(...)` also exposes `imageModel`, `video`, `speech`, `transcription` and `textEmbeddingModel` — none of which we wire today. Imagen is wired (`createVertex(...).imageModel()`, with a `VERTEX` case in the piece's image switch, so `VERTEX` is no longer in `NO_IMAGE_GENERATION_PROVIDERS`); video, speech, transcription and embeddings are not. Embeddings still have no `DEFAULT_EMBEDDING_MODELS` entry, so that path paths fail with an explanatory message instead of reaching a switch that has no case for it.+- **Vertex is a different door onto the same models, not a different vendor.** The `GOOGLE` provider is the Gemini Developer API (`generativelanguage.googleapis.com`, static API key); `VERTEX` is Vertex AI (`{region}-aiplatform.googleapis.com/v1beta1/projects/{project}/locations/{region}/publishers/google`, service-account OAuth2 with ~1h tokens) — the same Gemini models, but billed to the customer's GCP account and inheriting IAM, VPC-SC, CMEK, data residency and audit logs, plus Model Garden's Claude/Llama/Mistral. That rotating token is why the CUSTOM provider can never reach Vertex: `buildOpenAICompatibleHeaders` injects one static header, which is why the workaround used to be a LiteLLM proxy. `@ai-sdk/google-vertex` does the JWT-to-token exchange itself, so the native provider needs no proxy. Vertex models are entered by hand (`MANUAL_MODEL_PROVIDERS`) on purpose: availability is project-, region- and Model-Garden-specific, and a `publishers/google` listing would miss exactly the third-party models that motivate choosing Vertex. **But "same models" only holds for Gemini.** Model Garden also serves Anthropic, Meta, Mistral and xAI, and those do not share Gemini's API surface — `@ai-sdk/google-vertex` ships separate `/anthropic`, `/maas` and `/xai` entry points for exactly that reason, so one `createVertex(...)` call does not cover Vertex. Because models are typed in by hand, a Claude id reaches the factory as an ordinary string and, unrouted, gets built with the Gemini client and fails at the endpoint. `create-language-model.ts` routes ids containing `claude` to `createVertexAnthropic`; `vertexClientFor` picks the client from the id shape, so all three are routed. Because the shapes are unambiguous the check is a lookup, not a tuned heuristic — and note the publisher prefix has to be tested *before* the `claude` one, or a MaaS path containing "claude" routes to the Anthropic client. Routing is cheap because the id shapes are distinct, not because a heuristic was tuned: `gemini-2.5-pro` is bare, Anthropic carries an `@date` (`claude-3-5-sonnet@20241022`), and MaaS is publisher-prefixed and suffixed (`meta/llama-4-scout-17b-16e-instruct-maas`). The publisher prefix is a stronger discriminator than the `includes('claude')` match currently shipped, and it looks like an argument for listing models rather than taking them by hand — but it is not, see below: the listing is scoped to a single publisher, so Model Garden ids stay hand-typed and the string matching stays with them. **Listing was considered and rejected**, and the reason is worth keeping so it does not get reopened, and **the response shape does not need a GCP account to learn** — every Google API publishes an unauthenticated discovery document: `curl -s 'https://aiplatform.googleapis.com/$discovery/rest?version=v1beta1'` returns ~5MB of JSON whose `schemas` are the authoritative request/response types. `publishers.models.list` returns `{ publisherModels: PublisherModel[], nextPageToken }`, and `PublisherModel` is `{ name: 'publishers/google/models/<id>', versionId, versionState (STABLE|UNSTABLE), launchStage (GA|PUBLIC_PREVIEW|PRIVATE_PREVIEW|EXPERIMENTAL), openSourceCategory, supportedActions, predictSchemata, frameworks, parent }`. **There is no `displayName` on it** — the one in `google-vertexai`'s piece comes from `@google/genai`'s `Model` type, which is a different shape, so copying that code gives every row a blank label with nothing failing. `displayName` exists only on the nested `parent`, which is the base model a tuned model derives from. The decisive fact is in that same doc: `publishers.models.list` takes `parent` matching `^publishers/[^/]+$` — **one publisher per call**. Listing everything therefore means hardcoding the set of publishers to enumerate, which is the same shape of hardcoding it was meant to remove, and Model Garden models would still need hand entry, leaving two mechanisms where there is now one. `VERTEX` stays in `MANUAL_MODEL_PROVIDERS` alongside `CUSTOM` and `CLOUDFLARE_GATEWAY`, which fits: Vertex model availability really is per-project. Reach for the discovery doc before a live probe on any `*.googleapis.com` integration; a curl against the real endpoint needs **billing attached to the project even for a read** (`403 BILLING_DISABLED`), so it is the slower path and it is not free to set up. The `x-goog-user-project` header is not optional when probing with a personal login: without it aiplatform answers `403 SERVICE_DISABLED` naming `consumer: projects/32555940559`, which is Google's shared gcloud CLI project rather than yours, and the message talks about quota projects rather than the missing header. This is a user-credential quirk only — a service account carries its own `project_id`, so the provider itself never hits it. **The multi-vendor story is text only.** Vertex's image models are Google's own Imagen (`imagen-3.0-*`, `imagen-4.0-*`), not Model Garden's third parties, and `createVertex(...)` also exposes `imageModel`, `video`, `speech`, `transcription` and `textEmbeddingModel` — none of which we wire today. Imagen is wired (`createVertex(...).imageModel()`, with a `VERTEX` case in the piece's image switch, so `VERTEX` is no longer in `NO_IMAGE_GENERATION_PROVIDERS`); video, speech, transcription and embeddings are not. Embeddings still have no `EMBEDDING_MODELS` entry, so those paths fail with an explanatory message instead of reaching a switch that has no case for it.- **Chat-tier resolution answers "which model" from three places, and only one of them is the key.** `resolveModelIdForProvider` (`ee/agent/agent-model-resolution.ts`, spread into `agentHelpers`) now prefers the resolved key's own configured text models when its config carries a `models` array — that is the `MANUAL_MODEL_PROVIDERS` case (Vertex, Custom, Cloudflare Gateway), where the admin typed the exact ids the key exposes. **An empty catalog is not a missing one**, and collapsing the two is how the first cut of this went wrong: a helper returning `string[] | undefined` treated "lists zero text models" the same as "has no catalog", so a key configured with only image models fell through to the curated list and resolved to a Gemini id it never offered. An admin-listed catalog is the whole truth about a key, so an empty one now refuses the turn with a message rather than guessing. Otherwise it falls back to the static `ALLOWED_CHAT_MODELS_BY_PROVIDER`, and if the provider is missing from that too it returns the raw tier id with its vendor prefix stripped — which is how a Vertex key once resolved to `claude-sonnet-4-6` and handed it to the Gemini client. That map is `Partial<`, so omitting a chat-capable provider compiles cleanly and fails only at the endpoint. **The key's own `modelScope`/`modelIds` allow-list is applied last, to whichever candidate list was chosen**, and a resolution with nothing left refuses the turn rather than returning a model the key forbids. `GetProviderConfigResponse` carries both fields for that, populated at all three construction sites (`getChatProvider`, `getConfigOrThrow`, `enrichWithKeysIfNeeded`); adding fields there is backward compatible because the AI piece reads the response as a typed shape rather than parsing it. I first recorded this as too big for a provider PR — "a wire contract the engine and the AI piece both consume" — having never measured it. It was about thirty lines across four files. Measure before recording something as out of scope; the estimate outlives the guess. **The resolver is exported and has five call sites across four files, and only two of them are runs.** `agent-rpc-handlers` resolves the chat turn's model *and* its fast model, and `chat-personalization-service` resolves both for research — those four must be given the resolved row's `config`, `modelScope` and `modelIds`, or the key's constraints are bypassed on exactly the paths a user takes. `resolveTierModel` inside `agent-helpers` is the fifth. `agent-service` also calls it but holds only a provider name and sets a stored default on a draft, so it is correctly left thin (`agent-draft-ai` did too, until #15676 deleted it). Adding a parameter here means grepping `resolveModelIdForProvider|resolveFastModelId` across `packages/server`, not editing the call site in front of you — threading only `resolveTierModel` looks complete, passes every test, and still leaves the real chat path unconstrained. The `surface` argument was added as a required key on the whole family for exactly that reason: a missed call site is a compile error, except inside a `vi.mock` factory, which is not type-checked and has to be updated by hand. One trap when touching this function: a tier id (`fast`, `smart`) is **not** a model id, so the preferred pick must be the resolved native id unless the selection is itself among the candidates — passing `selectedModel` straight through makes `resolveFastModelId` return the first curated model instead of the fast tier's.- **A failed credential validation tells the admin nothing, for every provider except Cloudflare Gateway.** `aiProviderService.validateProviderCredentials` gates the upstream message behind `includeHttpErrorInMessage`, which is `provider === CLOUDFLARE_GATEWAY` and nothing else, so everyone else gets a bare `Failed to validate credentials for <name>`. The cause is not lost — it is logged one line earlier (`log.error({ error }, '[aiProviderService#validateProviderCredentials] ...')`) and passed as the `httpErrorResponse` error param — but **web never renders `httpErrorResponse`**, so the only way to diagnose a rejected key is the server log. Grep the log for `validateProviderCredentials` before assuming the provider integration is broken — that text is the whole diagnosis, and it is often not about credentials at all. Confirmed case: a brand-new xAI team with no credits purchased answers `GET /v1/models` with `403 permission-denied — Your newly created team doesn't have any credits or licenses yet`, naming the console page that fixes it, and we render that as "Failed to validate credentials for xAI" — sending the admin off to regenerate a key that was never wrong. Vendors also phrase real key failures inconsistently (xAI uses `400 Incorrect API key provided`, not a 401). The corollary: **a provider that saves without error is not a working provider.** A no-credits 403 and a bad key are indistinguishable in the UI, so only an actual generation proves a key end to end. This is an admin-only surface (`platformAdminOnly`), so there is little reason to keep hiding it.- **A provider's logo is an asset someone has to upload, not something the code ships.** `AiProviderInfo.logoUrl` in `packages/web/src/features/agents/ai-providers.ts` is a plain string rendered into an `<img src>`, and every provider points at `https://cdn.activepieces.com/pieces/<slug>.png` — nothing is bundled. Adding a provider therefore carries a cross-team dependency with no compile-time or test signal: a slug with no asset behind it renders a broken-image icon in the platform admin list, and only a live request tells you. Check the URL with `curl -o /dev/null -w '%{http_code}'` before assuming it works — a vendor that already ships as a *piece* usually has its logo there already (`deepseek.png`, `grok-xai.png` did), so start the upload request only for the genuinely missing ones. A Vite asset import also satisfies `logoUrl` (see `GoogleIcon` in `platform/security/sso/index.tsx`) and removes the runtime CDN dependency for air-gapped installs, but it diverges from every other provider — treat it as a fallback, not the default.@@ -211,8 +213,8 @@ after a file without chat keys it seeds the chat list from the live flow list.- **Chat model tiers are Activepieces-only.** `ACTIVEPIECES_CHAT_TIERS` (`fast`/`smart`/`premium`, shown as Fast/Expert/Heavy) hold OpenRouter-shaped Anthropic ids, so they only mean anything for the ACTIVEPIECES and OPENROUTER chat providers. Any provider that declares `ALLOWED_CHAT_MODELS_BY_PROVIDER` (openai, anthropic, google) picks a real model id from that list instead. Naively stripping the tier's vendor prefix for every provider is what once sent `claude-haiku-4-5` to OpenAI and broke every message.- **A short model list in the key's picker is the vendor's catalog, not a truncation.** `listModels` returns whatever the provider's own `/models` endpoint gives and filters nothing except the key's `modelScope` allow-list. Anthropic ships roughly a dozen models, OpenAI ~80 (mostly embeddings/tts/whisper), while OpenRouter is an aggregator and returns 400+ from every vendor it proxies — so the counts differ by an order of magnitude by design. Anthropic pages at 20 by default, which is why its request pins `?limit=1000`. If the list shows exactly three Claude models, that is the *chat* dropdown reading the curated `ANTHROPIC_CHAT_MODELS`, a different surface from the admin picker.- **Read the chat model list through `aiProviderUtils.getCuratedChatModels({ provider })`.** It is the one accessor the server resolver (`agentHelpers.resolveModelIdForProvider`) and the chat dropdown share, so the two cannot drift; it returns `{ id, label }` or `undefined` — never an empty list, so callers may treat a result as non-empty. Labels come from the hardcoded `CHAT_MODEL_LABELS` (falling back to the id) rather than `AIProviderModel.name`, because the live `listModels` response cannot supply one for every provider: anthropic returns `display_name` and google `displayName`, but OpenAI's `/v1/models` returns ids only.-- **`conversation.modelName` carries either a tier id or a real model id** — it is a free string with no discriminator. A legacy tier id resolves to the tier's equivalent model when the provider ships it, else the provider's first curated model, so old conversations keep working after a provider switch. Note `premium` maps to opus 4.8, which the native anthropic list does not carry, so a legacy `premium` on anthropic lands on Sonnet. A new web chat sends no model at all until the user picks one (`use-chat.ts` starts `modelName` at null): the server resolves the published chat default for that turn and the worker stamps the tier it ran onto the conversation, so the chat default lives in one place, the published file, and the picker shows it as selected by reading `chat.defaultTierId` from the tiers endpoint. Before that change the web sent `smart` explicitly on every new chat, which is why a published `defaultTierId` never reached web chats. **That holds only where the picker shows tiers.** An own-key provider with a curated model list shows concrete models, but a null model still resolves the published chat default tier and then that tier's `nativeModelId`, which is in the Anthropic curated list: a published default of `fast` ran Haiku on every Anthropic-key chat while the picker showed Sonnet, and the worker's tier stamp kept it there. So a new chat on a curated key sends the model the picker shows (`chatUtils.newChatModelName`); the tier picker sends null, and so does any chat whose picker is hidden (an agent or the agent builder: a saved agent's job carries the agent's own model anyway). The chat box does not mount until the chat provider has loaded, or a message sent in that window would go out with no model. Caught in review on #15838.-- Chat-provider resolution is **first `enabledForChat` row wins, else the visible managed ACTIVEPIECES row** — `pickChatRow`, shared by `findAvailableChatProviderRow` and both list endpoints. So a platform with `[openai, activepieces]` both chat-enabled still resolves to **openai** (an explicit pick beats the fallback), while a platform with nothing flagged resolves to the managed row instead of to nothing. The flag a list endpoint reports is therefore the *resolved* one, not the stored column — `ai_provider.enabledForChat` can say `false` on the row chat actually runs on, and `ensureManagedProviderRow` no longer writes it. The client mirror is `aiProviderQueries.useChatProvider()` (`providers.find((p) => p.enabledForChat)`) — always read the resolved chat provider through it rather than re-deriving the rule inline. A project entry is chat-enabled when it owns the picked row, whichever of its keys carries the flag: ranking (`selected` > `except` > `all`, newest first) and chat selection answer different questions, so reading `rows[0].enabledForChat` makes the client report "no provider configured" whenever the chat-enabled key is not the ranking winner. `findBy()` has no `ORDER BY`, so "first" is not guaranteed stable when several providers are chat-enabled.+- **`conversation.modelName` carries either a tier id or a real model id** — it is a free string with no discriminator. A legacy tier id resolves to the tier's equivalent model when the provider ships it, else the provider's first curated model, so old conversations keep working after a provider switch. Note `premium` maps to opus 4.8, which the native anthropic list does not carry, so a legacy `premium` on anthropic lands on Sonnet. A new web chat sends no model at all until the user picks one (`use-chat.ts` starts `modelName` at null): the server resolves the published chat default for that turn and the worker stamps the tier it ran onto the conversation, so the chat default lives in one place, the published file, and the picker shows it as selected by reading `chat.defaultTierId` from the tiers endpoint. Before that change the web sent `smart` explicitly on every new chat, which is why a published `defaultTierId` never reached web chats. **That holds only where the picker shows tiers.** An own-key provider with a curated model list shows concrete models, but a null model still resolves the published chat default tier and then that tier's `nativeModelId`, which is in the Anthropic curated list: a published default of `fast` ran Haiku on every Anthropic-key chat while the picker showed Sonnet, and the worker's tier stamp kept it there. Since 7b the chat uses the shared `ModelPicker` and a new chat sends the pick the pill shows (`model-options` `defaultChoice` when untouched); agent chats send none, since the agent's job carries its own model. A message sent before the options load goes out with no pick and the server's `defaultPick` resolves it. Caught in review on #15838.+- Chat-provider resolution is **first `enabledForChat` row wins, else the visible managed ACTIVEPIECES row** — `pickChatRow`, shared by `findAvailableChatProviderRow` and both list endpoints. So a platform with `[openai, activepieces]` both chat-enabled still resolves to **openai** (an explicit pick beats the fallback), while a platform with nothing flagged resolves to the managed row instead of to nothing. The flag a list endpoint reports is therefore the *resolved* one, not the stored column — `ai_provider.enabledForChat` can say `false` on the row chat actually runs on, and `ensureManagedProviderRow` no longer writes it. The web no longer reads it (7b removed `useChatProvider`). There is no Default AI key control any more: it is derived from the platform's **Default chat model** setting (the "Default chat model" card on Providers), so it always matches the model new chats start on. A chat with no pick and no usable tier stores the Default AI key's first curated model (the pill's default); if that key's models can't be listed it keeps the legacy path rather than failing. A project entry is chat-enabled when it owns the picked row, whichever of its keys carries the flag: ranking (`selected` > `except` > `all`, newest first) and chat selection answer different questions, so reading `rows[0].enabledForChat` makes the client report "no provider configured" whenever the chat-enabled key is not the ranking winner. `findBy()` has no `ORDER BY`, so "first" is not guaranteed stable when several providers are chat-enabled.- Listing providers is **not a pure read**: both `listConfigs` and `listForProject` go through `listVisibleRows`, which inserts the ACTIVEPIECES provider row when `aiCreditsEnabled && !activepiecesExists`. A `GET /v1/ai-providers` can therefore create a row. It also applies the hidden-provider filter (`plan.embeddingEnabled` hides the managed provider), which is why the client can trust its output without re-checking flags.- **A managed chat turn is charged in two events, not one.** The model cost arrives per model call fromthe billing wrapper, and the turn's own-key credit and tool calls are charged by `chatToolBilling.chargeForLatestTurn`@@ -228,7 +230,7 @@ after a file without chat keys it seeds the chat list from the live flow list.- **`/v1/ai-tools` is registered only in the CLOUD and ENTERPRISE branches of `app.ts`, but the AI Center page that reads it is not edition-gated** — so a Community admin opening the Capabilities tab fired `useAiToolConfigs`, got Fastify's `Route not found`, and the page showed the global "Failed to load data" dialog of the day. Shipped that way from #13911 until the tab was gated on `ApFlagId.EDITION` in the page. What made this class of bug hard to place is that the surface was then page-independent (raised from `QueryCache.onError` in `query-client.ts`) and React Query's 3 default retries meant it landed several seconds later on whatever page you navigated to next (the report was against `/platform/general`). The tab now renders `DataFetchErrorState` in place instead, so a repeat would at least accuse the right page. When a screenshot's edition is in doubt, read the sidebar: **Billing & subscription** and **Usage** carry a lock only when `edition === COMMUNITY`, every other lock there is plan-driven. Any new EE-only route needs its UI entry point gated the same way, `enabled:` on the query or hiding the surface.- **The AI Center providers page renders its whole state machine off one query, so every branch needs an `isLoading` gate above it.** `ProvidersTab` derives the empty state, the grouped list *and* the `?config=<id>` detail view from `useAiProviderConfigs()`. While that query is pending, `data` is `undefined` — `configs` is `[]`, so the empty "Connect your first provider" screen paints for a frame, and a hard refresh on a `?config=` URL finds no matching row and falls through to the list before flipping to the detail page. The parent `SuspenseWrapper` does not cover it: the route chunk and the suspense-backed projects collection resolve first, then the component mounts with no providers yet. Any new branch added to this page belongs below the `if (isLoading) return <ProvidersSkeleton />` gate, not beside it.- **A save bar in the AI Center needs a full-height column, not `fixed` and not bare `sticky`.** The page sits inside *two* nested scrollers — `PlatformLayout`'s `flex flex-col flex-1 overflow-auto` and the AI Center's own `flex-1 overflow-auto` column — so `fixed inset-x-0` centres the bar on the viewport, roughly a sidebar-width left of the content column it belongs to. Swapping it to `sticky bottom-4` fixes the centring for free but pins nothing when the content is shorter than the viewport: the bar just lands wherever the content ends, mid-page. The working shape is `min-h-full` + `flex flex-col` on the tab-content wrapper, `flex-1` on the `TabsContent`, `grow` on the panel root, then `sticky bottom-4 mt-auto` on the bar — `mt-auto` handles the short page, `sticky` handles the long one. `min-h-full` resolves only because every ancestor up to `SidebarInset h-full` has a definite height; that chain is what makes the whole thing work, so check it before reusing this elsewhere.-- **A chat *tier* is our own idea, so it has no meaning on a provider we ship no curated model list for — resolve it by asking the key what it offers.** `ACTIVEPIECES_CHAT_TIERS` (fast/smart/premium) only maps to a real id through `ALLOWED_CHAT_MODELS_BY_PROVIDER`, which covers Anthropic, OpenAI, Google, Vertex and Activepieces. Everything else — Bedrock, Azure, Mistral, xAI, DeepSeek and the other OpenAI-compatible vendors — has an empty candidate list. The resolver used to invent an id from the tier (strip the vendor prefix, dots to dashes: `anthropic/claude-haiku-4.5` -> `claude-haiku-4-5`), which Bedrock rejected as "The provided model identifier is invalid" (GIT-1840, Pylon 5836). #15355 removed the invention and left a throw in its place, which was worse: every agent turn on those providers died with `ENTITY_NOT_FOUND: this AI provider key allows no text model a chat turn can run on` before the configured model handled anything (Pylon 6069). **The missing ingredient was never a smarter guess, it was the key's own model list.** `agentHelpers.resolveModelId` is now the single resolver for every surface: it tries our catalogue first and, only when that has nothing to say, reads `aiProviderService.listModels` (process-cached, cleared nightly by cron, already filtered by the key's `modelScope`), preferring a model whose id *contains* the tier's `nativeModelId` — Bedrock spells them `eu.anthropic.claude-sonnet-4-6-...`, so a tier still selects the model it names wherever the vendor hosts it, and otherwise degrades to the first text model the way `pickAllowedModel` already does for an admin-listed catalogue. Picking from a list the provider returned is the opposite of the fabrication #15355 removed. **Two traps, both learned the hard way.** First, an agent surface and generic chat are not symmetric: an agent *carries* a real model id (its picker lists `listModels` output unfiltered, precisely because these providers have no `ALLOWED_CHAT_MODELS_BY_PROVIDER` entry) while chat carries only a tier name, because `ChatModelSelector` falls back to tier options when `getCuratedChatModels` returns `undefined`. Second, **being listed proves the key can see a model, not that the account can invoke it** — so where a model is already settled the fast round reuses it rather than choosing again (`getAgentConfig` passes the model the turn resolved; the tool RPC gets the run's own model from the worker, `modelId` on `executePieceTool`). One more trap, found in review on 2026-09-27: a stored name is not the model the run ran on. The worker stamps the resolved *tier id* on an agentless inline run's conversation, so reading it back as a model hands a bare `smart` to a catalogue-less own-key provider, and no rule on the string can save it, because a deployment may be named `smart` too. So nothing is read off the conversation or the agent for the fast round any more: the worker says which model the turn resolved, `modelId` on `ExecutePieceToolRequest` (core-execution), and the API borrows exactly that. The field is required, not optional, because the dispatch gate keeps worker and app on one release, so an older worker never reaches a newer API. Resolving the fast tier independently once picked a Haiku the account could not invoke and failed a turn whose configured Sonnet worked fine. A borrowed model still has to pass the key's current `modelScope`, or resolution falls through to the list, which applies it. Nothing crosses the worker, so a rolling deploy has no version-skew window.+- **A chat *tier* is our own idea, so it has no meaning on a provider we ship no curated model list for — resolve it by asking the key what it offers.** `ACTIVEPIECES_CHAT_TIERS` (fast/smart/premium) only maps to a real id through `ALLOWED_CHAT_MODELS_BY_PROVIDER`, which covers Anthropic, OpenAI, Google, Vertex and Activepieces. Everything else — Bedrock, Azure, Mistral, xAI, DeepSeek and the other OpenAI-compatible vendors — has an empty candidate list. The resolver used to invent an id from the tier (strip the vendor prefix, dots to dashes: `anthropic/claude-haiku-4.5` -> `claude-haiku-4-5`), which Bedrock rejected as "The provided model identifier is invalid" (GIT-1840, Pylon 5836). #15355 removed the invention and left a throw in its place, which was worse: every agent turn on those providers died with `ENTITY_NOT_FOUND: this AI provider key allows no text model a chat turn can run on` before the configured model handled anything (Pylon 6069). **The missing ingredient was never a smarter guess, it was the key's own model list.** `agentHelpers.resolveModelId` is now the single resolver for every surface: it tries our catalogue first and, only when that has nothing to say, reads `aiProviderService.listModels` (process-cached, cleared nightly by cron, already filtered by the key's `modelScope`), preferring a model whose id *contains* the tier's `nativeModelId` — Bedrock spells them `eu.anthropic.claude-sonnet-4-6-...`, so a tier still selects the model it names wherever the vendor hosts it, and otherwise degrades to the first text model the way `pickAllowedModel` already does for an admin-listed catalogue. Picking from a list the provider returned is the opposite of the fabrication #15355 removed. **Two traps, both learned the hard way.** First, an agent surface and generic chat are not symmetric: an agent *carries* a real model id (its picker lists `listModels` output unfiltered, precisely because these providers have no `ALLOWED_CHAT_MODELS_BY_PROVIDER` entry) while chat carries only a tier name, because the pre-7b chat selector fell back to tier options when `getCuratedChatModels` returned `undefined`. Second, **being listed proves the key can see a model, not that the account can invoke it** — so where a model is already settled the fast round reuses it rather than choosing again (`getAgentConfig` passes the model the turn resolved; the tool RPC gets the run's own model from the worker, `modelId` on `executePieceTool`). One more trap, found in review on 2026-09-27: a stored name is not the model the run ran on. The worker stamps the resolved *tier id* on an agentless inline run's conversation, so reading it back as a model hands a bare `smart` to a catalogue-less own-key provider, and no rule on the string can save it, because a deployment may be named `smart` too. So nothing is read off the conversation or the agent for the fast round any more: the worker says which model the turn resolved, `modelId` on `ExecutePieceToolRequest` (core-execution), and the API borrows exactly that. The field is required, not optional, because the dispatch gate keeps worker and app on one release, so an older worker never reaches a newer API. Resolving the fast tier independently once picked a Haiku the account could not invoke and failed a turn whose configured Sonnet worked fine. A borrowed model still has to pass the key's current `modelScope`, or resolution falls through to the list, which applies it. Nothing crosses the worker, so a rolling deploy has no version-skew window.- **Non-chat models are filtered out centrally in `fetchModels`, not per provider strategy.** OpenAI's `/v1/models` returns `whisper-1`, `tts-1`, `gpt-4o-transcribe`, `text-embedding-3-*`, `omni-moderation-latest` and `sora-*`, and every strategy that cannot tell them apart typed them `TEXT` — so they were offered in Ask AI / Summarize / Classify / Extract and died at run time on chat completion (#14496). One `aiProviderUtils.isChatModelId` denylist now runs inside `fetchModels`, which is the single choke point behind both the project route and the admin `configs/:id/models` route, so a new provider is covered without opting in. Three things about it are load-bearing: it tests **only `TEXT`-typed rows**, so image models are untouched; it **never judges a name the customer chose** — admin-typed configs (`'models' in config` — VERTEX, CUSTOM, CLOUDFLARE_GATEWAY) skip it because an admin who typed an id meant it, Azure skips it (`modelIdsAreCustomerNamed` on the strategy) because it lists deployment names like `support-voice-agent` and filters on `deployment.model` itself, and a fine-tune is judged by its base model only (`ft:<base>:<org>:<label>:…`, Azure `<base>.ft-…`) so an org called `voiceflow` or a `content-moderation` label does not hide a working chat model; and `validateConnection` **bypasses `fetchModels` entirely**, so a key that lists nothing but whisper still validates as a working key. The rule is a denylist on purpose — an unknown id is treated as chat, so a self-hoster's own model on a custom endpoint never disappears, at the cost of a new modality leaking until a pattern is added. Because pieces may not import `@activepieces/core-*` (eslint `no-restricted-imports`), the openai piece's `isLLM` reaches the same ruleset through a `packages/pieces/framework/src/index.ts` re-export. Still leaking, knowingly: vendor-branded generative models on the five compat vendors that publish no modality data (`cogview-*`, `wan*`, `music-*`, `video-01`), whose real ids nobody could verify without five paid keys — xAI is handled structurally, see the next bullet.- **xAI is the one compat vendor asked what its models output, because it is the one that answers.** `listVendorModels` hits `/v1/language-models` for XAI first and keeps a model only when `output_modalities` includes `text`; the OpenAI-shaped `/v1/models` that the other five vendors use carries no modality field at all, which is why `grok-2-image-1212` and the Grok Imagine image/video models were offered as chat. A model that declares no modalities falls back to the id denylist. Every failure mode degrades to the old path rather than emptying the picker: a 404, a changed shape, or an empty `models` array all fall through to `/v1/models`, and because that fallback is what authenticates, a bad key still fails validation with the vendor-prefixed error. The endpoint pair (`/language-models`, `/image-generation-models`) was already known in-repo — `packages/pieces/community/grok-xai` calls both. Adding a vendor to `VENDORS_DECLARING_MODALITIES` is the whole opt-in; do it only with a real `/models` response in hand, not from recollection of a catalogue.- **Google is filtered on `supportedGenerationMethods`, and that is what keeps Imagen out of the image picker.** A model survives only if the field is absent or includes `generateContent`, which is the only way to exclude `aqa` (`generateAnswer`) and `gemini-embedding-001` (`embedContent`) — no name pattern catches them. The side effect is deliberate: `imagen-*` was classified `IMAGE` (because `'imagen'.includes('image')`) and offered in Generate Image, but the AI piece reaches Google image generation through `generateText`/`:generateContent` (there is no `google` case in `buildNativeImageModel`), and Imagen only answers `:predict` — so those options always failed at run time. Gemini image models do expose `generateContent` and are unaffected; Vertex is where Imagen actually works, and it is admin-typed so the filter never sees it.diff --git a/brain/knowledge/ai-intelligence/model-picker.md b/brain/knowledge/ai-intelligence/model-picker.mdindex 604ae697bab..ba2c08290b6 100644--- a/brain/knowledge/ai-intelligence/model-picker.md+++ b/brain/knowledge/ai-intelligence/model-picker.md@@ -13,14 +13,15 @@ The one picker a builder uses to choose what an agent, chat or AI step runs on.- **Credits tiers:** shown whenever the managed provider is visible.- **Your keys:** one group per key that serves the project, empty when the admin hides specific models.-On `agent` and `chat` a tier whose main model can't call tools is hidden, and so is a key model without tool calling. On `chat`, keys with a curated list offer only that list.+On `agent` and `chat` a tier whose main model can't call tools is hidden, and so is a key model without tool calling. On `chat`, keys of a provider with a curated list offer, in the key's own order, only ids on that list or ids the catalog confirms call tools. Manual-list keys (Vertex, Custom) offer every typed-in tool model. Nothing is reordered or starred: there is no "recommended" in the UI.**Default choice** — `aiModelOptionsUtils.defaultChoice`, tried in this order:-1. The Default tier.-2. On chat only, the Default AI key's first model.-3. The credits default.-4. The first tier.-5. The first key model.+1. On chat only, the platform **Default chat model** (`platform_configuration.defaultChatModel`), if it can run in the project.+2. The Default tier.+3. On chat only, the Default AI key's first known chat model.+4. The credits default.+5. The first tier.+6. The first key model.## Gotchas- An agent model with no `providerConfigId` follows whichever key ranks first (`findEligibleRow` → `rankRows`), so adding a key could silently move it. Agent create and save now pin the key (`withDefaultModel` takes the chat key's id, `withPinnedKey` stores the key a run would use today). Agents saved before this stay unpinned until their next save. The default model follows the pinned chat key's model scope and typed-in list, or the run would reject it. Moving an agent keeps its key only if the target project can use it; otherwise it re-pins to the key a run there would pick (`findRunKeyId` with `preferredConfigId`).@@ -37,10 +38,21 @@ On `agent` and `chat` a tier whose main model can't call tools is hidden, and so- The Run Agent step does not go through `/v1/ai/execute`. Its piece posts to `/v1/agents/runs`, and the agent runtime resolves the model (`getAgentConfig` → `agentModelTier.resolveRun`). Steps pin an exact piece version, so a field the piece learns to forward reaches only steps on that version or newer.- The Run Agent step stores a tier as `{ modelTierId }` and only piece-ai 0.14.1+ forwards it. On an older step `AgentModelField` hides tiers and shows a one-line hint to update the step. Downgrading a step below 0.14.1 keeps the stored tier, and the old piece drops it, so that run uses the Default AI key.- A flow step has no server create hook, so `AgentModelField` writes `defaultChoice` once when the stored value is empty and the step is editable. On an old step it writes the credits default or the first key model instead of a tier.-- The knowledge-base section (and the agent panel's embedding note) checks the project's chat key for every pick, never the picked provider. Uploads embed with `knowledgeBaseService.embeddingModelFor`: the Embeddings capability pick when one is set, else that chat key (Default AI key, else the credits key when visible), whatever the step or agent picked, so a chat key that can't embed (Anthropic) breaks uploads. The web check does not see the Embeddings pick yet; 7b adds it with the Embeddings row. The web reads it from `useChatProvider()`, whose `/v1/ai-providers` row already applies the same `pickChatRow` fallback for the session project that uploads use.+- **The knowledge-base check asks the server, it never guesses.** The KB section and the agent panel's embedding note read `GET /v1/knowledge-base/files/embedding-source` (`useKnowledgeBaseEmbeddingSource`), which runs `knowledgeBaseService.embeddingSourceFor`, the same resolver uploads use: the Embeddings capability pick (key + model), else the Default AI key with its provider's default embedding model, else null. A Default AI key that can't embed (Anthropic) returns null, so the web shows the "no key can index files" note instead of an upload that fails. Builders can't read `/v1/ai-tools` (admin only), which is why this route exists.+- **Chat uses the same `ModelPicker` as agents, as `variant="pill"`.** The chat keeps the raw pick (`modelTierId` / `providerConfigId` + `modelName`) from the conversation and turns it into a `ModelChoice` only where the options are loaded (`chatUtils.choiceOf`). A pick on a deleted key keeps its id with a placeholder provider, so the picker shows Unavailable instead of silently showing the default. A new chat sends what the pill shows; agent chats send no pick (the agent's model wins).- An older managed pick can store a concrete id (`anthropic/claude-sonnet-4.6`) instead of a credits tier id. It still runs while the server's managed list has it (`managedChatModelIds()` plus the published credits tiers' models), so the picker checks that same list: a listed id shows as a Credits pick with its raw id, a retired one as Unavailable.- **Don't use `defaultChoice` on a hot run path.** `aiModelOptionsService.list` fetches every key's model list and skips a key whose list fails, so a flaky provider API (or a fake test key) can leave `defaultChoice` null, or point it somewhere else. The chat run path (`agentChatModel.defaultPick`) checks the Default tier and the Default AI key without listing models, and only falls back to `list` when neither exists.- The picker never writes a default by itself. An agent gets its default model from the server when it is created. An unknown pick shows an amber "Unavailable" and is never silently swapped (S11).+- **Builder-facing picker copy says "Tiers" and "Models", never "Your …".** Builders don't own the keys, the admin does (Kareem, 2026-10-14). Only the admin tier editor (`admin-model-picker.tsx`) keeps "Your keys".+- **A chat pinned to a key model fails only when the key no longer lists it and it is not a curated or deprecated id** (`agentChatModel.pinnedConfig` → `keyNoLongerListsModel`; a failed listing never blocks). Don't gate pins on the curated list alone: chat offers non-curated models, so that check would refuse them at run.+- **Chat model saves are queued, and send waits for the queue** (`use-chat.ts` `pickSaveQueueRef`): a failed save rolls back only if it is the newest pick, and a message sent right after a switch never runs on the old model. Anything that awaits before sending must re-check Stop afterwards (`isSendCancelled`), or a stopped message still goes out. The "set up an AI provider" gate runs only for new chats; a reopened chat uses its own project.+- **Anything that judges a saved tier pick must load model-options with that `tierId`.** `movedTiers` is only filled for the tier you ask about, so a call without it treats a replaced tier as gone (the chat send check blocked a pick the picker showed as "Moved").+- **Clearing the Default chat model is "pick it again"** in the Providers card (or the amber ✕ next to the picker when the pick is gone); `null` keeps the current Default AI key.+- **When the Default chat model is a tier, tier edits re-derive the Default AI key** (`syncDefaultChatKey` in `platform-model-tier-service.ts`, run by tier update, delete with replacement and `removeKeyFromTiers`; a replaced tier also moves the setting). The admin picker ignores "hide specific models", and when that is on a saved own-key default is still offered as chat's only key model.+- **Knowledge-base embeddings never follow a key that can't embed.** With no Embeddings key, `embeddingSourceFor` uses the Default AI key only if its provider has embedding models, then Credits (`findCreditsConfig`), else null. The admin cards mirror this order: the Embeddings card shows Credits as the fallback when the Default AI key can't embed, and the Default chat model card warns only when no Embeddings key is set and Credits isn't available either.+- **Deleting the key or tier behind the Default chat model clears the setting** (key delete and tier delete without a replacement null it in the same transaction), so the card never sits on a dead pick. A model that leaves the key still shows as unavailable, with a "Use default" button.+- **New agents follow the Default chat model** when it can run for agents (`agent-service` `withDefaultModel`), else the Default AI key's first known chat model, the same model a new chat gets. Agent and chat Credits catalogs differ, so agent defaults are checked against the `agent` surface options.+- **The Default AI key follows the Default chat model.** Saving the setting (`platformConfigurationService.update`, checked against `listForPlatform` outside the lock, then under the platform lock) sets `enabledForChat` on the pick's key: a key model's key, a tier's main entry key, or the Credits row. There is no "Set as default" button any more. Before any setting exists, the platform's first own key still gets the flag on create, and that step is skipped once a Default chat model is set so the derived key doesn't drift. Credits is matched by `provider === ACTIVEPIECES`, never by its row id, because that row can be recreated. Because the save also moves `enabledForChat`, the web's `useSetDefaultChatModel` reloads the key list and every `['ai-model-options']` query after it; refreshing only the configuration leaves the card naming the old fallback key.## Key files- `packages/web/src/features/agents/ai-model/`: `ModelPicker`, `ModelPickerPopover`, `ModelDetailCard`diff --git a/brain/knowledge/ai-intelligence/testing-model-tiers-locally.md b/brain/knowledge/ai-intelligence/testing-model-tiers-locally.mdindex 05ce0b69e12..4f6b90288ef 100644--- a/brain/knowledge/ai-intelligence/testing-model-tiers-locally.md+++ b/brain/knowledge/ai-intelligence/testing-model-tiers-locally.md@@ -13,3 +13,5 @@ How to see the published tier file drive chat, agents and the pickers on a dev b6. To see a re-point, change a `modelId` in the file, restart the backend (the catalog cache is in-process, 15 minutes) and reload the page (the web refetches every 15 minutes). Same label, new model in the log.The Activepieces provider must be enabled for chat under Platform, AI, which needs `AP_EDITION=cloud` and `AP_OPENROUTER_PROVISION_KEY` on the dev box.++**Changed a curated model list (`core-piece-types`)?** Rebuild it with `npx turbo run build --filter=@activepieces/core-piece-types`, then restart the backend, or touch any file under `packages/server/api/src`. The running API keeps the old build in memory, while the web already has the new list, so the picker sorts with old data but stars with new data.diff --git a/brain/knowledge/data-storage-observability/database.md b/brain/knowledge/data-storage-observability/database.mdindex a2641ea4a2c..07d8cf29b2a 100644--- a/brain/knowledge/data-storage-observability/database.md+++ b/brain/knowledge/data-storage-observability/database.md@@ -286,6 +286,7 @@ A background migration that fails every retry stops the app from booting. The gu## Gotchas+- **A long-lived PR's migration number goes stale.** Before every push, check `ls database/migration/postgres` *and* `postgres/background` on `origin/main`: if main has caught up, renumber yours past the highest in both tracks (rename the file, class, `name` and the `getMigrations()` lines), since the background track can reuse the same timestamp. #16533 went 1869 → 1872 → 1875 in one week.- **pglite doesn't support `CONCURRENTLY`.** `migrationHelpers.createIndexConcurrently` / `dropIndexConcurrently` fall back to plain `CREATE INDEX IF NOT EXISTS` / `DROP INDEX IF EXISTS` on pglite. Only affects local dev. Older migrations use an inline `const concurrently = isPGlite() ? '' : 'CONCURRENTLY'` ternary — don't reuse that pattern in new code, the helpers supersede it.- **`breaking = true` is the ROLLBACK-safety flag, not the customer-facing "breaking change" label.** Two different concepts. The label is decided per the [PR labels rules](../../../CLAUDE.md#pull-requests); the flag is decided per what the migration's `down()` can undo.- **Contract DDL in the same release as its backfill, skip-release upgrades, and fresh installs are all handled by boot catchup.** `runMigrationsWithCatchup` wraps TypeORM's `runMigrations`: when a blocking migration's guard throws `BackgroundMigrationNotCompleteError`, the catchup catches it, runs that one backfill synchronously, and retries. Max 10 catchup attempts (one per distinct dependency), then boot fails with the failing migration name. Normal upgrade pays nothing; skip-release pays a one-time slow boot while prior backfills catch up.diff --git a/brain/knowledge/data-storage-observability/knowledge-base.md b/brain/knowledge/data-storage-observability/knowledge-base.mdindex 8119aaf3638..9015be949d7 100644--- a/brain/knowledge/data-storage-observability/knowledge-base.md+++ b/brain/knowledge/data-storage-observability/knowledge-base.md@@ -21,6 +21,7 @@ A project-scoped document store: users upload PDF/DOCX/TXT/CSV files, which are- **pgvector is not created by a migration** — the `AddPgVectorExtension` migration is a no-op because `CREATE EXTENSION` crash-loops managed Postgres where the app user lacks privileges.- Instead `knowledgeBaseSeed` runs `knowledgeBaseSchema.ensure()` on **every boot** (under the migration lock, wrapped in `tryCatch`): creates the extension + table + indexes when available, else skips silently. Installing pgvector later activates KB on the next restart, no redeploy. PGLite bundles pgvector so CE works out of the box.- Gating: backend `preHandler` throws `FEATURE_DISABLED` when the extension is absent (cached once observed); frontend hides the UI via the `PGVECTOR_AVAILABLE` flag.+- **No Knowledge Base section in local agent settings?** `docker-compose.dev.yml` runs plain `postgres:14.4` (no pgvector), unlike `docker-compose.yml`'s `pgvector/pgvector:0.8.0-pg14`. Swap the image, recreate the db container, restart the API. Check with `GET /api/v1/flags` → `PGVECTOR_AVAILABLE`.- Allowed MIME types (`KB_ALLOWED_MIME_TYPES`): PDF, plain text, CSV, DOCX only.- **`chunkIndex` is a place in the file, and one place holds one row.** `storeChunks` resolves every submitted chunk to an index before it writes anything. An id moves that row to the index and displaces whoever was sitting there. No id takes over the row already at that index, which is what keeps a chunk id stable when a file is indexed again. A repeated index keeps the last copy. A repeated id, or one naming no chunk of this file, is refused rather than guessed at. All of it runs in one transaction behind a `pessimistic_write` lock on the *file* row. Thirteen review rounds on this endpoint were the same bug in different payloads, so add a case to `knowledge-base-storage.test.ts` instead of a branch to the service.- **Nothing in the database enforces one row per place.** There is no unique index on `(knowledgeBaseFileId, chunkIndex)`, so two writes arriving at once are held apart by that row lock alone, and the lock is a no-op on PGLite because it runs a single connection. The index ships with the indexing work.diff --git a/brain/knowledge/decisions/one-default-chat-model.md b/brain/knowledge/decisions/one-default-chat-model.mdnew file mode 100644index 00000000000..a2eda4f94b5--- /dev/null+++ b/brain/knowledge/decisions/one-default-chat-model.md@@ -0,0 +1,19 @@+---+status: accepted+---++# New chats start on one explicit Default chat model++## Decision+A platform has one **Default chat model** setting (`platform_configuration.defaultChatModel`): a tier, a key model, or a Credits tier, set from a card at the top of the Providers page. Every new chat starts there. Where it can't run (its key doesn't serve the project, or it was deleted), a new chat quietly falls back to the Default tier, the Default AI key, Credits, then the first option, and the card warns the admin. The Default AI key is derived from this setting, not set on its own.++## Context+Before, a new chat's model came from a hidden chain: Default tier → the Default AI key's first curated model → Credits → first option, with the Default AI key set from a button on a key page and "recommended" models starred in the picker. The PM and Louai found it unclear (2026-10-19): admins couldn't tell which model a new chat would use, or why, and the recommendations weren't backed by anything robust.++## Why+One explicit setting answers "what does a new chat use?" in one place, and folding the Default AI key into it leaves one concept to explain. Rejected: keep the rule chain and just explain it on screen. With recommendations gone, a key's "first model" is an arbitrary list order, so explaining the chain would describe a guess.++## Consequences+- One nullable jsonb column (migration 1875), no backfill. Existing platforms keep the old chain until an admin picks, and the chain keeps a Default AI key step so BYOK platforms aren't moved to Credits.+- Deleting the picked tier or key doesn't clean the setting: it falls back at read time and the card shows Unavailable.+- Bringing back recommendations needs a real recommendation system first.diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.mdindex 36b3cbdb059..0ff0b1d02ad 100644--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md@@ -42,6 +42,7 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def- **Reading the parallel test job's log: trust the turbo `Failed:` line at the tail, not the scary lines in the middle.** The job runs about 21 turbo tasks at once, so `gh run view <run> --job <job> --log-failed` interleaves all of them. `FATAL ERROR: Reached heap limit` and `Caught fatal signal 9` next to `test/lib/sandbox/*.test.ts` are the sandbox suite killing isolates on purpose; `Error: Boom inside engine trigger hook` and the `HttpError` stderr dumps are fixture output. Strip the prefixes (`sed 's/^[^\t]*\t[^\t]*\t//'`), grep ` FAIL ` for the real assertion, and read the `Tasks: … Failed: <task>` summary to know which package actually failed. Engine handler tests timing out at 20 s in that job are load, not hangs: `flow-skip-progress.test.ts` (28 s) and then `flow-rerun.test.ts` timed out on consecutive runs of #15707 while each finishes in 0.6 s locally. The CI step starts `turbo run test` and the API's `test-unit test-ce test-ee test-cloud` in parallel with `&` on a 4-vCPU runner, and a branch that touches `packages/core/*` invalidates about 60 downstream tasks, so the engine suites compete with four Postgres-backed API suites for the same cores; main mostly hits the turbo cache and never sees it. The engine's `testTimeout` is now 60 s, the value the API's vitest config already used for the same job; the real lever, if it recurs, is not running the two turbo invocations concurrently.- **A spurious `core` request on a pieces PR is not always the lockfile — check for a second root file.** [#14558](https://github.com/activepieces/activepieces/pull/14558) looked like the lockfile case but its non-pieces files were `bun.lock` *and* `tsconfig.base.json`; the `core` request landed 6s after the commit that touched the tsconfig, not after the pieces push. Per-piece `paths` mappings generated into root `tsconfig.base.json` mean a pieces change can still reach a core-owned file, and no CODEOWNERS pattern can fix that — the file holds real compiler options and CODEOWNERS has no sub-file granularity.- **Greptile's Confidence Score prose is cumulative, so a low score mixes resolved findings with live ones — triage each claim separately rather than trusting or dismissing the number.** It edits one summary comment in place, and its "Files Needing Attention" list keeps naming findings that are already resolved and outdated: #14825 sat at 2/5 citing three files, two of which were a closed P1 and a duplicate view of the third. Read the *unresolved* review threads (`reviewThreads(first:60) { isResolved isOutdated }` over GraphQL — the REST comments endpoint carries no resolution state) and judge from those; re-trigger the review to refresh the score. It also re-raises the same class of finding each round with a new comment id, so a fix on one thread does not silence its sibling. **The score recomputes on a push, never on a reply** — so a finding Greptile *itself* withdraws still counts against it. On [#15243](https://github.com/activepieces/activepieces/pull/15243) the second pass read the pushed fix, filed zero new comments, and replied "this is not a valid finding… Withdrawing the comment" on its own P2; the summary comment was edited 67 seconds later, but only the footer (`Reviews (2)`, last-reviewed-commit link) changed — the headline stayed 2/5 and still justified itself with the finding just retracted. So compare the summary's `updated_at` against the review `submitted_at` from `gh api repos/:owner/:repo/pulls/<n>/reviews`: a summary newer than the last review pass has usually only had its footer bumped. But do not read "cumulative" as "stale": a 2/5 on [#14934](https://github.com/activepieces/activepieces/pull/14934) listed three files, two carrying findings already fixed and one naming a real bypass nobody had tested — the approve path published without the guard the direct path ran. The resolved-thread count is the right gate for *merging*, and a weak signal about *content*, because a finding Greptile states only in the summary never becomes a thread to resolve. Read the summary's file list even at zero unresolved threads, and check each named file against the code. The same applies to a human reviewer's tool-generated summary: Amr's review on #15707 said "Blockers: 4" and named them, but only two had an inline thread; the other two never left his tool. Count the threads against the summary before triaging, and answer the missing ones in a PR comment so the record shows they were checked.+- **Greptile reads the PRs stacked on yours and flags a changed signature as breaking them.** On #16533 (7b) it filed a P1 because the child #16603 still called `movedTiers({ tierId })` after 7b changed it to `tierIds`, and suggested keeping the old argument. Don't add a compat shim: merge the parent into the child, fix the call there, and reply on the parent's thread with the child's commit. If the child never edited those lines, the merge alone fixes it.- **Greptile marks down a PR whose title describes the code instead of what the user gets.** A custom rule in the Greptile dashboard (not in this repo) deducts half a point and posts a P2 "Implementation-focused PR title" on a title like `feat(ai): the managed model dropdown stores a tier, not a model`. Write the title as the user-visible change and keep the Conventional Commit prefix, lowercase after the type ("Validate PR title" and commitlint check it), e.g. `feat(ai): managed AI steps follow their tier when it moves to a newer model`. Fix it with `gh pr edit <n> --title`; the `edited` event reruns the title check, and no commit is needed.- **`api` and `worker` resolve `@activepieces/shared` and the `core-*` packages from `dist`, so a package-local `tsc --noEmit` there reports whatever was built last.** Both `packages/server/api/tsconfig.app.json` and `packages/server/worker/tsconfig.lib.json` set `"paths": {}`, clearing the inherited source mappings, so an export added to `packages/core/shared/src` shows up as `TS2305: has no exported member` until that package is rebuilt — the error names your file and is not about your file. `web` is not affected for the packages it actually imports: `vite.config.mts` aliases `@activepieces/shared`, `@activepieces/pieces-framework`, `core-utils`, `core-formula`, `core-piece-types` and `core-execution` to their `src`. Nothing else is aliased there, so check `vite.config.mts` before assuming a package is exempt — `@activepieces/ai-providers` (note the name: no `core-` prefix) has no Vite alias and resolves through `dist`, though it is mapped to source in `tsconfig.base.json` and web does not import it today. `npx turbo run build --filter=<pkg>` needs no manual pre-build, since `build` declares `dependsOn: ["^build"]` and builds dependencies first; only the direct `tsc` invocation can lie, and `npx turbo run build --filter=@activepieces/shared` is the cure. **The web editor and `tsc` are affected too, one hop out.** `packages/web/tsconfig.app.json` maps only `@activepieces/shared`, `pieces-framework` and a few pieces to `src`; `shared/src` then imports `@activepieces/core-utils`, which resolves through `node_modules` to `dist`. So after a sync that changes a `core-utils` schema (a `sessionToken` field on the Bedrock auth, #15747), the editor reports `'sessionToken' does not exist in type` on main's own web code while `vite` is fine. Rebuild the core packages and restart the TS server; the code needs no change.- **The `main` CI job builds web, worker, api and engine before it runs a single test, so a build error there fails the whole job with no test output to point at it.** One missing enum import in a worker file surfaced only as `worker#build` exiting 2. Before pushing a change that moves code between files, run `npx turbo run build --filter=web --filter=worker --filter=api --filter=@activepieces/engine` — the same set the job builds — rather than trusting the per-package typecheck you happened to run before the move. Note that the `web` half of that command needs more heap than node gives it by default: on a 14 GB machine `vite build` transforms all ~7k modules and then dies with `node::OOMErrorHandler` / `SIGABRT` during bundling, which reads as a broken change rather than a full laptop. Run it as `NODE_OPTIONS=--max-old-space-size=8192 npx turbo run build --filter=web` and it finishes in well under a minute. CI runners have the headroom, so this only ever bites locally.@@ -95,6 +96,7 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def- **Mintlify-editor PRs arrive with `untitled-page*.mdx` at the docs root and `(1)`/`(2)`-suffixed media, wired into `docs.json` under those names.** The bot commits whatever the web editor autosaved, so pages land as `docs/untitled-page-5.mdx` rather than in the folder their nav group implies, and re-uploaded assets keep the browser's download-collision suffix (`data-flow-(1).mp4`, `01---insert-panel-(1.2x).mp4`). Mintlify's own link check passes — the names are internally consistent — so nothing flags it. Rename the files, fix the `docs.json` entries, then diff the *flattened nav tree* against `main` rather than reading the raw JSON diff: the editor also reindents, which buried a real change (the Enterprise Control `Security` group demoted to a child of `Guides`) inside 242 lines of whitespace churn on that PR.- **After rewriting a lower branch of a stack, the `--onto` upstream you need is that branch's *old* tip, and `<branch>@{1}` is where to read it.** Every commit above a rewritten branch has to be replayed with `git rebase --onto <new lower tip> <old lower tip> <upper>`, and the old tip stops being reachable by name the moment the rebase finishes. Guessing a SHA from an earlier terminal scroll either fails outright with `invalid upstream` or, worse, succeeds against the wrong base and replays a handful of commits instead of all of them, which surfaces as a pile of conflicts the branch has with itself. `git rev-parse <branch>@{1}` reads it from the reflog every time. Re-run the whole `--onto` chain top-down after any lower-branch amend, and confirm afterwards that `git log --format=%s main..<top>` has no duplicate subjects.- **When a stacked PR's parent is squash-merged, merge `main` into the child and retarget; do not rebase.** The parent's commits are on `main` by content but not by SHA, so `git merge origin/main` on the child sees both sides make the same change and auto-merges it; only the lines the child *rewrote* from the parent conflict, plus anything `main` changed in the same functions since (PR 2 of the model tiers work, #15825: three brain and docs pages where PR 2 had rewritten PR 1's sentences, and `agent-helpers.ts` where main's `resolveImageModelId` landed next to the surface-threaded fast-model helper). No history rewrite, a normal push, and the PR above it keeps its base untouched; a `--onto` rebase would replay every commit up the stack and force-push each. After the retarget, the PR's Commits tab still lists the parent's original SHAs (they reached `main` only as a squash) while Files changed shows only the child's files; the second view is the one that matters, so do not "fix" the first. Two traps in the resolution. `git checkout --ours <file>` on a conflicted file takes the *whole* file from your side and silently discards main's auto-merged hunks in it, so resolve hunk by hunk and check `git diff origin/main -- <file>` afterwards shows only your lines. And `tsc` against the merged tree resolves `@activepieces/shared` through the built dist, which still holds the pre-merge exports: three phantom "has no exported member" errors vanished after `npx turbo run build --filter=@activepieces/server-utils`. Rebuild the core libs before believing a typecheck, then run the child's own tests. A child branched off an *older* head of its parent (the parent took review fixes after the child was cut) also conflicts in files the child never touched: those are the parent's early copy against its final one on `main`. If `git log <old parent head>..HEAD -- <file>` lists none of the child's commits, `git checkout --theirs <file>` is the right answer there, because the whole file is main's (PR 4 of the model tiers work, #15866: `use-chat.ts`, `core/execution/package.json` and an agent test). For a file the child *did* change, take main's copy and replay only the child's own commit on top: `git checkout --theirs <files> && git add <files> && git show <child commit> -- <files> | git apply --3way` (it needs the files staged, and in zsh pass the list as an array, since a plain variable is not word-split); only hunks where main moved the child's own lines are left to resolve by hand (PR 5, #15871: six files, one hunk).+- **If the parent's final head is already inside the child, the `main` merge is a no-op: take the child's side for every conflict and check `git diff HEAD` is empty.** The squash commit has exactly the parent's final tree, so each conflict is the parent's old text against the child's newer edit. Check `git merge-base --is-ancestor <parent head> HEAD` first; if the parent got commits after the child last synced, resolve by hand. #16533 (7b on 7a, 2026-10-18): 9 conflicts, all child-side, tree unchanged. Run `git branch --show-current` before merging; a session can start on another stacked branch.- **When a plain `main` merge into a stacked child conflicts everywhere, build the merge from main's tree plus the child's own patch.** #16264 carried two squash-merged parents (3b and PR 4) and a plain merge gave 12 conflicts. Steps: `git diff --binary <child's last commit before its own work> origin/<child> > own.patch`, then `git merge -s ours --no-commit origin/main`, `git read-tree --reset -u origin/main`, and `git apply --3way own.patch`. That left 5 small conflicts: versions, `bun.lock`, translations and brain bullets. The tree equals main plus the child's work, so no deleted file comes back (the risk with a plain merge). History is still a real merge, so no force-push is needed. Check `git diff --cached origin/main --stat` lists only the child's files before committing.- **Retargeting a PR's base never starts CI, and a push made while the old base conflicts may not start it either.** `ci.yml` listens only to `pull_request` opened, synchronize and reopened; `gh pr edit --base` fires `edited`, which starts nothing. On #15866 the catch-up merge was pushed while the PR still targeted its squash-merged parent's branch, the main CI never ran on that head, and the retarget did not trigger it, so the PR showed only the small checks (title, breaking change, Greptile) and looked green. After a retarget, check `gh pr checks <n>` lists `build-test` and the `api` jobs; if not, push again (an empty `ci:` commit is enough). Never `gh run rerun`: it replays the old event. Simpler when a rebuild needs a force-push anyway: retarget first, then push. The push fires `synchronize` against the new base and the main CI starts on its own (#16116, after the parent squash-merged); pushing first and retargeting after needed the empty commit (#16197).- **Never commit a shared file onto a lower branch of a stack by copying it in from the stack top — you drag the upper branches' edits down with it.** Adding one gotcha bullet to a brain page while sitting on the top branch, then `git checkout <stash-or-top> -- <file>` after switching to the base branch, brings the *whole* file across, so every bullet the upper branches added to that page is silently duplicated onto the base. The commit stat is the tell: a one-line edit that reports six insertions is not a one-line edit. Switch branches first, re-apply the edit against **that branch's own copy** of the file, and re-check the stat before committing.diff --git a/packages/core/piece-types/src/lib/ai-providers.test.ts b/packages/core/piece-types/src/lib/ai-providers.test.tsindex fdd76c4c65b..74b63f2fdf9 100644--- a/packages/core/piece-types/src/lib/ai-providers.test.ts+++ b/packages/core/piece-types/src/lib/ai-providers.test.ts@@ -25,10 +25,11 @@ describe('AI_PROVIDER_CAPABILITIES', () => {].sort())})- it('marks embedding support iff a default embedding model exists', () => {+ it('marks embedding support iff the provider lists embedding models, the first being the default', () => {for (const provider of Object.values(AIProviderName)) {const caps = AI_PROVIDER_CAPABILITIES[provider]- expect(caps.supportsEmbedding).toBe(caps.defaultEmbeddingModel !== undefined)+ expect(caps.supportsEmbedding).toBe(caps.embeddingModels.length > 0)+ expect(caps.defaultEmbeddingModel).toBe(caps.embeddingModels[0])}})})@@ -138,7 +139,7 @@ describe('canDisableReasoning', () => {describe('tier native model ids', () => {it('names a model the native Anthropic list actually offers, so no tier resolves to an id that does not exist', () => {for (const tier of ACTIVEPIECES_CHAT_TIERS) {- expect(ALLOWED_CHAT_MODELS_BY_PROVIDER[AIProviderName.ANTHROPIC], tier.id).toContain(tier.nativeModelId)+ expect(aiProviderUtils.runnableChatModelIds({ provider: AIProviderName.ANTHROPIC }), tier.id).toContain(tier.nativeModelId)}})diff --git a/packages/core/piece-types/src/lib/ai-providers.ts b/packages/core/piece-types/src/lib/ai-providers.tsindex 58c7bb1f66a..fc6796dd2fd 100644--- a/packages/core/piece-types/src/lib/ai-providers.ts+++ b/packages/core/piece-types/src/lib/ai-providers.ts@@ -234,13 +234,15 @@ const CF_GATEWAY_SUBMODEL_TO_PROVIDER: Record<string, AIProviderName> = {}const OPENAI_CHAT_MODELS = ['gpt-5.5', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.4-mini', 'gpt-5.4-nano', 'gpt-4.1', 'gpt-4.1-mini'] as const-const ANTHROPIC_CHAT_MODELS = ['claude-sonnet-4-6', 'claude-opus-4-7', 'claude-haiku-4-5'] as const+const ANTHROPIC_CHAT_MODELS = ['claude-sonnet-5-5', 'claude-opus-5-5', 'claude-haiku-5-5'] as const+const DEPRECATED_ANTHROPIC_CHAT_MODELS = ['claude-sonnet-4-6', 'claude-opus-4-7', 'claude-haiku-4-5'] as constconst ANTHROPIC_OPENROUTER_CHAT_MODELS = ['claude-sonnet-4.6', 'claude-opus-4.7', 'claude-opus-4.8', 'claude-haiku-4.5'] as constconst GOOGLE_CHAT_MODELS = ['gemini-3.7-flash', 'gemini-3.1-pro-preview', 'gemini-3-flash-preview'] as constconst DEPRECATED_GOOGLE_CHAT_MODELS = ['gemini-2.5-pro', 'gemini-2.5-flash'] as constconst X_AI_OPENROUTER_CHAT_MODELS = ['grok-4.20'] as constconst DEPRECATED_CHAT_MODELS_BY_PROVIDER: Partial<Record<AIProviderName, readonly string[]>> = {+ [AIProviderName.ANTHROPIC]: DEPRECATED_ANTHROPIC_CHAT_MODELS,[AIProviderName.GOOGLE]: DEPRECATED_GOOGLE_CHAT_MODELS,[AIProviderName.VERTEX]: DEPRECATED_GOOGLE_CHAT_MODELS,}@@ -272,6 +274,9 @@ const CHAT_MODEL_LABELS: Record<string, string> = {'gpt-5.4-nano': 'GPT-5.4 nano','gpt-4.1': 'GPT-4.1','gpt-4.1-mini': 'GPT-4.1 mini',+ 'claude-sonnet-5-5': 'Claude Sonnet 5.5',+ 'claude-opus-5-5': 'Claude Opus 5.5',+ 'claude-haiku-5-5': 'Claude Haiku 5.5','claude-sonnet-4-6': 'Claude Sonnet 4.6','claude-opus-4-7': 'Claude Opus 4.7','claude-haiku-4-5': 'Claude Haiku 4.5',@@ -402,12 +407,12 @@ function getMaxContextTokens({ provider }: { provider: AIProviderName | undefinereturn PROVIDER_MAX_CONTEXT_TOKENS[provider] ?? DEFAULT_MAX_CONTEXT_TOKENS}-const DEFAULT_EMBEDDING_MODELS: Partial<Record<AIProviderName, string>> = {- [AIProviderName.OPENAI]: 'text-embedding-3-small',- [AIProviderName.GOOGLE]: 'text-embedding-004',- [AIProviderName.AZURE]: 'text-embedding-3-small',- [AIProviderName.ACTIVEPIECES]: 'text-embedding-3-small',- [AIProviderName.OPENROUTER]: 'openai/text-embedding-3-small',+const EMBEDDING_MODELS: Partial<Record<AIProviderName, readonly string[]>> = {+ [AIProviderName.OPENAI]: ['text-embedding-3-small', 'text-embedding-3-large'],+ [AIProviderName.GOOGLE]: ['text-embedding-004', 'gemini-embedding-001'],+ [AIProviderName.AZURE]: ['text-embedding-3-small', 'text-embedding-3-large'],+ [AIProviderName.ACTIVEPIECES]: ['text-embedding-3-small'],+ [AIProviderName.OPENROUTER]: ['openai/text-embedding-3-small', 'openai/text-embedding-3-large'],}const WEB_SEARCH_MODE_BY_PROVIDER: Partial<Record<AIProviderName, AIWebSearchMode>> = {@@ -441,8 +446,9 @@ function buildProviderCapabilities(provider: AIProviderName): AIProviderCapabilireturn {chatModels: ALLOWED_CHAT_MODELS_BY_PROVIDER[provider],maxContextTokens: getMaxContextTokens({ provider }),- defaultEmbeddingModel: DEFAULT_EMBEDDING_MODELS[provider],- supportsEmbedding: DEFAULT_EMBEDDING_MODELS[provider] !== undefined,+ embeddingModels: EMBEDDING_MODELS[provider] ?? [],+ defaultEmbeddingModel: EMBEDDING_MODELS[provider]?.[0],+ supportsEmbedding: (EMBEDDING_MODELS[provider] ?? []).length > 0,supportsImageGeneration: !NO_IMAGE_GENERATION_PROVIDERS.has(provider),defaultImageModel: DEFAULT_IMAGE_MODELS[provider],webSearch: WEB_SEARCH_MODE_BY_PROVIDER[provider],@@ -523,6 +529,7 @@ export type OpenAiCompatibleVendor =export type AIProviderCapabilities = {chatModels?: readonly string[] | undefinedmaxContextTokens: number+ embeddingModels: readonly string[]defaultEmbeddingModel: string | undefinedsupportsEmbedding: booleansupportsImageGeneration: booleandiff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex e5ff0ad0d43..d2e61e16353 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.202.1",+ "version": "0.203.0","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/automation/knowledge-base/index.ts b/packages/core/shared/src/lib/automation/knowledge-base/index.tsindex eaf40eb8335..baad88fe783 100644--- a/packages/core/shared/src/lib/automation/knowledge-base/index.ts+++ b/packages/core/shared/src/lib/automation/knowledge-base/index.ts@@ -1,4 +1,4 @@-import { BaseModelSchema } from '@activepieces/core-utils'+import { AIProviderName, BaseModelSchema, Nullable } from '@activepieces/core-utils'import { z } from 'zod'const KnowledgeBaseFile = z.object({@@ -8,4 +8,10 @@ const KnowledgeBaseFile = z.object({displayName: z.string(),})+export const KnowledgeBaseEmbeddingSource = z.object({+ provider: Nullable(z.enum(AIProviderName)),+ modelId: Nullable(z.string()),+})+export type KnowledgeBaseFile = z.infer<typeof KnowledgeBaseFile>+export type KnowledgeBaseEmbeddingSource = z.infer<typeof KnowledgeBaseEmbeddingSource>diff --git a/packages/core/shared/src/lib/management/platform/platform-configuration.ts b/packages/core/shared/src/lib/management/platform/platform-configuration.tsindex 2128d6321ff..b7ca2708efb 100644--- a/packages/core/shared/src/lib/management/platform/platform-configuration.ts+++ b/packages/core/shared/src/lib/management/platform/platform-configuration.ts@@ -1,6 +1,7 @@-import { BaseModelSchema, isNil } from '@activepieces/core-utils'+import { BaseModelSchema, isNil, Nullable } from '@activepieces/core-utils'import { z } from 'zod'import { formErrors } from '../../form-errors'+import { ModelChoice } from '../ai-providers'const MIN_BARRIER_SIGNALS = 1const MAX_BARRIER_SIGNALS = 10_000@@ -15,6 +16,7 @@ export const PlatformConfiguration = z.object({.min(MIN_BARRIER_SIGNALS, formErrors.atLeastOne).max(MAX_BARRIER_SIGNALS, formErrors.atMostTenThousand),aiSpecificModelsVisible: z.boolean(),+ defaultChatModel: Nullable(ModelChoice),})export type PlatformConfiguration = z.infer<typeof PlatformConfiguration>@@ -27,6 +29,7 @@ export type PlatformConfigurationSettings = z.infer<typeof PlatformConfigurationexport const UpdatePlatformConfigurationRequestBody = PlatformConfigurationSettings.partial().extend({aiSpecificModelsVisible: z.boolean().optional(),+ defaultChatModel: Nullable(ModelChoice),})export type UpdatePlatformConfigurationRequestBody = z.infer<typeof UpdatePlatformConfigurationRequestBody>diff --git a/packages/server/api/src/app/ai/ai-model-options-service.ts b/packages/server/api/src/app/ai/ai-model-options-service.tsindex 6c55965a9e3..05bd7055ea8 100644--- a/packages/server/api/src/app/ai/ai-model-options-service.ts+++ b/packages/server/api/src/app/ai/ai-model-options-service.ts@@ -1,6 +1,6 @@import { AIProviderName, isNil, PlatformId, spreadIfDefined } from '@activepieces/core-utils'import { modelCatalog, modelTierCatalog } from '@activepieces/server-utils'-import { AIProviderModel, AIProviderModelType, aiProviderUtils, ModelChoice, ModelOptions, ModelOptionsCredits, ModelOptionsKey, ModelOptionsSurface, ModelOptionsTier, OptionModel } from '@activepieces/shared'+import { AIProviderModel, AIProviderModelType, aiProviderUtils, ModelChoice, ModelOptions, ModelOptionsCredits, ModelOptionsKey, ModelOptionsSurface, ModelOptionsTier, OptionModel, PlatformConfiguration } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { platformConfigurationService } from '../platform/platform-configuration.service'import { aiKeyScope } from './ai-key-scope'@@ -10,42 +10,47 @@ import { platformModelTierService, TierForRun } from './platform-model-tier-servexport const aiModelOptionsService = (log: FastifyBaseLogger) => ({async list({ platformId, projectId, surface, tierId }: { platformId: PlatformId, projectId: string, surface: ModelOptionsSurface, tierId?: string }): Promise<ModelOptions> {- const [keys, tiersForRun, movedTiers, configuration, catalog] = await Promise.all([+ const configuration = await platformConfigurationService(log).getOrCreateForPlatform({ platformId })+ const [keys, tiersForRun, movedTiers, catalog] = await Promise.all([aiProviderService(log).listKeysForProject({ platformId, projectId }),platformModelTierService.listForPicker({ platformId, scope: { type: 'project', projectId } }),- platformModelTierService.movedTiers({ platformId, tierId }),- platformConfigurationService(log).getOrCreateForPlatform({ platformId }),+ platformModelTierService.movedTiers({ platformId, tierIds: [tierId, tierIdOf(configuration.defaultChatModel)] }),modelCatalog.load(),])- const lookup: Lookup = ({ provider, modelId }) => catalog.lookup({ provider, modelId })- const callsTools: CallsTools = ({ provider, modelId }) => surface === 'flow' || lookup({ provider, modelId })?.supportsToolCalling !== false- const tiers = tiersForRun.flatMap((forRun) => toTierOption({ forRun, keys, lookup, callsTools }))- const creditsKey = keys.find((key) => key.row.provider === AIProviderName.ACTIVEPIECES)- const credits = isNil(creditsKey) ? null : toCredits({ row: creditsKey.row, surface, lookup })- const specificModelsHidden = !configuration.aiSpecificModelsVisible- const keyOptions = specificModelsHidden ? [] : keys.flatMap((key) => toKeyOption({ key, surface, lookup, callsTools }))- const chatKeyId = keys.find((key) => key.isChatKey)?.row.id- return {- tiers,- credits,- keys: keyOptions,- defaultChoice: aiModelOptionsUtils.defaultChoice({ surface, tiers, credits, keys: keyOptions, chatKeyId }),- movedTiers,- specificModelsHidden,- }+ return buildOptions({ keys, tiersForRun, movedTiers, configuration, catalog, surface })+ },++ async listForPlatform({ platformId, surface, platformDefault }: { platformId: PlatformId, surface: ModelOptionsSurface, platformDefault?: ModelChoice | null }): Promise<ModelOptions> {+ const configuration = await platformConfigurationService(log).getOrCreateForPlatform({ platformId })+ const chatDefault = platformDefault === undefined ? configuration.defaultChatModel ?? null : platformDefault+ const [keys, tiersForRun, movedTiers, catalog] = await Promise.all([+ aiProviderService(log).listKeysForPlatform({ platformId }),+ platformModelTierService.listForPicker({ platformId, scope: { type: 'platform' }, anyProject: true }),+ platformModelTierService.movedTiers({ platformId, tierIds: [tierIdOf(chatDefault)] }),+ modelCatalog.load(),+ ])+ return buildOptions({ keys, tiersForRun, movedTiers, configuration: { ...configuration, defaultChatModel: chatDefault, aiSpecificModelsVisible: true }, catalog, surface })},})export const aiModelOptionsUtils = {- defaultChoice({ surface, tiers, credits, keys, chatKeyId }: DefaultChoiceParams): ModelChoice | null {+ usableChoice,+ defaultChoice({ surface, tiers, credits, keys, chatKeyId, platformDefault, movedTiers }: DefaultChoiceParams): ModelChoice | null {+ const chatLike = surface !== 'flow'+ const usableDefault = chatLike && !isNil(platformDefault)+ ? usableChoice({ choice: platformDefault, tiers, credits, keys, movedTiers: movedTiers ?? {} })+ : null+ if (!isNil(usableDefault)) {+ return usableDefault+ }const defaultTier = tiers.find((tier) => tier.isDefault)if (!isNil(defaultTier)) {return { type: 'tier', tierId: defaultTier.id }}- const chatKey = surface === 'chat' ? keys.find((key) => key.providerConfigId === chatKeyId) : undefined- const chatKeyModel = chatKey?.models[0]- if (!isNil(chatKey) && !isNil(chatKeyModel)) {- return modelChoiceOf({ key: chatKey, modelId: chatKeyModel.id })+ const chatKey = chatLike ? keys.find((key) => key.providerConfigId === chatKeyId) : undefined+ const chatKeyModelId = isNil(chatKey) ? undefined : firstRunnableModelId({ key: chatKey })+ if (!isNil(chatKey) && !isNil(chatKeyModelId)) {+ return modelChoiceOf({ key: chatKey, modelId: chatKeyModelId })}if (!isNil(credits)) {return { type: 'model', provider: AIProviderName.ACTIVEPIECES, providerConfigId: credits.providerConfigId, modelId: credits.defaultTierId }@@ -58,6 +63,61 @@ export const aiModelOptionsUtils = {},}+function buildOptions({ keys, tiersForRun, movedTiers, configuration, catalog, surface }: BuildOptionsParams): ModelOptions {+ const lookup: Lookup = ({ provider, modelId }) => catalog.lookup({ provider, modelId })+ const callsTools: CallsTools = ({ provider, modelId }) => surface === 'flow' || lookup({ provider, modelId })?.supportsToolCalling !== false+ const tiers = tiersForRun.flatMap((forRun) => toTierOption({ forRun, keys, lookup, callsTools }))+ const creditsKey = keys.find((key) => key.row.provider === AIProviderName.ACTIVEPIECES)+ const credits = isNil(creditsKey) ? null : toCredits({ row: creditsKey.row, surface, lookup })+ const specificModelsHidden = !configuration.aiSpecificModelsVisible+ const allKeyOptions = keys.flatMap((key) => toKeyOption({ key, surface, lookup, callsTools }))+ const keyOptions = specificModelsHidden+ ? onlyPlatformDefault({ keys: allKeyOptions, platformDefault: surface === 'flow' ? null : configuration.defaultChatModel ?? null })+ : allKeyOptions+ const chatKeyId = keys.find((key) => key.isChatKey)?.row.id+ return {+ tiers,+ credits,+ keys: keyOptions,+ defaultChoice: aiModelOptionsUtils.defaultChoice({ surface, tiers, credits, keys: keyOptions, chatKeyId, platformDefault: configuration.defaultChatModel ?? null, movedTiers }),+ movedTiers,+ specificModelsHidden,+ }+}++function usableChoice({ choice, tiers, credits, keys, movedTiers }: { choice: ModelChoice, tiers: ModelOptionsTier[], credits: ModelOptionsCredits | null, keys: ModelOptionsKey[], movedTiers: Record<string, string> }): ModelChoice | null {+ if (choice.type === 'tier') {+ const tierId = movedTiers[choice.tierId] ?? choice.tierId+ return tiers.some((tier) => tier.id === tierId) ? { type: 'tier', tierId } : null+ }+ if (choice.provider === AIProviderName.ACTIVEPIECES) {+ return !isNil(credits) && credits.tiers.some((tier) => tier.id === choice.modelId)+ ? { ...choice, providerConfigId: credits.providerConfigId }+ : null+ }+ const offered = keys.some((key) => key.providerConfigId === choice.providerConfigId && key.models.some((model) => model.id === choice.modelId))+ return offered ? choice : null+}++function onlyPlatformDefault({ keys, platformDefault }: { keys: ModelOptionsKey[], platformDefault: ModelChoice | null }): ModelOptionsKey[] {+ if (isNil(platformDefault) || platformDefault.type !== 'model' || platformDefault.provider === AIProviderName.ACTIVEPIECES) {+ return []+ }+ return keys.flatMap((key) => {+ const models = key.providerConfigId === platformDefault.providerConfigId ? key.models.filter((model) => model.id === platformDefault.modelId) : []+ return models.length === 0 ? [] : [{ ...key, models }]+ })+}++function firstRunnableModelId({ key }: { key: ModelOptionsKey }): string | undefined {+ const runnable = aiProviderUtils.runnableChatModelIds({ provider: key.provider })+ return runnable.find((modelId) => key.models.some((model) => model.id === modelId)) ?? key.models[0]?.id+}++function tierIdOf(choice: ModelChoice | null | undefined): string | undefined {+ return choice?.type === 'tier' ? choice.tierId : undefined+}+function toTierOption({ forRun, keys, lookup, callsTools }: { forRun: TierForRun, keys: ProjectKeyModels[], lookup: Lookup, callsTools: CallsTools }): ModelOptionsTier[] {const { tier, entries } = forRunconst usable = entries.filter((entry) => callsTools({ provider: entry.key.provider, modelId: entry.modelId }))@@ -108,26 +168,20 @@ function toKeyOption({ key, surface, lookup, callsTools }: { key: ProjectKeyModeif (row.provider === AIProviderName.ACTIVEPIECES || isNil(models)) {return []}- const textModels = models.filter((model) => model.type === AIProviderModelType.TEXT)- const offered = surface === 'chat'- ? chatModels({ row, textModels, lookup, callsTools })- : textModels.filter((model) => callsTools({ provider: row.provider, modelId: model.id }))+ const toolModels = models+ .filter((model) => model.type === AIProviderModelType.TEXT)+ .filter((model) => callsTools({ provider: row.provider, modelId: model.id }))+ const offered = surface === 'chat' ? chatModels({ row, toolModels, lookup }) : toolModelsreturn offered.length === 0 ? [] : [{ providerConfigId: row.id, provider: row.provider, name: row.displayName, models: offered }]}-function chatModels({ row, textModels, lookup, callsTools }: { row: AIProviderSchema, textModels: AIProviderModel[], lookup: Lookup, callsTools: CallsTools }): AIProviderModel[] {+function chatModels({ row, toolModels, lookup }: { row: AIProviderSchema, toolModels: AIProviderModel[], lookup: Lookup }): AIProviderModel[] {const curated = aiProviderUtils.getCuratedChatModels({ provider: row.provider })if (isNil(curated) || !isNil(aiKeyScope.manualModelIdsOf({ config: row.config }))) {- return textModels.filter((model) => callsTools({ provider: row.provider, modelId: model.id }))+ return toolModels}- return curated- .filter((model) => aiKeyScope.scopeAllows({ modelScope: row.modelScope, modelIds: row.modelIds, modelId: model.id }))- .map((model) => textModels.find((listed) => listed.id === model.id) ?? {- id: model.id,- name: model.label,- type: AIProviderModelType.TEXT,- ...spreadIfDefined('metadata', lookup({ provider: row.provider, modelId: model.id })),- })+ const runnable = aiProviderUtils.runnableChatModelIds({ provider: row.provider })+ return toolModels.filter((model) => runnable.includes(model.id) || lookup({ provider: row.provider, modelId: model.id })?.supportsToolCalling === true)}function modelChoiceOf({ key, modelId }: { key: ModelOptionsKey, modelId: string }): ModelChoice {@@ -143,4 +197,15 @@ type DefaultChoiceParams = {credits: ModelOptionsCredits | nullkeys: ModelOptionsKey[]chatKeyId: string | undefined+ platformDefault?: ModelChoice | null+ movedTiers?: Record<string, string>+}++type BuildOptionsParams = {+ keys: ProjectKeyModels[]+ tiersForRun: TierForRun[]+ movedTiers: Record<string, string>+ configuration: PlatformConfiguration+ catalog: Awaited<ReturnType<typeof modelCatalog.load>>+ surface: ModelOptionsSurface}diff --git a/packages/server/api/src/app/ai/ai-provider-controller.ts b/packages/server/api/src/app/ai/ai-provider-controller.tsindex 54f6d98f9ef..22003af4f66 100644--- a/packages/server/api/src/app/ai/ai-provider-controller.ts+++ b/packages/server/api/src/app/ai/ai-provider-controller.ts@@ -44,6 +44,13 @@ export const aiProviderController: FastifyPluginAsyncZod = async (app) => {tierId: request.query.tierId,})})+ app.get('/model-options/platform', ListPlatformModelOptions, async (request) => {+ return aiModelOptionsService(app.log).listForPlatform({+ platformId: request.principal.platform.id,+ surface: request.query.surface,+ platformDefault: null,+ })+ })app.get('/:provider/models', ListModels, async (request) => {return aiProviderService(app.log).listModels({platformId: request.principal.platform.id,@@ -158,6 +165,20 @@ const ListModelOptions = {},}+const ListPlatformModelOptions = {+ config: {+ security: securityAccess.platformAdminOnly([PrincipalType.USER]),+ },+ schema: {+ querystring: z.object({+ surface: ModelOptionsSurface,+ }),+ response: {+ [StatusCodes.OK]: ModelOptions,+ },+ },+}+const ListModels = {config: {security: securityAccess.project([PrincipalType.USER, PrincipalType.ENGINE], undefined, { type: ProjectResourceType.QUERY }),diff --git a/packages/server/api/src/app/ai/ai-provider-service.ts b/packages/server/api/src/app/ai/ai-provider-service.tsindex 909aa55a43b..b00dcc05180 100644--- a/packages/server/api/src/app/ai/ai-provider-service.ts+++ b/packages/server/api/src/app/ai/ai-provider-service.ts@@ -3,7 +3,7 @@ import { modelCatalog, modelTierCatalog } from '@activepieces/server-utils'import { ActivePiecesProviderAuthConfig, AI_PROVIDER_ENTITY_TYPES, AIProviderAuthConfig, AIProviderConfig, aiProviderCredentials, AIProviderModel, AIProviderModelType, AiProviderProjectScope, AiProviderToolConfig, aiProviderUtils, AIProviderWithoutSensitiveData, AiToolCapability, AiToolProvider, CreateAIProviderRequest, GetProviderConfigResponse, ProjectAIProvider, UpdateAIProviderRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import cron from 'node-cron'-import { EntityManager, FindOptionsWhere } from 'typeorm'+import { EntityManager, FindOptionsWhere, Not } from 'typeorm'import { repoFactory } from '../core/db/repo-factory'import { transaction } from '../core/db/transaction'import { getAiProviderConfirmKey, getManagedAiProviderKeyLockKey } from '../database/redis/keys'@@ -11,6 +11,7 @@ import { distributedLock, distributedStore } from '../database/redis-connectionsimport { openRouterApi } from '../ee/platform/platform-plan/openrouter/openrouter-api'import { flagService } from '../flags/flag.service'import { EncryptedObject, encryptUtils } from '../helper/encryption'+import { platformConfigurationService } from '../platform/platform-configuration.service'import { platformService } from '../platform/platform.service'import { aiKeyScope, ProviderScope } from './ai-key-scope'import { AIProviderEntity, AIProviderSchema } from './ai-provider-entity'@@ -75,18 +76,17 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({async listKeysForProject({ platformId, projectId }: { platformId: PlatformId, projectId: string }): Promise<ProjectKeyModels[]> {const rows = await listVisibleRows({ platformId, log })const scope: ProviderScope = { type: 'project', projectId }- const ranked = rankRows({ rows: rows.filter((row) => aiKeyScope.rowAllowsScope({ row, scope })), scope })- const chatRowId = pickChatRow(ranked)?.id- return Promise.all(ranked.map(async (row) => {- const { data } = row.provider === AIProviderName.ACTIVEPIECES- ? { data: null }- : await tryCatch(() => fetchModels({ aiProvider: row, platformId, log }))- return {- row,- isChatKey: row.id === chatRowId,- models: isNil(data) ? null : data.filter((model) => aiKeyScope.scopeAllows({ modelScope: row.modelScope, modelIds: row.modelIds, modelId: model.id })),- }- }))+ return withModels({ ranked: rankRows({ rows: rows.filter((row) => aiKeyScope.rowAllowsScope({ row, scope })), scope }), platformId, log })+ },++ async listKeysForPlatform({ platformId }: { platformId: PlatformId }): Promise<ProjectKeyModels[]> {+ const rows = await listVisibleRows({ platformId, log })+ return withModels({ ranked: rankRows({ rows, scope: { type: 'platform' } }), platformId, log })+ },++ async markDefaultKey({ manager, platformId, configId }: { manager: EntityManager, platformId: PlatformId, configId: string }): Promise<void> {+ await manager.update(AIProviderEntity, { platformId }, { enabledForChat: false })+ await manager.update(AIProviderEntity, { platformId, id: configId }, { enabledForChat: true })},async listModelsForConfig({ platformId, configId }: { platformId: PlatformId, configId: string }): Promise<AIProviderModel[]> {@@ -118,22 +118,33 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({}await assertDisplayNameIsFree({ platformId, provider: request.provider, displayName: request.displayName })await this.validateProviderCredentials(request.provider, request.auth, request.config)- const saved = await aiProviderRepo().save({- id: apId(),- auth: await encryptUtils.encryptObject(request.auth),- config: request.config,- provider: request.provider,- displayName: request.displayName,- platformId,- modelScope: 'all',- modelIds: [],- projectScope: 'all',- projectIds: [],- status: 'active',- statusReason: null,- statusUpdated: new Date().toISOString(),+ const auth = await encryptUtils.encryptObject(request.auth)+ const { saved, isFirstKey } = await transaction(async (manager) => {+ await platformModelTierService.lockPlatform({ manager, platformId })+ const hasDefaultChatModel = !isNil((await platformConfigurationService(log).getOrCreateForPlatform({ platformId })).defaultChatModel)+ const firstKey = !hasDefaultChatModel && !await aiProviderRepo(manager).existsBy({ platformId, provider: Not(AIProviderName.ACTIVEPIECES) })+ if (firstKey) {+ await aiProviderRepo(manager).update({ platformId }, { enabledForChat: false })+ }+ const row = await aiProviderRepo(manager).save({+ id: apId(),+ enabledForChat: firstKey,+ auth,+ config: request.config,+ provider: request.provider,+ displayName: request.displayName,+ platformId,+ modelScope: 'all',+ modelIds: [],+ projectScope: 'all',+ projectIds: [],+ status: 'active',+ statusReason: null,+ statusUpdated: new Date().toISOString(),+ })+ return { saved: row, isFirstKey: firstKey }})- return toConfigResponse({ row: saved, enabledForChat: false })+ return toConfigResponse({ row: saved, enabledForChat: isFirstKey })},async update(platformId: PlatformId, providerId: string, request: UpdateAIProviderRequest): Promise<void> {const aiProvider = await aiProviderRepo().findOneBy({@@ -233,6 +244,11 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({return { ...aiProviderCredentials({ provider: chatProvider.provider, auth, config: chatProvider.config }), configId: chatProvider.id, platformId, modelScope: chatProvider.modelScope, modelIds: chatProvider.modelIds }},+ async findCreditsConfig({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): Promise<GetProviderConfigResponse | null> {+ const row = (await listVisibleRows({ platformId, log })).find((candidate) => candidate.provider === AIProviderName.ACTIVEPIECES)+ return isNil(row) ? null : this.findKeyConfig({ platformId, configId: row.id, scope })+ },+async findKeyConfig({ platformId, configId, scope }: { platformId: PlatformId, configId: string, scope: ProviderScope }): Promise<GetProviderConfigResponse | null> {const row = await aiProviderRepo().findOneBy({ platformId, id: configId })if (isNil(row) || !aiKeyScope.rowAllowsScope({ row, scope })) {@@ -264,6 +280,10 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({async delete(platformId: PlatformId, providerId: string): Promise<void> {const deleted = await transaction(async (manager) => {await platformModelTierService.removeKeyFromTiers({ manager, platformId, configId: providerId })+ await manager.query(+ 'UPDATE "platform_configuration" SET "defaultChatModel" = NULL WHERE "platformId" = $1 AND "defaultChatModel"->>\'providerConfigId\' = $2',+ [platformId, providerId],+ )const row = await deleteRowForUpdate({ manager, where: { platformId, id: providerId } })await aiUsageHooks.get(log).unpinConversationsFromKey({ manager, platformId, configId: providerId, key: null })return row@@ -421,6 +441,20 @@ const PROJECT_SCOPE_SPECIFICITY: Record<AiProviderProjectScope, number> = {all: 2,}+async function withModels({ ranked, platformId, log }: { ranked: AIProviderSchema[], platformId: PlatformId, log: FastifyBaseLogger }): Promise<ProjectKeyModels[]> {+ const chatRowId = pickChatRow(ranked)?.id+ return Promise.all(ranked.map(async (row) => {+ const { data } = row.provider === AIProviderName.ACTIVEPIECES+ ? { data: null }+ : await tryCatch(() => fetchModels({ aiProvider: row, platformId, log }))+ return {+ row,+ isChatKey: row.id === chatRowId,+ models: isNil(data) ? null : data.filter((model) => aiKeyScope.scopeAllows({ modelScope: row.modelScope, modelIds: row.modelIds, modelId: model.id })),+ }+ }))+}+function rankRows({ rows, scope }: { rows: AIProviderSchema[], scope: ProviderScope }): AIProviderSchema[] {const order = scope.type === 'platform' ? PLATFORM_SCOPE_PREFERENCE : PROJECT_SCOPE_SPECIFICITYreturn [...rows].sort((a, b) => {@@ -520,7 +554,7 @@ async function assertCapabilitiesKeepKey({ manager, platformId, providerId, requreturn []}const losesProjects = next.projectScope !== 'all'- const losesModel = !isNil(choice.data.modelId) && !aiKeyScope.keyOffersModel({ key: next, modelId: choice.data.modelId })+ const losesModel = toolConfig.capability !== AiToolCapability.EMBEDDINGS && !isNil(choice.data.modelId) && !aiKeyScope.keyOffersModel({ key: next, modelId: choice.data.modelId })return losesProjects || losesModel ? [CAPABILITY_LABELS[toolConfig.capability]] : []})if (broken.length > 0) {diff --git a/packages/server/api/src/app/ai/ai-tool-config-service.ts b/packages/server/api/src/app/ai/ai-tool-config-service.tsindex 8788c0fa65c..c6994e0c972 100644--- a/packages/server/api/src/app/ai/ai-tool-config-service.ts+++ b/packages/server/api/src/app/ai/ai-tool-config-service.ts@@ -32,6 +32,7 @@ export const aiToolConfigService = (log: FastifyBaseLogger) => ({const encryptedAuth = await encryptUtils.encryptObject(request.auth ?? {})await saveUnderPlatformLock({platformId,+ capability: request.capability,choice: request.provider === AiToolProvider.AI_PROVIDER ? request.config : null,write: (manager) => aiToolConfigRepo(manager).save({id: existing?.id ?? apId(),@@ -65,6 +66,7 @@ export const aiToolConfigService = (log: FastifyBaseLogger) => ({const encryptedAuth = !isNil(request.auth) ? await encryptUtils.encryptObject(request.auth) : undefinedawait saveUnderPlatformLock({platformId,+ capability: config.capability,choice: provider === AiToolProvider.AI_PROVIDER ? request.config ?? config.config : null,write: (manager) => aiToolConfigRepo(manager).update(id, {...spreadIfDefined('provider', request.provider),@@ -114,14 +116,14 @@ export const aiToolConfigService = (log: FastifyBaseLogger) => ({},})-async function saveUnderPlatformLock({ platformId, choice, write }: { platformId: PlatformId, choice: AiToolProviderConfig | null | undefined, write: (manager: EntityManager) => Promise<unknown> }): Promise<void> {+async function saveUnderPlatformLock({ platformId, capability, choice, write }: { platformId: PlatformId, capability: AiToolCapability, choice: AiToolProviderConfig | null | undefined, write: (manager: EntityManager) => Promise<unknown> }): Promise<void> {await transaction(async (manager) => {await platformModelTierService.lockPlatform({ manager, platformId })const parsed = AiProviderToolConfig.safeParse(choice)if (parsed.success) {const key = await manager.getRepository(AIProviderEntity).findOneBy({ platformId, id: parsed.data.aiProviderId })const modelId = parsed.data.modelId- const dropsModel = !isNil(key) && !isNil(modelId) && !aiKeyScope.keyOffersModel({ key, modelId })+ const dropsModel = capability !== AiToolCapability.EMBEDDINGS && !isNil(key) && !isNil(modelId) && !aiKeyScope.keyOffersModel({ key, modelId })if (isNil(key) || key.projectScope !== 'all' || dropsModel) {throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'This AI provider cannot be used for this capability' } })}@@ -151,7 +153,8 @@ async function providerCovers({ platformId, capability, aiProvider, modelId, logreturn aiUtils.supportsWebSearch(aiProvider.provider)}if (capability === AiToolCapability.EMBEDDINGS) {- return AI_PROVIDER_CAPABILITIES[aiProvider.provider].supportsEmbedding+ const embeddingModels = AI_PROVIDER_CAPABILITIES[aiProvider.provider].embeddingModels+ return embeddingModels.length > 0 && (isNil(modelId) || embeddingModels.includes(modelId))}if (capability !== AiToolCapability.IMAGE_GENERATION || isNil(modelId)) {return falsediff --git a/packages/server/api/src/app/ai/platform-model-tier-service.ts b/packages/server/api/src/app/ai/platform-model-tier-service.tsindex 29f4a1bae47..0aec9792aa1 100644--- a/packages/server/api/src/app/ai/platform-model-tier-service.ts+++ b/packages/server/api/src/app/ai/platform-model-tier-service.ts@@ -35,22 +35,26 @@ export const platformModelTierService = {return listLive({ platformId })},- async listForPicker({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): Promise<TierForRun[]> {+ async listForPicker({ platformId, scope, anyProject = false }: { platformId: PlatformId, scope: ProviderScope, anyProject?: boolean }): Promise<TierForRun[]> {const tiers = await listLive({ platformId })const configIds = unique(tiers.flatMap((tier) => tier.entries.map((entry) => entry.configId)))const keys = configIds.length === 0 ? [] : await aiProviderRepo().findBy({ platformId, id: In(configIds) })const keyById = new Map(keys.map((key) => [key.id, key]))return tiers- .filter((tier) => mainRunsIn({ tier, keyById, scope }))- .map((tier) => ({ tier, entries: entriesThatRun({ tier, keyById, scope }) }))+ .filter((tier) => mainRunsIn({ tier, keyById, scope, anyProject }))+ .map((tier) => ({ tier, entries: entriesThatRun({ tier, keyById, scope, anyProject }) }))},- async movedTiers({ platformId, tierId }: { platformId: PlatformId, tierId: string | undefined }): Promise<Record<string, string>> {- if (isNil(tierId)) {+ async movedTiers({ platformId, tierIds }: { platformId: PlatformId, tierIds: (string | undefined)[] }): Promise<Record<string, string>> {+ const ids = tierIds.filter((id): id is string => !isNil(id))+ if (ids.length === 0) {return {}}- const live = (await followReplacementsInBulk({ platformId, ids: [tierId] })).get(tierId)- return isNil(live) || live.id === tierId ? {} : { [tierId]: live.id }+ const live = await followReplacementsInBulk({ platformId, ids })+ return Object.fromEntries(ids.flatMap((id) => {+ const replacement = live.get(id)+ return isNil(replacement) || replacement.id === id ? [] : [[id, replacement.id]]+ }))},async create({ platformId, request }: { platformId: PlatformId, request: CreatePlatformModelTierRequest }): Promise<PlatformModelTier> {@@ -106,6 +110,7 @@ export const platformModelTierService = {...spreadIfDefined('isDefault', request.isDefault),...spreadIfDefined('isFast', request.isFast),})+ await syncDefaultChatKey({ manager, platformId })return getLiveOrThrow({ manager, platformId, id })}))},@@ -147,6 +152,7 @@ export const platformModelTierService = {await tierRepo(manager).update({ platformId, id }, { isDefault: false, isFast: false })await tierRepo(manager).softDelete({ platformId, id })await platformConfigurationRepo(manager).update({ platformId }, { aiSpecificModelsVisible: true })+ await clearDefaultChatTier({ manager, platformId, tierIds: [id] })return}await getLiveOrThrow({ manager, platformId, id: replacedBy })@@ -162,6 +168,7 @@ export const platformModelTierService = {...(tier.isFast ? { isFast: true } : {}),})}+ await syncDefaultChatKey({ manager, platformId, replaced: { from: [id], to: replacedBy } })})},@@ -192,6 +199,7 @@ export const platformModelTierService = {)}if (emptied.length === 0) {+ await syncDefaultChatKey({ manager, platformId })return}const emptiedIds = emptied.map((tier) => tier.id)@@ -200,6 +208,7 @@ export const platformModelTierService = {const replacement = (await listLive({ platformId, manager }))[0]if (isNil(replacement)) {await platformConfigurationRepo(manager).update({ platformId }, { aiSpecificModelsVisible: true })+ await clearDefaultChatTier({ manager, platformId, tierIds: emptiedIds })return}await manager.query(@@ -210,6 +219,7 @@ export const platformModelTierService = {...(emptied.some((tier) => tier.isDefault) ? { isDefault: true } : {}),...(emptied.some((tier) => tier.isFast) ? { isFast: true } : {}),})+ await syncDefaultChatKey({ manager, platformId, replaced: { from: emptiedIds, to: replacement.id } })},async getDefaultForRun({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): Promise<TierForRun | null> {@@ -257,6 +267,11 @@ export const platformModelTierService = {}))},+ async mainKeyIdOf({ manager, platformId, tierId }: { manager: EntityManager, platformId: PlatformId, tierId: string }): Promise<string | null> {+ const tier = await tierRepo(manager).findOneBy({ platformId, id: tierId })+ return tier?.entries[0]?.configId ?? null+ },+async lockPlatform({ manager, platformId }: { manager: EntityManager, platformId: PlatformId }): Promise<void> {await lockPlatform({ manager, platformId })},@@ -287,22 +302,47 @@ async function lockPlatform({ manager, platformId }: { manager: EntityManager, p}}-function mainRunsIn({ tier, keyById, scope }: { tier: PlatformModelTier, keyById: Map<string, AIProviderSchema>, scope: ProviderScope }): boolean {+async function clearDefaultChatTier({ manager, platformId, tierIds }: { manager: EntityManager, platformId: PlatformId, tierIds: string[] }): Promise<void> {+ await manager.query(+ 'UPDATE "platform_configuration" SET "defaultChatModel" = NULL WHERE "platformId" = $1 AND "defaultChatModel"->>\'tierId\' = ANY($2)',+ [platformId, tierIds],+ )+}++async function syncDefaultChatKey({ manager, platformId, replaced }: { manager: EntityManager, platformId: PlatformId, replaced?: { from: string[], to: string } }): Promise<void> {+ const configuration = await platformConfigurationRepo(manager).findOneBy({ platformId })+ const choice = configuration?.defaultChatModel+ if (isNil(choice) || choice.type !== 'tier') {+ return+ }+ const tierId = !isNil(replaced) && replaced.from.includes(choice.tierId) ? replaced.to : choice.tierId+ if (tierId !== choice.tierId) {+ await platformConfigurationRepo(manager).update({ platformId }, { defaultChatModel: { type: 'tier', tierId } })+ }+ const mainKeyId = (await tierRepo(manager).findOneBy({ platformId, id: tierId }))?.entries[0]?.configId+ if (isNil(mainKeyId)) {+ return+ }+ await aiProviderRepo(manager).update({ platformId }, { enabledForChat: false })+ await aiProviderRepo(manager).update({ platformId, id: mainKeyId }, { enabledForChat: true })+}++function mainRunsIn({ tier, keyById, scope, anyProject = false }: { tier: PlatformModelTier, keyById: Map<string, AIProviderSchema>, scope: ProviderScope, anyProject?: boolean }): boolean {const main = tier.entries[0]- return !isNil(main) && entryRunsIn({ entry: main, key: keyById.get(main.configId), scope })+ return !isNil(main) && entryRunsIn({ entry: main, key: keyById.get(main.configId), scope, anyProject })}-function entryRunsIn({ entry, key, scope }: { entry: PlatformModelTierEntry, key: AIProviderSchema | undefined, scope: ProviderScope }): boolean {+function entryRunsIn({ entry, key, scope, anyProject = false }: { entry: PlatformModelTierEntry, key: AIProviderSchema | undefined, scope: ProviderScope, anyProject?: boolean }): boolean {return !isNil(key)&& key.provider !== AIProviderName.ACTIVEPIECES&& aiKeyScope.scopeAllows({ modelScope: key.modelScope, modelIds: key.modelIds, modelId: entry.modelId })- && aiKeyScope.rowAllowsScope({ row: key, scope })+ && (anyProject || aiKeyScope.rowAllowsScope({ row: key, scope }))}-function entriesThatRun({ tier, keyById, scope }: { tier: PlatformModelTier, keyById: Map<string, AIProviderSchema>, scope: ProviderScope }): TierForRun['entries'] {+function entriesThatRun({ tier, keyById, scope, anyProject = false }: { tier: PlatformModelTier, keyById: Map<string, AIProviderSchema>, scope: ProviderScope, anyProject?: boolean }): TierForRun['entries'] {return tier.entries.flatMap((entry) => {const key = keyById.get(entry.configId)- return isNil(key) || !entryRunsIn({ entry, key, scope }) ? [] : [{ modelId: entry.modelId, key }]+ return isNil(key) || !entryRunsIn({ entry, key, scope, anyProject }) ? [] : [{ modelId: entry.modelId, key }]})}diff --git a/packages/server/api/src/app/database/migration/postgres/1875000000000-AddDefaultChatModelToPlatformConfiguration.ts b/packages/server/api/src/app/database/migration/postgres/1875000000000-AddDefaultChatModelToPlatformConfiguration.tsnew file mode 100644index 00000000000..07128ff5bce--- /dev/null+++ b/packages/server/api/src/app/database/migration/postgres/1875000000000-AddDefaultChatModelToPlatformConfiguration.ts@@ -0,0 +1,23 @@+import { QueryRunner } from 'typeorm'+import { Migration } from '../../migration'++export class AddDefaultChatModelToPlatformConfiguration1875000000000 implements Migration {+ name = 'AddDefaultChatModelToPlatformConfiguration1875000000000'+ breaking = false+ release = '0.93.0'+ transaction = true++ public async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`+ ALTER TABLE "platform_configuration"+ ADD COLUMN "defaultChatModel" jsonb+ `)+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`+ ALTER TABLE "platform_configuration"+ DROP COLUMN "defaultChatModel"+ `)+ }+}diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.tsindex 9055df91072..ba9feb847e7 100644--- a/packages/server/api/src/app/database/postgres-connection.ts+++ b/packages/server/api/src/app/database/postgres-connection.ts@@ -460,6 +460,7 @@ import { AddProviderConfigIdToAgentConversation1868000000000 } from './migrationimport { DropChatRolloutUserTable1870000000000 } from './migration/postgres/1870000000000-DropChatRolloutUserTable'import { AddBarrierChildAttribution1871000000000 } from './migration/postgres/1871000000000-AddBarrierChildAttribution'import { AddPieceTranslationTable1873000000000 } from './migration/postgres/1873000000000-AddPieceTranslationTable'+import { AddDefaultChatModelToPlatformConfiguration1875000000000 } from './migration/postgres/1875000000000-AddDefaultChatModelToPlatformConfiguration'import { AddAgentConversationProviderConfigIdIndex1869000000000 } from './migration/postgres/background/1869000000000-AddAgentConversationProviderConfigIdIndex'import { ReshapeFlowRunListIndexesForBarrierChildren1871000000000 } from './migration/postgres/background/1871000000000-ReshapeFlowRunListIndexesForBarrierChildren'import { BackfillPieceTranslation1874000000000 } from './migration/postgres/background/1874000000000-BackfillPieceTranslation'@@ -945,6 +946,7 @@ export const getMigrations = (): (new () => Migration)[] => {DropChatRolloutUserTable1870000000000,AddBarrierChildAttribution1871000000000,AddPieceTranslationTable1873000000000,+ AddDefaultChatModelToPlatformConfiguration1875000000000,]return migrations}diff --git a/packages/server/api/src/app/ee/agent/agent-chat-model.ts b/packages/server/api/src/app/ee/agent/agent-chat-model.tsindex ed8ccd274a7..90c56cd8b06 100644--- a/packages/server/api/src/app/ee/agent/agent-chat-model.ts+++ b/packages/server/api/src/app/ee/agent/agent-chat-model.ts@@ -1,12 +1,11 @@import { ActivepiecesError, AIProviderName, ErrorCode, isNil, tryCatch } from '@activepieces/core-utils'-import { AgentConversation, AI_PROVIDER_ENTITY_TYPES, GetProviderConfigResponse } from '@activepieces/shared'+import { AgentConversation, AI_PROVIDER_ENTITY_TYPES, aiProviderUtils, GetProviderConfigResponse } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { IsNull } from 'typeorm'import { aiKeyScope, ProviderScope } from '../../ai/ai-key-scope'import { aiModelOptionsService } from '../../ai/ai-model-options-service'import { AIProviderEntity, AIProviderSchema } from '../../ai/ai-provider-entity'import { aiProviderService } from '../../ai/ai-provider-service'-import { platformModelTierService } from '../../ai/platform-model-tier-service'import { transaction } from '../../core/db/transaction'import { AgentConversationEntity } from './agent-conversation-entity'import { agentHelpers } from './agent-helpers'@@ -15,19 +14,11 @@ import { agentModelTier } from './agent-model-tier'export const agentChatModel = (log: FastifyBaseLogger) => ({async defaultPick({ platformId, projectId }: { platformId: string, projectId: string }): Promise<ChatPick | null> {- const scope: ProviderScope = { type: 'project', projectId }- const defaultTier = await platformModelTierService.getDefaultForRun({ platformId, scope })- if (!isNil(defaultTier)) {- const { error } = await tryCatch(() => agentModelTier(log).assertUsable({ platformId, tierId: defaultTier.tier.id, scope }))- if (isNil(error)) {- return { modelTierId: defaultTier.tier.id, providerConfigId: null, modelName: null }- }- }- if (!isNil(await aiProviderService(log).getChatKey({ platformId, scope }))) {- return null- }const { defaultChoice } = await aiModelOptionsService(log).list({ platformId, projectId, surface: 'chat' })if (isNil(defaultChoice)) {+ if (!isNil(await aiProviderService(log).getChatKey({ platformId, scope: { type: 'project', projectId } }))) {+ return null+ }throw new ActivepiecesError({code: ErrorCode.ENTITY_NOT_FOUND,params: { entityId: platformId, entityType: AI_PROVIDER_ENTITY_TYPES.chatProvider },@@ -53,6 +44,9 @@ export const agentChatModel = (log: FastifyBaseLogger) => ({if (isNil(config) || isNil(modelId)) {throw unavailableError()}+ if (await keyNoLongerListsModel({ platformId, configId, provider: config.provider, modelId, scope, log })) {+ throw unavailableError()+ }return { config, modelId }},@@ -115,6 +109,14 @@ export const agentChatModel = (log: FastifyBaseLogger) => ({},})+async function keyNoLongerListsModel({ platformId, configId, provider, modelId, scope, log }: { platformId: string, configId: string, provider: AIProviderName, modelId: string, scope: ProviderScope, log: FastifyBaseLogger }): Promise<boolean> {+ if (provider === AIProviderName.ACTIVEPIECES || provider === AIProviderName.OPENROUTER) {+ return false+ }+ const { data: models } = await tryCatch(() => aiProviderService(log).listModels({ platformId, provider, scope, configId }))+ return !isNil(models) && !models.some((model) => model.id === modelId) && !aiProviderUtils.runnableChatModelIds({ provider }).includes(modelId)+}+function unavailableError(): ActivepiecesError {return new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: CHAT_MODEL_UNAVAILABLE_MESSAGE } })}diff --git a/packages/server/api/src/app/ee/agent/agent-model-resolution.ts b/packages/server/api/src/app/ee/agent/agent-model-resolution.tsindex 68df4abc08c..09e23b33ad8 100644--- a/packages/server/api/src/app/ee/agent/agent-model-resolution.ts+++ b/packages/server/api/src/app/ee/agent/agent-model-resolution.ts@@ -108,17 +108,10 @@ function resolvePinnedModelId({ provider, modelName, config, modelScope, modelIdif (!isNil(catalog) && !catalog.includes(modelName)) {return null}- if (isNil(catalog) && isRetiredCuratedModel({ provider, modelId: modelName })) {- return null- }const { data } = tryCatchSync(() => resolveNamedModelId({ provider, modelName, surface: 'chat', modelScope, modelIds, log }))return data ?? null}-function isRetiredCuratedModel({ provider, modelId }: { provider: AIProviderName, modelId: string }): boolean {- return !isNil(aiProviderUtils.getCuratedChatModels({ provider })) && !aiProviderUtils.runnableChatModelIds({ provider }).includes(modelId)-}-function resolveModelIdForProvider({ provider, selectedModel, surface, config, modelScope, modelIds }: { provider: AIProviderName, selectedModel: string | null, surface: ModelTierSurface, config?: AiProviderCredentials['config'], modelScope?: AiProviderModelScope, modelIds?: string[] }): string {const catalog = manualTextModelCatalog({ config })if (!isNil(catalog)) {diff --git a/packages/server/api/src/app/ee/agent/agent-service.ts b/packages/server/api/src/app/ee/agent/agent-service.tsindex 10bb0f10575..dcf6679a080 100644--- a/packages/server/api/src/app/ee/agent/agent-service.ts+++ b/packages/server/api/src/app/ee/agent/agent-service.ts@@ -1,9 +1,12 @@import { createHash } from 'node:crypto'import { AgentToolType, McpAuthType } from '@activepieces/core-piece-types'-import { ActivepiecesError, AIProviderName, apId, ApId, connectionTemplate, Cursor, ErrorCode, isNil, omit, Permission, PlatformId, ProjectId, sanitizeObjectForPostgresql, SeekPage, unique, UserId } from '@activepieces/core-utils'-import { Agent, AgentConfig, AgentFlowTool, AgentKnowledgeBaseTool, AgentListSort, AgentMoveLoss, AgentMoveLossKind, AgentMovePreview, AgentRunSource, AgentSummary, agentUtils, AgentVisibility, CreateAgentRequest, DefaultProjectRole, Project, ProjectType, UpdateAgentRequest } from '@activepieces/shared'+import { ActivepiecesError, AIProviderName, apId, ApId, connectionTemplate, Cursor, ErrorCode, isNil, omit, Permission, PlatformId, ProjectId, sanitizeObjectForPostgresql, SeekPage, tryCatch, unique, UserId } from '@activepieces/core-utils'+import { Agent, AgentConfig, AgentFlowTool, AgentKnowledgeBaseTool, AgentListSort, AgentMoveLoss, AgentMoveLossKind, AgentMovePreview, AgentRunSource, AgentSummary, agentUtils, AgentVisibility, aiProviderUtils, CreateAgentRequest, DefaultProjectRole, Project, ProjectType, UpdateAgentRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { Brackets, EntityManager, In, SelectQueryBuilder } from 'typeorm'+import { aiKeyScope } from '../../ai/ai-key-scope'+import { aiModelOptionsService, aiModelOptionsUtils } from '../../ai/ai-model-options-service'+import { AIProviderSchema } from '../../ai/ai-provider-entity'import { aiProviderService } from '../../ai/ai-provider-service'import { appConnectionService } from '../../app-connection/app-connection-service/app-connection-service'import { repoFactory } from '../../core/db/repo-factory'@@ -16,6 +19,7 @@ import { paginationHelper } from '../../helper/pagination/pagination-utils'import { Order, OrderByConfig } from '../../helper/pagination/paginator'import { knowledgeBaseService } from '../../knowledge-base/knowledge-base.service'import { resolvePermissionChecker } from '../../mcp/mcp-permissions'+import { platformConfigurationService } from '../../platform/platform-configuration.service'import { projectService } from '../../project/project-service'import { userService } from '../../user/user-service'import { projectMemberService } from '../projects/project-members/project-member.service'@@ -446,6 +450,16 @@ async function withDefaultModel({ draft, platformId, projectId, log }: {if (!isNil(draft.modelName) || !isNil(draft.modelTierId)) {return draft}+ const platformDefault = (await platformConfigurationService(log).getOrCreateForPlatform({ platformId })).defaultChatModel+ if (!isNil(platformDefault)) {+ const { data: options } = await tryCatch(() => aiModelOptionsService(log).list({ platformId, projectId, surface: 'agent' }))+ const usable = isNil(options) ? null : aiModelOptionsUtils.usableChoice({ choice: platformDefault, tiers: options.tiers, credits: options.credits ?? null, keys: options.keys, movedTiers: options.movedTiers })+ if (!isNil(usable)) {+ return usable.type === 'tier'+ ? { ...draft, modelTierId: usable.tierId, provider: null, providerConfigId: null, modelName: null }+ : { ...draft, provider: usable.provider, providerConfigId: usable.providerConfigId, modelName: usable.modelId, modelTierId: null }+ }+ }const chatKey = await aiProviderService(log).getChatKey({ platformId, scope: { type: 'project', projectId } })if (isNil(chatKey)) {return draft@@ -453,13 +467,21 @@ async function withDefaultModel({ draft, platformId, projectId, log }: {const { provider, id: providerConfigId } = chatKeyconst modelName = provider === AIProviderName.ACTIVEPIECES? agentHelpers.resolveTier({ tierId: null, surface: 'flow' }).id- : agentHelpers.defaultModelIdForProvider({ provider, surface: 'flow', config: chatKey.config, modelScope: chatKey.modelScope, modelIds: chatKey.modelIds })+ : firstChatModelId({ key: chatKey }) ?? agentHelpers.defaultModelIdForProvider({ provider, surface: 'flow', config: chatKey.config, modelScope: chatKey.modelScope, modelIds: chatKey.modelIds })if (isNil(modelName)) {return { ...draft, provider, providerConfigId }}return { ...draft, provider, providerConfigId, modelName }}+function firstChatModelId({ key }: { key: AIProviderSchema }): string | undefined {+ if (!isNil(aiKeyScope.manualModelIdsOf({ config: key.config }))) {+ return undefined+ }+ return aiProviderUtils.runnableChatModelIds({ provider: key.provider })+ .find((modelId) => aiKeyScope.scopeAllows({ modelScope: key.modelScope, modelIds: key.modelIds, modelId }))+}+async function withPinnedKey({ draft, platformId, projectId, log }: {draft: AgentConfigplatformId: PlatformIddiff --git a/packages/server/api/src/app/knowledge-base/knowledge-base.controller.ts b/packages/server/api/src/app/knowledge-base/knowledge-base.controller.tsindex f906007dbfd..8781f9daeb8 100644--- a/packages/server/api/src/app/knowledge-base/knowledge-base.controller.ts+++ b/packages/server/api/src/app/knowledge-base/knowledge-base.controller.ts@@ -1,6 +1,6 @@import { ActivepiecesError, ApMultipartFile, ErrorCode, isMultipartFile, Permission } from '@activepieces/core-utils'import { EMBEDDING_DIMENSIONS } from '@activepieces/server-utils'-import { PrincipalType, SERVICE_KEY_SECURITY_OPENAPI } from '@activepieces/shared'+import { KnowledgeBaseEmbeddingSource, PrincipalType, SERVICE_KEY_SECURITY_OPENAPI } from '@activepieces/shared'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'import { z } from 'zod'@@ -55,6 +55,13 @@ export const knowledgeBaseController: FastifyPluginAsyncZod = async (fastify) =>})})+ fastify.get('/embedding-source', GetEmbeddingSourceRequest, async (request) => {+ return knowledgeBaseService(request.log).getEmbeddingSource({+ projectId: request.projectId,+ platformId: request.principal.platform.id,+ })+ })+fastify.delete('/:id', DeleteKnowledgeBaseFileRequest, async (request, reply) => {await knowledgeBaseService(request.log).deleteFile({projectId: request.projectId,@@ -170,6 +177,25 @@ const ListKnowledgeBaseFilesRequest = {},}+const GetEmbeddingSourceRequest = {+ config: {+ security: securityAccess.project(KB_PRINCIPALS, Permission.READ_KNOWLEDGE_BASE, {+ type: ProjectResourceType.QUERY,+ }),+ },+ schema: {+ tags: ['knowledge-base'],+ security: [SERVICE_KEY_SECURITY_OPENAPI],+ description: 'The AI provider and model that embed this project\'s knowledge base files, or null when none can',+ querystring: z.object({+ projectId: z.string(),+ }),+ response: {+ [StatusCodes.OK]: KnowledgeBaseEmbeddingSource,+ },+ },+}+const DeleteKnowledgeBaseFileRequest = {config: {security: securityAccess.project(KB_PRINCIPALS, Permission.WRITE_KNOWLEDGE_BASE, {diff --git a/packages/server/api/src/app/knowledge-base/knowledge-base.service.ts b/packages/server/api/src/app/knowledge-base/knowledge-base.service.tsindex 456b050ef7c..8fb27b81e4b 100644--- a/packages/server/api/src/app/knowledge-base/knowledge-base.service.ts+++ b/packages/server/api/src/app/knowledge-base/knowledge-base.service.ts@@ -1,6 +1,6 @@import { ActivepiecesAiBilling, ActivepiecesAiConsumerSource, ActivepiecesError, apId, ErrorCode, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'import { aiUtils } from '@activepieces/server-utils'-import { FileCompression, FileType, KnowledgeBaseFile } from '@activepieces/shared'+import { AI_PROVIDER_CAPABILITIES, FileCompression, FileType, GetProviderConfigResponse, KnowledgeBaseEmbeddingSource, KnowledgeBaseFile } from '@activepieces/shared'import { SharedV3ProviderOptions } from '@ai-sdk/provider'import { EmbeddingModel, embedMany } from 'ai'import { parse as parseCsv } from 'csv-parse/sync'@@ -157,17 +157,38 @@ export const knowledgeBaseService = (log: FastifyBaseLogger) => ({},async embeddingModelFor({ platformId, projectId, billing }: { platformId: string, projectId: string, billing: ActivepiecesAiBilling }): Promise<{ model: EmbeddingModel, providerOptions: SharedV3ProviderOptions }> {- const scope = { type: 'project' as const, projectId }- const choice = (await aiToolConfigService(log).getProviderChoices({ platformId })).embeddings- const chosen = isNil(choice) ? null : await aiProviderService(log).findKeyConfig({ platformId, configId: choice.aiProviderId, scope })- const provider = chosen ?? await aiProviderService(log).getChatProvider({ platformId, scope })- if (isNil(provider)) {+ const source = await this.embeddingSourceFor({ platformId, projectId })+ if (isNil(source)) {throw new ActivepiecesError({code: ErrorCode.VALIDATION,params: { message: KNOWLEDGE_BASE_NEEDS_AI_PROVIDER },})}- return aiUtils.createEmbeddingModel({ credentials: provider, platformId, providerConfigId: provider.configId, billing })+ const { credentials, modelId } = source+ return aiUtils.createEmbeddingModel({ credentials, modelId, platformId, providerConfigId: credentials.configId, billing })+ },++ async embeddingSourceFor({ platformId, projectId }: { platformId: string, projectId: string }): Promise<{ credentials: GetProviderConfigResponse, modelId: string } | null> {+ const scope = { type: 'project' as const, projectId }+ const choice = (await aiToolConfigService(log).getProviderChoices({ platformId })).embeddings+ const chosen = isNil(choice) ? null : await aiProviderService(log).findKeyConfig({ platformId, configId: choice.aiProviderId, scope })+ if (!isNil(chosen)) {+ const pickedModel = choice?.modelId ?? AI_PROVIDER_CAPABILITIES[chosen.provider].defaultEmbeddingModel+ return isNil(pickedModel) ? null : { credentials: chosen, modelId: pickedModel }+ }+ const defaultKey = await aiProviderService(log).getChatProvider({ platformId, scope })+ const defaultKeyModel = isNil(defaultKey) ? undefined : AI_PROVIDER_CAPABILITIES[defaultKey.provider].defaultEmbeddingModel+ if (!isNil(defaultKey) && !isNil(defaultKeyModel)) {+ return { credentials: defaultKey, modelId: defaultKeyModel }+ }+ const credits = await aiProviderService(log).findCreditsConfig({ platformId, scope })+ const creditsModel = isNil(credits) ? undefined : AI_PROVIDER_CAPABILITIES[credits.provider].defaultEmbeddingModel+ return isNil(credits) || isNil(creditsModel) ? null : { credentials: credits, modelId: creditsModel }+ },++ async getEmbeddingSource({ platformId, projectId }: { platformId: string, projectId: string }): Promise<KnowledgeBaseEmbeddingSource> {+ const source = await this.embeddingSourceFor({ platformId, projectId })+ return { provider: source?.credentials.provider ?? null, modelId: source?.modelId ?? null }},embedFnOf(params: { model: EmbeddingModel, providerOptions: SharedV3ProviderOptions }): EmbedFn {diff --git a/packages/server/api/src/app/platform/platform-configuration.controller.ts b/packages/server/api/src/app/platform/platform-configuration.controller.tsindex 51c6ba9a96d..31ce7b5f7a9 100644--- a/packages/server/api/src/app/platform/platform-configuration.controller.ts+++ b/packages/server/api/src/app/platform/platform-configuration.controller.ts@@ -18,6 +18,7 @@ export const platformConfigurationController: FastifyPluginAsyncZod = async (appisInfraSetupTelemetryEnabled: request.body.isInfraSetupTelemetryEnabled,maxBarrierSignals: request.body.maxBarrierSignals,aiSpecificModelsVisible: request.body.aiSpecificModelsVisible,+ defaultChatModel: request.body.defaultChatModel,})})}diff --git a/packages/server/api/src/app/platform/platform-configuration.entity.ts b/packages/server/api/src/app/platform/platform-configuration.entity.tsindex f964958c4e0..4ab9bc82fdf 100644--- a/packages/server/api/src/app/platform/platform-configuration.entity.ts+++ b/packages/server/api/src/app/platform/platform-configuration.entity.ts@@ -34,6 +34,10 @@ export const PlatformConfigurationEntity = new EntitySchema<PlatformConfigurationullable: false,default: true,},+ defaultChatModel: {+ type: 'jsonb',+ nullable: true,+ },},indices: [{diff --git a/packages/server/api/src/app/platform/platform-configuration.service.ts b/packages/server/api/src/app/platform/platform-configuration.service.tsindex 9163dc8a4c6..eeb28ad7deb 100644--- a/packages/server/api/src/app/platform/platform-configuration.service.ts+++ b/packages/server/api/src/app/platform/platform-configuration.service.ts@@ -1,7 +1,10 @@-import { apId, chunk, isEmpty, isNil, spreadIfNotUndefined } from '@activepieces/core-utils'-import { ApEdition, maxBarrierSignalsBounds, PlatformConfiguration, UpdatePlatformConfigurationRequestBody } from '@activepieces/shared'+import { ActivepiecesError, AIProviderName, apId, chunk, ErrorCode, isEmpty, isNil, spreadIfNotUndefined, tryCatch } from '@activepieces/core-utils'+import { ApEdition, maxBarrierSignalsBounds, ModelChoice, PlatformConfiguration, UpdatePlatformConfigurationRequestBody } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'-import { In } from 'typeorm'+import { EntityManager, In } from 'typeorm'+import { aiModelOptionsService, aiModelOptionsUtils } from '../ai/ai-model-options-service'+import { AIProviderEntity } from '../ai/ai-provider-entity'+import { aiProviderService } from '../ai/ai-provider-service'import { platformModelTierService } from '../ai/platform-model-tier-service'import { repoFactory } from '../core/db/repo-factory'import { transaction } from '../core/db/transaction'@@ -14,6 +17,7 @@ const platformConfigurationRepo = repoFactory(PlatformConfigurationEntity)const CREATE_LOCK_TIMEOUT_SECONDS = 60const CONFIGURATION_FILTER_BATCH_SIZE = 1_000+const DEFAULT_CHAT_MODEL_UNAVAILABLE = 'This model is not available for chat on this platform'export const platformConfigurationService = (log: FastifyBaseLogger) => ({async getOrCreateForPlatform({ platformId }: GetOrCreateParams): Promise<PlatformConfiguration> {@@ -93,19 +97,29 @@ export const platformConfigurationService = (log: FastifyBaseLogger) => ({return platformIds.filter((platformId) => !optedOutIds.has(platformId))},- async update({ platformId, isProductTelemetryEnabled, isInfraSetupTelemetryEnabled, maxBarrierSignals, aiSpecificModelsVisible }: UpdateParams): Promise<PlatformConfiguration> {+ async update({ platformId, isProductTelemetryEnabled, isInfraSetupTelemetryEnabled, maxBarrierSignals, aiSpecificModelsVisible, defaultChatModel }: UpdateParams): Promise<PlatformConfiguration> {await this.getOrCreateForPlatform({ platformId })+ const chatModel = isNil(defaultChatModel) ? defaultChatModel : await offeredChatModelOrThrow({ platformId, choice: defaultChatModel, log })const patch = {...spreadIfNotUndefined('isProductTelemetryEnabled', isProductTelemetryEnabled),...spreadIfNotUndefined('isInfraSetupTelemetryEnabled', isInfraSetupTelemetryEnabled),...spreadIfNotUndefined('maxBarrierSignals', maxBarrierSignals),...spreadIfNotUndefined('aiSpecificModelsVisible', aiSpecificModelsVisible),+ ...spreadIfNotUndefined('defaultChatModel', chatModel),}if (!isEmpty(patch)) {await transaction(async (manager) => {if (!isNil(aiSpecificModelsVisible)) {await platformModelTierService.assertSpecificModelsVisibilityAllowed({ manager, platformId, visible: aiSpecificModelsVisible })}+ if (!isNil(chatModel)) {+ await platformModelTierService.lockPlatform({ manager, platformId })+ const defaultKeyId = await defaultKeyIdOf({ manager, platformId, choice: chatModel })+ if (isNil(defaultKeyId)) {+ throw chatModelUnavailableError()+ }+ await aiProviderService(log).markDefaultKey({ manager, platformId, configId: defaultKeyId })+ }await platformConfigurationRepo(manager).update({ platformId }, patch)})}@@ -113,6 +127,30 @@ export const platformConfigurationService = (log: FastifyBaseLogger) => ({},})+async function offeredChatModelOrThrow({ platformId, choice, log }: { platformId: string, choice: ModelChoice, log: FastifyBaseLogger }): Promise<ModelChoice> {+ const { data: options } = await tryCatch(() => aiModelOptionsService(log).listForPlatform({ platformId, surface: 'chat', platformDefault: choice }))+ const usable = isNil(options) ? null : aiModelOptionsUtils.usableChoice({ choice, tiers: options.tiers, credits: options.credits ?? null, keys: options.keys, movedTiers: options.movedTiers })+ if (isNil(usable)) {+ throw chatModelUnavailableError()+ }+ return usable+}++async function defaultKeyIdOf({ manager, platformId, choice }: { manager: EntityManager, platformId: string, choice: ModelChoice }): Promise<string | null> {+ if (choice.type === 'tier') {+ return platformModelTierService.mainKeyIdOf({ manager, platformId, tierId: choice.tierId })+ }+ const where = choice.provider === AIProviderName.ACTIVEPIECES+ ? { platformId, provider: AIProviderName.ACTIVEPIECES }+ : { platformId, id: choice.providerConfigId }+ const key = await manager.getRepository(AIProviderEntity).findOneBy(where)+ return key?.id ?? null+}++function chatModelUnavailableError(): ActivepiecesError {+ return new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: DEFAULT_CHAT_MODEL_UNAVAILABLE } })+}+async function createInitialConfiguration({ platformId }: GetOrCreateParams): Promise<PlatformConfiguration> {const isProductTelemetryEnabled = system.getBoolean(AppSystemProp.TELEMETRY_ENABLED)const configuredMaxBarrierSignals = system.getNumber(AppSystemProp.MAX_BARRIER_SIGNALS)diff --git a/packages/server/api/test/integration/ce/ai-provider/ai-provider.test.ts b/packages/server/api/test/integration/ce/ai-provider/ai-provider.test.tsindex 4a1b27e1bc4..71df661b5b3 100644--- a/packages/server/api/test/integration/ce/ai-provider/ai-provider.test.ts+++ b/packages/server/api/test/integration/ce/ai-provider/ai-provider.test.ts@@ -56,6 +56,25 @@ describe('AI Providers API', () => {})})+ describe('the first key on a platform', () => {+ const createCustom = (displayName: string) => ctx.post('/v1/ai-providers', {+ provider: AIProviderName.CUSTOM,+ displayName,+ config: { baseUrl: 'https://api.example.com/v1', apiKeyHeader: 'Authorization', models: [] },+ auth: { apiKey: 'test-key' },+ })++ it('becomes the Default AI key, and later keys do not', async () => {+ const first = (await createCustom('First'))?.json()+ const second = (await createCustom('Second'))?.json()++ expect(first.enabledForChat).toBe(true)+ expect(second.enabledForChat).toBe(false)+ const rows = await db.findBy<{ id: string, enabledForChat: boolean }>('ai_provider', { platformId: ctx.platform.id })+ expect(rows.filter((row) => row.enabledForChat).map((row) => row.id)).toEqual([first.id])+ })+ })+describe('POST /v1/ai-providers/:id (update)', () => {it('should update defaultHeaders on an existing provider', async () => {const provider = await mockAndSaveAIProvider({diff --git a/packages/server/api/test/integration/ce/ai-provider/model-options.test.ts b/packages/server/api/test/integration/ce/ai-provider/model-options.test.tsindex dadd1be0cd3..9ae6b6dee5e 100644--- a/packages/server/api/test/integration/ce/ai-provider/model-options.test.ts+++ b/packages/server/api/test/integration/ce/ai-provider/model-options.test.ts@@ -4,6 +4,7 @@ import { AIProviderModelType, ModelOptions, PlatformModelTier } from '@activepieimport { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'import { vi } from 'vitest'+import { aiProviders } from '../../../../src/app/ai/providers'import { databaseConnection } from '../../../../src/app/database/database-connection'import { mockAndSaveAIProvider } from '../../../helpers/mocks'import { createTestContext, TestContext } from '../../../helpers/test-context'@@ -103,6 +104,70 @@ describe('GET /v1/ai-providers/model-options', () => {expect(options.keys.flatMap((key) => key.models.map((model) => model.id))).toEqual(['gemini-2.5-flash'])})+ it('offers chat known chat models and catalog-confirmed tool models in the key\'s own order', async () => {+ vi.spyOn(aiProviders[AIProviderName.OPENAI], 'listModels').mockResolvedValue([+ { id: 'gpt-4o', name: 'GPT-4o', type: AIProviderModelType.TEXT },+ { id: 'no-tools', name: 'No tools', type: AIProviderModelType.TEXT },+ { id: 'gpt-5.5', name: 'GPT-5.5', type: AIProviderModelType.TEXT },+ { id: 'gpt-4o-2024-05-13', name: 'Dated snapshot', type: AIProviderModelType.TEXT },+ ])+ vi.spyOn(modelCatalog, 'load').mockResolvedValue({+ lookup: (model) => model.modelId === 'no-tools' ? { supportsToolCalling: false } : model.modelId === 'gpt-4o' ? { supportsToolCalling: true } : undefined,+ })+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'OpenAI' })++ const chat = (await listOptions({ surface: 'chat' })).keys[0].models.map((model) => model.id)+ const agent = (await listOptions({ surface: 'agent' })).keys[0].models.map((model) => model.id)++ expect(chat).toEqual(['gpt-4o', 'gpt-5.5'])+ expect(agent).toEqual(['gpt-4o', 'gpt-5.5', 'gpt-4o-2024-05-13'])+ })++ it('starts new chats on the platform default chat model, and falls back where its key does not serve the project', async () => {+ const key = await seedKey({ name: 'Key', models: ['first', 'second'] })+ const away = await seedKey({ name: 'Away', models: ['elsewhere'], projectScope: 'except', projectIds: [ctx.project.id] })+ await setDefaultChatModel({ provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'second' })+ expect((await listOptions({ surface: 'chat' })).defaultChoice).toEqual({ type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'second' })++ await setDefaultChatModel({ provider: AIProviderName.CUSTOM, providerConfigId: away.id, modelId: 'elsewhere' })+ expect((await listOptions({ surface: 'chat' })).defaultChoice).not.toMatchObject({ providerConfigId: away.id })+ })++ it('moves the Default AI key when the default tier\'s main key changes', async () => {+ const first = await seedKey({ name: 'First', models: ['m'] })+ const second = await seedKey({ name: 'Second', models: ['m'] })+ const tier = await createTier({ name: 'Chat', entries: [{ configId: first.id, modelId: 'm' }] })+ expect((await ctx.post('/v1/platform-configurations', { defaultChatModel: { type: 'tier', tierId: tier.id } })).statusCode).toBe(StatusCodes.OK)++ await ctx.post(`${TIERS}/${tier.id}`, { entries: [{ configId: second.id, modelId: 'm' }] })++ const keys = await databaseConnection().getRepository('ai_provider').findBy({ platformId: ctx.platform.id })+ expect(keys.filter((key) => key.enabledForChat).map((key) => key.id)).toEqual([second.id])+ })++ it('keeps an own-key default chat model when specific models are hidden from builders', async () => {+ const key = await seedKey({ name: 'Key', models: ['first', 'second'] })+ await createTier({ name: 'Tier', entries: [{ configId: key.id, modelId: 'first' }] })+ expect((await ctx.post('/v1/platform-configurations', { defaultChatModel: { type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'second' } })).statusCode).toBe(StatusCodes.OK)+ expect((await ctx.post('/v1/platform-configurations', { aiSpecificModelsVisible: false })).statusCode).toBe(StatusCodes.OK)++ const chat = await listOptions({ surface: 'chat' })+ const admin = (await ctx.get('/v1/ai-providers/model-options/platform', { surface: 'chat' })).json() as ModelOptions++ expect(chat.keys.flatMap((option) => option.models.map((model) => model.id))).toEqual(['second'])+ expect(chat.defaultChoice).toMatchObject({ providerConfigId: key.id, modelId: 'second' })+ expect(admin.keys.flatMap((option) => option.models.map((model) => model.id))).toEqual(['first', 'second'])+ })++ it('lists every key for the admin picker, including ones limited to other projects, and only for admins', async () => {+ const away = await seedKey({ name: 'Away', models: ['elsewhere'], projectScope: 'except', projectIds: [ctx.project.id] })++ const response = await ctx.get('/v1/ai-providers/model-options/platform', { surface: 'chat' })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect((response.json() as ModelOptions).keys.map((key) => key.providerConfigId)).toContain(away.id)+ })+it('defaults to the Default tier, else credits, else the first option', async () => {const key = await seedKey({ name: 'Key', models: ['first', 'second'] })expect((await listOptions({ surface: 'flow' })).defaultChoice).toEqual({ type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'first' })@@ -166,4 +231,9 @@ function mockCatalogWithoutToolsFor({ modelId }: { modelId: string }): void {})}+async function setDefaultChatModel({ provider, providerConfigId, modelId }: { provider: AIProviderName, providerConfigId: string, modelId: string }): Promise<void> {+ await ctx.get('/v1/platform-configurations')+ await databaseConnection().getRepository('platform_configuration').update({ platformId: ctx.platform.id }, { defaultChatModel: { type: 'model', provider, providerConfigId, modelId } })+}+const TIERS = '/v1/platform-model-tiers'diff --git a/packages/server/api/test/integration/ce/platform/platform-configuration.test.ts b/packages/server/api/test/integration/ce/platform/platform-configuration.test.tsindex 0c1ea5f8d1c..71e80cf6f07 100644--- a/packages/server/api/test/integration/ce/platform/platform-configuration.test.ts+++ b/packages/server/api/test/integration/ce/platform/platform-configuration.test.ts@@ -1,7 +1,8 @@import { AIProviderName } from '@activepieces/core-utils'-import { ApFlagId, DefaultProjectRole, maxBarrierSignalsBounds } from '@activepieces/shared'+import { AIProviderModelType, ApFlagId, DefaultProjectRole, maxBarrierSignalsBounds } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'+import { databaseConnection } from '../../../../src/app/database/database-connection'import { system } from '../../../../src/app/helper/system/system'import { AppSystemProp } from '../../../../src/app/helper/system/system-props'import { mockAndSaveAIProvider } from '../../../helpers/mocks'@@ -195,6 +196,56 @@ describe('platform configuration', () => {expect(after.aiSpecificModelsVisible).toBe(true)})+ it('saves the default chat model and makes its key the Default AI key', async () => {+ const ctx = await createTestContext(app!)+ const first = await customKey({ platformId: ctx.platform.id, name: 'First', enabledForChat: true })+ const second = await customKey({ platformId: ctx.platform.id, name: 'Second' })+ const defaultChatModel = { type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: second.id, modelId: 'team-model' }++ const response = await ctx.post('/v1/platform-configurations', { defaultChatModel })++ expect(response?.statusCode).toBe(StatusCodes.OK)+ expect(response!.json().defaultChatModel).toEqual(defaultChatModel)+ const keys = await databaseConnection().getRepository('ai_provider').findBy({ platformId: ctx.platform.id })+ expect(keys.filter((key) => key.enabledForChat).map((key) => key.id)).toEqual([second.id])+ expect(first.id).not.toBe(second.id)+ })++ it('refuses a default chat model the key does not offer, and changes nothing', async () => {+ const ctx = await createTestContext(app!)+ const key = await customKey({ platformId: ctx.platform.id, name: 'Team' })++ const response = await ctx.post('/v1/platform-configurations', {+ maxBarrierSignals: 7,+ defaultChatModel: { type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'not-offered' },+ })++ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)+ const configuration = (await ctx.get('/v1/platform-configurations'))!.json()+ expect(configuration.defaultChatModel ?? null).toBeNull()+ expect(configuration.maxBarrierSignals).not.toBe(7)+ })++ it('clears the default chat model', async () => {+ const ctx = await createTestContext(app!)+ const key = await customKey({ platformId: ctx.platform.id, name: 'Team' })+ await ctx.post('/v1/platform-configurations', { defaultChatModel: { type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'team-model' } })++ await ctx.post('/v1/platform-configurations', { defaultChatModel: null })++ expect((await ctx.get('/v1/platform-configurations'))!.json().defaultChatModel ?? null).toBeNull()+ })++ it('clears the default chat model when its key is deleted', async () => {+ const ctx = await createTestContext(app!)+ const key = await customKey({ platformId: ctx.platform.id, name: 'Team' })+ await ctx.post('/v1/platform-configurations', { defaultChatModel: { type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'team-model' } })++ await ctx.delete(`/v1/ai-providers/${key.id}`)++ expect((await ctx.get('/v1/platform-configurations'))!.json().defaultChatModel ?? null).toBeNull()+ })+it('lets any platform member read the configuration, but only an admin write it', async () => {const ctx = await createTestContext(app!)const memberCtx = await createMemberContext(app!, ctx, {@@ -211,3 +262,17 @@ describe('platform configuration', () => {expect(write?.statusCode).toBe(StatusCodes.FORBIDDEN)})})++async function customKey({ platformId, name, enabledForChat }: { platformId: string, name: string, enabledForChat?: boolean }): Promise<{ id: string }> {+ return mockAndSaveAIProvider({+ platformId,+ provider: AIProviderName.CUSTOM,+ displayName: name,+ enabledForChat: enabledForChat ?? false,+ config: {+ baseUrl: 'https://api.example.com/v1',+ apiKeyHeader: 'Authorization',+ models: [{ modelId: 'team-model', modelName: 'team-model', modelType: AIProviderModelType.TEXT }],+ },+ })+}diff --git a/packages/server/api/test/integration/ee/agent/agent-chat-model.test.ts b/packages/server/api/test/integration/ee/agent/agent-chat-model.test.tsindex e4795057d75..fa74315138f 100644--- a/packages/server/api/test/integration/ee/agent/agent-chat-model.test.ts+++ b/packages/server/api/test/integration/ee/agent/agent-chat-model.test.ts@@ -1,11 +1,12 @@import { AIProviderName, assertNotNullOrUndefined, ErrorCode } from '@activepieces/core-utils'-import { aiUtils, modelTierCatalog } from '@activepieces/server-utils'+import { aiUtils, modelCatalog, modelTierCatalog } from '@activepieces/server-utils'import { AgentConversation, AIProviderModelType, aiProviderUtils, AiToolCapability, AiToolProvider, WorkerJobType } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'import { aiProviderService } from '../../../../src/app/ai/ai-provider-service'import { aiToolConfigService } from '../../../../src/app/ai/ai-tool-config-service'+import { aiProviders } from '../../../../src/app/ai/providers'import { agentChatModel } from '../../../../src/app/ee/agent/agent-chat-model'import { agentHelpers } from '../../../../src/app/ee/agent/agent-helpers'import { agentRpcHandlers } from '../../../../src/app/ee/agent/agent-rpc-handlers'@@ -45,6 +46,19 @@ describe('a chat pinned to a key', () => {expect(config.modelId).toBe('team-model')})+ it('accepts and runs a model the key lists that is not on the recommended list', async () => {+ const ctx = await context()+ vi.spyOn(aiProviders[AIProviderName.OPENAI], 'listModels').mockResolvedValue([{ id: 'gpt-4o', name: 'GPT-4o', type: AIProviderModelType.TEXT }])+ vi.spyOn(modelCatalog, 'load').mockResolvedValue({ lookup: ({ modelId }) => modelId === 'gpt-4o' ? { supportsToolCalling: true } : undefined })+ const key = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI })++ const conversation = await createConversation({ ctx, body: { projectId: ctx.project.id, providerConfigId: key.id, modelName: 'gpt-4o' } })+ const config = await getConfig({ ctx, conversationId: conversation.id })++ expect(config.providerConfigId).toBe(key.id)+ expect(config.modelId).toBe('gpt-4o')+ })+it('is refused when the key does not serve the chat\'s project', async () => {const ctx = await context()const key = await customKey({ ctx, name: 'Elsewhere', models: ['team-model'], projectScope: 'selected', projectIds: [] })@@ -63,8 +77,9 @@ describe('a chat pinned to a key', () => {expect(response.statusCode).toBe(StatusCodes.CONFLICT)})- it('fails clearly when its curated model is retired, instead of sending it to the vendor', async () => {+ it('fails clearly when the key no longer lists its model, instead of sending it to the vendor', async () => {const ctx = await context()+ vi.spyOn(aiProviders[AIProviderName.OPENAI], 'listModels').mockResolvedValue([{ id: 'gpt-5.5', name: 'GPT-5.5', type: AIProviderModelType.TEXT }])const key = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI })const conversation = await createConversation({ ctx, body: { projectId: ctx.project.id } })await db.update('agent_conversation', conversation.id, { providerConfigId: key.id, modelName: 'gpt-retired-model' })@@ -230,6 +245,42 @@ describe('a chat with no model picked', () => {expect(stored).toMatchObject({ modelTierId: tier.id, providerConfigId: null, modelName: null })})+ it('stores the Default AI key and its first known chat model when no default chat model is set', async () => {+ const ctx = await context()+ vi.spyOn(aiProviders[AIProviderName.OPENAI], 'listModels').mockResolvedValue([{ id: 'gpt-4o', name: 'GPT-4o', type: AIProviderModelType.TEXT }, { id: curatedOpenAiModel(), name: 'Curated', type: AIProviderModelType.TEXT }])+ const key = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, enabledForChat: true })+ const conversation = await createConversation({ ctx, body: { projectId: ctx.project.id } })++ await getConfig({ ctx, conversationId: conversation.id, dryRun: false })++ const stored = await db.findOneByOrFail<AgentConversation>('agent_conversation', { id: conversation.id })+ expect(stored).toMatchObject({ modelTierId: null, providerConfigId: key.id, modelName: curatedOpenAiModel() })+ })++ it('stores the platform default chat model, even when a Default tier exists', async () => {+ const ctx = await context()+ const key = await customKey({ ctx, name: 'Team', models: ['team-model', 'other-model'] })+ await createTier({ ctx, entries: [{ configId: key.id, modelId: 'team-model' }] })+ const saved = await ctx.post('/v1/platform-configurations', { defaultChatModel: { type: 'model', provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'other-model' } })+ expect(saved.statusCode).toBe(StatusCodes.OK)+ const conversation = await createConversation({ ctx, body: { projectId: ctx.project.id } })++ await getConfig({ ctx, conversationId: conversation.id, dryRun: false })++ const stored = await db.findOneByOrFail<AgentConversation>('agent_conversation', { id: conversation.id })+ expect(stored).toMatchObject({ modelTierId: null, providerConfigId: key.id, modelName: 'other-model' })+ })++ it('keeps the legacy path when the Default AI key\'s models cannot be listed', async () => {+ const ctx = await context()+ vi.spyOn(aiProviders[AIProviderName.OPENAI], 'listModels').mockRejectedValue(new Error('provider down'))+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, enabledForChat: true })++ const pick = await agentChatModel(app.log).defaultPick({ platformId: ctx.platform.id, projectId: ctx.project.id })++ expect(pick).toBeNull()+ })+it('can be talked to on a platform that has tiers but no Default AI key', async () => {const ctx = await context()const key = await customKey({ ctx, name: 'Team', models: ['team-model'] })@@ -293,6 +344,71 @@ describe('knowledge base embeddings', () => {expect(createEmbeddingModel).toHaveBeenCalledWith(expect.objectContaining({ providerConfigId: embeddingsKey.id }))})+ it('embeds with the picked model, even on a key whose chat models are narrowed', async () => {+ const ctx = await context()+ const embeddingsKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, modelScope: 'selected', modelIds: ['gpt-4o'] })+ await aiToolConfigService(app.log).upsert(ctx.platform.id, { capability: AiToolCapability.EMBEDDINGS, provider: AiToolProvider.AI_PROVIDER, config: { aiProviderId: embeddingsKey.id, modelId: 'text-embedding-3-large' } })+ const createEmbeddingModel = vi.spyOn(aiUtils, 'createEmbeddingModel')++ await knowledgeBaseService(app.log).embedderFor({ platformId: ctx.platform.id, projectId: ctx.project.id })+ await aiProviderService(app.log).update(ctx.platform.id, embeddingsKey.id, { displayName: 'OpenAI', modelScope: 'selected', modelIds: ['gpt-4o-mini'] })++ expect(createEmbeddingModel).toHaveBeenCalledWith(expect.objectContaining({ providerConfigId: embeddingsKey.id, modelId: 'text-embedding-3-large' }))+ })++ it('refuses an embedding model the provider does not list', async () => {+ const ctx = await context()+ const embeddingsKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI })++ await expect(aiToolConfigService(app.log).upsert(ctx.platform.id, { capability: AiToolCapability.EMBEDDINGS, provider: AiToolProvider.AI_PROVIDER, config: { aiProviderId: embeddingsKey.id, modelId: 'gpt-4o' } }))+ .rejects.toMatchObject({ error: { code: ErrorCode.VALIDATION } })+ })++ it('tells project members which provider and model embed their files', async () => {+ const ctx = await context()+ const embeddingsKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI })+ await aiToolConfigService(app.log).upsert(ctx.platform.id, { capability: AiToolCapability.EMBEDDINGS, provider: AiToolProvider.AI_PROVIDER, config: { aiProviderId: embeddingsKey.id, modelId: 'text-embedding-3-large' } })++ const response = await ctx.get(EMBEDDING_SOURCE_URL, { projectId: ctx.project.id })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json()).toEqual({ provider: AIProviderName.OPENAI, modelId: 'text-embedding-3-large' })+ })++ it('reports no embedding source when the Default AI key cannot embed and nothing is picked', async () => {+ const ctx = await context()+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ANTHROPIC, enabledForChat: true })++ const response = await ctx.get(EMBEDDING_SOURCE_URL, { projectId: ctx.project.id })++ expect(response.json()).toEqual({ provider: null, modelId: null })+ })++ it('does not tell another platform\'s user about a project\'s embedding source', async () => {+ const ctx = await context()+ const outsider = await context()++ const response = await outsider.get(EMBEDDING_SOURCE_URL, { projectId: ctx.project.id })++ expect(response.statusCode).toBe(StatusCodes.FORBIDDEN)+ })++ it('indexes with Credits when the Default AI key cannot embed', async () => {+ process.env.AP_OPENROUTER_PROVISION_KEY = 'test-provision-key'+ try {+ const ctx = await context()+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ANTHROPIC, enabledForChat: true })+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ACTIVEPIECES })++ const response = await ctx.get(EMBEDDING_SOURCE_URL, { projectId: ctx.project.id })++ expect(response.json()).toMatchObject({ provider: AIProviderName.ACTIVEPIECES })+ }+ finally {+ delete process.env.AP_OPENROUTER_PROVISION_KEY+ }+ })+it('refuses an Embeddings choice that is not one of the platform\'s AI keys', async () => {const ctx = await context()@@ -371,3 +487,4 @@ function curatedOpenAiModel(): string {}const CONVERSATIONS_URL = '/v1/agents/conversations'+const EMBEDDING_SOURCE_URL = '/v1/knowledge-base/files/embedding-source'diff --git a/packages/server/utils/src/ai-utils.ts b/packages/server/utils/src/ai-utils.tsindex e4e3a496240..6902d31cb5e 100644--- a/packages/server/utils/src/ai-utils.ts+++ b/packages/server/utils/src/ai-utils.ts@@ -259,13 +259,14 @@ function toStorageEmbedding(embedding: number[]): number[] {return magnitude === 0 ? truncated : truncated.map((value) => value / magnitude)}-function createEmbeddingModel({ credentials, billing, platformId, providerConfigId }: {+function createEmbeddingModel({ credentials, modelId, billing, platformId, providerConfigId }: {credentials: AiProviderCredentials+ modelId?: stringbilling?: ActivepiecesAiBillingplatformId?: stringproviderConfigId?: string}): { model: EmbeddingModel, providerOptions: SharedV3ProviderOptions } {- const embeddingModelId = AI_PROVIDER_CAPABILITIES[credentials.provider].defaultEmbeddingModel+ const embeddingModelId = modelId ?? AI_PROVIDER_CAPABILITIES[credentials.provider].defaultEmbeddingModelif (isNil(embeddingModelId)) {throw new Error(`Provider ${credentials.provider} does not support knowledge base search`)}diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 7cb5612aa71..df1ccafd28e 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -832,7 +832,6 @@"Model": "Model","Pick a model so this agent can answer.": "Pick a model so this agent can answer.","Embedding model for knowledge base: {model}": "Embedding model for knowledge base: {model}",- "Your chat provider does not support knowledge base embeddings.": "Your chat provider does not support knowledge base embeddings.","Max steps": "Max steps","Name": "Name","Description": "Description",@@ -960,7 +959,6 @@"Voice input": "Voice input","Drop files here": "Drop files here","Release to add files to your message": "Release to add files to your message",- "Credits are charged based on how much work the agent does, plus {count, plural, =1 {1 credit} other {# credits}} per tool call.": "Credits are charged based on how much work the agent does, plus {count, plural, =1 {1 credit} other {# credits}} per tool call.","Expired": "Expired","Using this {name} account": "Using this {name} account","Reconnect {name}": "Reconnect {name}",@@ -1818,7 +1816,6 @@"Page {page} of {pages}": "Page {page} of {pages}","Last checked {when}": "Last checked {when}","usedByTiersCount": "{count, plural, =1 {Used by 1 tier} other {Used by # tiers}}",- "Chat provider": "Chat provider","Recheck": "Recheck","Models": "Models","Access": "Access",@@ -1852,7 +1849,6 @@"Save credentials": "Save credentials","How to get {name} credentials": "How to get {name} credentials","{name} key": "{name} key",- "Chat provider updated": "Chat provider updated","Could not reach this provider": "Could not reach this provider","Connect a provider to turn on chat, agents, and AI steps across your platform.": "Connect a provider to turn on chat, agents, and AI steps across your platform.","Each key has its own models and project access.": "Each key has its own models and project access.",@@ -1868,7 +1864,6 @@"exceptProjectsCount": "{count, plural, =1 {All except 1 project} other {All except # projects}}","projectsCount": "{count, plural, =1 {1 project} other {# projects}}","{count} projects have access. Excluded: {names}": "{count} projects have access. Excluded: {names}",- "Powers the built-in chat for everyone on this platform": "Powers the built-in chat for everyone on this platform","Connect your first provider": "Connect your first provider","Bring an API key, then pick which models and projects can use it. Chat, agents, and AI steps run through it.": "Bring an API key, then pick which models and projects can use it. Chat, agents, and AI steps run through it.","Or choose another provider": "Or choose another provider",@@ -1973,7 +1968,6 @@"Every text model on this key is a tier's main model.": "Every text model on this key is a tier's main model.","No text models on this key.": "No text models on this key.","Fast": "Fast",- "Recommended for chat": "Recommended for chat","Tier actions": "Tier actions","Make default": "Make default","Use as fast model": "Use as fast model",@@ -2353,9 +2347,7 @@"Add Flow": "Add Flow","Remove knowledge source": "Remove knowledge source","Knowledge Base": "Knowledge Base",- "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.","Add knowledge": "Add knowledge",- "Knowledge base requires a provider that supports embeddings, such as OpenAI or Google.": "Knowledge base requires a provider that supports embeddings, such as OpenAI or Google.","Add files or tables as knowledge sources for your agent.": "Add files or tables as knowledge sources for your agent.","MCP Servers": "MCP Servers","Remove MCP server": "Remove MCP server",@@ -2391,7 +2383,6 @@"e.g., company_docs": "e.g., company_docs","e.g., products_catalog": "e.g., products_catalog","A unique name for the agent to reference this knowledge source": "A unique name for the agent to reference this knowledge source",- "Add an AI provider before uploading. Files are indexed when uploaded so agents can search them.": "Add an AI provider before uploading. Files are indexed when uploaded so agents can search them.","This file has no text that can be searched.": "This file has no text that can be searched.","Failed to upload file": "Failed to upload file","Connect an account": "Connect an account",@@ -2437,7 +2428,6 @@"Show all {count}": "Show all {count}","Trouble loading models": "Trouble loading models","No models available — ask your platform admin to add a provider.": "No models available — ask your platform admin to add a provider.",- "Your tiers": "Your tiers","Credits tiers": "Credits tiers","Unavailable model": "Unavailable model","Tier": "Tier",@@ -3278,6 +3268,34 @@"{count} mins ago": "{count} mins ago","1 hour ago": "1 hour ago","{count} hours ago": "{count} hours ago",+ "Pick another model to continue": "Pick another model to continue",+ "Embedding model": "Embedding model",+ "Files already in knowledge bases keep their old vectors. Re-upload them to search with the new key or model.": "Files already in knowledge bases keep their old vectors. Re-upload them to search with the new key or model.",+ "Add a key that serves all projects and supports embeddings, such as OpenAI, Google, Azure or OpenRouter.": "Add a key that serves all projects and supports embeddings, such as OpenAI, Google, Azure or OpenRouter.",+ "Embeddings": "Embeddings",+ "Index knowledge-base files so agents can search them. Pick one of your AI keys and its embedding model.": "Index knowledge-base files so agents can search them. Pick one of your AI keys and its embedding model.",+ "Knowledge bases go back to using {provider}.": "Knowledge bases go back to using {provider}.",+ "Knowledge bases can index files": "Knowledge bases can index files",+ "Knowledge bases can't index files yet": "Knowledge bases can't index files yet",+ "Add a provider key": "Add a provider key",+ "No AI key can index files for this project yet.": "No AI key can index files for this project yet.",+ "Pick an embedding model": "Pick an embedding model",+ "Ask your admin to set an Embeddings model.": "Ask your admin to set an Embeddings model.",+ "No AI key can index files yet. Set an Embeddings model in AI settings → Capabilities, or ask your admin.": "No AI key can index files yet. Set an Embeddings model in AI settings → Capabilities, or ask your admin.",+ "Couldn't switch the model. Try again.": "Couldn't switch the model. Try again.",+ "Default chat model updated": "Default chat model updated",+ "Default chat model": "Default chat model",+ "This model is not available for chat on this platform": "This model is not available for chat on this platform",+ "New chats start on this model.": "New chats start on this model.",+ "Not set": "Not set",+ "Not available in {count, plural, =1 {1 project} other {# projects}}": "Not available in {count, plural, =1 {1 project} other {# projects}}",+ "Not set · uses {model}": "Not set · uses {model}",+ "Use default": "Use default",+ "This model is no longer available.": "This model is no longer available.",+ "This model is no longer available. New chats use {model}.": "This model is no longer available. New chats use {model}.",+ "Not available in {count, plural, =1 {1 project} other {# projects}}.": "Not available in {count, plural, =1 {1 project} other {# projects}}.",+ "This key can't index knowledge-base files. Set an Embeddings key in Capabilities.": "This key can't index knowledge-base files. Set an Embeddings key in Capabilities.",+ "Couldn't check whether files can be indexed.": "Couldn't check whether files can be indexed.","Actions for {domain}": "Actions for {domain}","Add domain": "Add domain","Add this TXT record at your DNS provider.": "Add this TXT record at your DNS provider.",diff --git a/packages/web/src/app/components/admin/admin-page.tsx b/packages/web/src/app/components/admin/admin-page.tsxindex 9ebc7dbc485..e1a961a9d0e 100644--- a/packages/web/src/app/components/admin/admin-page.tsx+++ b/packages/web/src/app/components/admin/admin-page.tsx@@ -143,11 +143,12 @@ function AdminBackLink({ back }: { back: AdminPageBack }) {const WIDTH_CLASS: Record<AdminPageWidth, string> = {full: '',content: adminLayout.contentWidth,+ wide: 'mx-auto max-w-5xl',};type AdminPageBack = { label: string; to: string };-type AdminPageWidth = 'full' | 'content';+type AdminPageWidth = 'full' | 'content' | 'wide';type AdminPageProps = {width?: AdminPageWidth;diff --git a/packages/web/src/app/routes/agents/id/configure-panel/index.tsx b/packages/web/src/app/routes/agents/id/configure-panel/index.tsxindex d5b6dea392f..aeda74e6e11 100644--- a/packages/web/src/app/routes/agents/id/configure-panel/index.tsx+++ b/packages/web/src/app/routes/agents/id/configure-panel/index.tsx@@ -49,13 +49,13 @@ import { Textarea } from '@/components/ui/textarea';import {AgentStructuredOutput,ModelPicker,- PROVIDER_EMBEDDING_MODELS,+ NoEmbeddingSourceNote,+ useKnowledgeBaseEmbeddingSource,} from '@/features/agents';import { AgentMark } from '@/features/agents/agent-mark';import { DeleteAgentDialog } from '@/features/agents/delete-agent-dialog';import { agentsMutations } from '@/features/agents/hooks/agents-hooks';import { MoveAgentDialog } from '@/features/agents/move-agent-dialog';-import { aiProviderQueries } from '@/features/platform-admin/hooks/ai-provider-hooks';import {ApProjectDisplay,getProjectName,@@ -224,8 +224,7 @@ const ConfigureBehaviorTab = ({}) => {const tools = form.watch('draft.tools') ?? [];const draft = form.watch('draft');- const { data: chatProvider } = aiProviderQueries.useChatProvider();- const provider = chatProvider?.provider;+ const { data: embeddingSource } = useKnowledgeBaseEmbeddingSource();const knowledgeCount = tools.filter((tool) => tool.type === AgentToolType.KNOWLEDGE_BASE,).length;@@ -292,17 +291,17 @@ const ConfigureBehaviorTab = ({});}}/>- {knowledgeCount > 0 && !isNil(provider) && (- <p className="text-xs text-gray-11">- {PROVIDER_EMBEDDING_MODELS[provider]- ? t('Embedding model for knowledge base: {model}', {- model: PROVIDER_EMBEDDING_MODELS[provider],- })- : t(- 'Your chat provider does not support knowledge base embeddings.',- )}- </p>- )}+ {knowledgeCount > 0 &&+ !isNil(embeddingSource) &&+ (isNil(embeddingSource.modelId) ? (+ <NoEmbeddingSourceNote className="text-xs text-gray-11" />+ ) : (+ <p className="text-xs text-gray-11">+ {t('Embedding model for knowledge base: {model}', {+ model: embeddingSource.modelId,+ })}+ </p>+ ))}</FormItem><FormFieldcontrol={form.control}diff --git a/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsx b/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsxindex 6f95ae6799c..c0af6155ed4 100644--- a/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsx+++ b/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsx@@ -3,6 +3,7 @@ import {AgentConversation,AgentMessageSource,ChatPersonalizationStatus,+ ModelOptions,PlatformRole,} from '@activepieces/shared';import { useQueryClient } from '@tanstack/react-query';@@ -18,6 +19,9 @@ import {} from '@/components/prompt-kit/chat-container';import { ScrollButton } from '@/components/prompt-kit/scroll-button';import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { ModelPicker, modelPickerUtils } from '@/features/agents';+import { aiModelHooks } from '@/features/agents/ai-model/hooks';import { ChatCreditsAlert } from '@/features/billing';import { chatStoreSelectors } from '@/features/chat/lib/chat-store';import {@@ -30,9 +34,9 @@ import { onboardingPrefillUtils } from '@/features/chat/lib/onboarding-prefill';import { useAgentChat } from '@/features/chat/lib/use-chat';import { useCreditsState } from '@/features/chat/lib/use-credits-state';import { usePersonalization } from '@/features/chat/lib/use-personalization';-import { aiProviderQueries } from '@/features/platform-admin';import { platformHooks } from '@/hooks/platform-hooks';import { userHooks } from '@/hooks/user-hooks';+import { authenticationSession } from '@/lib/authentication-session';import { cn } from '@/lib/utils';import { AssistantMessage } from './components/assistant-message';@@ -66,14 +70,20 @@ export function AIChatBox({onTitleUpdate,onConversationCreated,}: AIChatBoxProps) {- const { data: chatProvider, isLoading: isLoadingProviders } =- aiProviderQueries.useChatProvider();+ const projectId = authenticationSession.getProjectId();+ const gated =+ agentId === undefined && isNil(conversationId) && !isNil(projectId);+ const { data: options, isLoading } = aiModelHooks.useModelOptions({+ projectId: projectId ?? '',+ surface: 'chat',+ enabled: gated,+ });- if (isLoadingProviders) {+ if (gated && isLoading) {return <MessageSkeletons />;}- if (!chatProvider) {+ if (gated && !isNil(options) && !hasAnyModel({ options })) {return <SetupRequiredState />;}@@ -113,11 +123,12 @@ function ChatBoxContent({}: AIChatBoxProps) {const queryClient = useQueryClient();const credits = useCreditsState();- const { data: chatProvider } = aiProviderQueries.useChatProvider();+ const sessionProjectId = authenticationSession.getProjectId();const {conversationId,- modelName,+ conversationProjectId,+ modelPick,messages,isStreaming,isResumedStream,@@ -128,14 +139,11 @@ function ChatBoxContent({sendMessage,cancelStream,setConversationId,- setModelName,+ setModelPick,} = useAgentChat({...(agentId === undefined ? {} : { agentId }),...(builder === undefined ? {} : { builder }),- defaultModelName:- agentId === undefined- ? chatUtils.newChatModelName({ provider: chatProvider?.provider })- : null,+ projectId: sessionProjectId,onTitleUpdate,onConversationCreated,onTurnEnd,@@ -182,6 +190,29 @@ function ChatBoxContent({return () => window.removeEventListener('keydown', handler);}, [isStreaming, cancelStream]);+ const chatProjectId = conversationProjectId ?? sessionProjectId;+ const showsPicker = agentId === undefined && !isNil(chatProjectId);+ const { data: modelOptions } = aiModelHooks.useModelOptions({+ projectId: chatProjectId ?? '',+ surface: 'chat',+ tierId: modelPick?.modelTierId ?? undefined,+ enabled: showsPicker,+ });+ const shownChoice = isNil(modelOptions)+ ? null+ : chatUtils.choiceOf({ pick: modelPick, options: modelOptions }) ??+ modelOptions.defaultChoice ??+ null;+ const awaitingSavedPick =+ !isNil(initialConversationId) && (isNil(modelPick) || isLoadingHistory);+ const pickUnavailable =+ showsPicker &&+ !isNil(modelOptions) &&+ modelPickerUtils.isUnavailable({+ options: modelOptions,+ value: shownChoice,+ });+const [hasSentMessage, setHasSentMessage] = useState(false);const handleSend = useCallback(@@ -191,10 +222,21 @@ function ChatBoxContent({options?: { messageSource?: AgentMessageSource },) => {if (!text.trim() && (!files || files.length === 0)) return;+ if (pickUnavailable) return;+ if (isNil(conversationId) && isNil(modelPick) && !isNil(shownChoice)) {+ await setModelPick(chatUtils.pickOf({ choice: shownChoice }));+ }setHasSentMessage(true);await sendMessage(text.trim(), files, options);},- [sendMessage],+ [+ sendMessage,+ pickUnavailable,+ conversationId,+ modelPick,+ shownChoice,+ setModelPick,+ ],);const sentInitialPrompt = useRef(false);@@ -212,8 +254,9 @@ function ChatBoxContent({const handleRetry = useCallback(() => {const lastUser = messages.findLast((m) => m.role === 'user');- if (lastUser) void sendMessage(getTextFromParts(lastUser.parts));- }, [messages, sendMessage]);+ if (lastUser && !pickUnavailable)+ void sendMessage(getTextFromParts(lastUser.parts));+ }, [messages, sendMessage, pickUnavailable]);const lastMessage = messages[messages.length - 1];const lastAssistantMessage = useMemo(@@ -474,11 +517,26 @@ function ChatBoxContent({onStop={cancelStream}onInputChange={setHasInput}recede={showOnboardingCard}- selectedModel={modelName}- onModelChange={setModelName}+ modelPicker={+ showsPicker && awaitingSavedPick ? (+ <Skeleton className="h-8 w-24 rounded-full" />+ ) : showsPicker && !isNil(chatProjectId) ? (+ <ModelPicker+ variant="pill"+ surface="chat"+ projectId={chatProjectId}+ value={shownChoice}+ onChange={(choice) =>+ void setModelPick(chatUtils.pickOf({ choice }))+ }+ />+ ) : null+ }+ sendBlockedReason={+ pickUnavailable ? t('Pick another model to continue') : undefined+ }lastAssistantMessage={lastAssistantMessage}lastMessageId={lastMessage?.id}- hideModelSelector={agentId !== undefined}placeholder={placeholder ??(showOnboardingCard@@ -508,6 +566,14 @@ function ChatBoxContent({);}+function hasAnyModel({ options }: { options: ModelOptions }): boolean {+ return (+ options.tiers.length > 0 ||+ !isNil(options.credits) ||+ options.keys.length > 0+ );+}+// A build's plan is replayed across many messages; assign each build to the// single (latest) message allowed to render its card so the plan shows once.function computeClaimedBuildIds(diff --git a/packages/web/src/app/routes/chat-with-ai/components/chat-bottom-bar.tsx b/packages/web/src/app/routes/chat-with-ai/components/chat-bottom-bar.tsxindex 63d35923dd7..6ec817cdd2b 100644--- a/packages/web/src/app/routes/chat-with-ai/components/chat-bottom-bar.tsx+++ b/packages/web/src/app/routes/chat-with-ai/components/chat-bottom-bar.tsx@@ -19,7 +19,6 @@ import {import { ActionPreviewCard } from './action-preview-card';import { ChatCardSkeleton } from './chat-card-primitives';import { ChatInput } from './chat-input';-import { ChatModelSelector } from './chat-model-selector';import { ConnectionPickerCard } from './connection-picker-card';import { McpReconnectCard, McpReconnectData } from './mcp-reconnect-card';import { MultiQuestionForm } from './multi-question-form';@@ -30,9 +29,8 @@ export function ChatBottomBar({onSend,onStop,onInputChange,- selectedModel,- onModelChange,- hideModelSelector,+ modelPicker,+ sendBlockedReason,lastAssistantMessage,lastMessageId,placeholder,@@ -144,14 +142,8 @@ export function ChatBottomBar({? t('Or reply in your own words'): placeholder ?? t('Reply...')}- rightActions={- hideModelSelector === true ? null : (- <ChatModelSelector- selectedModel={selectedModel}- onModelChange={onModelChange}- />- )- }+ rightActions={modelPicker}+ sendBlockedReason={sendBlockedReason}/></div></div>@@ -224,9 +216,8 @@ type ChatBottomBarProps = {onSend: (text: string, files?: File[]) => void;onStop: () => void;onInputChange?: (hasInput: boolean) => void;- selectedModel: string | null;- onModelChange: (modelId: string) => void;- hideModelSelector?: boolean;+ modelPicker?: ReactNode;+ sendBlockedReason?: string;lastAssistantMessage: ChatUIMessage | undefined;lastMessageId: string | undefined;placeholder?: string;diff --git a/packages/web/src/app/routes/chat-with-ai/components/chat-input.tsx b/packages/web/src/app/routes/chat-with-ai/components/chat-input.tsxindex 6cac8039c37..03666eac173 100644--- a/packages/web/src/app/routes/chat-with-ai/components/chat-input.tsx+++ b/packages/web/src/app/routes/chat-with-ai/components/chat-input.tsx@@ -1,3 +1,4 @@+import { isNil } from '@activepieces/core-utils';import { t } from 'i18next';import { ArrowUp, Mic, Paperclip, Square, X } from 'lucide-react';import { AnimatePresence, motion } from 'motion/react';@@ -30,6 +31,7 @@ export function ChatInput({rightActions,minimalUntilFocus = false,onFocusChange,+ sendBlockedReason,}: {isStreaming: boolean;onSend: (text: string, files?: File[]) => void;@@ -40,6 +42,7 @@ export function ChatInput({rightActions?: React.ReactNode;minimalUntilFocus?: boolean;onFocusChange?: (focused: boolean) => void;+ sendBlockedReason?: string;}) {const [value, setValue] = useState('');const [focused, setFocused] = useState(false);@@ -100,7 +103,11 @@ export function ChatInput({}, [isRecording, cancelRecording]);const handleSubmit = useCallback(() => {- if (!isStreaming && (value.trim() || attachedFiles.length > 0)) {+ if (+ isNil(sendBlockedReason) &&+ !isStreaming &&+ (value.trim() || attachedFiles.length > 0)+ ) {onSend(value.trim(),attachedFiles.length > 0 ? attachedFiles : undefined,@@ -108,7 +115,7 @@ export function ChatInput({setValue('');setAttachedFiles([]);}- }, [isStreaming, value, attachedFiles, onSend]);+ }, [isStreaming, value, attachedFiles, onSend, sendBlockedReason]);const handleFilesAdded = useCallback((files: File[]) => {setAttachedFiles((prev) => [...prev, ...files]);@@ -228,13 +235,15 @@ export function ChatInput({</Button></PromptInputAction>) : canSend ? (- <PromptInputAction tooltip={t('Send message')}>+ <PromptInputAction+ tooltip={sendBlockedReason ?? t('Send message')}+ ><Buttonvariant="default"size="icon"className="sm:h-7 sm:w-7 rounded-full"onClick={handleSubmit}- disabled={isStreaming}+ disabled={isStreaming || !isNil(sendBlockedReason)}><ArrowUp className="size-4" /></Button>diff --git a/packages/web/src/app/routes/chat-with-ai/components/chat-model-selector.tsx b/packages/web/src/app/routes/chat-with-ai/components/chat-model-selector.tsxdeleted file mode 100644index 886b7235baf..00000000000--- a/packages/web/src/app/routes/chat-with-ai/components/chat-model-selector.tsx+++ /dev/null@@ -1,235 +0,0 @@-import { AIProviderName, isNil } from '@activepieces/core-utils';-import {- aiProviderUtils,- CHAT_CREDITS_PER_TOOL_CALL,-} from '@activepieces/shared';-import { t } from 'i18next';-import {- ArrowDown,- ArrowUp,- Check,- ChevronDown,- CornerDownLeft,- Equal,- Lightbulb,- Rocket,- Sparkles,-} from 'lucide-react';-import React, { useEffect, useRef, useState } from 'react';--import { Button } from '@/components/ui/button';-import {- Popover,- PopoverContent,- PopoverTrigger,-} from '@/components/ui/popover';-import { aiProviderQueries } from '@/features/platform-admin';-import { cn } from '@/lib/utils';--const TIER_CONFIG: Partial<- Record<- string,- {- icon: React.ComponentType<{ className?: string }>;- description: string;- }- >-> = {- fast: {- icon: Equal,- description: 'Quick replies for simple tasks',- },- smart: {- icon: Lightbulb,- description: 'Best for everyday use',- },- premium: {- icon: Rocket,- description: 'Highest quality, a bit slower',- },-};--function useModelOptions(): {- options: ModelOption[];- defaultOptionId: string;-} {- const { data: chatProvider } = aiProviderQueries.useChatProvider();- const chatTiers = aiProviderQueries.useModelTiers('chat');- const curatedModels = isNil(chatProvider)- ? undefined- : aiProviderUtils.getCuratedChatModels({ provider: chatProvider.provider });- if (isNil(curatedModels)) {- return {- options: chatTiers.tiers.map((tier) => ({- id: tier.id,- ...(TIER_CONFIG[tier.id] ?? { icon: Sparkles, description: null }),- displayLabel: tier.label,- })),- defaultOptionId: chatTiers.defaultTierId,- };- }- return {- options: curatedModels.map((model) => ({- id: model.id,- icon: Sparkles,- displayLabel: model.label,- description: null,- })),- defaultOptionId: curatedModels[0].id,- };-}--export function ChatModelSelector({- selectedModel,- onModelChange,-}: {- selectedModel: string | null;- onModelChange: (modelId: string) => void;-}) {- const [open, setOpen] = useState(false);- const [focusedIndex, setFocusedIndex] = useState(-1);- const listRef = useRef<HTMLDivElement>(null);- const { data: chatProvider } = aiProviderQueries.useChatProvider();- const showCredits = chatProvider?.provider === AIProviderName.ACTIVEPIECES;-- const { options, defaultOptionId } = useModelOptions();- const selectedOption =- options.find((option) => option.id === selectedModel) ??- options.find((option) => option.id === defaultOptionId) ??- options[0];-- const focused =- focusedIndex === -1 ? options.indexOf(selectedOption) : focusedIndex;-- useEffect(() => {- if (!open) return;- const rafId = requestAnimationFrame(() => listRef.current?.focus());- return () => cancelAnimationFrame(rafId);- }, [open]);-- const handleKeyDown = (e: React.KeyboardEvent) => {- if (e.key === 'ArrowDown') {- e.preventDefault();- setFocusedIndex(focused < options.length - 1 ? focused + 1 : 0);- } else if (e.key === 'ArrowUp') {- e.preventDefault();- setFocusedIndex(focused > 0 ? focused - 1 : options.length - 1);- } else if (e.key === 'Enter') {- e.preventDefault();- onModelChange(options[focused].id);- setOpen(false);- }- };-- return (- <Popover- open={open}- onOpenChange={(next) => {- setOpen(next);- setFocusedIndex(-1);- }}- >- <PopoverTrigger asChild>- <Button- variant="ghost"- size="xs"- role="combobox"- aria-expanded={open}- className="rounded-full text-gray-11 hover:text-gray-12"- >- <span>{t(selectedOption.displayLabel)}</span>- <ChevronDown className="size-3 opacity-50" />- </Button>- </PopoverTrigger>- <PopoverContent- className="w-[330px] p-0"- align="end"- side="top"- onOpenAutoFocus={(e) => e.preventDefault()}- >- <div- ref={listRef}- tabIndex={0}- onKeyDown={handleKeyDown}- className="outline-none"- >- <div className="py-1">- {options.map((option, index) => {- const Icon = option.icon;- const isSelected = selectedOption.id === option.id;- const isFocused = focused === index;- return (- <div- key={option.id}- onClick={() => {- onModelChange(option.id);- setOpen(false);- }}- onMouseEnter={() => setFocusedIndex(index)}- className={cn(- 'flex items-center gap-3 px-3 py-3.5 cursor-pointer transition-colors',- isFocused && 'bg-gray-4',- )}- >- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border bg-gray-1">- <Icon className="size-4 text-gray-12" />- </div>- <div className="flex flex-1 flex-col gap-0.5">- <div className="flex items-center gap-2">- <span className="text-sm font-medium">- {t(option.displayLabel)}- </span>- </div>- {option.description && (- <span className="text-xs text-gray-11">- {t(option.description)}- </span>- )}- </div>- <Check- className={cn(- 'size-4 shrink-0',- isSelected ? 'opacity-100' : 'opacity-0',- )}- />- </div>- );- })}- </div>- {showCredits && (- <div className="border-t px-3 py-2 text-xs text-gray-11">- {t(- 'Credits are charged based on how much work the agent does, plus {count, plural, =1 {1 credit} other {# credits}} per tool call.',- { count: CHAT_CREDITS_PER_TOOL_CALL },- )}- </div>- )}- <div className="flex items-center gap-3 border-t px-3 py-2 text-xs text-gray-11">- <div className="flex items-center gap-1">- <kbd className="flex h-5 w-5 items-center justify-center rounded-md border bg-gray-3">- <ArrowUp className="size-3" />- </kbd>- <kbd className="flex h-5 w-5 items-center justify-center rounded-md border bg-gray-3">- <ArrowDown className="size-3" />- </kbd>- <span>{t('to navigate')}</span>- </div>- <div className="flex items-center gap-1">- <kbd className="flex h-5 w-5 items-center justify-center rounded-md border bg-gray-3">- <CornerDownLeft className="size-3" />- </kbd>- <span>{t('to select')}</span>- </div>- </div>- </div>- </PopoverContent>- </Popover>- );-}--type ModelOption = {- id: string;- icon: React.ComponentType<{ className?: string }>;- displayLabel: string;- description: string | null;-};diff --git a/packages/web/src/app/routes/platform/setup/ai-capabilities/ai-capability-dialog.tsx b/packages/web/src/app/routes/platform/setup/ai-capabilities/ai-capability-dialog.tsxindex c88a597aca1..28baafa1844 100644--- a/packages/web/src/app/routes/platform/setup/ai-capabilities/ai-capability-dialog.tsx+++ b/packages/web/src/app/routes/platform/setup/ai-capabilities/ai-capability-dialog.tsx@@ -1,5 +1,6 @@import { isNil } from '@activepieces/core-utils';import {+ AI_PROVIDER_CAPABILITIES,AIProviderModelType,AiProviderToolConfig,AIProviderWithoutSensitiveData,@@ -14,6 +15,7 @@ import { t } from 'i18next';import { ExternalLink } from 'lucide-react';import { useState } from 'react';import { useForm } from 'react-hook-form';+import { Link } from 'react-router-dom';import { z } from 'zod';import { adminLayout } from '@/app/components/admin';@@ -108,8 +110,27 @@ function CapabilityForm({providers,});const existingChoice = AiProviderToolConfig.safeParse(existingConfig?.config);+ const isEmbeddings =+ capabilityInfo.capability === AiToolCapability.EMBEDDINGS;const needsModel =+ isEmbeddings ||capabilityInfo.capability === AiToolCapability.IMAGE_GENERATION;+ const defaultSource = pickDefaultSource({+ preferred: existingChoice.success+ ? existingChoice.data.aiProviderId+ : existingConfig?.provider ?? defaultProviderId,+ sourceIds: [+ ...aiProviders.map((p) => p.id),+ ...capabilityInfo.providers.map((p) => p.id),+ ],+ fallback: capabilityInfo.providers[0]?.id ?? aiProviders[0]?.id ?? '',+ });+ const firstEmbeddingModel = (sourceId: string): string => {+ const provider = aiProviders.find((p) => p.id === sourceId);+ return isEmbeddings && !isNil(provider)+ ? AI_PROVIDER_CAPABILITIES[provider.provider].embeddingModels[0] ?? ''+ : '';+ };const savedKeyProvider = existingConfig?.hasApiKey? existingConfig.provider: undefined;@@ -136,34 +157,31 @@ function CapabilityForm({),mode: 'onChange',defaultValues: {- source: pickDefaultSource({- preferred: existingChoice.success- ? existingChoice.data.aiProviderId- : existingConfig?.provider ?? defaultProviderId,- sourceIds: [- ...aiProviders.map((p) => p.id),- ...capabilityInfo.providers.map((p) => p.id),- ],- fallback: capabilityInfo.providers[0].id,- }),+ source: defaultSource,apiKey: '',- modelId: existingChoice.success ? existingChoice.data.modelId ?? '' : '',+ modelId:+ (existingChoice.success ? existingChoice.data.modelId : undefined) ??+ firstEmbeddingModel(defaultSource),},});const source = form.watch('source');const selectedAiProvider = aiProviders.find((p) => p.id === source);const { data: models = [] } = aiProviderQueries.useConfigModels(- needsModel ? selectedAiProvider?.id : undefined,+ needsModel && !isEmbeddings ? selectedAiProvider?.id : undefined,);- const imageModels = isNil(selectedAiProvider)+ const modelOptions = isNil(selectedAiProvider)? []+ : isEmbeddings+ ? AI_PROVIDER_CAPABILITIES[selectedAiProvider.provider].embeddingModels.map(+ (id) => ({ id, name: id }),+ ): models.filter((model) =>model.type === AIProviderModelType.IMAGE &&modelAllowed({ model, provider: selectedAiProvider }),);- const selectedModel = imageModels.find(+ const selectedModel = modelOptions.find((model) => model.id === form.watch('modelId'),);@@ -240,7 +258,7 @@ function CapabilityForm({value={field.value}onValueChange={(value) => {field.onChange(value);- form.setValue('modelId', '');+ form.setValue('modelId', firstEmbeddingModel(value));}}><FormControl>@@ -273,7 +291,9 @@ function CapabilityForm({name="modelId"render={({ field }) => (<FormItem>- <FormLabel>{t('Image model')}</FormLabel>+ <FormLabel>+ {isEmbeddings ? t('Embedding model') : t('Image model')}+ </FormLabel><Select value={field.value} onValueChange={field.onChange}><FormControl><SelectTrigger>@@ -283,22 +303,26 @@ function CapabilityForm({<span className="truncate">{selectedModel.name}</span>- <span className="truncate text-xs text-gray-11">- {selectedModel.id}- </span>+ {selectedModel.name !== selectedModel.id && (+ <span className="truncate text-xs text-gray-11">+ {selectedModel.id}+ </span>+ )}</span>)}</SelectValue></SelectTrigger></FormControl><SelectContent>- {imageModels.map((model) => (+ {modelOptions.map((model) => (<SelectItem key={model.id} value={model.id}><span className="flex flex-col"><span>{model.name}</span>- <span className="text-xs text-gray-11">- {model.id}- </span>+ {model.name !== model.id && (+ <span className="text-xs text-gray-11">+ {model.id}+ </span>+ )}</span></SelectItem>))}@@ -310,7 +334,28 @@ function CapabilityForm({/>)}- {!selectedAiProvider && (+ {isEmbeddings && sourceCount > 0 && (+ <p className="text-xs text-gray-11">+ {t(+ 'Files already in knowledge bases keep their old vectors. Re-upload them to search with the new key or model.',+ )}+ </p>+ )}++ {sourceCount === 0 && (+ <div className="flex flex-col items-start gap-2">+ <p className="text-sm text-gray-11">+ {t(+ 'Add a key that serves all projects and supports embeddings, such as OpenAI, Google, Azure or OpenRouter.',+ )}+ </p>+ <Button asChild variant="outline" size="sm">+ <Link to="/platform/ai">{t('Add a provider key')}</Link>+ </Button>+ </div>+ )}++ {!selectedAiProvider && sourceCount > 0 && (<FormFieldcontrol={form.control}name="apiKey"@@ -361,6 +406,7 @@ function CapabilityForm({</Button><Buttontype="submit"+ disabled={sourceCount === 0}loading={isPending || isReenabling}{...adminControl(AdminControl.AI_CAPABILITY_SUBMIT)}>diff --git a/packages/web/src/app/routes/platform/setup/ai-capabilities/catalog.ts b/packages/web/src/app/routes/platform/setup/ai-capabilities/catalog.tsindex f2bf378769b..aaa37eb5fb9 100644--- a/packages/web/src/app/routes/platform/setup/ai-capabilities/catalog.ts+++ b/packages/web/src/app/routes/platform/setup/ai-capabilities/catalog.ts@@ -75,6 +75,14 @@ export const AI_TOOL_CATALOG: AiToolCapabilityInfo[] = [},],},+ {+ capability: AiToolCapability.EMBEDDINGS,+ name: t('Embeddings'),+ description: t(+ 'Index knowledge-base files so agents can search them. Pick one of your AI keys and its embedding model.',+ ),+ providers: [],+ },];function providerCovers({@@ -125,6 +133,9 @@ function servesByDefault({provider.modelScope !== 'selected' ||(!isNil(defaultImageModel) &&provider.modelIds.includes(defaultImageModel));+ if (capability === AiToolCapability.EMBEDDINGS) {+ return providerCovers({ capability, provider });+ }return (eligibleProviders({ capability, providers: [provider] }).length > 0 &&defaultModelAlloweddiff --git a/packages/web/src/app/routes/platform/setup/ai/capabilities-tab/index.tsx b/packages/web/src/app/routes/platform/setup/ai/capabilities-tab/index.tsxindex 89bc89e4699..2ca18719dba 100644--- a/packages/web/src/app/routes/platform/setup/ai/capabilities-tab/index.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/capabilities-tab/index.tsx@@ -14,6 +14,7 @@ import {Search,Trash2,} from 'lucide-react';+import { Link } from 'react-router-dom';import {AdminPageHeader,@@ -53,11 +54,11 @@ export function CapabilitiesTab() {} = aiProviderQueries.useAiProviderConfigs();const isError = configsFailed || providersFailed;const refetch = () => Promise.all([refetchConfigs(), refetchProviders()]);+ const creditsProvider = providers?.find(+ (provider) => provider.provider === AIProviderName.ACTIVEPIECES,+ );const chatProvider =- providers?.find((provider) => provider.enabledForChat) ??- providers?.find(- (provider) => provider.provider === AIProviderName.ACTIVEPIECES,- );+ providers?.find((provider) => provider.enabledForChat) ?? creditsProvider;const { mutate: remove } = aiToolConfigMutations.useDeleteAiToolConfig({onSuccess: () => refetchConfigs(),@@ -91,15 +92,13 @@ export function CapabilitiesTab() {capabilityInfo={capabilityInfo}config={config}providers={providers ?? []}- chatProviderFallback={- chatProvider &&- aiCapabilitySources.servesByDefault({- capability: capabilityInfo.capability,- provider: chatProvider,- })- ? chatProvider- : undefined- }+ chatProviderFallback={fallbackFor({+ capability: capabilityInfo.capability,+ candidates:+ capabilityInfo.capability === AiToolCapability.EMBEDDINGS+ ? [chatProvider, creditsProvider]+ : [chatProvider],+ })}onDelete={() => config && remove(config.id)}onSaved={() => refetchConfigs()}/>@@ -111,6 +110,20 @@ export function CapabilitiesTab() {);}+function fallbackFor({+ capability,+ candidates,+}: {+ capability: AiToolCapability;+ candidates: (AIProviderWithoutSensitiveData | undefined)[];+}): AIProviderWithoutSensitiveData | undefined {+ return candidates.find(+ (candidate): candidate is AIProviderWithoutSensitiveData =>+ candidate !== undefined &&+ aiCapabilitySources.servesByDefault({ capability, provider: candidate }),+ );+}+function CapabilityCard({capabilityInfo,config,@@ -127,6 +140,14 @@ function CapabilityCard({onSaved: () => void;}) {const Icon = CAPABILITY_ICON[capabilityInfo.capability];+ const isEmbeddings =+ capabilityInfo.capability === AiToolCapability.EMBEDDINGS;+ const needsProviderKey =+ isEmbeddings &&+ aiCapabilitySources.eligibleProviders({+ capability: capabilityInfo.capability,+ providers,+ }).length === 0;const connectedProvider = capabilityInfo.providers.find((provider) => provider.id === config?.provider,);@@ -173,9 +194,13 @@ function CapabilityCard({title={t('Reset {name}', { name: capabilityInfo.name })}message={chatProviderFallback- ? t('Chat goes back to using {provider}.', {- provider: chatProviderFallback.name,- })+ ? isEmbeddings+ ? t('Knowledge bases go back to using {provider}.', {+ provider: chatProviderFallback.name,+ })+ : t('Chat goes back to using {provider}.', {+ provider: chatProviderFallback.name,+ }): t('This removes the saved API key and disables this capability.',)@@ -200,24 +225,34 @@ function CapabilityCard({</p><div className="mt-auto flex items-center justify-between gap-4 border-t px-5 py-3"><span className="text-xs text-gray-11">- {inUse+ {isEmbeddings+ ? inUse+ ? t('Knowledge bases can index files')+ : t("Knowledge bases can't index files yet")+ : inUse? t('Available to the assistant'): t("The assistant can't do this yet")}</span>- <AiCapabilityDialog- capabilityInfo={capabilityInfo}- existingConfig={config}- defaultProviderId={chatProviderFallback?.id}- onSaved={onSaved}- >- <Button- variant="outline"- size="sm"- {...adminControl(AdminControl.AI_CAPABILITY_OPEN)}- >- {inUse ? t('Change') : t('Connect')}+ {needsProviderKey ? (+ <Button asChild variant="outline" size="sm">+ <Link to="/platform/ai">{t('Add a provider key')}</Link></Button>- </AiCapabilityDialog>+ ) : (+ <AiCapabilityDialog+ capabilityInfo={capabilityInfo}+ existingConfig={config}+ defaultProviderId={chatProviderFallback?.id}+ onSaved={onSaved}+ >+ <Button+ variant="outline"+ size="sm"+ {...adminControl(AdminControl.AI_CAPABILITY_OPEN)}+ >+ {inUse ? t('Change') : t('Connect')}+ </Button>+ </AiCapabilityDialog>+ )}</div></div>);diff --git a/packages/web/src/app/routes/platform/setup/ai/index.tsx b/packages/web/src/app/routes/platform/setup/ai/index.tsxindex ace826958ff..ba1480e702f 100644--- a/packages/web/src/app/routes/platform/setup/ai/index.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/index.tsx@@ -1,5 +1,5 @@import { ApEdition, ApFlagId } from '@activepieces/shared';-import { Navigate, useSearchParams } from 'react-router-dom';+import { Navigate } from 'react-router-dom';import { AdminPage } from '@/app/components/admin';import { flagsHooks } from '@/hooks/flags-hooks';@@ -14,16 +14,13 @@ export default function AIProvidersPage({ section }: AIProvidersPageProps) {function AICenter({ section }: { section: AISection }) {const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);- const [searchParams] = useSearchParams();- const showsSettings =- section === 'capabilities' || searchParams.has('config');if (section === 'capabilities' && edition === ApEdition.COMMUNITY) {return <Navigate to="/platform/ai" replace />;}return (- <AdminPage width={showsSettings ? 'content' : 'full'}>+ <AdminPage width="wide">{section === 'providers' ? (<ProvidersTab />) : section === 'tiers' ? (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.tsxindex 005dc395dba..79026a0921f 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@@ -146,7 +146,6 @@ export function ConfigDetail({const metaLine = [info.name,usedByTierCount > 0 && t('usedByTiersCount', { count: usedByTierCount }),- config.enabledForChat && t('Chat provider'),statusDetail,].filter(Boolean)diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/default-chat-model-card.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/default-chat-model-card.tsxnew file mode 100644index 00000000000..8c47ae48a05--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/default-chat-model-card.tsx@@ -0,0 +1,301 @@+import { AIProviderName, isNil } from '@activepieces/core-utils';+import {+ AI_PROVIDER_CAPABILITIES,+ AIProviderWithoutSensitiveData,+ AiToolCapability,+ ModelChoice,+ ModelOptions,+ PlatformModelTier,+} from '@activepieces/shared';+import { t } from 'i18next';+import { MessageSquare, TriangleAlert } from 'lucide-react';+import { useMemo } from 'react';++import { SettingsPanel, SettingsRow } from '@/app/components/admin';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import { ModelPicker, modelPickerUtils } from '@/features/agents';+import { aiModelHooks } from '@/features/agents/ai-model/hooks';+import { modelMeta } from '@/features/agents/ai-model/model-meta';+import { aiToolConfigQueries } from '@/features/platform-admin';+import { platformModelTierMutations } from '@/features/platform-admin/hooks/platform-model-tier-hooks';+import { platformConfigurationHooks } from '@/hooks/platform-configuration-hooks';+import { AdminControl, adminControl } from '@/lib/admin-control';++export function DefaultChatModelCard({+ configs,+ tiers,+ projectIds,+}: {+ configs: AIProviderWithoutSensitiveData[];+ tiers: PlatformModelTier[];+ projectIds: string[];+}) {+ const { data: configuration } =+ platformConfigurationHooks.useCurrentPlatformConfiguration();+ const { data: options } = aiModelHooks.useModelOptions({ surface: 'chat' });+ const { data: toolConfigs } = aiToolConfigQueries.useAiToolConfigs();+ const { mutate: save, isPending } =+ platformModelTierMutations.useSetDefaultChatModel();+ const value = configuration?.defaultChatModel ?? null;+ const configsById = useMemo(+ () => new Map(configs.map((config) => [config.id, config])),+ [configs],+ );+ const hasEmbeddingsKey = (toolConfigs ?? []).some(+ (toolConfig) =>+ toolConfig.capability === AiToolCapability.EMBEDDINGS &&+ toolConfig.enabled,+ );+ const status = isNil(options)+ ? null+ : statusOf({+ value,+ options,+ tiers,+ configsById,+ projectIds,+ hasEmbeddingsKey,+ });++ return (+ <SettingsPanel flush>+ <SettingsRow+ icon={<MessageSquare />}+ title={t('Default chat model')}+ description={t('New chats start on this model.')}+ >+ <div className="flex items-center gap-2">+ <div className="flex min-w-7 shrink-0 items-center justify-end">+ {!isNil(status) && status.unavailable && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ className="text-warning-11"+ onClick={() => save(null)}+ >+ {t('Use default')}+ </Button>+ </TooltipTrigger>+ <TooltipContent>{status.warnings.join(' ')}</TooltipContent>+ </Tooltip>+ )}+ {!isNil(status) &&+ !status.unavailable &&+ status.warnings.length > 0 && (+ <Tooltip>+ <TooltipTrigger asChild>+ <TriangleAlert+ className="size-4 text-warning-11"+ aria-label={status.warnings.join(' ')}+ />+ </TooltipTrigger>+ <TooltipContent>{status.warnings.join(' ')}</TooltipContent>+ </Tooltip>+ )}+ </div>+ <div+ className="w-64"+ {...adminControl(AdminControl.AI_DEFAULT_CHAT_MODEL_SELECT)}+ >+ {isNil(configuration) ? (+ <Skeleton className="h-9 w-full" />+ ) : (+ <ModelPicker+ surface="chat"+ value={value}+ disabled={isPending}+ placeholder={status?.placeholder}+ onChange={(choice) =>+ save(sameChoice({ a: choice, b: value }) ? null : choice)+ }+ />+ )}+ </div>+ </div>+ </SettingsRow>+ </SettingsPanel>+ );+}++function statusOf({+ value,+ options,+ tiers,+ configsById,+ projectIds,+ hasEmbeddingsKey,+}: {+ value: ModelChoice | null;+ options: ModelOptions;+ tiers: PlatformModelTier[];+ configsById: Map<string, AIProviderWithoutSensitiveData>;+ projectIds: string[];+ hasEmbeddingsKey: boolean;+}): CardStatus {+ const fallback = isNil(options.defaultChoice)+ ? null+ : labelOf({ choice: options.defaultChoice, options });+ if (isNil(value)) {+ return {+ placeholder: isNil(fallback)+ ? t('Not set')+ : t('Not set · uses {model}', { model: fallback }),+ warnings: [],+ unavailable: false,+ };+ }+ if (modelPickerUtils.isUnavailable({ options, value })) {+ return {+ placeholder: undefined,+ warnings: [+ isNil(fallback)+ ? t('This model is no longer available.')+ : t('This model is no longer available. New chats use {model}.', {+ model: fallback,+ }),+ ],+ unavailable: true,+ };+ }+ const missing = projectsWithout({ value, tiers, configsById, projectIds });+ const warnings = [+ ...(missing > 0+ ? [+ t(+ 'Not available in {count, plural, =1 {1 project} other {# projects}}.',+ { count: missing },+ ),+ ]+ : []),+ ...(!hasEmbeddingsKey &&+ isNil(options.credits) &&+ !canEmbed({ provider: keyProviderOf({ value, tiers, configsById }) })+ ? [+ t(+ "This key can't index knowledge-base files. Set an Embeddings key in Capabilities.",+ ),+ ]+ : []),+ ];+ return { placeholder: undefined, warnings, unavailable: false };+}++function keyProviderOf({+ value,+ tiers,+ configsById,+}: {+ value: ModelChoice;+ tiers: PlatformModelTier[];+ configsById: Map<string, AIProviderWithoutSensitiveData>;+}): AIProviderName | undefined {+ if (value.type === 'model') {+ return value.provider;+ }+ const mainConfigId = tiers.find((tier) => tier.id === value.tierId)+ ?.entries[0]?.configId;+ return isNil(mainConfigId)+ ? undefined+ : configsById.get(mainConfigId)?.provider;+}++function canEmbed({+ provider,+}: {+ provider: AIProviderName | undefined;+}): boolean {+ return (+ isNil(provider) || AI_PROVIDER_CAPABILITIES[provider].supportsEmbedding+ );+}++function sameChoice({+ a,+ b,+}: {+ a: ModelChoice;+ b: ModelChoice | null;+}): boolean {+ if (isNil(b) || a.type !== b.type) {+ return false;+ }+ if (a.type === 'tier' && b.type === 'tier') {+ return a.tierId === b.tierId;+ }+ return (+ a.type === 'model' &&+ b.type === 'model' &&+ a.modelId === b.modelId &&+ (a.providerConfigId === b.providerConfigId ||+ (a.provider === AIProviderName.ACTIVEPIECES &&+ b.provider === AIProviderName.ACTIVEPIECES))+ );+}++function projectsWithout({+ value,+ tiers,+ configsById,+ projectIds,+}: {+ value: ModelChoice;+ tiers: PlatformModelTier[];+ configsById: Map<string, AIProviderWithoutSensitiveData>;+ projectIds: string[];+}): number {+ if (value.type === 'tier') {+ const tier = tiers.find((candidate) => candidate.id === value.tierId);+ return isNil(tier)+ ? 0+ : modelMeta.tierReach({ tier, configsById, projectIds }).unavailableCount;+ }+ const config = configsById.get(value.providerConfigId);+ if (isNil(config)) {+ return 0;+ }+ const entry = { configId: value.providerConfigId, modelId: value.modelId };+ return projectIds.filter(+ (projectId) => !modelMeta.entryRunsIn({ entry, config, projectId }),+ ).length;+}++function labelOf({+ choice,+ options,+}: {+ choice: ModelChoice;+ options: ModelOptions;+}): string | null {+ if (choice.type === 'tier') {+ return (+ options.tiers.find((tier) => tier.id === choice.tierId)?.name ?? null+ );+ }+ if (choice.provider === AIProviderName.ACTIVEPIECES) {+ return (+ options.credits?.tiers.find((tier) => tier.id === choice.modelId)+ ?.label ?? null+ );+ }+ return (+ options.keys+ .find((key) => key.providerConfigId === choice.providerConfigId)+ ?.models.find((model) => model.id === choice.modelId)?.name ?? null+ );+}++type CardStatus = {+ placeholder: string | undefined;+ warnings: string[];+ unavailable: boolean;+};++export const defaultChatModelCardUtils = { statusOf, sameChoice };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.tsxindex 0888d7223d6..8469d48dbb6 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@@ -7,14 +7,7 @@ import {} from '@activepieces/shared';import { useQueryClient } from '@tanstack/react-query';import { t } from 'i18next';-import {- Bot,- ChevronRight,- Lock,- MessageSquare,- Plus,- Trash2,-} from 'lucide-react';+import { Bot, ChevronRight, Lock, Plus, Trash2 } from 'lucide-react';import { useState } from 'react';import { useSearchParams } from 'react-router-dom';import { toast } from 'sonner';@@ -24,7 +17,6 @@ import {AdminPageHeader,AdminSection,SettingsPanel,- SettingsRow,adminPageResources,adminSurface,} from '@/app/components/admin';@@ -33,13 +25,6 @@ import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state'import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Button } from '@/components/ui/button';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select';import { Skeleton } from '@/components/ui/skeleton';import {Tooltip,@@ -65,6 +50,7 @@ import { cn } from '@/lib/utils';import { ConfigDetail } from './config-detail';import { ConnectProviderDialog } from './connect-provider-dialog';+import { DefaultChatModelCard } from './default-chat-model-card';import { KeyStatusBadge, keyStatusText } from './key-status';import { ProjectSwatch } from './project-selection-panel';import { ProviderLogo } from './provider-logo';@@ -94,17 +80,10 @@ export function ProvidersTab() {const configs = (providers ?? []).filter((provider) => provider.provider !== AIProviderName.ACTIVEPIECES,);- const chatProviderRow = (providers ?? []).find(- (provider) => provider.enabledForChat,+ const hasCredits = (providers ?? []).some(+ (provider) => provider.provider === AIProviderName.ACTIVEPIECES,);- const { mutate: toggleChatProvider, isPending: isSwitchingChatProvider } =- aiProviderMutations.useToggleChatProvider({- onSuccess: () => {- refetch();- toast.success(t('Chat provider updated'));- },- });const { mutateAsync: deleteProvider } =aiProviderMutations.useDeleteAiProvider({onSuccess: () => refetch(),@@ -181,12 +160,6 @@ export function ProvidersTab() {}setCredentialsVersion((version) => version + 1);};- const selectChatConfig = (configId: string) => {- const row = (providers ?? []).find((config) => config.id === configId);- if (row) {- toggleChatProvider({ providerId: row.id, displayName: row.name });- }- };const connectedProviders = [...new Set(configs.map((c) => c.provider))];const available = SUPPORTED_AI_PROVIDERS.filter(@@ -263,6 +236,13 @@ export function ProvidersTab() {)}</AdminPageHeader>+ {!locked && !isProvidersError && (configs.length > 0 || hasCredits) && (+ <DefaultChatModelCard+ configs={configs}+ tiers={tiers ?? []}+ projectIds={(projects ?? []).map((project) => project.id)}+ />+ )}{isProvidersError ? (<DataFetchErrorState entity={t('AI providers')} onRetry={refetch} />) : configs.length === 0 ? (@@ -270,14 +250,6 @@ export function ProvidersTab() {) : (<>{locked && <LockedProvidersAlert />}- {!locked && (- <ChatProviderRow- configs={providers ?? []}- value={chatProviderRow?.id ?? null}- isSwitching={isSwitchingChatProvider}- onChange={selectChatConfig}- />- )}{connectedProviders.map((provider) => (<ProviderGroupkey={provider}@@ -494,11 +466,6 @@ function ConfigRow({<p className="truncate text-sm font-medium text-gray-12">{config.name}</p>- {config.enabledForChat && (- <span className="shrink-0 rounded-md bg-accent-3 px-2 py-px text-xs font-medium text-accent-11">- {t('Chat')}- </span>- )}<KeyStatusBadge status={config.status} /></div><Tooltip>@@ -618,53 +585,6 @@ function ProjectChips({);}-function ChatProviderRow({- configs,- value,- isSwitching,- onChange,-}: {- configs: AIProviderWithoutSensitiveData[];- value: string | null;- isSwitching: boolean;- onChange: (configId: string) => void;-}) {- return (- <SettingsPanel flush>- <SettingsRow- icon={<MessageSquare />}- title={t('Chat provider')}- description={t(- 'Powers the built-in chat for everyone on this platform',- )}- >- <Select- value={value ?? undefined}- onValueChange={onChange}- disabled={isSwitching}- >- <SelectTrigger className="w-52">- <SelectValue placeholder={t('Select provider')} />- </SelectTrigger>- <SelectContent>- {configs.map((config) => {- const info = providerInfoOf({ provider: config.provider });- return (- <SelectItem key={config.id} value={config.id}>- <div className="flex items-center gap-2">- {info && <ProviderLogo info={info} size="sm" />}- <span className="truncate">{config.name}</span>- </div>- </SelectItem>- );- })}- </SelectContent>- </Select>- </SettingsRow>- </SettingsPanel>- );-}-function EmptyProviders({onConnect,}: {diff --git a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-card.tsx b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-card.tsxindex c078fafe7b4..d8a5f80b461 100644--- a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-card.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/tier-card.tsx@@ -11,7 +11,6 @@ import {Brain,Info,Loader2,- MessageSquare,MoreHorizontal,Pencil,Plus,@@ -170,11 +169,6 @@ export function TierCard({{thinkingChip !== undefined && (<TierTag icon={Brain}>{thinkingChip}</TierTag>)}- {tools === 'recommended' && (- <TierTag icon={MessageSquare}>- {t('Recommended for chat')}- </TierTag>- )}{showSpinner && (<Loader2className="size-3.5 animate-spin text-gray-10"diff --git a/packages/web/src/features/agents/agent-tools/components/knowledge-base-tool.tsx b/packages/web/src/features/agents/agent-tools/components/knowledge-base-tool.tsxindex 13aea131307..12038bc113b 100644--- a/packages/web/src/features/agents/agent-tools/components/knowledge-base-tool.tsx+++ b/packages/web/src/features/agents/agent-tools/components/knowledge-base-tool.tsx@@ -7,6 +7,7 @@ import {} from '@activepieces/shared';import { t } from 'i18next';import { BookOpen, FileText, Table2, X } from 'lucide-react';+import { Link } from 'react-router-dom';import { Button } from '@/components/ui/button';import {@@ -14,12 +15,12 @@ import {TooltipContent,TooltipTrigger,} from '@/components/ui/tooltip';-import { PROVIDER_EMBEDDING_MODELS } from '@/features/agents';-import { aiProviderQueries } from '@/features/platform-admin/hooks/ai-provider-hooks';+import { useIsPlatformAdmin } from '@/hooks/authorization-hooks';import { flagsHooks } from '@/hooks/flags-hooks';import { cn } from '@/lib/utils';import { AgentKnowledgeBaseDialog } from '../knowledge-base-dialog';+import { useKnowledgeBaseEmbeddingSource } from '../knowledge-base-dialog/knowledge-base-hooks';import { useKnowledgeBaseToolDialogStore } from '../stores/knowledge-base-tools';import { AddKnowledgeBaseDropdown } from './add-knowledge-base-dropdown';@@ -85,6 +86,47 @@ function KnowledgeBaseToolPills({);}+export function NoEmbeddingSourceNote({+ className,+ isError = false,+ onRetry,+}: {+ className?: string;+ isError?: boolean;+ onRetry?: () => void;+}) {+ const isAdmin = useIsPlatformAdmin();+ if (isError) {+ return (+ <p className={className}>+ {t("Couldn't check whether files can be indexed.")}{' '}+ <button+ type="button"+ className="font-medium text-gray-12 underline underline-offset-2"+ onClick={onRetry}+ >+ {t('Retry')}+ </button>+ </p>+ );+ }+ return (+ <p className={className}>+ {t('No AI key can index files for this project yet.')}{' '}+ {isAdmin ? (+ <Link+ to="/platform/ai/capabilities"+ className="font-medium text-gray-12 underline underline-offset-2"+ >+ {t('Pick an embedding model')}+ </Link>+ ) : (+ t('Ask your admin to set an Embeddings model.')+ )}+ </p>+ );+}+export const KnowledgeBaseSection = ({disabled,tools,@@ -93,10 +135,12 @@ export const KnowledgeBaseSection = ({onToolsUpdate,layout = 'card',}: KnowledgeBaseSectionProps) => {- const { data: chatProvider } = aiProviderQueries.useChatProvider();- const embeddingProvider = chatProvider?.provider;- const supportsEmbeddings =- !isNil(embeddingProvider) && !!PROVIDER_EMBEDDING_MODELS[embeddingProvider];+ const {+ data: embeddingSource,+ isError: embeddingSourceFailed,+ refetch: retryEmbeddingSource,+ } = useKnowledgeBaseEmbeddingSource();+ const supportsEmbeddings = !isNil(embeddingSource?.provider);const { data: pgvectorAvailable } = flagsHooks.useFlag<boolean>(ApFlagId.PGVECTOR_AVAILABLE,);@@ -132,11 +176,11 @@ export const KnowledgeBaseSection = ({<AddKnowledgeBaseDropdown disabled={disabled} /></div>) : (- <p className="text-xs text-gray-11 mt-3">- {t(- 'Your chat provider does not support embeddings. Switch it to a provider like OpenAI or Google for knowledge base to work.',- )}- </p>+ <NoEmbeddingSourceNote+ className="text-xs text-gray-11 mt-3"+ isError={embeddingSourceFailed}+ onRetry={() => retryEmbeddingSource().catch(() => undefined)}+ />)}</div>) : asRows ? (@@ -145,11 +189,11 @@ export const KnowledgeBaseSection = ({<AddRow label={t('Add knowledge')} disabled={disabled} /></AddKnowledgeBaseDropdown>) : (- <p className="text-xs leading-4 text-gray-11">- {t(- 'Knowledge base requires a provider that supports embeddings, such as OpenAI or Google.',- )}- </p>+ <NoEmbeddingSourceNote+ className="text-xs leading-4 text-gray-11"+ isError={embeddingSourceFailed}+ onRetry={() => retryEmbeddingSource().catch(() => undefined)}+ />)) : (<div className="flex flex-col items-center justify-center gap-4 rounded-xl border bg-panel px-4 py-8 text-center">@@ -166,11 +210,11 @@ export const KnowledgeBaseSection = ({<AddKnowledgeBaseDropdown disabled={disabled} /></>) : (- <p className="text-sm text-gray-11">- {t(- 'Knowledge base requires a provider that supports embeddings, such as OpenAI or Google.',- )}- </p>+ <NoEmbeddingSourceNote+ className="text-sm text-gray-11"+ isError={embeddingSourceFailed}+ onRetry={() => retryEmbeddingSource().catch(() => undefined)}+ />)}</div>)}diff --git a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-api.ts b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-api.tsindex db0c5d7f529..af99e5a109d 100644--- a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-api.ts+++ b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-api.ts@@ -1,4 +1,7 @@-import { KnowledgeBaseFile } from '@activepieces/shared';+import {+ KnowledgeBaseEmbeddingSource,+ KnowledgeBaseFile,+} from '@activepieces/shared';import { api } from '@/lib/api';import { authenticationSession } from '@/lib/authentication-session';@@ -10,6 +13,13 @@ export const knowledgeBaseApi = {projectId,});},+ embeddingSource(): Promise<KnowledgeBaseEmbeddingSource> {+ const projectId = authenticationSession.getProjectId()!;+ return api.get<KnowledgeBaseEmbeddingSource>(+ '/v1/knowledge-base/files/embedding-source',+ { projectId },+ );+ },upload(formData: FormData): Promise<KnowledgeBaseFile> {const projectId = authenticationSession.getProjectId()!;return api.any<KnowledgeBaseFile>(diff --git a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.ts b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.tsindex 66b2db1fb4a..a996ea7af87 100644--- a/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.ts+++ b/packages/web/src/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks.ts@@ -1,8 +1,13 @@-import { KnowledgeBaseFile } from '@activepieces/shared';+import {+ ApFlagId,+ KnowledgeBaseEmbeddingSource,+ KnowledgeBaseFile,+} from '@activepieces/shared';import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { t } from 'i18next';import { toast } from 'sonner';+import { flagsHooks } from '@/hooks/flags-hooks';import { authenticationSession } from '@/lib/authentication-session';import { validationUtils } from '@/lib/validation-utils';@@ -16,6 +21,18 @@ export const useKnowledgeBaseFiles = () => {});};+export const useKnowledgeBaseEmbeddingSource = () => {+ const projectId = authenticationSession.getProjectId();+ const { data: pgvectorAvailable } = flagsHooks.useFlag<boolean>(+ ApFlagId.PGVECTOR_AVAILABLE,+ );+ return useQuery<KnowledgeBaseEmbeddingSource>({+ queryKey: ['knowledge-base-embedding-source', projectId],+ queryFn: () => knowledgeBaseApi.embeddingSource(),+ enabled: projectId !== null && pgvectorAvailable === true,+ });+};+export const useUploadKnowledgeBaseFile = () => {const queryClient = useQueryClient();const projectId = authenticationSession.getProjectId();@@ -50,7 +67,7 @@ function uploadErrorMessage(error: unknown): string {switch (error.response?.data?.params?.message) {case 'KNOWLEDGE_BASE_NEEDS_AI_PROVIDER':return t(- 'Add an AI provider before uploading. Files are indexed when uploaded so agents can search them.',+ 'No AI key can index files yet. Set an Embeddings model in AI settings → Capabilities, or ask your admin.',);case 'KNOWLEDGE_BASE_FILE_HAS_NO_TEXT':return t('This file has no text that can be searched.');diff --git a/packages/web/src/features/agents/ai-model/hooks.ts b/packages/web/src/features/agents/ai-model/hooks.tsindex f09df2c1637..d5af977bdbe 100644--- a/packages/web/src/features/agents/ai-model/hooks.ts+++ b/packages/web/src/features/agents/ai-model/hooks.ts@@ -8,15 +8,20 @@ export const aiModelHooks = {projectId,surface,tierId,+ enabled = true,}: {- projectId: string;+ projectId?: string;surface: ModelOptionsSurface;tierId?: string;+ enabled?: boolean;}) =>useQuery({- queryKey: ['ai-model-options', projectId, surface, tierId],+ enabled,+ queryKey: ['ai-model-options', projectId ?? 'platform', surface, tierId],queryFn: () =>- aiProviderApi.listModelOptions({ projectId, surface, tierId }),+ projectId === undefined+ ? aiProviderApi.listPlatformModelOptions({ surface })+ : aiProviderApi.listModelOptions({ projectId, surface, tierId }),placeholderData: keepPreviousData,}),};diff --git a/packages/web/src/features/agents/ai-model/index.ts b/packages/web/src/features/agents/ai-model/index.tsdeleted file mode 100644index 2c0a3975459..00000000000--- a/packages/web/src/features/agents/ai-model/index.ts+++ /dev/null@@ -1,11 +0,0 @@-import { AIProviderName } from '@activepieces/core-utils';--export const PROVIDER_EMBEDDING_MODELS: Partial<- Record<AIProviderName, string>-> = {- [AIProviderName.OPENAI]: 'text-embedding-3-small',- [AIProviderName.GOOGLE]: 'text-embedding-004',- [AIProviderName.AZURE]: 'text-embedding-3-small',- [AIProviderName.ACTIVEPIECES]: 'text-embedding-3-small',- [AIProviderName.OPENROUTER]: 'openai/text-embedding-3-small',-};diff --git a/packages/web/src/features/agents/ai-model/model-meta.ts b/packages/web/src/features/agents/ai-model/model-meta.tsindex da1ed9291f3..e944d96c406 100644--- a/packages/web/src/features/agents/ai-model/model-meta.ts+++ b/packages/web/src/features/agents/ai-model/model-meta.ts@@ -3,7 +3,6 @@ import {AiProviderKeyStatus,AIProviderModel,AIProviderModelType,- aiProviderUtils,AIProviderWithoutSensitiveData,PlatformModelTier,PlatformModelTierEntry,@@ -420,25 +419,13 @@ function keyScopeImpact({}function toolsVerdict({- config,- entry,model,}: {config: AIProviderWithoutSensitiveData | undefined;entry: PlatformModelTierEntry | undefined;model: AIProviderModel | undefined;}): ToolsVerdict {- if (model?.metadata?.supportsToolCalling === false) {- return 'noTools';- }- const curated =- config === undefined- ? undefined- : aiProviderUtils.getCuratedChatModels({ provider: config.provider });- return entry !== undefined &&- curated?.some((curatedModel) => curatedModel.id === entry.modelId) === true- ? 'recommended'- : null;+ return model?.metadata?.supportsToolCalling === false ? 'noTools' : null;}export const modelMeta = {@@ -510,4 +497,4 @@ export type KeyScopeImpact = {skippedProjects: number;};-export type ToolsVerdict = 'noTools' | 'recommended' | null;+export type ToolsVerdict = 'noTools' | null;diff --git a/packages/web/src/features/agents/ai-model/model-picker-popover.tsx b/packages/web/src/features/agents/ai-model/model-picker-popover.tsxindex 6e84e814359..d583cf0b1f6 100644--- a/packages/web/src/features/agents/ai-model/model-picker-popover.tsx+++ b/packages/web/src/features/agents/ai-model/model-picker-popover.tsx@@ -34,6 +34,7 @@ export function ModelPickerPopover<T>({open,onOpenChange,align = 'end',+ side,anchorOnly = false,matchTriggerWidth = false,detail,@@ -285,6 +286,7 @@ export function ModelPickerPopover<T>({)}<PopoverContentalign={align}+ side={side}className={cn('relative p-0',matchTriggerWidth@@ -476,6 +478,7 @@ type ModelPickerPopoverProps<T> = {open: boolean;onOpenChange: (open: boolean) => void;align?: 'start' | 'end';+ side?: 'top' | 'bottom';anchorOnly?: boolean;matchTriggerWidth?: boolean;detail?: (item: ModelPickerItem<T>) => ReactNode;diff --git a/packages/web/src/features/agents/ai-model/model-picker.tsx b/packages/web/src/features/agents/ai-model/model-picker.tsxindex 4a6c2cfb326..1e2963cb3c6 100644--- a/packages/web/src/features/agents/ai-model/model-picker.tsx+++ b/packages/web/src/features/agents/ai-model/model-picker.tsx@@ -37,6 +37,8 @@ export function ModelPicker({onChange,disabled = false,withTiers = true,+ variant = 'field',+ placeholder,className,}: ModelPickerProps) {const [open, setOpen] = useState(false);@@ -57,12 +59,19 @@ export function ModelPicker({);if (isLoading) {- return <Skeleton className={cn('h-9 w-full', className)} />;+ return (+ <Skeleton+ className={cn(+ variant === 'pill' ? 'h-8 w-24 rounded-full' : 'h-9 w-full',+ className,+ )}+ />+ );}return (<ModelPickerPopover- matchTriggerWidth+ matchTriggerWidth={variant === 'field'}groups={view?.groups ?? []}notices={isError ? (@@ -85,7 +94,8 @@ export function ModelPicker({onPick={(choice) => onChange(choice)}open={open}onOpenChange={setOpen}- align="start"+ align={variant === 'pill' ? 'end' : 'start'}+ side={variant === 'pill' ? 'top' : undefined}detail={(item) => {const detail = view?.detailById.get(item.id);return isNil(detail) ? null : <ModelDetailCard detail={detail} />;@@ -96,12 +106,26 @@ export function ModelPicker({disabled={disabled}data-testid="model-picker-trigger"className={cn(- 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border bg-panel px-2.5 text-left text-sm transition-colors hover:bg-gray-2 disabled:pointer-events-none disabled:opacity-50',+ variant === 'pill'+ ? 'flex h-8 min-w-0 max-w-64 items-center gap-1.5 rounded-full px-2.5 text-left text-xs transition-colors hover:bg-gray-3 disabled:pointer-events-none disabled:opacity-50'+ : 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border bg-panel px-2.5 text-left text-sm transition-colors hover:bg-gray-2 disabled:pointer-events-none disabled:opacity-50',className,)}>- <TriggerContent current={view?.current ?? emptyPick()} />- <ChevronDown className="ml-auto size-4 shrink-0 text-gray-10" />+ <TriggerContent+ current={+ (view?.current.kind ?? 'empty') === 'empty' && !isNil(placeholder)+ ? { ...emptyPick(), label: placeholder }+ : view?.current ?? emptyPick()+ }+ compact={variant === 'pill'}+ />+ <ChevronDown+ className={cn(+ 'ml-auto shrink-0 text-gray-10',+ variant === 'pill' ? 'size-3.5' : 'size-4',+ )}+ /></button></ModelPickerPopover>);@@ -227,9 +251,9 @@ export function modelPickerView({id: 'tiers',section: 'tiers',sectionHeading: (- <SectionHeading dot="bg-swatch-12-mark" label={t('Your tiers')} />+ <SectionHeading dot="bg-swatch-12-mark" label={t('Tiers')} />),- heading: t('Your tiers'),+ heading: t('Tiers'),items: tierItems.map(({ item }) => item),},]),@@ -249,9 +273,7 @@ export function modelPickerView({...keyGroups.map(({ key, info, models }) => ({id: `key:${key.providerConfigId}`,section: 'keys',- sectionHeading: (- <SectionHeading dot="bg-gray-10" label={t('Your keys')} />- ),+ sectionHeading: <SectionHeading dot="bg-gray-10" label={t('Models')} />,heading: (<><KeyLogo logoUrl={info.logoUrl} name={info.name} />@@ -402,13 +424,20 @@ function unavailablePick({ label }: { label: string }): CurrentPick {};}-function TriggerContent({ current }: { current: CurrentPick }) {+function TriggerContent({+ current,+ compact,+}: {+ current: CurrentPick;+ compact: boolean;+}) {const warn = current.kind === 'unavailable' || current.kind === 'hidden';return (<>{current.leading}<span className="truncate font-medium text-gray-12">{current.label}</span>{current.source !== '' &&+ (warn || !compact) &&(warn ? (<span className="shrink-0 rounded-full bg-warning-3 px-1.5 py-0.5 text-xs leading-none text-warning-11">{current.source}@@ -537,11 +566,24 @@ type PickerView = {};type ModelPickerProps = {- projectId: string;+ projectId?: string;surface: ModelOptionsSurface;value: ModelChoice | null;onChange: (choice: ModelChoice) => void;disabled?: boolean;withTiers?: boolean;+ variant?: 'field' | 'pill';+ placeholder?: string;className?: string;};++export const modelPickerUtils = {+ isUnavailable: ({+ options,+ value,+ }: {+ options: ModelOptions;+ value: ModelChoice | null;+ }): boolean =>+ resolveCurrent({ options, shown: value }).kind === 'unavailable',+};diff --git a/packages/web/src/features/agents/index.ts b/packages/web/src/features/agents/index.tsindex 3e662c44eae..3ee2ed618af 100644--- a/packages/web/src/features/agents/index.ts+++ b/packages/web/src/features/agents/index.ts@@ -2,7 +2,11 @@ export { AgentTimeline } from './agent-timeline';export { AddToolDropdown } from './agent-tools/add-agent-tool-dropwdown';export { AgentFlowToolComponent } from './agent-tools/components/flow-tool';export { AgentMcpToolComponent } from './agent-tools/components/mcp-tool';-export { KnowledgeBaseSection } from './agent-tools/components/knowledge-base-tool';+export {+ KnowledgeBaseSection,+ NoEmbeddingSourceNote,+} from './agent-tools/components/knowledge-base-tool';+export { useKnowledgeBaseEmbeddingSource } from './agent-tools/knowledge-base-dialog/knowledge-base-hooks';export { AgentPieceToolComponent } from './agent-tools/components/piece-tool';export { AgentFlowToolDialog } from './agent-tools/flow-tool-dialog';export { AgentMcpDialog } from './agent-tools/mcp-tool-dialog';@@ -10,8 +14,7 @@ export { ConnectionDropdown } from './agent-tools/piece-tool-dialog/connection-sexport { PieceActionsList } from './agent-tools/piece-tool-dialog/dialog-pages/piece-actions-list';export { PiecesList } from './agent-tools/piece-tool-dialog/dialog-pages/pieces-list';export { usePieceToolsDialogStore } from './agent-tools/stores/pieces-tools';-export { PROVIDER_EMBEDDING_MODELS } from './ai-model';-export { ModelPicker } from './ai-model/model-picker';+export { ModelPicker, modelPickerUtils } from './ai-model/model-picker';export { SUPPORTED_AI_PROVIDERS } from './ai-providers';export type { AiProviderInfo } from './ai-providers';export { AgentStructuredOutput } from './structured-output';diff --git a/packages/web/src/features/chat/lib/chat-utils.ts b/packages/web/src/features/chat/lib/chat-utils.tsindex 4c2a9c98d27..eacf93f4239 100644--- a/packages/web/src/features/chat/lib/chat-utils.ts+++ b/packages/web/src/features/chat/lib/chat-utils.ts@@ -1,12 +1,13 @@-import { AIProviderName, isObject } from '@activepieces/core-utils';+import { AIProviderName, isNil, isObject } from '@activepieces/core-utils';import {- aiProviderUtils,ActionReceiptEvent,BuildPlanEvent,BuildPlanStep,AgentHistoryMessage,FileProducedEvent,ImageGeneratedEvent,+ ModelChoice,+ ModelOptions,PersistedAgentMessage,PersistedAgentPart,PersistedAgentPartType,@@ -580,20 +581,82 @@ function reopensSameConversation({return current === next;}-function newChatModelName({- provider,+function choiceOf({+ pick,+ options,}: {- provider: AIProviderName | undefined;-}): string | null {- if (provider === undefined) {+ pick: ChatModelPick | null;+ options: ModelOptions;+}): ModelChoice | null {+ if (isNil(pick)) {return null;}- return aiProviderUtils.getCuratedChatModels({ provider })?.[0]?.id ?? null;+ if (!isNil(pick.modelTierId)) {+ return { type: 'tier', tierId: pick.modelTierId };+ }+ if (isNil(pick.modelName)) {+ return null;+ }+ if (isNil(pick.providerConfigId)) {+ return legacyChoiceOf({ modelName: pick.modelName, options });+ }+ const provider =+ pick.providerConfigId === options.credits?.providerConfigId+ ? AIProviderName.ACTIVEPIECES+ : options.keys.find(+ (key) => key.providerConfigId === pick.providerConfigId,+ )?.provider ?? AIProviderName.CUSTOM;+ return {+ type: 'model',+ provider,+ providerConfigId: pick.providerConfigId,+ modelId: pick.modelName,+ };+}++function legacyChoiceOf({+ modelName,+ options,+}: {+ modelName: string;+ options: ModelOptions;+}): ModelChoice | null {+ const credits = options.credits;+ if (!isNil(credits) && credits.tiers.some((tier) => tier.id === modelName)) {+ return {+ type: 'model',+ provider: AIProviderName.ACTIVEPIECES,+ providerConfigId: credits.providerConfigId,+ modelId: modelName,+ };+ }+ const key = options.keys.find((candidate) =>+ candidate.models.some((model) => model.id === modelName),+ );+ return isNil(key)+ ? null+ : {+ type: 'model',+ provider: key.provider,+ providerConfigId: key.providerConfigId,+ modelId: modelName,+ };+}++function pickOf({ choice }: { choice: ModelChoice }): ChatModelPick {+ return choice.type === 'tier'+ ? { modelTierId: choice.tierId, providerConfigId: null, modelName: null }+ : {+ modelTierId: null,+ providerConfigId: choice.providerConfigId,+ modelName: choice.modelId,+ };}export const chatUtils = {newChatEvent: 'ap:new-chat',- newChatModelName,+ choiceOf,+ pickOf,reopensSameConversation,sanitizeTitle,formatToolLabel: ({ part }: { part: AnyToolPart }) =>@@ -607,3 +670,9 @@ export const chatUtils = {extractFilesFromHistory,extractBuildsFromHistory,};++export type ChatModelPick = {+ modelTierId: string | null;+ providerConfigId: string | null;+ modelName: string | null;+};diff --git a/packages/web/src/features/chat/lib/use-chat.ts b/packages/web/src/features/chat/lib/use-chat.tsindex 8836c98fbae..94c863baed8 100644--- a/packages/web/src/features/chat/lib/use-chat.ts+++ b/packages/web/src/features/chat/lib/use-chat.ts@@ -19,6 +19,7 @@ import {import { useQuery } from '@tanstack/react-query';import { t } from 'i18next';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { toast } from 'sonner';import { api } from '@/lib/api';import { chatDebug } from '@/lib/chat-debug-logger';@@ -32,7 +33,7 @@ import {} from './chat-store';import { useChatStoreApi, useChatStoreContext } from './chat-store-context';import { ChatUIMessage, QuickRepliesData, chatPartUtils } from './chat-types';-import { chatUtils } from './chat-utils';+import { ChatModelPick, chatUtils } from './chat-utils';import { useStreamingReducer } from './use-streaming-reducer';function applyQuickRepliesToStore({@@ -324,6 +325,14 @@ function injectFilePartsIntoLastUserMessage({return result;}+function isSendCancelled({+ statusRef,+}: {+ statusRef: { current: SendStatus };+}): boolean {+ return statusRef.current.type === 'cancelled';+}+type SendStatus =| { type: 'idle' }| { type: 'submitting' }@@ -333,7 +342,7 @@ type SendStatus =export function useAgentChat({agentId,builder,- defaultModelName,+ projectId,onTitleUpdate,onConversationCreated,onCreditsExhausted,@@ -341,7 +350,7 @@ export function useAgentChat({}: {agentId?: string;builder?: boolean;- defaultModelName?: string | null;+ projectId?: string | null;onTitleUpdate?: (title: string) => void;onConversationCreated?: (conversationId: string) => void;onCreditsExhausted?: () => void;@@ -353,7 +362,10 @@ export function useAgentChat({const [conversationId, setConversationIdState] = useState<string | null>(null,);- const [modelName, setModelNameState] = useState<string | null>(null);+ const [modelPick, setModelPickState] = useState<ChatModelPick | null>(null);+ const [conversationProjectId, setConversationProjectId] = useState<+ string | null+ >(null);const [isLoadingHistory, setIsLoadingHistory] = useState(false);const [isPollingForAgentReply, setIsPollingForAgentReply] = useState(false);const [sendStatus, setSendStatus] = useState<SendStatus>({ type: 'idle' });@@ -376,9 +388,11 @@ export function useAgentChat({>(undefined);const lastSentFileNamesRef = useRef<string[]>([]);const conversationIdRef = useRef<string | null>(null);- const modelNameRef = useRef<string | null>(null);- const defaultModelNameRef = useRef(defaultModelName ?? null);- defaultModelNameRef.current = defaultModelName ?? null;+ const modelPickRef = useRef<ChatModelPick | null>(null);+ const savedPickRef = useRef<ChatModelPick | null>(null);+ const pickSaveQueueRef = useRef<Promise<unknown>>(Promise.resolve());+ const projectIdRef = useRef(projectId ?? null);+ projectIdRef.current = projectId ?? null;const onTitleUpdateRef = useRef(onTitleUpdate);onTitleUpdateRef.current = onTitleUpdate;const onConversationCreatedRef = useRef(onConversationCreated);@@ -749,16 +763,34 @@ export function useAgentChat({const createConversation = useCallback(async ({title,- modelName,- }: { title?: string | null; modelName?: string | null } = {}) => {+ pick,+ }: { title?: string | null; pick?: ChatModelPick | null } = {}) => {+ const chatProjectId = projectIdRef.current;const conv = await chatApi.createConversation({title: title ?? null,- modelName: modelName ?? null,- ...(agentId === undefined ? {} : { agentId }),+ ...(agentId === undefined+ ? {+ ...(pick ?? {}),+ ...(isNil(chatProjectId) ? {} : { projectId: chatProjectId }),+ }+ : { agentId }),...(builder === undefined ? {} : { builder }),});+ setConversationProjectId(conv.projectId ?? null);+ savedPickRef.current = pick ?? null;conversationIdRef.current = conv.id;setConversationIdState(conv.id);+ const latestPick = modelPickRef.current;+ if (!isNil(latestPick) && latestPick !== (pick ?? null)) {+ pickSaveQueueRef.current = pickSaveQueueRef.current.then(async () => {+ const { error } = await tryCatch(() =>+ chatApi.updateConversation(conv.id, latestPick),+ );+ if (isNil(error)) {+ savedPickRef.current = latestPick;+ }+ });+ }return conv;},[agentId, builder],@@ -771,6 +803,10 @@ export function useAgentChat({options?: { messageSource?: AgentMessageSource },) => {updateSendStatus({ type: 'submitting' });+ await pickSaveQueueRef.current;+ if (isSendCancelled({ statusRef: sendStatusRef })) {+ return;+ }const fileNames = files?.map((f) => f.name) ?? [];lastSentFileNamesRef.current = fileNames;@@ -822,7 +858,7 @@ export function useAgentChat({const { error: convError } = await tryCatch(async () => {const conv = await createConversation({title: content.slice(0, 100),- modelName: modelNameRef.current ?? defaultModelNameRef.current,+ pick: modelPickRef.current,});onConversationCreatedRef.current?.(conv.id);});@@ -834,7 +870,7 @@ export function useAgentChat({});return;}- if (sendStatusRef.current.type === 'cancelled') {+ if (isSendCancelled({ statusRef: sendStatusRef })) {setOptimisticUserMessage(null);return;}@@ -952,8 +988,15 @@ export function useAgentChat({data: historyResult.data.data,setState: store.setState,});- modelNameRef.current = convResult.data.modelName ?? null;- setModelNameState(convResult.data.modelName ?? null);+ const savedPick: ChatModelPick = {+ modelTierId: convResult.data.modelTierId ?? null,+ providerConfigId: convResult.data.providerConfigId ?? null,+ modelName: convResult.data.modelName ?? null,+ };+ modelPickRef.current = savedPick;+ savedPickRef.current = savedPick;+ setModelPickState(savedPick);+ setConversationProjectId(convResult.data.projectId ?? null);if (convResult.data.status === AgentConversationStatus.STREAMING) {const lastAssistantIdx = mapped.findLastIndex((m) => m.role === 'assistant',@@ -1050,20 +1093,35 @@ export function useAgentChat({refetchInterval: AGENT_POLL_INTERVAL_MS,});- const setModelName = useCallback(async (newModelName: string) => {- modelNameRef.current = newModelName;- setModelNameState(newModelName);+ const setModelPick = useCallback(async (newPick: ChatModelPick) => {+ modelPickRef.current = newPick;+ setModelPickState(newPick);const convId = conversationIdRef.current;- if (convId) {- await chatApi- .updateConversation(convId, { modelName: newModelName })- .catch(() => undefined);+ if (isNil(convId)) {+ return;+ }+ const save = pickSaveQueueRef.current.then(() =>+ tryCatch(() => chatApi.updateConversation(convId, newPick)),+ );+ pickSaveQueueRef.current = save;+ const { error } = await save;+ if (isNil(error)) {+ savedPickRef.current = newPick;+ return;+ }+ const stillLatest =+ modelPickRef.current === newPick && conversationIdRef.current === convId;+ if (stillLatest) {+ modelPickRef.current = savedPickRef.current;+ setModelPickState(savedPickRef.current);+ toast.error(t("Couldn't switch the model. Try again."));}}, []);return {conversationId,- modelName,+ conversationProjectId,+ modelPick,messages,isStreaming,isResumedStream,@@ -1074,6 +1132,6 @@ export function useAgentChat({sendMessage,cancelStream,setConversationId,- setModelName,+ setModelPick,};}diff --git a/packages/web/src/features/platform-admin/api/ai-provider-api.ts b/packages/web/src/features/platform-admin/api/ai-provider-api.tsindex 140c617aa90..5a83fd9e2a0 100644--- a/packages/web/src/features/platform-admin/api/ai-provider-api.ts+++ b/packages/web/src/features/platform-admin/api/ai-provider-api.ts@@ -30,6 +30,11 @@ export const aiProviderApi = {`/v1/ai-providers/configs/${configId}/suggested-models`,);},+ listPlatformModelOptions({ surface }: { surface: ModelOptionsSurface }) {+ return api.get<ModelOptions>('/v1/ai-providers/model-options/platform', {+ surface,+ });+ },listModelOptions({projectId,surface,@@ -45,9 +50,6 @@ export const aiProviderApi = {...(tierId === undefined ? {} : { tierId }),});},- listModelTiers() {- return api.get<ModelTiersResponse>('/v1/ai-providers/tiers');- },upsert(request: CreateAIProviderRequest) {return api.post<AIProviderWithoutSensitiveData>('/v1/ai-providers',@@ -67,18 +69,3 @@ export const aiProviderApi = {return api.delete(`/v1/ai-providers/${providerId}`);},};--export type ModelTierSurface = 'chat' | 'flow';--export type ModelTier = {- id: string;- label: string;- modelId: string;-};--export type ModelTierList = {- tiers: ModelTier[];- defaultTierId: string;-};--export type ModelTiersResponse = Record<ModelTierSurface, ModelTierList>;diff --git a/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.ts b/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.tsindex 4a4cb13e92a..be4181ab6fe 100644--- a/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.ts@@ -1,28 +1,20 @@import { isNil } from '@activepieces/core-utils';import {- ACTIVEPIECES_CHAT_TIERS,AIProviderAuthConfig,AiProviderKeyStatus,AIProviderWithoutSensitiveData,CreateAIProviderRequest,- DEFAULT_CHAT_TIER_ID,UpdateAIProviderRequest,} from '@activepieces/shared';-import { queryOptions, useMutation, useQuery } from '@tanstack/react-query';+import { useMutation, useQuery } from '@tanstack/react-query';import { AxiosError } from 'axios';import { authenticationSession } from '@/lib/authentication-session';-import {- aiProviderApi,- ModelTierList,- ModelTiersResponse,- ModelTierSurface,-} from '../api/ai-provider-api';+import { aiProviderApi } from '../api/ai-provider-api';export const aiProviderKeys = {configs: ['ai-provider-configs'] as const,- modelTiers: ['ai-provider-model-tiers'] as const,forProject: (projectId: string | null) =>['ai-providers', projectId] as const,configModels: (configId?: string) =>@@ -53,22 +45,6 @@ export const aiProviderQueries = {enabled: !isNil(projectId),});},- useChatProvider: () => {- const { data: providers, ...rest } =- aiProviderQueries.useProjectAiProviders();- return { ...rest, data: providers?.find((p) => p.enabledForChat) };- },- modelTiersOptions: () =>- queryOptions({- queryKey: aiProviderKeys.modelTiers,- queryFn: () => aiProviderApi.listModelTiers(),- staleTime: MODEL_TIERS_STALE_MS,- refetchInterval: MODEL_TIERS_STALE_MS,- }),- useModelTiers: (surface: ModelTierSurface): ModelTierList => {- const { data } = useQuery(aiProviderQueries.modelTiersOptions());- return (data ?? BUNDLED_MODEL_TIERS)[surface];- },};export const aiProviderMutations = {@@ -118,19 +94,6 @@ export const aiProviderMutations = {onError,});},- useToggleChatProvider: ({ onSuccess }: { onSuccess: () => void }) => {- return useMutation({- mutationFn: ({- providerId,- displayName,- }: {- providerId: string;- displayName: string;- }) =>- aiProviderApi.update(providerId, { displayName, enabledForChat: true }),- onSuccess,- });- },useUpsertAiProvider: ({providerId,onSuccess,@@ -168,22 +131,6 @@ export const hasAnyAuthFieldFilled = ();};-const BUNDLED_LIST: ModelTierList = {- tiers: ACTIVEPIECES_CHAT_TIERS.map(({ id, label, modelId }) => ({- id,- label,- modelId,- })),- defaultTierId: DEFAULT_CHAT_TIER_ID,-};--const BUNDLED_MODEL_TIERS: ModelTiersResponse = {- flow: BUNDLED_LIST,- chat: BUNDLED_LIST,-};--const MODEL_TIERS_STALE_MS = 15 * 60 * 1000;-type UpsertAiProviderOptions = {providerId?: string;onSuccess: (created?: AIProviderWithoutSensitiveData) => void;diff --git a/packages/web/src/features/platform-admin/hooks/platform-model-tier-hooks.ts b/packages/web/src/features/platform-admin/hooks/platform-model-tier-hooks.tsindex 77d270a1867..7a8f768e7eb 100644--- a/packages/web/src/features/platform-admin/hooks/platform-model-tier-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/platform-model-tier-hooks.ts@@ -1,6 +1,7 @@import {AIProviderWithoutSensitiveData,CreatePlatformModelTierRequest,+ ModelChoice,PlatformConfiguration,PlatformModelTier,UpdatePlatformModelTierRequest,@@ -188,6 +189,46 @@ export const platformModelTierMutations = {onSettled: () => settle({ queryClient }),});},+ useSetDefaultChatModel: () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (defaultChatModel: ModelChoice | null) =>+ platformConfigurationApi.update({ defaultChatModel }),+ onMutate: async (defaultChatModel) => {+ await queryClient.cancelQueries({+ queryKey: platformConfigurationHooks.queryKey,+ });+ const previous = queryClient.getQueryData<PlatformConfiguration>(+ platformConfigurationHooks.queryKey,+ );+ queryClient.setQueryData<PlatformConfiguration>(+ platformConfigurationHooks.queryKey,+ (old) => old && { ...old, defaultChatModel },+ );+ return { previous };+ },+ onSuccess: (configuration) => {+ queryClient.setQueryData(+ platformConfigurationHooks.queryKey,+ configuration,+ );+ queryClient.invalidateQueries({ queryKey: aiProviderKeys.configs });+ queryClient.invalidateQueries({ queryKey: ['ai-model-options'] });+ toast.success(t('Default chat model updated'), {+ duration: TOAST_SUCCESS_MS,+ });+ },+ onError: (error, _variables, context) => {+ if (context?.previous !== undefined) {+ queryClient.setQueryData(+ platformConfigurationHooks.queryKey,+ context.previous,+ );+ }+ toastError({ error, fallback: t('Could not save this setting') });+ },+ });+ },useSetSpecificModelsVisible: () => {const queryClient = useQueryClient();return useMutation({diff --git a/packages/web/src/lib/admin-control.ts b/packages/web/src/lib/admin-control.tsindex d72d339837f..eea2ab66f13 100644--- a/packages/web/src/lib/admin-control.ts+++ b/packages/web/src/lib/admin-control.ts@@ -17,6 +17,7 @@ export enum AdminControl {AI_PROVIDER_KEY_DELETE_CONFIRM = 'ai.provider-key-delete.confirm',AI_PROVIDER_KEY_DELETE_OPEN = 'ai.provider-key-delete.open',AI_PROVIDER_KEY_RECHECK_RUN = 'ai.provider-key-recheck.run',+ AI_DEFAULT_CHAT_MODEL_SELECT = 'ai.default-chat-model.select',AI_PROVIDER_KEY_SETTINGS_SUBMIT = 'ai.provider-key-settings.submit',AI_PROVIDER_KEY_OPEN = 'ai.provider-key.open',AI_PROVIDER_KEY_SUBMIT = 'ai.provider-key.submit',diff --git a/packages/web/test/app/routes/agents/id/leave-guard-arming.test.tsx b/packages/web/test/app/routes/agents/id/leave-guard-arming.test.tsxindex c791834d793..a32bbbe94ff 100644--- a/packages/web/test/app/routes/agents/id/leave-guard-arming.test.tsx+++ b/packages/web/test/app/routes/agents/id/leave-guard-arming.test.tsx@@ -42,7 +42,7 @@ vi.mock('@/features/agents', () => ({/></>),- PROVIDER_EMBEDDING_MODELS: {},+ useKnowledgeBaseEmbeddingSource: () => ({ data: undefined }),AgentStructuredOutput: () => <div data-testid="structured" />,KnowledgeBaseSection: () => <div data-testid="knowledge" />,useAgentsAvailable: () => true,diff --git a/packages/web/test/app/routes/agents/id/write-race.test.tsx b/packages/web/test/app/routes/agents/id/write-race.test.tsxindex 1bf1458b583..86b1b1d5095 100644--- a/packages/web/test/app/routes/agents/id/write-race.test.tsx+++ b/packages/web/test/app/routes/agents/id/write-race.test.tsx@@ -22,7 +22,7 @@ vi.mock('@/hooks/authorization-hooks', () => ({}));vi.mock('@/features/agents', () => ({ModelPicker: () => <div data-testid="model" />,- PROVIDER_EMBEDDING_MODELS: {},+ useKnowledgeBaseEmbeddingSource: () => ({ data: undefined }),AgentStructuredOutput: () => <div data-testid="structured" />,KnowledgeBaseSection: () => <div data-testid="knowledge" />,useAgentsAvailable: () => true,diff --git a/packages/web/test/app/routes/chat-with-ai/components/chat-model-selector.test.tsx b/packages/web/test/app/routes/chat-with-ai/components/chat-model-selector.test.tsxdeleted file mode 100644index e4f8db0f990..00000000000--- a/packages/web/test/app/routes/chat-with-ai/components/chat-model-selector.test.tsx+++ /dev/null@@ -1,76 +0,0 @@-// @vitest-environment jsdom-import { AIProviderName } from '@activepieces/core-utils';-import { aiProviderUtils } from '@activepieces/shared';-import { render } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--vi.mock('i18next', () => ({ t: (key: string) => key }));--const state = vi.hoisted(() => ({- provider: '',- useModelTiers: vi.fn(),-}));--vi.mock('@/features/platform-admin', () => ({- aiProviderQueries: {- useChatProvider: () => ({ data: { provider: state.provider } }),- useModelTiers: (surface: string) => state.useModelTiers(surface),- },-}));--import { ChatModelSelector } from '@/app/routes/chat-with-ai/components/chat-model-selector';--describe('ChatModelSelector', () => {- beforeEach(() => {- state.provider = AIProviderName.ACTIVEPIECES;- state.useModelTiers.mockReset();- state.useModelTiers.mockReturnValue(CHAT_TIERS);- });-- it('reads the chat tiers and shows the published default when nothing is picked', () => {- render(<ChatModelSelector selectedModel={null} onModelChange={noop} />);-- expect(state.useModelTiers).toHaveBeenCalledWith('chat');- expect(triggerText()).toBe('Turbo');- });-- it('shows the picked tier by its published label', () => {- render(<ChatModelSelector selectedModel="smart" onModelChange={noop} />);-- expect(triggerText()).toBe('Expert');- });-- it('falls back to the published default for a tier that is no longer listed', () => {- render(<ChatModelSelector selectedModel="gone" onModelChange={noop} />);-- expect(triggerText()).toBe('Turbo');- });-- it('shows the first curated model on an own-key provider with a curated list', () => {- state.provider = AIProviderName.OPENAI;- const curated = aiProviderUtils.getCuratedChatModels({- provider: AIProviderName.OPENAI,- });-- render(<ChatModelSelector selectedModel={null} onModelChange={noop} />);-- expect(triggerText()).toBe(curated?.[0].label);- });-});--function triggerText(): string | undefined {- return document.querySelector('button[role="combobox"]')?.textContent?.trim();-}--function noop(): void {- return undefined;-}--const CHAT_TIERS = {- tiers: [- { id: 'fast', label: 'Fast', modelId: 'anthropic/claude-haiku-4.5' },- { id: 'smart', label: 'Expert', modelId: 'google/gemini-3.7-flash' },- { id: 'turbo', label: 'Turbo', modelId: 'openai/gpt-5.5' },- ],- defaultTierId: 'turbo',-};diff --git a/packages/web/test/app/routes/platform/setup/ai-capabilities/catalog.test.ts b/packages/web/test/app/routes/platform/setup/ai-capabilities/catalog.test.tsnew file mode 100644index 00000000000..5ebcfac5edb--- /dev/null+++ b/packages/web/test/app/routes/platform/setup/ai-capabilities/catalog.test.ts@@ -0,0 +1,76 @@+import { AIProviderName } from '@activepieces/core-utils';+import {+ AIProviderWithoutSensitiveData,+ AiToolCapability,+} from '@activepieces/shared';+import { describe, expect, it, vi } from 'vitest';++vi.mock('i18next', () => ({ t: (key: string) => key }));++import {+ AI_TOOL_CATALOG,+ aiCapabilitySources,+} from '@/app/routes/platform/setup/ai-capabilities/catalog';++const key = ({+ provider,+ projectScope,+}: {+ provider: AIProviderName;+ projectScope: 'all' | 'selected';+}): AIProviderWithoutSensitiveData => ({+ id: `${provider}-${projectScope}`,+ name: provider,+ provider,+ config: {},+ enabledForChat: true,+ modelScope: 'all',+ modelIds: [],+ projectScope,+ projectIds: [],+ status: 'active',+ statusReason: null,+ statusUpdated: null,+});++describe('the Embeddings capability', () => {+ it('is listed as AI-key only', () => {+ const row = AI_TOOL_CATALOG.find(+ (info) => info.capability === AiToolCapability.EMBEDDINGS,+ );+ expect(row?.providers).toEqual([]);+ });++ it('can be set to an all-projects key that embeds, not to one that cannot', () => {+ const eligible = aiCapabilitySources.eligibleProviders({+ capability: AiToolCapability.EMBEDDINGS,+ providers: [+ key({ provider: AIProviderName.OPENAI, projectScope: 'all' }),+ key({ provider: AIProviderName.ANTHROPIC, projectScope: 'all' }),+ key({ provider: AIProviderName.GOOGLE, projectScope: 'selected' }),+ ],+ });+ expect(eligible.map((provider) => provider.id)).toEqual(['openai-all']);+ });++ it('falls back to a Default AI key that embeds, even one limited to some projects, like the server', () => {+ expect(+ aiCapabilitySources.servesByDefault({+ capability: AiToolCapability.EMBEDDINGS,+ provider: key({+ provider: AIProviderName.OPENAI,+ projectScope: 'selected',+ }),+ }),+ ).toBe(true);+ expect(+ aiCapabilitySources.servesByDefault({+ capability: AiToolCapability.EMBEDDINGS,+ provider: key({+ provider: AIProviderName.ANTHROPIC,+ projectScope: 'all',+ }),+ }),+ ).toBe(false);+ });+});diff --git a/packages/web/test/app/routes/platform/setup/ai/default-chat-model-card.test.ts b/packages/web/test/app/routes/platform/setup/ai/default-chat-model-card.test.tsnew file mode 100644index 00000000000..c8f345eec28--- /dev/null+++ b/packages/web/test/app/routes/platform/setup/ai/default-chat-model-card.test.ts@@ -0,0 +1,166 @@+/**+ * @vitest-environment jsdom+ */+import { AIProviderName } from '@activepieces/core-utils';+import {+ AIProviderModelType,+ AIProviderWithoutSensitiveData,+ ModelChoice,+ ModelOptions,+} from '@activepieces/shared';+import { describe, expect, it, vi } from 'vitest';++vi.mock('i18next', () => ({+ t: (key: string, values?: Record<string, unknown>) =>+ `${key}${values ? JSON.stringify(values) : ''}`,+}));++import { defaultChatModelCardUtils } from '@/app/routes/platform/setup/ai/providers-tab/default-chat-model-card';++const key = (+ projectScope: 'all' | 'selected',+): AIProviderWithoutSensitiveData => ({+ id: 'key-a',+ name: 'Team key',+ provider: AIProviderName.OPENAI,+ config: {},+ enabledForChat: false,+ modelScope: 'all',+ modelIds: [],+ projectScope,+ projectIds: projectScope === 'selected' ? ['p1'] : [],+ status: 'active',+ statusReason: null,+ statusUpdated: null,+});++const options: ModelOptions = {+ tiers: [],+ credits: null,+ keys: [+ {+ providerConfigId: 'key-a',+ provider: AIProviderName.OPENAI,+ name: 'Team key',+ models: [{ id: 'gpt-6', name: 'GPT-6', type: AIProviderModelType.TEXT }],+ },+ ],+ defaultChoice: {+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'key-a',+ modelId: 'gpt-6',+ },+ movedTiers: {},+ specificModelsHidden: false,+};++const pick: ModelChoice = {+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'key-a',+ modelId: 'gpt-6',+};++const noteFor = (+ value: ModelChoice | null,+ projectScope: 'all' | 'selected' = 'all',+) =>+ statusText(+ defaultChatModelCardUtils.statusOf({+ value,+ options,+ tiers: [],+ configsById: new Map([['key-a', key(projectScope)]]),+ projectIds: ['p1', 'p2', 'p3'],+ hasEmbeddingsKey: true,+ }),+ );++const statusText = (status: {+ placeholder: string | undefined;+ warnings: string[];+}): string | null =>+ status.placeholder ??+ (status.warnings.length === 0 ? null : status.warnings.join(' '));++describe('the default chat model card note', () => {+ it('names what new chats use when nothing is set', () => {+ expect(noteFor(null)).toContain('GPT-6');+ });++ it('says nothing when the pick runs in every project', () => {+ expect(noteFor(pick)).toBeNull();+ });++ it('counts the projects where the pick cannot run', () => {+ expect(noteFor(pick, 'selected')).toContain('"count":2');+ });++ it('flags a pick that is gone', () => {+ expect(+ noteFor({+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'deleted',+ modelId: 'old',+ }),+ ).toContain('no longer available');+ });+});++describe('picking the default chat model again', () => {+ it('clears it, and a different pick does not', () => {+ expect(defaultChatModelCardUtils.sameChoice({ a: pick, b: pick })).toBe(+ true,+ );+ expect(+ defaultChatModelCardUtils.sameChoice({+ a: { type: 'tier', tierId: 't1' },+ b: pick,+ }),+ ).toBe(false);+ expect(defaultChatModelCardUtils.sameChoice({ a: pick, b: null })).toBe(+ false,+ );+ });+});++describe('the embeddings warning', () => {+ it('appears when the default key cannot embed and no Embeddings key is set', () => {+ const status = defaultChatModelCardUtils.statusOf({+ value: { ...pick, provider: AIProviderName.ANTHROPIC },+ options: {+ ...options,+ keys: [{ ...options.keys[0], provider: AIProviderName.ANTHROPIC }],+ },+ tiers: [],+ configsById: new Map([['key-a', key('all')]]),+ projectIds: [],+ hasEmbeddingsKey: false,+ });+ expect(status.warnings.join(' ')).toContain('Embeddings key');+ });+});++describe('the embeddings warning with Credits', () => {+ it('stays quiet when Credits can index the files', () => {+ const status = defaultChatModelCardUtils.statusOf({+ value: { ...pick, provider: AIProviderName.ANTHROPIC },+ options: {+ ...options,+ keys: [{ ...options.keys[0], provider: AIProviderName.ANTHROPIC }],+ credits: {+ providerConfigId: 'managed',+ defaultTierId: 'smart',+ tiers: [],+ },+ },+ tiers: [],+ configsById: new Map([['key-a', key('all')]]),+ projectIds: [],+ hasEmbeddingsKey: false,+ });+ expect(status.warnings).toEqual([]);+ });+});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.tsxindex 1e12dba817a..a557d04b4d0 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@@ -66,7 +66,6 @@ vi.mock('@/features/platform-admin', () => {}),},aiProviderMutations: {- useToggleChatProvider: mutation,useDeleteAiProvider: mutation,useRecheckAiProvider: mutation,useUpdateAiProvider: mutation,@@ -99,6 +98,10 @@ vi.mock(() => ({ ConnectProviderDialog: () => null }),);+vi.mock(+ '@/app/routes/platform/setup/ai/providers-tab/default-chat-model-card',+ () => ({ DefaultChatModelCard: () => null }),+);vi.mock('@/app/routes/platform/setup/ai/providers-tab/config-detail', () => ({ConfigDetail: () => <h1>Key detail</h1>,}));diff --git a/packages/web/test/features/agents/agent-tools/knowledge-base-tool.test.tsx b/packages/web/test/features/agents/agent-tools/knowledge-base-tool.test.tsxindex f9e9484b548..20df1c7d37d 100644--- a/packages/web/test/features/agents/agent-tools/knowledge-base-tool.test.tsx+++ b/packages/web/test/features/agents/agent-tools/knowledge-base-tool.test.tsx@@ -8,19 +8,35 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-vi.mock('@/features/agents', () => ({- PROVIDER_EMBEDDING_MODELS: { openai: 'text-embedding-3-small' },+const source = vi.hoisted(() => ({+ loaded: true,+ provider: null as string | null,}));-const chat = vi.hoisted(() => ({ provider: undefined as string | undefined }));--vi.mock('@/features/platform-admin/hooks/ai-provider-hooks', () => ({- aiProviderQueries: {- useChatProvider: () => ({- data:- chat.provider === undefined ? undefined : { provider: chat.provider },+vi.mock(+ '@/features/agents/agent-tools/knowledge-base-dialog/knowledge-base-hooks',+ () => ({+ useKnowledgeBaseEmbeddingSource: () => ({+ data: source.loaded+ ? {+ provider: source.provider,+ modelId: source.provider === null ? null : 'text-embedding-3-small',+ }+ : undefined,}),- },+ }),+);++const viewer = vi.hoisted(() => ({ isAdmin: false }));++vi.mock('@/hooks/authorization-hooks', () => ({+ useIsPlatformAdmin: () => viewer.isAdmin,+}));++vi.mock('react-router-dom', () => ({+ Link: ({ to, children }: { to: string; children: React.ReactNode }) => (+ <a href={to}>{children}</a>+ ),}));vi.mock('@/hooks/flags-hooks', () => ({@@ -83,7 +99,9 @@ function canAddKnowledge(): boolean {}beforeEach(() => {- chat.provider = undefined;+ source.loaded = true;+ source.provider = null;+ viewer.isAdmin = false;container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -97,24 +115,35 @@ afterEach(() => {});describe('adding knowledge to an agent', () => {- it('is offered when the chat key can embed, whatever the step picked', () => {- chat.provider = AIProviderName.OPENAI;+ it("is offered when the server reports a provider that embeds this project's files", () => {+ source.provider = AIProviderName.OPENAI;render();expect(canAddKnowledge()).toBe(true);});- it('is explained when the chat key cannot embed', () => {- chat.provider = AIProviderName.ANTHROPIC;-+ it("tells a builder to ask the admin when no key can embed this project's files", () => {render();expect(canAddKnowledge()).toBe(false);- expect(container.textContent).toContain('requires a provider');+ expect(container.textContent).toContain('Ask your admin');+ expect(container.querySelector('a')).toBeNull();+ });++ it('links an admin to the Embeddings capability', () => {+ viewer.isAdmin = true;++ render();++ expect(container.querySelector('a')?.getAttribute('href')).toBe(+ '/platform/ai/capabilities',+ );});- it('is explained when the project has no chat key', () => {+ it('is not offered before the server answers', () => {+ source.loaded = false;+render();expect(canAddKnowledge()).toBe(false);diff --git a/packages/web/test/features/agents/ai-model/model-meta.test.ts b/packages/web/test/features/agents/ai-model/model-meta.test.tsindex 8b394d81be4..16e89d82bfd 100644--- a/packages/web/test/features/agents/ai-model/model-meta.test.ts+++ b/packages/web/test/features/agents/ai-model/model-meta.test.ts@@ -367,7 +367,7 @@ describe('modelMeta project scope', () => {]);});- it('flags a main model that cannot call tools and recommends a curated one', () => {+ it('flags a main model that cannot call tools and recommends nothing', () => {const openAi = key('k', { provider: AIProviderName.OPENAI });expect(modelMeta.toolsVerdict({@@ -382,7 +382,7 @@ describe('modelMeta project scope', () => {entry: { configId: 'k', modelId: 'gpt-4.1' },model: model('gpt-4.1', {}),}),- ).toBe('recommended');+ ).toBeNull();expect(modelMeta.toolsVerdict({config: openAi,diff --git a/packages/web/test/features/agents/ai-model/model-picker.test.tsx b/packages/web/test/features/agents/ai-model/model-picker.test.tsxindex 11c1e480d1c..4b78e8ba2a4 100644--- a/packages/web/test/features/agents/ai-model/model-picker.test.tsx+++ b/packages/web/test/features/agents/ai-model/model-picker.test.tsx@@ -14,7 +14,10 @@ vi.mock('i18next', () => ({t: (key: string) => key,}));-import { modelPickerView } from '@/features/agents/ai-model/model-picker';+import {+ modelPickerUtils,+ modelPickerView,+} from '@/features/agents/ai-model/model-picker';const optionModel = (modelId: string) => ({provider: AIProviderName.OPENAI,@@ -219,3 +222,28 @@ describe('modelPickerView', () => {).toMatchObject({ kind: 'unavailable' });});});++describe('modelPickerUtils.isUnavailable', () => {+ it('blocks a pick that is gone, but not one the admin hid or a live one', () => {+ const gone = {+ type: 'model',+ provider: AIProviderName.CUSTOM,+ providerConfigId: 'deleted-key',+ modelId: 'old',+ } as const;++ expect(modelPickerUtils.isUnavailable({ options, value: gone })).toBe(true);+ expect(+ modelPickerUtils.isUnavailable({+ options: { ...options, keys: [], specificModelsHidden: true },+ value: gone,+ }),+ ).toBe(false);+ expect(+ modelPickerUtils.isUnavailable({+ options,+ value: { type: 'tier', tierId: 'tier-expert' },+ }),+ ).toBe(false);+ });+});diff --git a/packages/web/test/features/chat/lib/chat-model-pick.test.ts b/packages/web/test/features/chat/lib/chat-model-pick.test.tsnew file mode 100644index 00000000000..be21bbfdbaa--- /dev/null+++ b/packages/web/test/features/chat/lib/chat-model-pick.test.ts@@ -0,0 +1,90 @@+import { AIProviderName } from '@activepieces/core-utils';+import { AIProviderModelType, ModelOptions } from '@activepieces/shared';+import { describe, expect, it, vi } from 'vitest';++vi.mock('i18next', () => ({ t: (key: string) => key }));++import { chatUtils } from '@/features/chat/lib/chat-utils';++const options: ModelOptions = {+ tiers: [],+ credits: { providerConfigId: 'managed', defaultTierId: 'smart', tiers: [] },+ keys: [+ {+ providerConfigId: 'key-a',+ provider: AIProviderName.OPENAI,+ name: 'Team key',+ models: [{ id: 'gpt-6', name: 'GPT-6', type: AIProviderModelType.TEXT }],+ },+ ],+ defaultChoice: null,+ movedTiers: {},+ specificModelsHidden: false,+};++describe('a chat model pick', () => {+ it('round-trips a tier, a key model and a credits tier', () => {+ const choices = [+ { type: 'tier', tierId: 'tier-1' },+ {+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'key-a',+ modelId: 'gpt-6',+ },+ {+ type: 'model',+ provider: AIProviderName.ACTIVEPIECES,+ providerConfigId: 'managed',+ modelId: 'smart',+ },+ ] as const;++ for (const choice of choices) {+ const pick = chatUtils.pickOf({ choice });+ expect(chatUtils.choiceOf({ pick, options })).toEqual(choice);+ }+ });++ it('clears the other side of the pick so the server drops it', () => {+ expect(+ chatUtils.pickOf({ choice: { type: 'tier', tierId: 'tier-1' } }),+ ).toEqual({+ modelTierId: 'tier-1',+ providerConfigId: null,+ modelName: null,+ });+ });++ it('keeps a pick on a deleted key so the picker can show it as unavailable', () => {+ expect(+ chatUtils.choiceOf({+ pick: { modelTierId: null, providerConfigId: 'gone', modelName: 'x' },+ options,+ }),+ ).toMatchObject({ type: 'model', providerConfigId: 'gone', modelId: 'x' });+ });++ it('shows an older chat that stores only a model name on the key that lists it', () => {+ expect(+ chatUtils.choiceOf({+ pick: { modelTierId: null, providerConfigId: null, modelName: 'gpt-6' },+ options,+ }),+ ).toEqual({+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'key-a',+ modelId: 'gpt-6',+ });+ });++ it('shows the default for an older chat whose model no key lists', () => {+ expect(+ chatUtils.choiceOf({+ pick: { modelTierId: null, providerConfigId: null, modelName: 'smart' },+ options,+ }),+ ).toBeNull();+ });+});diff --git a/packages/web/test/features/chat/lib/new-chat-model-name.test.ts b/packages/web/test/features/chat/lib/new-chat-model-name.test.tsdeleted file mode 100644index e25e4862855..00000000000--- a/packages/web/test/features/chat/lib/new-chat-model-name.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import { AIProviderName } from '@activepieces/core-utils';-import { aiProviderUtils } from '@activepieces/shared';-import { describe, expect, it } from 'vitest';--import { chatUtils } from '@/features/chat/lib/chat-utils';--describe('chatUtils.newChatModelName', () => {- it('sends no model on a tier picker, so the published chat default decides', () => {- expect(- chatUtils.newChatModelName({ provider: AIProviderName.ACTIVEPIECES }),- ).toBeNull();- expect(- chatUtils.newChatModelName({ provider: AIProviderName.BEDROCK }),- ).toBeNull();- expect(chatUtils.newChatModelName({ provider: undefined })).toBeNull();- });-- it('sends the model a curated own-key picker shows, so the turn cannot run the published default instead', () => {- const shown = aiProviderUtils.getCuratedChatModels({- provider: AIProviderName.ANTHROPIC,- })?.[0]?.id;-- expect(shown).toBeDefined();- expect(- chatUtils.newChatModelName({ provider: AIProviderName.ANTHROPIC }),- ).toBe(shown);- });-});diff --git a/packages/web/test/features/platform-admin/ai-provider-hooks.test.tsx b/packages/web/test/features/platform-admin/ai-provider-hooks.test.tsxdeleted file mode 100644index c5d36c6c694..00000000000--- a/packages/web/test/features/platform-admin/ai-provider-hooks.test.tsx+++ /dev/null@@ -1,143 +0,0 @@-// @vitest-environment jsdom-import {- ACTIVEPIECES_CHAT_TIERS,- DEFAULT_CHAT_TIER_ID,-} from '@activepieces/shared';-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import { renderHook, waitFor } from '@testing-library/react';-import { ReactNode } from 'react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--vi.mock('@/lib/authentication-session', () => ({- authenticationSession: { getProjectId: () => 'project-1' },-}));--const listModelTiers = vi.fn();-vi.mock('@/features/platform-admin/api/ai-provider-api', () => ({- aiProviderApi: { listModelTiers: () => listModelTiers() },-}));--import type {- ModelTierList,- ModelTiersResponse,- ModelTierSurface,-} from '@/features/platform-admin/api/ai-provider-api';-import {- aiProviderKeys,- aiProviderQueries,-} from '@/features/platform-admin/hooks/ai-provider-hooks';--describe('aiProviderQueries.useModelTiers', () => {- let queryClient: QueryClient;-- beforeEach(() => {- listModelTiers.mockReset();- queryClient = new QueryClient({- defaultOptions: { queries: { retry: false } },- });- });-- afterEach(() => {- queryClient.clear();- });-- it('refetches on the same cadence as the server, so an open page does not keep stale tiers', () => {- const options = aiProviderQueries.modelTiersOptions();-- expect(options.staleTime).toBe(FIFTEEN_MINUTES_MS);- expect(options.refetchInterval).toBe(FIFTEEN_MINUTES_MS);- });-- it('serves the chat list for chat and the flow list for flow from one request', async () => {- listModelTiers.mockResolvedValue(PUBLISHED);-- const { result: chat } = renderTiers('chat');- await waitFor(() => expect(chat.current.defaultTierId).toBe('turbo'));- expect(chat.current.tiers.map((tier) => tier.id)).toEqual([- 'fast',- 'smart',- 'turbo',- ]);- expect(modelIdOf(chat.current, 'smart')).toBe('google/gemini-3.7-flash');-- const { result: flow } = renderTiers('flow');- await waitFor(() =>- expect(modelIdOf(flow.current, 'smart')).toBe(- 'anthropic/claude-sonnet-5',- ),- );- expect(flow.current.tiers.map((tier) => tier.id)).toEqual([- 'fast',- 'smart',- 'premium',- ]);- expect(flow.current.defaultTierId).toBe('smart');- expect(listModelTiers).toHaveBeenCalledTimes(1);- });-- it('serves the bundled list before the response lands', () => {- listModelTiers.mockReturnValue(new Promise(() => undefined));-- const { result } = renderTiers('chat');-- expect(result.current).toEqual(BUNDLED);- });-- it('serves the bundled list on both surfaces when the request fails', async () => {- listModelTiers.mockRejectedValue(new Error('tiers endpoint down'));-- const { result: chat } = renderTiers('chat');- const { result: flow } = renderTiers('flow');- await waitFor(() =>- expect(queryClient.getQueryState(aiProviderKeys.modelTiers)?.status).toBe(- 'error',- ),- );-- expect(chat.current).toEqual(BUNDLED);- expect(flow.current).toEqual(BUNDLED);- });-- function renderTiers(surface: ModelTierSurface) {- const wrapper = ({ children }: { children: ReactNode }) => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- );- return renderHook(() => aiProviderQueries.useModelTiers(surface), {- wrapper,- });- }-});--function modelIdOf(list: ModelTierList, tierId: string): string | undefined {- return list.tiers.find((tier) => tier.id === tierId)?.modelId;-}--const PUBLISHED: ModelTiersResponse = {- flow: {- tiers: [- { id: 'fast', label: 'Fast', modelId: 'anthropic/claude-haiku-4.5' },- { id: 'smart', label: 'Expert', modelId: 'anthropic/claude-sonnet-5' },- { id: 'premium', label: 'Heavy', modelId: 'anthropic/claude-opus-4.8' },- ],- defaultTierId: 'smart',- },- chat: {- tiers: [- { id: 'fast', label: 'Fast', modelId: 'anthropic/claude-haiku-4.5' },- { id: 'smart', label: 'Expert', modelId: 'google/gemini-3.7-flash' },- { id: 'turbo', label: 'Turbo', modelId: 'openai/gpt-5.5' },- ],- defaultTierId: 'turbo',- },-};--const FIFTEEN_MINUTES_MS = 15 * 60 * 1000;--const BUNDLED: ModelTierList = {- tiers: ACTIVEPIECES_CHAT_TIERS.map(({ id, label, modelId }) => ({- id,- label,- modelId,- })),- defaultTierId: DEFAULT_CHAT_TIER_ID,-};