Agent Zero AI framework
fix agent profile switching logic
Alessandro282f13982b7a
diff --git a/plugins/_agent_editor/AGENTS.md b/plugins/_agent_editor/AGENTS.mdindex d19032cc1..da9b8da55 100644--- a/plugins/_agent_editor/AGENTS.md+++ b/plugins/_agent_editor/AGENTS.md@@ -16,6 +16,8 @@## Local Contracts- The editor performs zero model calls.+- Profile list requests stay lightweight: summary rows inspect only sparse+ editor-owned keys and files and never construct full save or removal plans.- Writes are limited to the selected profile layer — global`usr/agents/<profile-id>` or project`usr/projects/<project>/.a0proj/agents/<profile-id>` — and only to paths ordiff --git a/plugins/_agent_editor/helpers/editor.py b/plugins/_agent_editor/helpers/editor.pyindex 3920f7b52..f59a5bcaf 100644--- a/plugins/_agent_editor/helpers/editor.py+++ b/plugins/_agent_editor/helpers/editor.py@@ -216,10 +216,7 @@ def list_profiles(context: Any | None = None) -> list[dict[str, Any]]:"origin": state["origin"],"origin_chain": state["origin_chain"],"built_in": state["built_in"],- "scope_has_overrides": bool(- profile_exists(profile_id, context)- and plan_remove_changes(profile_id, context).changes- ),+ "scope_has_overrides": _scope_has_overrides(profile_id, context),"deletable": state["deletable"],"avatar": state["avatar"]["effective"],"avatar_url": effective_avatar_url(profile_id, context),@@ -345,10 +342,7 @@ def build_profile_state("origin": metadata.pop("origin"),"origin_chain": metadata.pop("origin_chain"),"built_in": metadata.pop("built_in"),- "scope_has_overrides": bool(- profile_exists(profile_id, context)- and plan_remove_changes(profile_id, context).changes- ),+ "scope_has_overrides": _scope_has_overrides(profile_id, context),"deletable": metadata.pop("deletable"),"metadata": metadata,"avatar_url": effective_avatar_url(profile_id, context),@@ -391,6 +385,54 @@ def metadata_state(profile_id: str, context: Any | None = None) -> dict[str, Anyreturn state+def _scope_has_overrides(profile_id: str, context: Any | None = None) -> bool:+ project_name = _context_project_name(context)+ root = _profile_root(profile_id, project_name)+ metadata = _read_mapping(+ root / "agent.yaml" if (root / "agent.yaml").is_file() else root / "agent.json"+ )+ if any(key in metadata for key in METADATA_KEYS):+ return True++ scope_prompts = root / "prompts"+ if scope_prompts.is_dir():+ inherited_roots = [+ directory / "prompts"+ for _, directory in _profile_directories(profile_id, context)+ if directory.absolute() != root.absolute()+ ]+ inherited_roots.append(Path(files.get_abs_path("prompts")))+ if any(+ path.name not in NON_PROMPT_MARKDOWN+ and any((inherited / path.name).is_file() for inherited in inherited_roots)+ for path in scope_prompts.glob("*.md")+ if path.is_file()+ ):+ return True++ from plugins._model_config.helpers import model_config++ checks = (+ (+ _profile_config_path(profile_id, "_model_config", project_name),+ (model_config.MODEL_PRESET_CONFIG_KEY,),+ ),+ (+ _profile_config_path(profile_id, tool_policy.PLUGIN_NAME, project_name),+ _TOOL_POLICY_KEYS,+ ),+ (+ _profile_config_path(+ profile_id,+ skills.ACTIVE_SKILLS_PLUGIN_NAME,+ project_name,+ ),+ ("visibility_policy",),+ ),+ )+ return any(any(key in _read_mapping(path) for key in keys) for path, keys in checks)++def prompt_catalog(agent: EditorAgent) -> list[dict[str, Any]]:roots = [Path(path) for path in subagents.get_paths(agent, "prompts")]names = {diff --git a/plugins/_model_config/AGENTS.md b/plugins/_model_config/AGENTS.mdindex a50814fd2..dd699df4a 100644--- a/plugins/_model_config/AGENTS.md+++ b/plugins/_model_config/AGENTS.md@@ -35,8 +35,9 @@current status without adding a selectable or editable row.- Reload the agent-profile selector catalog when a chat changes project oractive profile so project-only profiles never linger in the visible choices.-- When forced agent-profile catalog loads overlap, only the newest request may- replace selector state or finish its loading lifecycle.+- Concurrent agent-profile catalog loads for the same chat share one request;+ across chats, only the newest request may replace selector state or finish+ its loading lifecycle.- 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.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 48f67cf0e..40efc579a 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@@ -11,10 +11,7 @@$store.modelConfig.refreshSwitcher($store.chats?.selected || ''),$store.modelConfig.loadAgentProfiles(),]);- $watch('$store.chats.selected', v => Promise.all([- $store.modelConfig.refreshSwitcher(v || ''),- $store.modelConfig.loadAgentProfiles(true),- ]));+ $watch('$store.chats.selected', v => $store.modelConfig.refreshSwitcher(v || ''));"><template x-if="($store.modelConfig.switcherAllowed && !$store.modelConfig.switcherLoading) || $store.chats?.selectedContext?.agent_profile"><div class="model-switcher-container">diff --git a/plugins/_model_config/webui/switcher-mixin.js b/plugins/_model_config/webui/switcher-mixin.jsindex 9ec17dcf8..84aabfddd 100644--- a/plugins/_model_config/webui/switcher-mixin.js+++ b/plugins/_model_config/webui/switcher-mixin.js@@ -38,38 +38,53 @@ export const switcherState = {agentProfileSaving: false,};+let agentProfilesRequest = null;+let agentProfilesRequestContext = "";+export const switcherMethods = {async loadAgentProfiles(force = false) {+ const contextId = window.Alpine?.store("chats")?.selected || "";+ if (agentProfilesRequest && agentProfilesRequestContext === contextId) {+ return agentProfilesRequest;+ }if (!force && this.agentProfilesLoaded) return this.agentProfiles;const requestSeq = ++this.agentProfilesLoadSeq;this.agentProfilesLoading = true;+ const request = (async () => {+ try {+ const data = await callJsonApi("/plugins/_agent_editor/agent_editor", {+ action: "list",+ context_id: contextId,+ });+ if (requestSeq !== this.agentProfilesLoadSeq) return this.agentProfiles;+ this.agentProfiles = (data.profiles || [])+ .filter(profile => profile.id && !["_example", "default"].includes(profile.id) && profile.enabled !== false)+ .map(profile => ({+ key: profile.id,+ label: profile.title || profile.id,+ avatar: profile.avatar || null,+ avatarUrl: profile.avatar_url || "",+ }));+ this.agentProfilesLoaded = true;+ } catch (e) {+ if (requestSeq !== this.agentProfilesLoadSeq) return this.agentProfiles;+ console.error("Agent profile list load failed:", e);+ this.agentProfiles = [];+ this.agentProfilesLoaded = false;+ } finally {+ if (requestSeq === this.agentProfilesLoadSeq) {+ this.agentProfilesLoading = false;+ }+ }+ return this.agentProfiles;+ })();+ agentProfilesRequest = request;+ agentProfilesRequestContext = contextId;try {- const contextId = window.Alpine?.store("chats")?.selected || "";- const data = await callJsonApi("/plugins/_agent_editor/agent_editor", {- action: "list",- context_id: contextId,- });- if (requestSeq !== this.agentProfilesLoadSeq) return this.agentProfiles;- this.agentProfiles = (data.profiles || [])- .filter(profile => profile.id && !["_example", "default"].includes(profile.id) && profile.enabled !== false)- .map(profile => ({- key: profile.id,- label: profile.title || profile.id,- avatar: profile.avatar || null,- avatarUrl: profile.avatar_url || "",- }));- this.agentProfilesLoaded = true;- } catch (e) {- if (requestSeq !== this.agentProfilesLoadSeq) return this.agentProfiles;- console.error("Agent profile list load failed:", e);- this.agentProfiles = [];- this.agentProfilesLoaded = false;+ return await request;} finally {- if (requestSeq === this.agentProfilesLoadSeq) {- this.agentProfilesLoading = false;- }+ if (agentProfilesRequest === request) agentProfilesRequest = null;}- return this.agentProfiles;},async loadSwitcherState(contextId) {diff --git a/tests/test_agent_editor.py b/tests/test_agent_editor.pyindex 2d8be3aa9..95e24f2cc 100644--- a/tests/test_agent_editor.py+++ b/tests/test_agent_editor.py@@ -395,6 +395,30 @@ def test_model_and_off_tool_choices_write_only_their_json_contracts(}+def test_profile_summaries_do_not_build_removal_plans(+ user_root: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ profile = user_root / "researcher"+ (profile / "plugins" / "manual").mkdir(parents=True)+ (profile / "plugins" / "manual" / "config.json").write_text("{}")+ monkeypatch.setattr(+ editor,+ "plan_remove_changes",+ lambda *_args, **_kwargs: pytest.fail("profile summaries built a removal plan"),+ )++ assert editor.build_profile_state("researcher")["scope_has_overrides"] is False+ assert next(+ item for item in editor.list_profiles() if item["id"] == "researcher"+ )["scope_has_overrides"] is False++ prompts = profile / "prompts"+ prompts.mkdir()+ (prompts / editor.SPECIFICS_FILE).write_text("Scoped instructions")+ assert editor.build_profile_state("researcher")["scope_has_overrides"] is True++def test_project_tool_policy_reads_effective_access_and_writes_project_scope(project_scope: tuple[editor._EditorContext, Path],monkeypatch: pytest.MonkeyPatch,diff --git a/tests/test_agent_editor_webui.py b/tests/test_agent_editor_webui.pyindex d6630d0ba..1014e0836 100644--- a/tests/test_agent_editor_webui.py+++ b/tests/test_agent_editor_webui.py@@ -806,30 +806,38 @@ if (store.view !== "manage" || store.mode !== "easy" || store.draft !== null ||@pytest.mark.skipif(not shutil.which("node"), reason="node is required")-def test_latest_agent_profile_load_owns_switcher_state() -> None:+def test_agent_profile_loads_dedupe_same_context_and_ignore_stale_context() -> None:source = SWITCHER_MIXIN.read_text(encoding="utf-8")source = re.sub(r"^import .*?;\n", "", source, flags=re.MULTILINE)harness = r"""const pending = [];const callJsonApi = async () => await new Promise(resolve => pending.push(resolve));const fetchApi = async () => ({ ok: true, json: async () => ({}) });-globalThis.window = { Alpine: { store: () => ({ selected: "ctx" }) } };+let selectedContextId = "ctx";+globalThis.window = { Alpine: { store: () => ({ selected: selectedContextId }) } };"""checks = r"""const store = { ...switcherState, ...switcherMethods };const older = store.loadAgentProfiles(true);const newer = store.loadAgentProfiles(true);-if (pending.length !== 2 || !store.agentProfilesLoading) throw new Error("overlapping profile loads did not start");-pending[1]({ profiles: [+if (pending.length !== 1 || !store.agentProfilesLoading) throw new Error("same-context profile loads were not deduplicated");+pending[0]({ profiles: [{ id: "default", title: "Default", enabled: true },{ id: "new", title: "New", enabled: true },] });-await newer;+await Promise.all([older, newer]);if (store.agentProfiles[0]?.key !== "new" || store.agentProfilesLoading || !store.agentProfilesLoaded) throw new Error("newest profile load did not settle");if (store.agentProfiles.length !== 1 || store.getAgentProfileList("default", "Default").some(profile => profile.key === "default")) throw new Error("Default profile remained selectable in the chat popover");-pending[0]({ profiles: [{ id: "old", title: "Old", enabled: true }] });-await older;-if (store.agentProfiles[0]?.key !== "new" || store.agentProfilesLoading || !store.agentProfilesLoaded) throw new Error("stale profile load replaced newer state");+selectedContextId = "older-context";+const stale = store.loadAgentProfiles(true);+selectedContextId = "newer-context";+const fresh = store.loadAgentProfiles(true);+if (pending.length !== 3) throw new Error("different-context profile loads were incorrectly deduplicated");+pending[2]({ profiles: [{ id: "fresh", title: "Fresh", enabled: true }] });+await fresh;+pending[1]({ profiles: [{ id: "stale", title: "Stale", enabled: true }] });+await stale;+if (store.agentProfiles[0]?.key !== "fresh" || store.agentProfilesLoading) throw new Error("stale profile load replaced newer state");const requestCount = pending.length;await store.loadAgentProfiles();if (pending.length !== requestCount) throw new Error("cached profile catalog unexpectedly reloaded");diff --git a/tests/test_model_config_api_keys.py b/tests/test_model_config_api_keys.pyindex 468246913..eb779aba1 100644--- a/tests/test_model_config_api_keys.py+++ b/tests/test_model_config_api_keys.py@@ -201,6 +201,7 @@ def test_model_switcher_frontend_renders_custom_overrides():assert "normalizeModelIdentity(o.chat || o)" in switcher_contentassert "normalizeModelIdentity(o.utility)" in switcher_contentassert "$store.modelConfig.getSwitcherLabel()" in switcher_html+ assert "loadAgentProfiles(true)" not in switcher_htmlassert "model-switcher-active-pills" not in switcher_htmlassert "model-pill-role" not in switcher_htmlassert "_model_config_override_revision" in refresh_extension_content