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(ai): shared model picker with tiers, credits and keys (#16264)
Louai Boumedienedbda77a21eec
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.mdindex 1143171f533..df77fe53289 100644--- a/brain/knowledge/ai-intelligence/ai-providers.md+++ b/brain/knowledge/ai-intelligence/ai-providers.md@@ -76,6 +76,7 @@ after a file without chat keys it seeds the chat list from the live flow list.### Gotchas- **The admin Tiers page has no sidebar or search entry until the feature launches.** The route `/platform/ai/tiers` works, but the platform sidebar and the global search `STATIC_PAGES` deliberately leave it out, so only someone with the URL finds it. To launch, add `{ to: '/platform/ai/tiers', label: t('Tiers') }` to the AI subItems in `sidebar/platform/index.tsx` and add a `page-platform-ai-tiers` entry to `static-pages.ts`.+- **New shared AI-provider schemas go inside `packages/core/shared/src/lib/management/ai-providers/index.ts`, not in a sibling file that imports from it.** `index.ts` re-exports its siblings, so a sibling that imports `AIProviderModel` back from `./index` gets `undefined` when the module loads, and every importer crashes with `Cannot read properties of undefined (reading 'optional')`. `platform-model-tier.ts` works only because it imports from `core-utils`.- **The admin Tiers tab applies a key's `modelScope` itself.** `GET /v1/ai-providers/configs/:id/models` returns the unfiltered list on purpose (admins pick the allow-list from it), so the tier pickers and the Specific models list narrow it client-side in `modelMeta.scopedTextModels` (`packages/web/src/features/agents/ai-model/`). The server still refuses an out-of-scope entry on save (`assertEntriesValid`), so the client filter is convenience, not the guard.- **A key a live platform tier uses cannot be deleted, and its `modelScope` cannot drop a tier's model.** `aiProviderService.delete` and `update` call `platformModelTierService.assertKeyCanBeDeleted` / `assertKeyScopeKeepsTiers` under a `platform` row `FOR NO KEY UPDATE` lock and answer 409 with the tier names. The same lock serialises every tier write, so a tier save can't race a key delete into a dangling entry. The same update also refuses removing a typed-in model (Vertex, OpenAI-compatible, Cloudflare `config.models`) that a tier uses, even when `modelScope` is `all`, and limiting the projects of a key that a capability (web search, scraping, image) uses, or dropping the capability's `modelId` from its model list: capability keys must serve every project and keep their model (`assertCapabilitiesKeepKey`).- **A key's model list is enforced when a specific model runs, not only in pickers.** `/v1/ai/execute` checks `aiProviderService.assertModelAllowed` before queueing (the managed Activepieces key is skipped: it allows every model), and the worker's `resolveAiProvider` RPC sends `modelId` so the server checks it again against the key it resolves at run time (a model removed while the job waited fails then). `resolveNamedModelId` refuses any own-key model outside the list with no tier-id exemption: an own key never translates `smart`/`fast`, so a name that looks like a tier is just a customer model id. At platform scope, `rankRows` prefers keys open to every project; at project scope it still prefers the most specific key. Key edits and capability choices both take the `platform` row lock, and a capability save re-reads its key under that lock, so the two cannot interleave. One helper, `aiKeyScope.keyOffersModel`, decides whether a key still offers a model: its model scope, plus its typed-in `config.models` list when it has one. The tier and capability guards on a key edit both use it, and so does the locked re-check when a capability is saved. A key edit that removes a typed-in model a capability uses is refused like a model-scope change.diff --git a/brain/knowledge/ai-intelligence/index.md b/brain/knowledge/ai-intelligence/index.mdindex 1fdb7365f62..e1882a7ae16 100644--- a/brain/knowledge/ai-intelligence/index.md+++ b/brain/knowledge/ai-intelligence/index.md@@ -36,6 +36,7 @@ The per-project endpoint that exposes Activepieces tools to an external AI assis- **AI Providers** — configuring backends, credential storage, credit metering- **AI Agents** — the Agent step and its tool types+- **Model Picker** — the builder's tier / credits / key picker and its options endpoint- **MCP Server** — the per-project endpoint, tool exposure, visibility rules- **AI & MCP** — how the AI and MCP surfaces fit togetherdiff --git a/brain/knowledge/ai-intelligence/model-picker.md b/brain/knowledge/ai-intelligence/model-picker.mdnew file mode 100644index 00000000000..639d487364f--- /dev/null+++ b/brain/knowledge/ai-intelligence/model-picker.md@@ -0,0 +1,40 @@+---+icon: 🎛️+---+# Model Picker++The one picker a builder uses to choose what an agent, chat or AI step runs on. It lists what the current project may use, in three sections. Hovering a row opens a side card with that model's data, to the left of the list at the row's height. The card stays open while the pointer moves onto it.++**ModelChoice** — the stored pick: `{ type: 'tier', tierId }` or `{ type: 'model', provider, providerConfigId, modelId }`. A credits pick is a `model` on the managed Activepieces key with `modelId` set to the credits tier id, so there are two kinds, not three.+- *Avoid:* "credits choice" as a third kind.++**Model options** — `GET /v1/ai-providers/model-options?projectId&surface` (`aiModelOptionsService`). The server builds the whole list so the scope rules live in one place:+- **Your tiers:** a tier shows only when its main entry runs in the project. Fallbacks that can't run there are dropped.+- **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.++**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.++## 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`).+- A stored model pick is matched by its `providerConfigId` only. The "any key of this provider with this model" fallback is for old agent rows saved without a key id (`''`). Otherwise a deleted key would look selected while the run still fails on it.+- cmdk's `CommandItem` replaces any `onPointerMove` you pass it with its own hover-select. The picker reads hover on `CommandList` instead, from the closest `[cmdk-item]`'s `data-value`. Its `onValueChange` also fires when the list opens, because cmdk highlights the first row. So the detail card only follows `onValueChange` after an arrow key has been pressed.+- The side card hides any row it has no data for. Catalog metadata comes from the CDN `model-catalog.json`, and its publish has failed before, so expect gaps. The lookup is by exact id and is all-or-nothing. A real OpenAI key had 50 of 88 models with no data: 24 dated snapshots (`gpt-5.5-2026-04-23`, where the catalog has only `gpt-5.5`), 6 that exist only under `openrouter` as `openai/<id>`, and 20 search, research, alias or legacy ids.+- The admin Tiers page pickers (`AdminModelPicker`) use the same `ModelPickerPopover` and `ModelDetailCard`, so the cards look the same on both pages. Picker dropdown rows show no capability icons; the hover card shows them. The Tiers page model rows (`ModelDetailRow`) draw four fixed slots through `ModelCapabilityIcons`: tool calling, reasoning, vision, web search. An unsupported capability leaves an empty slot, so the columns stay lined up.+- All four capabilities always show, everywhere. In the card, an available one is a green pill and anything else is struck out. On Tiers page rows, unavailable icons are dimmed. "Not available" covers two cases. Tool calling, reasoning and vision come from the catalog, per model, so a model the catalog misses has them all struck. Web search comes from `AI_PROVIDER_CAPABILITIES`, per provider, and is struck when we haven't wired that provider's search (OpenAI today), even if the model itself can search.+- The hover card opens to the left of the list. It flips to the right when the popover sits too close to the left edge (Add fallback on a tier opens there).+- A stored deleted tier shows its live replacement ("Moved"), because the runtime follows `replacedBy` too. The picker sends its stored `tierId` and `movedTiers` follows only that chain; without a `tierId` it is empty.+- On chat, a key with a typed-in model list (Vertex, Custom) offers exactly that list, not the curated list. The chat runner (`agentModelResolution`) picks only from the manual list, so a curated model outside it would be silently swapped.+- A stored model that the admin hid with the specific-models toggle shows "Hidden by admin". It still runs, because the toggle is not enforced at run time.+- 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).++## Key files+- `packages/web/src/features/agents/ai-model/`: `ModelPicker`, `ModelPickerPopover`, `ModelDetailCard`+- `packages/server/api/src/app/ai/`: `aiModelOptionsService`diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.mdindex 31ccae1e390..df4d514eb5c 100644--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md@@ -24,6 +24,8 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def## Gotchas- **In a PR stack, resolve a shared conflict once with `git config rerere.enabled true`.** If a child branch merges a sibling PR that touches the same file as its parent, git records how you fixed the conflict. When that sibling reaches `main` and the parent merges `main`, git replays the fix ("Staged … using previous resolution"). Still read the staged result before committing.- **A clean merge of main can silently cancel your package version bump.** If main bumped the same package to the same version your branch did (seen 2026-10-08: both at core-execution `0.26.2`), `package.json` merges with no conflict. Your change then ships under a version main already published. After every main merge, compare each package your branch touches against `git show origin/main:<path>/package.json` and bump again if they match, then fix its `bun.lock` line.+- **Preview the merge order of two open PRs without checking anything out.** Run `git merge-tree --write-tree --name-only origin/<branch-a> origin/<branch-b>`. It lists every conflicting file and leaves your working tree alone. Run it before deciding which PR lands first.+- **Any push to an approved PR dismisses the approval.** Seen 2026-10-08 on #16116: a one-commit change after approval left the PR `BLOCKED` with an empty `reviewDecision`. So land small follow-ups before asking for approval, or plan for a second approval. Check `gh pr view <n> --json reviewDecision` after pushing.- **When merging main, `rerere` can replay a stale `bun.lock` resolution.** "Staged 'bun.lock' using previous resolution" means git reused an old answer, which can carry workspace versions that no longer match any `package.json` (seen: core-utils `0.8.6` in the lockfile against `0.8.5` in the manifest). If the branch adds no dependencies, take main's `bun.lock` and edit only the branch's own workspace `version` lines. Expect `bun install` to then rewrite a few lines for pieces the branch never touched: piece PRs on `main` often bump a `package.json` without its `bun.lock` entry (seen 2026-10-05: grist, microsoft-todo, ticktick, zendesk). Those lines are main catching up, not your change; keep them, because the lock should match the manifests.- **Any change to `bun.lock` runs every package's tests in `build-test`, all 700+ pieces included.** The `changes` job in `ci.yml` sets `all=true` when a changed file is outside `packages/`, `docs/`, `brain/`, `.agents/` and `.claude/` and is not a `*.md` file (so root Markdown alone does not count), and `tools/scripts/test-filters.ts` then adds every package with a `test` script **except `api`** (it lists with `--filter=!api`). API tests run in the separate `api-tests` matrix job (`api (ce)`, `api (cloud)`, `api (ee, unit, migrations)`), so look there for their results, not in `build-test`. Without that, a piece only runs when its own files or `pieces/framework` / `pieces/common` change; a `core-utils` change alone does not pull pieces in. Any workspace version bump edits `bun.lock`, so this hits most PRs that bump a package. A CPU-heavy piece test can then fail on the starved runner with no change of yours: an Odoo polling test that takes ~350ms locally passed vitest's 5s default in 3 of 3 runs, reruns included. Don't keep rerunning: give the heavy test an explicit timeout (third `it` argument). Even a test-only change needs that piece's patch bump (and its `bun.lock` line): `validate-publishable-packages` diffs the whole package folder against `origin/main`.- **After the base PR of a stack merges, merging main into the next PR silently keeps the base PR's old lines.** The merge base predates the base PR, so code the base PR dropped during review (fields, routes, columns) looks like a branch addition and survives with no conflict. Check with `git diff --name-only origin/main`: every file must be one the stacked PR itself changed. If not, save the stacked PR's own patch first (`git diff --binary <base-PR tip it was built on> <head before the merge> > pr.patch`; without `--binary`, an image or other binary file is written as "Binary files differ" and `read-tree` deletes it with no way back), then `git read-tree -u --reset origin/main` and `git apply --3way pr.patch`, and commit. `read-tree` also deletes files that exist only on the branch (a file the base PR added, then dropped), which `git checkout origin/main -- .` would leave behind. Use `origin/main`, not `MERGE_HEAD`: a merge with no conflicts commits itself and `MERGE_HEAD` is gone. **The rebuild is not finished until `origin/main` is an ancestor.** `read-tree` + `apply` makes a commit whose *tree* is main + patch, but the merge base with main is still the old one, so GitHub's PR diff counts every main change since then as the PR's (seen: 731 files for a 43-file PR). Follow it with `git merge origin/main`; every conflict is the same change on both sides, so `git diff --name-only --diff-filter=U | xargs git checkout --ours --` is the answer, and `git diff --cached HEAD --stat` must print nothing before you commit (the tree does not change, only the ancestry). A branch cut from a stacked branch with `git checkout -b` inherits its **upstream**, so `git status -sb` reads `feat/pr-4...origin/feat/pr-3` and a plain `git push` would push PR 4's commits onto PR 3's remote; run `git branch --unset-upstream` right after cutting it (seen 2026-10-05 on `feat/platform-tiers-admin-ui`). Then retarget it (`gh pr edit <n> --base main`): a PR still pointed at the merged base branch shows every main change since then (seen: 1,285 files for a 28-file PR). No rebase or force push needed.@@ -92,6 +94,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).+- **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.- **Cherry-picking a merged PR onto a release branch: the commit-msg hook rejects it, and `breaking-changes.mdx` conflicts pull in other people's entries.** GitHub writes the squash header server-side, so `fix(flows): … instead of reverting them (#14899)` never faced commitlint — replaying it locally trips the 100-character header limit and `git cherry-pick --continue` dies in husky with the working tree half-applied. Finish it with `git commit --no-verify -C <original-sha>` rather than rewording, so the release branch keeps the same subject as `main`. The `Unreleased` section of `docs/install/reference/breaking-changes.mdx` conflicts on almost every pick because it accumulates entries from unrelated `main` work: take only the section your own commit added. **Take it by its own heading, not by "everything after the marker" — the incoming side of that hunk usually runs on into `main`'s copy of an already-published `## X.Y.Z` section, and pasting the tail duplicates ~200 lines of published notes that no test, lint or typecheck will ever notice.** The reliable move is to rebuild the file: `git checkout origin/release/<version> -- docs/install/reference/breaking-changes.mdx`, then insert your entry under its own `## <new version>` heading above the previous release's, and confirm with `git diff --stat` that only your lines are added and `grep -c '^## '` that no version heading appears twice. Then run `bun install` before pushing — the release branch's `bun.lock` is usually stale against its own `package.json`s, and the pick drags those stale piece versions along until install corrects them; `git diff --stat origin/release/<version> -- bun.lock` should come back as just the packages your pick actually bumped. Expect the **PR size** gate to block it too: the picked commits drag their own upstream tests along (769/600 in `server/api` for two picks), and splitting a replay of already-reviewed work is the wrong answer — add `large-pr-ok`.diff --git a/brain/knowledge/engineering/server-module-anatomy.md b/brain/knowledge/engineering/server-module-anatomy.mdindex 4e8b438b5bb..f338188a3b9 100644--- a/brain/knowledge/engineering/server-module-anatomy.md+++ b/brain/knowledge/engineering/server-module-anatomy.md@@ -165,6 +165,7 @@ Verify with `npm run lint-dev` and `npm run test-api`.- **`permission: undefined` on `securityAccess.project(...)` silently allows any project member.** The argument is required in practice even though the type tolerates omitting it.- **Anything that does network I/O inside a module's `setup()` adds its own timeout to boot.** `app.ts` awaits every `setup()` and every `register()` in one sequential chain before the server listens, so a single `await someClient.load()` in a `setup()` means a slow or unreachable host delays startup by that client's full timeout — on every boot, for every self-hoster, including the ones with no outbound internet who will never get a useful answer. An unbounded `await` of the model-tier warm-up in `aiProviderService.setup()` put up to 10 seconds on the boot path this way; `modelTierCatalog.warmUp()` now races a 2 s timer for exactly that reason. The repo already has the right idiom a few lines above, and it is worth copying rather than reinventing: `rejectedPromiseHandler(toolSearchReindexJob(app.log).backfillIfNeeded(), app.log)` fires the work off and lets boot continue, with a comment saying it must never block or fail boot. If you genuinely need the value before the first request, give that one call its own short timeout instead of inheriting the client's.- **`security` goes under `config`, never under `schema`, and putting it in the wrong half fails silently.** Fastify reads the security config off `config`; a `security` key inside `schema` is just an unknown property on the schema object, so nothing validates it, nothing warns, and the route ships with no security config at all. It reads as correct at a glance because the two keys sit next to each other in the same literal and every route in the file has both. Caught on `GET /v1/ai-providers/tiers` before merge only because the diff was being read line by line. When you add a route, compare its literal against the one above it: `config: { security }` then `schema: { body, response }`, in that order.+- **Inside `transaction(...)`, every read must go through `repo(entityManager)`, including reads inside helpers you call.** A bare `repo()` takes a second pool connection while the transaction still holds its own, so with `AP_POSTGRES_POOL_SIZE=1` it waits forever and any row lock you took stays held. Thread `entityManager` down as an optional param (as `aiProviderService.findRunKeyId` does for agent move). PGlite tests cannot catch this either: one in-process connection never runs out.- **Every query filters by `projectId` or `platformId`.** For connections with multi-project access, use `ArrayContains([projectId])` on the `projectIds` array column.- **A mutation test against a `packages/core/*` package proves nothing until you rebuild its dist.** The api package resolves `@activepieces/core-utils` and friends through `node_modules` to `dist/`, not through the tsconfig path to `src/`, so breaking the source and re-running an api test reports a pass while the test is still executing the old build. Measured: removing the connection-template unwrap from `core-utils/src` left `agent-tool-pinning.test.ts` fully green, and the same mutation failed it once `turbo run build --filter=@activepieces/core-utils` had run. Web tests do not share the trap — vitest aliases the core packages to `src` in `packages/web/vitest.config.ts` — so a web suite catching a core mutation while the api suite ignores it is the signature of a stale dist rather than of missing coverage. Same cause as the phantom "has no exported member" errors after merging a branch that adds a core export.- **`npx vitest` must be run from `packages/server/api`, never the repo root.** The config's `setupFiles` is what loads `.env.tests`, and from the root that setup never runs, so every suite dies in `beforeAll` with `SYSTEM_PROP_NOT_DEFINED: AP_POSTGRES_DATABASE` (thrown from `createPostgresDataSource`) and vitest reports the file as a failed *suite* with all its tests skipped. It reads exactly like a real breakage in whatever you just changed — the tell is that the stack bottoms out in `test-setup.ts`/`database-connection.ts` and never reaches your code, and that the run's stdout is missing the `Configuring vitest …/.env.tests` line a healthy run prints first. `npm run test-api` sets the cwd for you; a hand-written `npx vitest run test/…` does not.diff --git a/brain/knowledge/engineering/web-feature-anatomy.md b/brain/knowledge/engineering/web-feature-anatomy.mdindex 8e29cafe00e..b492261e22a 100644--- a/brain/knowledge/engineering/web-feature-anatomy.md+++ b/brain/knowledge/engineering/web-feature-anatomy.md@@ -164,8 +164,10 @@ way back was to stash the handful of intended edits, `git checkout` the package,- **Platform admin has two page shells that disagree, and one settings-row primitive that got cloned five times.** `DashboardPageHeader` (over `components/custom/page-header.tsx`) is `sticky top-0 z-30`, `text-base font-semibold`, full width, and respects `embedState.hidePageHeader`; `CenteredPage` is `max-w-[40rem] mx-auto py-6`, `text-xl font-medium`, and follows itself with a `Separator`. Twelve admin pages take the first, six the second, and four (billing, usage, embed, AI Center) hand-roll their own `h1` instead. Nothing marks which a new page should use, so the choice has been made per-page by whoever copied the nearest neighbour. Same story one level down: `components/custom/item.tsx` (`Item` / `ItemGroup` / `ItemTitle` / `ItemDescription` / `ItemActions`) is the intended label-left, control-right settings row and has nine call sites, eight of them in platform admin, with SSO the clearest reference. But five local re-implementations sit beside it and reuse none of it: `BillingSection` in `billing/index.tsx`, `HealthCard` plus `HealthRowItem` in `infra/health/components/system-health-tab.tsx` (a near-clone of `Item` + `ItemGroup` + `ItemSeparator`), `SectionHeader` under `setup/ai/components/`, an open-coded `Item variant="outline"` in `setup/general/danger-zone-section.tsx`, and `AutoIncludePill` in `piece-set-details-page.tsx`. Reach for `Item` before writing a row, and check whether the clone next to you is one of those five. The real outlier is `appearance-section.tsx`, which is a vertically stacked `FormItem` form rather than a row list, so it is the one file a standardisation pass has to decide about rather than mechanically convert.- **`packages/web/public/locales/en/translation.json` contains duplicate keys, so no JSON tool may rewrite it — edit it as text.** `agentMoveLosesConnections`, `No projects yet`, `All projects` and `Model` each appear twice today. Any parse-and-dump round-trip (Python's `json`, `jq`, a formatter) silently keeps only the last of each pair and drops the rest, and will additionally unescape every `\uXXXX` sequence in the file — one such round-trip to add a single key produced a 36-line diff with a key deletion buried in it. Add or rename a key with a targeted string replacement and check `git diff --stat` says 1 insertion.- **Resolving a `translation.json` merge conflict is where that rule is hardest to keep and most worth keeping.** Both sides append to a flat map, so any long-lived web branch conflicts here, and the obvious resolution is to parse both sides and dump the union. That loses the duplicates and escapes exactly as above. It also has a three-way trap of its own: keeping every key that is in *ours* resurrects the keys main **deleted**, because our side never removed them either. Merge as main's bytes plus only the keys our side actually added (`in ours, not in the merge base`), appended as text before the closing brace, then confirm `git diff origin/main` is purely additive. Anything else and a reviewer sees deletions in a file they expected to grow.+- **The "New translation files" sync can delete `en` keys that are still in use.** #16370 pruned 361 keys and took `"Couldn't load {key} models"` with them, though the Tiers page calls it as `t("Couldn't load {key} models")`: keys written in double quotes (the usual form when the key holds an apostrophe) slip past whatever decides a key is unused. After merging such a sync, check that every `t('…')` / `t("…")` literal in your changed files is still a key, and add missing ones back as text.- **`AllowOnlyLoggedInUserOnlyGuard` calls its hooks after two early returns, and the linter only lets it.** `react-hooks/rules-of-hooks` does not flag member-expression calls, so `platformHooks.useCurrentPlatform()` / `flagsHooks.useFlags()` sail past it — but add a bare `useSomething()` there and the rule fires, correctly: `isLoggedIn()` can change between renders, so those calls really are conditional. Anything new that needs to run once a session is authenticated belongs in a null-rendering component placed inside the returned `<SocketProvider>` subtree, which mounts only after the guard passes. That is why automatic trial activation is `<AutomaticTrialActivation />` and not a hook.- **The layering is lint-enforced, not just a convention.** `packages/web/.eslintrc.json` has an `import/no-restricted-paths` zone making the codebase unidirectional: `src/app` may import `src/features`, and both may import `src/lib`/`hooks`/`components`/`types`/`utils` — never the reverse (the one exception is `app/query-client.ts`). So a hook that a public route needs belongs in `src/lib`, but anything rendering a feature's components has to live in that feature; you cannot keep the pair in one `lib` file. It fails as an `import/no-restricted-paths` **error**, not a warning, so it blocks lint.+- **`cn()` silently drops `text-xss` when a text colour is in the same call.** `cn` is plain `twMerge` with no config, so it does not know `xss` is a font size. It treats `text-xss` as a colour and lets a later `text-gray-11` or `text-warning-11` win. The element renders at the inherited size, with no error. Keep `text-xss` in a static `className`, or outside the `cn()` that also picks a colour. The same `twMerge` also misses Tailwind v4's `w-(--var)` syntax, so a component's default `w-72` wins over it. Write `w-[var(--radix-popover-trigger-width)]` instead.- **Arbitrary Tailwind values for type, tracking and radius get sent back in review — `packages/web` has its own scale and it is not stock Tailwind.** There is no `tailwind.config.js`; this is Tailwind v4 and the theme lives in the `@theme` block of `src/styles.css`, which *adds* `--text-xss: 0.65rem`, *overrides* `--text-3xl` to 1.75rem and `--text-4xl` to 2rem (both smaller than stock), and derives `--radius-{sm,md,lg,xs,xss}` from a single `--radius: 0.5rem`. So `text-[13px]`, `tracking-[-0.025em]` and `rounded-[11px]` are not just style nits — they sit *between* real tokens and drift the page off the scale. Map them: 10–11px → `text-xss`, 11.5–12.5px → `text-xs`, 13–13.5px → `text-sm`, 15–15.5px → `text-base`; negative tracking → `tracking-tight`, uppercase-eyebrow tracking → `tracking-wide`/`wider`; any `rounded-[9–11px]` → `rounded-md`. **A colour handed over as a hex is usually a step, and hardcoding it breaks dark mode**: every step but the brand solid is rebound in the `[data-theme='dark']` block, so a light-mode lavender hardcoded as hex sits under dark-mode text unchanged. Match the hex to the nearest step (a pale lavender is `accent-2` or `accent-3`) rather than reaching for `bg-[#...]`; see *design-system/colour*. Layout constraints are the exception and stay arbitrary — `max-w-[628px]` for a reading measure or `lg:w-[344px]` for a sidebar have no token equivalent and are idiomatic. Fractional spacing (`size-5.5`, `size-8.5`, `size-13`) is valid in v4 and beats `size-[22px]`, but **only at half-steps** — v4 generates `.5` and whole numbers, so a finer fraction like `ml-3.9` produces no rule at all and the property computes to `0`, with no build error and no lint error to say so. If a measured value falls between half-steps, either derive it from the geometry and round to the nearest real step, or use the arbitrary value; never invent a decimal and assume it took. Read the computed style back in the browser rather than trusting the class name. Neither eslint nor `tsc` catches any of this, so it only ever surfaces in review — the mapping is written up in the *Tailwind / Styling* section of `packages/web/AGENTS.md` so agents meet it before writing the class. Above 15.5px there is no px mapping, because heading sizes are a per-surface decision: copy the token the neighbouring heading on the same page already uses (a `text-[22px]` page heading becomes the `text-xl` its sibling section headings use) rather than rounding to the closest number.- **`npx prettier --check` lies about `packages/web` — it flags files nobody has touched, so never treat it as a gate.** Prettier is not in any CI workflow, and the root `.prettierrc` is a single `{"singleQuote": true}` while the resolved binary is prettier **2.8.4**, whose `trailingComma` default is `es5`. The checked-in code is formatted by prettier 3 (via the editor / eslint integration), which defaults to `all` — so every multi-line call with a trailing comma reads as a "code style issue". Running `--check` on a file straight out of `git show HEAD:` reproduces it. If you want to know whether your own edit is formatted, diff `npx prettier <file>` against the file and check the hunks are yours; the pass/fail verdict is meaningless. `npx turbo run lint --filter=web` is the real gate.- **A date test with hardcoded `Z` fixtures is a false green — CI runs UTC, and both `dayjs().isSame(x, 'day')` and `formatUtils.formatDate` are *local*.** Freezing the clock with `vi.setSystemTime(new Date('…Z'))` and then asserting against a literal `'2025-09-15T00:30:00Z'` only holds where local time is UTC. `grant-utils.test.ts` on [#15079](https://github.com/activepieces/activepieces/pull/15079) was 3/3 green in CI and on `TZ=UTC`, 1 failed on `TZ=America/New_York` (`00:30Z` is the *previous* local day, so "Active today" flips to "Last used Yesterday"), 2 failed on `TZ=Pacific/Honolulu` (the second being `formatDate` rendering `Aug 11` where the test asserted `Aug 12`). Nobody in the Americas can run the suite clean, and nothing in CI will ever tell you. Derive every fixture from the frozen clock instead of writing a literal — `dayjs(NOW).startOf('day').add(30, 'minute')`, `dayjs(NOW).subtract(34, 'day')` — and assert with the same local formatter the code uses (`earlier.format('MMM D')`), so fixture and assertion move together in any zone. Check any new date test with `TZ=America/New_York` and `TZ=Pacific/Honolulu` before pushing; those two straddle UTC on both sides and catch it. The production `isSame(…, 'day')` is *correct* — a user's "today" is their own day — so the bug is always in the test, never in the formatter.diff --git a/bun.lock b/bun.lockindex 04eaf322f8e..fceaa07c6fb 100644--- a/bun.lock+++ b/bun.lock@@ -166,7 +166,7 @@},"packages/core/shared": {"name": "@activepieces/shared",- "version": "0.200.1",+ "version": "0.201.0","dependencies": {"@activepieces/core-execution": "workspace:*","@activepieces/core-formula": "workspace:*",diff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex 73f05175055..42de9a917a6 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.200.2",+ "version": "0.201.0","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/management/ai-providers/index.ts b/packages/core/shared/src/lib/management/ai-providers/index.tsindex 31aba3cb417..74ae1c83820 100644--- a/packages/core/shared/src/lib/management/ai-providers/index.ts+++ b/packages/core/shared/src/lib/management/ai-providers/index.ts@@ -1,4 +1,4 @@-import { ActivePiecesProviderAuthConfig, ActivePiecesProviderConfig, AIProviderConfig, AiProviderCredentials, AiProviderKeyStatus, AIProviderModelType, AIProviderName, AnthropicProviderAuthConfig, AnthropicProviderConfig, AzureProviderAuthConfig, AzureProviderConfig, BaseAIProviderAuthConfig, BaseModelSchema, BedrockProviderAuthConfig, BedrockProviderConfig, CloudflareGatewayProviderAuthConfig, CloudflareGatewayProviderConfig, GoogleProviderAuthConfig, GoogleProviderConfig, MistralProviderAuthConfig, MistralProviderConfig, OpenAICompatibleProviderAuthConfig, OpenAICompatibleProviderConfig, OpenAiCompatibleVendorConfig, OpenAIProviderAuthConfig, OpenAIProviderConfig, OpenRouterProviderAuthConfig, OpenRouterProviderConfig, VertexProviderAuthConfig, VertexProviderConfig } from '@activepieces/core-utils'+import { ActivePiecesProviderAuthConfig, ActivePiecesProviderConfig, AIProviderConfig, AiProviderCredentials, AiProviderKeyStatus, AIProviderModelType, AIProviderName, AnthropicProviderAuthConfig, AnthropicProviderConfig, AzureProviderAuthConfig, AzureProviderConfig, BaseAIProviderAuthConfig, BaseModelSchema, BedrockProviderAuthConfig, BedrockProviderConfig, CloudflareGatewayProviderAuthConfig, CloudflareGatewayProviderConfig, GoogleProviderAuthConfig, GoogleProviderConfig, MistralProviderAuthConfig, MistralProviderConfig, Nullable, OpenAICompatibleProviderAuthConfig, OpenAICompatibleProviderConfig, OpenAiCompatibleVendorConfig, OpenAIProviderAuthConfig, OpenAIProviderConfig, OpenRouterProviderAuthConfig, OpenRouterProviderConfig, VertexProviderAuthConfig, VertexProviderConfig } from '@activepieces/core-utils'import { z } from 'zod'export { ActivePiecesProviderAuthConfig, ActivePiecesProviderConfig, AIProviderAuthConfig, AIProviderConfig, AiProviderCredentials, aiProviderCredentials, AIProviderModelType, AnthropicProviderAuthConfig, AnthropicProviderConfig, AzureProviderAuthConfig, AzureProviderConfig, BaseAIProviderAuthConfig, BedrockProviderAuthConfig, BedrockProviderConfig, CloudflareGatewayProviderAuthConfig, CloudflareGatewayProviderConfig, GoogleProviderAuthConfig, GoogleProviderConfig, MistralProviderAuthConfig, MistralProviderConfig, OpenAICompatibleProviderAuthConfig, OpenAICompatibleProviderConfig, OpenAiCompatibleVendorConfig, OpenAIProviderAuthConfig, OpenAIProviderConfig, OpenRouterProviderAuthConfig, OpenRouterProviderConfig, ProviderModelConfig, VertexProviderAuthConfig, VertexProviderConfig } from '@activepieces/core-utils'@@ -333,3 +333,78 @@ export type { ActivepiecesChatTier, ActivepiecesImageTier, AIProviderCapabilitieexport const AI_PIECE_COST_BILLING_VERSION = '0.11.0'export * from './platform-model-tier'++export const ModelOptionsSurface = z.enum(['flow', 'agent', 'chat'])++export const ModelChoice = z.discriminatedUnion('type', [+ z.object({+ type: z.literal('tier'),+ tierId: z.string(),+ }),+ z.object({+ type: z.literal('model'),+ provider: z.enum(AIProviderName),+ providerConfigId: z.string(),+ modelId: z.string(),+ }),+])++export const OptionModel = z.object({+ provider: z.enum(AIProviderName),+ modelId: z.string(),+ name: z.string(),+ keyName: z.string(),+ metadata: AIProviderModelMetadata.optional(),+})++export const ModelOptionsTier = z.object({+ id: z.string(),+ name: z.string(),+ emoji: z.string(),+ description: Nullable(z.string()),+ isDefault: z.boolean(),+ isFast: z.boolean(),+ main: OptionModel,+ fallbacks: z.array(OptionModel),+})++export const ModelOptionsCredits = z.object({+ providerConfigId: z.string(),+ defaultTierId: z.string(),+ tiers: z.array(z.object({+ id: z.string(),+ label: z.string(),+ model: OptionModel,+ })),+})++export const ModelOptionsKey = z.object({+ providerConfigId: z.string(),+ provider: z.enum(AIProviderName),+ name: z.string(),+ models: z.array(AIProviderModel),+})++export const ModelOptions = z.object({+ tiers: z.array(ModelOptionsTier),+ credits: Nullable(ModelOptionsCredits),+ keys: z.array(ModelOptionsKey),+ defaultChoice: Nullable(ModelChoice),+ movedTiers: z.record(z.string(), z.string()),+ specificModelsHidden: z.boolean(),+})++export const ListModelOptionsRequest = z.object({+ projectId: z.string(),+ surface: ModelOptionsSurface,+ tierId: z.string().optional(),+})++export type ModelOptionsSurface = z.infer<typeof ModelOptionsSurface>+export type ModelChoice = z.infer<typeof ModelChoice>+export type OptionModel = z.infer<typeof OptionModel>+export type ModelOptionsTier = z.infer<typeof ModelOptionsTier>+export type ModelOptionsCredits = z.infer<typeof ModelOptionsCredits>+export type ModelOptionsKey = z.infer<typeof ModelOptionsKey>+export type ModelOptions = z.infer<typeof ModelOptions>+export type ListModelOptionsRequest = z.infer<typeof ListModelOptionsRequest>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.tsnew file mode 100644index 00000000000..6c55965a9e3--- /dev/null+++ b/packages/server/api/src/app/ai/ai-model-options-service.ts@@ -0,0 +1,146 @@+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 { FastifyBaseLogger } from 'fastify'+import { platformConfigurationService } from '../platform/platform-configuration.service'+import { aiKeyScope } from './ai-key-scope'+import { AIProviderSchema } from './ai-provider-entity'+import { aiProviderService, ProjectKeyModels } from './ai-provider-service'+import { platformModelTierService, TierForRun } from './platform-model-tier-service'++export 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([+ aiProviderService(log).listKeysForProject({ platformId, projectId }),+ platformModelTierService.listForPicker({ platformId, scope: { type: 'project', projectId } }),+ platformModelTierService.movedTiers({ platformId, tierId }),+ platformConfigurationService(log).getOrCreateForPlatform({ platformId }),+ 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,+ }+ },+})++export const aiModelOptionsUtils = {+ defaultChoice({ surface, tiers, credits, keys, chatKeyId }: DefaultChoiceParams): ModelChoice | null {+ 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 })+ }+ if (!isNil(credits)) {+ return { type: 'model', provider: AIProviderName.ACTIVEPIECES, providerConfigId: credits.providerConfigId, modelId: credits.defaultTierId }+ }+ if (tiers.length > 0) {+ return { type: 'tier', tierId: tiers[0].id }+ }+ const firstKey = keys.find((key) => key.models.length > 0)+ return isNil(firstKey) ? null : modelChoiceOf({ key: firstKey, modelId: firstKey.models[0].id })+ },+}++function toTierOption({ forRun, keys, lookup, callsTools }: { forRun: TierForRun, keys: ProjectKeyModels[], lookup: Lookup, callsTools: CallsTools }): ModelOptionsTier[] {+ const { tier, entries } = forRun+ const usable = entries.filter((entry) => callsTools({ provider: entry.key.provider, modelId: entry.modelId }))+ const [main, ...fallbacks] = usable+ if (isNil(main) || main !== entries[0]) {+ return []+ }+ const optionOf = (entry: TierForRun['entries'][number]): OptionModel => ({+ provider: entry.key.provider,+ modelId: entry.modelId,+ name: keys.find((key) => key.row.id === entry.key.id)?.models?.find((model) => model.id === entry.modelId)?.name ?? entry.modelId,+ keyName: entry.key.displayName,+ ...spreadIfDefined('metadata', lookup({ provider: entry.key.provider, modelId: entry.modelId })),+ })+ return [{+ id: tier.id,+ name: tier.name,+ emoji: tier.emoji,+ description: tier.description ?? null,+ isDefault: tier.isDefault,+ isFast: tier.isFast,+ main: optionOf(main),+ fallbacks: fallbacks.map(optionOf),+ }]+}++function toCredits({ row, surface, lookup }: { row: AIProviderSchema, surface: ModelOptionsSurface, lookup: Lookup }): ModelOptionsCredits {+ const catalog = modelTierCatalog.current(surface === 'chat' ? 'chat' : 'flow')+ return {+ providerConfigId: row.id,+ defaultTierId: catalog.defaultTierId,+ tiers: catalog.tiers.map((tier) => ({+ id: tier.id,+ label: tier.label,+ model: {+ provider: AIProviderName.ACTIVEPIECES,+ modelId: tier.modelId,+ name: tier.modelId,+ keyName: row.displayName,+ ...spreadIfDefined('metadata', lookup({ provider: AIProviderName.ACTIVEPIECES, modelId: tier.modelId })),+ },+ })),+ }+}++function toKeyOption({ key, surface, lookup, callsTools }: { key: ProjectKeyModels, surface: ModelOptionsSurface, lookup: Lookup, callsTools: CallsTools }): ModelOptionsKey[] {+ const { row, models } = key+ if (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 }))+ return 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[] {+ 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 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 })),+ })+}++function modelChoiceOf({ key, modelId }: { key: ModelOptionsKey, modelId: string }): ModelChoice {+ return { type: 'model', provider: key.provider, providerConfigId: key.providerConfigId, modelId }+}++type Lookup = (params: { provider: AIProviderName, modelId: string }) => OptionModel['metadata']+type CallsTools = (params: { provider: AIProviderName, modelId: string }) => boolean++type DefaultChoiceParams = {+ surface: ModelOptionsSurface+ tiers: ModelOptionsTier[]+ credits: ModelOptionsCredits | null+ keys: ModelOptionsKey[]+ chatKeyId: string | undefined+}diff --git a/packages/server/api/src/app/ai/ai-provider-controller.ts b/packages/server/api/src/app/ai/ai-provider-controller.tsindex 6d57ba754fa..e21bad2b0cc 100644--- a/packages/server/api/src/app/ai/ai-provider-controller.ts+++ b/packages/server/api/src/app/ai/ai-provider-controller.ts@@ -1,12 +1,13 @@import { AiProviderKeyStatus, AIProviderName } from '@activepieces/core-utils'import { modelTierCatalog } from '@activepieces/server-utils'-import { AIProviderModel, CreateAIProviderRequest, PrincipalType, spreadIfDefined, UpdateAIProviderRequest } from '@activepieces/shared'+import { AIProviderModel, CreateAIProviderRequest, ModelOptions, ModelOptionsSurface, PrincipalType, spreadIfDefined, UpdateAIProviderRequest } from '@activepieces/shared'import { FastifyRequest } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'import { z } from 'zod'import { ProjectResourceType } from '../core/security/authorization/common'import { securityAccess } from '../core/security/authorization/fastify-security'+import { aiModelOptionsService } from './ai-model-options-service'import { aiProviderService } from './ai-provider-service'export const aiProviderController: FastifyPluginAsyncZod = async (app) => {@@ -29,6 +30,14 @@ export const aiProviderController: FastifyPluginAsyncZod = async (app) => {flow: modelTierCatalog.current('flow'),chat: modelTierCatalog.current('chat'),}))+ app.get('/model-options', ListModelOptions, async (request) => {+ return aiModelOptionsService(app.log).list({+ platformId: request.principal.platform.id,+ projectId: request.projectId,+ surface: request.query.surface,+ tierId: request.query.tierId,+ })+ })app.get('/:provider/models', ListModels, async (request) => {return aiProviderService(app.log).listModels({platformId: request.principal.platform.id,@@ -113,6 +122,22 @@ const ListModelTiers = {},}+const ListModelOptions = {+ config: {+ security: securityAccess.project([PrincipalType.USER], undefined, { type: ProjectResourceType.QUERY }),+ },+ schema: {+ querystring: z.object({+ projectId: z.string().optional(),+ surface: ModelOptionsSurface,+ tierId: z.string().optional(),+ }),+ 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 13319e23064..8fca1a9aab0 100644--- a/packages/server/api/src/app/ai/ai-provider-service.ts+++ b/packages/server/api/src/app/ai/ai-provider-service.ts@@ -71,6 +71,23 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({: models},+ 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 })),+ }+ }))+ },+async listModelsForConfig({ platformId, configId }: { platformId: PlatformId, configId: string }): Promise<AIProviderModel[]> {const aiProvider = await getRowByIdOrThrow({ platformId, configId })return fetchModels({ aiProvider, platformId, log })@@ -176,6 +193,17 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({return chatProvider?.provider ?? null},+ async getChatKey({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): Promise<AIProviderSchema | null> {+ return findAvailableChatProviderRow({ platformId, scope, log })+ },++ async findRunKeyId({ platformId, provider, scope, preferredConfigId, entityManager }: { platformId: PlatformId, provider: AIProviderName, scope: ProviderScope, preferredConfigId?: string, entityManager?: EntityManager }): Promise<string | null> {+ const rows = await aiProviderRepo(entityManager).findBy({ platformId, provider })+ const eligible = rows.filter((row) => aiKeyScope.rowAllowsScope({ row, scope }))+ const preferred = eligible.find((row) => row.id === preferredConfigId)+ return (preferred ?? rankRows({ rows: eligible, scope })[0])?.id ?? null+ },+async getChatProvider({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): Promise<GetProviderConfigResponse | null> {const chatProvider = await findAvailableChatProviderRow({ platformId, scope, log })if (isNil(chatProvider)) {@@ -692,3 +720,9 @@ function getModelsCacheKey({ provider, auth, config }: { provider: AIProviderNam}export type { ProviderScope }++export type ProjectKeyModels = {+ row: AIProviderSchema+ isChatKey: boolean+ models: AIProviderModel[] | null+}diff --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 5258b958367..97750be1a4e 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,6 +35,24 @@ export const platformModelTierService = {return listLive({ platformId })},+ async listForPicker({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): 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 }) }))+ },++ async movedTiers({ platformId, tierId }: { platformId: PlatformId, tierId: string | undefined }): Promise<Record<string, string>> {+ if (isNil(tierId)) {+ return {}+ }+ const live = (await followReplacementsInBulk({ platformId, ids: [tierId] })).get(tierId)+ return isNil(live) || live.id === tierId ? {} : { [tierId]: live.id }+ },+async create({ platformId, request }: { platformId: PlatformId, request: CreatePlatformModelTierRequest }): Promise<PlatformModelTier> {return withNameConflictAsValidation(() => transaction(async (manager) => {await lockPlatform({ manager, platformId })@@ -272,11 +290,15 @@ function entryRunsIn({ entry, key, scope }: { entry: PlatformModelTierEntry, key&& aiKeyScope.rowAllowsScope({ row: key, scope })}-function runnableEntries({ tier, keyById, scope }: { tier: PlatformModelTier, keyById: Map<string, AIProviderSchema>, scope: ProviderScope }): TierForRun['entries'] {- const runnable = tier.entries.flatMap((entry) => {+function entriesThatRun({ tier, keyById, scope }: { tier: PlatformModelTier, keyById: Map<string, AIProviderSchema>, scope: ProviderScope }): TierForRun['entries'] {+ return tier.entries.flatMap((entry) => {const key = keyById.get(entry.configId)return isNil(key) || !entryRunsIn({ entry, key, scope }) ? [] : [{ modelId: entry.modelId, key }]})+}++function runnableEntries({ tier, keyById, scope }: { tier: PlatformModelTier, keyById: Map<string, AIProviderSchema>, scope: ProviderScope }): TierForRun['entries'] {+ const runnable = entriesThatRun({ tier, keyById, scope })return [...runnable.filter((entry) => entry.key.status === 'active'),...runnable.filter((entry) => entry.key.status !== 'active'),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 e5fb3ac9ec6..f450281df4f 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@@ -107,8 +107,8 @@ function resolveModelIdForProvider({ provider, selectedModel, surface, config, mreturn pickAllowedModel({ provider, selectedModel: preferred, candidates, modelScope, modelIds })}-function defaultModelIdForProvider({ provider, surface }: { provider: AIProviderName, surface: ModelTierSurface }): string | null {- const { data } = tryCatchSync(() => resolveModelIdForProvider({ provider, selectedModel: modelTierCatalog.current(surface).defaultTierId, surface }))+function defaultModelIdForProvider({ provider, surface, config, modelScope, modelIds }: { provider: AIProviderName, surface: ModelTierSurface, config?: AiProviderCredentials['config'], modelScope?: AiProviderModelScope, modelIds?: string[] }): string | null {+ const { data } = tryCatchSync(() => resolveModelIdForProvider({ provider, selectedModel: modelTierCatalog.current(surface).defaultTierId, surface, config, modelScope, modelIds }))return data}diff --git a/packages/server/api/src/app/ee/agent/agent-service.ts b/packages/server/api/src/app/ee/agent/agent-service.tsindex 8ead302af57..10bb0f10575 100644--- a/packages/server/api/src/app/ee/agent/agent-service.ts+++ b/packages/server/api/src/app/ee/agent/agent-service.ts@@ -4,6 +4,7 @@ import { ActivepiecesError, AIProviderName, apId, ApId, connectionTemplate, Cursimport { Agent, AgentConfig, AgentFlowTool, AgentKnowledgeBaseTool, AgentListSort, AgentMoveLoss, AgentMoveLossKind, AgentMovePreview, AgentRunSource, AgentSummary, agentUtils, AgentVisibility, CreateAgentRequest, DefaultProjectRole, Project, ProjectType, UpdateAgentRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { Brackets, EntityManager, In, SelectQueryBuilder } from 'typeorm'+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'import { transaction } from '../../core/db/transaction'@@ -36,7 +37,7 @@ const AGENT_MOVED_AWAY = 'That agent has just been moved somewhere else. Reloadexport const agentService = (log: FastifyBaseLogger) => ({async create({ platformId, projectId, ownerId, request }: CreateParams): Promise<Agent> {const visibility = request.visibility ?? AgentVisibility.PROJECT- const draft = await withDefaultModel({ draft: await withTierOrModel({ draft: request.draft, platformId, projectId, log }), platformId, projectId, log })+ const draft = await withPinnedKey({ draft: await withDefaultModel({ draft: await withTierOrModel({ draft: request.draft, platformId, projectId, log }), platformId, projectId, log }), platformId, projectId, log })return agentRepo().save({id: apId(),projectId,@@ -120,7 +121,7 @@ export const agentService = (log: FastifyBaseLogger) => ({projectId,log,})- const draft = isNil(request.draft) ? agent.draft : sanitizeObjectForPostgresql(await withTierOrModel({ draft: request.draft, platformId, projectId, log }))+ const draft = isNil(request.draft) ? agent.draft : sanitizeObjectForPostgresql(await withPinnedKey({ draft: await withTierOrModel({ draft: request.draft, platformId, projectId, log }), platformId, projectId, log }))await getFolderIdFromRequest({ projectId, folderId: request.folderId ?? undefined, folderName: undefined, log })const goingLive = goLive && agentUtils.isPublishable(draft)const published = goingLive ? draft : agent.published@@ -270,6 +271,10 @@ export const agentService = (log: FastifyBaseLogger) => ({await transaction(async (entityManager) => {const repo = entityManager.getRepository(AgentEntity)const locked = await lockedAgentInProjectOrThrow({ entityManager, id, projectId })+ const [draft, published] = await Promise.all([+ withKeyFor({ config: locked.draft, platformId, projectId: target.id, entityManager, log }),+ isNil(locked.published) ? null : withKeyFor({ config: locked.published, platformId, projectId: target.id, entityManager, log }),+ ])const sharedWithUserIds = await resolveShare({ visibility: locked.visibility, requested: undefined, stored: locked.sharedWithUserIds, projectId: target.id, log })const clash = await repo.findOneBy({ projectId: target.id, externalId: agent.externalId })if (!isNil(clash)) {@@ -291,6 +296,7 @@ export const agentService = (log: FastifyBaseLogger) => ({if (movedRows.length === 0) {throw refuseBecauseFlowsUseIt({ agent, flowsInUse: await agentService(log).publishedFlowsUsing({ agent, projectId, userId }) })}+ await repo.save({ id, draft, published })await entityManager.getRepository(AgentConversationEntity).update({ agentId: id, source: AgentRunSource.AGENT },{ projectId: target.id },@@ -440,17 +446,45 @@ async function withDefaultModel({ draft, platformId, projectId, log }: {if (!isNil(draft.modelName) || !isNil(draft.modelTierId)) {return draft}- const provider = await agentHelpers.resolveChatProviderName({ platformId, projectId, log })- if (isNil(provider)) {+ const chatKey = await aiProviderService(log).getChatKey({ platformId, scope: { type: 'project', projectId } })+ if (isNil(chatKey)) {return draft}+ const { provider, id: providerConfigId } = chatKeyconst modelName = provider === AIProviderName.ACTIVEPIECES? agentHelpers.resolveTier({ tierId: null, surface: 'flow' }).id- : agentHelpers.defaultModelIdForProvider({ provider, surface: 'flow' })+ : agentHelpers.defaultModelIdForProvider({ provider, surface: 'flow', config: chatKey.config, modelScope: chatKey.modelScope, modelIds: chatKey.modelIds })if (isNil(modelName)) {- return { ...draft, provider }+ return { ...draft, provider, providerConfigId }}- return { ...draft, provider, modelName }+ return { ...draft, provider, providerConfigId, modelName }+}++async function withPinnedKey({ draft, platformId, projectId, log }: {+ draft: AgentConfig+ platformId: PlatformId+ projectId: ProjectId+ log: FastifyBaseLogger+}): Promise<AgentConfig> {+ if (isNil(draft.provider) || !isNil(draft.providerConfigId) || !isNil(draft.modelTierId)) {+ return draft+ }+ const configId = await aiProviderService(log).findRunKeyId({ platformId, provider: draft.provider, scope: { type: 'project', projectId } })+ return isNil(configId) ? draft : { ...draft, providerConfigId: configId }+}++async function withKeyFor({ config, platformId, projectId, entityManager, log }: {+ config: AgentConfig+ platformId: PlatformId+ projectId: ProjectId+ entityManager: EntityManager+ log: FastifyBaseLogger+}): Promise<AgentConfig> {+ if (isNil(config.provider) || isNil(config.providerConfigId)) {+ return config+ }+ const providerConfigId = await aiProviderService(log).findRunKeyId({ platformId, provider: config.provider, scope: { type: 'project', projectId }, preferredConfigId: config.providerConfigId, entityManager })+ return { ...config, providerConfigId }}async function resolveShare({ visibility, requested, stored, projectId, log }: ResolveShareParams): Promise<UserId[]> {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.tsnew file mode 100644index 00000000000..dadd1be0cd3--- /dev/null+++ b/packages/server/api/test/integration/ce/ai-provider/model-options.test.ts@@ -0,0 +1,169 @@+import { AIProviderName } from '@activepieces/core-utils'+import { modelCatalog } from '@activepieces/server-utils'+import { AIProviderModelType, ModelOptions, PlatformModelTier } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { vi } from 'vitest'+import { databaseConnection } from '../../../../src/app/database/database-connection'+import { mockAndSaveAIProvider } from '../../../helpers/mocks'+import { createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance | null = null+let ctx: TestContext++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++beforeEach(async () => {+ vi.restoreAllMocks()+ ctx = await createTestContext(app!)+})++describe('GET /v1/ai-providers/model-options', () => {+ it('hides a tier whose main key does not serve the project and drops fallbacks that cannot run there', async () => {+ const open = await seedKey({ name: 'Open', models: ['main', 'fallback'] })+ const away = await seedKey({ name: 'Away', models: ['main', 'fallback'], projectScope: 'except', projectIds: [ctx.project.id] })+ const shown = await createTier({ name: 'Shown', entries: [{ configId: open.id, modelId: 'main' }, { configId: away.id, modelId: 'fallback' }, { configId: open.id, modelId: 'fallback' }] })+ await createTier({ name: 'Hidden', entries: [{ configId: away.id, modelId: 'main' }] })++ const options = await listOptions({ surface: 'flow' })++ expect(options.tiers.map((tier) => tier.id)).toEqual([shown.id])+ expect(options.tiers[0].main).toMatchObject({ modelId: 'main', keyName: 'Open', name: 'main' })+ expect(options.tiers[0].fallbacks.map((fallback) => fallback.keyName)).toEqual(['Open'])+ expect(options.keys.map((key) => key.providerConfigId)).toEqual([open.id])+ })++ it('hides a tier whose main model cannot call tools on agent surfaces only', async () => {+ const key = await seedKey({ name: 'Key', models: ['no-tools', 'tools'] })+ const tier = await createTier({ name: 'Plain', entries: [{ configId: key.id, modelId: 'no-tools' }, { configId: key.id, modelId: 'tools' }] })+ mockCatalogWithoutToolsFor({ modelId: 'no-tools' })++ const flow = await listOptions({ surface: 'flow' })+ const agent = await listOptions({ surface: 'agent' })++ expect(flow.tiers.map((option) => option.id)).toEqual([tier.id])+ expect(agent.tiers).toEqual([])+ expect(agent.keys[0].models.map((model) => model.id)).toEqual(['tools'])+ })++ it('lists only the models the key allows and returns no keys when specific models are hidden', async () => {+ const key = await seedKey({ name: 'Key', models: ['allowed', 'blocked'] })+ await databaseConnection().getRepository('ai_provider').update({ id: key.id }, { modelScope: 'selected', modelIds: ['allowed'] })+ const tier = await createTier({ name: 'Expert', entries: [{ configId: key.id, modelId: 'allowed' }] })++ const visible = await listOptions({ surface: 'flow' })+ expect(visible.keys[0].models.map((model) => model.id)).toEqual(['allowed'])++ await databaseConnection().getRepository('platform_configuration').update({ platformId: ctx.platform.id }, { aiSpecificModelsVisible: false })+ const hidden = await listOptions({ surface: 'flow' })++ expect(hidden.keys).toEqual([])+ expect(hidden.specificModelsHidden).toBe(true)+ expect(hidden.tiers.map((option) => option.id)).toEqual([tier.id])+ })++ it('skips a key whose models cannot be loaded and still answers', async () => {+ const broken = await seedKey({ name: 'Broken', models: ['x'] })+ const working = await seedKey({ name: 'Working', models: ['y'] })+ await databaseConnection().getRepository('ai_provider').update({ id: broken.id }, { auth: { iv: 'bad', data: 'bad' } })++ const options = await listOptions({ surface: 'flow' })++ expect(options.keys.map((key) => key.providerConfigId)).toEqual([working.id])+ })++ it('maps a deleted tier to its live replacement', async () => {+ const key = await seedKey({ name: 'Key', models: ['a', 'b'] })+ const old = await createTier({ name: 'Old', entries: [{ configId: key.id, modelId: 'a' }] })+ const replacement = await createTier({ name: 'New', entries: [{ configId: key.id, modelId: 'b' }] })+ await ctx.delete(`${TIERS}/${old.id}`, { replacedBy: replacement.id })++ expect((await listOptions({ surface: 'flow', tierId: old.id })).movedTiers).toEqual({ [old.id]: replacement.id })+ expect((await listOptions({ surface: 'flow', tierId: replacement.id })).movedTiers).toEqual({})+ expect((await listOptions({ surface: 'flow' })).movedTiers).toEqual({})+ })++ it('offers chat only the typed-in models of a key with a manual model list', async () => {+ await mockAndSaveAIProvider({+ platformId: ctx.platform.id,+ provider: AIProviderName.VERTEX,+ displayName: 'Vertex',+ config: { project: 'acme', region: 'us-central1', models: [{ modelId: 'gemini-2.5-flash', modelName: 'Gemini 2.5 Flash', modelType: AIProviderModelType.TEXT }] },+ })++ const options = await listOptions({ surface: 'chat' })++ expect(options.keys.flatMap((key) => key.models.map((model) => model.id))).toEqual(['gemini-2.5-flash'])+ })++ 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' })++ const first = await createTier({ name: 'First', entries: [{ configId: key.id, modelId: 'first' }] })+ const second = await createTier({ name: 'Second', entries: [{ configId: key.id, modelId: 'second' }] })+ expect((await listOptions({ surface: 'flow' })).defaultChoice).toEqual({ type: 'tier', tierId: first.id })++ await ctx.post(`${TIERS}/${second.id}`, { isDefault: true })+ expect((await listOptions({ surface: 'flow' })).defaultChoice).toEqual({ type: 'tier', tierId: second.id })+ })++ it('shows credits when the managed provider is visible and prefers them over the first option', async () => {+ process.env.AP_OPENROUTER_PROVISION_KEY = 'test-provision-key'+ try {+ const managed = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ACTIVEPIECES, displayName: 'Activepieces' })+ await seedKey({ name: 'Key', models: ['first'] })++ const options = await listOptions({ surface: 'chat' })++ expect(options.credits?.providerConfigId).toBe(managed.id)+ expect(options.credits?.tiers.length).toBeGreaterThan(0)+ expect(options.defaultChoice).toEqual({ type: 'model', provider: AIProviderName.ACTIVEPIECES, providerConfigId: managed.id, modelId: options.credits?.defaultTierId })+ }+ finally {+ delete process.env.AP_OPENROUTER_PROVISION_KEY+ }+ })+})++async function listOptions({ surface, tierId }: { surface: 'flow' | 'agent' | 'chat', tierId?: string }): Promise<ModelOptions> {+ const response = await ctx.get('/v1/ai-providers/model-options', { projectId: ctx.project.id, surface, ...(tierId ? { tierId } : {}) })+ expect(response.statusCode).toBe(StatusCodes.OK)+ return response.json()+}++async function seedKey({ name, models, projectScope, projectIds }: { name: string, models: string[], projectScope?: 'all' | 'selected' | 'except', projectIds?: string[] }): Promise<{ id: string }> {+ return mockAndSaveAIProvider({+ platformId: ctx.platform.id,+ provider: AIProviderName.CUSTOM,+ displayName: name,+ config: {+ baseUrl: 'https://api.example.com/v1',+ apiKeyHeader: 'Authorization',+ models: models.map((modelId) => ({ modelId, modelName: modelId, modelType: AIProviderModelType.TEXT })),+ },+ ...(projectScope ? { projectScope } : {}),+ ...(projectIds ? { projectIds } : {}),+ })+}++async function createTier({ name, entries }: { name: string, entries: { configId: string, modelId: string }[] }): Promise<PlatformModelTier> {+ const response = await ctx.post(TIERS, { name, emoji: '⚡', description: null, entries })+ expect(response.statusCode).toBe(StatusCodes.OK)+ return response.json()+}++function mockCatalogWithoutToolsFor({ modelId }: { modelId: string }): void {+ vi.spyOn(modelCatalog, 'load').mockResolvedValue({+ lookup: (model) => model.modelId === modelId ? { supportsToolCalling: false } : undefined,+ })+}++const TIERS = '/v1/platform-model-tiers'diff --git a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts b/packages/server/api/test/integration/ee/agent/agent-controller.test.tsindex 73bcc68493f..df5239bdf8b 100644--- a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts+++ b/packages/server/api/test/integration/ee/agent/agent-controller.test.ts@@ -97,6 +97,38 @@ describe('agent crud', () => {expect(agent.draft.modelName).toBe('anthropic/claude-haiku-4.5')})+ it('pins the default model to the chat key, so a key added later does not take the agent over', async () => {+ const ctx = await context()+ const chatKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, enabledForChat: true })++ const agent = await createAgent(ctx)+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, displayName: 'Second key' })+ const reread = await ctx.get(`/v1/agents/${agent.id}`, { projectId: ctx.project.id })++ expect(agent.draft.providerConfigId).toBe(chatKey.id)+ expect(reread.json().draft.providerConfigId).toBe(chatKey.id)+ })++ it('picks a default model the pinned chat key allows', async () => {+ const ctx = await context()+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, enabledForChat: true, modelScope: 'selected', modelIds: ['gpt-4.1-mini'] })++ const agent = await createAgent(ctx)++ expect(agent.draft.modelName).toBe('gpt-4.1-mini')+ })++ it('pins a saved model that names no key to the key a run would use today', async () => {+ const ctx = await context()+ const agent = await createAgent(ctx)+ const key = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI })++ const response = await ctx.post(`/v1/agents/${agent.id}`, { draft: { ...agent.draft, provider: AIProviderName.OPENAI, modelName: 'gpt-5.5', providerConfigId: null } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json().draft.providerConfigId).toBe(key.id)+ })+it('leaves the model empty where the platform has no chat provider', async () => {const ctx = await context()@@ -788,6 +820,31 @@ describe('moving an agent to another project', () => {expect((row as { projectId: string }).projectId).toBe(target.id)})+ it('re-pins the model to a key the new project can use, so a moved agent keeps running', async () => {+ const ctx = await context()+ const target = await secondProjectOf(ctx)+ const sourceKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Source', projectScope: 'selected', projectIds: [ctx.project.id] })+ const targetKey = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Target', projectScope: 'selected', projectIds: [target.id] })+ const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, provider: AIProviderName.OPENAI, modelName: 'gpt-5.5', providerConfigId: sourceKey.id } })++ const moved = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })++ expect(moved.statusCode).toBe(StatusCodes.OK)+ expect(moved.json().draft.providerConfigId).toBe(targetKey.id)+ })++ it('keeps the pinned key on a move when the new project can use it too', async () => {+ const ctx = await context()+ const target = await secondProjectOf(ctx)+ const shared = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Shared' })+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENAI, displayName: 'Other' })+ const agent = await createAgent(ctx, { draft: { ...agentBody(ctx.project.id).draft, provider: AIProviderName.OPENAI, modelName: 'gpt-5.5', providerConfigId: shared.id } })++ const moved = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })++ expect(moved.json().draft.providerConfigId).toBe(shared.id)+ })+it('refuses a project the caller cannot reach', async () => {const ctx = await context()const stranger = await context()diff --git a/packages/server/api/test/integration/ee/agent/agent-turn.test.ts b/packages/server/api/test/integration/ee/agent/agent-turn.test.tsindex 29ff9dd842a..acb1768c360 100644--- a/packages/server/api/test/integration/ee/agent/agent-turn.test.ts+++ b/packages/server/api/test/integration/ee/agent/agent-turn.test.ts@@ -107,7 +107,7 @@ describe('which version a conversation runs', () => {await enableForChat(ctx.platform.id, AIProviderName.OPENROUTER)const agent = await createAgent(ctx, { modelName: CONFIGURED_MODEL, provider: AIProviderName.OPENROUTER })const cleared = await ctx.post(`/v1/agents/${agent.id}`, {- draft: { ...agent.draft, provider: null, modelName: null },+ draft: { ...agent.draft, provider: null, providerConfigId: null, modelName: null },})expect(cleared.statusCode).toBe(StatusCodes.OK)expect(cleared.json().published.modelName).toBeNull()diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex a8e8403d52c..7eff33ea9a6 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -3198,5 +3198,29 @@"{count} mins ago": "{count} mins ago","1 hour ago": "1 hour ago","{count} hours ago": "{count} hours ago",+ "Credits tiers": "Credits tiers",+ "{capability} not available": "{capability} not available",+ "Best for everyday use": "Best for everyday use",+ "Hidden by admin": "Hidden by admin",+ "Highest quality, a bit slower": "Highest quality, a bit slower",+ "Moved": "Moved",+ "Quick replies for simple tasks": "Quick replies for simple tasks",+ "Reasoning": "Reasoning",+ "Released": "Released",+ "Runs on": "Runs on",+ "Tier": "Tier",+ "Tool calling": "Tool calling",+ "Trouble loading models": "Trouble loading models",+ "Unavailable": "Unavailable",+ "Unavailable model": "Unavailable model",+ "Vision": "Vision",+ "Web search": "Web search",+ "Your keys": "Your keys",+ "Your tiers": "Your tiers",+ "{size} tokens": "{size} tokens",+ "Tries in this order": "Tries in this order",+ "No models available — ask your platform admin to add a provider.": "No models available — ask your platform admin to add a provider.",+ "{input} in · {output} out": "{input} in · {output} out",+ "Couldn't load {key} models": "Couldn't load {key} models","Flows and agents that use this key will fail.": "Flows and agents that use this key will fail."}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 86b9458b3de..e683db71f78 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@@ -46,7 +46,11 @@ import {import { Input } from '@/components/ui/input';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { Textarea } from '@/components/ui/textarea';-import { AIModelSelector, AgentStructuredOutput } from '@/features/agents';+import {+ AgentStructuredOutput,+ ModelPicker,+ PROVIDER_EMBEDDING_MODELS,+} 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';@@ -209,13 +213,17 @@ const AdvancedSection = ({ children }: { children: React.ReactNode }) => {const ConfigureBehaviorTab = ({form,needsModel,+ projectId,}: {form: ReturnType<typeof useForm<ConfigureAgentInput, unknown, ConfigureAgentValues>>;needsModel: boolean;+ projectId: string;}) => {const tools = form.watch('draft.tools') ?? [];+ const draft = form.watch('draft');+ const provider = draft.provider;const knowledgeCount = tools.filter((tool) => tool.type === AgentToolType.KNOWLEDGE_BASE,).length;@@ -250,18 +258,12 @@ const ConfigureBehaviorTab = ({{t('Pick a model so this agent can answer.')}</p>)}- <AIModelSelector- hideLabel- showEmbeddingNote={knowledgeCount > 0}- defaultProvider={form.watch('draft.provider') ?? undefined}- defaultModel={form.watch('draft.modelName') ?? undefined}- defaultConfigId={form.watch('draft.providerConfigId') ?? undefined}- onChange={({ provider, model, configId, picked: pickedBy }) => {- const picked = {- provider: parseProvider(provider) ?? null,- modelName: model ?? null,- providerConfigId: configId ?? null,- };+ <ModelPicker+ projectId={projectId}+ surface="agent"+ value={agentEditState.modelChoiceOf({ config: draft })}+ onChange={(choice) => {+ const picked = agentEditState.modelPickOf({ choice });if (!agentEditState.modelPickChanged({picked,@@ -270,14 +272,33 @@ const ConfigureBehaviorTab = ({) {return;}- const shouldDirty = pickedBy !== 'default';- form.setValue('draft.provider', picked.provider, { shouldDirty });- form.setValue('draft.modelName', picked.modelName, { shouldDirty });- form.setValue('draft.providerConfigId', picked.providerConfigId, {- shouldDirty,+ form.setValue(+ 'draft.provider',+ parseProvider(picked.provider ?? undefined),+ { shouldDirty: true },+ );+ form.setValue('draft.modelName', picked.modelName ?? null, {+ shouldDirty: true,+ });+ form.setValue(+ 'draft.providerConfigId',+ picked.providerConfigId ?? null,+ { shouldDirty: true },+ );+ form.setValue('draft.modelTierId', picked.modelTierId ?? null, {+ shouldDirty: true,});}}/>+ {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('This provider does not support knowledge base embeddings.')}+ </p>+ )}</FormItem><FormFieldcontrol={form.control}@@ -502,8 +523,9 @@ const AgentConfigurePanel = forwardRef<const updateAgent = agentsMutations.useUpdateAgent({ id: agent.id });const values = form.watch();- const formNeedsModel =- isNil(values.draft?.modelName) || isNil(values.draft?.provider);+ const formNeedsModel = !agentEditState.hasModel({+ config: values.draft ?? {},+ });const live = liveValuesOf(agent);const hasChanges =isNil(live) || !agentEditState.sameConfig({ left: values, right: live });@@ -692,7 +714,11 @@ const AgentConfigurePanel = forwardRef<value="behavior"className="mt-0 flex flex-col gap-6">- <ConfigureBehaviorTab form={form} needsModel={formNeedsModel} />+ <ConfigureBehaviorTab+ form={form}+ needsModel={formNeedsModel}+ projectId={agent.projectId}+ /></TabsContent><TabsContentvalue="settings"diff --git a/packages/web/src/app/routes/agents/id/index.tsx b/packages/web/src/app/routes/agents/id/index.tsxindex 743b0189229..a298ffb71fe 100644--- a/packages/web/src/app/routes/agents/id/index.tsx+++ b/packages/web/src/app/routes/agents/id/index.tsx@@ -26,6 +26,8 @@ import { agentsQueries } from '@/features/agents/hooks/agents-hooks';import { authenticationSession } from '@/lib/authentication-session';import { cn } from '@/lib/utils';+import { agentEditState } from '../lib/agent-edit-state';+import { AgentChatView } from './agent-chat-view';import {AgentConfigurePanel,@@ -66,8 +68,9 @@ const SLIDING_ASIDE ='shrink-0 overflow-hidden border-gray-6 transition-[width] duration-200';const needsAModel = (agent: Agent): boolean => {- const running = agent.published ?? agent.draft;- return isNil(running.provider) || isNil(running.modelName);+ return !agentEditState.hasModel({+ config: agent.published ?? agent.draft,+ });};const AgentEditorSkeleton = () => (diff --git a/packages/web/src/app/routes/agents/lib/agent-edit-state.ts b/packages/web/src/app/routes/agents/lib/agent-edit-state.tsindex 42acb38272f..e396ecbd420 100644--- a/packages/web/src/app/routes/agents/lib/agent-edit-state.ts+++ b/packages/web/src/app/routes/agents/lib/agent-edit-state.ts@@ -1,3 +1,6 @@+import { AIProviderName, isNil } from '@activepieces/core-utils';+import { ModelChoice } from '@activepieces/shared';+function sameConfig({left,right,@@ -20,10 +23,52 @@ function modelPickChanged({return !(same(picked.provider, current.provider) &&same(picked.modelName, current.modelName) &&- same(picked.providerConfigId, current.providerConfigId)+ same(picked.providerConfigId, current.providerConfigId) &&+ same(picked.modelTierId, current.modelTierId)+ );+}++function hasModel({ config }: { config: ModelPick }): boolean {+ return (+ !isNil(config.modelTierId) ||+ (!isNil(config.provider) && !isNil(config.modelName)));}+function modelChoiceOf({ config }: { config: ModelPick }): ModelChoice | null {+ if (!isNil(config.modelTierId)) {+ return { type: 'tier', tierId: config.modelTierId };+ }+ const provider = Object.values(AIProviderName).find(+ (name) => name === config.provider,+ );+ if (isNil(provider) || isNil(config.modelName)) {+ return null;+ }+ return {+ type: 'model',+ provider,+ providerConfigId: config.providerConfigId ?? '',+ modelId: config.modelName,+ };+}++function modelPickOf({ choice }: { choice: ModelChoice }): ModelPick {+ return choice.type === 'tier'+ ? {+ provider: null,+ modelName: null,+ providerConfigId: null,+ modelTierId: choice.tierId,+ }+ : {+ provider: choice.provider,+ modelName: choice.modelId,+ providerConfigId: choice.providerConfigId,+ modelTierId: null,+ };+}+function serverMovedWhileTyping({fromServer,lastSeen,@@ -71,6 +116,9 @@ export const agentEditState = {sameConfig,serverMovedWhileTyping,modelPickChanged,+ hasModel,+ modelChoiceOf,+ modelPickOf,leaveGuard,createWriteLock,};@@ -79,6 +127,7 @@ export type ModelPick = {provider?: string | null;modelName?: string | null;providerConfigId?: string | null;+ modelTierId?: string | null;};export type LeaveGuard = {open: boolean;diff --git a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/admin-model-picker.tsx b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/admin-model-picker.tsxindex 3b2a65f3ed3..b23dcc12abb 100644--- a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/admin-model-picker.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/admin-model-picker.tsx@@ -1,3 +1,4 @@+import { isNil } from '@activepieces/core-utils';import {AIProviderModel,AIProviderWithoutSensitiveData,@@ -10,6 +11,10 @@ import { ReactNode } from 'react';import { LogoPlate } from '@/components/custom/logo-plate';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';+import {+ ModelDetail,+ ModelDetailCard,+} from '@/features/agents/ai-model/model-detail-card';import {KeyModelsById,modelMeta,@@ -23,10 +28,10 @@ import {ModelPickerItem,ModelPickerPopover,} from '@/features/agents/ai-model/model-picker-popover';+import { SectionHeading } from '@/features/agents/ai-model/section-heading';import { cn } from '@/lib/utils';import { KeyStatusBadge } from '../providers-tab/key-status';-import { ProviderLogo } from '../providers-tab/provider-logo';export function AdminModelPicker({configs,@@ -44,57 +49,50 @@ export function AdminModelPicker({const pickable: PickableModel[] = configs.flatMap((config) =>(keyModels[config.id]?.models ?? []).map((model) => ({ config, model })),);- const toItem = (- item: RankedModel,- { showKey }: { showKey: boolean },- ): ModelPickerItem<PlatformModelTierEntry> => {- const entry = { configId: item.config.id, modelId: item.model.id };- const taken = exclude.some((other) => modelMeta.sameEntry(other, entry));- const info = modelMeta.providerInfoOf({ provider: item.config.provider });- return {- id: modelMeta.entryKey({ entry }),- value: entry,- name: item.model.name,- searchText: `${item.model.name} ${item.model.id} ${item.config.name} ${item.config.provider}`,- subtitle: showKey ? item.config.name : undefined,- leading:- info.logoUrl === '' ? undefined : (- <LogoPlate src={info.logoUrl} alt={info.name} size="xxs" />- ),- model: item.model,- note:- item.tradeOffs.length === 0- ? undefined- : item.tradeOffs.map(tradeOffText).join(' · '),- disabled: taken,- selected: taken,- };- };- const groups: ModelPickerGroup<PlatformModelTierEntry>[] =+ const sections: { kind: SectionKind; items: RankedModel[] }[] =mode === 'fallback'- ? modelMeta- .rankForFallback({ main, candidates: pickable })- .map((group) => ({- id: group.kind,- heading: rankedHeading({ kind: group.kind }),- items: group.items.map((item) => toItem(item, { showKey: true })),- }))- : configs.flatMap((config) => {- const items = pickable- .filter((item) => item.config.id === config.id)- .map((item) =>- toItem({ ...item, tradeOffs: [] }, { showKey: false }),- );- return items.length === 0- ? []- : [- {- id: config.id,- heading: <KeyHeading config={config} />,- items,- },- ];- });+ ? modelMeta.rankForFallback({ main, candidates: pickable })+ : [+ {+ kind: 'keys',+ items: pickable.map((item) => ({ ...item, tradeOffs: [] })),+ },+ ];+ const built = sections.flatMap(({ kind, items }) =>+ items.map((item) => ({ kind, ...buildItem({ item, exclude }) })),+ );+ const detailById = new Map(+ built.map(({ item, detail }) => [item.id, detail] as const),+ );+ const groups: ModelPickerGroup<PlatformModelTierEntry>[] = sections.flatMap(+ ({ kind }) =>+ configs.flatMap((config) => {+ const items = built+ .filter(+ (entry) =>+ entry.kind === kind && entry.item.value.configId === config.id,+ )+ .map(({ item }) => item);+ return items.length === 0+ ? []+ : [+ {+ id: `${kind}:${config.id}`,+ section: kind,+ sectionHeading: (+ <SectionHeading+ dot={SECTION_DOT[kind]}+ label={sectionLabel({ kind })}+ />+ ),+ heading: <KeyHeading config={config} />,+ collapsible: true,+ defaultOpen: configs.length === 1 || kind === 'full',+ items,+ },+ ];+ }),+ );const loadingKeys = configs.filter((config) => keyModels[config.id]?.isLoading === true,);@@ -123,22 +121,81 @@ export function AdminModelPicker({onOpenChange={onOpenChange}align={align}anchorOnly={anchorOnly}+ detail={(item) => {+ const detail = detailById.get(item.id);+ return isNil(detail) ? null : <ModelDetailCard detail={detail} />;+ }}>{children}</ModelPickerPopover>);}+function buildItem({+ item,+ exclude,+}: {+ item: RankedModel;+ exclude: PlatformModelTierEntry[];+}): {+ item: ModelPickerItem<PlatformModelTierEntry>;+ detail: ModelDetail;+} {+ const entry = { configId: item.config.id, modelId: item.model.id };+ const taken = exclude.some((other) => modelMeta.sameEntry(other, entry));+ const info = modelMeta.providerInfoOf({ provider: item.config.provider });+ const note =+ item.tradeOffs.length === 0+ ? undefined+ : item.tradeOffs.map(tradeOffText).join(' · ');+ const contextTokens = item.model.metadata?.contextTokens;+ return {+ item: {+ id: modelMeta.entryKey({ entry }),+ value: entry,+ name: item.model.name,+ searchText: `${item.model.name} ${item.model.id} ${item.config.name} ${item.config.provider}`,+ trailing: isNil(contextTokens)+ ? undefined+ : modelMeta.formatContext({ tokens: contextTokens }),+ note,+ disabled: taken,+ selected: taken,+ },+ detail: {+ title: item.model.name,+ leading:+ info.logoUrl === '' ? undefined : (+ <LogoPlate src={info.logoUrl} alt={info.name} size="xs" tint />+ ),+ description: note,+ model: {+ provider: item.config.provider,+ modelId: item.model.id,+ name: item.model.name,+ keyName: item.config.name,+ ...(isNil(item.model.metadata)+ ? {}+ : { metadata: item.model.metadata }),+ },+ runsOn: item.config.name,+ fallbacks: [],+ showPrices: true,+ },+ };+}+function KeyHeading({ config }: { config: AIProviderWithoutSensitiveData }) {+ const info = modelMeta.providerInfoOf({ provider: config.provider });return (- <span className="flex items-center gap-2">- <ProviderLogo- info={modelMeta.providerInfoOf({ provider: config.provider })}- size="sm"- />- <span>{config.name}</span>+ <>+ {info.logoUrl !== '' && (+ <LogoPlate src={info.logoUrl} alt={info.name} size="xs" tint />+ )}+ <span className="truncate font-semibold text-gray-12">{config.name}</span>+ <span className="truncate text-xs text-gray-10">{info.name}</span>{config.status !== 'active' && <KeyStatusBadge status={config.status} />}- </span>+ </>);}@@ -211,16 +268,17 @@ function emptyTextOf({: t('No models match');}-function rankedHeading({ kind }: { kind: RankedGroup['kind'] }): string {+function sectionLabel({ kind }: { kind: SectionKind }): string {switch (kind) {+ case 'keys':+ case 'all':+ return t('Your keys');case 'full':return t('Full matches');case 'tradeOff':return t('With trade-offs');case 'other':return t('Other models');- default:- return t('Models');}}@@ -235,6 +293,16 @@ function tradeOffText(tradeOff: TradeOff): string {}}+const SECTION_DOT: Record<SectionKind, string> = {+ keys: 'bg-gray-10',+ full: 'bg-success-10',+ tradeOff: 'bg-warning-10',+ other: 'bg-gray-10',+ all: 'bg-gray-10',+};++type SectionKind = RankedGroup['kind'] | 'keys';+type AdminModelPickerProps = {configs: AIProviderWithoutSensitiveData[];keyModels: KeyModelsById;diff --git a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/model-detail-row.tsx b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/model-detail-row.tsxindex 7bd945701f8..6aa62b01c30 100644--- a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/model-detail-row.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/model-detail-row.tsx@@ -3,16 +3,11 @@ import {AIProviderWithoutSensitiveData,} from '@activepieces/shared';import { t } from 'i18next';-import { Brain, Wrench } from 'lucide-react';import { ReactNode } from 'react';import { TextWithTooltip } from '@/components/custom/text-with-tooltip';import { Skeleton } from '@/components/ui/skeleton';-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from '@/components/ui/tooltip';+import { ModelCapabilityIcons } from '@/features/agents/ai-model/model-capability-icons';import { modelMeta } from '@/features/agents/ai-model/model-meta';import { cn } from '@/lib/utils';@@ -25,11 +20,12 @@ export function ModelDetailRow({nameSuffix,trailing,loading = false,+ nested = false,}: ModelDetailRowProps) {const metadata = model?.metadata;return (<div className="flex min-w-0 flex-1 items-center gap-3 py-2.5 pr-1">- {config !== undefined && (+ {config !== undefined && !nested && (<ProviderLogoinfo={modelMeta.providerInfoOf({ provider: config.provider })}/>@@ -41,7 +37,7 @@ export function ModelDetailRow({</TextWithTooltip>{nameSuffix}</div>- {config !== undefined && (+ {config !== undefined && !nested && (<span className="truncate text-xs text-gray-11">{config.name}</span>)}</div>@@ -51,15 +47,15 @@ export function ModelDetailRow({<Skeleton className="h-8 w-28" /></div>)}- {metadata !== undefined && (+ {model !== undefined && (<div className="hidden items-center gap-4 md:flex"><Stat label={t('Context')} className="w-16">- {metadata.contextTokens === undefined+ {metadata?.contextTokens === undefined? EMPTY: modelMeta.formatContext({ tokens: metadata.contextTokens })}</Stat><Stat label={t('Price per 1M')} className="w-28">- {metadata.inputCostPerMillionTokens === undefined ||+ {metadata?.inputCostPerMillionTokens === undefined ||metadata.outputCostPerMillionTokens === undefined ? (EMPTY) : (@@ -74,7 +70,12 @@ export function ModelDetailRow({</>)}</Stat>- <Capabilities model={model} />+ {config !== undefined && (+ <ModelCapabilityIcons+ provider={config.provider}+ metadata={metadata}+ />+ )}</div>)}{trailing}@@ -101,35 +102,6 @@ function Stat({);}-function Capabilities({ model }: { model: AIProviderModel | undefined }) {- const metadata = model?.metadata;- const items = [- ...(metadata?.supportsToolCalling === true- ? [{ icon: Wrench, label: t('Supports tool calling') }]- : []),- ...(metadata?.supportsReasoning === true- ? [{ icon: Brain, label: t('Supports reasoning') }]- : []),- ];- return (- <span className="flex w-14 items-center gap-1">- {items.map(({ icon: Icon, label }) => (- <Tooltip key={label}>- <TooltipTrigger asChild>- <span- className="inline-flex size-6 items-center justify-center rounded-md bg-gray-3 text-gray-11"- aria-label={label}- >- <Icon className="size-3.5" />- </span>- </TooltipTrigger>- <TooltipContent>{label}</TooltipContent>- </Tooltip>- ))}- </span>- );-}-const EMPTY = '—';type ModelDetailRowProps = {@@ -139,4 +111,5 @@ type ModelDetailRowProps = {nameSuffix?: ReactNode;trailing?: ReactNode;loading?: boolean;+ nested?: boolean;};diff --git a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsx b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsxindex 2c08ce9bf8c..90e2a714d13 100644--- a/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/tiers-tab/specific-models-section.tsx@@ -221,11 +221,11 @@ function KeyGroup({onOpenChange={setOpen}className="border-b border-gray-6/60 last:border-b-0">- <div className="flex items-center gap-2 pr-5">+ <div className="flex items-center gap-2 pr-5 hover:bg-gray-2"><CollapsibleTrigger asChild><buttontype="button"- className="flex min-w-0 flex-1 items-center gap-3 px-5 py-3 text-left hover:bg-gray-2"+ className="flex min-w-0 flex-1 items-center gap-3 py-3 pl-5 text-left"><ProviderLogoinfo={modelMeta.providerInfoOf({ provider: config.provider })}@@ -258,7 +258,7 @@ function KeyGroup({{isError && retryButton}</div><CollapsibleContent>- <div className="flex flex-col pb-2 pl-5 pr-4">+ <div className="flex flex-col pb-2 pl-16 pr-4">{isLoading &&[0, 1, 2].map((row) => (<div key={row} className="flex items-center gap-3 py-2.5">@@ -283,6 +283,7 @@ function KeyGroup({name={model.name}config={config}model={model}+ nestedtrailing={<Buttontype="button"diff --git a/packages/web/src/features/agents/ai-model/hooks.ts b/packages/web/src/features/agents/ai-model/hooks.tsindex fd6c43dca1a..f77709a828f 100644--- a/packages/web/src/features/agents/ai-model/hooks.ts+++ b/packages/web/src/features/agents/ai-model/hooks.ts@@ -3,8 +3,9 @@ import {AIProviderModel,AIProviderModelType,ALLOWED_CHAT_MODELS_BY_PROVIDER,+ ModelOptionsSurface,} from '@activepieces/shared';-import { useQuery } from '@tanstack/react-query';+import { keepPreviousData, useQuery } from '@tanstack/react-query';import { useCallback } from 'react';import {@@ -66,6 +67,22 @@ export const aiModelHooks = {});},+ useModelOptions: ({+ projectId,+ surface,+ tierId,+ }: {+ projectId: string;+ surface: ModelOptionsSurface;+ tierId?: string;+ }) =>+ useQuery({+ queryKey: ['ai-model-options', projectId, surface, tierId],+ queryFn: () =>+ aiProviderApi.listModelOptions({ projectId, surface, tierId }),+ placeholderData: keepPreviousData,+ }),+useGetModelsForProvider: (provider?: AIProviderName, configId?: string) => {const projectId = authenticationSession.getProjectId();const { tiers: flowTiers } = aiProviderQueries.useModelTiers('flow');diff --git a/packages/web/src/features/agents/ai-model/model-capability-icons.tsx b/packages/web/src/features/agents/ai-model/model-capability-icons.tsxnew file mode 100644index 00000000000..46aa0967672--- /dev/null+++ b/packages/web/src/features/agents/ai-model/model-capability-icons.tsx@@ -0,0 +1,69 @@+import {+ AI_PROVIDER_CAPABILITIES,+ AIProviderModelMetadata,+ AIProviderName,+} from '@activepieces/shared';+import { t } from 'i18next';+import { Brain, Eye, Globe, LucideIcon, Wrench } from 'lucide-react';++import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import { cn } from '@/lib/utils';++export function ModelCapabilityIcons({+ provider,+ metadata,+}: {+ provider: AIProviderName;+ metadata: AIProviderModelMetadata | undefined;+}) {+ const slots: { icon: LucideIcon; label: string; on: boolean }[] = [+ {+ icon: Wrench,+ label: t('Tool calling'),+ on: metadata?.supportsToolCalling === true,+ },+ {+ icon: Brain,+ label: t('Reasoning'),+ on: metadata?.supportsReasoning === true,+ },+ { icon: Eye, label: t('Vision'), on: metadata?.supportsVision === true },+ {+ icon: Globe,+ label: t('Web search'),+ on: AI_PROVIDER_CAPABILITIES[provider]?.webSearch !== undefined,+ },+ ];+ return (+ <span className="flex shrink-0 items-center gap-1">+ {slots.map(({ icon: Icon, label, on }) => (+ <Tooltip key={label}>+ <TooltipTrigger asChild>+ <span+ className={cn(+ 'inline-flex size-5 items-center justify-center rounded-sm',+ on ? 'bg-gray-3 text-gray-11' : 'text-gray-7',+ )}+ aria-label={+ on+ ? label+ : t('{capability} not available', { capability: label })+ }+ >+ <Icon className="size-3" />+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {on+ ? label+ : t('{capability} not available', { capability: label })}+ </TooltipContent>+ </Tooltip>+ ))}+ </span>+ );+}diff --git a/packages/web/src/features/agents/ai-model/model-detail-card.tsx b/packages/web/src/features/agents/ai-model/model-detail-card.tsxnew file mode 100644index 00000000000..4ee5da33061--- /dev/null+++ b/packages/web/src/features/agents/ai-model/model-detail-card.tsx@@ -0,0 +1,181 @@+import { AI_PROVIDER_CAPABILITIES, OptionModel } from '@activepieces/shared';+import dayjs from 'dayjs';+import i18next, { t } from 'i18next';+import { Check } from 'lucide-react';+import { ReactNode } from 'react';++import { cn } from '@/lib/utils';++import { modelMeta } from './model-meta';++export function ModelDetailCard({ detail }: { detail: ModelDetail }) {+ const { model } = detail;+ const metadata = model.metadata;+ const released =+ metadata?.releaseDate === undefined ? null : dayjs(metadata.releaseDate);+ const capabilities = [+ { label: t('Tool calling'), value: metadata?.supportsToolCalling },+ { label: t('Reasoning'), value: metadata?.supportsReasoning },+ { label: t('Vision'), value: metadata?.supportsVision },+ {+ label: t('Web search'),+ value: AI_PROVIDER_CAPABILITIES[model.provider]?.webSearch !== undefined,+ },+ ];+ const chain = [+ { name: model.name, keyName: detail.runsOn },+ ...detail.fallbacks,+ ];++ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1.5 px-3">+ <div className="flex min-w-0 items-center gap-2.5">+ {detail.leading}+ <span className="truncate text-base font-semibold text-gray-12">+ {detail.title}+ </span>+ {detail.badges}+ </div>+ {detail.description !== undefined && (+ <p className="text-sm leading-relaxed text-gray-11">+ {detail.description}+ </p>+ )}+ </div>++ <dl className="flex flex-col gap-2.5 px-3 text-xs">+ {detail.title !== model.name && (+ <DetailRow label={t('Model')}>{model.name}</DetailRow>+ )}+ {chain.length === 1 && (+ <DetailRow label={t('Runs on')}>{detail.runsOn}</DetailRow>+ )}+ {metadata?.contextTokens !== undefined && (+ <DetailRow label={t('Context')}>+ {t('{size} tokens', {+ size: modelMeta.formatContext({ tokens: metadata.contextTokens }),+ })}+ </DetailRow>+ )}+ {detail.showPrices &&+ metadata?.inputCostPerMillionTokens !== undefined &&+ metadata.outputCostPerMillionTokens !== undefined && (+ <DetailRow label={t('Price per 1M')}>+ {t('{input} in · {output} out', {+ input: modelMeta.formatPrice({+ perMillion: metadata.inputCostPerMillionTokens,+ }),+ output: modelMeta.formatPrice({+ perMillion: metadata.outputCostPerMillionTokens,+ }),+ })}+ </DetailRow>+ )}+ {released !== null && released.isValid() && (+ <DetailRow label={t('Released')}>+ <span className="flex items-center justify-end gap-1.5">+ {dayjs().diff(released, 'day') <= NEW_MODEL_DAYS && (+ <span className="rounded-full bg-success-3 px-1.5 py-0.5 text-xss leading-none text-success-11">+ {t('New')}+ </span>+ )}+ {Intl.DateTimeFormat(i18next.language, {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ }).format(released.toDate())}+ </span>+ </DetailRow>+ )}+ </dl>++ {chain.length > 1 && (+ <div className="flex flex-col gap-2.5 border-t px-3 pt-4">+ <span className="text-xs text-gray-11">+ {t('Tries in this order')}+ </span>+ <ol className="relative flex flex-col gap-2.5">+ <span className="absolute top-1.5 bottom-1.5 left-[4.5px] w-px bg-gray-7" />+ {chain.map((step, index) => (+ <li+ key={`${step.keyName}:${step.name}`}+ className="relative flex min-w-0 items-center gap-2.5 text-xs"+ >+ <span+ className={cn(+ 'size-2.5 shrink-0 rounded-full ring-2 ring-panel',+ index === 0 ? 'bg-accent-10' : 'bg-gray-8',+ )}+ />+ <span+ className={cn(+ 'truncate',+ index === 0 ? 'font-medium text-gray-12' : 'text-gray-11',+ )}+ title={step.name}+ >+ {step.name}+ </span>+ <span className="ml-auto shrink-0 truncate text-gray-10">+ {step.keyName}+ </span>+ </li>+ ))}+ </ol>+ </div>+ )}++ <div className="flex flex-wrap gap-1.5 border-t px-3 pt-4">+ {capabilities.map((capability) =>+ capability.value === true ? (+ <span+ key={capability.label}+ className="flex items-center gap-1 rounded-full bg-success-3 px-2 py-0.5 text-xs text-success-11"+ >+ <Check className="size-3 text-success-11" />+ {capability.label}+ </span>+ ) : (+ <span+ key={capability.label}+ className="rounded-full bg-gray-3 px-2 py-0.5 text-xs text-gray-10 line-through"+ >+ {capability.label}+ </span>+ ),+ )}+ </div>+ </div>+ );+}++function DetailRow({+ label,+ children,+}: {+ label: string;+ children: ReactNode;+}) {+ return (+ <div className="flex min-w-0 items-baseline justify-between gap-4">+ <dt className="shrink-0 text-xs text-gray-11">{label}</dt>+ <dd className="min-w-0 truncate text-right font-medium text-gray-12">+ {children}+ </dd>+ </div>+ );+}++const NEW_MODEL_DAYS = 60;++export type ModelDetail = {+ title: string;+ leading: ReactNode;+ badges?: ReactNode;+ description?: string;+ model: OptionModel;+ runsOn: string;+ fallbacks: { name: string; keyName: string }[];+ showPrices: boolean;+};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 a0ebb60b44e..16b6ac15372 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@@ -1,7 +1,14 @@-import { AIProviderModel } from '@activepieces/shared';+import { isNil } from '@activepieces/core-utils';import { t } from 'i18next';-import { Brain, Check, Wrench } from 'lucide-react';-import { ReactNode, useDeferredValue, useMemo, useState } from 'react';+import { Check, ChevronDown, ChevronRight } from 'lucide-react';+import {+ ReactNode,+ useDeferredValue,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import {Command,@@ -19,8 +26,6 @@ import {} from '@/components/ui/popover';import { cn } from '@/lib/utils';-import { modelMeta } from './model-meta';-export function ModelPickerPopover<T>({groups,notices,@@ -30,10 +35,29 @@ export function ModelPickerPopover<T>({onOpenChange,align = 'end',anchorOnly = false,+ matchTriggerWidth = false,+ detail,children,}: ModelPickerPopoverProps<T>) {const [search, setSearch] = useState('');const [expanded, setExpanded] = useState<string[]>([]);+ const [toggled, setToggled] = useState<Record<string, boolean>>({});+ const [highlighted, setHighlighted] = useState('');+ const [activeItem, setActiveItem] = useState<ModelPickerItem<T> | null>(null);+ const [rowTop, setRowTop] = useState(0);+ const [detailTop, setDetailTop] = useState(0);+ const [detailSide, setDetailSide] = useState<DetailSide>('left');+ const movedByKeyboard = useRef(false);+ const frameRef = useRef<HTMLDivElement>(null);+ const cardRef = useRef<HTMLDivElement>(null);+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ const cancelClose = () => {+ if (!isNil(closeTimer.current)) {+ clearTimeout(closeTimer.current);+ closeTimer.current = null;+ }+ };const needle = useDeferredValue(search.trim().toLowerCase());const visible = useMemo(() =>@@ -50,141 +74,298 @@ export function ModelPickerPopover<T>({.filter((group) => group.items.length > 0),[groups, needle],);+ const sections = useMemo(() => sectionsOf({ groups: visible }), [visible]);+ const itemByValue = useMemo(+ () =>+ new Map(+ visible.flatMap((group) =>+ group.items.map((item) => [itemValue({ group, item }), item]),+ ),+ ),+ [visible],+ );++ const isOpen = (group: ModelPickerGroup<T>) =>+ group.collapsible !== true ||+ needle !== '' ||+ (toggled[group.id] ?? group.defaultOpen === true);++ const showDetail = ({+ item,+ row,+ }: {+ item: ModelPickerItem<T>;+ row: Element | null | undefined;+ }) => {+ setActiveItem(item);+ const frame = frameRef.current;+ if (isNil(frame) || isNil(row)) {+ return;+ }+ setRowTop(+ row.getBoundingClientRect().top - frame.getBoundingClientRect().top,+ );+ };++ useLayoutEffect(() => {+ const frame = frameRef.current;+ const card = cardRef.current;+ if (isNil(frame) || isNil(card)) {+ return;+ }+ const {+ top: frameTop,+ left: frameLeft,+ right: frameRight,+ } = frame.getBoundingClientRect();+ const needed = card.offsetWidth + VIEWPORT_MARGIN;+ setDetailSide(+ frameLeft >= needed+ ? 'left'+ : window.innerWidth - frameRight >= needed+ ? 'right'+ : 'none',+ );+ const highest = VIEWPORT_MARGIN - frameTop;+ const lowest =+ window.innerHeight - VIEWPORT_MARGIN - frameTop - card.offsetHeight;+ setDetailTop(Math.max(highest, Math.min(rowTop, lowest)));+ }, [rowTop, activeItem]);++ const changeOpen = (next: boolean) => {+ if (!next) {+ cancelClose();+ setSearch('');+ setExpanded([]);+ setToggled({});+ setHighlighted('');+ setActiveItem(null);+ movedByKeyboard.current = false;+ }+ onOpenChange(next);+ };const pick = (item: ModelPickerItem<T>) => {onPick(item.value);- onOpenChange(false);+ changeOpen(false);};- return (- <Popover- modal- open={open}- onOpenChange={(next) => {- if (!next) {- setSearch('');- setExpanded([]);+ const renderItems = (group: ModelPickerGroup<T>) => {+ const isExpanded = expanded.includes(group.id);+ const shown = isExpanded ? group.items : group.items.slice(0, GROUP_CAP);+ return (+ <>+ {shown.map((item) => (+ <CommandItem+ key={item.id}+ value={itemValue({ group, item })}+ disabled={item.disabled}+ aria-disabled={item.disabled}+ onSelect={() => pick(item)}+ className="group"+ >+ <PickerRow item={item} indented={group.collapsible === true} />+ </CommandItem>+ ))}+ {shown.length < group.items.length && (+ <CommandItem+ value={`${group.id}:show-all`}+ onSelect={() => setExpanded((current) => [...current, group.id])}+ className="justify-center text-xs text-accent-11"+ >+ {t('Show all {count}', { count: group.items.length })}+ </CommandItem>+ )}+ </>+ );+ };++ const list = (+ <Command+ shouldFilter={false}+ value={highlighted}+ onValueChange={(value) => {+ setHighlighted(value);+ const item = itemByValue.get(value);+ if (item !== undefined && movedByKeyboard.current) {+ showDetail({+ item,+ row: Array.from(+ frameRef.current?.querySelectorAll('[cmdk-item]') ?? [],+ ).find((row) => row.getAttribute('data-value') === value),+ });+ }+ }}+ onKeyDown={(event) => {+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {+ movedByKeyboard.current = true;}- onOpenChange(next);}}>+ <CommandInput+ placeholder={t('Search models')}+ value={search}+ onValueChange={(value) => {+ setSearch(value);+ setExpanded([]);+ }}+ />+ {notices}+ <CommandList+ className={cn(+ 'overflow-y-auto',+ detail === undefined ? 'max-h-80' : 'max-h-96',+ )}+ onPointerMove={(event) => {+ const row =+ event.target instanceof Element+ ? event.target.closest('[cmdk-item]')+ : null;+ const item = itemByValue.get(row?.getAttribute('data-value') ?? '');+ if (item !== undefined && item !== activeItem) {+ movedByKeyboard.current = false;+ showDetail({ item, row });+ }+ }}+ >+ <CommandEmpty>{emptyText}</CommandEmpty>+ {sections.map((section) => (+ <CommandGroup+ key={section.id}+ heading={section.heading}+ className={cn(+ '[&_[cmdk-group-heading]]:sticky [&_[cmdk-group-heading]]:top-0 [&_[cmdk-group-heading]]:z-10 [&_[cmdk-group-heading]]:bg-panel',+ detail !== undefined && '[&_[cmdk-group-heading]]:pt-2.5',+ )}+ >+ {section.groups.map((group) =>+ group.collapsible === true ? (+ <div key={group.id}>+ <CommandItem+ value={`${group.id}:toggle`}+ aria-expanded={isOpen(group)}+ onSelect={() =>+ setToggled((current) => ({+ ...current,+ [group.id]: !isOpen(group),+ }))+ }+ >+ {isOpen(group) ? (+ <ChevronDown className="size-3.5 text-gray-10" />+ ) : (+ <ChevronRight className="size-3.5 text-gray-10" />+ )}+ <span className="flex min-w-0 flex-1 items-center gap-2">+ {group.heading}+ </span>+ <span className="w-10 shrink-0 text-right text-xs tabular-nums text-gray-10">+ {group.items.length}+ </span>+ <span className="size-4 shrink-0" />+ </CommandItem>+ {isOpen(group) && renderItems(group)}+ </div>+ ) : (+ <div key={group.id}>{renderItems(group)}</div>+ ),+ )}+ </CommandGroup>+ ))}+ </CommandList>+ </Command>+ );++ return (+ <Popover modal open={open} onOpenChange={changeOpen}>{anchorOnly ? (<PopoverAnchor asChild>{children}</PopoverAnchor>) : (<PopoverTrigger asChild>{children}</PopoverTrigger>)}- <PopoverContent align={align} className="w-[420px] p-0">- <Command shouldFilter={false}>- <CommandInput- placeholder={t('Search models')}- value={search}- onValueChange={(value) => {- setSearch(value);- setExpanded([]);- }}- />- {notices}- <CommandList className="max-h-80 overflow-y-auto">- <CommandEmpty>{emptyText}</CommandEmpty>- {visible.map((group) => {- const isExpanded = expanded.includes(group.id);- const shown = isExpanded- ? group.items- : group.items.slice(0, GROUP_CAP);- return (- <CommandGroup- key={group.id}- heading={- <span className="flex items-center gap-2">- {group.heading}- <span className="ml-auto tabular-nums text-gray-10">- {group.items.length}- </span>- </span>- }- className="[&_[cmdk-group-heading]]:sticky [&_[cmdk-group-heading]]:top-0 [&_[cmdk-group-heading]]:z-10 [&_[cmdk-group-heading]]:bg-panel"- >- {shown.map((item) => (- <CommandItem- key={item.id}- value={`${group.id}:${item.id}`}- disabled={item.disabled}- aria-disabled={item.disabled}- onSelect={() => pick(item)}- >- <PickerRow item={item} />- </CommandItem>- ))}- {shown.length < group.items.length && (- <CommandItem- value={`${group.id}:show-all`}- onSelect={() =>- setExpanded((current) => [...current, group.id])- }- className="justify-center text-xs text-accent-11"- >- {t('Show all {count}', { count: group.items.length })}- </CommandItem>- )}- </CommandGroup>- );- })}- </CommandList>- </Command>+ <PopoverContent+ align={align}+ className={cn(+ 'relative p-0',+ matchTriggerWidth+ ? 'w-[var(--radix-popover-trigger-width)] min-w-80'+ : 'w-[420px]',+ )}+ >+ <div+ ref={frameRef}+ className="relative"+ onPointerEnter={cancelClose}+ onPointerLeave={() => {+ if (movedByKeyboard.current) {+ return;+ }+ cancelClose();+ closeTimer.current = setTimeout(+ () => setActiveItem(null),+ DETAIL_CLOSE_DELAY_MS,+ );+ }}+ >+ {list}+ {detail !== undefined && activeItem !== null && (+ <div+ ref={cardRef}+ className={cn(+ 'absolute hidden transition-[top] duration-150 sm:block',+ detailSide === 'right' ? 'left-full pl-2' : 'right-full pr-2',+ detailSide === 'none' && 'invisible',+ )}+ style={{ top: detailTop }}+ >+ <div+ data-testid="model-picker-detail"+ className="w-[300px] rounded-lg border bg-panel px-2 py-5 text-gray-12 shadow-lg"+ >+ {detail(activeItem)}+ </div>+ </div>+ )}+ </div></PopoverContent></Popover>);}-function PickerRow<T>({ item }: { item: ModelPickerItem<T> }) {- const metadata = item.model?.metadata;- const meta = [- ...(metadata?.contextTokens === undefined- ? []- : [modelMeta.formatContext({ tokens: metadata.contextTokens })]),- ...(metadata?.inputCostPerMillionTokens === undefined ||- metadata.outputCostPerMillionTokens === undefined- ? []- : [- `${modelMeta.formatPrice({- perMillion: metadata.inputCostPerMillionTokens,- })} / ${modelMeta.formatPrice({- perMillion: metadata.outputCostPerMillionTokens,- })}`,- ]),- ];+function PickerRow<T>({+ item,+ indented,+}: {+ item: ModelPickerItem<T>;+ indented: boolean;+}) {return (- <span className="flex w-full min-w-0 flex-col gap-0.5">+ <span+ className={cn('flex w-full min-w-0 flex-col gap-0.5', indented && 'pl-7')}+ ><span className="flex w-full min-w-0 items-center gap-2">{item.leading}- <span className="truncate text-sm" title={item.name}>+ <span+ className={cn(+ 'truncate text-sm',+ indented+ ? 'text-gray-11 group-data-[selected=true]:text-gray-12'+ : item.description !== undefined && 'font-medium',+ )}+ title={item.name}+ >{item.name}</span>+ {item.badges}{item.subtitle !== undefined && (<span className="truncate text-xs text-gray-11">{item.subtitle}</span>)}<span className="ml-auto flex shrink-0 items-center gap-2">- {meta.length > 0 && (- <span className="text-xs tabular-nums text-gray-11">- {meta.join(' · ')}+ {item.trailing !== undefined && (+ <span className="w-10 text-right text-xs tabular-nums text-gray-11">+ {item.trailing}</span>)}- {metadata?.supportsToolCalling === true && (- <Wrench- className="size-3.5 text-gray-10"- aria-label={t('Supports tool calling')}- >- <title>{t('Supports tool calling')}</title>- </Wrench>- )}- {metadata?.supportsReasoning === true && (- <Brain- className="size-3.5 text-gray-10"- aria-label={t('Supports reasoning')}- >- <title>{t('Supports reasoning')}</title>- </Brain>- )}<CheckclassName={cn('size-4 text-gray-11',@@ -193,6 +374,11 @@ function PickerRow<T>({ item }: { item: ModelPickerItem<T> }) {/></span></span>+ {item.description !== undefined && (+ <span className="truncate pl-8 text-xs text-gray-11">+ {item.description}+ </span>+ )}{item.note !== undefined && (<span className="pl-6 text-xs text-warning-11">{item.note}</span>)}@@ -200,7 +386,56 @@ function PickerRow<T>({ item }: { item: ModelPickerItem<T> }) {);}+function sectionsOf<T>({+ groups,+}: {+ groups: ModelPickerGroup<T>[];+}): PickerSection<T>[] {+ return groups.reduce<PickerSection<T>[]>((sections, group) => {+ const last = sections[sections.length - 1];+ if (+ group.section !== undefined &&+ last !== undefined &&+ last.id === group.section+ ) {+ return [+ ...sections.slice(0, -1),+ { ...last, groups: [...last.groups, group] },+ ];+ }+ return [+ ...sections,+ {+ id: group.section ?? group.id,+ heading: group.sectionHeading ?? (+ <span className="flex items-center gap-2">+ {group.heading}+ <span className="ml-auto tabular-nums text-gray-10">+ {group.items.length}+ </span>+ </span>+ ),+ groups: [group],+ },+ ];+ }, []);+}++function itemValue<T>({+ group,+ item,+}: {+ group: ModelPickerGroup<T>;+ item: ModelPickerItem<T>;+}): string {+ return `${group.id}:${item.id}`;+}+const GROUP_CAP = 30;+const DETAIL_CLOSE_DELAY_MS = 150;+const VIEWPORT_MARGIN = 12;++type DetailSide = 'left' | 'right' | 'none';export type ModelPickerItem<T> = {id: string;@@ -208,8 +443,10 @@ export type ModelPickerItem<T> = {name: string;searchText: string;subtitle?: string;+ description?: string;+ trailing?: string;+ badges?: ReactNode;leading?: ReactNode;- model?: AIProviderModel;note?: string;disabled?: boolean;selected?: boolean;@@ -219,6 +456,16 @@ export type ModelPickerGroup<T> = {id: string;heading: ReactNode;items: ModelPickerItem<T>[];+ section?: string;+ sectionHeading?: ReactNode;+ collapsible?: boolean;+ defaultOpen?: boolean;+};++type PickerSection<T> = {+ id: string;+ heading: ReactNode;+ groups: ModelPickerGroup<T>[];};type ModelPickerPopoverProps<T> = {@@ -230,5 +477,7 @@ type ModelPickerPopoverProps<T> = {onOpenChange: (open: boolean) => void;align?: 'start' | 'end';anchorOnly?: boolean;+ matchTriggerWidth?: boolean;+ detail?: (item: ModelPickerItem<T>) => ReactNode;children: ReactNode;};diff --git a/packages/web/src/features/agents/ai-model/model-picker.tsx b/packages/web/src/features/agents/ai-model/model-picker.tsxnew file mode 100644index 00000000000..10c0f90fa7d--- /dev/null+++ b/packages/web/src/features/agents/ai-model/model-picker.tsx@@ -0,0 +1,514 @@+import { AIProviderName, isNil } from '@activepieces/core-utils';+import {+ ModelChoice,+ ModelOptions,+ ModelOptionsSurface,+ OptionModel,+} from '@activepieces/shared';+import { t } from 'i18next';+import {+ ChevronDown,+ Equal,+ Lightbulb,+ Rocket,+ Sparkles,+ Star,+ TriangleAlert,+ Zap,+} from 'lucide-react';+import { ReactNode, useMemo, useState } from 'react';++import { LogoPlate } from '@/components/custom/logo-plate';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { cn } from '@/lib/utils';++import { aiModelHooks } from './hooks';+import { ModelDetail, ModelDetailCard } from './model-detail-card';+import { modelMeta } from './model-meta';+import { ModelPickerGroup, ModelPickerPopover } from './model-picker-popover';+import { SectionHeading } from './section-heading';++export function ModelPicker({+ projectId,+ surface,+ value,+ onChange,+ disabled = false,+ className,+}: ModelPickerProps) {+ const [open, setOpen] = useState(false);+ const { data, isLoading, isError, refetch } = aiModelHooks.useModelOptions({+ projectId,+ surface,+ tierId: value?.type === 'tier' ? value.tierId : undefined,+ });+ const view = useMemo(+ () =>+ isNil(data) ? null : modelPickerView({ options: data, shown: value }),+ [data, value],+ );++ if (isLoading) {+ return <Skeleton className={cn('h-9 w-full', className)} />;+ }++ return (+ <ModelPickerPopover+ matchTriggerWidth+ groups={view?.groups ?? []}+ notices={+ isError ? (+ <div className="flex items-center justify-between gap-2 border-b px-3 py-2 text-xs text-gray-11">+ {t('Trouble loading models')}+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => refetch()}+ >+ {t('Retry')}+ </Button>+ </div>+ ) : undefined+ }+ emptyText={t(+ 'No models available — ask your platform admin to add a provider.',+ )}+ onPick={(choice) => onChange(choice)}+ open={open}+ onOpenChange={setOpen}+ align="start"+ detail={(item) => {+ const detail = view?.detailById.get(item.id);+ return isNil(detail) ? null : <ModelDetailCard detail={detail} />;+ }}+ >+ <button+ type="button"+ 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',+ className,+ )}+ >+ <TriggerContent current={view?.current ?? emptyPick()} />+ <ChevronDown className="ml-auto size-4 shrink-0 text-gray-10" />+ </button>+ </ModelPickerPopover>+ );+}++export function modelPickerView({+ options,+ shown,+}: {+ options: ModelOptions;+ shown: ModelChoice | null;+}): PickerView {+ const current = resolveCurrent({ options, shown });+ const tierItems = options.tiers.map((tier) => {+ const isSelected = current.kind === 'tier' && current.id === tier.id;+ return {+ item: {+ id: `tier:${tier.id}`,+ value: { type: 'tier', tierId: tier.id } satisfies ModelChoice,+ name: tier.name,+ description: tier.description ?? tier.main.name,+ trailing: contextOf({ model: tier.main }),+ leading: <TierTile emoji={tier.emoji} />,+ badges: <TierBadges isDefault={tier.isDefault} isFast={tier.isFast} />,+ searchText: [+ tier.name,+ tier.description ?? '',+ tier.main.name,+ tier.main.modelId,+ ...tier.fallbacks.map((fallback) => fallback.name),+ ].join(' '),+ selected: isSelected,+ },+ detail: {+ title: tier.name,+ leading: <TierTile emoji={tier.emoji} />,+ badges: <TierBadges isDefault={tier.isDefault} isFast={tier.isFast} />,+ description: tier.description ?? undefined,+ model: tier.main,+ runsOn: tier.main.keyName,+ fallbacks: tier.fallbacks.map((fallback) => ({+ name: fallback.name,+ keyName: fallback.keyName,+ })),+ showPrices: true,+ },+ };+ });+ const credits = options.credits;+ const creditItems = isNil(credits)+ ? []+ : credits.tiers.map((tier) => ({+ item: {+ id: `credits:${tier.id}`,+ value: {+ type: 'model',+ provider: AIProviderName.ACTIVEPIECES,+ providerConfigId: credits.providerConfigId,+ modelId: tier.id,+ } satisfies ModelChoice,+ name: tier.label,+ description: creditDescriptionOf({ tierId: tier.id }),+ leading: <CreditTile tierId={tier.id} />,+ trailing: contextOf({ model: tier.model }),+ searchText: `${tier.label} ${tier.model.modelId}`,+ selected: current.kind === 'credits' && current.id === tier.id,+ },+ detail: {+ title: tier.label,+ leading: <CreditTile tierId={tier.id} />,+ description: creditDescriptionOf({ tierId: tier.id }),+ model: tier.model,+ runsOn: t('Credits'),+ fallbacks: [],+ showPrices: false,+ },+ }));+ const keyGroups = options.keys.map((key) => {+ const info = modelMeta.providerInfoOf({ provider: key.provider });+ const models = key.models.map((model) => {+ const optionModel: OptionModel = {+ provider: key.provider,+ modelId: model.id,+ name: model.name,+ keyName: key.name,+ ...(isNil(model.metadata) ? {} : { metadata: model.metadata }),+ };+ return {+ item: {+ id: `model:${key.providerConfigId}:${model.id}`,+ value: {+ type: 'model',+ provider: key.provider,+ providerConfigId: key.providerConfigId,+ modelId: model.id,+ } satisfies ModelChoice,+ name: model.name,+ trailing: contextOf({ model: optionModel }),+ searchText: `${model.name} ${model.id} ${key.name} ${info.name}`,+ selected:+ current.kind === 'model' &&+ current.configId === key.providerConfigId &&+ current.id === model.id,+ },+ detail: {+ title: model.name,+ leading: <KeyLogo logoUrl={info.logoUrl} name={info.name} />,+ model: optionModel,+ runsOn: key.name,+ fallbacks: [],+ showPrices: true,+ },+ };+ });+ return { key, info, models };+ });++ const groups: ModelPickerGroup<ModelChoice>[] = [+ ...(tierItems.length === 0+ ? []+ : [+ {+ id: 'tiers',+ section: 'tiers',+ sectionHeading: (+ <SectionHeading dot="bg-swatch-12-mark" label={t('Your tiers')} />+ ),+ heading: t('Your tiers'),+ items: tierItems.map(({ item }) => item),+ },+ ]),+ ...(creditItems.length === 0+ ? []+ : [+ {+ id: 'credits',+ section: 'credits',+ sectionHeading: (+ <SectionHeading dot="bg-accent-10" label={t('Credits tiers')} />+ ),+ heading: t('Credits tiers'),+ items: creditItems.map(({ item }) => item),+ },+ ]),+ ...keyGroups.map(({ key, info, models }) => ({+ id: `key:${key.providerConfigId}`,+ section: 'keys',+ sectionHeading: (+ <SectionHeading dot="bg-gray-10" label={t('Your keys')} />+ ),+ heading: (+ <>+ <KeyLogo logoUrl={info.logoUrl} name={info.name} />+ <span className="truncate font-semibold text-gray-12">+ {key.name}+ </span>+ <span className="truncate text-xs text-gray-10">{info.name}</span>+ </>+ ),+ collapsible: true,+ defaultOpen:+ keyGroups.length === 1 ||+ (current.kind === 'model' && current.configId === key.providerConfigId),+ items: models.map(({ item }) => item),+ })),+ ];++ const detailById = new Map<string, ModelDetail>([+ ...tierItems.map(({ item, detail }) => [item.id, detail] as const),+ ...creditItems.map(({ item, detail }) => [item.id, detail] as const),+ ...keyGroups.flatMap(({ models }) =>+ models.map(({ item, detail }) => [item.id, detail] as const),+ ),+ ]);++ return { groups, detailById, current };+}++function resolveCurrent({+ options,+ shown,+}: {+ options: ModelOptions;+ shown: ModelChoice | null;+}): CurrentPick {+ if (isNil(shown)) {+ return emptyPick();+ }+ if (shown.type === 'tier') {+ const movedTo = options.movedTiers[shown.tierId];+ const tier = options.tiers.find(+ (candidate) => candidate.id === (movedTo ?? shown.tierId),+ );+ return isNil(tier)+ ? unavailablePick({ label: t('Unavailable model') })+ : {+ kind: 'tier',+ id: tier.id,+ label: tier.name,+ leading: <TierTile emoji={tier.emoji} size="sm" />,+ source: isNil(movedTo) ? t('Tier') : t('Moved'),+ };+ }+ if (shown.provider === AIProviderName.ACTIVEPIECES) {+ const tier = options.credits?.tiers.find(+ (candidate) => candidate.id === shown.modelId,+ );+ return isNil(tier)+ ? unavailablePick({ label: shown.modelId })+ : {+ kind: 'credits',+ id: tier.id,+ label: tier.label,+ leading: <CreditTile tierId={tier.id} size="sm" />,+ source: t('Credits'),+ };+ }+ const key =+ options.keys.find(+ (candidate) =>+ candidate.providerConfigId === shown.providerConfigId &&+ candidate.models.some((model) => model.id === shown.modelId),+ ) ??+ (shown.providerConfigId === ''+ ? options.keys.find(+ (candidate) =>+ candidate.provider === shown.provider &&+ candidate.models.some((model) => model.id === shown.modelId),+ )+ : undefined);+ const model = key?.models.find((candidate) => candidate.id === shown.modelId);+ if (isNil(key) || isNil(model)) {+ return options.specificModelsHidden+ ? {+ kind: 'hidden',+ id: shown.modelId,+ label: shown.modelId,+ leading: (+ <TriangleAlert className="size-4 shrink-0 text-warning-11" />+ ),+ source: t('Hidden by admin'),+ }+ : unavailablePick({ label: shown.modelId });+ }+ const info = modelMeta.providerInfoOf({ provider: key.provider });+ return {+ kind: 'model',+ id: model.id,+ configId: key.providerConfigId,+ label: model.name,+ leading: <KeyLogo logoUrl={info.logoUrl} name={info.name} size="xxs" />,+ source: key.name,+ };+}++function emptyPick(): CurrentPick {+ return {+ kind: 'empty',+ id: '',+ label: t('Pick a model'),+ leading: null,+ source: '',+ };+}++function unavailablePick({ label }: { label: string }): CurrentPick {+ return {+ kind: 'unavailable',+ id: '',+ label,+ leading: <TriangleAlert className="size-4 shrink-0 text-warning-11" />,+ source: t('Unavailable'),+ };+}++function TriggerContent({ current }: { current: CurrentPick }) {+ 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 ? (+ <span className="shrink-0 rounded-full bg-warning-3 px-1.5 py-0.5 text-xss leading-none text-warning-11">+ {current.source}+ </span>+ ) : (+ <span className="min-w-0 shrink truncate rounded-full bg-gray-3 px-1.5 py-0.5 text-xss leading-none text-gray-11">+ {current.source}+ </span>+ ))}+ </>+ );+}++function TierTile({ emoji, size = 'md' }: { emoji: string; size?: TileSize }) {+ return (+ <span+ className={cn(+ 'flex shrink-0 items-center justify-center rounded-md bg-gray-3',+ TILE_SIZE[size],+ )}+ >+ {emoji}+ </span>+ );+}++function CreditTile({+ tierId,+ size = 'md',+}: {+ tierId: string;+ size?: TileSize;+}) {+ const Icon = CREDIT_TIERS[tierId]?.icon ?? Sparkles;+ return (+ <span+ className={cn(+ 'flex shrink-0 items-center justify-center rounded-md bg-accent-3',+ TILE_SIZE[size],+ )}+ >+ <Icon className="size-3.5 text-accent-11" />+ </span>+ );+}++function KeyLogo({+ logoUrl,+ name,+ size = 'xs',+}: {+ logoUrl: string;+ name: string;+ size?: 'xxs' | 'xs';+}) {+ return <LogoPlate src={logoUrl} alt={name} size={size} tint />;+}++function TierBadges({+ isDefault,+ isFast,+}: {+ isDefault: boolean;+ isFast: boolean;+}) {+ return (+ <>+ {isDefault && (+ <span className="flex shrink-0 items-center gap-1 rounded-full bg-accent-3 px-1.5 py-0.5 text-xss leading-none text-accent-11">+ <Star className="size-3 text-accent-11" />+ {t('Default')}+ </span>+ )}+ {isFast && (+ <span className="flex shrink-0 items-center gap-1 rounded-full bg-warning-3 px-1.5 py-0.5 text-xss leading-none text-warning-11">+ <Zap className="size-3 text-warning-11" />+ {t('Fast')}+ </span>+ )}+ </>+ );+}++function contextOf({ model }: { model: OptionModel }): string | undefined {+ const tokens = model.metadata?.contextTokens;+ return isNil(tokens) ? undefined : modelMeta.formatContext({ tokens });+}++function creditDescriptionOf({+ tierId,+}: {+ tierId: string;+}): string | undefined {+ const description = CREDIT_TIERS[tierId]?.description;+ return isNil(description) ? undefined : t(description);+}++const CREDIT_TIERS: Partial<+ Record<string, { icon: typeof Sparkles; 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' },+};++type CurrentPick = {+ kind: 'tier' | 'credits' | 'model' | 'hidden' | 'unavailable' | 'empty';+ id: string;+ configId?: string;+ label: string;+ leading: ReactNode;+ source: string;+};++type TileSize = 'sm' | 'md';++const TILE_SIZE: Record<TileSize, string> = {+ sm: 'size-5 text-xs',+ md: 'size-6 text-sm',+};++type PickerView = {+ groups: ModelPickerGroup<ModelChoice>[];+ detailById: Map<string, ModelDetail>;+ current: CurrentPick;+};++type ModelPickerProps = {+ projectId: string;+ surface: ModelOptionsSurface;+ value: ModelChoice | null;+ onChange: (choice: ModelChoice) => void;+ disabled?: boolean;+ className?: string;+};diff --git a/packages/web/src/features/agents/ai-model/section-heading.tsx b/packages/web/src/features/agents/ai-model/section-heading.tsxnew file mode 100644index 00000000000..384bb0b6e68--- /dev/null+++ b/packages/web/src/features/agents/ai-model/section-heading.tsx@@ -0,0 +1,10 @@+import { cn } from '@/lib/utils';++export function SectionHeading({ dot, label }: { dot: string; label: string }) {+ return (+ <span className="flex items-center gap-2 text-xss font-semibold tracking-wider text-gray-11 uppercase">+ <span className={cn('size-1.5 rounded-full', dot)} />+ {label}+ </span>+ );+}diff --git a/packages/web/src/features/agents/index.ts b/packages/web/src/features/agents/index.tsindex 0a7715aeaec..635eb2172a8 100644--- a/packages/web/src/features/agents/index.ts+++ b/packages/web/src/features/agents/index.ts@@ -11,6 +11,7 @@ export { PieceActionsList } from './agent-tools/piece-tool-dialog/dialog-pages/pexport { PiecesList } from './agent-tools/piece-tool-dialog/dialog-pages/pieces-list';export { usePieceToolsDialogStore } from './agent-tools/stores/pieces-tools';export { AIModelSelector, PROVIDER_EMBEDDING_MODELS } from './ai-model';+export { ModelPicker } 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/platform-admin/api/ai-provider-api.ts b/packages/web/src/features/platform-admin/api/ai-provider-api.tsindex 32186107144..32a080893c2 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@@ -3,6 +3,8 @@ import {AIProviderModel,AIProviderWithoutSensitiveData,CreateAIProviderRequest,+ ModelOptions,+ ModelOptionsSurface,ProjectAIProvider,UpdateAIProviderRequest,} from '@activepieces/shared';@@ -33,6 +35,21 @@ export const aiProviderApi = {`/v1/ai-providers/configs/${configId}/models`,);},+ listModelOptions({+ projectId,+ surface,+ tierId,+ }: {+ projectId: string;+ surface: ModelOptionsSurface;+ tierId?: string;+ }) {+ return api.get<ModelOptions>('/v1/ai-providers/model-options', {+ projectId,+ surface,+ ...(tierId === undefined ? {} : { tierId }),+ });+ },listModelTiers() {return api.get<ModelTiersResponse>('/v1/ai-providers/tiers');},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 c26bd274b37..c791834d793 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@@ -1,16 +1,11 @@// @vitest-environment jsdom+import { AIProviderName } from '@activepieces/core-utils';+import { ModelChoice } from '@activepieces/shared';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { cleanup, render, screen } from '@testing-library/react';import { createMemoryRouter, RouterProvider } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-type ModelPick = {- provider?: string;- model?: string;- configId?: string;- picked?: 'user' | 'default';-};-const pendingSaves: { onSuccess?: () => void }[] = [];vi.mock('i18next', () => ({ t: (key: string) => key }));@@ -28,43 +23,26 @@ vi.mock('@/hooks/authorization-hooks', () => ({useAuthorization: () => ({ checkAccess: () => true }),}));vi.mock('@/features/agents', () => ({- AIModelSelector: ({ onChange }: { onChange: (value: ModelPick) => void }) => (+ ModelPicker: ({ onChange }: { onChange: (value: ModelChoice) => void }) => (<><buttondata-testid="model"onClick={() =>onChange({- provider: 'openai',- model: 'gpt-5',- configId: undefined,- picked: 'user',- })- }- />- <button- data-testid="model-replaced-by-default"- onClick={() =>- onChange({- provider: 'openai',- model: 'gpt-5-mini',- configId: undefined,- picked: 'default',+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'key-1',+ modelId: 'gpt-5',})}/><button- data-testid="model-filled-by-default"- onClick={() =>- onChange({- provider: 'openai',- model: 'gpt-5',- configId: undefined,- picked: 'default',- })- }+ data-testid="tier"+ onClick={() => onChange({ type: 'tier', tierId: 'tier-1' })}/></>),+ PROVIDER_EMBEDDING_MODELS: {},AgentStructuredOutput: () => <div data-testid="structured" />,KnowledgeBaseSection: () => <div data-testid="knowledge" />,useAgentsAvailable: () => true,@@ -150,31 +128,19 @@ beforeEach(() => {afterEach(cleanup);describe('the leave guard only speaks for edits a person made', () => {- it('lets you leave after the selector swapped in a model by itself', async () => {- const onExit = vi.fn();- renderScreen({ onExit });- await settle();-- screen.getByTestId('model-replaced-by-default').click();- await settle();- clickBack();- await settle();-- expect(screen.queryByText('Leave without saving?')).toBeNull();- expect(onExit).toHaveBeenCalledTimes(1);- });-- it('keeps a model the selector filled in for a blank agent', async () => {+ it('asks for a model on a blank agent until a tier is picked', async () => {renderScreen({ onExit: vi.fn() });await settle();expect(screen.queryByText('Pick a model so this agent can answer.'),).toBeTruthy();- screen.getByTestId('model-filled-by-default').click();+ screen.getByTestId('tier').click();await settle();- expect(screen.queryByText('Pick a model so this agent can answer.')).toBeNull();+ expect(+ screen.queryByText('Pick a model so this agent can answer.'),+ ).toBeNull();});it('still stops you when the model was picked by hand', async () => {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 473229b052f..1bf1458b583 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@@ -21,7 +21,8 @@ vi.mock('@/hooks/authorization-hooks', () => ({useAuthorization: () => ({ checkAccess: () => true }),}));vi.mock('@/features/agents', () => ({- AIModelSelector: () => <div data-testid="model" />,+ ModelPicker: () => <div data-testid="model" />,+ PROVIDER_EMBEDDING_MODELS: {},AgentStructuredOutput: () => <div data-testid="structured" />,KnowledgeBaseSection: () => <div data-testid="knowledge" />,useAgentsAvailable: () => true,diff --git a/packages/web/test/app/routes/agents/lib/agent-edit-state.test.ts b/packages/web/test/app/routes/agents/lib/agent-edit-state.test.tsindex 86378417301..973dcbbf34b 100644--- a/packages/web/test/app/routes/agents/lib/agent-edit-state.test.ts+++ b/packages/web/test/app/routes/agents/lib/agent-edit-state.test.ts@@ -1,3 +1,4 @@+import { AIProviderName } from '@activepieces/core-utils';import { describe, expect, it } from 'vitest';import { agentEditState } from '@/app/routes/agents/lib/agent-edit-state';@@ -232,3 +233,62 @@ describe('serverMovedWhileTyping', () => {).toBe(false);});});++describe('agentEditState model choice', () => {+ it('maps a tier pick to only the tier id and back', () => {+ const pick = agentEditState.modelPickOf({+ choice: { type: 'tier', tierId: 'tier-1' },+ });+ expect(pick).toEqual({+ provider: null,+ modelName: null,+ providerConfigId: null,+ modelTierId: 'tier-1',+ });+ expect(agentEditState.modelChoiceOf({ config: pick })).toEqual({+ type: 'tier',+ tierId: 'tier-1',+ });+ expect(agentEditState.hasModel({ config: pick })).toBe(true);+ });++ it('maps a model pick to provider, key and model, and clears the tier', () => {+ const pick = agentEditState.modelPickOf({+ choice: {+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'key-1',+ modelId: 'gpt-5',+ },+ });+ expect(pick).toEqual({+ provider: AIProviderName.OPENAI,+ modelName: 'gpt-5',+ providerConfigId: 'key-1',+ modelTierId: null,+ });+ expect(+ agentEditState.modelPickChanged({+ picked: pick,+ current: { ...pick, modelTierId: 'tier-1' },+ }),+ ).toBe(true);+ });++ it('reads a legacy row without a key id and treats no model as missing', () => {+ expect(+ agentEditState.modelChoiceOf({+ config: { provider: AIProviderName.OPENAI, modelName: 'gpt-5' },+ }),+ ).toEqual({+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: '',+ modelId: 'gpt-5',+ });+ expect(agentEditState.modelChoiceOf({ config: {} })).toBeNull();+ expect(+ agentEditState.hasModel({ config: { provider: AIProviderName.OPENAI } }),+ ).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 a1b6b8498a1..8b394d81be4 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@@ -286,13 +286,27 @@ describe('modelMeta project scope', () => {const open = key('open', {});const onlyA = key('onlyA', { projectScope: 'selected', projectIds: ['A'] });const notA = key('notA', { projectScope: 'except', projectIds: ['A'] });- const configsById = new Map([open, onlyA, notA].map((config) => [config.id, config]));+ const configsById = new Map(+ [open, onlyA, notA].map((config) => [config.id, config]),+ );const projectIds = ['A', 'B', 'C'];it('mirrors the server rule for which projects a key serves', () => {- expect(projectIds.filter((projectId) => modelMeta.keyServesProject({ config: onlyA, projectId }))).toEqual(['A']);- expect(projectIds.filter((projectId) => modelMeta.keyServesProject({ config: notA, projectId }))).toEqual(['B', 'C']);- expect(projectIds.filter((projectId) => modelMeta.keyServesProject({ config: open, projectId }))).toEqual(projectIds);+ expect(+ projectIds.filter((projectId) =>+ modelMeta.keyServesProject({ config: onlyA, projectId }),+ ),+ ).toEqual(['A']);+ expect(+ projectIds.filter((projectId) =>+ modelMeta.keyServesProject({ config: notA, projectId }),+ ),+ ).toEqual(['B', 'C']);+ expect(+ projectIds.filter((projectId) =>+ modelMeta.keyServesProject({ config: open, projectId }),+ ),+ ).toEqual(projectIds);});it('counts the projects a tier is missing from and the fallbacks skipped where it runs', () => {@@ -323,7 +337,10 @@ describe('modelMeta project scope', () => {it('reports what narrowing a key does to the tiers that use it', () => {const tiers = [- { ...tier('Expert', [{ configId: open.id, modelId: 'main' }]), name: 'Expert' },+ {+ ...tier('Expert', [{ configId: open.id, modelId: 'main' }]),+ name: 'Expert',+ },{...tier('Fast', [{ configId: notA.id, modelId: 'main' },@@ -331,7 +348,10 @@ describe('modelMeta project scope', () => {]),name: 'Fast',},- { ...tier('Other', [{ configId: notA.id, modelId: 'main' }]), name: 'Other' },+ {+ ...tier('Other', [{ configId: notA.id, modelId: 'main' }]),+ name: 'Other',+ },];const impact = modelMeta.keyScopeImpact({diff --git a/packages/web/test/features/agents/ai-model/model-picker-popover.test.tsx b/packages/web/test/features/agents/ai-model/model-picker-popover.test.tsxindex db2d0d3dd86..8fdc512748d 100644--- a/packages/web/test/features/agents/ai-model/model-picker-popover.test.tsx+++ b/packages/web/test/features/agents/ai-model/model-picker-popover.test.tsx@@ -101,6 +101,141 @@ describe('ModelPickerPopover', () => {).not.toBeNull();});+ const mountKeys = () => {+ act(() => {+ root = createRoot(document.body);+ root.render(+ <ModelPickerPopover+ groups={[+ {+ id: 'open-key',+ section: 'keys',+ heading: 'Open key',+ collapsible: true,+ defaultOpen: true,+ items: items('gamma', 2),+ },+ {+ id: 'closed-key',+ section: 'keys',+ heading: 'Closed key',+ collapsible: true,+ items: items('delta', 4),+ },+ ]}+ emptyText="No models match"+ onPick={() => undefined}+ open+ onOpenChange={() => undefined}+ detail={(item) => <span>detail of {item.name}</span>}+ >+ <button type="button">Pick</button>+ </ModelPickerPopover>,+ );+ });+ };++ const toggleRow = (label: string) =>+ Array.from(rows()).find((row) => row.textContent?.includes(label));++ it('shows a collapsed key as one toggle row and opens it on select or search', async () => {+ mountKeys();+ expect(rows()).toHaveLength(1 + 2 + 1);+ expect(bodyText()).not.toContain('delta model 1');++ act(() => {+ toggleRow('Closed key')?.dispatchEvent(+ new MouseEvent('click', { bubbles: true }),+ );+ });+ expect(bodyText()).toContain('delta model 1');++ act(() => {+ toggleRow('Closed key')?.dispatchEvent(+ new MouseEvent('click', { bubbles: true }),+ );+ });+ expect(bodyText()).not.toContain('delta model 1');++ typeSearch('delta model 2');+ await act(async () => {+ await Promise.resolve();+ });+ expect(bodyText()).toContain('delta model 2');+ expect(bodyText()).not.toContain('Open key');+ });++ it('shows the detail of the highlighted item, skips disabled rows and keeps it on a toggle row', () => {+ mountKeys();+ const detail = () =>+ document.querySelector('[data-testid="model-picker-detail"]')+ ?.textContent;+ const pressDown = () =>+ act(() => {+ document+ .querySelector('[cmdk-root]')+ ?.dispatchEvent(+ new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }),+ );+ });++ expect(detail()).toBeUndefined();+ pressDown();+ expect(detail()).toBe('detail of gamma model 1');+ pressDown();+ expect(detail()).toBe('detail of gamma model 1');+ });++ it('opens the detail card only on hover and closes it shortly after the pointer leaves', async () => {+ mountKeys();+ const detail = () =>+ document.querySelector('[data-testid="model-picker-detail"]')+ ?.textContent;+ expect(detail()).toBeUndefined();++ const row = Array.from(rows()).find((candidate) =>+ candidate.textContent?.includes('gamma model 1'),+ );+ act(() => {+ row?.dispatchEvent(new MouseEvent('pointermove', { bubbles: true }));+ });+ expect(detail()).toBe('detail of gamma model 1');++ act(() => {+ document+ .querySelector('[cmdk-root]')+ ?.parentElement?.dispatchEvent(+ new MouseEvent('pointerout', { bubbles: true }),+ );+ });+ expect(detail()).toBe('detail of gamma model 1');+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 200));+ });+ expect(detail()).toBeUndefined();+ });++ it('clears the detail card when a row is picked', () => {+ mountKeys();+ const row = Array.from(rows()).find((candidate) =>+ candidate.textContent?.includes('gamma model 1'),+ );+ act(() => {+ row?.dispatchEvent(new MouseEvent('pointermove', { bubbles: true }));+ });+ expect(+ document.querySelector('[data-testid="model-picker-detail"]'),+ ).not.toBeNull();++ act(() => {+ row?.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ expect(+ document.querySelector('[data-testid="model-picker-detail"]'),+ ).toBeNull();+ });+it('filters with its own matcher and drops empty groups', async () => {mount();typeSearch('alpha');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.tsxnew file mode 100644index 00000000000..94aa6d9c717--- /dev/null+++ b/packages/web/test/features/agents/ai-model/model-picker.test.tsx@@ -0,0 +1,190 @@+/**+ * @vitest-environment jsdom+ */+import { AIProviderName } from '@activepieces/core-utils';+import { AIProviderModelType, ModelOptions } from '@activepieces/shared';+import { describe, expect, it, vi } from 'vitest';++vi.mock('i18next', () => ({+ default: { language: 'en' },+ t: (key: string) => key,+}));++import { modelPickerView } from '@/features/agents/ai-model/model-picker';++const optionModel = (modelId: string) => ({+ provider: AIProviderName.OPENAI,+ modelId,+ name: `${modelId} name`,+ keyName: 'Team key',+});++const options: ModelOptions = {+ tiers: [+ {+ id: 'tier-expert',+ name: 'Expert',+ emoji: '🧠',+ description: 'Hard tasks',+ isDefault: true,+ isFast: false,+ main: optionModel('gpt-6'),+ fallbacks: [optionModel('gpt-6-mini')],+ },+ ],+ credits: {+ providerConfigId: 'managed',+ defaultTierId: 'smart',+ tiers: [+ {+ id: 'smart',+ label: 'Smart',+ model: { ...optionModel('anthropic/claude'), keyName: 'Managed' },+ },+ ],+ },+ keys: [+ {+ providerConfigId: 'key-a',+ provider: AIProviderName.OPENAI,+ name: 'Team key',+ models: [+ { id: 'gpt-6', name: 'GPT-6', type: AIProviderModelType.TEXT },+ {+ id: 'gpt-6-mini',+ name: 'GPT-6 mini',+ type: AIProviderModelType.TEXT,+ },+ ],+ },+ {+ providerConfigId: 'key-b',+ provider: AIProviderName.ANTHROPIC,+ name: 'Prod key',+ models: [+ { id: 'claude', name: 'Claude', type: AIProviderModelType.TEXT },+ ],+ },+ ],+ defaultChoice: { type: 'tier', tierId: 'tier-expert' },+ movedTiers: { 'tier-old': 'tier-expert' },+ specificModelsHidden: false,+};++describe('modelPickerView', () => {+ it('builds tiers, credits and one collapsible group per key, opening only the picked key', () => {+ const { groups } = modelPickerView({+ options,+ shown: {+ type: 'model',+ provider: AIProviderName.ANTHROPIC,+ providerConfigId: 'key-b',+ modelId: 'claude',+ },+ });++ expect(groups.map((group) => [group.id, group.section])).toEqual([+ ['tiers', 'tiers'],+ ['credits', 'credits'],+ ['key:key-a', 'keys'],+ ['key:key-b', 'keys'],+ ]);+ expect(groups[2]).toMatchObject({ collapsible: true, defaultOpen: false });+ expect(groups[3]).toMatchObject({ collapsible: true, defaultOpen: true });+ expect(groups[3].items[0].selected).toBe(true);+ expect(groups[0].items[0].searchText).toContain('gpt-6-mini name');+ });++ it('shows a deleted tier as its replacement', () => {+ const { current, groups } = modelPickerView({+ options,+ shown: { type: 'tier', tierId: 'tier-old' },+ });++ expect(current).toMatchObject({+ kind: 'tier',+ label: 'Expert',+ source: 'Moved',+ });+ expect(groups[0].items[0].selected).toBe(true);+ });++ it('marks a pick that is gone as unavailable, and one hidden by the admin as hidden', () => {+ const gone = modelPickerView({+ options,+ shown: { type: 'tier', tierId: 'tier-unknown' },+ });+ expect(gone.current).toMatchObject({+ kind: 'unavailable',+ source: 'Unavailable',+ });++ const hidden = modelPickerView({+ options: { ...options, keys: [], specificModelsHidden: true },+ shown: {+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'key-a',+ modelId: 'gpt-6',+ },+ });+ expect(hidden.current).toMatchObject({ kind: 'hidden', label: 'gpt-6' });+ });++ it('finds a legacy model pick without a key id by its provider', () => {+ const { current } = modelPickerView({+ options,+ shown: {+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: '',+ modelId: 'gpt-6-mini',+ },+ });++ expect(current).toMatchObject({+ kind: 'model',+ configId: 'key-a',+ label: 'GPT-6 mini',+ });+ });++ it('shows a pick on a key that is gone as unavailable, even when another key has the model', () => {+ const { current } = modelPickerView({+ options,+ shown: {+ type: 'model',+ provider: AIProviderName.OPENAI,+ providerConfigId: 'deleted-key',+ modelId: 'gpt-6',+ },+ });++ expect(current).toMatchObject({ kind: 'unavailable', label: 'gpt-6' });+ });++ it('picks a credits tier with the managed key and keeps details for every row', () => {+ const { groups, detailById, current } = modelPickerView({+ options,+ shown: {+ type: 'model',+ provider: AIProviderName.ACTIVEPIECES,+ providerConfigId: 'managed',+ modelId: 'smart',+ },+ });++ expect(current).toMatchObject({ kind: 'credits', label: 'Smart' });+ expect(groups[1].items[0].value).toEqual({+ type: 'model',+ provider: AIProviderName.ACTIVEPIECES,+ providerConfigId: 'managed',+ modelId: 'smart',+ });+ expect(detailById.get('tier:tier-expert')?.fallbacks).toEqual([+ { name: 'gpt-6-mini name', keyName: 'Team key' },+ ]);+ expect(detailById.get('credits:smart')?.showPrices).toBe(false);+ expect(detailById.size).toBe(5);+ });+});