Skip to content

Agent Zero AI framework

Finish scoped Agent Editor profile workflows

Alessandro9e5fd188e282
diff --git a/agents/AGENTS.md b/agents/AGENTS.md
index ae6bda3c5..c2abc4a58 100644
--- a/agents/AGENTS.md
+++ b/agents/AGENTS.md
@@ -8,7 +8,8 @@
## Ownership
- Each direct profile directory owns its `agent.yaml`, optional `prompts/`, optional `tools/`, and optional `extensions/`.
-- `_example/` demonstrates profile layout and should stay suitable as a reference.
+- `_example/` demonstrates profile layout, is not selectable, and should stay
+ suitable as a reference.
- User-created local profiles belong under `usr/agents/`, not here, unless they are intended to ship with the product.
## Local Contracts
diff --git a/agents/_example/AGENTS.md b/agents/_example/AGENTS.md
index 555428ee6..ba62b6250 100644
--- a/agents/_example/AGENTS.md
+++ b/agents/_example/AGENTS.md
@@ -7,7 +7,8 @@
## Ownership
-- `agent.yaml` owns the example profile metadata.
+- This reference intentionally has no `agent.yaml`, so it is not discovered as
+ a selectable profile.
- `prompts/` owns prompt override examples.
- `tools/` owns profile-local tool examples.
- `extensions/` owns profile-local lifecycle extension examples.
diff --git a/api/agent_profile_set.py b/api/agent_profile_set.py
index bec0b2ef1..d268bf137 100644
--- a/api/agent_profile_set.py
+++ b/api/agent_profile_set.py
@@ -1,19 +1,11 @@
from agent import AgentContext
-from helpers import subagents
+from helpers import projects, subagents
from helpers.api import ApiHandler, Request, Response
from helpers.persist_chat import save_tmp_chat
from helpers.state_monitor_integration import mark_dirty_for_context
from initialize import initialize_agent
-def _agent_profile_labels() -> dict[str, str]:
- return {
- str(item.get("key") or ""): str(item.get("label") or item.get("key") or "")
- for item in subagents.get_all_agents_list()
- if item.get("key")
- }
-
-
class SetAgentProfile(ApiHandler):
async def process(self, input: dict, request: Request) -> dict | Response:
context_id = str(input.get("context_id", "") or "").strip()
@@ -33,8 +25,11 @@ class SetAgentProfile(ApiHandler):
response="Agent profile can be changed after the current run finishes.",
)
- labels = _agent_profile_labels()
- if profile not in labels:
+ profiles = subagents.get_available_agents_dict(
+ projects.get_context_project_name(context)
+ )
+ selected_profile = profiles.get(profile)
+ if selected_profile is None:
return Response(status=404, response=f"Agent profile '{profile}' not found")
config = initialize_agent(override_settings={"agent_profile": profile})
@@ -46,5 +41,5 @@ class SetAgentProfile(ApiHandler):
return {
"ok": True,
"agent_profile": profile,
- "agent_profile_label": labels.get(profile, profile),
+ "agent_profile_label": selected_profile.title or profile,
}
diff --git a/api/agent_profile_set.py.dox.md b/api/agent_profile_set.py.dox.md
index 8e891085d..25e87a33b 100644
--- a/api/agent_profile_set.py.dox.md
+++ b/api/agent_profile_set.py.dox.md
@@ -13,8 +13,6 @@
- Classes:
- `SetAgentProfile` (`ApiHandler`)
- `async process(self, input: dict, request: Request) -> dict | Response`
-- Top-level functions:
-- `_agent_profile_labels() -> dict[str, str]`
## Runtime Contracts
@@ -24,11 +22,13 @@
- `SetAgentProfile` defines `process(...)`.
- Observed side-effect areas: filesystem writes, settings/state persistence.
- Switching a chat profile updates the context and top-level agent profile only; existing subordinate agents keep their own profile configs.
+- A profile can be selected only when it is available in the chat's active
+ project scope; profiles owned by other projects are not valid candidates.
- Imported dependency areas include: `agent`, `helpers`, `helpers.api`, `helpers.persist_chat`, `helpers.state_monitor_integration`.
## Key Concepts
-- Important called helpers/classes observed in the source: `str.strip`, `context.is_running`, `_agent_profile_labels`, `initialize_agent`, `context.agent0.config`, `save_tmp_chat`, `mark_dirty_for_context`, `subagents.get_all_agents_list`, `Response`.
+- Important called helpers/classes observed in the source: `str.strip`, `context.is_running`, `initialize_agent`, `context.agent0.config`, `save_tmp_chat`, `mark_dirty_for_context`, `projects.get_context_project_name`, `subagents.get_available_agents_dict`, `Response`.
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
## Work Guidance
diff --git a/api/chat_create.py b/api/chat_create.py
index 88430bf70..0ad9c7fc2 100644
--- a/api/chat_create.py
+++ b/api/chat_create.py
@@ -25,6 +25,10 @@ class CreateChat(ApiHandler):
if current_data_2:
new_context.set_output_data(projects.CONTEXT_DATA_KEY_PROJECT, current_data_2)
+ projects.reconcile_agent_profile(
+ new_context, projects.get_context_project_name(new_context)
+ )
+
# copy model override from current context (only if override is allowed)
if current_context:
model_override = current_context.get_data("chat_model_override")
diff --git a/api/chat_create.py.dox.md b/api/chat_create.py.dox.md
index 3546f4389..49f67a70a 100644
--- a/api/chat_create.py.dox.md
+++ b/api/chat_create.py.dox.md
@@ -20,12 +20,14 @@
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
- `CreateChat` is an `ApiHandler`.
- `CreateChat` defines `process(...)`.
+- A newly created chat reconciles its profile after project inheritance, so it
+ never keeps a profile unavailable in the inherited scope.
- Observed side-effect areas: filesystem writes, model calls, plugin state, settings/state persistence.
- Imported dependency areas include: `agent`, `helpers`, `helpers.api`.
## Key Concepts
-- Important called helpers/classes observed in the source: `self.use_context`, `mark_dirty_all`, `guids.generate_id`, `current_context.get_data`, `current_context.get_output_data`, `new_context.set_data`, `new_context.set_output_data`, `is_chat_override_allowed`, `settings.get_settings`.
+- Important called helpers/classes observed in the source: `self.use_context`, `mark_dirty_all`, `guids.generate_id`, `current_context.get_data`, `current_context.get_output_data`, `new_context.set_data`, `new_context.set_output_data`, `is_chat_override_allowed`, `settings.get_settings`, `projects.get_context_project_name`, `projects.reconcile_agent_profile`.
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
## Work Guidance
diff --git a/helpers/context_utils.py b/helpers/context_utils.py
index afa8dbccd..bb48d7cbd 100644
--- a/helpers/context_utils.py
+++ b/helpers/context_utils.py
@@ -8,6 +8,7 @@ ThreadLockType = Union[threading.Lock, threading.RLock]
def use_context(lock: ThreadLockType, ctxid: str, create_if_not_exists: bool = True):
from agent import AgentContext
+ from helpers import projects
from initialize import initialize_agent
with lock:
@@ -17,6 +18,9 @@ def use_context(lock: ThreadLockType, ctxid: str, create_if_not_exists: bool = T
AgentContext.use(first.id)
return first
context = AgentContext(config=initialize_agent(), set_current=True)
+ projects.reconcile_agent_profile(
+ context, projects.get_context_project_name(context)
+ )
return context
got = AgentContext.use(ctxid)
if got:
@@ -25,6 +29,8 @@ def use_context(lock: ThreadLockType, ctxid: str, create_if_not_exists: bool = T
context = AgentContext(
config=initialize_agent(), id=ctxid, set_current=True
)
+ projects.reconcile_agent_profile(
+ context, projects.get_context_project_name(context)
+ )
return context
- else:
- raise Exception(f"Context {ctxid} not found")
+ raise Exception(f"Context {ctxid} not found")
diff --git a/helpers/context_utils.py.dox.md b/helpers/context_utils.py.dox.md
index 725340ecd..da640f1a0 100644
--- a/helpers/context_utils.py.dox.md
+++ b/helpers/context_utils.py.dox.md
@@ -22,7 +22,10 @@
## Key Concepts
-- Important called helpers/classes observed in the source: `AgentContext.use`, `AgentContext.first`, `AgentContext`, `Exception`, `initialize_agent`.
+- Newly constructed contexts reconcile their active profile against Global
+ availability before returning. Existing context lookups return the stored
+ context unchanged; explicit profile and project transitions own any repair.
+- Important called helpers/classes observed in the source: `AgentContext.use`, `AgentContext.first`, `AgentContext`, `Exception`, `initialize_agent`, `projects.get_context_project_name`, `projects.reconcile_agent_profile`.
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
## Work Guidance
@@ -34,7 +37,8 @@
## Verification
- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers.
-- No direct test reference was found by name search; choose the nearest behavioral test or perform a focused smoke check.
+- `tests/test_projects.py` verifies that lookup is read-only while context
+ creation reconciles once.
## Child DOX Index
diff --git a/helpers/projects.py b/helpers/projects.py
index 41bbf9d44..b06d83008 100644
--- a/helpers/projects.py
+++ b/helpers/projects.py
@@ -405,6 +405,52 @@ def _get_projects_list(parent_dir):
return projects
+def reconcile_agent_profile(
+ context: "AgentContext", project_name: str | None, available: dict | None = None
+) -> bool:
+ from helpers import subagents
+ from initialize import initialize_agent
+
+ if available is None:
+ available = subagents.get_available_agents_dict(project_name)
+ if getattr(context.config, "profile", "") in available:
+ return False
+
+ config = initialize_agent()
+ if config.profile not in available:
+ fallback = "agent0" if "agent0" in available else next(iter(available), "agent0")
+ config = initialize_agent(override_settings={"agent_profile": fallback})
+ context.config = config
+ context.agent0.config = config
+ return True
+
+
+def reconcile_agent_profiles(
+ project_name: str | None, *, all_scopes: bool = False
+) -> None:
+ from agent import AgentContext
+ from helpers import subagents
+ from helpers.state_monitor_integration import mark_dirty_for_context
+
+ available_by_project: dict[str | None, dict] = {}
+ for context in AgentContext.all():
+ context_project = get_context_project_name(context)
+ if not all_scopes and context_project != project_name:
+ continue
+ if context_project not in available_by_project:
+ available_by_project[context_project] = (
+ subagents.get_available_agents_dict(context_project)
+ )
+ if not reconcile_agent_profile(
+ context, context_project, available_by_project[context_project]
+ ):
+ continue
+ persist_chat.save_tmp_chat(context)
+ mark_dirty_for_context(
+ context.id, reason="projects.reconcile_agent_profiles"
+ )
+
+
def activate_project(context_id: str, name: str, *, mark_dirty: bool = True):
from agent import AgentContext
@@ -419,6 +465,7 @@ def activate_project(context_id: str, name: str, *, mark_dirty: bool = True):
CONTEXT_DATA_KEY_PROJECT,
{"name": name, "title": display_name, "color": data.get("color", "")},
)
+ reconcile_agent_profile(context, name)
# persist
persist_chat.save_tmp_chat(context)
@@ -436,6 +483,7 @@ def deactivate_project(context_id: str, *, mark_dirty: bool = True):
raise Exception("Context not found")
context.set_data(CONTEXT_DATA_KEY_PROJECT, None)
context.set_output_data(CONTEXT_DATA_KEY_PROJECT, None)
+ reconcile_agent_profile(context, None)
# persist
persist_chat.save_tmp_chat(context)
@@ -648,7 +696,7 @@ def load_project_subagents(name: str) -> dict[str, SubAgentSettings]:
abs_path = files.get_abs_path(get_project_meta(name), "agents.json")
data = dirty_json.parse(files.read_file(abs_path))
if isinstance(data, dict):
- return _normalize_subagents(data) # type: ignore[arg-type,return-value]
+ return _normalize_subagents(data, name) # type: ignore[arg-type,return-value]
return {}
except Exception:
return {}
@@ -656,21 +704,21 @@ def load_project_subagents(name: str) -> dict[str, SubAgentSettings]:
def save_project_subagents(name: str, subagents_data: dict[str, SubAgentSettings]):
abs_path = files.get_abs_path(get_project_meta(name), "agents.json")
- normalized = _normalize_subagents(subagents_data)
+ normalized = _normalize_subagents(subagents_data, name)
content = dirty_json.stringify(normalized)
files.write_file(abs_path, content)
def _normalize_subagents(
- subagents_data: dict[str, SubAgentSettings]
+ subagents_data: dict[str, SubAgentSettings], project_name: str = ""
) -> dict[str, SubAgentSettings]:
from helpers import subagents
- agents_dict = subagents.get_agents_dict()
+ scoped_agents = subagents.get_agents_dict(project_name or None)
normalized: dict[str, SubAgentSettings] = {}
for key, value in subagents_data.items():
- agent = agents_dict.get(key)
+ agent = scoped_agents.get(key)
if not agent:
continue
diff --git a/helpers/projects.py.dox.md b/helpers/projects.py.dox.md
index e1e1b592e..478e01d94 100644
--- a/helpers/projects.py.dox.md
+++ b/helpers/projects.py.dox.md
@@ -42,6 +42,8 @@
- `save_project_mcp_servers(name: str, mcp_servers: str)`
- `get_active_projects_list()`
- `_get_projects_list(parent_dir)`
+- `reconcile_agent_profile(context: AgentContext, project_name: str | None) -> bool`
+- `reconcile_agent_profiles(project_name: str | None, *, all_scopes: bool=...) -> None`
- `activate_project(context_id: str, name: str, mark_dirty: bool=...)`
- `deactivate_project(context_id: str, mark_dirty: bool=...)`
- `reactivate_project_in_chats(name: str)`
@@ -54,6 +56,9 @@
- `get_project_agents_md_instruction_file(name: str) -> tuple[str, str] | None`
- `_format_project_instruction_files(instruction_files: list[tuple[str, str]]) -> str`
- `_normalize_include_agents_md(value: object) -> bool`
+- `load_project_subagents(name: str) -> dict[str, SubAgentSettings]`
+- `save_project_subagents(name: str, subagents_data: dict[str, SubAgentSettings])`
+- `_normalize_subagents(subagents_data: dict[str, SubAgentSettings], project_name: str=...) -> dict[str, SubAgentSettings]`
- Notable constants/configuration names: `PROJECTS_PARENT_DIR`, `PROJECT_META_DIR`, `PROJECT_INSTRUCTIONS_DIR`, `PROJECT_KNOWLEDGE_DIR`, `PROJECT_SKILLS_DIR`, `PROJECT_HEADER_FILE`, `PROJECT_MCP_SERVERS_FILE`, `PROJECT_AGENTS_MD_FILES`, `DEFAULT_MCP_SERVERS_CONFIG`, `CONTEXT_DATA_KEY_PROJECT`.
## Runtime Contracts
@@ -69,8 +74,21 @@
- Active-project AGENTS.md protocol guidance excludes the exact project root AGENTS.md because `build_system_prompt_vars(...)` already loads it into project instructions; prose for that protocol block lives in `prompts/agent.protocol.projects.agents_md.md`.
- Project MCP config uses the same JSON string shape as global MCP settings: an object with `mcpServers`.
- Project MCP load/save paths validate project names as simple folder basenames before touching `.a0proj/mcp_servers.json`.
+- Activating or deactivating a project preserves the active chat profile when it
+ is available in the destination scope; otherwise it replaces it with the
+ configured default profile, then `agent0`, then the first available profile.
+- Per-project profile availability is persisted sparsely in `.a0proj/agents.json`;
+ entries matching the profile definition's scoped default are omitted. The
+ helper retains the established plain load/save contract for project settings.
+- Profile reconciliation treats `None` as the Global scope. Callers must pass
+ `all_scopes=True` to check every loaded chat after a Global availability
+ change. Each pass resolves the available profile catalog once per encountered
+ scope; only chats whose active profile actually changes are persisted and
+ marked dirty. Context creation uses the same reconciliation after resolving
+ its scope, so a disabled configured profile cannot become invisibly active.
- Observed side-effect areas: filesystem reads, filesystem writes, filesystem deletion, plugin state, settings/state persistence, secret handling.
-- Imported dependency areas include: `helpers`, `helpers.print_style`, `os`, `typing`.
+- Imported dependency areas include: `helpers`, `helpers.print_style`, `os`,
+ `typing`.
## Key Concepts
diff --git a/helpers/subagents.py b/helpers/subagents.py
index e544f4276..db4de677a 100644
--- a/helpers/subagents.py
+++ b/helpers/subagents.py
@@ -96,6 +96,8 @@ def _get_agents_list_from_dir(dir: str, origin: Origin) -> dict[str, SubAgentLis
try:
raw = _read_agent_definition(dir, subdir)
except FileNotFoundError:
+ if origin == "default":
+ continue
raw = {}
agent_data = SubAgentListItem.model_validate(raw)
name = agent_data.name or subdir
@@ -312,9 +314,7 @@ def get_default_promp_file_names() -> list[str]:
def get_available_agents_dict(
project_name: str | None,
) -> dict[str, SubAgentListItem]:
- # all available agents
- all_agents = get_agents_dict()
- # filter by project settings
+ all_agents = get_agents_dict(project_name)
from helpers import projects
project_settings = (
@@ -323,6 +323,8 @@ def get_available_agents_dict(
filtered_agents: dict[str, SubAgentListItem] = {}
for name, agent in all_agents.items():
+ if name == "_example":
+ continue
if name in project_settings:
agent.enabled = project_settings[name]["enabled"]
if agent.enabled:
diff --git a/helpers/subagents.py.dox.md b/helpers/subagents.py.dox.md
index f2aa5a8f1..03830b28e 100644
--- a/helpers/subagents.py.dox.md
+++ b/helpers/subagents.py.dox.md
@@ -49,6 +49,11 @@
missing keys inherit while explicitly empty values remain overrides. Runtime
`name`, `path`, `origin`, and `prompts` fields are handled separately; derived
title fallbacks do not become authored overrides.
+- Available-profile resolution includes definitions from the selected project,
+ then applies that project's sparse `agents.json` availability overrides.
+- Bundled directories require an authored profile definition; the `_example`
+ reference directory is never selectable. Every real profile, including
+ `Default`, follows the same Global and project availability rules.
- Important called helpers/classes observed in the source: `cache.toggle_area`, `model_validator`, `_get_agents_list_from_dir`, `plugins.get_enabled_plugin_paths`, `_merge_agent_dicts`, `files.get_subdirectories`, `_load_agent_data_from_dir`, `_merge_agent`, `files.write_file`, `files.delete_dir`, `SubAgent`, `SubAgentListItem`, `files.find_existing_paths_by_pattern`, `get_agents_roots`, `files.list_files`, `get_agents_dict`, `cache.determine_cache_key`, `cache.add`, `projects.get_project_meta`, `FileNotFoundError`.
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
diff --git a/plugins/_agent_editor/AGENTS.md b/plugins/_agent_editor/AGENTS.md
index ec3786b95..50d26c682 100644
--- a/plugins/_agent_editor/AGENTS.md
+++ b/plugins/_agent_editor/AGENTS.md
@@ -19,7 +19,13 @@
- 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 or
- config keys listed in the validated change plan.
+ config keys listed in the validated change plan. The availability toggle
+ reuses the existing project `.a0proj/agents.json` load/save owner; the WebUI
+ permits one availability save at a time. Global availability remains a sparse
+ `enabled` profile override.
+- Every profile, including `Default`, can be made unavailable. The backend
+ rejects only the change that would leave the selected scope with no available
+ profile, then reconciles loaded chats through the shared project owner.
- Never call `helpers.subagents.save_agent_data`.
- Authored profile definitions remain YAML; editor-written plugin configs remain
JSON.
@@ -41,7 +47,16 @@
- Model selection reuses `_model_config`'s compact preset dropdown and preset
editor; Agent Editor persists only the scoped preset reference.
- Manage agents reuses the plugin-settings project vocabulary: Global or one
- existing project. Save & test activates that same scope in the fresh chat.
+ existing project. The active chat profile appears once above the list; each
+ row exposes scoped availability, duplication, icon-only Edit, and Delete for
+ profiles owned by that scope. Duplicate materializes the effective source
+ profile into the selected writable layer with a collision-free ID and title.
+ Availability changes quietly refresh the adjacent profile switcher catalog
+ without a success toast.
+- The same project selector is available inside Create and Edit. Create keeps
+ the in-progress draft when its destination changes; Edit reloads the selected
+ profile from the new scope after guarding unsaved changes.
+- Save & test activates the saved profile in a fresh chat using that same scope.
- The WebUI uses the shared modal stack, labeled prompt scroll regions, and
24px-or-larger policy and text-action targets.
diff --git a/plugins/_agent_editor/README.md b/plugins/_agent_editor/README.md
index 23cca24cb..160acda7e 100644
--- a/plugins/_agent_editor/README.md
+++ b/plugins/_agent_editor/README.md
@@ -12,3 +12,8 @@ Global agents and customizations live under `usr/agents/<profile-id>` and apply
across projects. Project-scoped agents and customizations live under
`usr/projects/<project>/.a0proj/agents/<profile-id>`, inherit the Global layer,
and can be removed without changing it.
+
+Manage agents can duplicate the effective profile into the selected scope and
+toggle whether each profile is available there. Project availability reuses
+`.a0proj/agents.json`; Global availability is a sparse profile override.
+The Default profile always remains available.
diff --git a/plugins/_agent_editor/api/agent_editor.py b/plugins/_agent_editor/api/agent_editor.py
index 2f32dade5..936913633 100644
--- a/plugins/_agent_editor/api/agent_editor.py
+++ b/plugins/_agent_editor/api/agent_editor.py
@@ -4,7 +4,7 @@ from pathlib import Path
from typing import Any
from agent import AgentContext
-from helpers import projects
+from helpers import projects, subagents
from helpers.api import ApiHandler, Request, Response
from plugins._agent_editor.helpers import editor
@@ -35,6 +35,43 @@ class AgentEditor(ApiHandler):
**receipt,
"effective_profile": editor.build_profile_state(profile_id, context),
}
+ if action == "set_enabled":
+ profile_id = editor.validate_profile_id(input.get("profile_id"))
+ enabled = input.get("enabled")
+ if not isinstance(enabled, bool):
+ raise ValueError("Agent availability must be true or false.")
+ if not enabled:
+ project_name = editor._context_project_name(context)
+ for live_context in AgentContext.all():
+ if (
+ getattr(live_context.config, "profile", "") == profile_id
+ and live_context.is_running()
+ and (
+ not project_name
+ or projects.get_context_project_name(live_context)
+ == project_name
+ )
+ ):
+ raise ValueError(
+ "This agent is running. Disable it after the run finishes."
+ )
+ receipt = editor.set_profile_enabled(profile_id, enabled, context)
+ return {
+ "ok": True,
+ **receipt,
+ **_active_profile(input),
+ }
+ if action == "duplicate":
+ profile_id = editor.validate_profile_id(input.get("profile_id"))
+ plan, title = editor.plan_duplicate_profile(profile_id, context)
+ receipt = editor.apply_change_plan(plan)
+ return {
+ "ok": True,
+ **receipt,
+ "profile_id": plan.profile_id,
+ "title": title,
+ "profiles": editor.list_profiles(context),
+ }
if action in {"plan_remove_changes", "remove_changes"}:
profile_id = editor.validate_profile_id(input.get("profile_id"))
plan = editor.plan_remove_changes(
@@ -61,7 +98,12 @@ class AgentEditor(ApiHandler):
}
if input.get("confirm") is not True:
raise ValueError("Deleting a custom agent requires confirmation.")
- return {"ok": True, **editor.apply_change_plan(plan)}
+ receipt = editor.apply_change_plan(plan)
+ project_name = editor._context_project_name(context)
+ projects.reconcile_agent_profiles(
+ project_name or None, all_scopes=not project_name
+ )
+ return {"ok": True, **receipt}
raise ValueError(f"Unknown Agent Editor action: {action}")
except ValueError as exc:
return Response(status=400, response=str(exc), mimetype="text/plain")
@@ -80,3 +122,19 @@ def _context(input: dict[str, Any]) -> Any:
if not Path(projects.get_project_folder(project_name)).is_dir():
raise ValueError("Project not found.")
return editor._EditorContext(project_name)
+
+
+def _active_profile(input: dict[str, Any]) -> dict[str, str]:
+ context_id = str(input.get("active_context_id") or "").strip()
+ context = AgentContext.get(context_id) if context_id else None
+ if not context:
+ return {}
+ profile_id = str(getattr(context.config, "profile", "") or "")
+ profiles = subagents.get_available_agents_dict(
+ projects.get_context_project_name(context)
+ )
+ profile = profiles.get(profile_id)
+ return {
+ "active_profile": profile_id,
+ "active_profile_label": profile.title if profile else profile_id,
+ }
diff --git a/plugins/_agent_editor/extensions/webui/chat-input-progress-start/agent-ready-note.html b/plugins/_agent_editor/extensions/webui/chat-input-progress-start/agent-ready-note.html
index ae347ce80..0d3ba568f 100644
--- a/plugins/_agent_editor/extensions/webui/chat-input-progress-start/agent-ready-note.html
+++ b/plugins/_agent_editor/extensions/webui/chat-input-progress-start/agent-ready-note.html
@@ -5,7 +5,7 @@
<div x-data x-show="$store.agentEditor?.readyNoteVisible()" class="agent-ready-note" role="status" style="display:none">
<x-icon name="celebration" aria-hidden="true"></x-icon>
<span>Your agent is ready. You can refine it anytime from Edit agent.</span>
- <button type="button" class="button icon" aria-label="Dismiss agent ready note" @click="$store.agentEditor.dismissReadyNote()"><x-icon name="close"></x-icon></button>
+ <button type="button" class="agent-ready-dismiss" aria-label="Dismiss agent ready note" @click="$store.agentEditor.dismissReadyNote()"><x-icon name="close"></x-icon></button>
</div>
<style>
@@ -23,4 +23,17 @@
font-size:.82rem;
}
.agent-ready-note > span { flex:1; }
+ .agent-ready-dismiss {
+ display:grid;
+ flex:0 0 2rem;
+ height:2rem;
+ place-items:center;
+ padding:0;
+ border:0;
+ background:transparent;
+ color:inherit;
+ cursor:pointer;
+ opacity:.75;
+ }
+ .agent-ready-dismiss:hover { opacity:1; }
</style>
diff --git a/plugins/_agent_editor/helpers/editor.py b/plugins/_agent_editor/helpers/editor.py
index 17def539e..840af0537 100644
--- a/plugins/_agent_editor/helpers/editor.py
+++ b/plugins/_agent_editor/helpers/editor.py
@@ -165,6 +165,7 @@ def profile_exists(profile_id: str, context: Any | None = None) -> bool:
def list_profiles(context: Any | None = None) -> list[dict[str, Any]]:
project_name = _context_project_name(context)
resolved = subagents.get_agents_dict(project_name)
+ enabled = subagents.get_available_agents_dict(project_name)
names = set(resolved)
roots = [Path(files.get_abs_path("agents")), USER_AGENTS_ROOT]
if project_name:
@@ -190,7 +191,7 @@ def list_profiles(context: Any | None = None) -> list[dict[str, Any]]:
"deletable": state["deletable"],
"avatar": state["avatar"]["effective"],
"avatar_url": effective_avatar_url(profile_id, context),
- "enabled": bool(getattr(resolved.get(profile_id), "enabled", True)),
+ "enabled": profile_id in enabled,
"available": profile_exists(profile_id, context),
}
)
@@ -468,7 +469,9 @@ def effective_avatar_url(profile_id: str, context: Any | None = None) -> str:
return "/api/plugins/_agent_editor/agent_editor_avatar?" + urlencode(query)
-def _metadata_layers(profile_id: str, context: Any | None) -> list[ProfileLayer]:
+def _profile_directories(
+ profile_id: str, context: Any | None
+) -> list[tuple[str, Path]]:
agent = EditorAgent(profile_id, context)
directories: list[tuple[str, Path]] = [
(
@@ -488,10 +491,13 @@ def _metadata_layers(profile_id: str, context: Any | None) -> list[ProfileLayer]
Path(projects.get_project_meta(project_name, "agents", profile_id)),
)
)
+ return directories
+
+def _metadata_layers(profile_id: str, context: Any | None) -> list[ProfileLayer]:
return [
layer
- for kind, directory in directories
+ for kind, directory in _profile_directories(profile_id, context)
if (layer := _load_profile_layer(kind, directory)) is not None
]
@@ -705,6 +711,127 @@ def build_change_plan(
return plan
+def plan_profile_enabled(
+ profile_id: str,
+ enabled: bool,
+ context: Any | None = None,
+) -> ChangePlan:
+ profile_id = validate_profile_id(profile_id)
+ if _context_project_name(context):
+ raise ValueError("Project availability is stored in project settings.")
+ if not profile_exists(profile_id, context):
+ raise ValueError(f'Agent profile "{profile_id}" does not exist.')
+
+ root = _profile_root(profile_id)
+ yaml_path = root / "agent.yaml"
+ legacy_path = root / "agent.json"
+ data = _read_mapping_strict(
+ yaml_path if yaml_path.is_file() else legacy_path,
+ "profile metadata",
+ )
+ lower_layers = [
+ layer for layer in _metadata_layers(profile_id, context)
+ if layer.kind != "user"
+ ]
+ inherited, _, _ = _layer_value(lower_layers, "enabled")
+ inherited = True if inherited is None else bool(inherited)
+ if enabled == inherited:
+ data.pop("enabled", None)
+ else:
+ data["enabled"] = enabled
+
+ plan = ChangePlan(profile_id=profile_id)
+ if data:
+ plan.write(yaml_path, yaml_helper.dumps(data))
+ else:
+ plan.delete(yaml_path)
+ return plan
+
+
+def set_profile_enabled(
+ profile_id: str,
+ enabled: bool,
+ context: Any | None = None,
+) -> dict[str, Any]:
+ profile_id = validate_profile_id(profile_id)
+ project_name = _context_project_name(context)
+ if not profile_exists(profile_id, context):
+ raise ValueError(f'Agent profile "{profile_id}" does not exist.')
+
+ available = subagents.get_available_agents_dict(project_name or None)
+ if not enabled and profile_id in available and len(available) == 1:
+ raise ValueError("At least one agent profile must remain available.")
+
+ if project_name:
+ settings = projects.load_project_subagents(project_name)
+ settings[profile_id] = {"enabled": enabled}
+ projects.save_project_subagents(project_name, settings)
+ receipt = {
+ "written": [
+ _relative_source(
+ Path(projects.get_project_meta(project_name, "agents.json"))
+ )
+ ],
+ "deleted": [],
+ "warnings": [],
+ }
+ else:
+ receipt = apply_change_plan(plan_profile_enabled(profile_id, enabled, context))
+
+ if not enabled:
+ projects.reconcile_agent_profiles(
+ project_name or None, all_scopes=not project_name
+ )
+ return receipt
+
+
+def plan_duplicate_profile(
+ profile_id: str,
+ context: Any | None = None,
+) -> tuple[ChangePlan, str]:
+ profile_id = validate_profile_id(profile_id)
+ if not profile_exists(profile_id, context):
+ raise ValueError(f'Agent profile "{profile_id}" does not exist.')
+
+ state = metadata_state(profile_id, context)
+ source_title = str(state["title"]["effective"] or profile_id).strip() or profile_id
+ index = 1
+ while True:
+ suffix = f"-{index}"
+ stem = profile_id[: 64 - len(suffix)].rstrip("-_")
+ target_id = f"{stem}{suffix}"
+ if not profile_exists(target_id, context):
+ break
+ index += 1
+
+ target_title = f"{source_title} {index}"
+ project_name = _context_project_name(context)
+ target_root = _profile_root(target_id, project_name)
+ plan = ChangePlan(profile_id=target_id, project_name=project_name)
+
+ metadata: dict[str, Any] = {}
+ for layer in _metadata_layers(profile_id, context):
+ metadata.update(layer.data)
+ for key in ("name", "path", "origin", "prompts", "enabled"):
+ metadata.pop(key, None)
+ metadata["title"] = target_title
+ plan.write(target_root / "agent.yaml", yaml_helper.dumps(metadata))
+
+ skipped = {"agent.yaml", "agent.json", "AGENTS.md"}
+ for _, source_root in _profile_directories(profile_id, context):
+ if not source_root.is_dir():
+ continue
+ if source_root.is_symlink():
+ raise ValueError("Profile symlinks must be removed before duplication.")
+ for source in sorted(source_root.rglob("*")):
+ if source.is_symlink():
+ raise ValueError("Profile symlinks must be removed before duplication.")
+ if source.is_file() and source.name not in skipped:
+ plan.write(target_root / source.relative_to(source_root), source.read_bytes())
+
+ return plan, target_title
+
+
def _plan_metadata(
plan: ChangePlan,
value: Any,
diff --git a/plugins/_agent_editor/webui/agent-editor-store.js b/plugins/_agent_editor/webui/agent-editor-store.js
index 4959c29c8..3edcc811e 100644
--- a/plugins/_agent_editor/webui/agent-editor-store.js
+++ b/plugins/_agent_editor/webui/agent-editor-store.js
@@ -87,6 +87,8 @@ const model = {
projects: [],
projectName: "",
profiles: [],
+ profileAvailabilitySaving: false,
+ duplicatingProfile: "",
draft: null,
initialDraft: null,
selectedPrompt: SPECIFICS,
@@ -146,6 +148,8 @@ const model = {
this.loading = true;
this.error = "";
this.pendingMutation = null;
+ this.profileAvailabilitySaving = false;
+ this.duplicatingProfile = "";
this.plan = { written: [], deleted: [], warnings: [] };
this.planStatus = "idle";
this.view = this.intent.view === "manage" ? "manage" : "editor";
@@ -221,12 +225,114 @@ const model = {
return this.projectName ? "Inherited" : "Default";
},
+ activeProjectName() {
+ const project = chatsStore.selectedContext?.project;
+ return typeof project === "object"
+ ? String(project?.name || "")
+ : String(project || "");
+ },
+
+ currentChatUsesScope() {
+ return Boolean(
+ chatsStore.selected
+ && (!this.projectName || this.projectName === this.activeProjectName())
+ );
+ },
+
+ isProfileActive(profileId) {
+ return this.currentChatUsesScope()
+ && chatsStore.selectedContext?.agent_profile === profileId;
+ },
+
+ activeProfile() {
+ return this.profiles.find((profile) => this.isProfileActive(profile.id)) || null;
+ },
+
+ async setProfileEnabled(profile, enabled) {
+ if (!profile?.id || this.profileAvailabilitySaving) return;
+ const previous = !!profile.enabled;
+ profile.enabled = enabled;
+ this.profileAvailabilitySaving = true;
+ try {
+ const data = await callJsonApi(API, {
+ action: "set_enabled",
+ profile_id: profile.id,
+ enabled,
+ active_context_id: chatsStore.selected || "",
+ ...this.scopeInput(),
+ });
+ if (data.active_profile && chatsStore.selectedContext) {
+ chatsStore.selectedContext.agent_profile = data.active_profile;
+ chatsStore.selectedContext.agent_profile_label = data.active_profile_label || data.active_profile;
+ }
+ await modelConfigStore.loadAgentProfiles(true);
+ } catch (error) {
+ profile.enabled = previous;
+ this.error = error.message || String(error);
+ } finally {
+ this.profileAvailabilitySaving = false;
+ }
+ },
+
+ async duplicateProfile(profile) {
+ if (!profile?.id || this.duplicatingProfile) return;
+ this.duplicatingProfile = profile.id;
+ this.error = "";
+ try {
+ const data = await callJsonApi(API, {
+ action: "duplicate",
+ profile_id: profile.id,
+ ...this.scopeInput(),
+ });
+ this.profiles = data.profiles || [];
+ await modelConfigStore.loadAgentProfiles(true);
+ globalThis.justToast?.(
+ `${data.title || profile.title || profile.id} created.`,
+ "success", 1800, "agent-profile-duplicate",
+ );
+ } catch (error) {
+ this.error = error.message || String(error);
+ } finally {
+ this.duplicatingProfile = "";
+ }
+ },
+
async onScopeChanged() {
- this.intent = { ...this.intent, projectName: this.projectName || "" };
+ const previous = this.intent.projectName || "";
+ const next = this.projectName || "";
+ if (previous === next) return;
+ if (this.view === "editor" && !this.draft?.creating && this.dirty
+ && !window.confirm("Changing project will discard your unsaved changes. Continue?")) {
+ this.projectName = previous;
+ return;
+ }
+ this.intent = { ...this.intent, projectName: next };
this.loading = true;
this.error = "";
try {
await this.loadProfiles();
+ if (this.view !== "editor" || !this.draft) return;
+ if (!this.draft.creating
+ && !this.profiles.some((profile) => profile.id === this.draft.profileId)) {
+ this.projectName = previous;
+ this.intent = { ...this.intent, projectName: previous };
+ await this.loadProfiles();
+ throw new Error("This agent is not available in the selected scope.");
+ }
+ const data = await callJsonApi(API, {
+ action: "load",
+ profile_id: this.draft.creating ? "new-agent" : this.draft.profileId,
+ ...this.scopeInput(),
+ });
+ this.state = data.state;
+ if (!this.draft.creating) this.makeDraft(false);
+ } catch (error) {
+ if (this.view === "editor" && this.projectName !== previous) {
+ this.projectName = previous;
+ this.intent = { ...this.intent, projectName: previous };
+ await this.loadProfiles();
+ }
+ this.error = error.message || String(error);
} finally {
this.loading = false;
}
@@ -1079,14 +1185,9 @@ const model = {
async deleteProfile(profileId) {
try {
- const data = await callJsonApi(API, {
- action: "plan_delete",
- profile_id: profileId,
- ...this.scopeInput(),
- });
const confirmed = await showConfirmDialog({
title: `Delete ${escapeHtml(profileId)}?`,
- message: `${this.deletionImpactHtml(data)}<p>This permanently removes this custom agent from ${escapeHtml(this.scopeLabel)}.</p>`,
+ message: `<p>This agent profile will be permanently deleted from ${escapeHtml(this.scopeLabel)} and cannot be recovered.</p>`,
confirmText: "Delete agent",
type: "danger",
});
@@ -1107,23 +1208,6 @@ const model = {
}
},
- deletionImpactHtml(data) {
- const impact = data?.impact || {};
- const list = (values, empty) => values?.length
- ? `<ul>${values.map((value) => `<li><code>${escapeHtml(value)}</code></li>`).join("")}</ul>`
- : `<span>${empty}</span>`;
- const contents = Object.entries(impact.contains || {})
- .filter(([, present]) => present)
- .map(([name]) => name);
- return [
- `<p><strong>Files</strong>${list(impact.files || data?.deleted || [], "None")}</p>`,
- `<p><strong>Model preset</strong><br>${escapeHtml(impact.model_preset || "None")}</p>`,
- `<p><strong>Projects using this agent</strong>${list(impact.project_references, "None found")}</p>`,
- `<p><strong>Open chats using this agent</strong>${list(impact.active_sessions, "None found")}</p>`,
- `<p><strong>Saved settings</strong><br>${escapeHtml(contents.length ? contents.join(", ") : "No additional settings or assets")}</p>`,
- ].join("");
- },
-
showManager() {
if (this.dirty && !window.confirm("You have unsaved changes that will be lost. Continue?")) return;
this.view = "manage";
diff --git a/plugins/_agent_editor/webui/main.html b/plugins/_agent_editor/webui/main.html
index fc547c516..4ebac0e11 100644
--- a/plugins/_agent_editor/webui/main.html
+++ b/plugins/_agent_editor/webui/main.html
@@ -27,27 +27,34 @@
<template x-if="!$store.agentEditor.loading && $store.agentEditor.view === 'manage'">
<section class="agent-manager" aria-label="Manage agents">
<div class="agent-scope-selector">
- <div class="agent-scope-header">
- <div class="agent-scope-copy">
- <strong>Agent scope</strong>
- <p>Choose whether agents and customizations apply globally or only to one project.</p>
+ <label class="agent-scope-field">
+ <span>Project</span>
+ <select x-model="$store.agentEditor.projectName"
+ x-init="$nextTick(() => $el.value = $store.agentEditor.projectName)"
+ @change="$store.agentEditor.onScopeChanged()">
+ <option value="">Global</option>
+ <template x-for="project in $store.agentEditor.projects" :key="project.key">
+ <option :value="project.key" x-text="project.label"></option>
+ </template>
+ </select>
+ </label>
+ </div>
+ <div class="agent-manager-list-header">
+ <template x-if="$store.agentEditor.activeProfile()">
+ <div class="active-agent-display">
+ <span class="active-agent-summary">
+ <span>Active:</span>
+ <span class="active-agent-avatar" aria-hidden="true" :style="`background:${$store.agentEditor.profileVisual($store.agentEditor.activeProfile()).color}`">
+ <img x-show="$store.agentEditor.profileVisual($store.agentEditor.activeProfile()).url" :src="$store.agentEditor.profileVisual($store.agentEditor.activeProfile()).url" alt="">
+ <span x-show="!$store.agentEditor.profileVisual($store.agentEditor.activeProfile()).url" x-text="$store.agentEditor.profileVisual($store.agentEditor.activeProfile()).initials"></span>
+ </span>
+ <strong x-text="$store.agentEditor.activeProfile().title || $store.agentEditor.activeProfile().id"></strong>
+ </span>
+ <button type="button" class="button icon-button" title="Edit" :aria-label="`Edit ${$store.agentEditor.activeProfile().title || $store.agentEditor.activeProfile().id}`" @click="$store.agentEditor.loadEditor($store.agentEditor.activeProfile().id, false)"><x-icon class="icon" name="edit"></x-icon></button>
</div>
- </div>
- <div class="agent-scope-toolbar">
- <label class="agent-scope-field">
- <span>Project</span>
- <select x-model="$store.agentEditor.projectName"
- x-init="$nextTick(() => $el.value = $store.agentEditor.projectName)"
- @change="$store.agentEditor.onScopeChanged()">
- <option value="">Global</option>
- <template x-for="project in $store.agentEditor.projects" :key="project.key">
- <option :value="project.key" x-text="project.label"></option>
- </template>
- </select>
- </label>
- </div>
+ </template>
+ <button type="button" class="button agent-manager-create" @click="$store.agentEditor.loadEditor('new-agent', true)"><x-icon class="icon" name="add"></x-icon>Create agent</button>
</div>
- <p class="agent-manager-intro" x-text="$store.agentEditor.projectName ? `Create agents and customize inherited profiles only for ${$store.agentEditor.scopeLabel}. Global and original files are never modified.` : 'Create agents and customize inherited profiles for every project. Originals are never modified.'"></p>
<div class="agent-manager-list">
<template x-for="profile in $store.agentEditor.profiles" :key="profile.id">
<article class="agent-manager-card">
@@ -59,16 +66,29 @@
<div class="agent-manager-name">
<strong x-text="profile.title || profile.id"></strong>
<span class="agent-origin" x-text="profile.origin"></span>
- <span class="agent-status-badge is-customized" x-show="profile.scope_has_overrides">
- <x-icon name="edit_note"></x-icon><span>Customized by you</span>
- </span>
+ <span class="agent-customized-indicator" x-show="profile.scope_has_overrides" title="Customized" aria-label="Customized" role="img"><x-icon name="edit_note"></x-icon></span>
</div>
<p x-text="profile.description || 'No description'"></p>
- <code x-text="profile.id"></code>
+ <button type="button" class="text-button agent-manager-inline-action"
+ :disabled="!!$store.agentEditor.duplicatingProfile"
+ :aria-label="`Duplicate ${profile.title || profile.id}`"
+ @click="$store.agentEditor.duplicateProfile(profile)">
+ <x-icon name="content_copy"></x-icon><span>Duplicate</span>
+ </button>
</div>
<div class="agent-manager-actions">
- <button type="button" class="button" @click="$store.agentEditor.loadEditor(profile.id, false)"><x-icon name="edit"></x-icon>Edit</button>
- <button type="button" class="button danger" x-show="profile.deletable" @click="$store.agentEditor.deleteProfile(profile.id)"><x-icon name="delete"></x-icon>Delete</button>
+ <label class="toggle agent-profile-availability"
+ :title="`${profile.enabled ? 'Make unavailable' : 'Make available'} in ${$store.agentEditor.scopeLabel}`">
+ <input type="checkbox"
+ :checked="profile.enabled"
+ :disabled="$store.agentEditor.profileAvailabilitySaving"
+ :aria-label="`${profile.enabled ? 'Disable' : 'Enable'} ${profile.title || profile.id} in ${$store.agentEditor.scopeLabel}`"
+ @change="$store.agentEditor.setProfileEnabled(profile, $event.target.checked)"
+ @click.stop>
+ <span class="toggler"></span>
+ </label>
+ <button type="button" class="button icon-button" title="Edit" :aria-label="`Edit ${profile.title || profile.id}`" @click="$store.agentEditor.loadEditor(profile.id, false)"><x-icon class="icon" name="edit"></x-icon></button>
+ <button type="button" class="button cancel icon-button" x-show="profile.deletable" title="Delete" :aria-label="`Delete ${profile.title || profile.id}`" @click="$store.agentEditor.deleteProfile(profile.id)"><x-icon class="icon" name="delete"></x-icon></button>
</div>
</article>
</template>
@@ -81,7 +101,17 @@
<header class="agent-editor-topbar">
<div class="agent-editor-heading">
<button type="button" class="button icon" x-show="$store.agentEditor.intent.view === 'manage'" aria-label="Back to agents" @click="$store.agentEditor.showManager()"><x-icon name="arrow_back"></x-icon></button>
- <span class="agent-scope-indicator"><x-icon :name="$store.agentEditor.projectName ? 'folder' : 'public'"></x-icon><span>Scope:</span><strong x-text="$store.agentEditor.scopeLabel"></strong></span>
+ <label class="agent-scope-field agent-editor-scope">
+ <span>Project</span>
+ <select x-model="$store.agentEditor.projectName"
+ x-init="$nextTick(() => $el.value = $store.agentEditor.projectName)"
+ @change="$store.agentEditor.onScopeChanged()">
+ <option value="">Global</option>
+ <template x-for="project in $store.agentEditor.projects" :key="project.key">
+ <option :value="project.key" x-text="project.label"></option>
+ </template>
+ </select>
+ </label>
<div class="agent-editor-subtitle" x-show="$store.agentEditor.dirty">
<span class="agent-status-badge is-unsaved"><x-icon name="edit_note"></x-icon><span>Unsaved changes</span></span>
</div>
@@ -106,13 +136,13 @@
<button type="button" class="text-button" x-show="$store.agentEditor.state.profile.metadata.avatar.has_override || $store.agentEditor.draft.avatar" @click="$store.agentEditor.resetAvatar()">Remove</button>
</div>
</div>
- <label class="agent-field agent-name-field">
- <span class="agent-field-label">Agent name</span>
+ <div class="agent-field agent-name-field">
+ <label for="agent-editor-name" class="agent-field-label">Agent name</label>
<input id="agent-editor-name" type="text" x-model="$store.agentEditor.draft.title" @input="$store.agentEditor.onNameInput(); $store.agentEditor.markMetadataSet('title')" required autocomplete="off" :aria-invalid="$store.agentEditor.fieldIssue('name') ? 'true' : null" :aria-describedby="$store.agentEditor.fieldIssue('name') ? 'agent-editor-name-error' : null">
- </label>
- <div class="agent-id-feedback" x-show="$store.agentEditor.fieldIssue('name')">
- <span id="agent-editor-name-error" class="field-error" role="alert" x-text="$store.agentEditor.fieldIssue('name')?.message"></span>
- <button type="button" class="text-button" x-show="$store.agentEditor.profileConflict" @click="$store.agentEditor.openConflictingProfile()">Open existing agent</button>
+ <div class="agent-id-feedback" x-show="$store.agentEditor.fieldIssue('name')">
+ <span id="agent-editor-name-error" class="field-error" role="alert" x-text="$store.agentEditor.fieldIssue('name')?.message"></span>
+ <button type="button" class="text-button" x-show="$store.agentEditor.profileConflict" @click="$store.agentEditor.openConflictingProfile()">Open existing agent</button>
+ </div>
</div>
</section>
@@ -143,7 +173,7 @@
<div class="agent-advanced" x-show="$store.agentEditor.mode === 'advanced'">
<nav class="agent-advanced-nav" aria-label="Advanced editor sections">
- <template x-for="item in [{id:'1',label:'Identity & models'},{id:'2',label:'Prompt files'},{id:'3',label:'Tools'},{id:'4',label:'Skills'},{id:'5',label:'Review'}]" :key="item.id">
+ <template x-for="item in [{id:'1',label:'Identity'},{id:'2',label:'Prompt files'},{id:'3',label:'Tools'},{id:'4',label:'Skills'},{id:'5',label:'Review'}]" :key="item.id">
<button type="button" :class="{ active: $store.agentEditor.section === item.id }" :aria-current="$store.agentEditor.section === item.id ? 'step' : null" @click="$store.agentEditor.setSection(item.id)">
<span class="section-number" x-text="item.id"></span><span x-text="item.label"></span>
<span class="agent-status-badge compact" :class="$store.agentEditor.sectionIssues(item.id).length ? 'is-error' : 'is-unsaved'" x-show="$store.agentEditor.sectionIssues(item.id).length || $store.agentEditor.sectionDirty(item.id)"><x-icon :name="$store.agentEditor.sectionIssues(item.id).length ? 'error' : 'edit_note'"></x-icon><span x-text="$store.agentEditor.sectionIssues(item.id).length ? 'Needs attention' : 'Changed'"></span></span>
@@ -153,7 +183,7 @@
<div class="agent-advanced-content">
<section x-show="$store.agentEditor.section === '1'" data-agent-editor-section="1" tabindex="-1" aria-labelledby="agent-section-1-title">
- <header class="advanced-section-heading"><h3 id="agent-section-1-title">Identity & models</h3><p>Set the agent’s identity, delegation guidance, and model preset.</p></header>
+ <header class="advanced-section-heading"><h3 id="agent-section-1-title">Identity</h3><p>Set the agent’s identity, delegation guidance, and model preset.</p></header>
<div class="origin-row">
<span class="agent-origin" x-text="$store.agentEditor.state.profile.origin"></span>
<span class="agent-status-badge is-customized" x-show="$store.agentEditor.state.profile.scope_has_overrides"><x-icon name="edit_note"></x-icon><span>Customized by you</span></span>
@@ -175,21 +205,22 @@
<div class="agent-field"><label for="agent-editor-advanced-name" class="agent-field-label">Agent name</label><input id="agent-editor-advanced-name" type="text" x-model="$store.agentEditor.draft.title" @input="$store.agentEditor.onNameInput(); $store.agentEditor.markMetadataSet('title')" :aria-invalid="$store.agentEditor.fieldIssue('name') ? 'true' : null" :aria-describedby="$store.agentEditor.fieldIssue('name') ? 'agent-editor-advanced-name-error' : null"><span id="agent-editor-advanced-name-error" class="field-error" role="alert" x-show="$store.agentEditor.fieldIssue('name')" x-text="$store.agentEditor.fieldIssue('name')?.message"></span><small class="field-provenance" x-text="$store.agentEditor.metadataProvenance('title')"></small><button type="button" class="text-button" x-show="$store.agentEditor.canResetMetadata('title')" @click="$store.agentEditor.resetMetadata('title')">Reset to inherited</button><small class="field-status" x-show="$store.agentEditor.metadataResetPending('title')">Will reset to inherited on save.</small></div>
<label class="agent-field"><span class="agent-field-label">Profile ID</span><input type="text" :value="$store.agentEditor.draft.profileId" readonly aria-describedby="profile-id-help"><small id="profile-id-help">Used as the profile folder name. Existing IDs do not change when the display name changes.</small></label>
<div class="agent-field wide"><label for="agent-editor-description" class="agent-field-label">Description</label><textarea id="agent-editor-description" rows="2" x-model="$store.agentEditor.draft.description" @input="$store.agentEditor.markMetadataSet('description')"></textarea><small>Short summary shown in profile lists.</small><small class="field-provenance" x-text="$store.agentEditor.metadataProvenance('description')"></small><button type="button" class="text-button" x-show="$store.agentEditor.canResetMetadata('description')" @click="$store.agentEditor.resetMetadata('description')">Reset to inherited</button><small class="field-status" x-show="$store.agentEditor.metadataResetPending('description')">Will reset to inherited on save.</small></div>
+ <div class="agent-field wide agent-model-preset">
+ <label for="agent-editor-model-preset" class="agent-field-label">Model preset</label>
+ <div class="agent-model-preset-picker">
+ <select id="agent-editor-model-preset" x-model="$store.agentEditor.draft.modelPreset">
+ <option value="" x-text="`Use current preset (${$store.agentEditor.state.model_preset.effective})`"></option>
+ <template x-for="preset in $store.agentEditor.state.model_presets" :key="preset.name">
+ <option :value="preset.name" x-text="preset.name"></option>
+ </template>
+ </select>
+ <button type="button" class="button" @click="$store.agentEditor.openPresetManager()"><x-icon class="icon" name="tune"></x-icon>Edit Presets</button>
+ </div>
+ <small>Use the current preset or choose another setup for this agent.</small>
+ </div>
<div class="agent-field wide"><label for="agent-editor-context" class="agent-field-label">When should other agents use this agent?</label><textarea id="agent-editor-context" rows="3" x-model="$store.agentEditor.draft.context" @input="$store.agentEditor.markMetadataSet('context')"></textarea><small>Helps Agent Zero decide when to delegate work to this profile.</small><small class="field-provenance" x-text="$store.agentEditor.metadataProvenance('context')"></small><button type="button" class="text-button" x-show="$store.agentEditor.canResetMetadata('context')" @click="$store.agentEditor.resetMetadata('context')">Reset to inherited</button><small class="field-status" x-show="$store.agentEditor.metadataResetPending('context')">Will reset to inherited on save.</small><span class="field-status" x-show="!$store.agentEditor.draft.context">Delegation quality can be lower while this is empty.</span></div>
</div>
</div>
- <div class="agent-model-preset">
- <label class="agent-model-preset-picker">
- <span><span class="agent-field-label">Model preset</span><small>Use the current preset or choose another setup for this agent.</small></span>
- <select x-model="$store.agentEditor.draft.modelPreset">
- <option value="" x-text="`Use current preset (${$store.agentEditor.state.model_preset.effective})`"></option>
- <template x-for="preset in $store.agentEditor.state.model_presets" :key="preset.name">
- <option :value="preset.name" x-text="preset.name"></option>
- </template>
- </select>
- </label>
- <button type="button" class="button" @click="$store.agentEditor.openPresetManager()"><x-icon class="icon" name="tune"></x-icon>Edit Presets</button>
- </div>
</section>
<section x-show="$store.agentEditor.section === '2'" data-agent-editor-section="2" tabindex="-1" aria-labelledby="agent-section-2-title">
@@ -301,7 +332,6 @@
<button type="button" class="btn btn-cancel" x-show="$store.agentEditor.view === 'editor'" @click="window.closeModal?.()">Cancel</button>
</div>
<div class="footer-actions">
- <button type="button" class="btn btn-ok" x-show="$store.agentEditor.view === 'manage'" @click="$store.agentEditor.loadEditor('new-agent', true)">Create agent</button>
<button type="button" class="btn agent-editor-secondary-action" x-show="$store.agentEditor.view === 'editor' && !$store.agentEditor.draft?.creating" @click="$store.agentEditor.save(true)" :disabled="$store.agentEditor.saving || $store.agentEditor.validationIssues().length > 0">Save & test</button>
<button type="button" class="btn btn-ok" x-show="$store.agentEditor.view === 'editor'" @click="$store.agentEditor.save(false)" :disabled="$store.agentEditor.saving || $store.agentEditor.avatarUploading || $store.agentEditor.validationIssues().length > 0" :title="$store.agentEditor.validationIssues().length ? 'Fix the highlighted issues before saving' : ''"><span x-text="$store.agentEditor.saving ? 'Saving…' : $store.agentEditor.draft?.creating ? 'Create agent' : 'Save changes'"></span></button>
</div>
@@ -334,10 +364,7 @@
.agent-editor-error span { flex:1; white-space:pre-wrap; }
.agent-editor-loading { min-height:20rem; display:grid; place-content:center; justify-items:center; gap:.65rem; color:var(--color-text-secondary); }
.agent-editor-topbar { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom:1rem; }
- .agent-editor-heading { display:flex; align-items:center; gap:.6rem; }
- .agent-scope-indicator { display:inline-flex; align-items:center; gap:.3rem; min-width:0; color:var(--color-text-secondary); font-size:.78rem; }
- .agent-scope-indicator strong { max-width:18rem; overflow:hidden; color:var(--color-text); text-overflow:ellipsis; white-space:nowrap; }
- .agent-scope-indicator x-icon { font-size:1rem; }
+ .agent-editor-heading { display:flex; flex:1 1 auto; flex-wrap:wrap; align-items:center; gap:.6rem; min-width:0; }
.agent-editor-subtitle { margin-top:.2rem; font-size:.78rem; color:var(--color-text-secondary); }
.agent-status-badge { display:inline-flex; align-items:center; gap:.25rem; max-width:100%; padding:.2rem .45rem; border:1px solid var(--color-border); border-radius:999px; font-size:.7rem; font-weight:500; line-height:1.2; white-space:normal; }
.agent-status-badge x-icon { flex:0 0 auto; font-size:.85rem; }
@@ -362,10 +389,11 @@
.agent-name-field { align-self:start; }
.agent-field-label { font-weight:650; font-size:.92rem; }
.agent-field input,.agent-field textarea,.agent-easy textarea,.prompt-find input,.policy-filters input,.policy-filters select,.compact-search input { width:100%; box-sizing:border-box; }
- .agent-field small,.agent-field-heading p,.agent-id-feedback,.field-status { color:var(--color-text-secondary); font-size:.79rem; }
+ .agent-field small,.agent-field-heading p,.field-status { color:var(--color-text-secondary); font-size:.79rem; }
.field-status { display:block; margin-top:.15rem; }
- .field-error { display:block; color:var(--color-text-secondary); font-size:.79rem; }
- .agent-id-feedback { grid-column:2; margin-top:-.6rem; }
+ .field-error { display:block; color:var(--color-text); font-size:.79rem; font-weight:600; line-height:1.35; }
+ .agent-id-feedback { display:flex; flex-wrap:wrap; align-items:center; gap:.35rem .65rem; }
+ .agent-easy-field .field-error { margin-top:.35rem; }
.agent-field-heading { display:flex; justify-content:space-between; gap:1rem; align-items:flex-start; margin-bottom:.5rem; }
.agent-editor .text-button { display:inline-flex; align-items:center; min-height:1.5rem; border:0; padding:0; background:transparent; color:var(--agent-editor-action); cursor:pointer; font-size:.82rem; text-align:left; }
.agent-editor .text-button:hover { text-decoration:underline; }
@@ -392,12 +420,9 @@
.advanced-avatar { align-self:start; }
.identity-fields { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:.9rem; }
.identity-fields .agent-field.wide { grid-column:1/-1; }
- .agent-model-preset { display:flex; flex-direction:column; align-items:flex-start; gap:.75rem; }
- .agent-model-preset-picker { width:100%; display:grid; grid-template-columns:minmax(0,1fr) minmax(13rem,18rem); align-items:center; gap:1rem; margin:0; }
- .agent-model-preset-picker > span { display:flex; flex-direction:column; gap:.2rem; min-width:0; }
- .agent-model-preset-picker small { color:var(--color-text-secondary); font-size:.79rem; }
+ .agent-model-preset-picker { width:100%; display:grid; grid-template-columns:minmax(13rem,18rem) auto; align-items:center; justify-content:space-between; gap:1rem; }
.agent-model-preset-picker select { width:100%; }
- .agent-model-preset > .button { display:inline-flex; align-items:center; gap:.35rem; }
+ .agent-model-preset-picker > .button { display:inline-flex; align-items:center; gap:.35rem; }
.prompt-workspace { display:grid; grid-template-columns:minmax(13rem,16rem) minmax(0,1fr); gap:.8rem; min-width:0; height:34rem; }
.prompt-browser { display:flex; flex-direction:column; min-width:0; min-height:0; height:100%; border:1px solid var(--color-border); border-radius:10px; overflow:hidden; }
.compact-search { display:flex; align-items:center; gap:.3rem; padding:.45rem; border-bottom:1px solid var(--color-border); }
@@ -424,9 +449,9 @@
.prompt-find span { color:var(--color-text-secondary); font-size:.75rem; white-space:nowrap; }
.prompt-panes { display:grid; grid-template-columns:1fr; gap:.65rem; min-height:18rem; }
.prompt-panes.compare { grid-template-columns:1fr 1fr; }
- .prompt-pane { min-width:0; display:flex; flex-direction:column; gap:.35rem; }
+ .prompt-pane { min-width:0; min-height:0; display:flex; flex-direction:column; gap:.35rem; }
.prompt-pane label,.prompt-pane-title { color:var(--color-text-secondary); font-size:.75rem; }
- .prompt-pane textarea,.prompt-pane pre,.effective-preview pre { flex:1; box-sizing:border-box; width:100%; min-height:18rem; margin:0; padding:.75rem; overflow:auto; border:1px solid var(--color-border); border-radius:8px; background:var(--color-input); color:var(--color-text); font:13px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace; white-space:pre-wrap; tab-size:2; resize:vertical; }
+ .prompt-pane textarea,.prompt-pane pre,.effective-preview pre { flex:1; box-sizing:border-box; width:100%; min-height:0; margin:0; padding:.75rem; overflow:auto; border:1px solid var(--color-border); border-radius:8px; background:var(--color-input); color:var(--color-text); font:13px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace; white-space:pre-wrap; tab-size:2; resize:vertical; }
.prompt-pane textarea:focus-visible { outline-offset:-2px; }
.prompt-pane.inherited pre { opacity:.86; }
.effective-preview { border:1px solid var(--color-border); border-radius:8px; padding:.55rem .7rem; }
@@ -482,24 +507,31 @@
.agent-editor .button.danger { display:inline-flex; align-items:center; gap:.35rem; border-color:color-mix(in srgb,var(--agent-editor-danger) 60%,var(--color-border)); color:var(--agent-editor-danger); background:color-mix(in srgb,var(--agent-editor-danger) 7%,var(--color-panel)); }
.agent-editor .button.danger:hover { background:color-mix(in srgb,var(--agent-editor-danger) 15%,var(--color-panel)); }
.agent-manager { display:flex; flex-direction:column; gap:1rem; }
- .agent-scope-selector { overflow:hidden; border:1px solid var(--color-border); border-radius:4px; }
- .agent-scope-header { padding:.75rem 1rem; border-bottom:1px solid var(--color-border); background:var(--color-bg-secondary); }
- .agent-scope-copy { min-width:0; }
- .agent-scope-copy strong { color:var(--color-text-primary); font-size:var(--font-size-normal); font-weight:600; }
- .agent-scope-copy p { margin-top:.25rem; color:var(--color-text-secondary); font-size:var(--font-size-small); }
- .agent-scope-toolbar { display:flex; padding:1rem; }
+ .agent-scope-selector { padding:.75rem 1rem; border:1px solid var(--color-border); border-radius:4px; }
.agent-scope-field { display:flex; flex:1 1 0; align-items:center; gap:.5rem; min-width:12rem; margin:0; }
.agent-scope-field span { color:var(--color-text-secondary); font-weight:600; white-space:nowrap; }
.agent-scope-field select { flex:1 1 auto; min-width:0; }
- .agent-manager-intro,.agent-manager-copy p { color:var(--color-text-secondary); font-size:.82rem; }
+ .agent-editor-scope { flex:0 1 24rem; }
+ .agent-manager-copy p { color:var(--color-text-secondary); font-size:.82rem; }
+ .agent-manager-list-header { display:flex; align-items:center; justify-content:flex-end; gap:1rem; }
+ .active-agent-display { display:flex; align-items:center; gap:.5rem; min-width:0; margin-right:auto; padding:.5rem; border:1px solid var(--color-highlight); border-radius:.5rem; }
+ .active-agent-summary { display:flex; align-items:center; gap:.5rem; min-width:0; }
+ .active-agent-summary strong { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+ .active-agent-avatar { width:1.5rem; aspect-ratio:1; display:grid; flex:0 0 auto; place-items:center; overflow:hidden; border-radius:6px; color:#fff; font-size:.65rem; font-weight:700; }
+ .active-agent-avatar img { width:100%; height:100%; object-fit:cover; }
+ .agent-manager-create { flex:0 0 auto; display:inline-flex; align-items:center; gap:.35rem; }
.agent-manager-list { display:flex; flex-direction:column; gap:.55rem; }
.agent-manager-card { display:grid; grid-template-columns:3rem minmax(0,1fr) auto; gap:.75rem; align-items:center; padding:.75rem; border:1px solid var(--color-border); border-radius:10px; }
.agent-manager-avatar { width:3rem; aspect-ratio:1; display:grid; place-items:center; border-radius:10px; color:white; font-weight:700; overflow:hidden; }
.agent-manager-avatar img { width:100%; height:100%; object-fit:cover; }
.agent-manager-copy { min-width:0; }
.agent-manager-name { display:flex; flex-wrap:wrap; align-items:center; gap:.4rem; }
- .agent-manager-copy code { font-size:.7rem; color:var(--color-text-secondary); }
- .agent-manager-actions { display:flex; flex-wrap:wrap; gap:.4rem; }
+ .agent-customized-indicator { display:inline-grid; place-items:center; color:var(--color-text-secondary); }
+ .agent-customized-indicator x-icon { font-size:1rem; }
+ .agent-editor .agent-manager-inline-action { gap:.25rem; margin-top:.15rem; color:var(--color-message-text); opacity:.7; }
+ .agent-editor .agent-manager-inline-action:hover:not(:disabled) { background:transparent; color:var(--color-text); text-decoration:none; opacity:1; }
+ .agent-manager-actions { display:flex; flex-wrap:wrap; align-items:center; gap:.4rem; }
+ .agent-profile-availability input { width:0; height:0; margin:0; border:0; }
.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
.toast-link { border:0; background:transparent; color:var(--agent-editor-action); text-decoration:underline; cursor:pointer; }
.agent-editor :focus-visible { outline:2px solid var(--agent-editor-action); outline-offset:2px; }
@@ -509,10 +541,12 @@
.modal-inner.agent-editor-advanced .agent-editor,.modal-inner.agent-editor-advanced .agent-editor-workspace { min-height:100%; }
@media (max-width: 760px) {
.modal-inner.agent-editor-easy,.modal-inner.agent-editor-advanced { width:100vw; max-width:none; height:100vh; max-height:none; border-radius:0; }
- .agent-editor-topbar { align-items:flex-start; }
+ .agent-editor-topbar { align-items:flex-start; flex-wrap:wrap; }
+ .agent-editor-heading { width:100%; }
+ .agent-editor-scope { flex:1 1 14rem; }
.agent-easy-identity { grid-template-columns:1fr; justify-items:center; padding-top:1.8rem; }
.agent-name-field { width:100%; }
- .agent-id-feedback { grid-column:1; width:100%; margin:0; }
+ .agent-id-feedback { width:100%; }
.agent-advanced { grid-template-columns:1fr; }
.agent-advanced-nav { position:static; flex-direction:row; overflow-x:auto; }
.agent-advanced-nav button { grid-template-columns:auto auto auto; white-space:nowrap; }
@@ -526,6 +560,9 @@
.identity-fields .agent-field.wide { grid-column:1; }
.policy-filters { grid-template-columns:1fr; }
.policy-list { min-height:20rem; }
+ .agent-manager-list-header { flex-wrap:wrap; }
+ .active-agent-display { width:100%; }
+ .agent-manager-create { margin-left:auto; }
.agent-manager-card { grid-template-columns:3rem minmax(0,1fr); }
.agent-manager-actions { grid-column:1/-1; justify-content:flex-end; }
.agent-scope-field { flex-basis:100%; min-width:0; }
diff --git a/plugins/_model_config/AGENTS.md b/plugins/_model_config/AGENTS.md
index 2d288c6b3..e68e7ed34 100644
--- a/plugins/_model_config/AGENTS.md
+++ b/plugins/_model_config/AGENTS.md
@@ -28,7 +28,9 @@
- `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.
-- The adjacent agent-profile selector reads the always-enabled Agent Editor list endpoint directly so the active profile shows its effective title and avatar.
+- The adjacent agent-profile selector reads the always-enabled Agent Editor list endpoint directly so the active profile shows its effective title and avatar, and omits profiles disabled in the chat's current scope.
+- Reload the agent-profile selector catalog when a chat changes project or
+ active profile so project-only profiles never linger in the visible choices.
- 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/apply_snapshot_before/refresh-switcher.js b/plugins/_model_config/extensions/webui/apply_snapshot_before/refresh-switcher.js
index 87fcaeb10..e85b3c419 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
@@ -26,6 +26,7 @@ export default async function refreshSwitcherOnOverrideRevision(ctx) {
String(projectName),
String(activeContext?.agent_profile || ""),
]);
+ const scopeChanged = contextId !== lastContextId || scopeKey !== lastScopeKey;
if (
contextId === lastContextId
@@ -36,5 +37,6 @@ export default async function refreshSwitcherOnOverrideRevision(ctx) {
lastContextId = contextId;
lastRevision = revision;
lastScopeKey = scopeKey;
+ if (scopeChanged) await modelConfigStore.loadAgentProfiles(true);
await modelConfigStore.refreshSwitcher(contextId);
}
diff --git a/plugins/_model_config/webui/switcher-mixin.js b/plugins/_model_config/webui/switcher-mixin.js
index e149a96ff..1977a324c 100644
--- a/plugins/_model_config/webui/switcher-mixin.js
+++ b/plugins/_model_config/webui/switcher-mixin.js
@@ -48,7 +48,7 @@ export const switcherMethods = {
context_id: contextId,
});
this.agentProfiles = (data.profiles || [])
- .filter(profile => profile.id && profile.id !== "_example")
+ .filter(profile => profile.id && profile.id !== "_example" && profile.enabled !== false)
.map(profile => ({
key: profile.id,
label: profile.title || profile.id,
diff --git a/tests/test_agent_editor.py b/tests/test_agent_editor.py
index a764bc775..9d05fe549 100644
--- a/tests/test_agent_editor.py
+++ b/tests/test_agent_editor.py
@@ -559,6 +559,135 @@ def test_display_title_change_keeps_profile_id_and_builtin_delete_is_rejected(
assert not (user_root / "renamed-display").exists()
+def test_profile_availability_is_a_sparse_global_override(user_root: Path) -> None:
+ disabled = editor.plan_profile_enabled("researcher", False)
+
+ assert list(disabled.changes) == [user_root / "researcher" / "agent.yaml"]
+ editor.apply_change_plan(disabled)
+ assert yaml_helper.loads(
+ (user_root / "researcher" / "agent.yaml").read_text(encoding="utf-8")
+ ) == {"enabled": False}
+
+ restored = editor.plan_profile_enabled("researcher", True)
+ editor.apply_change_plan(restored)
+ assert not (user_root / "researcher" / "agent.yaml").exists()
+
+
+def test_default_profile_can_be_disabled_when_another_profile_is_available(
+ user_root: Path,
+ project_scope: tuple[editor._EditorContext, Path],
+) -> None:
+ context, _ = project_scope
+
+ editor.set_profile_enabled("default", False)
+ assert yaml_helper.loads(
+ (user_root / "default" / "agent.yaml").read_text(encoding="utf-8")
+ ) == {"enabled": False}
+ editor.set_profile_enabled("default", True)
+ assert not (user_root / "default" / "agent.yaml").exists()
+
+ editor.set_profile_enabled("default", False, context)
+ assert editor.projects.load_project_subagents("demo") == {
+ "default": {"enabled": False}
+ }
+
+
+def test_last_available_profile_cannot_be_disabled(
+ user_root: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ editor.subagents,
+ "get_available_agents_dict",
+ lambda _project=None: {
+ "default": editor.subagents.SubAgentListItem(name="default")
+ },
+ )
+
+ with pytest.raises(ValueError, match="At least one agent profile"):
+ editor.set_profile_enabled("default", False)
+
+ assert not (user_root / "default").exists()
+
+
+def test_duplicate_profile_materializes_the_effective_profile(
+ user_root: Path,
+) -> None:
+ plan, title = editor.plan_duplicate_profile("developer")
+
+ assert plan.profile_id == "developer-1"
+ assert title == "Developer 1"
+ assert all(path.is_relative_to(user_root / "developer-1") for path in plan.changes)
+ editor.apply_change_plan(plan)
+
+ duplicate = user_root / "developer-1"
+ metadata = yaml_helper.loads(
+ (duplicate / "agent.yaml").read_text(encoding="utf-8")
+ )
+ assert metadata["title"] == "Developer 1"
+ assert metadata["description"] == "Agent specialized in complex software development."
+ assert "enabled" not in metadata
+ assert (duplicate / "prompts" / editor.SPECIFICS_FILE).read_bytes() == (
+ Path("agents/developer/prompts") / editor.SPECIFICS_FILE
+ ).read_bytes()
+ assert not (duplicate / "AGENTS.md").exists()
+
+ next_plan, next_title = editor.plan_duplicate_profile("developer")
+ assert next_plan.profile_id == "developer-2"
+ assert next_title == "Developer 2"
+
+
+def test_duplicate_profile_targets_the_selected_project(
+ project_scope: tuple[editor._EditorContext, Path],
+) -> None:
+ context, project_agents = project_scope
+
+ plan, title = editor.plan_duplicate_profile("developer", context)
+
+ assert plan.project_name == "demo"
+ assert plan.profile_id == "developer-1"
+ assert title == "Developer 1"
+ assert all(
+ path.is_relative_to(project_agents / "developer-1")
+ for path in plan.changes
+ )
+
+
+def test_project_profile_availability_uses_project_settings(
+ project_scope: tuple[editor._EditorContext, Path],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ context, _ = project_scope
+ reconciled: list[tuple[tuple, dict]] = []
+ monkeypatch.setattr(
+ editor.projects,
+ "reconcile_agent_profiles",
+ lambda *args, **kwargs: reconciled.append((args, kwargs)),
+ )
+ monkeypatch.setattr(
+ editor.subagents,
+ "get_agents_dict",
+ lambda _project=None: {
+ "default": editor.subagents.SubAgentListItem(
+ name="default", enabled=True
+ ),
+ "researcher": editor.subagents.SubAgentListItem(
+ name="researcher", enabled=True
+ )
+ },
+ )
+
+ editor.set_profile_enabled("researcher", False, context)
+
+ assert editor.projects.load_project_subagents("demo") == {
+ "researcher": {"enabled": False}
+ }
+
+ editor.set_profile_enabled("researcher", True, context)
+
+ assert editor.projects.load_project_subagents("demo") == {}
+ assert reconciled == [(("demo",), {"all_scopes": False})]
+
+
def test_save_rolls_back_every_file_after_commit_failure(
user_root: Path,
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/test_agent_editor_webui.py b/tests/test_agent_editor_webui.py
index 86215c2ec..da8548355 100644
--- a/tests/test_agent_editor_webui.py
+++ b/tests/test_agent_editor_webui.py
@@ -26,6 +26,7 @@ SWITCHER_MIXIN = ROOT / "plugins" / "_model_config" / "webui" / "switcher-mixin.
def test_agent_editor_surface_has_normative_entry_points_and_accessible_controls() -> None:
modal = MODAL.read_text(encoding="utf-8")
+ store = STORE.read_text(encoding="utf-8")
switcher = SWITCHER.read_text(encoding="utf-8")
tool_section = re.search(
r'data-agent-editor-section="3".*?(?=<section x-show="\$store\.agentEditor\.section === \'4\'")',
@@ -55,7 +56,7 @@ def test_agent_editor_surface_has_normative_entry_points_and_accessible_controls
assert all(
label in modal
for label in (
- "Identity & models",
+ "Identity",
"Prompt files",
"Tools",
"Skills",
@@ -100,9 +101,31 @@ def test_agent_editor_surface_has_normative_entry_points_and_accessible_controls
assert 'x-for="project in $store.agentEditor.projects"' in modal
assert 'x-show="profile.deletable"' in modal
assert 'x-show="profile.scope_has_overrides"' in modal
+ assert 'class="agent-customized-indicator"' in modal
+ assert 'title="Customized"' in modal
+ assert 'class="button agent-manager-create"' in modal
+ assert 'class="active-agent-display"' in modal
+ assert 'class="button icon-button" title="Edit"' in modal
+ assert 'class="text-button agent-manager-inline-action"' in modal
+ inline_action_style = re.search(
+ r"\.agent-editor \.agent-manager-inline-action\s*\{([^}]*)\}", modal
+ ).group(1)
+ assert "color:var(--color-message-text)" in inline_action_style
+ assert ".agent-editor .agent-manager-inline-action:hover:not(:disabled)" in modal
+ assert ':disabled="!!$store.agentEditor.duplicatingProfile"' in modal
+ assert ':aria-label="`Duplicate ${profile.title || profile.id}`"' in modal
+ assert "$store.agentEditor.duplicateProfile(profile)" in modal
+ assert 'class="toggle agent-profile-availability"' in modal
+ assert ':disabled="$store.agentEditor.profileAvailabilitySaving"' in modal
+ assert "Default is always available" not in modal
+ assert "$store.agentEditor.setProfileEnabled(profile, $event.target.checked)" in modal
+ assert "agent-profile-availability" not in store
+ assert "activateProfile(profile.id)" not in modal
+ assert 'class="button cancel icon-button" x-show="profile.deletable"' in modal
assert "project_override_active" not in modal
assert "profile.origin === 'Custom'" not in modal
- assert "Scope:" in modal
+ assert "Agent scope" not in modal
+ assert "Create agents and customize inherited profiles" not in modal
assert "Unavailable — kept in your settings" in modal
assert "Customize this file" not in modal
assert 'role="tablist" aria-label="Prompt view"' in modal
@@ -143,15 +166,9 @@ def test_agent_editor_surface_has_normative_entry_points_and_accessible_controls
assert 'aria-label="Accept current edit"' in modal
assert ':readonly="!$store.agentEditor.isPromptEditing' not in modal
assert ".prompt-pane textarea:focus-visible { outline-offset:-2px; }" in modal
- assert all(
- label in STORE.read_text(encoding="utf-8")
- for label in (
- "Model preset",
- "Projects using this agent",
- "Open chats using this agent",
- "Saved settings",
- )
- )
+ store_source = STORE.read_text(encoding="utf-8")
+ assert "cannot be recovered" in store_source
+ assert "deletionImpactHtml" not in store_source
assert "agent-profile-avatar" in switcher
assert '<button type="button" class="model-switcher-item agent-profile-item"' in switcher
assert '<div class="model-switcher-item agent-profile-item"' not in switcher
@@ -163,15 +180,16 @@ def test_agent_editor_surface_has_normative_entry_points_and_accessible_controls
assert ".easy-tool-summary" not in modal
assert "grid-template-columns:minmax(0,1fr) 2.5rem minmax(0,1fr)" in modal
assert ".policy-lists .policy-transfer-actions { flex-direction:row; }" in modal
- store_source = STORE.read_text(encoding="utf-8")
assert "easyToolsOpen" not in store_source
assert "easySkills" not in store_source
assert "get toolMode" not in store_source
assert "get easyTools" not in store_source
assert "firstSentence" not in store_source
assert '.agent-editor [aria-invalid="true"]' not in modal
- assert ".field-error { display:block; color:var(--color-text-secondary)" in modal
+ assert ".field-error { display:block; color:var(--color-text)" in modal
+ assert ".prompt-pane { min-width:0; min-height:0;" in modal
assert 'callJsonApi("/plugins/_agent_editor/agent_editor"' in switcher_mixin
+ assert "profile.enabled !== false" in switcher_mixin
assert "@keydown.ctrl.s.prevent" in modal
assert "@media (max-width: 760px)" in modal
assert modal.count("data-modal-footer") == 1
@@ -199,9 +217,19 @@ def test_local_slugging_and_fresh_chat_profile_selection_are_deterministic() ->
harness = r"""
const calls = [];
const confirmations = [];
+let setEnabledHandler = null;
const createStore = (_name, value) => value;
const callJsonApi = async (endpoint, payload) => {
calls.push({ endpoint, payload });
+ if (payload?.action === "set_enabled") return setEnabledHandler
+ ? setEnabledHandler(payload)
+ : { ok: true, active_profile: "default", active_profile_label: "Default" };
+ if (payload?.action === "duplicate") return {
+ ok: true,
+ profile_id: "researcher-1",
+ title: "Researcher 1",
+ profiles: [{ id: "researcher" }, { id: "researcher-1" }],
+ };
return endpoint === "/chat_create" ? { ok: true, ctxid: "fresh-chat" } : { ok: true };
};
const fetchApi = async () => ({ ok: true, json: async () => ({}) });
@@ -210,10 +238,15 @@ const openModal = async () => {};
const showConfirmDialog = async options => { confirmations.push(options); return false; };
const chatsStore = {
selected: "old-chat",
+ selectedContext: { project: { name: "demo" }, agent_profile: "researcher" },
selectChat: async (id) => calls.push({ endpoint: "selectChat", payload: id }),
};
const modelConfigStore = {
- loadAgentProfiles: async () => {},
+ loadAgentProfiles: async force => calls.push({ endpoint: "loadAgentProfiles", payload: force }),
+ selectAgentProfile: async (contextId, profileId) => {
+ calls.push({ endpoint: "selectAgentProfile", payload: { contextId, profileId } });
+ return true;
+ },
getAgentProfileVisual: (_id, label) => ({ color: "#123456", url: "", initials: label?.[0] || "A" }),
};
globalThis.window = globalThis;
@@ -298,6 +331,43 @@ store.state.tools.effective_policy = { mode: "inherit", default: "block", allowe
store.chooseTools();
if (store.draft.toolPolicy.default !== "allow" || store.draft.toolPolicy.blocked.length) throw new Error("inactive inherited exceptions leaked into custom policy");
store.projectName = "demo";
+store.intent = { ...store.intent, projectName: "demo" };
+if (!store.currentChatUsesScope() || !store.isProfileActive("researcher")) throw new Error("active project profile state mismatch");
+store.profiles = [{ id: "researcher", title: "Researcher", enabled: true }, { id: "default", title: "Default", enabled: true }];
+if (store.activeProfile()?.id !== "researcher") throw new Error("active profile summary mismatch");
+await store.setProfileEnabled(store.profiles[0], false);
+if (!calls.some(item => item.payload?.action === "set_enabled" && item.payload.profile_id === "researcher") || chatsStore.selectedContext.agent_profile !== "default") throw new Error("profile availability did not reconcile the active chat");
+if (!calls.some(item => item.endpoint === "loadAgentProfiles" && item.payload === true)) throw new Error("profile switcher did not refresh eagerly");
+let releaseFirstToggle;
+const firstToggleResponse = new Promise(resolve => { releaseFirstToggle = resolve; });
+let toggleRequest = 0;
+setEnabledHandler = () => {
+ toggleRequest += 1;
+ return toggleRequest === 1
+ ? firstToggleResponse
+ : Promise.resolve({ ok: true });
+};
+const rapidProfiles = [
+ { id: "agent0", title: "Agent 0", enabled: true },
+ { id: "developer", title: "Developer", enabled: true },
+];
+store.profiles = rapidProfiles;
+const firstToggle = store.setProfileEnabled(rapidProfiles[0], false);
+while (!toggleRequest) await Promise.resolve();
+const secondToggle = store.setProfileEnabled(rapidProfiles[1], false);
+await secondToggle;
+if (toggleRequest !== 1 || rapidProfiles[1].enabled !== true || !store.profileAvailabilitySaving) throw new Error("availability saves were not serialized");
+releaseFirstToggle({ ok: true });
+await firstToggle;
+if (store.profiles !== rapidProfiles || rapidProfiles[0].enabled || rapidProfiles[1].enabled !== true || store.profileAvailabilitySaving) throw new Error("first availability save did not settle cleanly");
+await store.setProfileEnabled(rapidProfiles[1], false);
+if (toggleRequest !== 2 || rapidProfiles[1].enabled || store.profileAvailabilitySaving) throw new Error("availability gate did not reopen after save");
+setEnabledHandler = null;
+await store.duplicateProfile({ id: "researcher", title: "Researcher" });
+if (!calls.some(item => item.payload?.action === "duplicate" && item.payload.profile_id === "researcher") || !store.profiles.some(profile => profile.id === "researcher-1")) throw new Error("profile duplication failed");
+store.projectName = "other";
+if (store.currentChatUsesScope() || store.isProfileActive("default")) throw new Error("foreign project profile appeared active");
+store.projectName = "demo";
store.state.tools.effective_policy = { mode: "custom", default: "allow", allowed: [], blocked: ["local:shell"] };
store.useStandardTools();
if (store.isToolAllowed(store.state.tools.catalog[0])) throw new Error("project scope ignored inherited tool restriction");
@@ -381,6 +451,13 @@ await store.applyPendingMutation();
if (confirmations.length !== 1 || confirmations[0].type !== "danger") throw new Error("danger confirmation missing");
if (!confirmations[0].message.includes("agent.yaml") || !confirmations[0].message.includes("old.md")) throw new Error("planned paths missing from confirmation");
if (confirmations[0].title !== "Delete all customizations for this profile?") throw new Error("cleanup confirmation title mismatch");
+confirmations.length = 0;
+calls.length = 0;
+store.projectName = "";
+await store.deleteProfile("custom-agent");
+if (calls.length) throw new Error("cancelled deletion made an API request");
+if (confirmations.length !== 1 || confirmations[0].title !== "Delete custom-agent?") throw new Error("delete confirmation mismatch");
+if (confirmations[0].message !== "<p>This agent profile will be permanently deleted from Global and cannot be recovered.</p>") throw new Error("delete confirmation is not concise");
"""
module_source = harness + "\n" + source + "\n" + checks
module_url = "data:text/javascript;base64," + base64.b64encode(
diff --git a/tests/test_model_config_api_keys.py b/tests/test_model_config_api_keys.py
index fdc4190a8..468246913 100644
--- a/tests/test_model_config_api_keys.py
+++ b/tests/test_model_config_api_keys.py
@@ -206,6 +206,7 @@ def test_model_switcher_frontend_renders_custom_overrides():
assert "_model_config_override_revision" in refresh_extension_content
assert "activeContext?.agent_profile" in refresh_extension_content
assert "activeContext?.project" in refresh_extension_content
+ assert "modelConfigStore.loadAgentProfiles(true)" in refresh_extension_content
assert "modelConfigStore.refreshSwitcher(contextId)" in refresh_extension_content
diff --git a/tests/test_projects.py b/tests/test_projects.py
index 0a2192ebb..242e4227c 100644
--- a/tests/test_projects.py
+++ b/tests/test_projects.py
@@ -1,6 +1,13 @@
+import threading
from pathlib import Path
+from types import SimpleNamespace
-from helpers import dirty_json, files, projects
+import pytest
+
+import initialize
+from agent import AgentConfig, AgentContext
+from helpers import dirty_json, files, persist_chat, projects, subagents
+from helpers import state_monitor_integration
def _prepare_project_tree(monkeypatch, tmp_path: Path) -> None:
@@ -10,6 +17,215 @@ def _prepare_project_tree(monkeypatch, tmp_path: Path) -> None:
(tmp_path / "plugins").mkdir(parents=True, exist_ok=True)
+ "destination_project", ["project-y", None], ids=["project", "global"]
+)
+def test_project_switch_resets_only_profiles_missing_from_the_new_scope(
+ monkeypatch, destination_project
+):
+ context_id = "ctx-project-profile-switch"
+ AgentContext.remove(context_id)
+ context = AgentContext(
+ config=AgentConfig(mcp_servers="", profile="project-only"),
+ id=context_id,
+ set_current=False,
+ )
+ monkeypatch.setattr(
+ projects,
+ "load_edit_project_data",
+ lambda name: {"title": name.title(), "color": ""},
+ )
+ monkeypatch.setattr(persist_chat, "save_tmp_chat", lambda _context: None)
+ monkeypatch.setattr(
+ subagents,
+ "get_agents_dict",
+ lambda project_name=None: {
+ "agent0": subagents.SubAgentListItem(name="agent0"),
+ **(
+ {
+ "project-only": subagents.SubAgentListItem(
+ name="project-only"
+ )
+ }
+ if project_name == "project-x"
+ else {}
+ ),
+ },
+ )
+ monkeypatch.setattr(
+ initialize,
+ "initialize_agent",
+ lambda override_settings=None: AgentConfig(
+ mcp_servers="",
+ profile=(override_settings or {}).get("agent_profile", "agent0"),
+ ),
+ )
+
+ try:
+ projects.activate_project(context_id, "project-x", mark_dirty=False)
+ assert context.config.profile == "project-only"
+
+ if destination_project:
+ projects.activate_project(
+ context_id, destination_project, mark_dirty=False
+ )
+ else:
+ projects.deactivate_project(context_id, mark_dirty=False)
+ assert context.config.profile == "agent0"
+ assert context.agent0.config.profile == "agent0"
+ finally:
+ AgentContext.remove(context_id)
+
+
+def test_project_agent_availability_retains_project_only_profiles(
+ monkeypatch,
+) -> None:
+ monkeypatch.setattr(
+ subagents,
+ "get_agents_dict",
+ lambda project_name=None: {
+ "global": subagents.SubAgentListItem(name="global", enabled=True),
+ **(
+ {
+ "project-only": subagents.SubAgentListItem(
+ name="project-only", enabled=True
+ )
+ }
+ if project_name == "demo"
+ else {}
+ ),
+ },
+ )
+
+ assert projects._normalize_subagents(
+ {
+ "global": {"enabled": True},
+ "project-only": {"enabled": False},
+ "missing": {"enabled": False},
+ },
+ "demo",
+ ) == {"project-only": {"enabled": False}}
+
+
+def test_profile_reconciliation_uses_an_available_fallback(monkeypatch) -> None:
+ context_id = "ctx-profile-availability-fallback"
+ AgentContext.remove(context_id)
+ context = AgentContext(
+ config=AgentConfig(mcp_servers="", profile="disabled"),
+ id=context_id,
+ set_current=False,
+ )
+ monkeypatch.setattr(
+ subagents,
+ "get_available_agents_dict",
+ lambda _project_name: {
+ "researcher": subagents.SubAgentListItem(name="researcher")
+ },
+ )
+ monkeypatch.setattr(
+ initialize,
+ "initialize_agent",
+ lambda override_settings=None: AgentConfig(
+ mcp_servers="",
+ profile=(override_settings or {}).get("agent_profile", "default"),
+ ),
+ )
+
+ try:
+ assert projects.reconcile_agent_profile(context, None) is True
+ assert context.config.profile == "researcher"
+ assert context.agent0.config.profile == "researcher"
+ finally:
+ AgentContext.remove(context_id)
+
+
+def test_context_lookup_reconciles_only_new_contexts(monkeypatch) -> None:
+ from helpers.context_utils import use_context
+
+ existing_id = "ctx-existing-profile"
+ created_id = "ctx-new-profile"
+ AgentContext.remove(existing_id)
+ AgentContext.remove(created_id)
+ existing = AgentContext(
+ config=AgentConfig(mcp_servers="", profile="default"),
+ id=existing_id,
+ set_current=False,
+ )
+ reconciled: list[str] = []
+ monkeypatch.setattr(
+ initialize,
+ "initialize_agent",
+ lambda: AgentConfig(mcp_servers="", profile="default"),
+ )
+ monkeypatch.setattr(
+ projects,
+ "reconcile_agent_profile",
+ lambda context, _project: reconciled.append(context.id),
+ )
+
+ try:
+ assert use_context(threading.RLock(), existing_id) is existing
+ assert reconciled == []
+
+ assert use_context(threading.RLock(), created_id).id == created_id
+ assert reconciled == [created_id]
+ finally:
+ AgentContext.remove(existing_id)
+ AgentContext.remove(created_id)
+
+
+ ("all_scopes", "expected"),
+ [
+ (False, ["global-changed"]),
+ (True, ["global-changed", "project-changed"]),
+ ],
+)
+def test_bulk_profile_reconciliation_persists_only_changed_chats(
+ monkeypatch, all_scopes: bool, expected: list[str]
+) -> None:
+ unchanged = SimpleNamespace(id="global-unchanged", project=None)
+ global_changed = SimpleNamespace(id="global-changed", project=None)
+ project_changed = SimpleNamespace(id="project-changed", project="demo")
+ saved: list[str] = []
+ dirty: list[str] = []
+ catalog_lookups: list[str | None] = []
+ monkeypatch.setattr(
+ AgentContext,
+ "all",
+ classmethod(
+ lambda _cls: [unchanged, global_changed, project_changed]
+ ),
+ )
+ monkeypatch.setattr(
+ projects, "get_context_project_name", lambda context: context.project
+ )
+ monkeypatch.setattr(
+ projects,
+ "reconcile_agent_profile",
+ lambda context, _project, _available: context is not unchanged,
+ )
+ monkeypatch.setattr(
+ subagents,
+ "get_available_agents_dict",
+ lambda project: catalog_lookups.append(project) or {},
+ )
+ monkeypatch.setattr(
+ persist_chat, "save_tmp_chat", lambda context: saved.append(context.id)
+ )
+ monkeypatch.setattr(
+ state_monitor_integration,
+ "mark_dirty_for_context",
+ lambda context_id, **_kwargs: dirty.append(context_id),
+ )
+
+ projects.reconcile_agent_profiles(None, all_scopes=all_scopes)
+
+ assert saved == expected
+ assert dirty == expected
+ assert catalog_lookups == ([None, "demo"] if all_scopes else [None])
+
+
def test_project_include_agents_md_defaults_true_and_saves(monkeypatch, tmp_path):
_prepare_project_tree(monkeypatch, tmp_path)
meta = tmp_path / "usr" / "projects" / "demo" / ".a0proj"
diff --git a/tests/test_subagent_metadata_merge.py b/tests/test_subagent_metadata_merge.py
index 7794a55e6..db82950d3 100644
--- a/tests/test_subagent_metadata_merge.py
+++ b/tests/test_subagent_metadata_merge.py
@@ -1,6 +1,6 @@
from pathlib import Path
-from helpers import subagents
+from helpers import projects, subagents
def _write_profile(root: Path, name: str, metadata: str = "") -> Path:
@@ -76,6 +76,13 @@ def test_nonexistent_layer_is_not_an_override(tmp_path: Path) -> None:
)
+def test_bundled_directory_without_definition_is_not_a_profile(tmp_path: Path) -> None:
+ root = tmp_path / "agents"
+ _write_profile(root, "_example")
+
+ assert subagents._get_agents_list_from_dir(str(root), "default") == {}
+
+
def test_default_specifics_uses_only_the_canonical_prompt_path() -> None:
root = Path(__file__).resolve().parents[1]
legacy = root / "agents" / "default" / "agent.system.main.specifics.md"
@@ -90,3 +97,38 @@ def test_default_specifics_uses_only_the_canonical_prompt_path() -> None:
assert not legacy.exists()
assert canonical.is_file()
assert canonical.read_bytes() == b""
+
+
+def test_available_agents_include_project_profiles_and_project_overrides(
+ monkeypatch,
+) -> None:
+ requested = []
+ monkeypatch.setattr(
+ subagents,
+ "get_agents_dict",
+ lambda project_name=None: requested.append(project_name) or {
+ "_example": subagents.SubAgentListItem(
+ name="_example", enabled=True
+ ),
+ "default": subagents.SubAgentListItem(
+ name="default", enabled=False
+ ),
+ "global": subagents.SubAgentListItem(name="global", enabled=True),
+ "project-only": subagents.SubAgentListItem(
+ name="project-only", enabled=True
+ ),
+ },
+ )
+ monkeypatch.setattr(
+ projects,
+ "load_project_subagents",
+ lambda _name: {
+ "default": {"enabled": False},
+ "global": {"enabled": False},
+ },
+ )
+
+ available = subagents.get_available_agents_dict("demo")
+
+ assert requested == ["demo"]
+ assert list(available) == ["project-only"]
diff --git a/tests/test_subagent_profiles.py b/tests/test_subagent_profiles.py
index d6a81abf7..605e83fd3 100644
--- a/tests/test_subagent_profiles.py
+++ b/tests/test_subagent_profiles.py
@@ -5,7 +5,7 @@ from types import SimpleNamespace
import pytest
from agent import Agent, AgentConfig, AgentContext
-from helpers import persist_chat
+from helpers import persist_chat, projects
from helpers.errors import RepairableException
@@ -182,14 +182,19 @@ def test_persist_chat_roundtrip_preserves_each_agent_profile(monkeypatch) -> Non
AgentContext.remove(context_id)
[email protected]("project_name", [None, "demo"], ids=["global", "project"])
@pytest.mark.asyncio
-async def test_agent_profile_set_preserves_subagent_profile(monkeypatch) -> None:
+async def test_agent_profile_set_uses_scope_and_preserves_subagent_profile(
+ monkeypatch, project_name
+) -> None:
import api.agent_profile_set as agent_profile_set
+ requested_scopes = []
monkeypatch.setattr(
- agent_profile_set,
- "_agent_profile_labels",
- lambda: {"researcher": "Researcher"},
+ agent_profile_set.subagents,
+ "get_agents_dict",
+ lambda scope: requested_scopes.append(scope)
+ or {"researcher": SimpleNamespace(title="Researcher", enabled=True)},
)
monkeypatch.setattr(
agent_profile_set,
@@ -216,6 +221,8 @@ async def test_agent_profile_set_preserves_subagent_profile(monkeypatch) -> None
child = Agent(1, AgentConfig(mcp_servers="", profile="developer"), context)
context.agent0.set_data(Agent.DATA_NAME_SUBORDINATE, child)
child.set_data(Agent.DATA_NAME_SUPERIOR, context.agent0)
+ if project_name:
+ context.set_data(projects.CONTEXT_DATA_KEY_PROJECT, project_name)
try:
handler = agent_profile_set.SetAgentProfile.__new__(
@@ -230,5 +237,6 @@ async def test_agent_profile_set_preserves_subagent_profile(monkeypatch) -> None
assert context.config.profile == "researcher"
assert context.agent0.config.profile == "researcher"
assert child.config.profile == "developer"
+ assert requested_scopes == [project_name]
finally:
AgentContext.remove(context_id)