Agent Zero AI framework
Refactor API key handling and update system improvements
frdele680256b2934
diff --git a/api/self_update_tags.py b/api/self_update_tags.pynew file mode 100644index 000000000..591d6beea--- /dev/null+++ b/api/self_update_tags.py@@ -0,0 +1,35 @@+from helpers.api import ApiHandler, Request, Response++from helpers import runtime+from helpers import self_update+++class SelfUpdateTags(ApiHandler):+ async def process(self, input: dict, request: Request) -> dict | Response:+ branch = str(input.get("branch", "")).strip().lower()+ query = str(input.get("query", ""))+ current_branch = self_update.get_repo_version_info().get("branch", "").strip().lower()+ default_branch = current_branch if current_branch in self_update.SUPPORTED_BRANCHES else "main"++ try:+ tags, error = self_update.get_available_tags(+ branch or None,+ query=query,+ )+ return {+ "success": True,+ "supported": runtime.is_dockerized(),+ "branch": branch or default_branch,+ "query": query,+ "tags": tags,+ "error": error,+ }+ except Exception as e:+ return {+ "success": False,+ "supported": runtime.is_dockerized(),+ "branch": branch or "main",+ "query": query,+ "tags": [],+ "error": str(e),+ }diff --git a/conf/dummy_update_test.txt b/conf/dummy_update_test.txtindex e69de29bb..07436c4ba 100644--- a/conf/dummy_update_test.txt+++ b/conf/dummy_update_test.txt@@ -0,0 +1 @@+Dummy file to test the update system.\ No newline at end of filediff --git a/extensions/python/banners/_20_missing_api_key.py b/extensions/python/banners/_20_missing_api_key.pyindex 7535712bf..7e236c136 100644--- a/extensions/python/banners/_20_missing_api_key.py+++ b/extensions/python/banners/_20_missing_api_key.py@@ -1,6 +1,6 @@from helpers.extension import Extensionfrom helpers import plugins-import models+from plugins._model_config.helpers import model_configclass MissingApiKeyCheck(Extension):@@ -8,6 +8,13 @@ class MissingApiKeyCheck(Extension):LOCAL_PROVIDERS = {"ollama", "lm_studio"}LOCAL_EMBEDDING = {"huggingface"}+ CONFIGURE_MODEL_SETTINGS_LINK = (+ """<a href="#" onclick="(async()=>{"""+ """const { store: s } = await import('/components/plugins/plugin-settings-store.js');"""+ """if(s&&s.openConfig){await s.openConfig('_model_config');}"""+ """})();return false;">"""+ """Configure model settings</a>"""+ )async def execute(self, banners: list = [], frontend_context: dict = {}, **kwargs):cfg = plugins.get_plugin_config("_model_config") or {}@@ -28,8 +35,10 @@ class MissingApiKeyCheck(Extension):if label == "Embedding Model" and provider_lower in self.LOCAL_EMBEDDING:continue- api_key = models.get_api_key(provider_lower)- if not (api_key and api_key.strip() and api_key != "None"):+ if not model_config.has_provider_api_key(+ provider_lower,+ model_cfg.get("api_key", ""),+ ):missing_providers.append({"model_type": label,"provider": provider,@@ -47,8 +56,7 @@ class MissingApiKeyCheck(Extension):"title": "Missing LLM API Key for current settings","html": f"""No API key configured for: {model_list}.<br>Agent Zero will not be able to function properly unless you provide an API key or change your settings.<br>- <a href="#" onclick="(async()=>{{await import('/components/plugins/plugin-settings-store.js');const s=Alpine.store('pluginSettingsPrototype');if(s&&s.open){{await s.open('_model_config',{{perProjectConfig:true,perAgentConfig:true}});}}openModal('components/plugins/plugin-settings.html');}})();return false;">- Configure model settings</a>""",+ {self.CONFIGURE_MODEL_SETTINGS_LINK}""","dismissible": False,"source": "backend"})@@ -73,8 +81,7 @@ class MissingApiKeyCheck(Extension):# Skip if preset has its own api_keyif slot.get("api_key", "").strip():continue- api_key = models.get_api_key(provider_lower)- if not (api_key and api_key.strip() and api_key != "None"):+ if not model_config.has_provider_api_key(provider_lower):seen.add(provider_lower)preset_missing.append(f"{preset_name}/{slot_label} ({provider})")@@ -87,8 +94,7 @@ class MissingApiKeyCheck(Extension):"title": "Missing API Key for model presets","html": f"""No API key configured for preset models: {preset_list}.<br>These presets will not work until you provide the required API keys.<br>- <a href="#" onclick="(async()=>{{await import('/components/plugins/plugin-settings-store.js');const s=Alpine.store('pluginSettingsPrototype');if(s&&s.open){{await s.open('_model_config',{{perProjectConfig:true,perAgentConfig:true}});}}openModal('components/plugins/plugin-settings.html');}})();return false;">- Configure model settings</a>""",+ {self.CONFIGURE_MODEL_SETTINGS_LINK}""","dismissible": True,"source": "backend"})diff --git a/helpers/self_update.py b/helpers/self_update.pyindex 332bb0d74..f0fb91897 100644--- a/helpers/self_update.py+++ b/helpers/self_update.py@@ -17,6 +17,7 @@ BRANCH_OPTIONS = [{"value": "testing", "label": "testing"},{"value": "development", "label": "development"},]+SUPPORTED_BRANCHES = {option["value"] for option in BRANCH_OPTIONS}BACKUP_CONFLICT_POLICIES = {"rename", "overwrite", "fail"}UPDATE_FILE_PATH = Path("/exe/a0-self-update.yaml")@@ -133,7 +134,12 @@ def get_repo_version_info(repo_dir: str | Path | None = None) -> dict[str, str]:repository = get_repo_dir(repo_dir)describe = _run_git(repository, "describe", "--tags", "--always")commit = _run_git(repository, "rev-parse", "HEAD")+ try:+ branch = _run_git(repository, "branch", "--show-current")+ except Exception:+ branch = ""return {+ "branch": branch,"describe": describe,"short_tag": _normalize_describe_to_version(describe),"commit": commit,@@ -162,9 +168,7 @@ def build_default_backup_name(target_tag: str | None = None,) -> str:timestamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")- current_slug = _slugify_version(current_version)- target_slug = _slugify_version(target_tag or current_version)- return f"agent-zero-usr-{current_slug}-to-{target_slug}-{timestamp}.zip"+ return f"usr-{timestamp}.zip"def _resolve_backup_path(@@ -180,18 +184,58 @@ def _resolve_backup_path(return path.resolve()-def get_available_tags() -> tuple[list[str], str]:+def _get_branch_reference_names(branch: str) -> list[str]:+ normalized_branch = branch.strip().lower()+ if normalized_branch not in SUPPORTED_BRANCHES:+ return []+ return [f"origin/{normalized_branch}", normalized_branch]+++def _get_branch_merged_tags(+ branch: str,+ repo_dir: str | Path | None = None,+) -> set[str]:+ repository = get_repo_dir(repo_dir)+ for ref in _get_branch_reference_names(branch):+ try:+ _run_git(repository, "rev-parse", "--verify", ref)+ output = _run_git(repository, "tag", "--merged", ref)+ return {line.strip() for line in output.splitlines() if line.strip()}+ except Exception:+ continue+ return set()+++def get_available_tags(+ branch: str | None = None,+ *,+ repo_dir: str | Path | None = None,+ query: str = "",+) -> tuple[list[str], str]:result = git.get_remote_releases(OFFICIAL_REPO_AUTHOR, OFFICIAL_REPO_NAME)if result.error:return [], result.error- return [release.tag for release in result.releases], ""+ tags = [release.tag for release in result.releases]++ if branch:+ merged_tags = _get_branch_merged_tags(branch, repo_dir=repo_dir)+ if merged_tags:+ tags = [tag for tag in tags if tag in merged_tags]++ normalized_query = query.strip().lower()+ if normalized_query:+ tags = [tag for tag in tags if normalized_query in tag.lower()]++ return tags, ""def get_update_info(repo_dir: str | Path | None = None) -> dict[str, Any]:repository = get_repo_dir(repo_dir)version_info = get_repo_version_info(repository)current_version = version_info["short_tag"]- tags, tags_error = get_available_tags()+ current_branch = version_info.get("branch", "").strip().lower()+ default_branch = current_branch if current_branch in SUPPORTED_BRANCHES else "main"+ tags, tags_error = get_available_tags(default_branch, repo_dir=repository)return {"repo_dir": str(repository),"current": version_info,@@ -206,7 +250,7 @@ def get_update_info(repo_dir: str | Path | None = None) -> dict[str, Any]:"log_file": str(get_log_file_path()),},"defaults": {- "branch": "main",+ "branch": default_branch,"tag": current_version,"backup_usr": True,"backup_path": str(get_default_backup_dir(repository)),@@ -230,7 +274,7 @@ def schedule_update(version_info = get_repo_version_info(repository)normalized_branch = branch.strip().lower()- if normalized_branch not in {option["value"] for option in BRANCH_OPTIONS}:+ if normalized_branch not in SUPPORTED_BRANCHES:raise ValueError("Branch must be one of: main, testing, development.")normalized_tag = tag.strip()diff --git a/models.py b/models.pyindex 7be6aca9d..265dae12b 100644--- a/models.py+++ b/models.py@@ -68,6 +68,7 @@ class ModelConfig:type: ModelTypeprovider: strname: str+ api_key: str = ""api_base: str = ""ctx_length: int = 0limit_requests: int = 0@@ -78,6 +79,8 @@ class ModelConfig:def build_kwargs(self):kwargs = self.kwargs.copy() or {}+ if self.api_key and "api_key" not in kwargs:+ kwargs["api_key"] = self.api_keyif self.api_base and "api_base" not in kwargs:kwargs["api_base"] = self.api_basereturn kwargsdiff --git a/plugins/_model_config/api/model_config_set.py b/plugins/_model_config/api/model_config_set.pyindex c58013d3b..cabaf300a 100644--- a/plugins/_model_config/api/model_config_set.py+++ b/plugins/_model_config/api/model_config_set.py@@ -1,7 +1,11 @@+from copy import deepcopy+from helpers.api import ApiHandler, Request, Response-from helpers import plugins, defer+from helpers import plugins, defer, dotenvfrom helpers.extension import call_extensions_async+API_KEY_PLACEHOLDER = "************"+class ModelConfigSet(ApiHandler):async def process(self, input: dict, request: Request) -> dict | Response:@@ -12,6 +16,22 @@ class ModelConfigSet(ApiHandler):if not config or not isinstance(config, dict):return Response(status=400, response="Missing or invalid config")+ config_to_save = deepcopy(config)+ for section_name in ("chat_model", "utility_model", "embedding_model"):+ section = config_to_save.get(section_name, {})+ if not isinstance(section, dict):+ continue+ provider = str(section.get("provider", "")).strip()+ api_key = section.get("api_key", "")+ if (+ provider+ and isinstance(api_key, str)+ and api_key.strip()+ and api_key != API_KEY_PLACEHOLDER+ ):+ dotenv.save_dotenv_value(f"API_KEY_{provider.upper()}", api_key)+ section.pop("api_key", None)+# Read previous config BEFORE saving so we can detect changesprev_config = plugins.get_plugin_config("_model_config",@@ -23,12 +43,12 @@ class ModelConfigSet(ApiHandler):"_model_config",project_name=project_name,agent_profile=agent_profile,- settings=config,+ settings=config_to_save,)# Check if embedding model changed and notifyprev_embed = prev_config.get("embedding_model", {})- new_embed = config.get("embedding_model", {})+ new_embed = config_to_save.get("embedding_model", {})if (prev_embed.get("provider") != new_embed.get("provider")or prev_embed.get("name") != new_embed.get("name")diff --git a/plugins/_model_config/helpers/model_config.py b/plugins/_model_config/helpers/model_config.pyindex 28d2f5e5d..81fd4ca73 100644--- a/plugins/_model_config/helpers/model_config.py+++ b/plugins/_model_config/helpers/model_config.py@@ -6,6 +6,8 @@ from helpers.providers import get_providersPRESETS_FILE = "presets.yaml"DEFAULT_PRESETS_FILE = "default_presets.yaml"+LOCAL_PROVIDERS = {"ollama", "lm_studio"}+LOCAL_EMBEDDING = {"huggingface"}def _get_presets_path() -> str:@@ -158,6 +160,7 @@ def build_model_config(cfg: dict, model_type: models.ModelType) -> models.ModelCtype=model_type,provider=cfg.get("provider", ""),name=cfg.get("name", ""),+ api_key=cfg.get("api_key", ""),api_base=cfg.get("api_base", ""),ctx_length=int(cfg.get("ctx_length", 0)),vision=bool(cfg.get("vision", False)),@@ -222,14 +225,20 @@ def get_embedding_providers():return get_providers("embedding")+def has_provider_api_key(provider: str, configured_api_key: str = "") -> bool:+ configured_value = (configured_api_key or "").strip()+ if configured_value and configured_value != "None":+ return True++ api_key = models.get_api_key(provider.lower())+ return bool(api_key and api_key.strip() and api_key != "None")++def get_missing_api_key_providers(agent=None) -> list[dict]:"""Check which configured providers are missing API keys."""cfg = get_config(agent)missing = []- LOCAL_PROVIDERS = {"ollama", "lm_studio"}- LOCAL_EMBEDDING = {"huggingface"}-checks = [("Chat Model", cfg.get("chat_model", {})),("Utility Model", cfg.get("utility_model", {})),@@ -246,8 +255,7 @@ def get_missing_api_key_providers(agent=None) -> list[dict]:if label == "Embedding Model" and provider_lower in LOCAL_EMBEDDING:continue- api_key = models.get_api_key(provider_lower)- if not (api_key and api_key.strip() and api_key != "None"):+ if not has_provider_api_key(provider_lower, model_cfg.get("api_key", "")):missing.append({"model_type": label, "provider": provider})return missingdiff --git a/plugins/_model_config/hooks.py b/plugins/_model_config/hooks.pyindex 75ada70db..5c632dd4c 100644--- a/plugins/_model_config/hooks.py+++ b/plugins/_model_config/hooks.py@@ -4,4 +4,5 @@ def save_plugin_config(result=None, settings=None, **kwargs):for section in ("chat_model", "utility_model", "embedding_model"):if section in settings and isinstance(settings[section], dict):settings[section].pop("_kwargs_text", None)+ settings[section].pop("api_key", None)return settingsdiff --git a/plugins/_model_config/webui/api-keys.html b/plugins/_model_config/webui/api-keys.htmlindex 4730425d0..4189a3d18 100644--- a/plugins/_model_config/webui/api-keys.html+++ b/plugins/_model_config/webui/api-keys.html@@ -10,12 +10,61 @@<div x-data><template x-if="$store.modelConfig">-<div x-data="{ keys: {}, loading: true }"- x-init="- await $store.modelConfig.ensureLoaded();- $store.modelConfig.allProviders.forEach(p => keys[p.value] = '');- loading = false;- ">+<div x-data="{+ keys: {},+ originalKeys: {},+ touched: {},+ loading: true,+ saving: false,+ error: '',+ get hasChanges() {+ return Object.keys(this.touched).some((provider) => this.touched[provider]);+ },+ async init() {+ await $store.modelConfig.ensureLoaded();+ await $store.modelConfig.refreshApiKeyStatus();+ $store.modelConfig.allProviders.forEach((provider) => {+ this.keys[provider.value] = '';+ this.originalKeys[provider.value] = '';+ this.touched[provider.value] = false;+ });+ this.loading = false;+ },+ markChanged(provider) {+ this.touched[provider] = this.keys[provider] !== this.originalKeys[provider];+ },+ async reveal(provider) {+ try {+ const value = await $store.modelConfig.revealApiKey(provider);+ this.keys[provider] = value || '';+ this.originalKeys[provider] = value || '';+ this.touched[provider] = false;+ } catch (e) {+ this.error = e?.message || 'Failed to reveal API key.';+ }+ },+ async saveAndClose() {+ this.saving = true;+ this.error = '';+ try {+ const updates = {};+ for (const provider of Object.keys(this.touched)) {+ if (!this.touched[provider]) continue;+ const value = (this.keys[provider] || '').trim();+ if (!value) continue;+ updates[provider] = value;+ }+ await $store.modelConfig.saveApiKeys(updates);+ await $store.modelConfig.refreshApiKeyStatus();+ window.closeModal?.();+ } catch (e) {+ this.error = e?.message || 'Failed to save API keys.';+ } finally {+ this.saving = false;+ }+ }+ }"+ x-init="init()"><div class="api-keys-section"><div class="section-title">API Keys</div>@@ -24,6 +73,11 @@For more information about Agent Zero Venice provider, see <a href="http://agent-zero.ai/?community/api-dashboard/about" target="_blank">Agent Zero Venice</a>.</div>+ <div x-show="error" class="plugin-settings-error" style="margin-top: 1rem;">+ <span class="material-symbols-outlined">error</span>+ <span x-text="error"></span>+ </div>+<div x-show="loading" style="text-align:center; padding: 20px;"><span class="material-symbols-outlined spinning">progress_activity</span></div>@@ -39,13 +93,13 @@x-model="keys[provider.value]":placeholder="provider.has_key ? '••••••••••••' : ''"autocomplete="off"- @input.debounce.800ms="keys[provider.value] && $store.modelConfig.saveApiKey(provider.value, keys[provider.value])"+ @input="markChanged(provider.value)"style="padding-right:32px;" /><span class="material-symbols-outlined eye-toggle"@click="showKey = !showKey;if (showKey && !keys[provider.value] && provider.has_key) {- $store.modelConfig.revealApiKey(provider.value).then(v => { if (v) keys[provider.value] = v; });+ reveal(provider.value);}"x-text="showKey ? 'visibility' : 'visibility_off'"></span>@@ -56,7 +110,16 @@</div><div class="modal-footer" data-modal-footer>- <button class="btn btn-cancel" @click="closeModal()">Close</button>+ <button class="btn btn-ok"+ @click="saveAndClose()"+ :disabled="loading || saving || !hasChanges">+ Save+ </button>+ <button class="btn btn-cancel"+ @click="window.closeModal?.()"+ :disabled="saving">+ Close+ </button></div></div></template>diff --git a/plugins/_model_config/webui/config.html b/plugins/_model_config/webui/config.htmlindex a62047731..591a0679b 100644--- a/plugins/_model_config/webui/config.html+++ b/plugins/_model_config/webui/config.html@@ -10,7 +10,9 @@<div x-datax-init="await $store.modelConfig.ensureLoaded();+ await $store.modelConfig.refreshApiKeyStatus();$store.modelConfig.initConfigFields(config);+ $store.modelConfig.installPluginSettingsSaveHook(context, config);const _origReset = context.resetToDefault.bind(context);context.resetToDefault = async () => {const before = context.settings;@@ -117,7 +119,6 @@x-model="$store.modelConfig.apiKeyValues[config[section.key].provider]":placeholder="$store.modelConfig.apiKeyStatus[config[section.key].provider] ? '••••••••••••' : ''"autocomplete="off"- @input.debounce.800ms="$store.modelConfig.saveApiKeyIfSet(config[section.key].provider)"style="padding-right:32px;" /><span class="material-symbols-outlined eye-toggle"@click="diff --git a/plugins/_model_config/webui/model-config-store.js b/plugins/_model_config/webui/model-config-store.jsindex aeff3adbb..867a95f1b 100644--- a/plugins/_model_config/webui/model-config-store.js+++ b/plugins/_model_config/webui/model-config-store.js@@ -67,6 +67,22 @@ export const store = createStore("modelConfig", {init() {},+ _setProviderHasKey(provider, hasKey) {+ if (!provider) return;+ this.apiKeyStatus = { ...this.apiKeyStatus, [provider]: !!hasKey };+ const normalized = provider.toLowerCase();+ this.allProviders = (this.allProviders || []).map((item) =>+ item.value?.toLowerCase() === normalized ? { ...item, has_key: !!hasKey } : item+ );+ },++ _ensureApiKeySlot(provider) {+ if (!provider) return;+ if (!(provider in this.apiKeyValues)) {+ this.apiKeyValues = { ...this.apiKeyValues, [provider]: '' };+ }+ },+_normalizePresets(rawPresets) {return (rawPresets || []).map(p => ({name: p.name || '',@@ -103,6 +119,35 @@ export const store = createStore("modelConfig", {this._loaded = true;},+ async refreshApiKeyStatus() {+ await this.ensureLoaded();+ const res = await fetchApi(`${API_BASE}/api_keys`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ action: 'get' })+ });+ const data = await res.json();+ const keys = data.keys || {};++ const nextStatus = { ...this.apiKeyStatus };+ const nextValues = { ...this.apiKeyValues };++ for (const provider of this.allProviders) {+ const entry = keys[provider.value] || {};+ const hasKey = !!entry.has_key;+ nextStatus[provider.value] = hasKey;+ provider.has_key = hasKey;+ if (!hasKey && !nextValues[provider.value]) {+ nextValues[provider.value] = '';+ }+ }++ this.apiKeyStatus = nextStatus;+ this.apiKeyValues = nextValues;+ this.allProviders = [...this.allProviders];+ return keys;+ },+async _fetchConfigData() {const res = await fetchApi(`${API_BASE}/model_config_get`, {method: 'POST',@@ -180,15 +225,39 @@ export const store = createStore("modelConfig", {},// API Key operations- async saveApiKey(provider, value) {- await fetchApi(`${API_BASE}/api_keys`, {+ async saveApiKeys(updates) {+ const normalized = {};+ for (const [provider, value] of Object.entries(updates || {})) {+ if (!provider || typeof value !== 'string') continue;+ if (!value.trim()) continue;+ normalized[provider] = value;+ }++ if (Object.keys(normalized).length === 0) {+ return { ok: true };+ }++ const res = await fetchApi(`${API_BASE}/api_keys`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ action: 'set', keys: { [provider]: value } })+ body: JSON.stringify({ action: 'set', keys: normalized })});- this.apiKeyStatus = { ...this.apiKeyStatus, [provider]: true };- const ap = this.allProviders.find(x => x.value === provider);- if (ap) ap.has_key = true;+ const data = await res.json();+ if (!data?.ok) {+ throw new Error(data?.error || 'Failed to save API keys.');+ }++ const nextValues = { ...this.apiKeyValues };+ for (const [provider, value] of Object.entries(normalized)) {+ nextValues[provider] = value;+ this._setProviderHasKey(provider, true);+ }+ this.apiKeyValues = nextValues;+ return data;+ },++ async saveApiKey(provider, value) {+ return this.saveApiKeys({ [provider]: value });},saveApiKeyIfSet(provider) {@@ -203,7 +272,45 @@ export const store = createStore("modelConfig", {body: JSON.stringify({ action: 'reveal', provider })});const data = await res.json();- return data.value || '';+ if (!data?.ok) {+ throw new Error(data?.error || 'Failed to load API key.');+ }+ const value = data.value || '';+ if (provider && value) {+ this._ensureApiKeySlot(provider);+ this.apiKeyValues = { ...this.apiKeyValues, [provider]: value };+ this._setProviderHasKey(provider, true);+ }+ return value;+ },++ async persistApiKeysForConfig(config) {+ const updates = {};+ for (const section of this.MODEL_SECTIONS) {+ const provider = config?.[section.key]?.provider;+ if (!provider) continue;+ const value = this.apiKeyValues[provider];+ if (typeof value === 'string' && value.trim()) {+ updates[provider] = value;+ }+ }+ return this.saveApiKeys(updates);+ },++ installPluginSettingsSaveHook(context, config) {+ if (!context || context.__modelConfigSaveHookInstalled) return;+ const originalSave = context.save.bind(context);+ context.save = async () => {+ context.error = null;+ try {+ await this.persistApiKeysForConfig(config);+ } catch (e) {+ context.error = e?.message || 'Failed to save API keys.';+ return;+ }+ await originalSave();+ };+ context.__modelConfigSaveHookInstalled = true;},// Model searchdiff --git a/webui/components/settings/backup/backup-settings.html b/webui/components/settings/backup/backup-settings.htmlindex 4ebf3a0a3..147280e37 100644--- a/webui/components/settings/backup/backup-settings.html+++ b/webui/components/settings/backup/backup-settings.html@@ -1,6 +1,6 @@<html><head>- <title>Backup & Restore</title>+ <title>Update</title></head><body>@@ -9,6 +9,12 @@<div><nav><ul>+ <li>+ <a href="#section-self-update">+ <img src="/public/update_checker.svg" alt="Self Update" />+ <span>Self Update</span>+ </a>+ </li><li><a href="#section-backup-restore"><img src="/public/backup_restore.svg" alt="Backup & Restore" />@@ -18,6 +24,10 @@</ul></nav>+ <div id="section-self-update" class="section">+ <x-component path="settings/backup/self-update.html"></x-component>+ </div>+<div id="section-backup-restore" class="section"><x-component path="settings/backup/backup_restore.html"></x-component></div>diff --git a/webui/components/settings/backup/self-update.html b/webui/components/settings/backup/self-update.htmlnew file mode 100644index 000000000..63bbc8b31--- /dev/null+++ b/webui/components/settings/backup/self-update.html@@ -0,0 +1,51 @@+<html>+ <head>+ <title>Self Update</title>+ </head>++ <body>+ <div x-data>+ <div>+ <div class="section-title">Self Update</div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Open Self Update</div>+ <div class="field-description">+ Choose the target branch and tag, decide whether to zip <code>/a0/usr</code> first, and review the durable trigger, status, and log file locations used across restarts.+ </div>+ <template x-if="!$store.settings.additional?.is_dockerized">+ <div class="field-description">+ This action is currently available only in dockerized installs.+ </div>+ </template>+ </div>+ <div class="field-control">+ <button+ class="btn btn-field"+ @click="openModal('settings/external/self-update-modal.html')"+ :disabled="!$store.settings.additional?.is_dockerized"+ >+ Open Self Update+ </button>+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Enable Update Checker</div>+ <div class="field-description">+ Periodically check for newer Agent Zero releases and show a notification when an update is recommended.+ </div>+ </div>+ <div class="field-control">+ <label class="toggle">+ <input type="checkbox" x-model="$store.settings.settings.update_check_enabled" />+ <span class="toggler"></span>+ </label>+ </div>+ </div>+ </div>+ </div>+ </body>+</html>diff --git a/webui/components/settings/external/external-settings.html b/webui/components/settings/external/external-settings.htmlindex 1e248f09f..c64021fe0 100644--- a/webui/components/settings/external/external-settings.html+++ b/webui/components/settings/external/external-settings.html@@ -39,12 +39,6 @@<span>External API</span></a></li>- <li>- <a href="#section-update-checker">- <img src="/public/update_checker.svg" alt="Update Checker" />- <span>Update Checker</span>- </a>- </li><li><a href="#section-tunnel"><img src="/public/tunnel.svg" alt="Tunnel" />@@ -69,10 +63,6 @@<div id="section-external-api" class="section"><x-component path="settings/external/external_api.html"></x-component></div>- <div id="section-update-checker" class="section">- <x-component path="settings/external/update_checker.html"></x-component>- </div>-<!-- Tunnel section content --><div id="section-tunnel" class="section"><x-component path="settings/tunnel/tunnel-section.html"></x-component>diff --git a/webui/components/settings/external/self-update-modal.html b/webui/components/settings/external/self-update-modal.htmlindex 932181fcd..26b930ce7 100644--- a/webui/components/settings/external/self-update-modal.html+++ b/webui/components/settings/external/self-update-modal.html@@ -14,26 +14,30 @@x-destroy="$store.selfUpdateStore.cleanup()"class="self-update-modal">- <div class="self-update-copy">- <p>- Agent Zero saves this request into- <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>,- restarts once, applies the requested branch and release tag before the UI- starts again, then reloads this page when <code>/api/health</code> is healthy.- </p>- <p>- If the updated UI does not become healthy within 2 minutes, the bootstrap- manager in <code>/exe</code> restores the previous checkout and starts that- version again, so even an older downgraded <code>/a0</code> can be upgraded back- by creating the YAML file manually.- </p>- </div>+ <details class="self-update-howto">+ <summary>How it works?</summary>+ <div class="self-update-copy">+ <p>+ Agent Zero saves this request into+ <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>,+ restarts once, applies the requested branch and release tag before the UI+ starts again, then reloads this page when <code>/api/health</code> is healthy.+ </p>+ <p>+ If the updated UI does not become healthy within 2 minutes, the bootstrap+ manager in <code>/exe</code> restores the previous checkout and starts that+ version again, so even an older downgraded <code>/a0</code> can be upgraded back+ by creating the YAML file manually.+ </p>+ </div>+ </details><div class="self-update-summary-grid"><div class="self-update-summary-card"><div class="summary-label">Current version</div><div class="summary-value" x-text="$store.selfUpdateStore.currentVersion"></div><div class="summary-meta" x-text="$store.selfUpdateStore.info?.current?.short_commit || ''"></div>+ <div class="summary-meta" x-text="$store.selfUpdateStore.currentBranch || ''"></div></div><div class="self-update-summary-card" x-show="$store.selfUpdateStore.info?.pending">@@ -94,6 +98,7 @@<div class="field-control"><selectx-model="$store.selfUpdateStore.form.branch"+ @change="$store.selfUpdateStore.onBranchChanged()":disabled="$store.selfUpdateStore.isBusy"><template x-for="branch in ($store.selfUpdateStore.info?.branches || [])" :key="branch.value">@@ -107,28 +112,52 @@<div class="field-label"><div class="field-title">Target release tag</div><div class="field-description">- Start typing or pick one of the tags fetched from the official repo. Downgrades are allowed.+ Start typing to filter, or use the search button to fetch tags from the selected branch. Exact text entry is still allowed, including downgrades.</div>- <template x-if="$store.selfUpdateStore.info?.available_tags_error">+ <template x-if="$store.selfUpdateStore.tagsError"><div class="field-description">Tag lookup failed:- <span x-text="$store.selfUpdateStore.info?.available_tags_error"></span>+ <span x-text="$store.selfUpdateStore.tagsError"></span></div></template></div>- <div class="field-control">+ <div class="field-control self-update-tag-search" @click.outside="$store.selfUpdateStore.closeTagDropdown()"><inputtype="text"- list="self-update-tag-list"x-model="$store.selfUpdateStore.form.tag"+ @input="$store.selfUpdateStore.onTagInput()"+ @focus="$store.selfUpdateStore.openTagDropdown()"+ @keydown.enter.prevent="$store.selfUpdateStore.searchTags()"placeholder="v0.9.0":disabled="$store.selfUpdateStore.isBusy"+ style="padding-right: 32px;"/>- <datalist id="self-update-tag-list">- <template x-for="tag in $store.selfUpdateStore.availableTags" :key="tag">- <option :value="tag"></option>+ <span+ class="material-symbols-outlined self-update-tag-search-btn"+ :class="{ 'spinning': $store.selfUpdateStore.tagsLoading }"+ @click="if (!$store.selfUpdateStore.isBusy) $store.selfUpdateStore.searchTags()"+ title="Search tags from selected branch"+ x-text="$store.selfUpdateStore.tagsLoading ? 'progress_activity' : 'search'"+ ></span>+ <div+ class="self-update-tag-results"+ x-show="$store.selfUpdateStore.tagDropdownOpen"+ x-transition.opacity+ >+ <template x-if="$store.selfUpdateStore.tagsLoading">+ <div class="self-update-tag-item disabled">Loading tags...</div>+ </template>+ <template x-if="!$store.selfUpdateStore.tagsLoading && $store.selfUpdateStore.tagSuggestions.length === 0">+ <div class="self-update-tag-item disabled">No matching tags found</div></template>- </datalist>+ <template x-for="tag in $store.selfUpdateStore.tagSuggestions" :key="tag">+ <div+ class="self-update-tag-item"+ @click="$store.selfUpdateStore.selectTag(tag)"+ x-text="tag"+ ></div>+ </template>+ </div></div></div>@@ -172,7 +201,7 @@<div class="field-label"><div class="field-title">Backup filename</div><div class="field-description">- The manager normalizes this into a safe <code>.zip</code> filename.+ The manager normalizes this into a safe <code>.zip</code> filename. Leave it as-is for the default <code>usr-timestamp.zip</code> format.</div></div><div class="field-control">@@ -220,8 +249,12 @@<div class="self-update-loading" x-show="$store.selfUpdateStore.loading">Loading update status...</div>- <div class="self-update-loading" x-show="$store.selfUpdateStore.restarting">- Restarting Agent Zero and waiting for the health check...+ <div class="self-update-progress-state" x-show="$store.selfUpdateStore.restarting">+ <div class="self-update-progress-spinner"></div>+ <div>+ <div class="self-update-progress-title" x-text="$store.selfUpdateStore.restartStatusText || 'Update in progress'"></div>+ <div class="self-update-progress-copy" x-text="$store.selfUpdateStore.restartDetailText || 'Waiting for Agent Zero to restart and become healthy again.'"></div>+ </div></div><div class="modal-footer" data-modal-footer>@@ -258,6 +291,51 @@gap: 1rem;}+ .self-update-tag-search {+ position: relative;+ }++ .self-update-tag-search-btn {+ position: absolute;+ right: 0.5rem;+ top: 0.55rem;+ cursor: pointer;+ color: var(--color-text-secondary, #777);+ display: inline-flex;+ align-items: center;+ justify-content: center;+ }++ .self-update-tag-results {+ position: absolute;+ inset: calc(100% + 0.35rem) 0 auto 0;+ max-height: 14rem;+ overflow-y: auto;+ z-index: 20;+ border: 1px solid var(--color-border, #ddd);+ border-radius: 0.75rem;+ background: var(--color-surface, #fff);+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);+ }++ .self-update-tag-item {+ padding: 0.65rem 0.85rem;+ cursor: pointer;+ }++ .self-update-tag-item:hover {+ background: var(--color-panel-bg, rgba(0, 0, 0, 0.04));+ }++ .self-update-tag-item.disabled {+ cursor: default;+ color: var(--color-text-secondary, #777);+ }++ .self-update-tag-item.disabled:hover {+ background: transparent;+ }+.self-update-copy {color: var(--color-text-secondary);line-height: 1.5;@@ -267,6 +345,57 @@margin: 0 0 0.75rem;}+ .self-update-howto {+ border: 1px solid var(--color-border, #ddd);+ border-radius: 0.9rem;+ background: var(--color-surface, #fff);+ padding: 0.9rem 1rem;+ }++ .self-update-howto summary {+ cursor: pointer;+ font-weight: 700;+ list-style: none;+ }++ .self-update-howto summary::-webkit-details-marker {+ display: none;+ }++ .self-update-howto[open] summary {+ margin-bottom: 0.75rem;+ }++ .self-update-progress-state {+ display: flex;+ align-items: center;+ gap: 0.9rem;+ padding: 1rem 1.1rem;+ border-radius: 0.9rem;+ background: rgba(37, 99, 235, 0.08);+ color: var(--color-text, #111827);+ }++ .self-update-progress-spinner {+ width: 1.5rem;+ height: 1.5rem;+ flex: 0 0 auto;+ border-radius: 999px;+ border: 3px solid rgba(37, 99, 235, 0.18);+ border-top-color: var(--color-primary, #2563eb);+ animation: spin 1s linear infinite;+ }++ .self-update-progress-title {+ font-weight: 700;+ margin-bottom: 0.25rem;+ }++ .self-update-progress-copy {+ color: var(--color-text-secondary, #475569);+ line-height: 1.45;+ }+.self-update-summary-grid {display: grid;gap: 0.75rem;diff --git a/webui/components/settings/external/self-update-store.js b/webui/components/settings/external/self-update-store.jsindex 01c60fcd1..726a66a3e 100644--- a/webui/components/settings/external/self-update-store.js+++ b/webui/components/settings/external/self-update-store.js@@ -4,13 +4,22 @@ import { store as notificationStore } from "/components/notifications/notificaticonst HEALTH_POLL_INTERVAL_MS = 2000;const HEALTH_WAIT_BUFFER_MS = 30000;+const TAG_SEARCH_DEBOUNCE_MS = 250;+const SELF_UPDATE_RETURN_URL_KEY = "a0:self-update:return-url";+const SELF_UPDATE_OVERLAY_ID = "self-update-progress-overlay";const model = {loading: false,saving: false,restarting: false,+ tagsLoading: false,error: "",+ tagsError: "",info: null,+ tagSuggestions: [],+ tagDropdownOpen: false,+ restartStatusText: "",+ restartDetailText: "",form: {branch: "main",tag: "",@@ -20,6 +29,8 @@ const model = {backup_conflict_policy: "rename",},_reconnectTimer: null,+ _tagSearchTimer: null,+ _tagRequestId: 0,get isBusy() {return this.loading || this.saving || this.restarting;@@ -33,8 +44,8 @@ const model = {return this.info?.current?.short_tag || "unknown";},- get availableTags() {- return Array.isArray(this.info?.available_tags) ? this.info.available_tags : [];+ get currentBranch() {+ return this.info?.current?.branch || "";},async init() {@@ -43,10 +54,17 @@ const model = {cleanup() {this.clearReconnectTimer();+ this.clearTagSearchTimer();this.error = "";+ this.tagsError = "";this.loading = false;this.saving = false;this.restarting = false;+ this.tagsLoading = false;+ this.tagDropdownOpen = false;+ this.restartStatusText = "";+ this.restartDetailText = "";+ this.removeProgressOverlay();},clearReconnectTimer() {@@ -56,6 +74,13 @@ const model = {}},+ clearTagSearchTimer() {+ if (this._tagSearchTimer) {+ clearTimeout(this._tagSearchTimer);+ this._tagSearchTimer = null;+ }+ },+formatTimestamp(value) {if (!value) return "";try {@@ -69,6 +94,123 @@ const model = {return `${branch || "main"} / ${tag || "None"}`;},+ getSavedReturnUrl() {+ try {+ return sessionStorage.getItem(SELF_UPDATE_RETURN_URL_KEY) || "";+ } catch {+ return "";+ }+ },++ saveReturnUrl(url = "") {+ try {+ if (url) {+ sessionStorage.setItem(SELF_UPDATE_RETURN_URL_KEY, url);+ } else {+ sessionStorage.removeItem(SELF_UPDATE_RETURN_URL_KEY);+ }+ } catch {+ // ignore storage errors+ }+ },++ getProgressOverlay() {+ return document.getElementById(SELF_UPDATE_OVERLAY_ID);+ },++ ensureProgressOverlay() {+ let overlay = this.getProgressOverlay();+ if (!overlay) {+ overlay = document.createElement("div");+ overlay.id = SELF_UPDATE_OVERLAY_ID;+ overlay.innerHTML = `+ <div class="self-update-progress-card">+ <div class="self-update-progress-spinner"></div>+ <div class="self-update-progress-title"></div>+ <div class="self-update-progress-detail"></div>+ </div>+ `;+ Object.assign(overlay.style, {+ position: "fixed",+ inset: "0",+ zIndex: "10000",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ padding: "1.5rem",+ background: "rgba(15, 23, 42, 0.42)",+ backdropFilter: "blur(6px)",+ });+ document.body.appendChild(overlay);++ const style = document.createElement("style");+ style.id = `${SELF_UPDATE_OVERLAY_ID}-styles`;+ style.textContent = `+ #${SELF_UPDATE_OVERLAY_ID} .self-update-progress-card {+ width: min(28rem, calc(100vw - 2rem));+ border-radius: 1rem;+ background: var(--color-surface, #ffffff);+ color: var(--color-text, #111827);+ box-shadow: 0 24px 64px rgba(15, 23, 42, 0.22);+ padding: 1.5rem;+ text-align: center;+ }+ #${SELF_UPDATE_OVERLAY_ID} .self-update-progress-spinner {+ width: 2.5rem;+ height: 2.5rem;+ margin: 0 auto 1rem;+ border-radius: 999px;+ border: 3px solid rgba(15, 23, 42, 0.12);+ border-top-color: var(--color-primary, #2563eb);+ animation: self-update-spin 1s linear infinite;+ }+ #${SELF_UPDATE_OVERLAY_ID} .self-update-progress-title {+ font-size: 1.05rem;+ font-weight: 700;+ margin-bottom: 0.5rem;+ }+ #${SELF_UPDATE_OVERLAY_ID} .self-update-progress-detail {+ color: var(--color-text-secondary, #475569);+ line-height: 1.5;+ }+ @keyframes self-update-spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `;+ document.head.appendChild(style);+ }+ this.updateProgressOverlay();+ },++ updateProgressOverlay() {+ const overlay = this.getProgressOverlay();+ if (!overlay) return;+ const title = overlay.querySelector(".self-update-progress-title");+ const detail = overlay.querySelector(".self-update-progress-detail");+ if (title) {+ title.textContent = this.restartStatusText || "Applying self-update";+ }+ if (detail) {+ detail.textContent =+ this.restartDetailText ||+ "Agent Zero is restarting, applying the requested release, and will reload this page when the health check responds again.";+ }+ },++ removeProgressOverlay() {+ this.getProgressOverlay()?.remove();+ document.getElementById(`${SELF_UPDATE_OVERLAY_ID}-styles`)?.remove();+ },++ setRestartState(statusText, detailText = "") {+ this.restartStatusText = statusText;+ this.restartDetailText = detailText;+ if (this.restarting) {+ this.ensureProgressOverlay();+ }+ },+async refresh() {this.loading = true;this.error = "";@@ -79,6 +221,7 @@ const model = {}this.info = response;this.applyFormState(response.pending || response.defaults || {});+ await this.searchTags({ openResults: false });} catch (error) {console.error("Failed to load self-update info:", error);this.error = error.message || "Failed to load self-update info.";@@ -98,6 +241,71 @@ const model = {source?.backup_conflict_policy || "rename";},+ closeTagDropdown() {+ this.tagDropdownOpen = false;+ },++ openTagDropdown() {+ this.tagDropdownOpen = true;+ },++ async onBranchChanged() {+ this.openTagDropdown();+ await this.searchTags();+ },++ onTagInput() {+ this.openTagDropdown();+ this.scheduleTagSearch();+ },++ scheduleTagSearch() {+ this.clearTagSearchTimer();+ this._tagSearchTimer = setTimeout(() => {+ this._tagSearchTimer = null;+ void this.searchTags();+ }, TAG_SEARCH_DEBOUNCE_MS);+ },++ async searchTags({ openResults = true } = {}) {+ const requestId = ++this._tagRequestId;+ this.tagsLoading = true;+ this.tagsError = "";++ try {+ const response = await API.callJsonApi("self_update_tags", {+ branch: this.form.branch,+ query: this.form.tag,+ });+ if (!response?.success) {+ throw new Error(response?.error || "Failed to fetch release tags.");+ }+ if (requestId !== this._tagRequestId) {+ return;+ }+ this.tagSuggestions = Array.isArray(response?.tags) ? response.tags : [];+ this.tagsError = response?.error || "";+ this.tagDropdownOpen = openResults;+ } catch (error) {+ console.error("Failed to fetch self-update tags:", error);+ if (requestId !== this._tagRequestId) {+ return;+ }+ this.tagSuggestions = [];+ this.tagsError = error.message || "Failed to fetch release tags.";+ this.tagDropdownOpen = openResults;+ } finally {+ if (requestId === this._tagRequestId) {+ this.tagsLoading = false;+ }+ }+ },++ selectTag(tag) {+ this.form.tag = tag;+ this.tagDropdownOpen = false;+ },+async scheduleUpdate() {if (!this.form.branch?.trim()) {this.error = "Choose a branch.";@@ -135,6 +343,7 @@ const model = {undefined,true,);+ this.saveReturnUrl(window.location.href);await this.restartAndReload();} catch (error) {console.error("Failed to schedule self-update:", error);@@ -147,14 +356,25 @@ const model = {async restartAndReload() {this.restarting = true;this.clearReconnectTimer();+ this.setRestartState(+ "Starting self-update",+ "The request was saved. Agent Zero is about to restart and apply the requested branch and tag."+ );+ this.ensureProgressOverlay();try {- await API.fetchApi("/restart", {+ const token = await API.getCsrfToken();+ void fetch("/api/restart", {method: "POST",+ credentials: "same-origin",+ keepalive: true,headers: {"Content-Type": "application/json",+ "X-CSRF-Token": token,},body: JSON.stringify({}),+ }).catch(() => {+ // The restart request usually terminates the backend mid-flight.});} catch (_error) {// The restart request often terminates the backend mid-flight.@@ -168,6 +388,10 @@ const model = {HEALTH_WAIT_BUFFER_MS;const deadline = Date.now() + maxWaitMs;let lastError = "";+ this.setRestartState(+ "Update in progress",+ "Agent Zero is restarting and the updater is running. This page will reload automatically when /api/health starts responding again."+ );while (Date.now() < deadline) {try {@@ -177,7 +401,9 @@ const model = {cache: "no-store",});if (response.ok) {- window.location.reload();+ const returnUrl = this.getSavedReturnUrl() || window.location.href;+ this.saveReturnUrl("");+ window.location.replace(returnUrl);return;}lastError = `Health check returned HTTP ${response.status}.`;@@ -194,6 +420,8 @@ const model = {}this.restarting = false;+ this.removeProgressOverlay();+ this.saveReturnUrl("");this.error ="Agent Zero did not come back within the expected window. It may still be rolling back. " +(lastError ? `Last health check error: ${lastError}` : "");diff --git a/webui/components/settings/external/update_checker.html b/webui/components/settings/external/update_checker.htmlindex aa886ec99..c9cec85fb 100644--- a/webui/components/settings/external/update_checker.html+++ b/webui/components/settings/external/update_checker.html@@ -24,32 +24,6 @@</label></div></div>-- <div class="field">- <div class="field-label">- <div class="field-title">Manual Self Update</div>- <div class="field-description">- Schedule a branch plus release tag, optionally zip <code>/a0/usr</code>,- restart Agent Zero, and let the durable bootstrap manager in- <code>/exe</code> either finish the update or automatically roll back if- the UI never becomes healthy.- </div>- <template x-if="!$store.settings.additional?.is_dockerized">- <div class="field-description">- This action is currently available only in dockerized installs.- </div>- </template>- </div>- <div class="field-control">- <button- class="btn btn-field"- @click="openModal('settings/external/self-update-modal.html')"- :disabled="!$store.settings.additional?.is_dockerized"- >- Open Self Update- </button>- </div>- </div></div></template></div>diff --git a/webui/components/settings/settings.html b/webui/components/settings/settings.htmlindex 9f8f39ed3..fa3b8652b 100644--- a/webui/components/settings/settings.html+++ b/webui/components/settings/settings.html@@ -53,7 +53,7 @@<div class="settings-tab":class="{'active': $store.settings.activeTab === 'backup'}"@click="$store.settings.switchTab('backup')"- title="Backup & Restore">Backup & Restore</div>+ title="Update">Update</div></div></div>@@ -139,4 +139,3 @@to { transform: rotate(360deg); }}</style>-