Agent Zero AI framework
Unify global model presets
frdel15a2b553beaa
diff --git a/README.md b/README.mdindex 45efd23d1..0aa2d8a8e 100644--- a/README.md+++ b/README.md@@ -33,7 +33,7 @@ Agent Zero is an open agent framework for work that needs more than chat: a Dock| **Browser DOM annotation** | Click page elements and turn them into inspect, change, lift, or review instructions. || **Live document cowork** | Edit Markdown, Writer, Spreadsheet, and Presentation files together instead of losing work in chat. || **Plugin Hub** | Install 100+ community plugins or publish your own extension points. |-| **Projects and memory** | Keep files, instructions, secrets, memories, repositories, and model presets isolated per project. |+| **Projects and memory** | Keep files, instructions, secrets, memories, repositories, and model-preset choices isolated per project. || **Host-machine bridge** | Connect with the A0 CLI so the same agent can work in your real local repositories. || **Multi-agent cooperation** | Let agents delegate research, coding, analysis, or review tasks to focused subagents. || **Transparent internals** | Prompts, tools, plugins, skills, and settings are inspectable and editable. |@@ -223,7 +223,7 @@ For full setup, see the [A0 CLI Connector guide](https://www.agent-zero.ai/p/doc## Projects, Skills, Agent Profiles, and Model Presets-**Projects** isolate workspaces, instructions, memory, secrets, knowledge, repositories, and model presets. Clone a public or private Git repo into a project and give the agent context that belongs to that work alone.+**Projects** isolate workspaces, instructions, memory, secrets, knowledge, repositories, and model-preset choices. Clone a public or private Git repo into a project and give the agent context that belongs to that work alone.**Skills** can be loaded on demand by Agent Zero, or pinned from the chat input when you want a specific procedure to stay active.diff --git a/docs/guides/model-presets.md b/docs/guides/model-presets.mdindex ff23a06fd..0bf3e317a 100644--- a/docs/guides/model-presets.md+++ b/docs/guides/model-presets.md@@ -1,6 +1,7 @@# Model Presets-Model Presets are named shortcuts for model choices.+Model Presets are named, reusable model setups. Every setup contains a main,+utility, and embedding model.Use them when you want to switch a chat between setups such as "fast", "cheap","local", "balanced", or "maximum power" without rebuilding the settings each@@ -9,6 +10,8 @@ time.## Choose A PresetThe preset menu is the first dropdown on the left side of the chat status bar.+Its closed label shows the preset and the short main-model name, without the+provider prefix.@@ -16,20 +19,35 @@ The preset menu is the first dropdown on the left side of the chat status bar.2. Click the current preset name.3. Choose the preset you want.-The selected preset affects the current chat.+The selected preset affects the current chat. Choose **Use scoped preset** to+return the chat to the default selected for its project and agent profile. If no+more specific choice exists, Agent Zero uses the global preset.++The **Default** preset is always available. You can edit its models, but you+cannot rename or delete it.++## Initial Presets++When no saved preset collection exists at startup, Agent Zero downloads the+curated **Default**, **Efficiency**, and **Power** presets from the public+[`agent0ai/a0-presets`](https://github.com/agent0ai/a0-presets) repository. If+GitHub is unavailable or the file is invalid, Agent Zero saves its bundled+plugin fallback instead. Existing saved presets short-circuit this check and+are never replaced.## Edit PresetsClick **Edit presets** from the same menu.--From this screen you can:- rename presets;- choose the main model;- choose the utility model;+- choose the embedding model;+- enter the shared API key for each model provider;- open API key settings;+- add or delete presets (except **Default**);- save the preset list.Think of a preset as a label on a model setup.@@ -38,17 +56,14 @@ Think of a preset as a label on a model setup.| --- | --- || **Main model** | The model that does the main conversation and reasoning. || **Utility model** | A smaller helper model for lighter internal tasks. |+| **Embedding model** | The model that creates vectors for memory and knowledge retrieval. |-Presets can be partial. If a preset does not set a utility model, Agent Zero-uses your configured Utility Model. If a preset changes the utility model but-does not set advanced fields, your configured context window, rate limits, and-other advanced values stay in place.+The editor presents each preset as one complete setup. Internally, an existing+non-default preset may inherit omitted advanced values from **Default**.## Add A Preset-Click **Add Preset**, give it a name, choose models, then click **Save Presets**.--+Click **Add**, give it a name, choose models, then click **Save**.Good preset names are easy to spot quickly:@@ -76,11 +91,22 @@ If you are not sure what to create, start with three presets:You can always rename them later.+## Choose Defaults For New Chats++In **Settings → Agent → Models**, choose the global preset used by new chats.+The summary shows its main, utility, and embedding models. Changing it also+applies that preset to the currently open chat.++Use **Per-project / agent** to open the full Model Configuration plugin. Its+scope selector lets you choose a different default preset for a project, an+agent profile, or their combination. These scopes store only the preset choice;+editing a preset updates every scope that uses it.+## How Presets Fit With Other Controls| Control | What it changes || --- | --- |-| **Model Preset** | Which models power the chat. |+| **Model Preset** | Which main, utility, and embedding models power the chat. || **Agent Profile** | The agent's role, tone, and prompt behavior. || **Project** | Workspace, files, memory, secrets, and project instructions. || **Skill** | A specific procedure added to prompt protocol. |diff --git a/extensions/python/message_loop_prompts_after/_70_include_agent_info.py b/extensions/python/message_loop_prompts_after/_70_include_agent_info.pyindex 85d38215c..c4dc3f4d7 100644--- a/extensions/python/message_loop_prompts_after/_70_include_agent_info.py+++ b/extensions/python/message_loop_prompts_after/_70_include_agent_info.py@@ -8,15 +8,12 @@ class IncludeAgentInfo(Extension):return# read prompt- from plugins._model_config.helpers.model_config import get_chat_model_config, is_chat_override_allowed+ from plugins._model_config.helpers.model_config import (+ get_chat_model_config,+ get_effective_preset_name,+ )chat_cfg = get_chat_model_config(self.agent)-- # detect active preset (only when override is allowed)- preset_name = ""- if is_chat_override_allowed(self.agent):- override = self.agent.context.get_data("chat_model_override")- if isinstance(override, dict):- preset_name = override.get("preset_name", "")+ preset_name = get_effective_preset_name(self.agent)agent_info_prompt = self.agent.read_prompt("agent.extras.agent_info.md",diff --git a/helpers/integration_commands.py b/helpers/integration_commands.pyindex b4c4cc361..34eb9fbfa 100644--- a/helpers/integration_commands.py+++ b/helpers/integration_commands.py@@ -15,6 +15,7 @@ if TYPE_CHECKING:_CLEAR_VALUES = {"", "default", "none", "clear", "off"}+_MODEL_INHERIT_VALUES = {"", "none", "clear", "off", "inherit"}@dataclass(frozen=True)@@ -85,7 +86,7 @@ COMMAND_REGISTRY: tuple[IntegrationCommandDef, ...] = ("Show or switch the chat model preset.","Configuration",aliases=("config", "preset"),- args_hint="[preset|default]",+ args_hint="[preset|inherit]",),IntegrationCommandDef("agent",@@ -270,7 +271,6 @@ def _handle_queue(context: "AgentContext", args: str) -> str:def _handle_status(context: "AgentContext") -> str:project_name = context.get_data("project") or "none"- override = context.get_data("chat_model_override")agent_profile = getattr(context.agent0.config, "profile", "default")running = "running" if context.is_running() else "idle"if getattr(context, "paused", False):@@ -279,7 +279,7 @@ def _handle_status(context: "AgentContext") -> str:return (f"Status: {running}\n"f"Project: {project_name}\n"- f"Model: {_describe_override(override)}\n"+ f"Model: {model_config.get_effective_preset_name(context.agent0)}\n"f"Agent: {agent_profile}\n"f"Queued messages: {queue_count}")@@ -394,9 +394,9 @@ def _handle_model(context: "AgentContext", args: str) -> str:current_override = context.get_data("chat_model_override")if not args:- current_label = _describe_override(current_override)+ current_label = model_config.get_effective_preset_name(context.agent0)available = ", ".join(preset["name"] for preset in presets) or "none"- suffix = "Use /model <name> to switch, or /model default to clear it."+ suffix = "Use /model <name> to switch, or /model inherit to use the scoped preset."if not allowed:suffix = "Per-chat config switching is disabled in Model Configuration."return (@@ -409,13 +409,14 @@ def _handle_model(context: "AgentContext", args: str) -> str:return "Config switching is disabled in Model Configuration."desired = _strip_quotes(args)- if _normalize_lookup(desired) in _CLEAR_VALUES:+ if _normalize_lookup(desired) in _MODEL_INHERIT_VALUES:if not current_override:- return "Already using the default config."+ return "Already using the scoped model preset."context.set_data("chat_model_override", None)save_tmp_chat(context)mark_dirty_for_context(context.id, reason="integration_commands.config_clear")- return "Switched back to the default config."+ inherited = model_config.get_effective_preset_name(context.agent0)+ return f"Switched back to the scoped model preset: {inherited}."match, ambiguous = _match_named_item(presets, desired, keys=("name",))if ambiguous:@@ -503,14 +504,6 @@ def _describe_project(items: list[dict], current_name: str) -> str:return current_name-def _describe_override(override: dict | None) -> str:- if not override:- return "Default"- if isinstance(override, dict) and override.get("preset_name"):- return str(override["preset_name"])- return "Custom override"--def _strip_quotes(value: str) -> str:trimmed = value.strip()if len(trimmed) >= 2 and trimmed[0] == trimmed[-1] and trimmed[0] in {'"', "'"}:diff --git a/helpers/integration_commands.py.dox.md b/helpers/integration_commands.py.dox.mdindex 1d00fb083..ec3266fb0 100644--- a/helpers/integration_commands.py.dox.md+++ b/helpers/integration_commands.py.dox.md@@ -3,27 +3,16 @@## Purpose- Own the `integration_commands.py` helper module.-- This module parses external integration slash commands such as project/config/send controls.+- This module parses external integration slash commands such as project/model/send controls.- Keep this file-level DOX profile synchronized with `integration_commands.py` because this directory is intentionally flat.## Ownership- `integration_commands.py` owns the runtime implementation.- `integration_commands.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.-- Top-level functions:-- `extract_command_line(text: str) -> str`-- `parse_command(text: str) -> tuple[str, str] | None`-- `try_handle_command(context: 'AgentContext', text: str) -> str | None`-- `_handle_queue(context: 'AgentContext', args: str) -> str`-- `_handle_project(context: 'AgentContext', args: str) -> str`-- `_handle_config(context: 'AgentContext', args: str) -> str`-- `_format_project_entry(item: dict) -> str`-- `_describe_project(items: list[dict], current_name: str) -> str`-- `_describe_override(override: dict | None) -> str`-- `_strip_quotes(value: str) -> str`-- `_normalize_lookup(value: str) -> str`-- `_match_named_item(items: list[dict], desired: str, keys: tuple[str, ...]) -> tuple[dict | None, list[dict]]`-- Notable constants/configuration names: `_CLEAR_VALUES`, `_SUPPORTED_COMMANDS`.+- Public command helpers are `extract_command_line`, `parse_command`, `resolve_command`, `telegram_menu_commands`, `command_names`, `help_text`, `unknown_command_text`, and `try_handle_command`.+- Internal handlers own queue, status, session, lifecycle, toggle, project, model-preset, and agent-profile commands.+- Notable constants are `COMMAND_REGISTRY`, `_CLEAR_VALUES`, and `_MODEL_INHERIT_VALUES`.## Runtime Contracts@@ -32,10 +21,11 @@- Observed side-effect areas: filesystem writes, model calls, plugin state, settings/state persistence.- Imported dependency areas include: `__future__`, `helpers`, `helpers.persist_chat`, `helpers.state_monitor_integration`, `plugins._model_config.helpers`, `re`, `typing`.- `/agent` switches the top-level chat profile and preserves existing subordinate agent profiles.+- `/model <preset>` stores a per-chat global preset reference, `/model inherit` clears it, and status always reports the effective scoped-or-chat preset. `Default` is a real selectable preset, not an alias for clearing the chat selection.## Key Concepts-- Important called helpers/classes observed in the source: `splitlines`, `extract_command_line`, `line.partition`, `command.strip.lower`, `parse_command`, `mq.get_queue`, `args.strip.lower`, `mq.send_all_aggregated`, `mark_dirty_for_context`, `_strip_quotes`, `_match_named_item`, `projects.activate_project`, `initialize_agent`, `model_config.is_chat_override_allowed`, `context.get_data`, `context.set_data`, `save_tmp_chat`, `str.strip`, `value.strip`, `value.lower.strip`, `re.sub`.+- Important called helpers/classes include `mq.get_queue`, `mq.send_all_aggregated`, `mark_dirty_for_context`, `projects.activate_project`, `initialize_agent`, `model_config.get_effective_preset_name`, `model_config.get_presets`, `context.get_data`, `context.set_data`, and `save_tmp_chat`.- Keep request/response, tool, or helper semantics documented here at the same time as source changes.## Work Guidancediff --git a/plugins/_a0_connector/AGENTS.md b/plugins/_a0_connector/AGENTS.mdindex 64ad6e612..63230523d 100644--- a/plugins/_a0_connector/AGENTS.md+++ b/plugins/_a0_connector/AGENTS.md@@ -61,6 +61,7 @@`connector_file_op_result` frames; resolve the pending file operation onlyafter all chunks for the `op_id` are assembled.- Host browser status metadata may advertise `available_browsers` entries with browser ids, labels, CDP endpoints, status, and enabled state; keep older CLI payloads without those fields compatible.+- Model preset definitions exposed through v1 are global; project arguments select scope but never create project-owned definitions. Model switcher state reports the effective main, utility, and embedding models and preserves embedding-change notifications.## Work Guidancediff --git a/plugins/_a0_connector/api/v1/model_presets.py b/plugins/_a0_connector/api/v1/model_presets.pyindex 1b2df6a83..b06276432 100644--- a/plugins/_a0_connector/api/v1/model_presets.py+++ b/plugins/_a0_connector/api/v1/model_presets.py@@ -8,6 +8,12 @@ import plugins._a0_connector.api.v1.base as connector_baseclass ModelPresets(connector_base.ProtectedConnectorApiHandler):async def process(self, input: dict, request: Request) -> dict | Response:from plugins._model_config.helpers import model_config+ from plugins._model_config.api.model_presets import (+ _embedding_signature,+ _notify_embedding_changed,+ _rename_preset_references,+ _retired_preset_references,+ )action = str(input.get("action", "get")).strip() or "get"project_name = str(input.get("project_name") or "").strip()@@ -15,18 +21,13 @@ class ModelPresets(connector_base.ProtectedConnectorApiHandler):if action == "get":if scope == "project":- presets = model_config.get_project_presets(project_name) if project_name else []- return {"ok": True, "presets": presets}+ return {"ok": True, "presets": []}if scope == "combined" or project_name:return {"ok": True,"presets": model_config.get_combined_presets(project_name or None),"global_presets": model_config.get_presets(),- "project_presets": (- model_config.get_project_presets(project_name)- if project_name- else []- ),+ "project_presets": [],}return {"ok": True, "presets": model_config.get_presets()}@@ -34,16 +35,54 @@ class ModelPresets(connector_base.ProtectedConnectorApiHandler):presets = input.get("presets")if not isinstance(presets, list):return Response(status=400, response="presets must be an array")- model_config.save_presets(- presets,- project_name=project_name if scope == "project" or project_name else None,- )- return {"ok": True, "presets": model_config.clean_presets_for_file(presets)}+ if scope == "project" or project_name:+ return Response(+ status=400,+ response="Preset definitions are global; select a global preset for this project.",+ )+ previous = model_config.get_presets()+ previous_names = {str(preset.get("name") or "") for preset in previous}+ previous_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in previous+ }+ try:+ model_config.save_presets(presets)+ except ValueError as exc:+ return Response(status=400, response=str(exc))+ saved = model_config.get_presets()+ saved_names = {str(preset.get("name") or "") for preset in saved}+ retired = _retired_preset_references(previous_names, saved_names)+ renames = input.get("renames") if isinstance(input.get("renames"), list) else []+ _rename_preset_references([*retired, *renames])+ saved_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in saved+ }+ if previous_embeddings != saved_embeddings:+ _notify_embedding_changed()+ return {"ok": True, "presets": saved}if action == "reset":- presets = model_config.reset_presets(- project_name=project_name if scope == "project" or project_name else None+ if scope == "project" or project_name:+ return Response(status=400, response="Project presets cannot be reset.")+ previous = model_config.get_presets()+ previous_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in previous+ }+ presets = model_config.reset_presets()+ saved_names = {str(preset.get("name") or "") for preset in presets}+ previous_names = {str(preset.get("name") or "") for preset in previous}+ _rename_preset_references(+ _retired_preset_references(previous_names, saved_names))+ current_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in presets+ }+ if previous_embeddings != current_embeddings:+ _notify_embedding_changed()return {"ok": True, "presets": presets}if action == "resolve":@@ -52,8 +91,7 @@ class ModelPresets(connector_base.ProtectedConnectorApiHandler):return Response(status=400, response="Missing preset name")resolved = model_config.resolve_preset(name,- scope=scope or "global",- project_name=project_name or None,+ scope="global",)if not resolved:return Response(status=404, response=f"Preset '{name}' not found")@@ -61,8 +99,8 @@ class ModelPresets(connector_base.ProtectedConnectorApiHandler):"ok": True,"preset": {**resolved,- "scope": scope or "global",- "project_name": project_name if scope == "project" else "",+ "scope": "global",+ "project_name": "",},}diff --git a/plugins/_a0_connector/api/v1/model_switcher.py b/plugins/_a0_connector/api/v1/model_switcher.pyindex f3204daba..faeccb9f0 100644--- a/plugins/_a0_connector/api/v1/model_switcher.py+++ b/plugins/_a0_connector/api/v1/model_switcher.py@@ -4,7 +4,9 @@ from __future__ import annotationsimport timefrom typing import Callable+from helpers import deferfrom helpers.api import Request, Response+from helpers.extension import call_extensions_asyncimport plugins._a0_connector.api.v1.base as connector_base_MODEL_OVERRIDE_REVISION_KEY = "_model_config_override_revision"@@ -91,6 +93,11 @@ def _notify_model_override_changed(context: object, context_id: str) -> None:pass+def _notify_embedding_if_changed(before: dict, after: dict) -> None:+ if before != after:+ defer.DeferredTask().start_task(call_extensions_async, "embedding_model_changed")++class ModelSwitcher(connector_base.ProtectedConnectorApiHandler):async def process(self, input: dict, request: Request) -> dict | Response:from agent import AgentContext@@ -113,6 +120,7 @@ class ModelSwitcher(connector_base.ProtectedConnectorApiHandler):chat_providers = []chat_model = model_config.get_chat_model_config(agent)utility_model = model_config.get_utility_model_config(agent)+ embedding_model = model_config.get_embedding_model_config(agent)def _has_api_key(config: object) -> bool:if not isinstance(config, dict):@@ -130,10 +138,16 @@ class ModelSwitcher(connector_base.ProtectedConnectorApiHandler):"ok": True,"allowed": bool(model_config.is_chat_override_allowed(agent)),"override": override,+ "configured_preset": model_config.get_configured_preset_name(agent=agent),+ "effective_preset": model_config.get_effective_preset_name(agent),"presets": model_config.get_presets(),"chat_providers": chat_providers,"main_model": _model_payload(chat_model, has_api_key=_has_api_key(chat_model)),"utility_model": _model_payload(utility_model, has_api_key=_has_api_key(utility_model)),+ "embedding_model": _model_payload(+ embedding_model,+ has_api_key=_has_api_key(embedding_model),+ ),}if action == "get":@@ -155,31 +169,52 @@ class ModelSwitcher(connector_base.ProtectedConnectorApiHandler):preset = model_config.get_preset_by_name(preset_name)if not preset:return Response(status=404, response=f"Preset '{preset_name}' not found")- context.set_data("chat_model_override", {"preset_name": preset_name})+ previous_embedding = model_config.get_embedding_model_config(agent)+ context.set_data(+ "chat_model_override",+ {"preset_name": str(preset.get("name") or preset_name)},+ )save_tmp_chat(context)_notify_model_override_changed(context, context_id)+ _notify_embedding_if_changed(+ previous_embedding,+ model_config.get_embedding_model_config(agent),+ )return build_state()if action == "clear":+ previous_embedding = model_config.get_embedding_model_config(agent)context.set_data("chat_model_override", None)save_tmp_chat(context)_notify_model_override_changed(context, context_id)+ _notify_embedding_if_changed(+ previous_embedding,+ model_config.get_embedding_model_config(agent),+ )return build_state()if action == "set_override":main_model = _coerce_override_model(input.get("main_model"))utility_model = _coerce_override_model(input.get("utility_model"))- if not main_model and not utility_model:+ embedding_model = _coerce_override_model(input.get("embedding_model"))+ if not main_model and not utility_model and not embedding_model:return Response(status=400, response="Missing model override payload")+ previous_embedding = model_config.get_embedding_model_config(agent)override: dict[str, dict[str, str]] = {}if main_model:override["chat"] = main_modelif utility_model:override["utility"] = utility_model+ if embedding_model:+ override["embedding"] = embedding_modelcontext.set_data("chat_model_override", override)save_tmp_chat(context)_notify_model_override_changed(context, context_id)+ _notify_embedding_if_changed(+ previous_embedding,+ model_config.get_embedding_model_config(agent),+ )return build_state()return Response(status=400, response=f"Unknown action: {action}")diff --git a/plugins/_browser/AGENTS.md b/plugins/_browser/AGENTS.mdindex c9c40c57e..68e84f0b4 100644--- a/plugins/_browser/AGENTS.md+++ b/plugins/_browser/AGENTS.md@@ -30,6 +30,7 @@- Browser URL-intent handling must only claim web URL schemes and leave custom Agent Zero schemes to their owning surfaces.- Prefer DOM/CDP browser actions with refs, selectors, frame-chain refs, and screenshots over viewport coordinate input. Coordinates remain a visual fallback.- Do not hardcode user-specific browser paths or secrets.+- Browser model-preset selection resolves omitted preset fields from `_model_config`'s global `Default` preset, not from an unrelated currently scoped model selection.## Work Guidancediff --git a/plugins/_browser/helpers/config.py b/plugins/_browser/helpers/config.pyindex 60d0bfac5..964c242dc 100644--- a/plugins/_browser/helpers/config.py+++ b/plugins/_browser/helpers/config.py@@ -249,9 +249,17 @@ def resolve_browser_model_selection(preset = model_config.get_preset_by_name(preset_name)if isinstance(preset, dict):if hasattr(model_config, "build_config_from_preset"):+ default_preset = model_config.get_preset_by_name(+ model_config.DEFAULT_PRESET_NAME+ ) or {}+ base_config = (+ model_config.preset_to_config(default_preset)+ if hasattr(model_config, "preset_to_config")+ else {}+ )preset_config = model_config.build_config_from_preset(preset,- model_config.get_config(agent) if hasattr(model_config, "get_config") else {},+ base_config,strip_api_key=False,slots=("chat",),)diff --git a/plugins/_model_config/AGENTS.md b/plugins/_model_config/AGENTS.mdindex ee46e3039..51e7faead 100644--- a/plugins/_model_config/AGENTS.md+++ b/plugins/_model_config/AGENTS.md@@ -2,27 +2,35 @@## Purpose-- Own LLM model selection, presets, API-key checks, scoped overrides, and model settings UI.+- Own global LLM preset definitions, scoped preset selection, API-key checks, chat overrides, migration, and model settings UI.## Ownership- `helpers/model_config.py` owns config resolution, presets, overrides, and runtime model object construction.- `api/` owns model config, override, preset, search, and API-key endpoints.- `webui/` owns model settings, summaries, switcher, and API-key UI.-- `default_config.yaml`, `default_presets.yaml`, `provider_metadata.yaml`, `hooks.py`, and `plugin.yaml` own defaults, metadata, hooks, and manifest.+- `extensions/python/startup_migration/` owns conversion from legacy full configs and project presets, followed by first-launch preset initialization.+- `default_config.yaml`, `mode_presets_fallback.yaml`, `provider_metadata.yaml`, `hooks.py`, and `plugin.yaml` own plugin defaults, offline presets, metadata, hooks, and manifest.## Local Contracts-- Preserve global, project, agent, and chat override resolution order.+- `Default` is the first global preset and cannot be deleted or renamed. It owns the complete main, utility, and embedding baseline.+- Preset definitions are global. Global, project, agent-profile, and project/profile plugin configs persist only `model_preset`; chats may persist a preset reference as their explicit override.+- Preserve scoped plugin resolution order and fall back invalid or missing scope/chat references to `Default`.- Project Settings `llm` payloads are owned here through the generic `helpers.projects` project extension-data hooks; keep project helper code agnostic to `_model_config` paths, presets, and inheritance rules.- Keep provider metadata and API-key checks safe around secrets.- Coordinate OAuth-backed providers with `_oauth` instead of hardcoding provider-specific auth here.- `model_config_get` exposes `model_configured` as a derived chat-model readiness flag from provider, model name, and API-key availability.-- Applying a model preset may inherit durable tuning such as context windows and rate limits, but must replace or clear per-slot `kwargs` so provider-specific extra params never leak across model providers.+- Non-default presets may inherit omitted slots or durable tuning from `Default`, but must replace or clear per-slot `kwargs` so provider-specific extra params never leak across model providers.- Changing a model provider in the settings UI must clear `api_base` and `kwargs` because both may be provider-specific.- Repair provider-specific model-config aliases at the model-config read/build boundary; keep provider-specific repairs out of provider-agnostic core wrappers such as `models.py`.- `modelConfig.createPresetEditor()` owns local preset drafts, row actions, and stable UI-only row keys so deletion or renaming cannot rebind nested model fields.+- The preset editor maps each model provider's API-key field to the shared API-key store; saving the editor persists dirty keys separately and never writes secrets into preset YAML.+- The compact chat selector label combines the effective preset with only the leaf name of its main model; utility and provider text stay out of the closed selector.- Preset editor reset actions must remove the user override through the preset API and refresh the open draft from bundled defaults.+- Preset rename, delete, and reset actions must repair scoped config and durable/live chat references; removed definitions fall back to `Default`.+- Migration must preserve existing definitions and distinct scoped model choices, back up replaced user files once, strip inline secrets, and remain idempotent.+- On every startup after migration, short-circuit when `usr/plugins/_model_config/presets.yaml` exists. Only a missing collection may fetch `agent0ai/a0-presets`; parse remote and plugin-local fallback YAML through the same validator, strip secrets before persistence, and persist `mode_presets_fallback.yaml` when download or validation fails.- Model-name catalogs open below the input from either a field click or the embedded magnifier.## Work Guidancediff --git a/plugins/_model_config/README.md b/plugins/_model_config/README.mdindex 61274b2d4..12b3d122d 100644--- a/plugins/_model_config/README.md+++ b/plugins/_model_config/README.md@@ -1,86 +1,58 @@# Model Configuration-Manage which models Agent Zero uses for chat, utility, and embeddings, with support for scoped overrides and reusable presets.+Manage the reusable model presets used for Agent Zero's main, utility, and embedding models.-## What It Does+## Model Presets-This plugin centralizes model selection and model-related settings for the application. It provides helpers and APIs for:+- `Default` is always present, appears first, and cannot be renamed or deleted.+- Every runtime configuration resolves from a preset. There is no separate durable model configuration layer.+- Preset definitions are global and live in `usr/plugins/_model_config/presets.yaml`. Plugin defaults in `mode_presets_fallback.yaml` are used only when a saved collection cannot be initialized.+- Non-default presets may omit advanced fields or model slots; omitted values resolve from `Default`, while provider-specific `kwargs` are replaced or cleared instead of leaking between providers.+- API keys remain in the approved environment/settings flow and are never written into preset YAML.-- selecting chat, utility, and embedding models-- reading and saving model presets-- checking for missing API keys-- allowing optional per-chat model overrides-- resolving config at global, project, agent, and chat scope+## Scoped Selection-## Main Behavior+Global, project, project/profile, and agent-profile scopes store only a preset name in their standard plugin `config.json`:-- **Scoped configuration**- - Reads plugin config through the standard plugin config system with project and agent overrides.-- **Preset management**- - Loads presets from a user file when present and falls back to bundled defaults.- - Project presets can be stored beside a project's scoped model config.-- **Per-chat override**- - Allows a chat context to store a temporary override or preset reference in context data.-- **Model object construction**- - Builds `ModelConfig` objects and the runtime chat, utility, and embedding wrappers used elsewhere in the app.-- **API key validation**- - Reports configured providers that still require API keys.+```json+{"model_preset": "Balance"}+```-## Key Files+For example, a project selection is stored at:-- **Core helper**- - `helpers/model_config.py` resolves config, presets, overrides, and runtime model objects.-- **APIs**- - `api/model_config_get.py`- - `api/model_config_set.py`- - `api/model_override.py`- - `api/model_presets.py`- - `api/model_search.py`- - `api/api_keys.py`-- **Hooks**- - `hooks.py` exposes plugin-level integration hooks.+```text+/a0/usr/projects/<project>/.a0proj/plugins/_model_config/config.json+```-## Configuration Scope+The normal plugin resolution order selects the most specific available reference. A missing or deleted reference safely resolves to `Default`. Chats may store an explicit preset reference in `chat_model_override`; clearing it returns the chat to its scoped selection.-- **Settings section**: `agent`-- **Per-project config**: `true`-- **Per-agent config**: `true`-- **Always enabled**: `true`+## User Interfaces-## Project-Scoped Model Config+- Agent Settings shows the global selection, its three resolved models, and actions for preset editing, API keys, and per-project/agent settings.+- The full plugin settings modal uses the generic scope selector and stores only the chosen preset at that scope.+- The closed chat switcher shows the effective preset plus the main model's short name; its menu supports a chat-only selection or returning to the scoped preset.+- The preset editor exposes the shared API key for each selected provider and saves key changes separately from secret-free preset definitions.+- Project Settings selects from the same global preset definitions.-Projects store copied model settings in the standard scoped plugin path:+## Initial Presets And Migration-```text-/a0/usr/projects/<project>/.a0proj/plugins/_model_config/config.json-```--Project-only presets live beside that config:+The startup migration converts the prior global full model configuration into `Default`, preserves existing global presets, promotes distinct scoped full configurations and legacy project presets into uniquely named global presets, and rewrites scoped config files to selection-only JSON. Original files receive a `.pre-unified-presets.bak` backup before replacement; the migration is idempotent.-```text-/a0/usr/projects/<project>/.a0proj/plugins/_model_config/presets.yaml-```+At every startup, legacy migration runs first. If `usr/plugins/_model_config/presets.yaml` then exists, initialization returns immediately without network access. Otherwise the plugin makes one bounded request for [`agent0ai/a0-presets/model_presets.yaml`](https://github.com/agent0ai/a0-presets/blob/main/model_presets.yaml), validates the whole collection, removes secret fields, and saves it locally. A download, parse, or validation failure processes and saves plugin-local `mode_presets_fallback.yaml` through the same validation path, so initialization remains usable offline.-The project preset file uses the same plain YAML list schema as global presets. It does not contain scope metadata:--```yaml-- name: Research- chat:- provider: openrouter- name: anthropic/claude-sonnet-5- api_base: ""- ctx_length: 200000- ctx_history: 0.7- vision: true- utility:- provider: openrouter- name: openai/gpt-5.4-mini-```+## Key Files-Preset slots are partial overlays. Missing fields inherit from the current effective config, so a preset can switch only the model identity while preserving tuned context windows and rate limits. Provider-specific `kwargs` are replaced or cleared. The `utility` and `embedding` slots are optional and only apply when they declare a provider or model name; otherwise those configured models are inherited. Selecting a preset for a project writes the merged result into the project's `config.json`.+- `helpers/model_config.py` owns preset validation, resolution, compatibility config shapes, and runtime model construction.+- `api/model_presets.py` owns global preset editing, scoped selection, and reference repair after rename/delete/reset.+- `extensions/python/startup_migration/_10_migrate_model_config.py` owns legacy conversion.+- `extensions/python/startup_migration/_20_bootstrap_model_presets.py` owns missing-collection initialization and plugin-local fallback.+- `webui/preset-overview.html` is the shared Settings/plugin-settings summary widget.+- `webui/main.html` is the preset editor.## Plugin Metadata-- **Name**: `_model_config`-- **Title**: `Model Configuration`-- **Description**: Manages LLM model selection and configuration for chat, utility, and embedding models. Supports per-project and per-agent overrides with optional per-chat model switching.+- Name: `_model_config`+- Settings section: `agent`+- Per-project config: `true`+- Per-agent config: `true`+- Always enabled: `true`diff --git a/plugins/_model_config/api/model_config_get.py b/plugins/_model_config/api/model_config_get.pyindex 1dce9e7f4..7a02a3d98 100644--- a/plugins/_model_config/api/model_config_get.py+++ b/plugins/_model_config/api/model_config_get.py@@ -1,7 +1,7 @@from helpers.api import ApiHandler, Request, Response-from helpers import pluginsfrom helpers.providers import get_raw_providersfrom plugins._model_config.helpers import model_config+from agent import AgentContextimport models@@ -9,15 +9,27 @@ class ModelConfigGet(ApiHandler):async def process(self, input: dict, request: Request) -> dict | Response:project_name = input.get("project_name", "")agent_profile = input.get("agent_profile", "")+ context_id = str(input.get("context_id") or "").strip()+ context = AgentContext.get(context_id) if context_id else None+ agent = context.agent0 if context else None- config = model_config.get_config(- project_name=project_name or None,- agent_profile=agent_profile or None,- )-- # Provide default if no config found- if not config:- config = plugins.get_default_plugin_config("_model_config") or {}+ if agent:+ config = model_config.get_effective_config(agent)+ configured_preset = model_config.get_configured_preset_name(agent=agent)+ selected_preset = model_config.get_effective_preset_name(agent)+ else:+ config = model_config.get_config(+ project_name=project_name or None,+ agent_profile=agent_profile or None,+ )+ configured_preset = model_config.get_configured_preset_name(+ project_name=project_name or None,+ agent_profile=agent_profile or None,+ )+ selected_preset = str(+ config.get(model_config.MODEL_PRESET_CONFIG_KEY)+ or model_config.DEFAULT_PRESET_NAME+ )# Add provider lists for UI dropdownschat_providers = model_config.get_chat_providers()@@ -51,4 +63,7 @@ class ModelConfigGet(ApiHandler):"model_configured_label": " / ".join(part for part in (chat_provider, chat_name) if part),+ "presets": model_config.get_presets(),+ "configured_preset": configured_preset,+ "selected_preset": selected_preset,}diff --git a/plugins/_model_config/api/model_config_set.py b/plugins/_model_config/api/model_config_set.pyindex cabaf300a..a7b38e0b7 100644--- a/plugins/_model_config/api/model_config_set.py+++ b/plugins/_model_config/api/model_config_set.py@@ -1,8 +1,9 @@from copy import deepcopyfrom helpers.api import ApiHandler, Request, Response-from helpers import plugins, defer, dotenv+from helpers import defer, dotenvfrom helpers.extension import call_extensions_async+from plugins._model_config.helpers import model_configAPI_KEY_PLACEHOLDER = "************"@@ -32,18 +33,39 @@ class ModelConfigSet(ApiHandler):dotenv.save_dotenv_value(f"API_KEY_{provider.upper()}", api_key)section.pop("api_key", None)- # Read previous config BEFORE saving so we can detect changes- prev_config = plugins.get_plugin_config(- "_model_config",- project_name=project_name or None,- agent_profile=agent_profile or None,- ) or {}+ preset_name = str(+ input.get("preset_name")+ or config_to_save.get(model_config.MODEL_PRESET_CONFIG_KEY)+ or model_config.get_configured_preset_name(+ project_name=project_name or None,+ agent_profile=agent_profile or None,+ )+ ).strip()+ preset = model_config.resolve_preset(preset_name)+ if not preset:+ return Response(status=404, response=f"Preset '{preset_name}' not found")+ preset_name = str(preset.get("name") or model_config.DEFAULT_PRESET_NAME)++ # Read the preset before saving so embedding changes can still trigger+ # the established re-index notification.+ prev_config = model_config.resolve_config_settings(+ {model_config.MODEL_PRESET_CONFIG_KEY: preset_name}+ )++ try:+ model_config.update_preset_from_config(preset_name, config_to_save)+ except ValueError as exc:+ return Response(status=400, response=str(exc))++ # Keep the requested scope pointed at the preset being edited. This is+ # selection-only persistence; model dictionaries live in presets.yaml.+ from helpers import pluginsplugins.save_plugin_config("_model_config",- project_name=project_name,- agent_profile=agent_profile,- settings=config_to_save,+ project_name=project_name or None,+ agent_profile=agent_profile or None,+ settings={model_config.MODEL_PRESET_CONFIG_KEY: preset_name},)# Check if embedding model changed and notify@@ -58,4 +80,4 @@ class ModelConfigSet(ApiHandler):call_extensions_async, "embedding_model_changed")- return {"ok": True}+ return {"ok": True, "preset_name": preset_name}diff --git a/plugins/_model_config/api/model_override.py b/plugins/_model_config/api/model_override.pyindex 663c4adbd..55840b7ac 100644--- a/plugins/_model_config/api/model_override.py+++ b/plugins/_model_config/api/model_override.py@@ -1,6 +1,8 @@import timefrom helpers.api import ApiHandler, Request, Response+from helpers import defer+from helpers.extension import call_extensions_asyncfrom helpers.persist_chat import save_tmp_chatfrom agent import AgentContextfrom plugins._model_config.helpers import model_config@@ -19,6 +21,11 @@ def _notify_model_override_changed(ctx: AgentContext) -> None:pass+def _notify_embedding_if_changed(before: dict, after: dict) -> None:+ if before != after:+ defer.DeferredTask().start_task(call_extensions_async, "embedding_model_changed")++class ModelOverride(ApiHandler):async def process(self, input: dict, request: Request) -> dict | Response:context_id = input.get("context_id", "")@@ -34,7 +41,12 @@ class ModelOverride(ApiHandler):if action == "get":override = ctx.get_data("chat_model_override")allowed = model_config.is_chat_override_allowed(ctx.agent0)- return {"override": override, "allowed": allowed}+ return {+ "override": override,+ "allowed": allowed,+ "configured_preset": model_config.get_configured_preset_name(agent=ctx.agent0),+ "effective_preset": model_config.get_effective_preset_name(ctx.agent0),+ }elif action == "set":if not model_config.is_chat_override_allowed(ctx.agent0):@@ -42,9 +54,14 @@ class ModelOverride(ApiHandler):override_config = input.get("override")if not override_config or not isinstance(override_config, dict):return Response(status=400, response="Missing or invalid override config")+ previous_embedding = model_config.get_embedding_model_config(ctx.agent0)ctx.set_data("chat_model_override", override_config)save_tmp_chat(ctx)_notify_model_override_changed(ctx)+ _notify_embedding_if_changed(+ previous_embedding,+ model_config.get_embedding_model_config(ctx.agent0),+ )return {"ok": True, "override": override_config}elif action == "set_preset":@@ -53,21 +70,36 @@ class ModelOverride(ApiHandler):preset_name = input.get("preset_name", "")if not preset_name:return Response(status=400, response="Missing preset_name")+ previous_embedding = model_config.get_embedding_model_config(ctx.agent0)# Verify preset existspreset = model_config.get_preset_by_name(preset_name)if not preset:return Response(status=404, response=f"Preset '{preset_name}' not found")# Store as a preset reference- override_value = {"preset_name": preset_name}+ canonical_name = str(preset.get("name") or preset_name)+ override_value = {"preset_name": canonical_name}ctx.set_data("chat_model_override", override_value)save_tmp_chat(ctx)_notify_model_override_changed(ctx)- return {"ok": True, "preset_name": preset_name}+ _notify_embedding_if_changed(+ previous_embedding,+ model_config.get_embedding_model_config(ctx.agent0),+ )+ return {"ok": True, "preset_name": canonical_name}elif action == "clear":+ previous_embedding = model_config.get_embedding_model_config(ctx.agent0)ctx.set_data("chat_model_override", None)save_tmp_chat(ctx)_notify_model_override_changed(ctx)- return {"ok": True, "override": None}+ _notify_embedding_if_changed(+ previous_embedding,+ model_config.get_embedding_model_config(ctx.agent0),+ )+ return {+ "ok": True,+ "override": None,+ "effective_preset": model_config.get_configured_preset_name(agent=ctx.agent0),+ }return Response(status=400, response=f"Unknown action: {action}")diff --git a/plugins/_model_config/api/model_presets.py b/plugins/_model_config/api/model_presets.pyindex a63477560..6c994ddd8 100644--- a/plugins/_model_config/api/model_presets.py+++ b/plugins/_model_config/api/model_presets.py@@ -1,66 +1,262 @@+import json+from helpers.api import ApiHandler, Request, Response+from helpers import defer, files, plugins+from helpers.extension import call_extensions_async+from helpers.persist_chat import _write_atomic, save_tmp_chat+from agent import AgentContext+from plugins._model_config.api.model_override import _notify_model_override_changedfrom plugins._model_config.helpers import model_config+def _rename_preset_references(renames: object) -> None:+ if not isinstance(renames, list):+ return+ mapping = {+ str(item.get("from") or "").strip().casefold(): str(item.get("to") or "").strip()+ for item in renames+ if isinstance(item, dict)+ and str(item.get("from") or "").strip()+ and str(item.get("to") or "").strip()+ }+ mapping.pop(model_config.DEFAULT_PRESET_NAME.casefold(), None)+ if not mapping:+ return++ assets = plugins.find_plugin_assets(+ plugins.CONFIG_FILE_NAME,+ plugin_name="_model_config",+ project_name="*",+ agent_profile="*",+ only_first=False,+ )+ for asset in assets:+ path = str(asset.get("path") or "")+ try:+ config = json.loads(files.read_file(path))+ except Exception:+ continue+ if not isinstance(config, dict):+ continue+ selected = str(config.get(model_config.MODEL_PRESET_CONFIG_KEY) or "").strip()+ replacement = mapping.get(selected.casefold())+ if replacement:+ config[model_config.MODEL_PRESET_CONFIG_KEY] = replacement+ files.write_file(path, json.dumps(config))++ # Chats are lazy-loaded, so update durable references as well as live+ # AgentContext objects. Otherwise renaming a preset would silently send an+ # unopened chat back to Default the next time it is loaded.+ loaded_context_ids = {str(context.id) for context in AgentContext.all()}+ chat_paths = files.find_existing_paths_by_pattern(+ files.get_abs_path("usr", "chats", "*", "chat.json")+ )+ for path in chat_paths:+ chat_id = files.basename(files.dirname(path))+ if chat_id in loaded_context_ids:+ continue+ try:+ chat = json.loads(files.read_file(path))+ except Exception:+ continue+ data = chat.get("data") if isinstance(chat, dict) else None+ override = data.get("chat_model_override") if isinstance(data, dict) else None+ selected = str(override.get("preset_name") or "").strip() if isinstance(override, dict) else ""+ replacement = mapping.get(selected.casefold())+ if not replacement:+ continue+ data["chat_model_override"] = {"preset_name": replacement}+ _write_atomic(path, json.dumps(chat, ensure_ascii=False))++ for context in AgentContext.all():+ override = context.get_data("chat_model_override")+ if not isinstance(override, dict):+ continue+ selected = str(override.get("preset_name") or "").strip()+ replacement = mapping.get(selected.casefold())+ if not replacement:+ continue+ context.set_data("chat_model_override", {"preset_name": replacement})+ save_tmp_chat(context)+ _notify_model_override_changed(context)+++def _retired_preset_references(+ previous_names: set[str],+ saved_names: set[str],+) -> list[dict[str, str]]:+ saved_by_casefold = {name.casefold(): name for name in saved_names}+ return [+ {+ "from": name,+ "to": saved_by_casefold.get(+ name.casefold(),+ model_config.DEFAULT_PRESET_NAME,+ ),+ }+ for name in previous_names - saved_names+ ]+++def _embedding_signature(preset: dict | None):+ if not isinstance(preset, dict):+ return {}+ default = model_config.resolve_preset(model_config.DEFAULT_PRESET_NAME) or {}+ config = model_config.preset_to_config(default)+ if str(preset.get("name") or "") != model_config.DEFAULT_PRESET_NAME:+ config = model_config.build_config_from_preset(+ preset,+ config,+ strip_api_key=False,+ )+ embedding = config.get("embedding_model")+ return embedding if isinstance(embedding, dict) else {}+++def _notify_embedding_changed() -> None:+ defer.DeferredTask().start_task(call_extensions_async, "embedding_model_changed")++class ModelPresets(ApiHandler):async def process(self, input: dict, request: Request) -> dict | Response:action = input.get("action", "get")project_name = str(input.get("project_name") or "").strip()+ agent_profile = str(input.get("agent_profile") or "").strip()+ context_id = str(input.get("context_id") or "").strip()scope = str(input.get("scope") or "").strip()if action == "get":if scope == "project":- presets = model_config.get_project_presets(project_name) if project_name else []- return {"ok": True, "presets": presets}-- if scope == "combined" or project_name:- return {- "ok": True,- "presets": model_config.get_combined_presets(project_name or None),- "global_presets": model_config.get_presets(),- "project_presets": (- model_config.get_project_presets(project_name)- if project_name- else []- ),- }-+ return {"ok": True, "presets": []}presets = model_config.get_presets()- return {"ok": True, "presets": presets}+ context = AgentContext.get(context_id) if context_id else None+ if context:+ configured = model_config.get_configured_preset_name(agent=context.agent0)+ selected = model_config.get_effective_preset_name(context.agent0)+ else:+ configured = model_config.get_configured_preset_name(+ project_name=project_name or None,+ agent_profile=agent_profile or None,+ )+ selected = configured+ return {+ "ok": True,+ "presets": presets,+ "global_presets": presets,+ "project_presets": [],+ "configured_preset": configured,+ "selected_preset": selected,+ }elif action == "save":presets = input.get("presets")if not isinstance(presets, list):return Response(status=400, response="presets must be an array")- model_config.save_presets(- presets,- project_name=project_name if scope == "project" or project_name else None,- )- return {"ok": True, "presets": model_config.clean_presets_for_file(presets)}+ if scope == "project" or project_name:+ return Response(+ status=400,+ response="Preset definitions are global; select a global preset for this project.",+ )+ previous_names = {+ str(preset.get("name") or "") for preset in model_config.get_presets()+ }+ previous_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in model_config.get_presets()+ }+ try:+ model_config.save_presets(presets)+ except ValueError as exc:+ return Response(status=400, response=str(exc))+ saved_names = {+ str(preset.get("name") or "") for preset in model_config.get_presets()+ }+ retired = _retired_preset_references(previous_names, saved_names)+ renames = input.get("renames") if isinstance(input.get("renames"), list) else []+ _rename_preset_references([*retired, *renames])+ saved_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in model_config.get_presets()+ }+ if previous_embeddings != saved_embeddings:+ _notify_embedding_changed()+ return {"ok": True, "presets": model_config.get_presets()}elif action == "reset":- presets = model_config.reset_presets(- project_name=project_name if scope == "project" or project_name else None- )+ if scope == "project" or project_name:+ return Response(status=400, response="Project presets cannot be reset.")+ previous = model_config.get_presets()+ previous_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in previous+ }+ presets = model_config.reset_presets()+ saved_names = {str(preset.get("name") or "") for preset in presets}+ previous_names = {str(preset.get("name") or "") for preset in previous}+ retired = _retired_preset_references(previous_names, saved_names)+ _rename_preset_references(retired)+ current_embeddings = {+ str(preset.get("name") or ""): _embedding_signature(preset)+ for preset in presets+ }+ if previous_embeddings != current_embeddings:+ _notify_embedding_changed()return {"ok": True, "presets": presets}+ elif action == "select":+ name = str(input.get("name") or "").strip()+ preset = model_config.resolve_preset(name)+ if not preset:+ return Response(status=404, response=f"Preset '{name}' not found")+ canonical_name = str(preset.get("name") or model_config.DEFAULT_PRESET_NAME)+ context = AgentContext.get(context_id) if context_id else None+ previous_embedding = (+ model_config.get_embedding_model_config(context.agent0)+ if context+ else None+ )+ previous_name = (+ model_config.get_effective_preset_name(context.agent0)+ if context+ else model_config.get_configured_preset_name(+ project_name=project_name or None,+ agent_profile=agent_profile or None,+ )+ )+ previous = model_config.resolve_preset(previous_name)+ plugins.save_plugin_config(+ "_model_config",+ project_name,+ agent_profile,+ {model_config.MODEL_PRESET_CONFIG_KEY: canonical_name},+ )++ if context:+ context.set_data("chat_model_override", {"preset_name": canonical_name})+ save_tmp_chat(context)+ _notify_model_override_changed(context)+ current_embedding = (+ model_config.get_embedding_model_config(context.agent0)+ if context+ else _embedding_signature(preset)+ )+ if (previous_embedding or _embedding_signature(previous)) != current_embedding:+ _notify_embedding_changed()+ return {"ok": True, "selected_preset": canonical_name}+elif action == "resolve":name = str(input.get("name") or "").strip()if not name:return Response(status=400, response="Missing preset name")- resolved = model_config.resolve_preset(- name,- scope=scope or "global",- project_name=project_name or None,- )+ resolved = model_config.resolve_preset(name)if not resolved:return Response(status=404, response=f"Preset '{name}' not found")return {"ok": True,"preset": {**resolved,- "scope": scope or "global",- "project_name": project_name if scope == "project" else "",+ "scope": "global",+ "project_name": "",},}diff --git a/plugins/_model_config/default_config.yaml b/plugins/_model_config/default_config.yamlindex 8a65f0445..b1ed706f2 100644--- a/plugins/_model_config/default_config.yaml+++ b/plugins/_model_config/default_config.yaml@@ -1,33 +1 @@-allow_chat_override: true--chat_model:- provider: "openrouter"- name: "openai/gpt-5.6-terra"- api_base: ""- ctx_length: 200000- ctx_history: 0.7- vision: true- max_embeds: 10- rl_requests: 0- rl_input: 0- rl_output: 0- kwargs: {}--utility_model:- provider: "openrouter"- name: "google/gemini-3.1-flash-lite"- api_base: ""- ctx_length: 128000- ctx_input: 0.7- rl_requests: 0- rl_input: 0- rl_output: 0- kwargs: {}--embedding_model:- provider: "huggingface"- name: "sentence-transformers/all-MiniLM-L6-v2"- api_base: ""- rl_requests: 0- rl_input: 0- kwargs: {}+model_preset: "Default"diff --git a/plugins/_model_config/default_presets.yaml b/plugins/_model_config/default_presets.yamldeleted file mode 100644index c49f45c36..000000000--- a/plugins/_model_config/default_presets.yaml+++ /dev/null@@ -1,36 +0,0 @@-- name: "Max Power"- chat:- provider: "openrouter"- name: "anthropic/claude-opus-4.6"- api_key: ""- api_base: ""- ctx_length: 200000- ctx_history: 0.7- vision: true- utility:- provider: "openrouter"- name: "openai/gpt-5.4-mini"-- name: "Balance"- chat:- provider: "openrouter"- name: "openai/gpt-5.6-terra"- api_key: ""- api_base: ""- ctx_length: 200000- ctx_history: 0.7- vision: true- utility:- provider: "openrouter"- name: "google/gemini-3.1-flash-lite"-- name: "Cost Efficient"- chat:- provider: "openrouter"- name: "moonshotai/kimi-k2.5"- api_key: ""- api_base: ""- ctx_length: 128000- ctx_history: 0.7- vision: false- utility:- provider: "openrouter"- name: "openai/gpt-5.4-nano"diff --git a/plugins/_model_config/extensions/python/banners/_20_missing_api_key.py b/plugins/_model_config/extensions/python/banners/_20_missing_api_key.pyindex 4bc8002d2..cf7c589e3 100644--- a/plugins/_model_config/extensions/python/banners/_20_missing_api_key.py+++ b/plugins/_model_config/extensions/python/banners/_20_missing_api_key.py@@ -1,5 +1,4 @@from helpers.extension import Extension-from helpers import pluginsfrom plugins._model_config.helpers import model_config@@ -11,7 +10,6 @@ class MissingApiKeyCheck(Extension):ONBOARDING_CTA_TEXT = "Start Onboarding"async def execute(self, banners: list = [], frontend_context: dict = {}, **kwargs):- cfg = plugins.get_plugin_config("_model_config") or {}missing_providers = model_config.get_missing_api_key_providers()if missing_providers:@@ -31,40 +29,48 @@ class MissingApiKeyCheck(Extension):})# Check preset providers for missing API keys (warning level)- if cfg.get("allow_chat_override"):- preset_missing = []- seen = set()- for preset in cfg.get("model_presets", []):- preset_name = preset.get("name", "Unnamed")- for slot_key, slot_label in [("chat", "Main"), ("utility", "Utility")]:- slot = preset.get(slot_key, {})- provider = slot.get("provider", "")- if not provider:- continue- provider_lower = provider.lower()- if provider_lower in self.LOCAL_PROVIDERS:- continue- # Skip if already covered by default checks- if provider_lower in seen:- continue- # Skip if preset has its own api_key- if slot.get("api_key", "").strip():- continue- if not model_config.has_provider_api_key(provider_lower):- seen.add(provider_lower)- preset_missing.append(f"{preset_name}/{slot_label} ({provider})")+ preset_missing = []+ seen = set()+ for preset in model_config.get_presets():+ preset_name = preset.get("name", "Unnamed")+ for slot_key, slot_label, model_type in [+ ("chat", "Main", "chat"),+ ("utility", "Utility", "chat"),+ ("embedding", "Embedding", "embedding"),+ ]:+ slot = preset.get(slot_key, {})+ provider = slot.get("provider", "")+ if not provider:+ continue+ provider_lower = provider.lower()+ identity = (provider_lower, model_type)+ if (+ provider_lower in self.LOCAL_PROVIDERS+ or model_type == "embedding"+ and provider_lower in model_config.LOCAL_EMBEDDING+ or identity in seen+ ):+ continue+ if slot.get("api_key", "").strip():+ continue+ if not model_config.has_provider_api_key(+ provider_lower,+ model_type=model_type,+ ):+ seen.add(identity)+ preset_missing.append(f"{preset_name}/{slot_label} ({provider})")- if preset_missing:- preset_list = ", ".join(preset_missing)- banners.append({- "id": "missing-preset-api-key",- "type": "warning",- "priority": 90,- "title": "Missing API Key for model presets",- "html": f"""No API key configured for preset models: {preset_list}.<br>- These presets will not work until you provide the required API keys.""",- "cta_text": self.ONBOARDING_CTA_TEXT,- "cta_action": f"open-modal:{self.ONBOARDING_MODAL_PATH}",- "dismissible": True,- "source": "backend"- })+ if preset_missing:+ preset_list = ", ".join(preset_missing)+ banners.append({+ "id": "missing-preset-api-key",+ "type": "warning",+ "priority": 90,+ "title": "Missing API Key for model presets",+ "html": f"""No API key configured for preset models: {preset_list}.<br>+ These presets will not work until you provide the required API keys.""",+ "cta_text": self.ONBOARDING_CTA_TEXT,+ "cta_action": f"open-modal:{self.ONBOARDING_MODAL_PATH}",+ "dismissible": True,+ "source": "backend"+ })diff --git a/plugins/_model_config/extensions/python/startup_migration/_10_migrate_model_config.py b/plugins/_model_config/extensions/python/startup_migration/_10_migrate_model_config.pyindex a00c6fe79..7e2b2f5dc 100644--- a/plugins/_model_config/extensions/python/startup_migration/_10_migrate_model_config.py+++ b/plugins/_model_config/extensions/python/startup_migration/_10_migrate_model_config.py@@ -5,14 +5,11 @@ from copy import deepcopyfrom helpers.extension import Extensionfrom helpers import files, plugins, yaml as yaml_helperfrom helpers.print_style import PrintStyle+from plugins._model_config.helpers import model_configclass MigrateModelConfig(Extension):- """- One-time migration: copy legacy model settings into _model_config plugin config.- Runs during initialize_migration. Only migrates if no global plugin config exists yet- and the settings file contains legacy model fields.- """+ """Migrate every legacy full model config to unified global presets."""LEGACY_FIELDS = ["chat_model_provider", "chat_model_name", "chat_model_api_base",@@ -31,39 +28,43 @@ class MigrateModelConfig(Extension):]CONFIG_SECTIONS = ("chat_model", "utility_model", "embedding_model")PRESET_SECTIONS = ("chat", "utility", "embedding")+ BACKUP_SUFFIX = ".pre-unified-presets.bak"VENICE_KWARGS = {"a0_api_mode": "chat","venice_parameters": {"include_venice_system_prompt": False},}def execute(self, **kwargs):- self._repair_saved_venice_config()+ self._create_global_config_from_legacy_settings()+ changed = self._migrate_saved_configs_and_presets()+ if changed:+ PrintStyle(+ background_color="#6734C3",+ font_color="white",+ padding=True,+ ).print("Migrated model configuration to unified model presets.")- # Check if global plugin config already exists+ def _create_global_config_from_legacy_settings(self) -> None:global_config_path = files.get_abs_path(- files.USER_DIR, files.PLUGINS_DIR, "_model_config", plugins.CONFIG_FILE_NAME+ files.USER_DIR,+ files.PLUGINS_DIR,+ "_model_config",+ plugins.CONFIG_FILE_NAME,)if os.path.exists(global_config_path):- return # already migrated or manually configured+ return- # Read raw settings file to check for legacy model fieldssettings_file = files.get_abs_path("usr/settings.json")if not os.path.exists(settings_file):return-try:raw = json.loads(files.read_file(settings_file))except Exception:return-- # Check if any legacy model field exists in the raw settings- has_legacy = any(field in raw for field in self.LEGACY_FIELDS)- if not has_legacy:+ if not isinstance(raw, dict) or not any(field in raw for field in self.LEGACY_FIELDS):return- # Build plugin config from legacy settings- plugin_config = {- "allow_chat_override": False,+ config = {"chat_model": {"provider": raw.get("chat_model_provider", "openrouter"),"name": raw.get("chat_model_name", ""),@@ -89,59 +90,286 @@ class MigrateModelConfig(Extension):},"embedding_model": {"provider": raw.get("embed_model_provider", "huggingface"),- "name": raw.get("embed_model_name", "sentence-transformers/all-MiniLM-L6-v2"),+ "name": raw.get(+ "embed_model_name",+ "sentence-transformers/all-MiniLM-L6-v2",+ ),"api_base": raw.get("embed_model_api_base", ""),"rl_requests": raw.get("embed_model_rl_requests", 0),"rl_input": raw.get("embed_model_rl_input", 0),"kwargs": raw.get("embed_model_kwargs", {}),},}+ for section in self.CONFIG_SECTIONS:+ if not isinstance(config[section].get("kwargs"), dict):+ config[section]["kwargs"] = {}+ files.write_file(global_config_path, json.dumps(config))- # Ensure kwargs are dicts (might be strings from .env format)- for section in ["chat_model", "utility_model", "embedding_model"]:- kw = plugin_config[section].get("kwargs")- if isinstance(kw, str):- plugin_config[section]["kwargs"] = {}-- self._repair_venice_config_slots(plugin_config)-- # Save as global plugin config- plugins.save_plugin_config("_model_config", "", "", plugin_config)- PrintStyle(background_color="#6734C3", font_color="white", padding=True).print(- "Migrated legacy model settings to _model_config plugin config."+ def _migrate_saved_configs_and_presets(self) -> bool:+ config_assets = plugins.find_plugin_assets(+ plugins.CONFIG_FILE_NAME,+ plugin_name="_model_config",+ project_name="*",+ agent_profile="*",+ only_first=False,)-- def _repair_saved_venice_config(self):- changed = False- config_path = files.get_abs_path(- files.USER_DIR, files.PLUGINS_DIR, "_model_config", plugins.CONFIG_FILE_NAME+ config_assets.sort(+ key=lambda item: bool(item.get("project_name") or item.get("agent_profile")))- presets_path = files.get_abs_path(- files.USER_DIR, files.PLUGINS_DIR, "_model_config", "presets.yaml"++ presets_path = model_config._get_presets_path()+ saved_presets = self._read_yaml_list(presets_path)+ presets = self._normalize_preset_collection(model_config.get_presets())+ changed = (+ os.path.exists(presets_path)+ and (+ saved_presets is None+ or saved_presets != model_config.clean_presets_for_file(presets)+ ))+ for preset in presets:+ changed = self._repair_venice_preset(preset) or changed- if os.path.exists(config_path):- try:- config = json.loads(files.read_file(config_path))- except Exception:- config = None- if isinstance(config, dict) and self._repair_venice_config_slots(config):- files.write_file(config_path, json.dumps(config))+ config_updates: list[tuple[str, str]] = []+ for asset in config_assets:+ path = str(asset.get("path") or "")+ if not path:+ continue+ raw = self._read_json_dict(path)+ if raw is None:+ config_updates.append((path, model_config.DEFAULT_PRESET_NAME))changed = True+ continue- if os.path.exists(presets_path):+ label = self._scope_label(asset)+ embedded_presets = raw.get("model_presets")+ if isinstance(embedded_presets, list):+ changed = self._merge_presets(presets, embedded_presets, label) or changed++ if any(section in raw for section in self.CONFIG_SECTIONS):+ self._repair_venice_config_slots(raw)+ if not asset.get("project_name") and not asset.get("agent_profile"):+ replacement = model_config.config_to_preset(+ raw,+ model_config.DEFAULT_PRESET_NAME,+ )+ current_default = self._preset_by_name(+ presets,+ model_config.DEFAULT_PRESET_NAME,+ ) or {}+ for slot in self.PRESET_SECTIONS:+ if not self._slot_has_identity(replacement.get(slot)):+ fallback = current_default.get(slot)+ if isinstance(fallback, dict):+ replacement[slot] = deepcopy(fallback)+ self._replace_default(presets, replacement)+ selected_name = model_config.DEFAULT_PRESET_NAME+ else:+ candidate = model_config.config_to_preset(raw, label)+ selected_name = self._find_matching_name(presets, candidate)+ if not selected_name:+ candidate["name"] = self._unique_name(presets, label)+ presets.append(candidate)+ selected_name = candidate["name"]+ config_updates.append((path, selected_name))+ changed = True+ continue++ selected = str(+ raw.get(model_config.MODEL_PRESET_CONFIG_KEY)+ or model_config.DEFAULT_PRESET_NAME+ ).strip()+ resolved = self._preset_by_name(presets, selected)+ canonical = (+ str(resolved.get("name"))+ if resolved+ else model_config.DEFAULT_PRESET_NAME+ )+ normalized = {model_config.MODEL_PRESET_CONFIG_KEY: canonical}+ if raw != normalized:+ config_updates.append((path, canonical))+ changed = True++ retired_project_preset_paths = self._collect_project_presets(presets)+ changed = bool(retired_project_preset_paths) or changed+ if not changed:+ return False++ presets = model_config.validate_presets(+ self._normalize_preset_collection(presets)+ )+ self._backup(presets_path)+ files.write_file(presets_path, yaml_helper.dumps(presets))++ for path, selected_name in config_updates:+ self._backup(path)+ files.write_file(+ path,+ json.dumps({model_config.MODEL_PRESET_CONFIG_KEY: selected_name}),+ )+ for path in retired_project_preset_paths:+ self._backup(path)+ if os.path.exists(path):+ os.remove(path)+ return True++ def _collect_project_presets(self, presets: list) -> list[str]:+ assets = plugins.find_plugin_assets(+ model_config.PRESETS_FILE,+ plugin_name="_model_config",+ project_name="*",+ agent_profile="*",+ only_first=False,+ )+ global_path = model_config._get_presets_path()+ retired_paths: list[str] = []+ for asset in assets:+ path = str(asset.get("path") or "")+ if not path or path == global_path:+ continuetry:- presets = yaml_helper.loads(files.read_file(presets_path))+ legacy = yaml_helper.loads(files.read_file(path))except Exception:- presets = None- if isinstance(presets, list) and self._repair_venice_presets(presets):- files.write_file(presets_path, yaml_helper.dumps(presets))- changed = True+ legacy = None+ if isinstance(legacy, list):+ self._merge_presets(+ presets,+ legacy,+ self._scope_label(asset),+ )+ retired_paths.append(path)+ return retired_paths- if changed:- PrintStyle(background_color="#6734C3", font_color="white", padding=True).print(- "Updated saved Venice model settings for chat completions."+ def _merge_presets(self, presets: list, incoming: list, scope_label: str) -> bool:+ changed = False+ for raw in incoming:+ if not isinstance(raw, dict):+ continue+ candidate = deepcopy(raw)+ self._repair_venice_preset(candidate)+ requested_name = str(candidate.get("name") or "").strip()+ if not requested_name:+ continue+ candidate["name"] = requested_name+ matching = self._find_matching_name(presets, candidate)+ if matching:+ continue+ if self._preset_by_name(presets, requested_name):+ candidate["name"] = self._unique_name(+ presets,+ f"{scope_label} · {requested_name}",+ )+ presets.append(candidate)+ changed = True+ return changed++ def _normalize_preset_collection(self, presets: list) -> list:+ """Preserve malformed legacy entries by canonicalizing or uniquely renaming them."""+ normalized: list[dict] = []+ for raw in presets:+ if not isinstance(raw, dict):+ continue+ candidate = model_config._clean_preset_for_file(raw)+ name = str(candidate.get("name") or "").strip()+ if not name:+ continue+ candidate["name"] = (+ model_config.DEFAULT_PRESET_NAME+ if name.casefold() == model_config.DEFAULT_PRESET_NAME.casefold()+ else name)+ existing = self._preset_by_name(normalized, candidate["name"])+ if existing:+ if self._preset_signature(existing) == self._preset_signature(candidate):+ continue+ if candidate["name"] == model_config.DEFAULT_PRESET_NAME:+ continue+ candidate["name"] = self._unique_name(normalized, candidate["name"])+ normalized.append(candidate)+ return model_config._ensure_default_preset(normalized)++ def _replace_default(self, presets: list, replacement: dict) -> None:+ for index, preset in enumerate(presets):+ if str(preset.get("name") or "").casefold() == "default":+ presets[index] = replacement+ if index:+ presets.insert(0, presets.pop(index))+ return+ presets.insert(0, replacement)++ def _find_matching_name(self, presets: list, candidate: dict) -> str:+ signature = self._preset_signature(candidate)+ for preset in presets:+ if self._preset_signature(preset) == signature:+ return str(preset.get("name") or "")+ return ""++ def _preset_signature(self, preset: dict):+ clean = model_config._clean_preset_for_file(preset)+ clean.pop("name", None)+ return clean++ @staticmethod+ def _preset_by_name(presets: list, name: str) -> dict | None:+ normalized = str(name or "").strip().casefold()+ return next(+ (+ preset+ for preset in presets+ if str(preset.get("name") or "").strip().casefold() == normalized+ ),+ None,+ )++ def _unique_name(self, presets: list, preferred: str) -> str:+ base = str(preferred or "Migrated preset").strip()+ candidate = base+ suffix = 2+ while self._preset_by_name(presets, candidate):+ candidate = f"{base} ({suffix})"+ suffix += 1+ return candidate++ @staticmethod+ def _scope_label(asset: dict) -> str:+ project = str(asset.get("project_name") or "").strip()+ profile = str(asset.get("agent_profile") or "").strip()+ if project and profile:+ return f"Project {project} · Profile {profile}"+ if project:+ return f"Project {project}"+ if profile:+ return f"Profile {profile}"+ return "Global"++ @staticmethod+ def _read_json_dict(path: str) -> dict | None:+ try:+ value = json.loads(files.read_file(path))+ except Exception:+ return None+ return value if isinstance(value, dict) else None++ @staticmethod+ def _read_yaml_list(path: str) -> list | None:+ if not path or not os.path.exists(path):+ return None+ try:+ value = yaml_helper.loads(files.read_file(path))+ except Exception:+ return None+ return value if isinstance(value, list) else None++ @staticmethod+ def _slot_has_identity(slot) -> bool:+ return isinstance(slot, dict) and bool(slot.get("provider") or slot.get("name"))++ def _backup(self, path: str) -> None:+ if not path or not os.path.exists(path):+ return+ backup_path = path + self.BACKUP_SUFFIX+ if not os.path.exists(backup_path):+ files.write_file(backup_path, files.read_file(path))def _repair_venice_config_slots(self, config: dict) -> bool:changed = False@@ -149,24 +377,19 @@ class MigrateModelConfig(Extension):changed = self._repair_venice_slot(config.get(section)) or changedreturn changed- def _repair_venice_presets(self, presets: list) -> bool:+ def _repair_venice_preset(self, preset: dict) -> bool:changed = False- for preset in presets:- if not isinstance(preset, dict):- continue- for section in self.PRESET_SECTIONS:- changed = self._repair_venice_slot(preset.get(section)) or changed- if not any(section in preset for section in self.PRESET_SECTIONS):- changed = self._repair_venice_slot(preset) or changed+ for section in self.PRESET_SECTIONS:+ changed = self._repair_venice_slot(preset.get(section)) or changed+ if not any(section in preset for section in self.PRESET_SECTIONS):+ changed = self._repair_venice_slot(preset) or changedreturn changeddef _repair_venice_slot(self, slot) -> bool:if not isinstance(slot, dict):return Falseprovider = str(slot.get("provider") or "").strip().lower()- if provider != "venice":- return False- if slot.get("kwargs") == self.VENICE_KWARGS:+ if provider != "venice" or slot.get("kwargs") == self.VENICE_KWARGS:return Falseslot["kwargs"] = deepcopy(self.VENICE_KWARGS)return Truediff --git a/plugins/_model_config/extensions/python/startup_migration/_20_bootstrap_model_presets.py b/plugins/_model_config/extensions/python/startup_migration/_20_bootstrap_model_presets.pynew file mode 100644index 000000000..761c9f16d--- /dev/null+++ b/plugins/_model_config/extensions/python/startup_migration/_20_bootstrap_model_presets.py@@ -0,0 +1,77 @@+import os+import urllib.request++from helpers import files+from helpers.extension import Extension+from helpers.print_style import PrintStyle+from plugins._model_config.helpers import model_config+++REMOTE_PRESETS_URL = (+ "https://raw.githubusercontent.com/agent0ai/a0-presets/"+ "main/model_presets.yaml"+)+FETCH_TIMEOUT_SECONDS = 5+MAX_PRESETS_BYTES = 256 * 1024+++class BootstrapModelPresets(Extension):+ """Ensure a missing user preset collection is initialized at startup."""++ def execute(self, **kwargs):+ presets_path = model_config._get_presets_path()++ # This is the normal startup path and must not perform network I/O.+ if os.path.exists(presets_path):+ return "existing"++ source = "remote"+ try:+ presets = self._download_presets()+ except Exception as exc:+ source = "fallback"+ PrintStyle.warning(+ "Could not initialize model presets from agent0ai/a0-presets; "+ f"using fallback presets. {exc}"+ )+ try:+ presets = model_config.parse_preset_collection(+ files.read_file(model_config._get_fallback_presets_path())+ )+ except Exception as fallback_exc:+ PrintStyle.error(+ f"Fallback model presets are invalid: {fallback_exc}"+ )+ return "error"++ try:+ model_config.save_presets(presets)+ except Exception as exc:+ # Runtime preset resolution still falls back to the local file if+ # initialization cannot be persisted.+ PrintStyle.error(f"Could not persist initial model presets: {exc}")+ return "error"++ if source == "remote":+ PrintStyle.info("Initialized model presets from agent0ai/a0-presets.")+ return source++ def _download_presets(self) -> list:+ request = urllib.request.Request(+ REMOTE_PRESETS_URL,+ headers={+ "Accept": "application/yaml, text/yaml, text/plain",+ "User-Agent": "AgentZero-Model-Preset-Bootstrap",+ },+ )+ with urllib.request.urlopen(+ request,+ timeout=FETCH_TIMEOUT_SECONDS,+ ) as response:+ payload = response.read(MAX_PRESETS_BYTES + 1)++ if len(payload) > MAX_PRESETS_BYTES:+ raise ValueError("Remote model preset file is too large.")++ text = payload.decode("utf-8-sig")+ return model_config.parse_preset_collection(text)diff --git a/plugins/_model_config/extensions/webui/apply_snapshot_before/refresh-switcher.js b/plugins/_model_config/extensions/webui/apply_snapshot_before/refresh-switcher.jsindex 839fb34ae..87fcaeb10 100644--- a/plugins/_model_config/extensions/webui/apply_snapshot_before/refresh-switcher.js+++ b/plugins/_model_config/extensions/webui/apply_snapshot_before/refresh-switcher.js@@ -4,6 +4,7 @@ const OVERRIDE_REVISION_KEY = "_model_config_override_revision";let lastContextId = "";let lastRevision = null;+let lastScopeKey = "";export default async function refreshSwitcherOnOverrideRevision(ctx) {const snapshot = ctx?.snapshot;@@ -12,16 +13,28 @@ export default async function refreshSwitcherOnOverrideRevision(ctx) {if (!contextId) {lastContextId = "";lastRevision = null;+ lastScopeKey = "";return;}const contexts = Array.isArray(snapshot?.contexts) ? snapshot.contexts : [];const activeContext = contexts.find(item => item?.id === contextId) || null;const revision = activeContext?.[OVERRIDE_REVISION_KEY] || null;+ const project = activeContext?.project;+ const projectName = typeof project === "object" ? project?.name || "" : project || "";+ const scopeKey = JSON.stringify([+ String(projectName),+ String(activeContext?.agent_profile || ""),+ ]);- if (contextId === lastContextId && revision === lastRevision) return;+ if (+ contextId === lastContextId+ && revision === lastRevision+ && scopeKey === lastScopeKey+ ) return;lastContextId = contextId;lastRevision = revision;+ lastScopeKey = scopeKey;await modelConfigStore.refreshSwitcher(contextId);}diff --git a/plugins/_model_config/extensions/webui/chat-input-progress-start/model-switcher.html b/plugins/_model_config/extensions/webui/chat-input-progress-start/model-switcher.htmlindex 8d740171d..1d552e914 100644--- a/plugins/_model_config/extensions/webui/chat-input-progress-start/model-switcher.html+++ b/plugins/_model_config/extensions/webui/chat-input-progress-start/model-switcher.html@@ -1,4 +1,4 @@-<!-- Model Switcher - Floating Preset Selector (left-aligned with inline model display) -->+<!-- Model Switcher - Floating Preset Selector --><script type="module">import { store } from "/plugins/_model_config/webui/model-config-store.js";</script>@@ -26,35 +26,16 @@<span class="material-symbols-outlined" style="font-size: 0.7rem;"x-text="showDropdown ? 'expand_less' : 'expand_more'"></span></button>-- <!-- Inline active model pills (shown when a preset is active) -->- <template x-if="$store.modelConfig.switcherOverride">- <div class="model-switcher-active-pills">- <template x-if="$store.modelConfig.getActiveModels().main">- <div class="model-pill">- <span class="model-pill-role">Main</span>- <span class="model-pill-name" x-text="$store.modelConfig.getActiveModels().main.name"></span>- </div>- </template>- <template x-if="$store.modelConfig.getActiveModels().utility">- <div class="model-pill">- <span class="model-pill-role">Util</span>- <span class="model-pill-name" x-text="$store.modelConfig.getActiveModels().utility.name"></span>- </div>- </template>- </div>- </template>-<!-- Dropdown (opens upward) --><div class="model-switcher-dropdown" x-show="showDropdown" x-transition.opacity style="display: none;">- <!-- Use Default -->+ <!-- Return to the project/profile selection --><template x-if="$store.modelConfig.switcherOverride"><div class="model-switcher-item revert" @click="$store.modelConfig.clearOverrideSwitch($store.chats?.selected || '');showDropdown = false;"><span class="material-symbols-outlined" style="font-size: 15px;">undo</span>- <span>Use Default</span>+ <span>Use scoped preset</span></div></template><div class="model-switcher-divider" x-show="$store.modelConfig.switcherOverride"></div>@@ -67,7 +48,7 @@<!-- Preset list --><template x-for="preset in $store.modelConfig.switcherPresets" :key="preset.name"><div class="model-switcher-item"- :class="{ 'active': $store.modelConfig.switcherOverride?.preset_name === preset.name }"+ :class="{ 'active': $store.modelConfig.switcherEffectivePreset === preset.name }"@click="$store.modelConfig.selectPresetSwitch($store.chats?.selected || '', preset.name);showDropdown = false;@@ -94,6 +75,16 @@</span></div></template>+ <template x-if="preset.embedding?.name">+ <div class="model-switcher-model-row">+ <span class="model-switcher-model-label">Embed</span>+ <span class="model-switcher-model-value">+ <span x-text="preset.embedding.provider" style="opacity:0.5;"></span>+ <span style="opacity:0.3; margin:0 3px;">/</span>+ <span x-text="preset.embedding.name"></span>+ </span>+ </div>+ </template></div></div></template>@@ -101,7 +92,10 @@<!-- Edit Presets shortcut --><div class="model-switcher-divider" style="opacity:0.2;"></div><div class="model-switcher-item model-switcher-edit" @click="- openModal('/plugins/_model_config/webui/main.html');+ $store.modelConfig.openPresetEditor(+ $store.modelConfig.switcherEffectivePreset,+ $store.chats?.selected || ''+ );showDropdown = false;"><span class="material-symbols-outlined" style="font-size: 14px;">tune</span>@@ -209,7 +203,7 @@/* color: var(--color-text); */}.model-switcher-label {- max-width: 120px;+ max-width: min(240px, 38vw);overflow: hidden;text-overflow: ellipsis;}@@ -236,43 +230,6 @@overflow: hidden;text-overflow: ellipsis;}-- /* Inline active model pills */- .model-switcher-active-pills {- display: flex;- align-items: center;- gap: 6px;- flex-shrink: 1;- min-width: 0;- }- .model-pill {- display: flex;- align-items: center;- gap: 4px;- padding: 2px 8px;- border-radius: 12px;- background: color-mix(in srgb, var(--color-highlight) 8%, transparent);- border: 1px solid color-mix(in srgb, var(--color-highlight) 15%, transparent);- font-size: 0.68rem;- white-space: nowrap;- min-width: 0;- overflow: hidden;- }- .model-pill-role {- font-weight: 600;- opacity: 0.55;- font-size: 0.62rem;- text-transform: uppercase;- letter-spacing: 0;- flex-shrink: 0;- }- .model-pill-name {- opacity: 0.85;- overflow: hidden;- text-overflow: ellipsis;- min-width: 0;- }-/* Dropdown - opens upward, aligned to left */.model-switcher-dropdown {position: absolute;@@ -395,10 +352,9 @@font-weight: 500;}- /* Responsive: hide pills on narrow screens */@media (max-width: 600px) {- .model-switcher-active-pills {- display: none;+ .model-switcher-label {+ max-width: 160px;}.agent-profile-label {max-width: 92px;diff --git a/plugins/_model_config/helpers/model_config.py b/plugins/_model_config/helpers/model_config.pyindex 07639d537..6a1386451 100644--- a/plugins/_model_config/helpers/model_config.py+++ b/plugins/_model_config/helpers/model_config.py@@ -2,13 +2,16 @@ import osfrom copy import deepcopyimport models-from helpers import plugins, files+from helpers import defer, plugins, files+from helpers.extension import call_extensions_asyncfrom helpers import yaml as yaml_helperfrom helpers.providers import get_provider_config, get_providersPRESETS_FILE = "presets.yaml"-DEFAULT_PRESETS_FILE = "default_presets.yaml"+FALLBACK_PRESETS_FILE = "mode_presets_fallback.yaml"PROVIDER_METADATA_FILE = "provider_metadata.yaml"+DEFAULT_PRESET_NAME = "Default"+MODEL_PRESET_CONFIG_KEY = "model_preset"PRESET_SCOPE_GLOBAL = "global"PRESET_SCOPE_PROJECT = "project"PRESET_SLOT_CONFIG_SECTIONS = {@@ -83,20 +86,76 @@ def _get_presets_path(project_name: str | None = None) -> str:return files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR, "_model_config", PRESETS_FILE)-def _get_default_presets_path() -> str:- """Return the path to the default presets file shipped with the plugin."""+def _get_fallback_presets_path() -> str:+ """Return the plugin-local fallback used when no saved presets exist."""plugin_dir = plugins.find_plugin_dir("_model_config")- return files.get_abs_path(plugin_dir, DEFAULT_PRESETS_FILE) if plugin_dir else ""+ return files.get_abs_path(plugin_dir, FALLBACK_PRESETS_FILE) if plugin_dir else ""def get_config(agent=None, project_name=None, agent_profile=None):- """Get the full model config dict for the given agent/scope."""- return plugins.get_plugin_config(+ """Get the resolved model config for an agent or selected scope."""+ config = plugins.get_plugin_config("_model_config",agent=agent,project_name=project_name,agent_profile=agent_profile,) or {}+ # The plugin hook resolves selection-only config. Keep this boundary robust+ # when hooks are disabled by tests or embedding applications.+ if any(section in config for section in PRESET_SLOT_CONFIG_SECTIONS.values()):+ return config+ return resolve_config_settings(config)+++def get_configured_preset_name(agent=None, project_name=None, agent_profile=None) -> str:+ """Return the valid scoped preset selection, falling back to Default."""+ config = plugins.get_plugin_config(+ "_model_config",+ agent=agent,+ project_name=project_name,+ agent_profile=agent_profile,+ ) or {}+ name = str(config.get(MODEL_PRESET_CONFIG_KEY) or DEFAULT_PRESET_NAME).strip()+ return name if resolve_preset(name) else DEFAULT_PRESET_NAME+++def preset_to_config(preset: dict) -> dict:+ """Convert a complete preset into the legacy runtime model-config shape."""+ config: dict = {}+ for slot, section in PRESET_SLOT_CONFIG_SECTIONS.items():+ slot_config = preset.get(slot) if isinstance(preset, dict) else None+ config[section] = (+ _strip_ui_fields(slot_config, strip_api_key=False)+ if isinstance(slot_config, dict)+ else {}+ )+ return config+++def config_to_preset(config: dict, name: str = DEFAULT_PRESET_NAME) -> dict:+ """Convert legacy full model config into a preset without UI/API-key fields."""+ preset = {"name": str(name or "").strip()}+ for slot, section in PRESET_SLOT_CONFIG_SECTIONS.items():+ slot_config = config.get(section) if isinstance(config, dict) else None+ if isinstance(slot_config, dict):+ preset[slot] = _strip_ui_fields(slot_config, strip_api_key=True)+ return preset+++def resolve_config_settings(settings: dict | None) -> dict:+ """Resolve selection-only settings to the complete runtime config shape."""+ raw = settings if isinstance(settings, dict) else {}+ selected_name = str(raw.get(MODEL_PRESET_CONFIG_KEY) or DEFAULT_PRESET_NAME).strip()+ default_preset = resolve_preset(DEFAULT_PRESET_NAME) or {"name": DEFAULT_PRESET_NAME}+ selected = resolve_preset(selected_name) or default_preset+ config = preset_to_config(default_preset)+ if selected.get("name") != DEFAULT_PRESET_NAME:+ config = build_config_from_preset(selected, config, strip_api_key=False)+ config[MODEL_PRESET_CONFIG_KEY] = str(selected.get("name") or DEFAULT_PRESET_NAME)+ # Retained as a read-only compatibility flag for integrations that still+ # inspect it. The switcher is always available in the unified preset model.+ config["allow_chat_override"] = True+ return configdef has_project_config(project_name: str) -> bool:@@ -107,75 +166,60 @@ def has_project_config(project_name: str) -> bool:def load_project_llm_data(project_name: str) -> dict:- """Build the model-settings payload shown in Project Settings."""+ """Build the preset-selection payload shown in Project Settings."""project_config_exists = has_project_config(project_name)- config = normalize_config_for_save(get_config(project_name=project_name) or {})+ preset_name = get_configured_preset_name(project_name=project_name)return {- "config": config,- "config_scope": "project" if project_config_exists else "inherited","has_project_config": project_config_exists,"selected_preset": {- "scope": "current",- "project_name": project_name,- "name": "Current config",+ "scope": PRESET_SCOPE_GLOBAL,+ "project_name": "",+ "name": preset_name,},- "presets": get_combined_presets(project_name),+ "presets": get_combined_presets(),"global_presets": get_presets(),- "project_presets": get_project_presets(project_name),+ "project_presets": [],}def save_project_llm_settings(project_name: str, llm_data: object) -> None:- """Persist Project Settings model data without freezing inherited globals."""+ """Persist only a project preset selection from Project Settings."""if not isinstance(llm_data, dict):return-- project_config_exists = has_project_config(project_name)- project_presets = llm_data.get("project_presets")- presets_path = _get_presets_path(project_name)- if isinstance(project_presets, list) and (- project_presets or files.exists(presets_path)- ):- save_presets(project_presets, project_name=project_name)-- config_to_save = Noneselected_preset = llm_data.get("selected_preset")- if isinstance(selected_preset, dict) and selected_preset.get("scope") in {- PRESET_SCOPE_GLOBAL,- PRESET_SCOPE_PROJECT,- }:- preset = resolve_preset_selection(selected_preset, project_name=project_name)- if preset:- base_config = get_config(project_name=project_name) or {}- config_to_save = build_config_from_preset(preset, base_config)-- config = llm_data.get("config")- config_scope = str(llm_data.get("config_scope") or "")- config_is_inherited = not project_config_exists and (- config_scope == "inherited"- or isinstance(selected_preset, dict)- and selected_preset.get("scope") == "current"- )- should_save_config = (- project_config_exists- or config_scope == "project"- or not config_scope- )- if (- config_to_save is None- and isinstance(config, dict)- and should_save_config- and not config_is_inherited- ):- config_to_save = normalize_config_for_save(config)-- if config_to_save is not None:- plugins.save_plugin_config("_model_config", project_name, "", config_to_save)+ if not isinstance(selected_preset, dict):+ return+ name = str(selected_preset.get("name") or "").strip()+ if resolve_preset(name):+ if not has_project_config(project_name) and name == get_configured_preset_name():+ return+ previous_embedding = get_config(project_name=project_name).get(+ "embedding_model",+ {},+ )+ plugins.save_plugin_config(+ "_model_config",+ project_name,+ "",+ {MODEL_PRESET_CONFIG_KEY: name},+ )+ current_embedding = get_config(project_name=project_name).get(+ "embedding_model",+ {},+ )+ if previous_embedding != current_embedding:+ defer.DeferredTask().start_task(+ call_extensions_async,+ "embedding_model_changed",+ )def _load_presets_from_path(path: str) -> list | None:if files.exists(path):- data = yaml_helper.loads(files.read_file(path))+ try:+ data = yaml_helper.loads(files.read_file(path))+ except Exception:+ return Noneif isinstance(data, list):return datareturn None@@ -210,14 +254,34 @@ def _strip_implicit_preset_defaults(slot: str, slot_config: dict) -> dict:def _clean_preset_for_file(preset: dict) -> dict:+ name = str(preset.get("name", "") or "").strip()+ if name.casefold() == DEFAULT_PRESET_NAME.casefold():+ name = DEFAULT_PRESET_NAMEcleaned = {- "name": str(preset.get("name", "") or ""),+ "name": name,}+ has_named_slots = any(+ isinstance(preset.get(slot), dict) for slot in PRESET_SLOT_CONFIG_SECTIONS+ )for slot in PRESET_SLOT_CONFIG_SECTIONS:slot_config = preset.get(slot)if isinstance(slot_config, dict):- slot_clean = _strip_ui_fields(slot_config, strip_api_key=False)- cleaned[slot] = _strip_implicit_preset_defaults(slot, slot_clean)+ slot_clean = _strip_ui_fields(slot_config, strip_api_key=True)+ cleaned[slot] = (+ slot_clean+ if name == DEFAULT_PRESET_NAME+ else _strip_implicit_preset_defaults(slot, slot_clean)+ )+ # Very old presets stored the main model directly beside ``name``. Preserve+ # those definitions while bringing them into the canonical slot schema.+ if not has_named_slots and _slot_has_identity(preset):+ raw_chat = {+ key: value+ for key, value in preset.items()+ if key not in {"name", "scope", "project_name"}+ }+ raw_chat["name"] = name+ cleaned["chat"] = _strip_ui_fields(raw_chat, strip_api_key=True)return cleaned@@ -230,6 +294,48 @@ def clean_presets_for_file(presets: list) -> list:return cleaned+def validate_presets(presets: list, *, require_default: bool = True) -> list:+ """Validate and clean the durable global preset collection."""+ if not isinstance(presets, list):+ raise ValueError("Presets must be a list.")++ cleaned: list[dict] = []+ seen: set[str] = set()+ for raw in presets:+ if not isinstance(raw, dict):+ raise ValueError("Every preset must be an object.")+ preset = _clean_preset_for_file(raw)+ name = str(preset.get("name") or "").strip()+ if not name:+ raise ValueError("Preset names cannot be empty.")+ normalized = name.casefold()+ if normalized in seen:+ raise ValueError(f"Preset names must be unique: '{name}'.")+ if normalized == DEFAULT_PRESET_NAME.casefold():+ preset["name"] = DEFAULT_PRESET_NAME+ for slot, label in (+ ("chat", "main"),+ ("utility", "utility"),+ ("embedding", "embedding"),+ ):+ if not _slot_has_identity(preset.get(slot) or {}):+ raise ValueError(+ f"The Default preset requires a {label} model."+ )+ seen.add(normalized)+ cleaned.append(preset)++ default_index = next(+ (i for i, preset in enumerate(cleaned) if preset["name"] == DEFAULT_PRESET_NAME),+ None,+ )+ if require_default and default_index is None:+ raise ValueError("The Default preset cannot be deleted or renamed.")+ if default_index not in (None, 0):+ cleaned.insert(0, cleaned.pop(default_index))+ return cleaned++def normalize_config_for_save(config: dict) -> dict:"""Remove UI-only fields and inline API keys before storing scoped config."""cleaned = deepcopy(config or {})@@ -240,24 +346,98 @@ def normalize_config_for_save(config: dict) -> dict:return cleaned+def _legacy_default_preset() -> dict | None:+ """Build Default from a pre-v2 global config when startup migration has not run."""+ path = plugins.determine_plugin_asset_path(+ "_model_config", "", "", plugins.CONFIG_FILE_NAME+ )+ if not files.exists(path):+ return None+ try:+ raw = files.read_file_json(path)+ except Exception:+ return None+ if not isinstance(raw, dict) or not any(+ section in raw for section in PRESET_SLOT_CONFIG_SECTIONS.values()+ ):+ return None+ return config_to_preset(raw, DEFAULT_PRESET_NAME)+++def parse_preset_collection(text: str) -> list:+ """Parse, validate, and sanitize a preset YAML document."""+ return validate_presets(yaml_helper.loads(text))+++def _fallback_presets() -> list:+ path = _get_fallback_presets_path()+ if not files.exists(path):+ return []+ try:+ return parse_preset_collection(files.read_file(path))+ except Exception:+ return []+++def _ensure_default_preset(presets: list) -> list:+ result = [deepcopy(preset) for preset in presets if isinstance(preset, dict)]+ legacy_default = _legacy_default_preset()+ bundled_default = next(+ (+ deepcopy(preset)+ for preset in _fallback_presets()+ if isinstance(preset, dict)+ and str(preset.get("name") or "").strip().casefold()+ == DEFAULT_PRESET_NAME.casefold()+ ),+ None,+ )+ fallback_default = bundled_default or {"name": DEFAULT_PRESET_NAME}+ if legacy_default:+ for slot in PRESET_SLOT_CONFIG_SECTIONS:+ legacy_slot = legacy_default.get(slot)+ if _slot_has_identity(legacy_slot or {}):+ fallback_default[slot] = deepcopy(legacy_slot)+ default_index = next(+ (+ i+ for i, preset in enumerate(result)+ if str(preset.get("name") or "").strip().casefold()+ == DEFAULT_PRESET_NAME.casefold()+ ),+ None,+ )+ if default_index is not None:+ result[default_index]["name"] = DEFAULT_PRESET_NAME+ for slot in PRESET_SLOT_CONFIG_SECTIONS:+ if not _slot_has_identity(result[default_index].get(slot) or {}):+ fallback_slot = fallback_default.get(slot)+ if isinstance(fallback_slot, dict):+ result[default_index][slot] = deepcopy(fallback_slot)+ if default_index:+ result.insert(0, result.pop(default_index))+ return result++ result.insert(0, fallback_default)+ return result++def get_presets(project_name: str | None = None) -> list:- """Get global model presets list (not scoped to project/agent)."""+ """Get global presets with the required Default preset first."""if project_name:return get_project_presets(project_name)path = _get_presets_path()presets = _load_presets_from_path(path)if presets is not None:- return presets+ return _ensure_default_preset(presets)- # Fall back to defaults bundled with the plugin- default_path = _get_default_presets_path()- default_presets = _load_presets_from_path(default_path) if default_path else None- return default_presets or []+ # Fall back to the repository-shipped offline collection.+ return _ensure_default_preset(_fallback_presets())def get_project_presets(project_name: str) -> list:- """Get presets stored beside the project-scoped _model_config config."""+ """Load legacy project presets for migration/compatibility only."""return _load_presets_from_path(_get_presets_path(project_name)) or []@@ -270,33 +450,57 @@ def _with_preset_metadata(preset: dict, scope: str, project_name: str = "") -> ddef get_combined_presets(project_name: str | None = None) -> list:- """Get presets with explicit API metadata for unambiguous UI/API selection."""- presets = [+ """Get global presets with API metadata (project definitions are retired)."""+ return [_with_preset_metadata(preset, PRESET_SCOPE_GLOBAL)for preset in get_presets()if isinstance(preset, dict)]- if project_name:- presets.extend(- _with_preset_metadata(preset, PRESET_SCOPE_PROJECT, project_name)- for preset in get_project_presets(project_name)- if isinstance(preset, dict)- )- return presetsdef save_presets(presets: list, project_name: str | None = None) -> None:- """Save the presets list for the requested scope."""+ """Save global presets while enforcing the immutable Default identity."""+ if project_name:+ raise ValueError("Project-specific preset definitions are no longer supported.")+ cleaned = validate_presets(presets)path = _get_presets_path(project_name)- files.write_file(path, yaml_helper.dumps(clean_presets_for_file(presets)))+ files.write_file(path, yaml_helper.dumps(cleaned))+++def update_preset_from_config(name: str, config: dict) -> dict:+ """Replace one global preset's model slots from a legacy config payload."""+ target = resolve_preset(name)+ if not target:+ raise ValueError(f"Preset '{name}' was not found.")+ canonical_name = str(target.get("name") or DEFAULT_PRESET_NAME)+ replacement = config_to_preset(config, canonical_name)+ if canonical_name == DEFAULT_PRESET_NAME:+ for slot in PRESET_SLOT_CONFIG_SECTIONS:+ if not _slot_has_identity(replacement.get(slot) or {}):+ current_slot = target.get(slot)+ if isinstance(current_slot, dict):+ replacement[slot] = deepcopy(current_slot)+ presets = get_presets()+ updated = False+ for index, preset in enumerate(presets):+ if str(preset.get("name") or "").casefold() == canonical_name.casefold():+ presets[index] = replacement+ updated = True+ break+ if not updated:+ raise ValueError(f"Preset '{name}' was not found.")+ save_presets(presets)+ return replacementdef reset_presets(project_name: str | None = None) -> list:"""Delete user presets for the scope. Global reset falls back to bundled defaults."""+ if project_name:+ raise ValueError("Project-specific preset definitions are no longer supported.")path = _get_presets_path(project_name)if os.path.exists(path):os.remove(path)- return get_project_presets(project_name) if project_name else get_presets()+ return get_presets()def resolve_preset(@@ -307,14 +511,11 @@ def resolve_preset() -> dict | None:"""Resolve a preset by explicit scope so same-name presets are unambiguous."""if scope == PRESET_SCOPE_PROJECT:- if not project_name:- return None- presets = get_project_presets(project_name)- else:- presets = get_presets()+ return None+ presets = get_presets()for p in presets:- if p.get("name") == name:+ if str(p.get("name") or "").casefold() == str(name or "").strip().casefold():return preturn None@@ -491,39 +692,60 @@ def _resolve_override(agent) -> dict | None:return override-def get_chat_model_config(agent=None) -> dict:- """Get chat model config, with per-chat override if active."""- cfg = get_config(agent)+def get_effective_preset_name(agent=None) -> str:+ """Return the valid preset used by a chat, including its explicit override."""+ if agent:+ override = getattr(agent, "context", None)+ override = override.get_data("chat_model_override") if override else None+ if isinstance(override, dict):+ name = str(override.get("preset_name") or "").strip()+ preset = resolve_preset(name) if name else None+ if preset:+ return str(preset.get("name") or DEFAULT_PRESET_NAME)+ config = get_config(agent)+ return str(config.get(MODEL_PRESET_CONFIG_KEY) or DEFAULT_PRESET_NAME)+++def get_effective_config(agent=None) -> dict:+ """Resolve the complete model config, including a per-chat preset selection."""+ config = get_config(agent)+ raw_override = None+ if agent and getattr(agent, "context", None):+ raw_override = agent.context.get_data("chat_model_override")+ uses_named_preset = isinstance(raw_override, dict) and bool(+ raw_override.get("preset_name")+ )override = _resolve_override(agent)if override:+ base = (+ preset_to_config(resolve_preset(DEFAULT_PRESET_NAME) or {})+ if uses_named_preset+ else config+ )config = build_config_from_preset(override,- cfg,+ base,strip_api_key=False,- slots=("chat",),)- return config.get("chat_model", {})- return cfg.get("chat_model", {})+ if uses_named_preset:+ config[MODEL_PRESET_CONFIG_KEY] = get_effective_preset_name(agent)+ config["allow_chat_override"] = True+ return config+++def get_chat_model_config(agent=None) -> dict:+ """Get chat model config, with per-chat override if active."""+ return get_effective_config(agent).get("chat_model", {})def get_utility_model_config(agent=None) -> dict:"""Get utility model config, with per-chat override if active."""- cfg = get_config(agent)- override = _resolve_override(agent)- if override:- config = build_config_from_preset(- override,- cfg,- strip_api_key=False,- slots=("utility",),- )- return config.get("utility_model", {})- return cfg.get("utility_model", {})+ return get_effective_config(agent).get("utility_model", {})def get_embedding_model_config(agent=None) -> dict:- """Get embedding model config."""- cfg = get_config(agent)+ """Get embedding model config from the effective preset."""+ cfg = get_effective_config(agent)model_cfg = deepcopy(cfg.get("embedding_model", {}))provider = str(model_cfg.get("provider") or "").strip().lower()name = str(model_cfg.get("name") or "").strip().strip('"').strip("'")@@ -545,9 +767,8 @@ def get_embedding_model_config(agent=None) -> dict:def is_chat_override_allowed(agent=None) -> bool:- """Check if per-chat model override is enabled."""- cfg = get_config(agent)- return bool(cfg.get("allow_chat_override", False))+ """The unified preset switcher is always enabled."""+ return Truedef get_ctx_history(agent=None) -> float:@@ -652,7 +873,7 @@ def has_provider_api_key(provider: str, configured_api_key: str = "", model_typedef get_missing_api_key_providers(agent=None) -> list[dict]:"""Check which configured providers are missing API keys."""- cfg = get_config(agent)+ cfg = get_effective_config(agent)missing = []checks = [diff --git a/plugins/_model_config/hooks.py b/plugins/_model_config/hooks.pyindex 5c632dd4c..1d6a77ecf 100644--- a/plugins/_model_config/hooks.py+++ b/plugins/_model_config/hooks.py@@ -1,8 +1,23 @@+from plugins._model_config.helpers import model_config+++def get_plugin_config(default=None, **kwargs):+ """Expose the legacy complete config shape to runtime callers."""+ return model_config.resolve_config_settings(default)++def save_plugin_config(result=None, settings=None, **kwargs):- if settings and isinstance(settings, dict):- # Remove transient UI-only fields before persisting- for section in ("chat_model", "utility_model", "embedding_model"):- if section in settings and isinstance(settings[section], dict):- settings[section].pop("_kwargs_text", None)- settings[section].pop("api_key", None)- return settings+ """Persist only the scoped preset selection."""+ raw = settings if isinstance(settings, dict) else {}+ name = str(+ raw.get(model_config.MODEL_PRESET_CONFIG_KEY)+ or model_config.DEFAULT_PRESET_NAME+ ).strip()+ preset = model_config.resolve_preset(name)+ return {+ model_config.MODEL_PRESET_CONFIG_KEY: (+ str(preset.get("name"))+ if preset+ else model_config.DEFAULT_PRESET_NAME+ )+ }diff --git a/plugins/_model_config/mode_presets_fallback.yaml b/plugins/_model_config/mode_presets_fallback.yamlnew file mode 100644index 000000000..aec70f908--- /dev/null+++ b/plugins/_model_config/mode_presets_fallback.yaml@@ -0,0 +1,54 @@+- name: Default+ chat:+ provider: openrouter+ name: openai/gpt-5.6-terra+ api_base: ""+ ctx_length: 200000+ ctx_history: 0.7+ vision: true+ max_embeds: 10+ rl_requests: 0+ rl_input: 0+ rl_output: 0+ kwargs: {}+ utility:+ provider: openrouter+ name: google/gemini-3.1-flash-lite+ api_base: ""+ ctx_length: 128000+ ctx_input: 0.7+ rl_requests: 0+ rl_input: 0+ rl_output: 0+ kwargs: {}+ embedding:+ provider: huggingface+ name: sentence-transformers/all-MiniLM-L6-v2+ api_base: ""+ rl_requests: 0+ rl_input: 0+ kwargs: {}++- name: Efficiency+ chat:+ provider: openrouter+ name: z-ai/glm-5.2+ api_base: ""+ ctx_length: 128000+ ctx_history: 0.7+ vision: false+ utility:+ provider: openrouter+ name: deepseek/deepseek-v4-flash++- name: Power+ chat:+ provider: openrouter+ name: openai/gpt-5.6-sol+ api_base: ""+ ctx_length: 200000+ ctx_history: 0.7+ vision: true+ utility:+ provider: openrouter+ name: openai/gpt-5.6-lunadiff --git a/plugins/_model_config/plugin.yaml b/plugins/_model_config/plugin.yamlindex b16891d93..e5a7416b6 100644--- a/plugins/_model_config/plugin.yaml+++ b/plugins/_model_config/plugin.yaml@@ -1,7 +1,7 @@name: _model_configtitle: Model Configuration-description: Manages LLM model selection and configuration for chat, utility, and embedding models. Supports per-project and per-agent overrides with optional per-chat model switching.-version: 1.0.0+description: Manages reusable model presets and selects them globally, per project, per agent profile, and per chat.+version: 2.1.0always_enabled: truesettings_sections:- agentdiff --git a/plugins/_model_config/webui/config.html b/plugins/_model_config/webui/config.htmlindex 7c21309ac..3cdb32068 100644--- a/plugins/_model_config/webui/config.html+++ b/plugins/_model_config/webui/config.html@@ -1,83 +1,27 @@<html><head>- <title>Model Configuration</title>+ <title>Model Preset</title><script type="module">import { store } from "/plugins/_model_config/webui/model-config-store.js";</script></head><body>- <div x-data- x-init="- await $store.modelConfig.ensureLoaded();- $store.modelConfig.resetApiKeyDrafts();- await $store.modelConfig.refreshApiKeyStatus();- $store.modelConfig.installSettingsHooks(context);- ">- <template x-if="config && $store.modelConfig._loaded">- <div class="model-config-sections">-- <!-- Model Sections (Main, Utility, Embedding) -->- <template x-for="section in $store.modelConfig.MODEL_SECTIONS" :key="section.key">- <div class="model-section"- x-data="{ get model() { return config[section.key]; }, modelType: section.key.replace('_model', ''), providers: $store.modelConfig.getProviders(section.key), searchType: $store.modelConfig.getSearchType(section.key), apiKeyMode: 'store' }">- <div class="section-title" x-text="section.title"></div>- <div class="section-description" x-text="section.desc"></div>- <x-component path="/plugins/_model_config/webui/model-field.html"></x-component>- </div>- </template>--- <!-- Per-Chat Override -->- <div class="model-section">- <div class="section-title">Per-Chat Override</div>- <div class="section-description">Allow switching model presets from the chat navigation bar. New chats inherit the active preset.</div>- <div class="field">- <div class="field-label">- <div class="field-title">Enable model switcher</div>- <div class="field-description">Show a preset switcher in the chat navigation bar. Overrides main and utility model for the current chat.</div>- </div>- <div class="field-control">- <label class="toggle">- <input type="checkbox" x-model="config.allow_chat_override" />- <span class="toggler"></span>- </label>- </div>- </div>- <div class="override-presets-link" x-show="config.allow_chat_override">- <button class="text-button" @click="openModal('/plugins/_model_config/webui/main.html')">- <span class="material-symbols-outlined">tune</span>- <span>Edit Presets</span>- </button>- </div>- </div>-- </div>- </template>+ <div x-data="$store.modelConfig.createScopedPresetSelector(context)"+ x-init="await init()">+ <div class="section-title">Model Preset</div>+ <div class="section-description">+ This scope stores only a preset selection. Edit the preset once and every scope using it stays in sync.+ </div>+ <div class="scoped-preset-overview">+ <x-component path="/plugins/_model_config/webui/preset-overview.html"></x-component>+ </div></div>-<style>- .model-config-sections {- display: flex;- flex-direction: column;- gap: 16px;- }- .model-section {- border: 1px solid var(--color-border);- border-radius: 8px;- padding: 16px;- }- .model-section .section-title {- margin-top: 0;- }- .override-presets-link {- margin-top: 4px;- }- .override-presets-link .text-button {- font-size: 0.78rem !important;- gap: 4px;- }--</style>+ <style>+ .scoped-preset-overview {+ margin-top: 1rem;+ }+ </style></body></html>diff --git a/plugins/_model_config/webui/main.html b/plugins/_model_config/webui/main.htmlindex ca6472961..00f9ca9a3 100644--- a/plugins/_model_config/webui/main.html+++ b/plugins/_model_config/webui/main.html@@ -1,6 +1,6 @@<html><head>- <title>Model Presets</title>+ <title>Edit Model Presets</title><script type="module">import { store } from "/plugins/_model_config/webui/model-config-store.js";</script>@@ -10,158 +10,183 @@<div x-datax-init="await $store.modelConfig.ensureLoaded();- await $store.modelConfig.loadGlobalPresets();$store.modelConfig.resetApiKeyDrafts();await $store.modelConfig.refreshApiKeyStatus();+ await $store.modelConfig.loadGlobalPresets();+ await $store.modelConfig.preparePresetEditor($store.chats?.selected || '');"><template x-if="$store.modelConfig._loaded && $store.modelConfig._presetsLoaded">- <div class="presets-page" x-data="$store.modelConfig.createPresetEditor()">- <div class="presets-header">- <div class="field-title" style="font-size:1rem;">Model Presets</div>- <div class="field-description">Global presets shared across all projects and agents. Used by the model switcher in the chat area.</div>+ <div class="preset-editor"+ x-data="$store.modelConfig.createPresetEditor($store.modelConfig.presetEditorInitialName)">+ <div class="preset-editor-intro">+ <div class="field-title">Model Presets</div>+ <div class="field-description">+ Each preset contains the complete main, utility, and embedding model setup. Default is always available.+ </div>+ </div>++ <div class="preset-editor-toolbar">+ <label class="preset-editor-select">+ <span class="field-title">Preset</span>+ <select x-model.number="selectedKey">+ <template x-for="preset in presets" :key="preset._key">+ <option :value="preset._key" x-text="preset.name"></option>+ </template>+ </select>+ </label>+ <button type="button" class="button" @click="addPreset()">+ <span class="icon material-symbols-outlined">add</span>+ Add+ </button>+ <button type="button" class="button"+ x-show="canDeleteSelected"+ @click="$confirmClick($event, () => removeSelectedPreset())">+ <span class="icon material-symbols-outlined">delete</span>+ Delete+ </button></div>- <template x-for="(preset, idx) in presets" :key="preset._key">- <div class="preset-card" x-data="{ expanded: false }">- <div class="preset-card-header" @click="expanded = !expanded">- <span class="material-symbols-outlined preset-expand-icon"- :style="expanded ? 'transform:rotate(90deg)' : ''"- style="font-size:16px; transition:transform 0.15s ease;">chevron_right</span>- <span class="preset-card-name" x-text="preset.name || '(unnamed)'"></span>- <span class="preset-card-summary" x-show="!expanded"- x-text="(preset.chat?.provider ? preset.chat.provider + '/' : '') + (preset.chat?.name || '')"></span>- <button class="text-button preset-delete-btn"- @click.stop="$confirmClick($event, () => removePreset(idx))"- title="Remove preset">- <span class="material-symbols-outlined" style="font-size:16px;">close</span>- </button>- </div>-- <div class="preset-card-body" x-show="expanded" x-transition.opacity>- <div class="field">+ <template x-if="selectedPreset">+ <div class="preset-editor-body">+ <template x-if="canRenameSelected">+ <div class="field preset-name-field"><div class="field-label"><div class="field-title">Preset name</div>- <div class="field-description">Display name shown in the model switcher dropdown.</div>+ <div class="field-description">Shown in settings and the chat model switcher.</div>+ </div>+ <div class="field-control">+ <input type="text"+ x-model="selectedPreset.name"+ placeholder="Preset name"></div>- <div class="field-control"><input type="text" x-model="preset.name" placeholder="e.g. GPT-4o, Claude Sonnet"- @blur="if (!preset.name.trim()) preset.name = 'Preset ' + (idx + 1)" required /></div></div>+ </template>- <div class="preset-subheader">Main Model</div>- <div x-data="{ model: preset.chat, modelType: 'chat', providers: $store.modelConfig.chatProviders, searchType: 'chat', apiKeyMode: 'store' }">+ <section class="preset-model-section">+ <div class="preset-model-heading">+ <div class="section-title">Main Model</div>+ <div class="section-description">Primary model for conversations, reasoning, and tools.</div>+ </div>+ <div x-data="{ get model() { return selectedPreset.chat; }, modelType: 'chat', providers: $store.modelConfig.chatProviders, searchType: 'chat', apiKeyMode: 'store' }"><x-component path="/plugins/_model_config/webui/model-field.html"></x-component></div>+ </section>- <div class="preset-subheader">Utility Model <span style="opacity:0.5; font-size:0.75rem;">(optional — falls back to the configured Utility Model)</span></div>- <div x-data="{ model: preset.utility, modelType: 'utility', providers: $store.modelConfig.chatProviders, searchType: 'chat', apiKeyMode: 'store', providerFallback: preset.chat.provider, apiBaseFallback: preset.chat.api_base }">+ <section class="preset-model-section">+ <div class="preset-model-heading">+ <div class="section-title">Utility Model</div>+ <div class="section-description">Faster helper model for summaries and background work.</div>+ </div>+ <div x-data="{ get model() { return selectedPreset.utility; }, modelType: 'utility', providers: $store.modelConfig.chatProviders, searchType: 'chat', apiKeyMode: 'store', get providerFallback() { return selectedPreset.chat.provider; }, get apiBaseFallback() { return selectedPreset.chat.api_base; } }"><x-component path="/plugins/_model_config/webui/model-field.html"></x-component></div>- </div>+ </section>++ <section class="preset-model-section">+ <div class="preset-model-heading">+ <div class="section-title">Embedding Model</div>+ <div class="section-description">Creates vectors for memory and knowledge retrieval.</div>+ </div>+ <div x-data="{ get model() { return selectedPreset.embedding; }, modelType: 'embedding', providers: $store.modelConfig.embeddingProviders, searchType: 'embedding', apiKeyMode: 'store' }">+ <x-component path="/plugins/_model_config/webui/model-field.html"></x-component>+ </div>+ </section></div></template>- <div class="presets-actions">- <button class="text-button preset-add-btn" @click="addPreset()">- <span class="material-symbols-outlined">add</span>- <span>Add Preset</span>- </button>- <button class="text-button" @click="(async () => {- await import('/components/plugins/plugin-settings-store.js');- await $store.pluginSettingsPrototype.openConfig('_model_config');- refreshPresets();- })()">- <span class="material-symbols-outlined">settings</span>- <span>Settings</span>- </button>- <button class="text-button" @click="openModal('/plugins/_model_config/webui/api-keys.html')">+ <div class="preset-editor-secondary-actions">+ <button type="button" class="text-button" @click="$store.modelConfig.openApiKeysFromSummary()"><span class="material-symbols-outlined">key</span>- <span>API Keys</span>+ API Keys+ </button>+ <button type="button" class="text-button"+ @click="$confirmClick($event, () => resetPresets())">+ <span class="material-symbols-outlined">restart_alt</span>+ Restore bundled presets</button></div>- <div class="presets-footer">- <button class="button" @click="$confirmClick($event, () => resetPresets())">- <span class="icon material-symbols-outlined">restart_alt</span> Reset to default- </button>- <button class="button" @click="savePresets()">- <span class="icon material-symbols-outlined">save</span> Save Presets- </button>+ <div class="modal-footer" data-modal-footer>+ <button type="button" class="btn btn-ok"+ @click="if (await savePresets()) window.closeModal?.()">Save</button>+ <button type="button" class="btn btn-cancel"+ @click="window.closeModal?.()">Close</button></div></div></template></div><style>- .presets-page {- display: flex;- flex-direction: column;- gap: 8px;- }- .presets-header {- margin-bottom: 8px;- }- .presets-footer {- margin-top: 12px;- display: flex;- justify-content: flex-end;- gap: 8px;- }- .preset-card {- border: 1px solid var(--color-border);- border-radius: 6px;- }- .preset-card-header {- display: flex;- align-items: center;- gap: 6px;- padding: 8px 10px;- cursor: pointer;- font-size: 0.85rem;- }- .preset-card-header:hover {- background: var(--color-background-hover, rgba(255,255,255,0.04));- }- .preset-card-name {- font-weight: 500;- }- .preset-card-summary {- flex: 1;- text-align: right;- opacity: 0.5;- font-size: 0.75rem;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- .preset-delete-btn {- margin-left: auto;- opacity: 0.5;- padding: 2px !important;- }- .preset-delete-btn:hover {- opacity: 1;- color: var(--color-error, #f44) !important;- }- .preset-card-body {- padding: 4px 12px 12px;- border-top: 1px solid var(--color-border);- }- .preset-subheader {- font-size: 0.8rem;- font-weight: 500;- opacity: 0.7;- margin: 10px 0 4px;- padding-top: 8px;- border-top: 1px dashed var(--color-border);- }- .presets-actions {- display: flex;- gap: 12px;- flex-wrap: wrap;- align-items: center;- margin-top: 4px;- }+ .preset-editor,+ .preset-editor-body {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ }++ .preset-editor-intro .field-title {+ font-size: 1rem;+ }++ .preset-editor-toolbar {+ display: flex;+ align-items: flex-end;+ gap: 0.5rem;+ padding: 0.8rem;+ border: 1px solid var(--color-border);+ border-radius: 8px;+ background: var(--color-input);+ }++ .preset-editor-select {+ display: flex;+ flex: 1 1 auto;+ flex-direction: column;+ gap: 0.35rem;+ min-width: 0;+ margin: 0;+ }++ .preset-editor-select select {+ width: 100%;+ }++ .preset-name-field,+ .preset-model-section {+ padding: 1rem;+ border: 1px solid var(--color-border);+ border-radius: 8px;+ }++ .preset-model-heading {+ margin-bottom: 0.75rem;+ }++ .preset-model-heading .section-title {+ margin-top: 0;+ }++ .preset-editor-secondary-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem;+ }++ @media (max-width: 640px) {+ .preset-editor-toolbar {+ align-items: stretch;+ flex-wrap: wrap;+ }++ .preset-editor-select {+ flex-basis: 100%;+ }+ .preset-editor-toolbar .button {+ flex: 1 1 auto;+ justify-content: center;+ }+ }</style></body></html>diff --git a/plugins/_model_config/webui/model-config-store.js b/plugins/_model_config/webui/model-config-store.jsindex 57945c372..5e69bde20 100644--- a/plugins/_model_config/webui/model-config-store.js+++ b/plugins/_model_config/webui/model-config-store.js@@ -80,7 +80,12 @@ function presetDefaultValuesEqual(value, defaultValue) {return JSON.stringify(value) === JSON.stringify(defaultValue);}-function cleanPresetSlot(slot, stripApiKey = true, slotKey = '') {+function cleanPresetSlot(+ slot,+ stripApiKey = true,+ slotKey = '',+ preserveImplicitDefaults = false,+) {const clean = {};const implicitDefaults = IMPLICIT_PRESET_SLOT_DEFAULTS[slotKey] || {};for (const [key, value] of Object.entries(slot || {})) {@@ -92,7 +97,11 @@ function cleanPresetSlot(slot, stripApiKey = true, slotKey = '') {}if (key === 'kwargs' && isBlankPresetValue(value)) continue;if (isBlankPresetValue(value)) continue;- if (key in implicitDefaults && presetDefaultValuesEqual(value, implicitDefaults[key])) continue;+ if (+ !preserveImplicitDefaults+ && key in implicitDefaults+ && presetDefaultValuesEqual(value, implicitDefaults[key])+ ) continue;clean[key] = value;}return clean;@@ -151,6 +160,7 @@ export function configFromPreset(preset, baseConfig, stripApiKey = true) {// ── Alpine Store ──const API_BASE = "/plugins/_model_config";+export const DEFAULT_PRESET_NAME = "Default";export const store = createStore("modelConfig", {// Core state@@ -168,12 +178,16 @@ export const store = createStore("modelConfig", {// Global presets stateglobalPresets: [],_presetsLoaded: false,+ _lastPresetReferenceChanges: {},// Model summary statemodelsSummary: [],+ modelsSummaryPreset: DEFAULT_PRESET_NAME,modelsSummaryLoading: false,_modelsSummaryLoaded: false,_modelsSummaryPromise: null,+ presetEditorInitialName: DEFAULT_PRESET_NAME,+ _presetEditorSelectionPinned: false,// Switcher state (from mixin)...switcherState,@@ -189,12 +203,26 @@ export const store = createStore("modelConfig", {// ── Core methods ──_normalizePresets(rawPresets) {- return (rawPresets || []).map(p => ({- name: p.name || '',- chat: { provider: '', name: '', api_key: '', api_base: '', kwargs: {}, _kwargs_text: kwargsToText(p.chat?.kwargs), ...(p.chat || {}) },- utility: { provider: '', name: '', api_key: '', api_base: '', kwargs: {}, _kwargs_text: kwargsToText(p.utility?.kwargs), ...(p.utility || {}) },- embedding: p.embedding ? { provider: '', name: '', api_key: '', api_base: '', kwargs: {}, _kwargs_text: kwargsToText(p.embedding?.kwargs), ...(p.embedding || {}) } : undefined,- }));+ const source = (rawPresets || []).filter(p => p && typeof p === 'object');+ const rawDefault = source.find(p => String(p.name || '').toLowerCase() === 'default') || {};+ const slot = value => ({ provider: '', name: '', api_key: '', api_base: '', kwargs: {}, ...(value || {}) });+ const defaultConfig = {+ chat_model: slot(rawDefault.chat),+ utility_model: slot(rawDefault.utility),+ embedding_model: slot(rawDefault.embedding),+ };++ return source.map(p => {+ const effective = String(p.name || '').toLowerCase() === 'default'+ ? defaultConfig+ : configFromPreset(p, defaultConfig, true);+ return {+ name: p.name || '',+ chat: { ...slot(effective.chat_model), _kwargs_text: kwargsToText(effective.chat_model?.kwargs) },+ utility: { ...slot(effective.utility_model), _kwargs_text: kwargsToText(effective.utility_model?.kwargs) },+ embedding: { ...slot(effective.embedding_model), _kwargs_text: kwargsToText(effective.embedding_model?.kwargs) },+ };+ });},async ensureLoaded() {@@ -232,12 +260,13 @@ export const store = createStore("modelConfig", {this._loaded = true;},- async _fetchConfigData() {+ async _fetchConfigData(input = {}) {const res = await fetchApi(`${API_BASE}/model_config_get`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({})+ body: JSON.stringify(input)});+ if (!res.ok) throw new Error(await res.text());return await res.json();},@@ -256,49 +285,109 @@ export const store = createStore("modelConfig", {? context._toComparableJson(config): null;- this.initConfigFields(config);+ const selected = String(config.model_preset || DEFAULT_PRESET_NAME).trim();+ context.settings = {+ model_preset: this.globalPresets.some(p => p.name === selected)+ ? selected+ : DEFAULT_PRESET_NAME,+ };if (refreshCleanSnapshot &&typeof context._toComparableJson === 'function' &&context.settingsSnapshotJson === snapshotBeforeInit) {- context.settingsSnapshotJson = context._toComparableJson(config);+ context.settingsSnapshotJson = context._toComparableJson(context.settings);}},// Global presets- createPresetEditor() {+ createPresetEditor(initialName = '') {const store = this;let nextPresetKey = 0;const presets = clonePlain(this.globalPresets).map(preset => ({...preset,+ _originalName: preset.name,_key: nextPresetKey++,}));+ const initial = presets.find(p => p.name === initialName)+ || presets.find(p => p.name === DEFAULT_PRESET_NAME)+ || presets[0]+ || null;return {presets,+ selectedKey: initial?._key ?? null,+ get selectedPreset() {+ return this.presets.find(p => p._key === this.selectedKey) || null;+ },+ get canRenameSelected() {+ return !!this.selectedPreset && this.selectedPreset._originalName !== DEFAULT_PRESET_NAME;+ },+ get canDeleteSelected() {+ return this.canRenameSelected;+ },+ uniquePresetName(preferred = 'New Preset') {+ const names = new Set(this.presets.map(p => String(p.name || '').toLowerCase()));+ let candidate = preferred;+ let suffix = 2;+ while (names.has(candidate.toLowerCase())) candidate = `${preferred} ${suffix++}`;+ return candidate;+ },addPreset() {- this.presets = [...this.presets, {+ const base = clonePlain(+ this.presets.find(p => p.name === DEFAULT_PRESET_NAME)+ || this.presets[0]+ || {+ chat: { provider: '', name: '', api_base: '', kwargs: {}, _kwargs_text: '' },+ utility: { provider: '', name: '', api_base: '', kwargs: {}, _kwargs_text: '' },+ embedding: { provider: '', name: '', api_base: '', kwargs: {}, _kwargs_text: '' },+ }+ );+ const preset = {+ ...base,_key: nextPresetKey++,- name: `Preset ${this.presets.length + 1}`,- chat: { provider: '', name: '', api_key: '', api_base: '', kwargs: {}, _kwargs_text: '' },- utility: { provider: '', name: '', api_key: '', api_base: '', kwargs: {}, _kwargs_text: '' },- }];+ _originalName: '',+ name: this.uniquePresetName(),+ };+ this.presets = [...this.presets, preset];+ this.selectedKey = preset._key;},- removePreset(index) {- this.presets.splice(index, 1);- this.presets = [...this.presets];+ removeSelectedPreset() {+ if (!this.canDeleteSelected) return;+ const removeKey = this.selectedKey;+ this.presets = this.presets.filter(p => p._key !== removeKey);+ this.selectedKey = this.presets.find(p => p.name === DEFAULT_PRESET_NAME)?._key+ ?? this.presets[0]?._key+ ?? null;},async savePresets() {- await store.persistAllDirtyApiKeys();- await store.saveGlobalPresets(this.presets);+ if (this.selectedPreset && !String(this.selectedPreset.name || '').trim()) {+ globalThis.justToast?.('Preset names cannot be empty.', 'error');+ return false;+ }+ try {+ await store.persistAllDirtyApiKeys();+ } catch (e) {+ console.error('Failed to save API keys:', e);+ globalThis.justToast?.(e?.message || 'Failed to save API keys.', 'error');+ return false;+ }+ if (!await store.saveGlobalPresets(this.presets)) return false;+ this.refreshPresets();+ return true;},refreshPresets() {+ const selectedName = this.selectedPreset?.name || initialName || DEFAULT_PRESET_NAME;this.presets = clonePlain(store.globalPresets).map(preset => ({...preset,+ _originalName: preset.name,_key: nextPresetKey++,}));+ this.selectedKey = this.presets.find(p => p.name === selectedName)?._key+ ?? this.presets.find(p => p.name === DEFAULT_PRESET_NAME)?._key+ ?? this.presets[0]?._key+ ?? null;},async resetPresets() {if (!await store.resetGlobalPresets()) return;@@ -315,6 +404,7 @@ export const store = createStore("modelConfig", {headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ action: 'get' })});+ if (!res.ok) throw new Error(await res.text());const data = await res.json();this.globalPresets = this._normalizePresets(data.presets);} catch (e) {@@ -325,45 +415,75 @@ export const store = createStore("modelConfig", {},async saveGlobalPresets(presets) {+ const previousNames = this.globalPresets.map(p => String(p.name || '')).filter(Boolean);// Strip UI-only and globally-managed fields before savingconst clean = presets.map(p => {const c = { name: p.name };+ const isDefault = p._originalName === DEFAULT_PRESET_NAME;for (const slot of ['chat', 'utility']) {if (p[slot]) {- const rest = cleanPresetSlot(p[slot], true, slot);+ const rest = cleanPresetSlot(p[slot], true, slot, isDefault);if (hasModelIdentity(rest)) c[slot] = rest;}}if (p.embedding) {- const embedding = cleanPresetSlot(p.embedding, true, 'embedding');+ const embedding = cleanPresetSlot(p.embedding, true, 'embedding', isDefault);if (hasModelIdentity(embedding)) c.embedding = embedding;}return c;});+ const renames = presets+ .filter(p => p._originalName && p._originalName !== p.name)+ .map(p => ({ from: p._originalName, to: p.name }));try {- await fetchApi(`${API_BASE}/model_presets`, {+ const res = await fetchApi(`${API_BASE}/model_presets`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ action: 'save', presets: clean })+ body: JSON.stringify({ action: 'save', presets: clean, renames })});- this.globalPresets = presets;- this.switcherPresets = presets.filter(p => p.name);- justToast('Presets saved');+ if (!res.ok) throw new Error(await res.text());+ const data = await res.json();+ this.globalPresets = this._normalizePresets(data.presets || clean);+ const savedNames = new Set(this.globalPresets.map(p => p.name));+ this._lastPresetReferenceChanges = Object.fromEntries([+ ...previousNames+ .filter(name => !savedNames.has(name))+ .map(name => [name.toLowerCase(), DEFAULT_PRESET_NAME]),+ ...renames.map(rename => [String(rename.from).toLowerCase(), rename.to]),+ ]);+ this.modelsSummaryPreset = this.remapPresetName(this.modelsSummaryPreset);+ this.switcherConfiguredPreset = this.remapPresetName(this.switcherConfiguredPreset);+ this.switcherEffectivePreset = this.remapPresetName(this.switcherEffectivePreset);+ this.switcherPresets = this.globalPresets.filter(p => p.name);+ globalThis.justToast?.('Presets saved', 'success');+ return this.globalPresets;} catch (e) {console.error('Failed to save global presets:', e);- justToast('Failed to save presets');+ globalThis.justToast?.(e?.message || 'Failed to save presets', 'error');+ return false;}},async resetGlobalPresets() {+ const previousNames = this.globalPresets.map(p => String(p.name || '')).filter(Boolean);try {const res = await fetchApi(`${API_BASE}/model_presets`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ action: 'reset' })});+ if (!res.ok) throw new Error(await res.text());const data = await res.json();this.globalPresets = this._normalizePresets(data.presets);+ const savedNames = new Set(this.globalPresets.map(p => p.name));+ this._lastPresetReferenceChanges = Object.fromEntries(+ previousNames+ .filter(name => !savedNames.has(name))+ .map(name => [name.toLowerCase(), DEFAULT_PRESET_NAME])+ );+ this.modelsSummaryPreset = this.remapPresetName(this.modelsSummaryPreset);+ this.switcherConfiguredPreset = this.remapPresetName(this.switcherConfiguredPreset);+ this.switcherEffectivePreset = this.remapPresetName(this.switcherEffectivePreset);this.switcherPresets = this.globalPresets.filter(p => p.name);this._presetsLoaded = true;return true;@@ -376,9 +496,8 @@ export const store = createStore("modelConfig", {/*** Install hooks on the plugin settings context.- * - Load/reset: initialize UI-only model fields when the settings object changes.- * - Save: persist dirty API keys before the normal config save.- * - Reset: reload global presets when settings are reset to defaults.+ * Keep the generic plugin settings modal selection-only across scope changes,+ * saves, and resets.*/installSettingsHooks(context) {if (!context || context.__modelConfigHooksInstalled) return;@@ -394,16 +513,34 @@ export const store = createStore("modelConfig", {};}- const originalSave = context.save.bind(context);context.save = async () => {context.error = null;+ this.syncContextConfigFields(context);+ context.isSaving = true;try {- await this.persistApiKeysForConfig(context.settings);+ const res = await fetchApi(`${API_BASE}/model_presets`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ action: 'select',+ name: context.settings.model_preset,+ project_name: context.projectName || '',+ agent_profile: context.agentProfileKey || '',+ }),+ });+ if (!res.ok) {+ context.error = await res.text() || 'Save failed';+ return;+ }+ context.settingsSnapshotJson = context._toComparableJson(context.settings);+ const contextId = window.Alpine?.store('chats')?.selected || '';+ if (contextId) await this.refreshSwitcher(contextId);+ window.closeModal?.();} catch (e) {- context.error = e?.message || 'Failed to save API keys.';- return;+ context.error = e?.message || 'Save failed';+ } finally {+ context.isSaving = false;}- await originalSave();};const originalReset = context.resetToDefault.bind(context);@@ -412,7 +549,6 @@ export const store = createStore("modelConfig", {await originalReset();if (context.settings !== before) {this.syncContextConfigFields(context);- await this.resetGlobalPresets();}};@@ -466,12 +602,148 @@ export const store = createStore("modelConfig", {return { matched, rest };},+ presetModelRows(preset) {+ const chatP = this.chatProviders || [];+ const embedP = this.embeddingProviders || [];+ const label = (list, id) => (list.find(x => x.value === id) || {}).label || id || '\u2014';+ return [+ { icon: 'chat', title: 'Main', cfg: preset?.chat, pList: chatP },+ { icon: 'manufacturing', title: 'Utility', cfg: preset?.utility, pList: chatP },+ { icon: 'database', title: 'Embedding', cfg: preset?.embedding, pList: embedP },+ ].map(s => ({ icon: s.icon, title: s.title, provider: label(s.pList, s.cfg?.provider), name: s.cfg?.name || '\u2014' }));+ },++ getPreset(name) {+ return this.globalPresets.find(p => p.name === name)+ || this.globalPresets.find(p => p.name === DEFAULT_PRESET_NAME)+ || null;+ },++ remapPresetName(name) {+ const current = String(name || DEFAULT_PRESET_NAME);+ const renamed = this._lastPresetReferenceChanges[current.toLowerCase()];+ if (renamed && this.globalPresets.some(p => p.name === renamed)) return renamed;+ if (this.globalPresets.some(p => p.name === current)) return current;+ return DEFAULT_PRESET_NAME;+ },++ createScopedPresetSelector(context) {+ const store = this;+ return {+ context,+ loading: true,+ showScopedSettings: false,+ get presets() { return store.globalPresets; },+ get presetDescription() {+ const project = String(context?.projectName || '');+ const profile = String(context?.agentProfileKey || '');+ if (project && profile) return 'Default for this project and agent profile.';+ if (project) return 'Default for this project.';+ if (profile) return 'Default for this agent profile.';+ return 'Global default for all projects and agent profiles.';+ },+ get selectedPresetName() {+ return String(context?.settings?.model_preset || DEFAULT_PRESET_NAME);+ },+ get modelRows() { return store.presetModelRows(store.getPreset(this.selectedPresetName)); },+ async init() {+ this.loading = true;+ try {+ await store.ensureLoaded();+ await store.loadGlobalPresets();+ store.syncContextConfigFields(context, true);+ store.installSettingsHooks(context);+ } finally {+ this.loading = false;+ }+ },+ selectPreset(name) {+ context.settings.model_preset = name || DEFAULT_PRESET_NAME;+ },+ async editPresets() {+ await store.openPresetEditor(this.selectedPresetName);+ context.settings.model_preset = store.remapPresetName(this.selectedPresetName);+ },+ apiKeys() { return store.openApiKeysFromSummary(); },+ };+ },++ createGlobalPresetSelector() {+ const store = this;+ return {+ contextId: '',+ selectedPresetName: DEFAULT_PRESET_NAME,+ loading: true,+ presetDescription: 'Global default for new chats. Changing it also updates the open chat.',+ showScopedSettings: true,+ get presets() { return store.globalPresets; },+ get modelRows() { return store.presetModelRows(store.getPreset(this.selectedPresetName)); },+ async init(contextId = '') {+ this.contextId = String(contextId || '');+ this.loading = true;+ try {+ await store.ensureLoaded();+ const data = await store._fetchConfigData(+ this.contextId ? { context_id: this.contextId } : {}+ );+ store.globalPresets = store._normalizePresets(data.presets || []);+ store._presetsLoaded = true;+ this.selectedPresetName = data.selected_preset || data.configured_preset || DEFAULT_PRESET_NAME;+ } finally {+ this.loading = false;+ }+ },+ async selectPreset(name) {+ if (this.loading) return false;+ this.loading = true;+ try {+ const res = await fetchApi(`${API_BASE}/model_presets`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ action: 'select',+ name,+ context_id: this.contextId,+ }),+ });+ if (!res.ok) {+ const message = await res.text();+ globalThis.justToast?.(message || 'Failed to select model preset', 'error');+ return false;+ }+ const data = await res.json();+ this.selectedPresetName = data.selected_preset || name;+ store.modelsSummaryPreset = this.selectedPresetName;+ store.modelsSummary = this.modelRows;+ if (this.contextId) await store.refreshSwitcher(this.contextId);+ globalThis.justToast?.(`Model preset: ${this.selectedPresetName}`, 'success');+ return true;+ } catch (e) {+ console.error('Failed to select model preset:', e);+ globalThis.justToast?.(e?.message || 'Failed to select model preset', 'error');+ return false;+ } finally {+ this.loading = false;+ }+ },+ async editPresets() {+ await store.openPresetEditor(this.selectedPresetName, this.contextId);+ this.selectedPresetName = store.remapPresetName(this.selectedPresetName);+ },+ apiKeys() { return store.openApiKeysFromSummary(); },+ scopedSettings() { return store.openScopedPresetSettings(); },+ };+ },+// Model summary for agent-settings page- async loadModelsSummary() {- const data = await this._fetchConfigData();+ async loadModelsSummary(contextId = '') {+ await this.ensureLoaded();+ const data = await this._fetchConfigData(contextId ? { context_id: contextId } : {});const cfg = data.config || {};const chatP = data.chat_providers || [];const embedP = data.embedding_providers || [];+ this.globalPresets = this._normalizePresets(data.presets || this.globalPresets);+ this.modelsSummaryPreset = data.selected_preset || data.configured_preset || DEFAULT_PRESET_NAME;const label = (list, id) => (list.find(x => x.value === id) || {}).label || id || '\u2014';return [{ icon: 'chat', title: 'Main', cfg: cfg.chat_model, pList: chatP },@@ -480,13 +752,13 @@ export const store = createStore("modelConfig", {].map(s => ({ icon: s.icon, title: s.title, provider: label(s.pList, s.cfg?.provider), name: s.cfg?.name || '\u2014' }));},- async refreshModelsSummary() {+ async refreshModelsSummary(contextId = '') {if (this._modelsSummaryPromise) return await this._modelsSummaryPromise;this.modelsSummaryLoading = true;this._modelsSummaryPromise = (async () => {try {- const models = await this.loadModelsSummary();+ const models = await this.loadModelsSummary(contextId);this.modelsSummary = models;this._modelsSummaryLoaded = true;return models;@@ -512,6 +784,10 @@ export const store = createStore("modelConfig", {},async openConfigFromSummary() {+ return await this.openScopedPresetSettings();+ },++ async openScopedPresetSettings() {try {await pluginSettingsStore.openConfig('_model_config');} finally {@@ -520,7 +796,34 @@ export const store = createStore("modelConfig", {},async openPresetsFromSummary() {- await window.openModal?.('/plugins/_model_config/webui/main.html');+ await this.openPresetEditor(this.modelsSummaryPreset);+ },++ async openPresetEditor(name = DEFAULT_PRESET_NAME, contextId = '') {+ this.presetEditorInitialName = name || DEFAULT_PRESET_NAME;+ this._lastPresetReferenceChanges = {};+ if (contextId) await this.refreshSwitcher(contextId);+ this._presetEditorSelectionPinned = true;+ try {+ await window.openModal?.('/plugins/_model_config/webui/main.html');+ } finally {+ this._presetEditorSelectionPinned = false;+ }+ },++ async preparePresetEditor(contextId = '') {+ if (this._presetEditorSelectionPinned) return;+ try {+ const data = await this._fetchConfigData(+ contextId ? { context_id: contextId } : {}+ );+ this.presetEditorInitialName = data.selected_preset+ || data.configured_preset+ || DEFAULT_PRESET_NAME;+ } catch (e) {+ console.error('Failed to resolve the active model preset:', e);+ this.presetEditorInitialName = DEFAULT_PRESET_NAME;+ }},async openApiKeysFromSummary() {diff --git a/plugins/_model_config/webui/model-field.html b/plugins/_model_config/webui/model-field.htmlindex 2e30df718..ece344c21 100644--- a/plugins/_model_config/webui/model-field.html+++ b/plugins/_model_config/webui/model-field.html@@ -13,7 +13,7 @@modelType — 'chat' | 'utility' | 'embedding'providers — array of { value, label }searchType — 'chat' | 'embedding'- apiKeyMode — 'store' (config.html: key lives in $store.modelConfig.apiKeyValues) | 'inline' (preset: key lives in model.api_key)+ apiKeyMode — 'store' (key lives in $store.modelConfig.apiKeyValues), 'inline' (key lives in model.api_key), or 'none'Optional:providerFallback — fallback provider string for search/API key status (e.g. preset.chat.provider for utility slot)apiBaseFallback — fallback api_base string for search (e.g. preset.chat.api_base for utility slot)diff --git a/plugins/_model_config/webui/models-summary.html b/plugins/_model_config/webui/models-summary.htmlindex 0c4bd6940..9a1d11f76 100644--- a/plugins/_model_config/webui/models-summary.html+++ b/plugins/_model_config/webui/models-summary.html@@ -1,145 +1,48 @@<html>-<head>- <title>Model Configuration</title>-</head>--<body>+ <title>Models</title><script type="module">import { store } from "/plugins/_model_config/webui/model-config-store.js";</script>+</head>+<body><div x-data><template x-if="$store.modelConfig"><div>- <div class="section-title">Model Configuration</div>+ <div class="section-title">Models</div><div class="section-description">- AI models can be configured globally, per project, per agent and using quick-switch presets as well.+ Choose a global model preset. Project and agent-profile defaults are available in the full model settings.</div>- <!-- Read-only model config summary -->- <div x-init="$store.modelConfig.refreshModelsSummary()" class="model-summary">- <div class="model-summary-header">- <div class="field-title">Current Models</div>- <div class="field-description">Active model configuration resolved from global, project, and agent profile- scopes.</div>+ <div class="settings-model-preset"+ x-data="$store.modelConfig.createGlobalPresetSelector()"+ x-init="await init($store.chats?.selected || '')">+ <div x-show="loading" class="settings-model-loading">+ <span class="material-symbols-outlined spinning">progress_activity</span>+ Loading model preset...</div>- <div x-show="$store.modelConfig.modelsSummaryLoading" style="text-align:center; padding:12px;">- <span class="material-symbols-outlined spinning" style="font-size:18px;">progress_activity</span>+ <div x-show="!loading">+ <x-component path="/plugins/_model_config/webui/preset-overview.html"></x-component></div>- <template x-if="!$store.modelConfig.modelsSummaryLoading && $store.modelConfig.modelsSummary.length">- <div class="model-summary-grid">- <template x-for="m in $store.modelConfig.modelsSummary" :key="m.title">- <div class="model-summary-row">- <span class="material-symbols-outlined model-summary-icon" x-text="m.icon"></span>- <span class="model-summary-label" x-text="m.title"></span>- <span class="model-summary-value">- <span x-text="m.provider" style="opacity:0.6;"></span>- <span style="opacity:0.3; margin:0 4px;">/</span>- <span x-text="m.name"></span>- </span>- </div>- </template>- </div>- </template>- </div>-- <div style="display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px;">- <button class="btn btn-field" @click="$store.modelConfig.openConfigFromSummary()">- Configure Models- </button>- <button class="btn btn-field" @click="$store.modelConfig.openPresetsFromSummary()">- Configure Presets- </button>- <button class="btn btn-field" @click="$store.modelConfig.openApiKeysFromSummary()">- Configure API Keys- </button></div>-</div></template></div><style>- .model-summary {- margin-top: 14px;- }-- .model-summary-header {- margin-bottom: 8px;- }-- .model-summary-grid {- display: flex;- flex-direction: column;- background: var(--color-input);- /* border: 1px solid var(--color-border);- border-radius: 8px; */- /* padding: 0.75em 1em; */- max-width: 100%;- overflow: hidden;- box-sizing: border-box;+ .settings-model-preset {+ margin-top: 1rem;}- .model-summary-row {+ .settings-model-loading {display: flex;align-items: center;- gap: 8px;- padding: 9px 14px;- font-size: 0.82rem;- min-width: 0;- }-- .model-summary-row:not(:last-child) {- border-bottom: 1px solid var(--color-border);- }-- .model-summary-icon {- font-size: 16px;- opacity: 0.45;- flex-shrink: 0;- }-- .model-summary-label {- width: 80px;- flex-shrink: 0;- font-weight: 500;- opacity: 0.7;- }-- .model-summary-value {- flex: 1;- min-width: 0;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- @media (max-width: 600px) {- .model-summary-grid {- padding: 0.5em 0.5em;- }-- .model-summary-row {- flex-wrap: wrap;- padding: 8px 8px;- gap: 4px;- }-- .model-summary-label {- width: auto;- }-- .model-summary-value {- width: 100%;- flex-basis: 100%;- padding-left: 24px;- font-size: 0.78rem;- white-space: normal;- word-break: break-all;- }+ justify-content: center;+ gap: 0.5rem;+ min-height: 7rem;+ color: var(--color-text-secondary);}</style></body>-</html>diff --git a/plugins/_model_config/webui/preset-overview.html b/plugins/_model_config/webui/preset-overview.htmlnew file mode 100644index 000000000..893489376--- /dev/null+++ b/plugins/_model_config/webui/preset-overview.html@@ -0,0 +1,139 @@+<html>+<body>+ <div class="model-preset-widget">+ <label class="model-preset-picker">+ <span>+ <span class="field-title">Model preset</span>+ <span class="field-description" x-text="presetDescription || 'Choose the models Agent Zero should use.'"></span>+ </span>+ <select :value="selectedPresetName"+ @change="selectPreset($el.value)"+ :disabled="loading">+ <template x-for="preset in presets" :key="preset.name">+ <option :value="preset.name" x-text="preset.name"></option>+ </template>+ </select>+ </label>++ <div class="model-preset-rows" aria-live="polite">+ <template x-for="model in modelRows" :key="model.title">+ <div class="model-preset-row">+ <span class="material-symbols-outlined model-preset-icon" x-text="model.icon"></span>+ <span class="model-preset-role" x-text="model.title"></span>+ <span class="model-preset-identity">+ <span class="model-preset-provider" x-text="model.provider"></span>+ <span class="model-preset-separator">/</span>+ <span x-text="model.name"></span>+ </span>+ </div>+ </template>+ </div>++ <div class="model-preset-actions">+ <button type="button" class="button" @click="editPresets()">+ <span class="icon material-symbols-outlined">tune</span>+ Edit Presets+ </button>+ <button type="button" class="button" @click="apiKeys()">+ <span class="icon material-symbols-outlined">key</span>+ API Keys+ </button>+ <button type="button" class="button" x-show="showScopedSettings" @click="scopedSettings()">+ <span class="icon material-symbols-outlined">account_tree</span>+ Per-project / agent+ </button>+ </div>+ </div>++ <style>+ .model-preset-widget {+ display: flex;+ flex-direction: column;+ gap: 0.85rem;+ }++ .model-preset-picker {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(13rem, 18rem);+ align-items: center;+ gap: 1rem;+ margin: 0;+ }++ .model-preset-picker select {+ width: 100%;+ min-width: 0;+ }++ .model-preset-rows {+ overflow: hidden;+ border: 1px solid var(--color-border);+ border-radius: 8px;+ background: var(--color-input);+ }++ .model-preset-row {+ display: grid;+ grid-template-columns: 1.25rem 5.5rem minmax(0, 1fr);+ align-items: center;+ gap: 0.5rem;+ min-width: 0;+ padding: 0.65rem 0.8rem;+ font-size: 0.82rem;+ }++ .model-preset-row + .model-preset-row {+ border-top: 1px solid var(--color-border);+ }++ .model-preset-icon,+ .model-preset-provider,+ .model-preset-separator {+ opacity: 0.5;+ }++ .model-preset-icon {+ font-size: 1rem;+ }++ .model-preset-role {+ font-weight: 600;+ opacity: 0.75;+ }++ .model-preset-identity {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .model-preset-separator {+ margin: 0 0.25rem;+ }++ .model-preset-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ }++ @media (max-width: 640px) {+ .model-preset-picker {+ grid-template-columns: 1fr;+ gap: 0.5rem;+ }++ .model-preset-row {+ grid-template-columns: 1.25rem 4.5rem minmax(0, 1fr);+ padding: 0.6rem;+ }++ .model-preset-actions .button {+ flex: 1 1 auto;+ justify-content: center;+ }+ }+ </style>+</body>+</html>diff --git a/plugins/_model_config/webui/switcher-mixin.js b/plugins/_model_config/webui/switcher-mixin.jsindex d1fda99c9..6f0fccb16 100644--- a/plugins/_model_config/webui/switcher-mixin.js+++ b/plugins/_model_config/webui/switcher-mixin.js@@ -13,15 +13,18 @@ function normalizeModelIdentity(value) {return { provider, name };}-function formatModelIdentity(value) {- if (!value) return "";- if (value.provider && value.name) return `${value.provider}/${value.name}`;- return value.name || value.provider || "";+export function getModelLeafName(value) {+ const name = String(typeof value === "string" ? value : value?.name || "").trim();+ if (!name) return "";+ const leaf = name.slice(name.lastIndexOf("/") + 1).trim();+ return leaf || name;}export const switcherState = {switcherAllowed: false,switcherOverride: null,+ switcherConfiguredPreset: "Default",+ switcherEffectivePreset: "Default",switcherPresets: [],switcherLoading: true,agentProfiles: [],@@ -58,7 +61,7 @@ export const switcherMethods = {},async loadSwitcherState(contextId) {- const result = { allowed: false, presets: [], override: null };+ const result = { allowed: false, presets: [], override: null, configuredPreset: "Default", effectivePreset: "Default" };try {await this.loadGlobalPresets();result.presets = this.globalPresets.filter(p => p.name);@@ -71,6 +74,8 @@ export const switcherMethods = {const overData = await overRes.json();result.allowed = !!overData.allowed;result.override = overData.override || null;+ result.configuredPreset = overData.configured_preset || "Default";+ result.effectivePreset = overData.effective_preset || result.configuredPreset;}} catch (e) {console.error("Model switcher load failed:", e);@@ -85,7 +90,8 @@ export const switcherMethods = {headers: { "Content-Type": "application/json" },body: JSON.stringify({ action: "set_preset", context_id: contextId, preset_name: presetName }),});- return !!(await res.json()).ok;+ const data = await res.json();+ return data?.ok ? data : null;} catch (e) {console.error("Failed to set preset override:", e);return false;@@ -99,7 +105,8 @@ export const switcherMethods = {headers: { "Content-Type": "application/json" },body: JSON.stringify({ action: "clear", context_id: contextId }),});- return !!(await res.json()).ok;+ const data = await res.json();+ return data?.ok ? data : null;} catch (e) {console.error("Failed to clear override:", e);return false;@@ -178,6 +185,7 @@ export const switcherMethods = {selectedContext.agent_profile = data.agent_profile || agentProfile;selectedContext.agent_profile_label = label;}+ await this.refreshSwitcher(contextId);window.justToast?.(`Agent profile: ${label}`, "success", 1600, "agent-profile-switch");return true;} catch (e) {@@ -208,6 +216,8 @@ export const switcherMethods = {this.switcherAllowed = state.allowed;this.switcherPresets = state.presets;this.switcherOverride = state.override;+ this.switcherConfiguredPreset = state.configuredPreset;+ this.switcherEffectivePreset = state.effectivePreset;} catch (e) {console.error('Model switcher refresh failed:', e);} finally {@@ -216,30 +226,41 @@ export const switcherMethods = {},async selectPresetSwitch(contextId, presetName) {- const ok = await this.setPresetOverride(contextId, presetName);- if (ok) this.switcherOverride = { preset_name: presetName };- return ok;+ const data = await this.setPresetOverride(contextId, presetName);+ if (data) {+ const selected = data.preset_name || presetName;+ this.switcherOverride = { preset_name: selected };+ this.switcherEffectivePreset = selected;+ }+ return !!data;},async clearOverrideSwitch(contextId) {- const ok = await this.clearOverride(contextId);- if (ok) this.switcherOverride = null;- return ok;+ const data = await this.clearOverride(contextId);+ if (data) {+ this.switcherOverride = null;+ this.switcherEffectivePreset = data.effective_preset || this.switcherConfiguredPreset || 'Default';+ }+ return !!data;},getSwitcherLabel() {const o = this.switcherOverride;- if (!o) return 'Default LLM';- if (o.preset_name) return o.preset_name;+ const presetName = this.switcherEffectivePreset || o?.preset_name || 'Default';+ const preset = this.getActivePreset();+ if (preset) {+ const mainModelName = getModelLeafName(preset.chat);+ return mainModelName ? `${presetName} ${mainModelName}` : presetName;+ }+ if (!o || o.preset_name) return presetName;const models = this.getCustomOverrideModels();- return formatModelIdentity(models.main) || formatModelIdentity(models.utility) || o.name || o.provider || 'Custom';+ const mainModelName = getModelLeafName(models.main);+ return mainModelName ? `Custom ${mainModelName}` : 'Custom';},getActivePreset() {- const o = this.switcherOverride;- if (!o || !o.preset_name) return null;- return this.switcherPresets.find(p => p.name === o.preset_name) || null;+ return this.switcherPresets.find(p => p.name === this.switcherEffectivePreset) || null;},getActiveModels() {@@ -248,6 +269,7 @@ export const switcherMethods = {return {main: normalizeModelIdentity(preset.chat),utility: normalizeModelIdentity(preset.utility),+ embedding: normalizeModelIdentity(preset.embedding),};}return this.getCustomOverrideModels();@@ -255,10 +277,11 @@ export const switcherMethods = {getCustomOverrideModels() {const o = this.switcherOverride;- if (!o || o.preset_name) return { main: null, utility: null };+ if (!o || o.preset_name) return { main: null, utility: null, embedding: null };return {main: normalizeModelIdentity(o.chat || o),utility: normalizeModelIdentity(o.utility),+ embedding: normalizeModelIdentity(o.embedding),};},};diff --git a/plugins/_onboarding/AGENTS.md b/plugins/_onboarding/AGENTS.mdindex 3bfcd8d2c..3bb1c400d 100644--- a/plugins/_onboarding/AGENTS.md+++ b/plugins/_onboarding/AGENTS.md@@ -14,6 +14,7 @@- Keep onboarding provider choices synchronized with model configuration and provider metadata.- Do not ask for or expose API keys outside approved settings/API flows.- Avoid blocking already-configured users with unnecessary onboarding prompts.+- Completion updates the selected global model preset (normally immutable-name `Default`); advanced setup opens that preset in the shared editor.## Work Guidancediff --git a/plugins/_onboarding/webui/onboarding-store.js b/plugins/_onboarding/webui/onboarding-store.jsindex 868781275..e02d049e8 100644--- a/plugins/_onboarding/webui/onboarding-store.js+++ b/plugins/_onboarding/webui/onboarding-store.js@@ -860,7 +860,8 @@ export const store = createStore("onboarding", {async openAdvancedSettings() {window.closeModal?.();- const { store: pluginSettingsStore } = await import("/components/plugins/plugin-settings-store.js");- await pluginSettingsStore.openConfig("_model_config");+ await modelConfigStore.openPresetEditor(+ this.config?.model_preset || "Default"+ );},});diff --git a/plugins/_telegram_integration/AGENTS.md b/plugins/_telegram_integration/AGENTS.mdindex b39f92ad0..3b36cb663 100644--- a/plugins/_telegram_integration/AGENTS.md+++ b/plugins/_telegram_integration/AGENTS.md@@ -17,6 +17,7 @@- Keep allowed-user, group-mode, project, model, and `/send` controls enforced.- Install Telegram dependencies into the framework runtime only when required.- Agent profile picker actions change the top-level chat profile and must preserve existing subordinate agent profiles.+- Model picker status shows the effective preset; clearing a chat override returns to its scoped preset rather than assuming `Default`.## Work Guidancediff --git a/plugins/_telegram_integration/helpers/command_ui.py b/plugins/_telegram_integration/helpers/command_ui.pyindex 50f20f75b..48b7e367e 100644--- a/plugins/_telegram_integration/helpers/command_ui.py+++ b/plugins/_telegram_integration/helpers/command_ui.py@@ -279,13 +279,14 @@ def _model_view(]current = context.get_data("chat_model_override")current_name = current.get("preset_name") if isinstance(current, dict) else ""- status = f"Current model: <b>{_html(current_name or 'Default')}</b>"+ effective_name = model_config.get_effective_preset_name(context.agent0)+ status = f"Current model: <b>{_html(effective_name)}</b>"if not model_config.is_chat_override_allowed(context.agent0):return status + "\nPer-chat model switching is disabled.", Noneif selected:status = "Model updated.\n" + status- rows = _paged_buttons("model", presets, page, current_name)- rows.append([{"text": "Default", "callback_data": "tg:model:clear"}])+ rows = _paged_buttons("model", presets, page, effective_name)+ rows.append([{"text": "Use scoped preset", "callback_data": "tg:model:clear"}])return status, {"inline_keyboard": rows}diff --git a/skills/a0-create-agent/AGENTS.md b/skills/a0-create-agent/AGENTS.mdindex bb455953b..7e988b93b 100644--- a/skills/a0-create-agent/AGENTS.md+++ b/skills/a0-create-agent/AGENTS.md@@ -14,6 +14,7 @@- Default new user profiles to `usr/agents/`, not bundled `agents/`.- Keep `agent.yaml`, prompt inheritance, tools, and extension guidance synchronized with profile loader behavior.- Do not encourage storing secrets or provider credentials in profiles.+- Optional profile `_model_config/config.json` files contain only an existing global `model_preset` selection; never generate copied model dictionaries or profile-local preset definitions.## Work Guidancediff --git a/skills/a0-create-agent/SKILL.md b/skills/a0-create-agent/SKILL.mdindex 4a31ef5ff..6d88103c7 100644--- a/skills/a0-create-agent/SKILL.md+++ b/skills/a0-create-agent/SKILL.md@@ -72,7 +72,7 @@ Recommended interview flow:- "Should it work more like a concise specialist, a rigorous researcher, a code-heavy implementer, or something else?"4. Ask about advanced options only when the user's request implies them:- custom output format- - profile-specific Main/Utility models+ - a profile-specific model preset- custom tools- lifecycle extensions- plugin/project scope@@ -141,14 +141,12 @@ Before writing files, produce exactly one valid JSON object in a fenced `json` b"llm_config": {"enabled": false,"path": "/a0/usr/agents/data-analyst/plugins/_model_config/config.json",- "source": "inherit_global",- "chat_model": null,- "utility_model": null,- "embedding_model": null,+ "source": "inherit_scoped",+ "model_preset": null,"notes": ["Do not put model settings in agent.yaml.",- "Only create this config file if the user wants profile-specific Main or Utility models.",- "Scoped _model_config config is not deep-merged; include a complete config with chat_model, utility_model, and embedding_model."+ "Only create this config file if the user wants this profile to select a specific global model preset.",+ "Scoped _model_config config stores only model_preset."]},"files": [@@ -183,7 +181,7 @@ Rules for the blueprint:- `profile.name` must be lowercase letters, numbers, hyphens, or underscores only.- `prompt_strategy.root_prompt_overrides` must list any inherited root `/prompts` files being considered or replaced and why.- If a root prompt override is only a possibility, list it in `prompt_strategy` but do not add it to `files` until confirmed.-- `llm_config.enabled` controls whether a profile-scoped `_model_config/config.json` file is created. Keep it `false` when models should inherit from global/project settings.+- `llm_config.enabled` controls whether a profile-scoped `_model_config/config.json` file is created. Keep it `false` when the preset should inherit from broader project/global settings.- `files[*].content` must be the exact file content to write.- Include only files that should actually be created.- Set `status` to `draft` until all required choices are known; set it to `ready` only after resolving open questions.@@ -203,7 +201,7 @@ The blueprint must contain these required profile inputs:| **context** | instructions telling the *superior* agent when to delegate to this profile | `Use this agent for data analysis tasks, creating visualizations, statistical analysis, and working with datasets in Python.` |> [!NOTE]-> `agent.yaml` has **only** these three content fields (`title`, `description`, `context`). Do not add model, temperature, or `allowed_tools` fields to `agent.yaml`. Profile-specific model settings live in a companion `_model_config` plugin config file, and tool availability is controlled by plugin activation.+> `agent.yaml` has **only** these three content fields (`title`, `description`, `context`). Do not add model, temperature, or `allowed_tools` fields to `agent.yaml`. A profile-specific preset selection lives in a companion `_model_config` plugin config file, and tool availability is controlled by plugin activation.---@@ -232,9 +230,9 @@ A profile with only `agent.yaml` is valid — it inherits everything from `defau----## Step 4: Optional profile-specific LLM config+## Step 4: Optional profile-specific model preset-Agent Zero does **not** read Main/Utility model settings from `agent.yaml`. The `_model_config` plugin is always enabled and supports per-agent-profile config. If the user wants this profile to use specific LLMs, create a companion config file:+Agent Zero does **not** read model settings from `agent.yaml`. The `_model_config` plugin is always enabled and supports per-agent-profile preset selection. If the user wants this profile to use a specific existing global preset, create a companion config file:| Profile scope | Model config path ||---|---|@@ -242,54 +240,21 @@ Agent Zero does **not** read Main/Utility model settings from `agent.yaml`. The| Plugin-distributed profile | `/a0/usr/plugins/<plugin>/agents/<profile>/plugins/_model_config/config.json` || Project-scoped profile | `<project>/.a0proj/agents/<profile>/plugins/_model_config/config.json` |-Scoped `_model_config/config.json` files are selected as a whole; they are **not** deep-merged with broader global/project config. Therefore, if you create this file, include a complete effective model config. When the user only wants to customize Main or Utility, copy the other sections from the current effective config.+Scoped `_model_config/config.json` files contain only the selected global preset name. Preset definitions are managed centrally in Model Configuration and are not copied into profiles.-Minimal complete profile-scoped config:+Profile-scoped selection:```json{- "allow_chat_override": true,- "chat_model": {- "provider": "openrouter",- "name": "anthropic/claude-sonnet-4.6",- "api_base": "",- "ctx_length": 200000,- "ctx_history": 0.7,- "vision": true,- "rl_requests": 0,- "rl_input": 0,- "rl_output": 0,- "kwargs": {}- },- "utility_model": {- "provider": "openrouter",- "name": "openai/gpt-5.4-mini",- "api_base": "",- "ctx_length": 128000,- "ctx_input": 0.7,- "rl_requests": 0,- "rl_input": 0,- "rl_output": 0,- "kwargs": {}- },- "embedding_model": {- "provider": "huggingface",- "name": "sentence-transformers/all-MiniLM-L6-v2",- "api_base": "",- "rl_requests": 0,- "rl_input": 0,- "kwargs": {}- }+ "model_preset": "Research"}```Rules:-- Ask the user whether Main/Utility should inherit defaults or be profile-specific.-- Do not store API keys in this file; API keys are managed globally through settings/secrets.-- Include `chat_model`, `utility_model`, and `embedding_model` in the generated file if any profile-scoped model config is created.-- If only Main or Utility is customized, copy the non-customized model sections from the current effective `_model_config` config.-- Use provider IDs and model names exactly as `_model_config` expects.+- Ask whether the profile should inherit its scoped preset or select an existing global preset.+- Verify the preset exists before adding the file. If new model choices are needed, create a global preset through Model Configuration first.+- Do not store API keys or model dictionaries in this file; API keys and preset definitions are managed centrally.- Add this file to `files` only when `llm_config.enabled` is `true`.---@@ -446,7 +411,7 @@ Copy this shape when in doubt — it demonstrates every customization surface a- [ ] Confirmed profile scope (user / plugin / project)- [ ] Produced and confirmed `agent_zero.agent_profile_blueprint.v1` JSON-- [ ] Confirmed whether Main/Utility models inherit defaults or need `_model_config/config.json`+- [ ] Confirmed whether the model preset inherits or needs a profile-specific `_model_config/config.json` selection- [ ] Directory name is unique and matches allowed characters- [ ] `agent.yaml` contains exactly `title`, `description`, `context`- [ ] Prompt overrides only include files that actually change behaviordiff --git a/tests/test_model_config_api_keys.py b/tests/test_model_config_api_keys.pyindex ddd09f31c..8f764a2ea 100644--- a/tests/test_model_config_api_keys.py+++ b/tests/test_model_config_api_keys.py@@ -107,7 +107,7 @@ async def test_missing_api_key_banner_exposes_missing_providers(monkeypatch):assert "onboarding-banner-btn-container" not in row["html"]-def test_model_config_frontend_tracks_inline_api_key_edits():+def test_model_config_frontend_tracks_provider_api_key_edits():store_path = PROJECT_ROOT / "plugins" / "_model_config" / "webui" / "model-config-store.js"api_keys_mixin_path = PROJECT_ROOT / "plugins" / "_model_config" / "webui" / "api-keys-mixin.js"model_gate_path = PROJECT_ROOT / "webui" / "components" / "chat" / "model-gate-store.js"@@ -121,10 +121,15 @@ def test_model_config_frontend_tracks_inline_api_key_edits():+ api_keys_mixin_path.read_text(encoding="utf-8"))model_gate_content = model_gate_path.read_text(encoding="utf-8")+ preset_modal_content = (+ PROJECT_ROOT / "plugins" / "_model_config" / "webui" / "main.html"+ ).read_text(encoding="utf-8")config_content = (config_path.read_text(encoding="utf-8")+ "\n"+ model_field_path.read_text(encoding="utf-8")+ + "\n"+ + preset_modal_content)modal_content = modal_path.read_text(encoding="utf-8")@@ -135,8 +140,12 @@ def test_model_config_frontend_tracks_inline_api_key_edits():assert 'callJsonApi("/plugins/_model_config/model_config_get"' in model_gate_contentassert "dispatchPendingIfConfigured()" in model_gate_contentassert "/plugins/_model_config/missing_api_key_status" not in model_gate_content- assert "$store.modelConfig.resetApiKeyDrafts();" in config_contentassert '@input="$store.modelConfig.setApiKeyValue(_prov, $el.value)"' in config_content+ assert "apiKeyMode: 'none'" not in preset_modal_content+ assert preset_modal_content.count("apiKeyMode: 'store'") == 3+ assert "$store.modelConfig.resetApiKeyDrafts();" in preset_modal_content+ assert "await $store.modelConfig.refreshApiKeyStatus();" in preset_modal_content+ assert "await store.persistAllDirtyApiKeys();" in store_contentassert "persistAllDirtyApiKeys()" in modal_contentassert "$store.modelConfig.resetApiKeyDrafts();" in modal_content@@ -166,14 +175,30 @@ def test_model_switcher_frontend_renders_custom_overrides():)switcher_content = switcher_path.read_text(encoding="utf-8")+ switcher_html = (+ PROJECT_ROOT+ / "plugins"+ / "_model_config"+ / "extensions"+ / "webui"+ / "chat-input-progress-start"+ / "model-switcher.html"+ ).read_text(encoding="utf-8")refresh_extension_content = refresh_extension_path.read_text(encoding="utf-8")assert "function normalizeModelIdentity(value)" in switcher_content- assert "formatModelIdentity(models.main)" in switcher_content- assert "formatModelIdentity(models.utility)" in switcher_content+ assert "export function getModelLeafName(value)" in switcher_content+ assert 'name.lastIndexOf("/") + 1' in switcher_content+ assert "`${presetName} ${mainModelName}`" in switcher_content+ assert "formatModelIdentity(models.utility)" not in switcher_contentassert "normalizeModelIdentity(o.chat || o)" in switcher_contentassert "normalizeModelIdentity(o.utility)" in switcher_content+ assert "$store.modelConfig.getSwitcherLabel()" in switcher_html+ assert "model-switcher-active-pills" not in switcher_html+ assert "model-pill-role" not in switcher_htmlassert "_model_config_override_revision" in refresh_extension_content+ assert "activeContext?.agent_profile" in refresh_extension_content+ assert "activeContext?.project" in refresh_extension_contentassert "modelConfigStore.refreshSwitcher(contextId)" in refresh_extension_content@@ -385,12 +410,15 @@ def test_model_config_migration_repairs_saved_venice_user_slots(monkeypatch, tmpconfig = json.loads(config_path.read_text(encoding="utf-8"))presets = yaml.safe_load(presets_path.read_text(encoding="utf-8"))- assert config["chat_model"]["kwargs"] == expected- assert config["embedding_model"]["kwargs"] == expected- assert config["utility_model"]["kwargs"] == {"a0_api_mode": "responses"}+ assert config == {"model_preset": "Default"}+ assert presets[0]["name"] == "Default"assert presets[0]["chat"]["kwargs"] == expected- assert presets[0]["utility"]["kwargs"] == {"keep": True}- assert presets[1]["kwargs"] == expected+ assert presets[0]["embedding"]["kwargs"] == expected+ assert presets[0]["utility"]["kwargs"] == {"a0_api_mode": "responses"}+ assert presets[1]["chat"]["kwargs"] == expected+ assert presets[1]["utility"]["kwargs"] == {"keep": True}+ assert presets[2]["chat"]["kwargs"] == expected+ assert (plugin_dir / "config.json.pre-unified-presets.bak").exists()def test_local_chat_providers_default_to_chat_completions():diff --git a/tests/test_model_config_project_presets.py b/tests/test_model_config_project_presets.pyindex 8142efd49..bb8c67045 100644--- a/tests/test_model_config_project_presets.py+++ b/tests/test_model_config_project_presets.py@@ -7,6 +7,7 @@ import typesfrom pathlib import Pathimport pytest+import yamlfrom flask import Flask@@ -79,30 +80,29 @@ def _prepare_a0_tree(monkeypatch, tmp_path: Path):"name: _model_config\nper_project_config: true\nper_agent_config: true\n",encoding="utf-8",)- (plugin_dir / "default_presets.yaml").write_text(+ fallback_path = plugin_dir / "mode_presets_fallback.yaml"+ fallback_path.write_text("""-- name: Default Balance+- name: Defaultchat:provider: openroutername: default-chatutility:provider: openroutername: default-utility+ embedding:+ provider: huggingface+ name: default-embedding+- name: Balance+ chat:+ provider: openrouter+ name: balanced-chat""".lstrip(),encoding="utf-8",)(plugin_dir / "default_config.yaml").write_text("""-allow_chat_override: true-chat_model:- provider: openrouter- name: configured-chat-utility_model:- provider: openrouter- name: configured-utility-embedding_model:- provider: huggingface- name: configured-embedding+model_preset: Default""".lstrip(),encoding="utf-8",)@@ -242,15 +242,16 @@ class ProjectConflictLoader(Extension):_clear_runtime_caches()-def test_global_presets_keep_legacy_default_and_save_behavior(monkeypatch, tmp_path):+def test_global_presets_require_immutable_default_and_save_behavior(monkeypatch, tmp_path):_prepare_a0_tree(monkeypatch, tmp_path)from plugins._model_config.helpers import model_config- assert model_config.get_presets()[0]["name"] == "Default Balance"+ assert model_config.get_presets()[0]["name"] == "Default"model_config.save_presets([+ model_config.get_presets()[0],{"name": "Global One","scope": "project",@@ -261,63 +262,126 @@ def test_global_presets_keep_legacy_default_and_save_behavior(monkeypatch, tmp_p)presets = model_config.get_presets()- assert presets == [- {"name": "Global One", "chat": {"provider": "openai", "name": "gpt-test"}}- ]+ assert presets[0]["name"] == "Default"+ assert presets[1] == {+ "name": "Global One",+ "chat": {"provider": "openai", "name": "gpt-test"},+ }saved_path = tmp_path / "usr" / "plugins" / "_model_config" / "presets.yaml"assert "scope:" not in saved_path.read_text(encoding="utf-8")- model_config.save_presets([])- assert model_config.get_presets() == []+ with pytest.raises(ValueError, match="cannot be deleted or renamed"):+ model_config.save_presets([])- assert model_config.reset_presets()[0]["name"] == "Default Balance"+ assert model_config.reset_presets()[0]["name"] == "Default"-def test_project_presets_are_separate_and_resolve_by_scope(monkeypatch, tmp_path):+def test_project_scope_selects_global_presets_only(monkeypatch, tmp_path):_prepare_a0_tree(monkeypatch, tmp_path)- from helpers import projects+ from helpers import projects, pluginsfrom plugins._model_config.helpers import model_configprojects.create_project("demo", {"title": "Demo"})- model_config.save_presets(- [{"name": "Shared", "chat": {"provider": "global", "name": "chat"}}]- )- model_config.save_presets(- [{"name": "Shared", "chat": {"provider": "project", "name": "chat"}}],- project_name="demo",- )+ plugins.save_plugin_config("_model_config", "demo", "", {"model_preset": "Balance"})- assert model_config.get_presets()[0]["chat"]["provider"] == "global"- assert model_config.get_project_presets("demo")[0]["chat"]["provider"] == "project"+ assert model_config.get_configured_preset_name(project_name="demo") == "Balance"+ assert model_config.resolve_preset("Balance", scope="global")["chat"]["name"] == "balanced-chat"+ assert model_config.resolve_preset("Balance", scope="project", project_name="demo") is None+ with pytest.raises(ValueError, match="no longer supported"):+ model_config.save_presets(model_config.get_presets(), project_name="demo")- combined = model_config.get_combined_presets("demo")- assert [(item["scope"], item["project_name"], item["name"]) for item in combined] == [- ("global", "", "Shared"),- ("project", "demo", "Shared"),- ]- assert model_config.resolve_preset("Shared", scope="global")["chat"]["provider"] == "global"- assert (- model_config.resolve_preset("Shared", scope="project", project_name="demo")["chat"]["provider"]- == "project"++def test_selected_preset_resolves_complete_runtime_config_from_default(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from helpers import plugins+ from plugins._model_config.helpers import model_config++ plugins.save_plugin_config("_model_config", "", "", {"model_preset": "Balance"})+ config = model_config.get_config()++ assert config["model_preset"] == "Balance"+ assert config["chat_model"]["name"] == "balanced-chat"+ assert config["utility_model"]["name"] == "default-utility"+ assert config["embedding_model"]["name"] == "default-embedding"+ assert config["allow_chat_override"] is True+++def test_legacy_raw_preset_is_preserved_as_canonical_chat_slot(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.helpers import model_config++ cleaned = model_config.clean_presets_for_file(+ [+ {+ "name": "Legacy",+ "provider": "venice",+ "api_key": "must-not-persist",+ "kwargs": {"temperature": 0.2},+ }+ ])+ assert cleaned == [+ {+ "name": "Legacy",+ "chat": {+ "provider": "venice",+ "kwargs": {"temperature": 0.2},+ "name": "Legacy",+ },+ }+ ]-def test_bundled_utility_presets_inherit_advanced_settings():- import yaml- presets_path = PROJECT_ROOT / "plugins" / "_model_config" / "default_presets.yaml"- presets = yaml.safe_load(presets_path.read_text(encoding="utf-8"))+def test_fallback_non_default_utility_presets_inherit_advanced_settings():+ from plugins._model_config.helpers import model_config++ presets_path = (+ PROJECT_ROOT / "plugins" / "_model_config" / "mode_presets_fallback.yaml"+ )+ presets = model_config.parse_preset_collection(+ presets_path.read_text(encoding="utf-8")+ )++ assert {+ preset["name"]: (+ preset["chat"]["name"],+ preset["utility"]["name"],+ preset["chat"]["vision"],+ )+ for preset in presets+ } == {+ "Default": (+ "openai/gpt-5.6-terra",+ "google/gemini-3.1-flash-lite",+ True,+ ),+ "Efficiency": (+ "z-ai/glm-5.2",+ "deepseek/deepseek-v4-flash",+ False,+ ),+ "Power": (+ "openai/gpt-5.6-sol",+ "openai/gpt-5.6-luna",+ True,+ ),+ }for preset in presets:+ if preset.get("name") == "Default":+ continueutility = preset.get("utility") or {}assert "ctx_length" not in utilityassert "ctx_input" not in utility@pytest.mark.asyncio-async def test_model_presets_api_returns_global_or_combined_by_project(monkeypatch, tmp_path):+async def test_model_presets_api_returns_global_presets_for_project_scope(monkeypatch, tmp_path):_prepare_a0_tree(monkeypatch, tmp_path)from helpers import projects@@ -325,29 +389,405 @@ async def test_model_presets_api_returns_global_or_combined_by_project(monkeypatfrom plugins._model_config.helpers import model_configprojects.create_project("demo", {"title": "Demo"})- model_config.save_presets(- [{"name": "Global", "chat": {"provider": "global", "name": "chat"}}]- )- model_config.save_presets(- [{"name": "Project", "chat": {"provider": "project", "name": "chat"}}],- project_name="demo",- )+ presets = model_config.get_presets()+ presets.append({"name": "Global", "chat": {"provider": "global", "name": "chat"}})+ model_config.save_presets(presets)handler = ModelPresets(Flask(__name__), threading.Lock())global_response = await handler.process({"action": "get"}, None)- assert global_response["presets"] == [- {"name": "Global", "chat": {"provider": "global", "name": "chat"}}+ assert [preset["name"] for preset in global_response["presets"]] == [+ "Default",+ "Balance",+ "Global",]- assert "scope" not in global_response["presets"][0]project_response = await handler.process({"action": "get", "project_name": "demo"}, None)- assert [(p["scope"], p["name"]) for p in project_response["presets"]] == [- ("global", "Global"),- ("project", "Project"),+ assert [p["name"] for p in project_response["presets"]] == [+ "Default",+ "Balance",+ "Global",+ ]+ assert project_response["project_presets"] == []+++async def test_model_presets_api_saves_only_scoped_selection(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from helpers import projects+ from plugins._model_config.api.model_presets import ModelPresets++ projects.create_project("demo", {"title": "Demo"})+ handler = ModelPresets(Flask(__name__), threading.Lock())++ response = await handler.process(+ {+ "action": "select",+ "name": "Balance",+ "project_name": "demo",+ },+ None,+ )++ assert response == {"ok": True, "selected_preset": "Balance"}+ config_path = (+ tmp_path+ / "usr"+ / "projects"+ / "demo"+ / ".a0proj"+ / "plugins"+ / "_model_config"+ / "config.json"+ )+ assert json.loads(config_path.read_text(encoding="utf-8")) == {+ "model_preset": "Balance"+ }+++def test_unified_preset_migration_preserves_global_and_scoped_configs(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from helpers import projects+ from plugins._model_config.extensions.python.startup_migration._10_migrate_model_config import (+ MigrateModelConfig,+ )++ global_dir = tmp_path / "usr" / "plugins" / "_model_config"+ global_dir.mkdir(parents=True, exist_ok=True)+ global_config = {+ "chat_model": {"provider": "openrouter", "name": "legacy-global-chat"},+ "utility_model": {"provider": "openrouter", "name": "legacy-global-utility"},+ "embedding_model": {"provider": "huggingface", "name": "legacy-global-embedding"},+ }+ (global_dir / "config.json").write_text(json.dumps(global_config), encoding="utf-8")+ (global_dir / "presets.yaml").write_text(+ "- name: Existing\n chat:\n provider: openrouter\n name: existing-chat\n",+ encoding="utf-8",+ )++ projects.create_project("demo", {"title": "Demo"})+ project_config_path = (+ tmp_path+ / "usr"+ / "projects"+ / "demo"+ / ".a0proj"+ / "plugins"+ / "_model_config"+ / "config.json"+ )+ project_config_path.parent.mkdir(parents=True, exist_ok=True)+ project_config_path.write_text(+ json.dumps(+ {+ "chat_model": {"provider": "anthropic", "name": "project-chat"},+ "utility_model": {"provider": "openrouter", "name": "project-utility"},+ "embedding_model": {"provider": "openai", "name": "project-embedding"},+ }+ ),+ encoding="utf-8",+ )++ migration = MigrateModelConfig(agent=None)+ migration.execute()++ presets = yaml.safe_load((global_dir / "presets.yaml").read_text(encoding="utf-8"))+ assert [preset["name"] for preset in presets] == [+ "Default",+ "Existing",+ "Project demo",+ ]+ assert presets[0]["chat"]["name"] == "legacy-global-chat"+ assert presets[2]["embedding"]["name"] == "project-embedding"+ assert json.loads((global_dir / "config.json").read_text(encoding="utf-8")) == {+ "model_preset": "Default"+ }+ assert json.loads(project_config_path.read_text(encoding="utf-8")) == {+ "model_preset": "Project demo"+ }+ assert Path(str(project_config_path) + ".pre-unified-presets.bak").exists()++ before = (global_dir / "presets.yaml").read_text(encoding="utf-8")+ migration.execute()+ assert (global_dir / "presets.yaml").read_text(encoding="utf-8") == before+++def test_unified_preset_migration_repairs_partial_legacy_default(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.extensions.python.startup_migration._10_migrate_model_config import (+ MigrateModelConfig,+ )++ global_dir = tmp_path / "usr" / "plugins" / "_model_config"+ global_dir.mkdir(parents=True, exist_ok=True)+ (global_dir / "config.json").write_text(+ json.dumps(+ {+ "chat_model": {+ "provider": "anthropic",+ "name": "legacy-chat",+ }+ }+ ),+ encoding="utf-8",+ )++ MigrateModelConfig(agent=None).execute()++ presets = yaml.safe_load((global_dir / "presets.yaml").read_text(encoding="utf-8"))+ default = presets[0]+ assert default["name"] == "Default"+ assert default["chat"]["name"] == "legacy-chat"+ assert default["utility"]["name"] == "default-utility"+ assert default["embedding"]["name"] == "default-embedding"+++def test_unified_preset_migration_recovers_malformed_user_files(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.extensions.python.startup_migration._10_migrate_model_config import (+ MigrateModelConfig,+ )++ global_dir = tmp_path / "usr" / "plugins" / "_model_config"+ global_dir.mkdir(parents=True, exist_ok=True)+ config_path = global_dir / "config.json"+ presets_path = global_dir / "presets.yaml"+ config_path.write_text("{broken", encoding="utf-8")+ presets_path.write_text("not: [valid", encoding="utf-8")++ MigrateModelConfig(agent=None).execute()++ assert json.loads(config_path.read_text(encoding="utf-8")) == {+ "model_preset": "Default"+ }+ presets = yaml.safe_load(presets_path.read_text(encoding="utf-8"))+ assert presets[0]["name"] == "Default"+ assert Path(str(config_path) + ".pre-unified-presets.bak").exists()+ assert Path(str(presets_path) + ".pre-unified-presets.bak").exists()+++def test_new_instance_bootstraps_validated_remote_presets_once(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.extensions.python.startup_migration._10_migrate_model_config import (+ MigrateModelConfig,+ )+ from plugins._model_config.extensions.python.startup_migration import (+ _20_bootstrap_model_presets as bootstrap,+ )++ # The normal startup order runs legacy migration before initialization.+ MigrateModelConfig(agent=None).execute()++ remote_yaml = """+- name: Default+ chat:+ provider: openrouter+ name: openai/gpt-test+ api_key: must-not-persist+ utility:+ provider: openrouter+ name: openai/gpt-test-mini+ embedding:+ provider: huggingface+ name: sentence-transformers/test+- name: Efficiency+ chat:+ provider: openrouter+ name: vendor/efficient+- name: Power+ chat:+ provider: openrouter+ name: vendor/power+""".lstrip().encode()++ class Response:+ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ def read(self, _limit):+ return remote_yaml++ calls = []++ def urlopen(request, timeout):+ calls.append((request.full_url, timeout, request.headers.get("User-agent")))+ return Response()++ monkeypatch.setattr(bootstrap.urllib.request, "urlopen", urlopen)++ result = bootstrap.BootstrapModelPresets(agent=None).execute()++ presets_path = tmp_path / "usr" / "plugins" / "_model_config" / "presets.yaml"+ presets = yaml.safe_load(presets_path.read_text(encoding="utf-8"))+ assert result == "remote"+ assert [preset["name"] for preset in presets] == ["Default", "Efficiency", "Power"]+ assert "api_key" not in presets[0]["chat"]+ assert calls == [+ (+ bootstrap.REMOTE_PRESETS_URL,+ bootstrap.FETCH_TIMEOUT_SECONDS,+ "AgentZero-Model-Preset-Bootstrap",+ )]+ monkeypatch.setattr(+ bootstrap.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ AssertionError("bootstrap fetched more than once")+ ),+ )+ assert bootstrap.BootstrapModelPresets(agent=None).execute() == "existing"+++def test_remote_preset_failure_persists_local_fallback(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.extensions.python.startup_migration import (+ _20_bootstrap_model_presets as bootstrap,+ )++ monkeypatch.setattr(+ bootstrap.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("offline")),+ )++ result = bootstrap.BootstrapModelPresets(agent=None).execute()++ presets_path = tmp_path / "usr" / "plugins" / "_model_config" / "presets.yaml"+ presets = yaml.safe_load(presets_path.read_text(encoding="utf-8"))+ assert result == "fallback"+ assert [preset["name"] for preset in presets] == ["Default", "Balance"]+++def test_invalid_remote_preset_collection_uses_local_fallback(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.extensions.python.startup_migration import (+ _20_bootstrap_model_presets as bootstrap,+ )++ class Response:+ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ def read(self, _limit):+ return b"- name: Default\n chat: invalid\n"++ monkeypatch.setattr(+ bootstrap.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: Response(),+ )++ result = bootstrap.BootstrapModelPresets(agent=None).execute()++ presets_path = tmp_path / "usr" / "plugins" / "_model_config" / "presets.yaml"+ presets = yaml.safe_load(presets_path.read_text(encoding="utf-8"))+ assert result == "fallback"+ assert [preset["name"] for preset in presets] == ["Default", "Balance"]+++def test_remote_bootstrap_never_overwrites_existing_presets(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.extensions.python.startup_migration import (+ _20_bootstrap_model_presets as bootstrap,+ )++ presets_path = tmp_path / "usr" / "plugins" / "_model_config" / "presets.yaml"+ presets_path.parent.mkdir(parents=True, exist_ok=True)+ existing = "- name: Existing user preset\n"+ presets_path.write_text(existing, encoding="utf-8")+ monkeypatch.setattr(+ bootstrap.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ AssertionError("existing instances must not fetch")+ ),+ )++ result = bootstrap.BootstrapModelPresets(agent=None).execute()++ assert result == "existing"+ assert presets_path.read_text(encoding="utf-8") == existing+++def test_obsolete_bootstrap_marker_does_not_block_missing_presets(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.extensions.python.startup_migration import (+ _20_bootstrap_model_presets as bootstrap,+ )+ from plugins._model_config.helpers import model_config++ marker = tmp_path / "usr" / "plugins" / "_model_config" / "preset_bootstrap.json"+ marker.parent.mkdir(parents=True, exist_ok=True)+ marker.write_text('{"source":"remote"}', encoding="utf-8")+ monkeypatch.setattr(+ bootstrap.BootstrapModelPresets,+ "_download_presets",+ lambda _self: model_config._fallback_presets(),+ )++ result = bootstrap.BootstrapModelPresets(agent=None).execute()++ presets_path = marker.with_name("presets.yaml")+ assert result == "remote"+ assert presets_path.exists()+ assert [+ preset["name"]+ for preset in yaml.safe_load(presets_path.read_text(encoding="utf-8"))+ ] == ["Default", "Balance"]+++def test_preset_rename_updates_scopes_and_unloaded_chats(monkeypatch, tmp_path):+ _prepare_a0_tree(monkeypatch, tmp_path)++ from plugins._model_config.api import model_presets++ global_config = tmp_path / "usr" / "plugins" / "_model_config" / "config.json"+ global_config.parent.mkdir(parents=True, exist_ok=True)+ global_config.write_text(json.dumps({"model_preset": "Research"}), encoding="utf-8")++ chat_path = tmp_path / "usr" / "chats" / "chat-1" / "chat.json"+ chat_path.parent.mkdir(parents=True, exist_ok=True)+ chat_path.write_text(+ json.dumps(+ {+ "id": "chat-1",+ "data": {"chat_model_override": {"preset_name": "Research"}},+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(model_presets.AgentContext, "all", lambda *_args: [])++ model_presets._rename_preset_references(+ [{"from": "Research", "to": "Deep Research"}]+ )++ assert json.loads(global_config.read_text(encoding="utf-8")) == {+ "model_preset": "Deep Research"+ }+ chat = json.loads(chat_path.read_text(encoding="utf-8"))+ assert chat["data"]["chat_model_override"] == {+ "preset_name": "Deep Research"+ }+-def test_project_save_copies_selected_preset_to_scoped_model_config(monkeypatch, tmp_path):+def test_project_save_persists_only_selected_preset_reference(monkeypatch, tmp_path):_prepare_a0_tree(monkeypatch, tmp_path)from helpers import projects@@ -355,6 +795,7 @@ def test_project_save_copies_selected_preset_to_scoped_model_config(monkeypatch,model_config.save_presets([+ model_config.get_presets()[0],{"name": "Research","chat": {"provider": "anthropic", "name": "claude-research"},@@ -384,9 +825,7 @@ def test_project_save_copies_selected_preset_to_scoped_model_config(monkeypatch,/ "config.json")config = json.loads(config_path.read_text(encoding="utf-8"))- assert config["chat_model"]["name"] == "claude-research"- assert config["utility_model"]["name"] == "utility-research"- assert config["embedding_model"]["name"] == "configured-embedding"+ assert config == {"model_preset": "Research"}project_json = (tmp_path / "usr" / "projects" / "demo" / ".a0proj" / "project.json"@@ -416,35 +855,20 @@ def test_project_save_does_not_freeze_inherited_global_model_config()project_data = projects.load_edit_project_data("demo")- assert project_data["llm"]["config_scope"] == "inherited"assert project_data["llm"]["has_project_config"] is False- project_data["llm"].pop("config_scope")- project_data["llm"].pop("has_project_config")projects.update_project("demo", project_data)assert not config_path.exists()- plugins.save_plugin_config(- "_model_config",- "",- "",- {- "chat_model": {"provider": "openrouter", "name": "new-global-chat"},- "utility_model": {"provider": "openrouter", "name": "new-global-utility"},- "embedding_model": {- "provider": "huggingface",- "name": "new-global-embedding",- },- },- )+ plugins.save_plugin_config("_model_config", "", "", {"model_preset": "Balance"})reloaded_data = projects.load_edit_project_data("demo")- assert reloaded_data["llm"]["config_scope"] == "inherited"- assert reloaded_data["llm"]["config"]["chat_model"]["name"] == "new-global-chat"+ assert reloaded_data["llm"]["has_project_config"] is False+ assert reloaded_data["llm"]["selected_preset"]["name"] == "Balance"-def test_project_save_updates_existing_scoped_model_config(monkeypatch, tmp_path):+def test_project_save_updates_existing_scoped_preset_selection(monkeypatch, tmp_path):_prepare_a0_tree(monkeypatch, tmp_path)from helpers import plugins, projects@@ -454,16 +878,12 @@ def test_project_save_updates_existing_scoped_model_config(monkeypatch, tmp_path"_model_config","demo","",- {- "chat_model": {"provider": "openrouter", "name": "project-chat"},- "utility_model": {"provider": "openrouter", "name": "project-utility"},- "embedding_model": {"provider": "huggingface", "name": "project-embedding"},- },+ {"model_preset": "Default"},)project_data = projects.load_edit_project_data("demo")- assert project_data["llm"]["config_scope"] == "project"- project_data["llm"]["config"]["chat_model"]["name"] = "project-chat-updated"+ assert project_data["llm"]["has_project_config"] is True+ project_data["llm"]["selected_preset"]["name"] = "Balance"projects.update_project("demo", project_data)@@ -478,7 +898,7 @@ def test_project_save_updates_existing_scoped_model_config(monkeypatch, tmp_path/ "config.json")config = json.loads(config_path.read_text(encoding="utf-8"))- assert config["chat_model"]["name"] == "project-chat-updated"+ assert config == {"model_preset": "Balance"}def test_project_extended_data_supports_multiple_plugin_sections(@@ -513,7 +933,7 @@ def test_project_extended_data_supports_multiple_plugin_sections(}project_data = projects.load_edit_project_data("demo")- assert project_data["llm"]["config_scope"] == "inherited"+ assert project_data["llm"]["has_project_config"] is Falseassert project_data["extra"] == {"loaded_for": "demo", "enabled": True}project_data["extra"] = {"enabled": True, "note": "updated"}@@ -727,7 +1147,7 @@ def test_legacy_utility_preset_defaults_preserve_tuning_but_clear_kwargs(assert utility["kwargs"] == {}-def test_preset_override_preserves_configured_utility_context(monkeypatch, tmp_path):+def test_preset_override_preserves_default_preset_utility_context(monkeypatch, tmp_path):_prepare_a0_tree(monkeypatch, tmp_path)from plugins._model_config.helpers import model_config@@ -761,6 +1181,12 @@ def test_preset_override_preserves_configured_utility_context(monkeypatch, tmp_p"get_preset_by_name",lambda name, **kwargs: preset if name == "Fast" else None,)+ default_preset = model_config.config_to_preset(base_config, "Default")+ monkeypatch.setattr(+ model_config,+ "resolve_preset",+ lambda name, **kwargs: preset if name == "Fast" else default_preset if name == "Default" else None,+ )utility = model_config.get_utility_model_config(FakeAgent())@@ -769,55 +1195,21 @@ def test_preset_override_preserves_configured_utility_context(monkeypatch, tmp_passert utility["ctx_input"] == 0.4-def test_project_save_disambiguates_same_name_project_preset(monkeypatch, tmp_path):+def test_missing_scoped_preset_falls_back_to_default(monkeypatch, tmp_path):_prepare_a0_tree(monkeypatch, tmp_path)- from helpers import projects+ from helpers import plugins, projectsfrom plugins._model_config.helpers import model_config- model_config.save_presets(- [{"name": "Shared", "chat": {"provider": "global", "name": "chat"}}]- )- projects.create_project(+ projects.create_project("demo", {"title": "Demo"})+ plugins.save_plugin_config(+ "_model_config","demo",- {- "title": "Demo",- "llm": {- "selected_preset": {- "scope": "project",- "project_name": "demo",- "name": "Shared",- },- "project_presets": [- {"name": "Shared", "chat": {"provider": "project", "name": "chat"}}- ],- },- },+ "",+ {"model_preset": "Deleted"},)- config = json.loads(- (- tmp_path- / "usr"- / "projects"- / "demo"- / ".a0proj"- / "plugins"- / "_model_config"- / "config.json"- ).read_text(encoding="utf-8")- )- assert config["chat_model"]["provider"] == "project"-- presets_yaml = (- tmp_path- / "usr"- / "projects"- / "demo"- / ".a0proj"- / "plugins"- / "_model_config"- / "presets.yaml"- ).read_text(encoding="utf-8")- assert "scope:" not in presets_yaml- assert "project_name:" not in presets_yaml+ assert model_config.get_configured_preset_name(project_name="demo") == "Default"+ resolved = model_config.get_config(project_name="demo")+ assert resolved["model_preset"] == "Default"+ assert resolved["chat_model"]["name"] == "default-chat"diff --git a/tests/test_model_config_ui.py b/tests/test_model_config_ui.pyindex 0a6a02add..1feb61061 100644--- a/tests/test_model_config_ui.py+++ b/tests/test_model_config_ui.py@@ -11,29 +11,31 @@ def read(*parts: str) -> str:def test_model_config_text_buttons_have_shared_primitive() -> None:buttons_css = read("webui", "css", "buttons.css")preset_modal = read("plugins", "_model_config", "webui", "main.html")- config_modal = read("plugins", "_model_config", "webui", "config.html")+ overview = read("plugins", "_model_config", "webui", "preset-overview.html")assert ".text-button {" in buttons_cssassert "appearance: none;" in buttons_cssassert ".text-button:hover:not(:disabled)" in buttons_cssassert ".text-button .material-symbols-outlined" in buttons_css- assert 'class="text-button preset-add-btn"' in preset_modal- assert 'class="text-button preset-delete-btn"' in preset_modal- assert 'class="text-button"' in config_modal+ assert 'class="text-button"' in preset_modal+ assert 'class="model-preset-actions"' in overviewdef test_model_preset_rows_keep_stable_identity_after_middle_delete() -> None:preset_modal = read("plugins", "_model_config", "webui", "main.html")preset_store = read("plugins", "_model_config", "webui", "model-config-store.js")- assert 'x-data="$store.modelConfig.createPresetEditor()"' in preset_modal+ assert 'x-data="$store.modelConfig.createPresetEditor($store.modelConfig.presetEditorInitialName)"' in preset_modalassert ':key="preset._key"' in preset_modal- assert "createPresetEditor()" in preset_store+ assert 'x-model.number="selectedKey"' in preset_modal+ assert "createPresetEditor(initialName = '')" in preset_store+ assert "preparePresetEditor($store.chats?.selected || '')" in preset_modalassert "_key: nextPresetKey++" in preset_store- assert "removePreset(index)" in preset_store+ assert "removeSelectedPreset()" in preset_store+ assert "selectedKey" in preset_storeassert ':key="idx"' not in preset_modalassert "JSON.parse(JSON.stringify" not in preset_modal- assert "presets.splice" not in preset_modal+ assert "presets.splice" not in preset_storedef test_model_preset_editor_can_reset_to_bundled_defaults() -> None:@@ -41,11 +43,46 @@ def test_model_preset_editor_can_reset_to_bundled_defaults() -> None:preset_store = read("plugins", "_model_config", "webui", "model-config-store.js")assert '$confirmClick($event, () => resetPresets())' in preset_modal- assert "Reset to default" in preset_modal+ assert "Restore bundled presets" in preset_modalassert "async resetPresets()" in preset_storeassert "if (!await store.resetGlobalPresets()) return;" in preset_storeassert "this.refreshPresets();" in preset_store- assert "refreshPresets();" in preset_modal+++def test_default_preset_is_locked_and_shared_overview_is_reused() -> None:+ preset_modal = read("plugins", "_model_config", "webui", "main.html")+ config_modal = read("plugins", "_model_config", "webui", "config.html")+ settings_summary = read("plugins", "_model_config", "webui", "models-summary.html")+ helper = read("plugins", "_model_config", "helpers", "model_config.py")++ assert '<template x-if="canRenameSelected">' in preset_modal+ assert "get canRenameSelected()" in read(+ "plugins", "_model_config", "webui", "model-config-store.js"+ )+ assert "Default cannot be renamed or deleted." not in preset_modal+ assert ":readonly=" not in preset_modal+ assert "The Default preset cannot be deleted or renamed." in helper+ assert "preserveImplicitDefaults" in read(+ "plugins", "_model_config", "webui", "model-config-store.js"+ )+ component_path = "/plugins/_model_config/webui/preset-overview.html"+ assert component_path in config_modal+ assert component_path in settings_summary+ assert "Per-project / agent" in read(+ "plugins", "_model_config", "webui", "preset-overview.html"+ )+++def test_preset_editor_uses_standard_modal_footer_buttons() -> None:+ preset_modal = read("plugins", "_model_config", "webui", "main.html")+ api_keys_modal = read("plugins", "_model_config", "webui", "api-keys.html")++ for content in (preset_modal, api_keys_modal):+ assert '<div class="modal-footer" data-modal-footer>' in content+ assert 'class="btn btn-ok"' in content+ assert 'class="btn btn-cancel"' in content++ assert "preset-editor-footer" not in preset_modaldef test_plugin_settings_reset_is_explicit_and_does_not_capture_toast_early() -> None:diff --git a/tests/test_welcome_composer_static.py b/tests/test_welcome_composer_static.pyindex 0b54e6da3..9000f356d 100644--- a/tests/test_welcome_composer_static.py+++ b/tests/test_welcome_composer_static.py@@ -121,7 +121,7 @@ def test_welcome_composer_can_create_a_chat_before_sending() -> None:assert 'document.addEventListener("model-configured"' in gate_storeassert 'document.addEventListener("model-setup-changed"' in gate_storeassert "bypassModelGate: true" in gate_store- assert 'openPluginConfig("_model_config", "Advanced model configuration")' in gate_store+ assert "modelConfigStore.openPresetEditor(" in gate_storeassert 'openPluginConfig("_oauth"' not in gate_storeassert "Your message sends automatically once a model is connected." in gate_componentassert "openOnboarding('cloud')" in gate_componentdiff --git a/webui/components/chat/AGENTS.md b/webui/components/chat/AGENTS.mdindex d4104e929..6363a86b6 100644--- a/webui/components/chat/AGENTS.md+++ b/webui/components/chat/AGENTS.md@@ -22,7 +22,7 @@- Composer text uses the main UI font by default; typing a triple-backtick fence and pressing Enter turns that line into a visual code block that serializes back to fenced Markdown, while pasted fenced Markdown stays plain text.- Missing model setup is gated at send intent: the first unconfigured send renders an in-thread setup card, keeps the pending prompt in browser session storage for refresh recovery, and must not call `/message_async` until a chat model is configured.- While the setup gate is open, the composer remains typeable but send is blocked until setup succeeds.-- The setup gate must delegate Cloud/Local setup, account connections, and advanced model configuration to the existing onboarding and plugin settings modals; do not duplicate provider/model/key forms inline.+- The setup gate must delegate Cloud/Local setup, account connections, and advanced model configuration to the existing onboarding and model-preset editor modals; do not duplicate provider/model/key forms inline.- A connected OAuth account without Main/Utility model selection is its own gate state; route to model configuration and do not select models automatically.- Model setup surfaces that change readiness must notify the gate with `model-setup-changed`, `model-configured`, or an existing modal/onboarding completion signal so the pending prompt can retry automatically.- The top-section project selector, clock, and connection indicator must respect the instance-level mobile/desktop visibility preferences.diff --git a/webui/components/chat/model-gate-store.js b/webui/components/chat/model-gate-store.jsindex e6026799a..242a17ffd 100644--- a/webui/components/chat/model-gate-store.js+++ b/webui/components/chat/model-gate-store.js@@ -2,7 +2,6 @@ import { createStore } from "/js/AlpineStore.js";import { callJsonApi } from "/js/api.js";import { store as modelConfigStore } from "/plugins/_model_config/webui/model-config-store.js";import { store as onboardingStore } from "/plugins/_onboarding/webui/onboarding-store.js";-import { store as pluginSettingsStore } from "/components/plugins/plugin-settings-store.js";import { toastFrontendError } from "/components/notifications/notification-store.js";const ONBOARDING_MODAL_PATH = "/plugins/_onboarding/webui/onboarding.html";@@ -135,16 +134,18 @@ export const store = createStore("modelGate", {},async openAdvancedModelConfiguration() {- await this.openPluginConfig("_model_config", "Advanced model configuration");- },-- async openPluginConfig(pluginName, title) {try {- await pluginSettingsStore.openConfig(pluginName);+ const data = await callJsonApi("/plugins/_model_config/model_config_get", {});+ await modelConfigStore.openPresetEditor(+ data?.selected_preset || data?.configured_preset || "Default"+ );await this.dispatchPendingIfConfigured();} catch (error) {- console.error(`Could not open ${pluginName} configuration:`, error);- void toastFrontendError(error?.message || "Could not open configuration.", title);+ console.error("Could not open model preset editor:", error);+ void toastFrontendError(+ error?.message || "Could not open model presets.",+ "Advanced model configuration"+ );}},diff --git a/webui/components/projects/AGENTS.md b/webui/components/projects/AGENTS.mdindex 094af8980..d25375d1b 100644--- a/webui/components/projects/AGENTS.md+++ b/webui/components/projects/AGENTS.md@@ -16,6 +16,7 @@- Keep project API payloads synchronized with backend project handlers.- Do not expose project secrets in logs, URLs, or long-lived frontend state unnecessarily.- Preserve scoped settings interactions with plugins, models, skills, and MCP servers.+- Project model settings select a global `_model_config` preset; they do not own copied model dictionaries or project-local preset definitions.## Work Guidancediff --git a/webui/components/projects/project-edit-llm.html b/webui/components/projects/project-edit-llm.htmlindex 4f3724df1..e657c5608 100644--- a/webui/components/projects/project-edit-llm.html+++ b/webui/components/projects/project-edit-llm.html@@ -17,13 +17,12 @@<select class="projects-form-select"x-model="$store.projects.selectedProject.llm.preset_key"@change="$store.projects.applySelectedLlmPreset()">- <option value="current">Current project config</option><template x-for="preset in $store.projects.selectedProject.llm.global_presets" :key="$store.projects.getLlmPresetKey(preset)"><option :value="$store.projects.getLlmPresetKey(preset)" x-text="preset.name"></option></template></select><button type="button" class="button icon-button project-llm-edit-presets"- @click="openModal('/plugins/_model_config/webui/main.html')">+ @click="$store.projects.editSelectedProjectPresets()"><span class="icon material-symbols-outlined">tune</span><span>Edit Presets</span></button>diff --git a/webui/components/projects/projects-store.js b/webui/components/projects/projects-store.jsindex 8cec83edc..d885dabba 100644--- a/webui/components/projects/projects-store.js+++ b/webui/components/projects/projects-store.js@@ -5,7 +5,7 @@ import * as notifications from "/components/notifications/notification-store.js"import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";import { store as browserStore } from "/components/modals/file-browser/file-browser-store.js";import { store as skillsImportStore } from "/components/settings/skills/skills-import-store.js";-import { store as modelConfigStore, configFromPreset } from "/plugins/_model_config/webui/model-config-store.js";+import { store as modelConfigStore } from "/plugins/_model_config/webui/model-config-store.js";import * as shortcuts from "/js/shortcuts.js";import { showConfirmDialog } from "/js/confirmDialog.js";@@ -373,6 +373,8 @@ const model = {notifications.NotificationPriority.NORMAL,true);+ const contextId = chatsStore.getSelectedChatId();+ if (contextId) await modelConfigStore.refreshSwitcher(contextId);return response.data;} else {notifications.toastFrontendError(@@ -441,56 +443,37 @@ const model = {const presetsResult = await api.callJsonApi("/plugins/_model_config/model_presets", {action: "get",project_name: projectName || "",- scope: projectName ? "combined" : "global",});return this._normalizeProjectLlmData({- config: configResult.config || {},selected_preset: {- scope: "current",- project_name: projectName || "",- name: "Current config",+ scope: "global",+ project_name: "",+ name: configResult.selected_preset || configResult.configured_preset || "Default",},global_presets: presetsResult.global_presets || presetsResult.presets || [],- project_presets: presetsResult.project_presets || [],presets: presetsResult.presets || [],}, projectName);},_normalizeProjectLlmData(raw, projectName) {const data = raw || {};- const config = JSON.parse(JSON.stringify(data.config || {}));- config.chat_model = config.chat_model || {};- config.utility_model = config.utility_model || {};- config.embedding_model = config.embedding_model || {};- modelConfigStore.initConfigFields(config);-const globalPresets = this._normalizePresetsWithScope(data.global_presets || [],"global","");- const projectPresets = this._normalizePresetsWithScope(- data.project_presets || [],- "project",- projectName || ""- );- const presets = [- ...globalPresets,- ...projectPresets,- ];+ const presets = [...globalPresets];const selected = data.selected_preset || {- scope: "current",- project_name: projectName || "",- name: "Current config",+ scope: "global",+ project_name: "",+ name: "Default",};return {- config,selected_preset: selected,preset_key: this.getLlmPresetKey(selected),global_presets: globalPresets,- project_presets: projectPresets,+ project_presets: [],presets,- new_preset_name: "",};},@@ -506,27 +489,19 @@ const model = {},getLlmPresetKey(preset) {- if (!preset || preset.scope === "current") return "current";+ if (!preset) return "global||Default";return `${preset.scope || "global"}|${preset.project_name || ""}|${preset.name || ""}`;},_findLlmPresetByKey(key) {const llm = this.selectedProject?.llm;- if (!llm || key === "current") return null;+ if (!llm) return null;return (llm.presets || []).find((preset) => this.getLlmPresetKey(preset) === key) || null;},applySelectedLlmPreset() {const llm = this.selectedProject?.llm;if (!llm) return;- if (llm.preset_key === "current") {- llm.selected_preset = {- scope: "current",- project_name: this.selectedProject?.name || "",- name: "Current config",- };- return;- }const preset = this._findLlmPresetByKey(llm.preset_key);if (!preset) return;llm.selected_preset = {@@ -534,96 +509,27 @@ const model = {project_name: preset.project_name || "",name: preset.name || "",};- llm.config = this._configFromPreset(preset, llm.config || {});- modelConfigStore.initConfigFields(llm.config);},- markLlmCurrent() {+ async editSelectedProjectPresets() {const llm = this.selectedProject?.llm;if (!llm) return;+ const selectedName = llm.selected_preset?.name || "Default";+ await modelConfigStore.openPresetEditor(selectedName);+ await modelConfigStore.loadGlobalPresets();+ llm.global_presets = this._normalizePresetsWithScope(+ modelConfigStore.globalPresets,+ "global",+ ""+ );+ llm.presets = [...llm.global_presets];+ const remappedName = modelConfigStore.remapPresetName(selectedName);llm.selected_preset = {- scope: "current",- project_name: this.selectedProject?.name || "",- name: "Current config",- };- llm.preset_key = "current";- },-- _configFromPreset(preset, baseConfig) {- return configFromPreset(preset, baseConfig || {}, true);- },-- _cleanModelSlot(slot, stripApiKey = true) {- const clean = JSON.parse(JSON.stringify(slot || {}));- for (const key of Object.keys(clean)) {- if (key.startsWith("_")) delete clean[key];- }- if (stripApiKey) delete clean.api_key;- return clean;- },-- _presetFromLlmConfig(name, config) {- return {- name,- chat: this._cleanModelSlot(config?.chat_model || {}, true),- utility: this._cleanModelSlot(config?.utility_model || {}, true),- embedding: this._cleanModelSlot(config?.embedding_model || {}, true),- };- },-- async saveSelectedLlmProjectPreset() {- const project = this.selectedProject;- const llm = project?.llm;- const name = (llm?.new_preset_name || "").trim();- if (!project || !llm || !name) return;-- const preset = {- ...this._presetFromLlmConfig(name, llm.config || {}),- scope: "project",- project_name: project.name || "",- };- const projectPresets = llm.project_presets || (llm.project_presets = []);- const existingIndex = projectPresets.findIndex((p) => p.name === name);- if (existingIndex >= 0) projectPresets.splice(existingIndex, 1, preset);- else projectPresets.push(preset);-- llm.presets = [- ...(llm.global_presets || []),- ...(llm.project_presets || []),- ];- llm.selected_preset = {- scope: "project",- project_name: project.name || "",- name,+ scope: "global",+ project_name: "",+ name: remappedName,};llm.preset_key = this.getLlmPresetKey(llm.selected_preset);- llm.new_preset_name = "";-- if (!project._meta?.creating && project.name) {- await api.callJsonApi("/plugins/_model_config/model_presets", {- action: "save",- scope: "project",- project_name: project.name,- presets: llm.project_presets,- });- notifications.toastFrontendSuccess(- "Project preset saved",- "LLM preset",- 3,- "projects_llm",- notifications.NotificationPriority.NORMAL,- true- );- } else {- notifications.toastFrontendSuccess(- "Project preset ready",- "LLM preset",- 3,- "projects_llm",- notifications.NotificationPriority.NORMAL,- true- );- }},async browseSelected(...relPath) {