Agent Zero AI framework
refactor: comprehensive UI server restructuring and self-update enhancements
frdelb94d4b79ae01
diff --git a/helpers/migration.py b/helpers/migration.pyindex caa09892a..4aa609aaa 100644--- a/helpers/migration.py+++ b/helpers/migration.py@@ -18,9 +18,7 @@ def migrate_user_data() -> None:"""Migrate user data from /tmp and other locations to /usr."""-- PrintStyle().print("Checking for data migration...")-+# --- Migrate Directories -------------------------------------------------------# Move directories from tmp/ or other source locations to usr/@@ -54,8 +52,6 @@ def migrate_user_data() -> None:# Remove obsolete directories after migration_cleanup_obsolete()- PrintStyle().print("Migration check complete.")-def convert_agents_json_yaml() -> None:for root in subagents.get_agents_roots():diff --git a/helpers/self_update.py b/helpers/self_update.pyindex bfcf25a20..37f589464 100644--- a/helpers/self_update.py+++ b/helpers/self_update.py@@ -186,10 +186,27 @@ def _is_latest_selector_tag(tag: str) -> bool:return tag.strip().lower() == "latest"+def _get_tag_release_time_in_repo(+ repo_dir: str | Path,+ tag: str,+) -> str:+ normalized_tag = tag.strip()+ if not normalized_tag:+ return ""+ try:+ timestamp = _run_git(repo_dir, "log", "-1", "--format=%ct", normalized_tag)+ if not timestamp:+ return ""+ return datetime.fromtimestamp(int(timestamp)).strftime("%Y-%m-%d %H:%M:%S")+ except Exception:+ return ""++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")+ short_tag = _normalize_describe_to_version(describe)try:branch = _run_git(repository, "branch", "--show-current")except Exception:@@ -197,10 +214,11 @@ def get_repo_version_info(repo_dir: str | Path | None = None) -> dict[str, str]:return {"branch": branch,"describe": describe,- "short_tag": _normalize_describe_to_version(describe),+ "short_tag": short_tag,"display_version": _format_branch_head_version(branch, describe),"commit": commit,"short_commit": commit[:7],+ "released_at": _get_tag_release_time_in_repo(repository, short_tag),}@@ -402,7 +420,7 @@ def _get_remote_branch_merged_tags(branch: str) -> set[str]:def _get_remote_branch_head_info(branch: str) -> dict[str, str]:normalized_branch = branch.strip().lower()if _is_excluded_self_update_branch(normalized_branch):- return {"describe": "", "short_tag": "", "commit": ""}+ return {"describe": "", "short_tag": "", "commit": "", "released_at": ""}cached = _remote_branch_head_cache.get(normalized_branch)now = time.monotonic()@@ -425,11 +443,14 @@ def _get_remote_branch_head_info(branch: str) -> dict[str, str]:remote_ref = f"refs/remotes/origin/{normalized_branch}"describe = _run_git(repository, "describe", "--tags", "--always", remote_ref)commit = _run_git(repository, "rev-parse", remote_ref)+ short_tag = _normalize_describe_to_version(describe)+ released_at = _get_tag_release_time_in_repo(repository, short_tag)payload = {"describe": describe,- "short_tag": _normalize_describe_to_version(describe),+ "short_tag": short_tag,"commit": commit,+ "released_at": released_at,}_remote_branch_head_cache[normalized_branch] = (now, payload)return dict(payload)@@ -464,10 +485,14 @@ def _get_local_branch_head_info("describe": describe,"short_tag": _normalize_describe_to_version(describe),"commit": commit,+ "released_at": _get_tag_release_time_in_repo(+ repository,+ _normalize_describe_to_version(describe),+ ),}except Exception:continue- return {"describe": "", "short_tag": "", "commit": ""}+ return {"describe": "", "short_tag": "", "commit": "", "released_at": ""}def _get_branch_merged_tags(@@ -555,6 +580,93 @@ def _format_branch_head_version(branch: str, describe: str) -> str:return f"{short_tag}+{commits_since_tag}"+def _get_release_tag_info(+ branch: str,+ tag: str,+ *,+ repo_dir: str | Path | None = None,+) -> dict[str, Any]:+ repository = get_repo_dir(repo_dir)+ commit = ""+ try:+ commit = _run_git(repository, "rev-parse", f"refs/tags/{tag}^{{commit}}")+ except Exception:+ commit = ""+ return {+ "branch": branch.strip().lower(),+ "supported": True,+ "describe": tag,+ "short_tag": tag,+ "display_version": tag,+ "commit": commit,+ "short_commit": commit[:7] if commit else "",+ "released_at": _get_tag_release_time_in_repo(repository, tag),+ }+++def get_current_major_main_latest_info(+ current_version: str,+ *,+ repo_dir: str | Path | None = None,+) -> dict[str, Any]:+ repository = get_repo_dir(repo_dir)+ available_branches = set(get_available_branch_values(repo_dir=repository))+ if "main" not in available_branches:+ return {+ "branch": "main",+ "supported": False,+ "describe": "",+ "short_tag": "",+ "display_version": "",+ "commit": "",+ "short_commit": "",+ "released_at": "",+ }++ current_major = _parse_major_version(current_version)+ if current_major is None:+ return get_current_branch_latest_info("main", repo_dir=repository)++ tags, error = get_available_tags("main", repo_dir=repository)+ if error:+ return get_current_branch_latest_info("main", repo_dir=repository)++ latest_same_major_tag = next(+ (tag for tag in tags if _parse_major_version(tag) == current_major),+ "",+ )+ if not latest_same_major_tag:+ return {+ "branch": "main",+ "supported": True,+ "describe": "",+ "short_tag": "",+ "display_version": "",+ "commit": "",+ "short_commit": "",+ "released_at": "",+ }++ branch_head_info = _get_branch_head_info("main", repo_dir=repository)+ head_describe = branch_head_info.get("describe", "")+ head_short_tag = branch_head_info.get("short_tag", "")+ _, commits_since_tag = _split_describe_version(head_describe)+ if head_short_tag == latest_same_major_tag and commits_since_tag <= 0:+ commit = branch_head_info.get("commit", "")+ return {+ "branch": "main",+ "supported": True,+ "describe": head_describe,+ "short_tag": head_short_tag,+ "display_version": _format_branch_head_version("main", head_describe),+ "commit": commit,+ "short_commit": commit[:7] if commit else "",+ "released_at": branch_head_info.get("released_at", ""),+ }++ return _get_release_tag_info("main", latest_same_major_tag, repo_dir=repository)++def get_current_branch_latest_info(current_branch: str,*,@@ -572,6 +684,7 @@ def get_current_branch_latest_info("display_version": "","commit": "","short_commit": "",+ "released_at": "",}branch_head_info = _get_branch_head_info(normalized_branch, repo_dir=repository)@@ -587,6 +700,7 @@ def get_current_branch_latest_info(),"commit": commit,"short_commit": commit[:7] if commit else "",+ "released_at": branch_head_info.get("released_at", ""),}@@ -700,9 +814,21 @@ def get_update_info(repo_dir: str | Path | None = None) -> dict[str, Any]:repo_dir=repository,current_version=current_version,)+ if "main" in available_branch_values:+ _, major_upgrade_versions, _ = get_selector_tag_options(+ "main",+ repo_dir=repository,+ current_version=current_version,+ )+ else:+ major_upgrade_versions = []return {"repo_dir": str(repository),"current": version_info,+ "main_branch_latest": get_current_major_main_latest_info(+ current_version,+ repo_dir=repository,+ ),"current_branch_latest": get_current_branch_latest_info(current_branch,repo_dir=repository,@@ -714,6 +840,7 @@ def get_update_info(repo_dir: str | Path | None = None) -> dict[str, Any]:"available_tag_options": tag_options,"available_tags_error": tags_error,"available_higher_major_versions": higher_major_versions,+ "major_upgrade_versions": major_upgrade_versions,"paths": {"update_file": str(get_update_file_path()),"status_file": str(get_status_file_path()),diff --git a/helpers/server_startup.py b/helpers/server_startup.pynew file mode 100644index 000000000..8e3a59393--- /dev/null+++ b/helpers/server_startup.py@@ -0,0 +1,401 @@+from collections import deque+import asyncio+from contextlib import asynccontextmanager, contextmanager+from dataclasses import dataclass+import faulthandler+import os+import sys+import threading+import time+from typing import Callable, Iterator+import urllib.request++import uvicorn++from helpers import process+from helpers.print_style import PrintStyle+++def _env_int(name: str, default: int, minimum: int = 0) -> int:+ try:+ return max(minimum, int(os.getenv(name, str(default))))+ except (TypeError, ValueError):+ return default+++def _env_float(name: str, default: float, minimum: float = 0.0) -> float:+ try:+ return max(minimum, float(os.getenv(name, str(default))))+ except (TypeError, ValueError):+ return default+++@dataclass(frozen=True)+class StartupConfig:+ timeout_seconds: int+ max_attempts: int+ retry_delay_seconds: float++ @classmethod+ def from_env(cls) -> "StartupConfig":+ return cls(+ timeout_seconds=_env_int("A0_STARTUP_TIMEOUT_SECONDS", 90, minimum=15),+ max_attempts=_env_int("A0_STARTUP_MAX_ATTEMPTS", 2, minimum=1),+ retry_delay_seconds=_env_float(+ "A0_STARTUP_RETRY_DELAY_SECONDS", 2.0, minimum=0.0+ ),+ )+++@dataclass+class StartupStageRecord:+ name: str+ timestamp: float+ detail: str | None = None+++class StartupMonitor:+ def __init__(+ self,+ bind_host: str,+ probe_host: str,+ port: int,+ attempt: int,+ max_attempts: int,+ timeout_seconds: int,+ ) -> None:+ self.bind_host = bind_host+ self.probe_host = probe_host+ self.port = port+ self.attempt = attempt+ self.max_attempts = max_attempts+ self.timeout_seconds = timeout_seconds+ self.start_time = time.monotonic()+ self._stage = "created"+ self._stage_detail: str | None = None+ self._stage_started_at = self.start_time+ self._history: deque[StartupStageRecord] = deque(maxlen=30)+ self._history.append(StartupStageRecord(self._stage, self.start_time))+ self._ready = threading.Event()+ self._stop = threading.Event()+ self._lock = threading.RLock()+ self._server: uvicorn.Server | None = None+ self._watchdog_thread: threading.Thread | None = None++ def _prefix(self) -> str:+ return f"[startup attempt {self.attempt}/{self.max_attempts}]"++ def mark(self, stage: str, detail: str | None = None) -> None:+ now = time.monotonic()+ with self._lock:+ self._stage = stage+ self._stage_detail = detail+ self._stage_started_at = now+ self._history.append(StartupStageRecord(stage, now, detail))+ elapsed = now - self.start_time++ suffix = f" ({detail})" if detail else ""+ PrintStyle.debug(f"{self._prefix()} {stage}{suffix} at +{elapsed:.1f}s")++ @contextmanager+ def stage(self, stage: str, detail: str | None = None) -> Iterator[None]:+ self.mark(f"{stage}.start", detail)+ try:+ yield+ except BaseException as e:+ message = f"{type(e).__name__}: {e}"+ self.mark(f"{stage}.error", message[:200])+ raise+ else:+ self.mark(f"{stage}.done", detail)++ def lifespan(self):+ @asynccontextmanager+ async def _lifespan(_app):+ self.mark("starlette.lifespan.startup")+ try:+ yield+ finally:+ self.mark("starlette.lifespan.shutdown")++ return _lifespan++ def attach_server(self, server: uvicorn.Server) -> None:+ with self._lock:+ self._server = server++ def start_watchdog(self) -> None:+ if self._watchdog_thread and self._watchdog_thread.is_alive():+ return+ self._watchdog_thread = threading.Thread(+ target=self._watchdog_loop,+ daemon=True,+ name=f"StartupWatchdog-{self.attempt}",+ )+ self._watchdog_thread.start()++ def mark_ready(self, source: str = "health_check") -> None:+ if self._ready.is_set():+ return+ self.mark("ready", source)+ self._ready.set()+ self._stop.set()++ def is_ready(self) -> bool:+ return self._ready.is_set()++ def close(self) -> None:+ self._stop.set()++ def stop_event(self) -> threading.Event:+ return self._stop++ def _watchdog_loop(self) -> None:+ next_progress_log = self.start_time + 10+ while not self._stop.wait(timeout=1):+ if self._ready.is_set():+ return++ now = time.monotonic()+ if now >= next_progress_log:+ stage, detail, stage_elapsed, total_elapsed, _history = self.snapshot()+ detail_text = f" ({detail})" if detail else ""+ PrintStyle.warning(+ f"{self._prefix()} still waiting for readiness after "+ f"{total_elapsed:.1f}s; current stage '{stage}' has been active "+ f"for {stage_elapsed:.1f}s{detail_text}"+ )+ next_progress_log = now + 10++ if now - self.start_time >= self.timeout_seconds:+ self._handle_timeout()+ return++ def snapshot(+ self,+ ) -> tuple[str, str | None, float, float, list[StartupStageRecord]]:+ now = time.monotonic()+ with self._lock:+ return (+ self._stage,+ self._stage_detail,+ now - self._stage_started_at,+ now - self.start_time,+ list(self._history),+ )++ def _handle_timeout(self) -> None:+ stage, detail, stage_elapsed, total_elapsed, history = self.snapshot()+ detail_text = f" ({detail})" if detail else ""+ PrintStyle.error(+ f"{self._prefix()} startup timed out after {total_elapsed:.1f}s while "+ f"waiting for bind={self.bind_host}:{self.port} "+ f"probe=http://{self.probe_host}:{self.port}/api/health; current stage "+ f"'{stage}' has been active for {stage_elapsed:.1f}s{detail_text}"+ )++ PrintStyle.error(f"{self._prefix()} recent stage history follows:")+ for record in history:+ relative = record.timestamp - self.start_time+ suffix = f" ({record.detail})" if record.detail else ""+ PrintStyle.standard(f" +{relative:5.1f}s {record.name}{suffix}")++ active_threads = ", ".join(+ f"{thread.name}(alive={thread.is_alive()}, daemon={thread.daemon})"+ for thread in threading.enumerate()+ )+ PrintStyle.error(f"{self._prefix()} active threads: {active_threads}")+ PrintStyle.error(+ f"{self._prefix()} dumping all thread stack traces for startup diagnosis"+ )+ try:+ faulthandler.dump_traceback(file=sys.stderr, all_threads=True)+ except Exception as e:+ PrintStyle.error(f"{self._prefix()} failed to dump thread traces: {e}")++ with self._lock:+ server = self._server++ if server is not None:+ PrintStyle.warning(+ f"{self._prefix()} requesting uvicorn shutdown after startup timeout"+ )+ server.should_exit = True++ if not self._stop.wait(timeout=3):+ PrintStyle.error(+ f"{self._prefix()} forcing process exit so the supervisor can restart it"+ )+ os._exit(1)+++def get_health_probe_host(bind_host: str) -> str:+ if bind_host in {"0.0.0.0", "::", "[::]", ""}:+ return "127.0.0.1"+ return bind_host+++def run_uvicorn_with_retries(+ *,+ host: str,+ port: int,+ build_asgi_app: Callable[[StartupMonitor], object],+ flush_callback: Callable[[str], None],+ access_log: bool = False,+ log_level: str = "info",+ ws: str = "wsproto",+ startup_config: StartupConfig | None = None,+) -> None:+ startup_config = startup_config or StartupConfig.from_env()+ health_host = get_health_probe_host(host)+ PrintStyle.debug(+ f"[startup] bind={host}:{port} probe=http://{health_host}:{port}/api/health "+ f"timeout={startup_config.timeout_seconds}s attempts={startup_config.max_attempts}"+ )++ for attempt in range(1, startup_config.max_attempts + 1):+ startup_monitor = StartupMonitor(+ bind_host=host,+ probe_host=health_host,+ port=port,+ attempt=attempt,+ max_attempts=startup_config.max_attempts,+ timeout_seconds=startup_config.timeout_seconds,+ )+ try:+ if _run_server_attempt(+ host=host,+ health_host=health_host,+ port=port,+ startup_monitor=startup_monitor,+ build_asgi_app=build_asgi_app,+ flush_callback=flush_callback,+ access_log=access_log,+ log_level=log_level,+ ws=ws,+ ):+ return+ except BaseException as e:+ if isinstance(e, SystemExit) and startup_monitor.is_ready():+ raise++ PrintStyle.error(+ f"[startup attempt {attempt}/{startup_config.max_attempts}] "+ f"server startup failed before readiness with "+ f"{type(e).__name__}: {e}"+ )+ if attempt >= startup_config.max_attempts:+ raise+ else:+ if attempt >= startup_config.max_attempts:+ raise RuntimeError(+ "Uvicorn exited before readiness on the final startup attempt."+ )++ PrintStyle.warning(+ f"[startup attempt {attempt}/{startup_config.max_attempts}] "+ "server exited before readiness; retrying"+ )++ if startup_config.retry_delay_seconds > 0:+ PrintStyle.warning(+ f"[startup attempt {attempt}/{startup_config.max_attempts}] "+ f"sleeping {startup_config.retry_delay_seconds:.1f}s before retry"+ )+ time.sleep(startup_config.retry_delay_seconds)++ raise RuntimeError("Server failed to reach readiness after all startup attempts.")+++def _run_server_attempt(+ *,+ host: str,+ health_host: str,+ port: int,+ startup_monitor: StartupMonitor,+ build_asgi_app: Callable[[StartupMonitor], object],+ flush_callback: Callable[[str], None],+ access_log: bool,+ log_level: str,+ ws: str,+) -> bool:+ startup_monitor.start_watchdog()+ try:+ asgi_app = build_asgi_app(startup_monitor)++ with startup_monitor.stage("uvicorn.config.create"):+ config = uvicorn.Config(+ asgi_app,+ host=host,+ port=port,+ log_level=log_level,+ access_log=access_log,+ ws=ws,+ )++ with startup_monitor.stage("uvicorn.server.create"):+ server = uvicorn.Server(config)++ startup_monitor.attach_server(server)+ process.set_server(_UvicornServerWrapper(server, flush_callback))++ startup_monitor.mark("health.thread.start")+ threading.Thread(+ target=wait_for_health,+ args=(health_host, port, startup_monitor),+ daemon=True,+ name=f"StartupHealth-{startup_monitor.attempt}",+ ).start()++ PrintStyle().debug(f"Starting server at http://{host}:{port} ...")+ startup_monitor.mark("uvicorn.run.enter")+ _serve_uvicorn(server)++ if startup_monitor.is_ready():+ return True++ PrintStyle.warning(+ f"[startup attempt {startup_monitor.attempt}/{startup_monitor.max_attempts}] "+ "uvicorn exited before the health probe observed readiness"+ )+ return False+ finally:+ startup_monitor.close()+ process.set_server(None)+ flush_callback("server_exit")+++def wait_for_health(host: str, port: int, startup_monitor: StartupMonitor) -> None:+ url = f"http://{host}:{port}/api/health"+ while not startup_monitor.stop_event().is_set():+ try:+ with urllib.request.urlopen(url, timeout=2) as resp:+ if resp.status == 200:+ startup_monitor.mark_ready("health_probe")+ PrintStyle().print("Agent Zero is running.")+ return+ except Exception:+ pass+ startup_monitor.stop_event().wait(1)+++class _UvicornServerWrapper:+ def __init__(+ self, server: uvicorn.Server, flush_callback: Callable[[str], None]+ ) -> None:+ self._server = server+ self._flush_callback = flush_callback++ def shutdown(self) -> None:+ self._flush_callback("shutdown")+ self._server.should_exit = True+++def _serve_uvicorn(server: uvicorn.Server) -> None:+ # Avoid uvicorn.Server.run(), which delegates to asyncio.run(...) and can+ # conflict with the global nest_asyncio patch used by the runtime.+ # The project requires uvicorn>=0.38.0, where loop setup is exposed via+ # Config.get_loop_factory().+ loop_factory = server.config.get_loop_factory()+ with asyncio.Runner(loop_factory=loop_factory) as runner:+ runner.run(server.serve())diff --git a/helpers/ui_server.py b/helpers/ui_server.pynew file mode 100644index 000000000..57519660d--- /dev/null+++ b/helpers/ui_server.py@@ -0,0 +1,283 @@+from dataclasses import dataclass, field+from datetime import timedelta+import asyncio+import logging+import os+import secrets+import threading+import time+from typing import Any++from flask import (+ Flask,+ Response,+ redirect,+ render_template_string,+ request,+ send_file,+ session,+ url_for,+)+from socketio import ASGIApp+from starlette.applications import Starlette+from starlette.routing import Mount+from uvicorn.middleware.wsgi import WSGIMiddleware+from werkzeug.wrappers.request import Request as WerkzeugRequest+import socketio # type: ignore[import-untyped]++from helpers import dotenv, fasta2a_server, files, git, login, mcp_server, runtime+from helpers.api import register_api_route, requires_auth+from helpers.extension import extensible+from helpers.files import get_abs_path+from helpers.print_style import PrintStyle+from helpers.server_startup import StartupMonitor+from helpers import settings as settings_helper+from helpers.ws import register_ws_namespace, validate_ws_origin+from helpers.ws_manager import WsManager, set_shared_ws_manager+++UPLOAD_LIMIT_BYTES = 5 * 1024 * 1024 * 1024+++def configure_process_environment() -> None:+ logging.getLogger().setLevel(logging.WARNING)+ os.environ["TZ"] = "UTC"+ os.environ["TOKENIZERS_PARALLELISM"] = "false"+ if hasattr(time, "tzset"):+ time.tzset()+++@dataclass+class UiServerRuntime:+ webapp: Flask+ socketio_server: socketio.AsyncServer+ ws_manager: WsManager+ lock: threading.RLock+ settings_snapshot: dict[str, Any]+ _routes_registered: bool = False+ _transport_registered: bool = False+ _route_handlers: "UiRouteHandlers | None" = field(default=None, init=False)++ @classmethod+ def create(cls) -> "UiServerRuntime":+ webapp = Flask("app", static_folder=get_abs_path("./webui"), static_url_path="/")+ webapp.secret_key = os.getenv("FLASK_SECRET_KEY") or secrets.token_hex(32)++ WerkzeugRequest.max_form_memory_size = UPLOAD_LIMIT_BYTES+ webapp.config.update(+ JSON_SORT_KEYS=False,+ SESSION_COOKIE_NAME="session_" + runtime.get_runtime_id(),+ SESSION_COOKIE_SAMESITE="Lax",+ SESSION_PERMANENT=True,+ PERMANENT_SESSION_LIFETIME=timedelta(days=1),+ MAX_CONTENT_LENGTH=int(+ os.getenv("FLASK_MAX_CONTENT_LENGTH", str(UPLOAD_LIMIT_BYTES))+ ),+ MAX_FORM_MEMORY_SIZE=int(+ os.getenv("FLASK_MAX_FORM_MEMORY_SIZE", str(UPLOAD_LIMIT_BYTES))+ ),+ )++ lock = threading.RLock()+ socketio_server = socketio.AsyncServer(+ async_mode="asgi",+ namespaces="*",+ cors_allowed_origins=lambda _origin, environ: validate_ws_origin(environ)[0],+ logger=False,+ engineio_logger=False,+ ping_interval=25,+ ping_timeout=20,+ max_http_buffer_size=50 * 1024 * 1024,+ )++ ws_manager = WsManager(socketio_server, lock)+ set_shared_ws_manager(ws_manager)++ server_runtime = cls(+ webapp=webapp,+ socketio_server=socketio_server,+ ws_manager=ws_manager,+ lock=lock,+ settings_snapshot={},+ )+ server_runtime.refresh_runtime_settings()+ return server_runtime++ def refresh_runtime_settings(self) -> None:+ self.settings_snapshot = settings_helper.get_settings()+ settings_helper.set_runtime_settings_snapshot(self.settings_snapshot)+ self.ws_manager.set_server_restart_broadcast(+ self.settings_snapshot.get("websocket_server_restart_enabled", True)+ )++ def register_http_routes(self) -> None:+ if self._routes_registered:+ return++ handlers = UiRouteHandlers(self)+ self._route_handlers = handlers+ self.webapp.add_url_rule(+ "/login",+ "login_handler",+ handlers.login_handler,+ methods=["GET", "POST"],+ )+ self.webapp.add_url_rule(+ "/logout",+ "logout_handler",+ handlers.logout_handler,+ methods=["GET"],+ )+ self.webapp.add_url_rule(+ "/",+ "serve_index",+ handlers.serve_index,+ methods=["GET"],+ )+ self.webapp.add_url_rule(+ "/plugins/<plugin_name>/<path:asset_path>",+ "serve_builtin_plugin_asset",+ handlers.serve_builtin_plugin_asset,+ methods=["GET"],+ )+ self.webapp.add_url_rule(+ "/usr/plugins/<plugin_name>/<path:asset_path>",+ "serve_plugin_asset",+ handlers.serve_plugin_asset,+ methods=["GET"],+ )+ self.webapp.add_url_rule(+ "/extensions/webui/<path:asset_path>",+ "serve_extension_asset",+ handlers.serve_extension_asset,+ methods=["GET"],+ )+ self._routes_registered = True++ def register_transport_handlers(self) -> None:+ if self._transport_registered:+ return+ register_api_route(self.webapp, self.lock)+ register_ws_namespace(+ self.socketio_server,+ self.webapp,+ self.lock,+ manager=self.ws_manager,+ )+ self._transport_registered = True++ def build_asgi_app(self, startup_monitor: StartupMonitor):+ with startup_monitor.stage("wsgi.middleware.create"):+ wsgi_app = WSGIMiddleware(self.webapp)++ with startup_monitor.stage("mcp.proxy.init"):+ mcp_app = mcp_server.DynamicMcpProxy.get_instance()++ with startup_monitor.stage("a2a.proxy.init"):+ a2a_app = fasta2a_server.DynamicA2AProxy.get_instance()++ with startup_monitor.stage("starlette.app.create"):+ starlette_app = Starlette(+ routes=[+ Mount("/mcp", app=mcp_app),+ Mount("/a2a", app=a2a_app),+ Mount("/", app=wsgi_app),+ ],+ lifespan=startup_monitor.lifespan(),+ )++ with startup_monitor.stage("socketio.asgi.create"):+ return ASGIApp(self.socketio_server, other_asgi_app=starlette_app)++ def access_log_enabled(self) -> bool:+ return self.settings_snapshot.get("uvicorn_access_logs_enabled", False)+++class UiRouteHandlers:+ def __init__(self, runtime_state: UiServerRuntime) -> None:+ self.runtime = runtime_state++ @extensible+ async def login_handler(self):+ error = None+ if request.method == "POST":+ user = dotenv.get_dotenv_value("AUTH_LOGIN")+ password = dotenv.get_dotenv_value("AUTH_PASSWORD")++ if request.form["username"] == user and request.form["password"] == password:+ session["authentication"] = login.get_credentials_hash()+ return redirect(url_for("serve_index"))+ else:+ await asyncio.sleep(1)+ error = "Invalid Credentials. Please try again."++ login_page_content = files.read_file("webui/login.html")+ return render_template_string(login_page_content, error=error)++ @extensible+ async def logout_handler(self):+ session.pop("authentication", None)+ return redirect(url_for("login_handler"))++ @requires_auth+ @extensible+ async def serve_index(self):+ try:+ gitinfo = git.get_git_info()+ except Exception:+ gitinfo = {+ "version": "unknown",+ "commit_time": "unknown",+ }++ index = files.read_file("webui/index.html")+ return files.replace_placeholders_text(+ _content=index,+ version_no=gitinfo["version"],+ version_time=gitinfo["commit_time"],+ runtime_id=runtime.get_runtime_id(),+ runtime_is_development=("true" if runtime.is_development() else "false"),+ logged_in=("true" if login.get_credentials_hash() else "false"),+ )++ @requires_auth+ async def serve_builtin_plugin_asset(self, plugin_name, asset_path):+ return await self._serve_plugin_asset(plugin_name, asset_path)++ @requires_auth+ async def serve_plugin_asset(self, plugin_name, asset_path):+ return await self._serve_plugin_asset(plugin_name, asset_path)++ @requires_auth+ async def serve_extension_asset(self, asset_path):+ exts = files.get_abs_path("extensions/webui")+ path = files.get_abs_path(exts, asset_path)+ if not files.is_in_dir(path, exts):+ return Response("Access denied", 403)+ return send_file(path)++ @extensible+ async def _serve_plugin_asset(self, plugin_name, asset_path):+ from helpers import plugins++ plugin_dir = plugins.find_plugin_dir(plugin_name)+ if not plugin_dir:+ return Response("Plugin not found", 404)++ try:+ asset_file = files.get_abs_path(plugin_dir, asset_path)+ webui_dir = files.get_abs_path(plugin_dir, "webui")+ webui_extensions_dir = files.get_abs_path(plugin_dir, "extensions/webui")++ if not files.is_in_dir(str(asset_file), str(webui_dir)) and not files.is_in_dir(+ str(asset_file), str(webui_extensions_dir)+ ):+ return Response("Access denied", 403)++ if not files.is_file(asset_file):+ return Response("Asset not found", 404)++ return send_file(str(asset_file))+ except Exception as e:+ PrintStyle.error(f"Error serving plugin asset: {e}")+ return Response("Error serving asset", 500)diff --git a/run_ui.py b/run_ui.pyindex fe1e2dbd5..a90e7a183 100644--- a/run_ui.py+++ b/run_ui.py@@ -1,242 +1,62 @@-from datetime import timedelta-import os-import secrets-import time-import threading-import asyncio--import urllib.request-import uvicorn-from flask import Flask, request, Response, session, redirect, url_for, render_template_string-from werkzeug.wrappers.request import Request as WerkzeugRequest-import initialize-from helpers import files, git, mcp_server, fasta2a_server, settings as settings_helper, extension-from helpers.files import get_abs_path-from helpers import runtime, dotenv, process-from helpers.api import register_api_route, requires_auth, csrf_protect-from helpers.ws import register_ws_namespace, validate_ws_origin+from helpers import dotenv, extension, runtimefrom helpers.print_style import PrintStyle-from helpers import login-import socketio # type: ignore[import-untyped]-from socketio import ASGIApp, packet-from starlette.applications import Starlette-from starlette.routing import Mount-from uvicorn.middleware.wsgi import WSGIMiddleware-from helpers.ws_manager import WsManager, set_shared_ws_manager-from flask import send_file--# disable logging-import logging-logging.getLogger().setLevel(logging.WARNING)---# Set the new timezone to 'UTC'-os.environ["TZ"] = "UTC"-os.environ["TOKENIZERS_PARALLELISM"] = "false"-# Apply the timezone change-if hasattr(time, 'tzset'):- time.tzset()--# initialize the internal Flask server-webapp = Flask("app", static_folder=get_abs_path("./webui"), static_url_path="/")-webapp.secret_key = os.getenv("FLASK_SECRET_KEY") or secrets.token_hex(32)--UPLOAD_LIMIT_BYTES = 5 * 1024 * 1024 * 1024--# Werkzeug's default max_form_memory_size is 500_000 bytes which can trigger 413 for multipart requests-# with larger non-file fields. Raise it to match our intended upload limit.-WerkzeugRequest.max_form_memory_size = UPLOAD_LIMIT_BYTES--webapp.config.update(- JSON_SORT_KEYS=False,- SESSION_COOKIE_NAME="session_" + runtime.get_runtime_id(), # bind the session cookie name to runtime id to prevent session collision on same host- SESSION_COOKIE_SAMESITE="Lax",- SESSION_PERMANENT=True,- PERMANENT_SESSION_LIFETIME=timedelta(days=1),- MAX_CONTENT_LENGTH=int(os.getenv("FLASK_MAX_CONTENT_LENGTH", str(UPLOAD_LIMIT_BYTES))),- MAX_FORM_MEMORY_SIZE=int(os.getenv("FLASK_MAX_FORM_MEMORY_SIZE", str(UPLOAD_LIMIT_BYTES))),-)--lock = threading.RLock()--socketio_server = socketio.AsyncServer(- async_mode="asgi",- namespaces="*",- cors_allowed_origins=lambda _origin, environ: validate_ws_origin(environ)[0],- logger=False,- engineio_logger=False,- ping_interval=25, # explicit default to avoid future lib changes- ping_timeout=20, # explicit default to avoid future lib changes- max_http_buffer_size=50 * 1024 * 1024,-)--ws_manager = WsManager(socketio_server, lock)-set_shared_ws_manager(ws_manager)-_settings = settings_helper.get_settings()-settings_helper.set_runtime_settings_snapshot(_settings)-ws_manager.set_server_restart_broadcast(- _settings.get("websocket_server_restart_enabled", True)-)--# Set up basic authentication for UI and API but not MCP-# basic_auth = BasicAuth(webapp)--[email protected]("/login", methods=["GET", "POST"])-async def login_handler():- error = None- if request.method == 'POST':- user = dotenv.get_dotenv_value("AUTH_LOGIN")- password = dotenv.get_dotenv_value("AUTH_PASSWORD")-- if request.form['username'] == user and request.form['password'] == password:- session['authentication'] = login.get_credentials_hash()- return redirect(url_for('serve_index'))- else:- await asyncio.sleep(1)- error = 'Invalid Credentials. Please try again.'-- login_page_content = files.read_file("webui/login.html")- return render_template_string(login_page_content, error=error)--[email protected]("/logout")-async def logout_handler():- session.pop('authentication', None)- return redirect(url_for('login_handler'))---# handle default address, load index[email protected]("/", methods=["GET"])-@requires_auth-async def serve_index():- gitinfo = None- try:- gitinfo = git.get_git_info()- except Exception:- gitinfo = {- "version": "unknown",- "commit_time": "unknown",- }- index = files.read_file("webui/index.html")- index = files.replace_placeholders_text(- _content=index,- version_no=gitinfo["version"],- version_time=gitinfo["commit_time"],- runtime_id=runtime.get_runtime_id(),- runtime_is_development=("true" if runtime.is_development() else "false"),- logged_in=("true" if login.get_credentials_hash() else "false"),- )- return index-+from helpers.server_startup import run_uvicorn_with_retries+from helpers.ui_server import UiServerRuntime, configure_process_environment-# Serve plugin assets[email protected]("/plugins/<plugin_name>/<path:asset_path>", methods=["GET"])-@requires_auth-async def serve_builtin_plugin_asset(plugin_name, asset_path):- return await _serve_plugin_asset(plugin_name, asset_path)[email protected]("/usr/plugins/<plugin_name>/<path:asset_path>", methods=["GET"])-@requires_auth-async def serve_plugin_asset(plugin_name, asset_path):- return await _serve_plugin_asset(plugin_name, asset_path)+configure_process_environment()[email protected]("/extensions/webui/<path:asset_path>", methods=["GET"])-@requires_auth-async def serve_extension_asset(asset_path):- exts = files.get_abs_path("extensions/webui")- path = files.get_abs_path(exts, asset_path)- if not files.is_in_dir(path, exts):- return Response(f"Access denied", 403)- return send_file(path)+def run():+ PrintStyle().print("Initializing Python framework...")+ PrintStyle().print("Checking for data migration...")+ run_migration_checks()-async def _serve_plugin_asset(plugin_name, asset_path):- """- Serve static assets from plugin directories.- Resolves using the plugin system (with overrides).- """- from helpers import plugins--- # Use the new find_plugin helper- plugin_dir = plugins.find_plugin_dir(plugin_name)- if not plugin_dir:- return Response("Plugin not found", 404)-- # Resolve the plugin asset path with security checks- try:- # Construct path using plugin root- asset_file = files.get_abs_path(plugin_dir, asset_path)- webui_dir = files.get_abs_path(plugin_dir, "webui")- webui_extensions_dir = files.get_abs_path(plugin_dir, "extensions/webui")-- # Security: ensure the resolved path is within the plugin webui directory- if not files.is_in_dir(str(asset_file), str(webui_dir)) and not files.is_in_dir(str(asset_file), str(webui_extensions_dir)):- return Response("Access denied", 403)-- if not files.is_file(asset_file):- return Response("Asset not found", 404)-- return send_file(str(asset_file))- except Exception as e:- PrintStyle.error(f"Error serving plugin asset: {e}")- return Response("Error serving asset", 500)+ PrintStyle().print("Preparing web server runtime...")+ server_runtime, host, port = prepare_web_runtime()+ PrintStyle().print("Initializing Agent Zero components...")+ init_a0()+ PrintStyle().print("Starting UI/API server...")+ start_web_server(server_runtime, host, port)-def run():- PrintStyle().print("Initializing framework...")-- # migrate data before anything else+def run_migration_checks() -> None:initialize.initialize_migration()- # # Suppress only request logs but keep the startup messages- # from werkzeug.serving import WSGIRequestHandler- # from werkzeug.serving import make_server- # from werkzeug.middleware.dispatcher import DispatcherMiddleware- # from a2wsgi import ASGIMiddleware-- PrintStyle().print("Starting server...")-- # class NoRequestLoggingWSGIRequestHandler(WSGIRequestHandler):- # def log_request(self, code="-", size="-"):- # pass # Override to suppress request logging- # Get configuration from environment- port = runtime.get_web_ui_port()+def prepare_web_runtime() -> tuple[UiServerRuntime, str, int]:host = (runtime.get_arg("host") or dotenv.get_dotenv_value("WEB_UI_HOST") or "localhost")+ port = runtime.get_web_ui_port()+ server_runtime = UiServerRuntime.create()+ server_runtime.register_http_routes()+ server_runtime.register_transport_handlers()- register_api_route(webapp, lock)-- register_ws_namespace(socketio_server, webapp, lock, manager=ws_manager)+ return server_runtime, host, port- init_a0()- wsgi_app = WSGIMiddleware(webapp)- starlette_app = Starlette(- routes=[- Mount("/mcp", app=mcp_server.DynamicMcpProxy.get_instance()),- Mount("/a2a", app=fasta2a_server.DynamicA2AProxy.get_instance()),- Mount("/", app=wsgi_app),- ]+def start_web_server(server_runtime: UiServerRuntime, host: str, port: int) -> None:+ run_uvicorn_with_retries(+ host=host,+ port=port,+ build_asgi_app=server_runtime.build_asgi_app,+ flush_callback=create_flush_callback(),+ access_log=server_runtime.access_log_enabled(),+ ws="wsproto",)- asgi_app = ASGIApp(socketio_server, other_asgi_app=starlette_app)+def create_flush_callback():def flush_and_shutdown_callback() -> None:"""TODO(dev): add cleanup + flush-to-disk logic here."""return+flush_ran = Falsedef _run_flush(reason: str) -> None:@@ -249,62 +69,19 @@ def run():except Exception as e:PrintStyle.warning(f"Shutdown flush failed ({reason}): {e}")- config = uvicorn.Config(- asgi_app,- host=host,- port=port,- log_level="info",- access_log=_settings.get("uvicorn_access_logs_enabled", False),- ws="wsproto",- )- server = uvicorn.Server(config)-- class _UvicornServerWrapper:- def __init__(self, server: uvicorn.Server):- self._server = server-- def shutdown(self) -> None:- _run_flush("shutdown")- self._server.should_exit = True-- process.set_server(_UvicornServerWrapper(server))-- PrintStyle().debug(f"Starting server at http://{host}:{port} ...")- threading.Thread(target=wait_for_health, args=(host, port), daemon=True).start()- try:- server.run()- finally:- _run_flush("server_exit")---def wait_for_health(host: str, port: int):- url = f"http://{host}:{port}/api/health"- while True:- try:- with urllib.request.urlopen(url, timeout=2) as resp:- if resp.status == 200:- PrintStyle().print("Agent Zero is running.")- return- except Exception:- pass- time.sleep(1)+ return _run_flush@extension.extensibledef init_a0():- # initialize contexts and MCPinit_chats = initialize.initialize_chats()- # only wait for init chats, otherwise they would seem to disappear for a while on restartinit_chats.result_sync()initialize.initialize_mcp()- # start job loopinitialize.initialize_job_loop()- # preloadinitialize.initialize_preload()-# run the internal serverif __name__ == "__main__":runtime.initialize()dotenv.load_dotenv()diff --git a/tests/test_self_update_tag_filter.py b/tests/test_self_update_tag_filter.pyindex dbbb70d48..b0a3d3376 100644--- a/tests/test_self_update_tag_filter.py+++ b/tests/test_self_update_tag_filter.py@@ -320,10 +320,15 @@ def test_self_update_update_info_uses_current_branch_for_latest_version(monkeypa"get_selector_tag_options",lambda branch, *, repo_dir=None, current_version=None: ([{"value": "latest", "label": "latest (v1.4)"}],- [],+ [2] if branch == "main" else [],"",),)+ monkeypatch.setattr(+ self_update,+ "get_available_tags",+ lambda branch, *, repo_dir=None, query="": (["v1.4", "v1.2"], ""),+ )monkeypatch.setattr(self_update,"durable_self_update_supports_latest",@@ -358,6 +363,102 @@ def test_self_update_update_info_uses_current_branch_for_latest_version(monkeypa"display_version": "v1.4","commit": "def5678abcd","short_commit": "def5678",+ "released_at": "",+ }+ assert info["main_branch_latest"] == {+ "branch": "main",+ "supported": True,+ "describe": "v1.4",+ "short_tag": "v1.4",+ "display_version": "v1.4",+ "commit": "def5678abcd",+ "short_commit": "def5678",+ "released_at": "",+ }+ assert info["major_upgrade_versions"] == [2]+++def test_self_update_main_branch_latest_stays_within_current_major(monkeypatch, tmp_path):+ monkeypatch.setattr(+ self_update,+ "get_available_branch_values",+ lambda repo_dir=None: ["main", "development"],+ )+ monkeypatch.setattr(+ self_update,+ "get_available_tags",+ lambda branch, *, repo_dir=None, query="": (+ ["v2.0", "v1.4", "v1.2"],+ "",+ ),+ )+ monkeypatch.setattr(+ self_update,+ "_get_branch_head_info",+ lambda branch, repo_dir=None: {+ "describe": "v2.0",+ "short_tag": "v2.0",+ "commit": "feedbee1234",+ "released_at": "2026-03-30 15:15:50",+ },+ )+ monkeypatch.setattr(+ self_update,+ "_run_git",+ lambda repo_dir, *args: {+ ("rev-parse", "refs/tags/v1.4^{commit}"): "deadbeef1234",+ }[args],+ )+ monkeypatch.setattr(+ self_update,+ "_get_tag_release_time_in_repo",+ lambda repo_dir, tag: "2026-02-01 08:30:00" if tag == "v1.4" else "",+ )++ info = self_update.get_current_major_main_latest_info("v1.2", repo_dir=tmp_path)++ assert info == {+ "branch": "main",+ "supported": True,+ "describe": "v1.4",+ "short_tag": "v1.4",+ "display_version": "v1.4",+ "commit": "deadbeef1234",+ "short_commit": "deadbee",+ "released_at": "2026-02-01 08:30:00",+ }+++def test_self_update_remote_branch_head_info_resolves_release_time_before_temp_repo_is_removed(+ monkeypatch,+):+ monkeypatch.setattr(self_update, "_remote_branch_head_cache", {})++ def fake_run_git(repo_dir, *args):+ if args[:2] == ("init", "--bare"):+ return ""+ if args[0] == "fetch":+ return ""+ if args[:3] == ("describe", "--tags", "--always"):+ return "v1.5"+ if args[:2] == ("rev-parse", "refs/remotes/origin/main"):+ return "abc1234def5678"+ raise AssertionError(args)++ monkeypatch.setattr(self_update, "_run_git", fake_run_git)+ monkeypatch.setattr(+ self_update,+ "_get_tag_release_time_in_repo",+ lambda repo_dir, tag: "2026-03-30 15:15:50" if Path(repo_dir).exists() else "",+ )++ info = self_update._get_remote_branch_head_info("main")++ assert info == {+ "describe": "v1.5",+ "short_tag": "v1.5",+ "commit": "abc1234def5678",+ "released_at": "2026-03-30 15:15:50",}@@ -376,9 +477,16 @@ def test_self_update_frontend_uses_preloaded_select():assert "const MIN_SELECTOR_VERSION = [1, 0];" in contentassert "availableTagOptions: []" in contentassert "higherMajorVersions: []" in content+ assert "majorUpgradeVersions: []" in content+ assert 'activeTab: "quick"' in content+ assert "get hasPendingInitialLoad()" in content+ assert "get isCheckingStatus()" in content+ assert "get hasMajorUpgrade()" in content+ assert "get majorUpgradeBannerMessage()" in contentassert "this.applyAvailableTags({" in contentassert "response.available_tag_options" in contentassert "response.available_higher_major_versions" in content+ assert "response.major_upgrade_versions" in contentassert "response.tag_options" in contentassert "response.higher_major_versions" in contentassert "response.pending || {" in content@@ -390,8 +498,20 @@ def test_self_update_frontend_uses_preloaded_select():assert "Release tag must be v1.0 or newer." in contentassert "isLatestSelectorTag(value)" in contentassert "this.isSelectableTag(this.form.tag)" in content+ assert "get mainBranchLatestTag()" in content+ assert "quickUpdateAvailable" in content+ assert "scheduleQuickUpdate()" in content+ assert 'branch: "main"' in content+ assert "quickComparisonIcon" in content+ assert "quickComparisonIconClass" in content+ assert "Checking update status..." in content+ assert '"CHECKING"' in content+ assert '"Loading"' in content+ assert "formatReleaseTimestamp(value)" in contentassert "getLastStatusBadgeClass(status)" in contentassert "this.info?.current?.display_version" in content+ assert "this.info?.main_branch_latest?.display_version" in content+ assert "this.info?.current?.released_at" in contentassert "resetRestartState()" in contentassert "restartRequestStarted" in contentassert "restartResponse.status >= 500" in content@@ -433,14 +553,39 @@ def test_self_update_modal_uses_standard_select_and_manual_backup():assert "$store.selfUpdateStore.availableTagOptions" in contentassert "$store.selfUpdateStore.info?.current?.describe" in contentassert "current_branch_latest?.display_version" in content+ assert "mainBranchLatestVersion" in contentassert "tagOption.label" in content+ assert 'id="self-update-quick-tab"' in content+ assert 'id="self-update-advanced-tab"' in contentassert 'data-bs-target="#self-update-last-attempt-collapse"' in content+ assert "New major version available" in content+ assert 'x-show="$store.selfUpdateStore.hasMajorUpgrade"' in content+ assert "$store.selfUpdateStore.majorUpgradeBannerMessage" in content+ assert "Website installation guide" in contentassert "self-update-header-status" in content+ assert ".status-pill.self-update-quick-status" in contentassert "getLastStatusLabel($store.selfUpdateStore.info?.last_status?.status)" in content+ assert "Current version vs latest on main" not in content+ assert "quickComparisonIcon" in content+ assert "quickComparisonIconClass" in content+ assert "{ spinning: $store.selfUpdateStore.isCheckingStatus }" in content+ assert "formatReleaseTimestamp($store.selfUpdateStore.currentReleasedAt)" in content+ assert "formatReleaseTimestamp($store.selfUpdateStore.mainBranchLatestReleasedAt)" in contentassert "Latest version" in contentassert "Docker update guide" in contentassert "https://www.agent-zero.ai/p/docs/get-started/" in content+ assert "Version numbers use the format <code>vMAJOR.MINOR</code>" in content+ assert "requires a newer" in content+ assert "Docker image." in content+ assert "minor release line" in content+ assert "Agent Zero self-update inside the existing image." in content+ assert "On development branches you may also see versions like <code>v1.5+2</code>" in content+ assert "This suffix is not used on" in content+ assert "Only versions from the current major release line are listed here." in contentassert "Manual backup" in content+ assert ">Refresh Status<" not in content+ assert "Refresh" in content+ assert "Loading update status..." not in contentassert 'type="button"' in contentassert "@blur" not in contentassert "selectTag(tag)" not in contentdiff --git a/webui/components/settings/external/self-update-modal.html b/webui/components/settings/external/self-update-modal.htmlindex 8625f14e6..13dd5622f 100644--- a/webui/components/settings/external/self-update-modal.html+++ b/webui/components/settings/external/self-update-modal.html@@ -14,314 +14,447 @@x-destroy="$store.selfUpdateStore.cleanup()"class="self-update-modal">- <div class="self-update-version-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">- Commit- <code x-text="$store.selfUpdateStore.info?.current?.short_commit || 'unknown'"></code>+ <div+ class="self-update-warning-banner self-update-major-version-banner"+ x-show="$store.selfUpdateStore.hasMajorUpgrade"+ >+ <div class="self-update-major-version-banner-copy">+ <div class="self-update-major-version-banner-title">+ New major version available</div>- <div class="summary-meta" x-text="`Branch ${$store.selfUpdateStore.currentBranch || 'unknown'}`"></div>- <template x-if="$store.selfUpdateStore.info?.current?.describe && $store.selfUpdateStore.info?.current?.describe !== $store.selfUpdateStore.info?.current?.short_tag">- <div- class="summary-meta"- x-text="$store.selfUpdateStore.info?.current?.describe"- ></div>- </template>+ <div x-text="$store.selfUpdateStore.majorUpgradeBannerMessage"></div></div>+ <a+ href="https://www.agent-zero.ai/p/docs/get-started/"+ target="_blank"+ rel="noreferrer"+ >+ Website installation guide+ </a>+ </div>- <div class="self-update-summary-card">- <div class="summary-label">Latest version</div>- <div- class="summary-value"- x-text="$store.selfUpdateStore.info?.current_branch_latest?.display_version || 'Unavailable'"- ></div>- <template x-if="$store.selfUpdateStore.info?.current_branch_latest?.short_commit && $store.selfUpdateStore.info?.current_branch_latest?.branch !== 'main'">- <div class="summary-meta">- Commit- <code x-text="$store.selfUpdateStore.info?.current_branch_latest?.short_commit"></code>+ <div class="self-update-tabs">+ <ul class="nav nav-tabs" id="self-update-tabs" role="tablist">+ <li class="nav-item" role="presentation">+ <button+ class="nav-link"+ :class="{ active: $store.selfUpdateStore.activeTab === 'quick' }"+ id="self-update-quick-tab"+ type="button"+ role="tab"+ aria-controls="self-update-quick"+ :aria-selected="$store.selfUpdateStore.activeTab === 'quick'"+ @click="$store.selfUpdateStore.setTab('quick')"+ >+ Quick+ </button>+ </li>+ <li class="nav-item" role="presentation">+ <button+ class="nav-link"+ :class="{ active: $store.selfUpdateStore.activeTab === 'advanced' }"+ id="self-update-advanced-tab"+ type="button"+ role="tab"+ aria-controls="self-update-advanced"+ :aria-selected="$store.selfUpdateStore.activeTab === 'advanced'"+ @click="$store.selfUpdateStore.setTab('advanced')"+ >+ Advanced+ </button>+ </li>+ </ul>+ </div>++ <template x-if="$store.selfUpdateStore.activeTab === 'quick'">+ <div id="self-update-quick" role="tabpanel" aria-labelledby="self-update-quick-tab">+ <div class="self-update-quick-card">+ <div class="self-update-quick-header">+ <div+ class="status-pill self-update-quick-status"+ :class="$store.selfUpdateStore.quickStatusBadgeClass"+ x-text="$store.selfUpdateStore.quickStatusLabel"+ ></div></div>- </template>- <div- class="summary-meta"- x-text="`Branch ${$store.selfUpdateStore.info?.current_branch_latest?.branch || $store.selfUpdateStore.currentBranch || 'unknown'}`"- ></div>- <template x-if="$store.selfUpdateStore.info?.current_branch_latest?.describe && $store.selfUpdateStore.info?.current_branch_latest?.describe !== $store.selfUpdateStore.info?.current_branch_latest?.short_tag">+<div- class="summary-meta"- x-text="$store.selfUpdateStore.info?.current_branch_latest?.describe"+ class="self-update-quick-copy self-update-quick-copy-prominent"+ x-text="$store.selfUpdateStore.quickStatusMessage"></div>- </template>- <template x-if="$store.selfUpdateStore.info?.current_branch_latest?.supported === false">- <div class="summary-meta">- Latest official version is only tracked for <code>main</code>, <code>testing</code>,- and <code>development</code>.++ <div class="self-update-quick-grid">+ <div class="self-update-quick-version-card">+ <div class="summary-label">Current</div>+ <div class="summary-value" x-text="$store.selfUpdateStore.currentVersion"></div>+ <div class="summary-meta">+ <span x-text="$store.selfUpdateStore.formatReleaseTimestamp($store.selfUpdateStore.currentReleasedAt)"></span>+ </div>+ </div>++ <div class="self-update-quick-arrow" :class="$store.selfUpdateStore.quickComparisonIconClass" aria-hidden="true">+ <span+ class="material-symbols-outlined"+ :class="{ spinning: $store.selfUpdateStore.isCheckingStatus }"+ x-text="$store.selfUpdateStore.quickComparisonIcon"+ ></span>+ </div>++ <div class="self-update-quick-version-card self-update-quick-version-card-accent">+ <div class="summary-label">Latest on main</div>+ <div+ class="summary-value"+ x-text="$store.selfUpdateStore.mainBranchLatestVersion"+ ></div>+ <div class="summary-meta">+ <span x-text="$store.selfUpdateStore.formatReleaseTimestamp($store.selfUpdateStore.mainBranchLatestReleasedAt)"></span>+ </div>+ </div></div>- </template>- </div>- </div>- <div class="self-update-summary-grid" x-show="$store.selfUpdateStore.info?.pending">- <div class="self-update-summary-card">- <div class="summary-label">Pending request</div>- <div- class="summary-value"- x-text="$store.selfUpdateStore.formatBranchTag($store.selfUpdateStore.info?.pending?.branch, $store.selfUpdateStore.info?.pending?.tag)"- ></div>- <div- class="summary-meta"- x-text="$store.selfUpdateStore.formatTimestamp($store.selfUpdateStore.info?.pending?.requested_at)"- ></div>- </div>- </div>+ <div class="self-update-quick-note">+ Quick mode always targets <code>main</code> and uses the default backup settings.+ Use Advanced for a different branch, manual version selection, or custom backup behavior.+ </div>+ </div>- <template x-if="!$store.selfUpdateStore.isSupported">- <div class="self-update-warning">- Self-update is currently available only in dockerized Agent Zero deployments- that boot through <code>/exe/run_A0.sh</code>.+ <div+ class="self-update-warning-banner"+ x-show="$store.selfUpdateStore.quickMajorUpgradeNotice"+ >+ <span x-text="$store.selfUpdateStore.quickMajorUpgradeNotice"></span>+ </div></div></template>- <div class="self-update-panel">- <button- type="button"- class="self-update-panel-toggle"- data-bs-toggle="collapse"- data-bs-target="#self-update-howto-collapse"- aria-expanded="false"- aria-controls="self-update-howto-collapse"+ <template x-if="$store.selfUpdateStore.activeTab === 'advanced'">+ <div+ id="self-update-advanced"+ role="tabpanel"+ aria-labelledby="self-update-advanced-tab"+ class="self-update-advanced-layout">- <span>How it works?</span>- <span class="material-symbols-outlined self-update-panel-toggle-icon">expand_more</span>- </button>- <div class="collapse" id="self-update-howto-collapse">- <div class="self-update-panel-body 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 version target 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>- </div>- </div>-- <template x-if="$store.selfUpdateStore.info?.last_status">- <div class="self-update-panel">- <button- type="button"- class="self-update-panel-toggle"- data-bs-toggle="collapse"- data-bs-target="#self-update-last-attempt-collapse"- aria-expanded="false"- aria-controls="self-update-last-attempt-collapse"- >- <span>Last Attempt</span>- <span class="self-update-panel-toggle-trailing">- <span- class="status-pill self-update-header-status"- :class="$store.selfUpdateStore.getLastStatusBadgeClass($store.selfUpdateStore.info?.last_status?.status)"- x-text="$store.selfUpdateStore.getLastStatusLabel($store.selfUpdateStore.info?.last_status?.status)"- ></span>- <span class="material-symbols-outlined self-update-panel-toggle-icon">expand_more</span>- </span>- </button>- <div class="collapse" id="self-update-last-attempt-collapse">- <div class="self-update-panel-body">- <div class="status-message" x-text="$store.selfUpdateStore.info?.last_status?.message || ''"></div>+ <div class="self-update-version-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">- Trigger:- <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>- </div>- <div class="summary-meta">- Log:- <code x-text="$store.selfUpdateStore.info?.paths?.log_file || '/exe/a0-self-update.log'"></code>+ Commit+ <code x-text="$store.selfUpdateStore.info?.current?.short_commit || 'unknown'"></code></div>+ <div class="summary-meta" x-text="`Branch ${$store.selfUpdateStore.currentBranch || 'unknown'}`"></div>+ <template x-if="$store.selfUpdateStore.info?.current?.describe && $store.selfUpdateStore.info?.current?.describe !== $store.selfUpdateStore.info?.current?.short_tag">+ <div+ class="summary-meta"+ x-text="$store.selfUpdateStore.info?.current?.describe"+ ></div>+ </template>+ </div>++ <div class="self-update-summary-card">+ <div class="summary-label">Latest version</div>+ <div+ class="summary-value"+ x-text="$store.selfUpdateStore.info?.current_branch_latest?.display_version || 'Unavailable'"+ ></div>+ <template x-if="$store.selfUpdateStore.info?.current_branch_latest?.short_commit && $store.selfUpdateStore.info?.current_branch_latest?.branch !== 'main'">+ <div class="summary-meta">+ Commit+ <code x-text="$store.selfUpdateStore.info?.current_branch_latest?.short_commit"></code>+ </div>+ </template><divclass="summary-meta"- x-text="$store.selfUpdateStore.formatTimestamp($store.selfUpdateStore.info?.last_status?.finished_at)"+ x-text="`Branch ${$store.selfUpdateStore.info?.current_branch_latest?.branch || $store.selfUpdateStore.currentBranch || 'unknown'}`"></div>- <template x-if="$store.selfUpdateStore.info?.last_status?.backup_zip_path">- <div class="status-path">- Backup:- <code x-text="$store.selfUpdateStore.info?.last_status?.backup_zip_path"></code>+ <template x-if="$store.selfUpdateStore.info?.current_branch_latest?.describe && $store.selfUpdateStore.info?.current_branch_latest?.describe !== $store.selfUpdateStore.info?.current_branch_latest?.short_tag">+ <div+ class="summary-meta"+ x-text="$store.selfUpdateStore.info?.current_branch_latest?.describe"+ ></div>+ </template>+ <template x-if="$store.selfUpdateStore.info?.current_branch_latest?.supported === false">+ <div class="summary-meta">+ Latest official version is only tracked for <code>main</code>, <code>testing</code>,+ and <code>development</code>.</div></template></div></div>- </div>- </template>- <template x-if="$store.selfUpdateStore.isSupported">- <div>- <div class="field">- <div class="field-label">- <div class="field-title">Target branch</div>- <div class="field-description">- Choose which official branch context should be used when resolving the requested tag.- </div>- </div>- <div class="field-control">- <select- x-model="$store.selfUpdateStore.form.branch"- x-effect="$nextTick(() => { $el.value = $store.selfUpdateStore.form.branch || 'main'; })"- @change="$store.selfUpdateStore.onBranchChanged()"- :disabled="$store.selfUpdateStore.isBusy"- >- <template x-for="branch in ($store.selfUpdateStore.info?.branches || [])" :key="branch.value">- <option :value="branch.value" x-text="branch.label"></option>- </template>- </select>+ <div class="self-update-summary-grid" x-show="$store.selfUpdateStore.info?.pending">+ <div class="self-update-summary-card">+ <div class="summary-label">Pending request</div>+ <div+ class="summary-value"+ x-text="$store.selfUpdateStore.formatBranchTag($store.selfUpdateStore.info?.pending?.branch, $store.selfUpdateStore.info?.pending?.tag)"+ ></div>+ <div+ class="summary-meta"+ x-text="$store.selfUpdateStore.formatTimestamp($store.selfUpdateStore.info?.pending?.requested_at)"+ ></div></div></div>- <div class="field">- <div class="field-label">- <div class="field-title">Version</div>- <div class="field-description">- Choose a preloaded version target from the- <a href="https://github.com/agent0ai/agent-zero" target="_blank" rel="noreferrer">Agent Zero repository</a>.- Only versions from the current major release line are listed here. Newer major lines require a Docker image update first.- </div>- <div class="field-description">- <code>latest</code> resolves to the newest tag on <code>main</code>, and to the current branch head on <code>testing</code> and <code>development</code>.- </div>- <template x-if="$store.selfUpdateStore.tagsError">- <div class="field-description">- Version lookup failed:- <span x-text="$store.selfUpdateStore.tagsError"></span>- </div>- </template>+ <template x-if="!$store.selfUpdateStore.isSupported">+ <div class="self-update-warning">+ Self-update is currently available only in dockerized Agent Zero deployments+ that boot through <code>/exe/run_A0.sh</code>.</div>- <template x-if="$store.selfUpdateStore.higherMajorVersionMessage">- <div class="self-update-warning-banner">- <div x-text="$store.selfUpdateStore.higherMajorVersionMessage"></div>- <a- href="https://www.agent-zero.ai/p/docs/get-started/"- target="_blank"- rel="noreferrer"- >- Docker update guide- </a>- </div>- </template>- <div class="field-control">- <select- x-model="$store.selfUpdateStore.form.tag"- :disabled="$store.selfUpdateStore.isBusy || $store.selfUpdateStore.tagsLoading || !$store.selfUpdateStore.hasAvailableTags"- >- <option value="" x-text="$store.selfUpdateStore.versionSelectPlaceholder"></option>- <template x-for="tagOption in $store.selfUpdateStore.availableTagOptions" :key="tagOption.value">- <option :value="tagOption.value" x-text="tagOption.label"></option>- </template>- </select>- </div>- </div>+ </template>- <div class="field">- <div class="field-label">- <div class="field-title">Back up <code>/a0/usr</code> first</div>- <div class="field-description">- Creates a zip backup before the release files are replaced.+ <div class="self-update-panel">+ <button+ type="button"+ class="self-update-panel-toggle"+ data-bs-toggle="collapse"+ data-bs-target="#self-update-howto-collapse"+ aria-expanded="false"+ aria-controls="self-update-howto-collapse"+ >+ <span>How it works?</span>+ <span class="material-symbols-outlined self-update-panel-toggle-icon">expand_more</span>+ </button>+ <div class="collapse" id="self-update-howto-collapse">+ <div class="self-update-panel-body 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 version target 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>+ <p>+ Version numbers use the format <code>vMAJOR.MINOR</code>. The first number is+ the major release line and moving to a newer major version requires a newer+ Docker image. The second number is the minor release line and those updates can+ be applied through Agent Zero self-update inside the existing image.+ </p>+ <p>+ On development branches you may also see versions like <code>v1.5+2</code>.+ The <code>+2</code> means that checkout is based on <code>v1.5</code> plus two+ additional commits after that release tag. This suffix is not used on+ <code>main</code>.+ </p></div></div>- <div class="field-control">- <label class="toggle">- <input- type="checkbox"- x-model="$store.selfUpdateStore.form.backup_usr"- :disabled="$store.selfUpdateStore.isBusy"- />- <span class="toggler"></span>- </label>- </div></div>- <div x-show="$store.selfUpdateStore.form.backup_usr">- <div class="field">- <div class="field-label">- <div class="field-title">Backup directory</div>- <div class="field-description">- Absolute or repo-relative path where the <code>usr</code> zip should be written.+ <template x-if="$store.selfUpdateStore.info?.last_status">+ <div class="self-update-panel">+ <button+ type="button"+ class="self-update-panel-toggle"+ data-bs-toggle="collapse"+ data-bs-target="#self-update-last-attempt-collapse"+ aria-expanded="false"+ aria-controls="self-update-last-attempt-collapse"+ >+ <span>Last Attempt</span>+ <span class="self-update-panel-toggle-trailing">+ <span+ class="status-pill self-update-header-status"+ :class="$store.selfUpdateStore.getLastStatusBadgeClass($store.selfUpdateStore.info?.last_status?.status)"+ x-text="$store.selfUpdateStore.getLastStatusLabel($store.selfUpdateStore.info?.last_status?.status)"+ ></span>+ <span class="material-symbols-outlined self-update-panel-toggle-icon">expand_more</span>+ </span>+ </button>+ <div class="collapse" id="self-update-last-attempt-collapse">+ <div class="self-update-panel-body">+ <div class="status-message" x-text="$store.selfUpdateStore.info?.last_status?.message || ''"></div>+ <div class="summary-meta">+ Trigger:+ <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>+ </div>+ <div class="summary-meta">+ Log:+ <code x-text="$store.selfUpdateStore.info?.paths?.log_file || '/exe/a0-self-update.log'"></code>+ </div>+ <div+ class="summary-meta"+ x-text="$store.selfUpdateStore.formatTimestamp($store.selfUpdateStore.info?.last_status?.finished_at)"+ ></div>+ <template x-if="$store.selfUpdateStore.info?.last_status?.backup_zip_path">+ <div class="status-path">+ Backup:+ <code x-text="$store.selfUpdateStore.info?.last_status?.backup_zip_path"></code>+ </div>+ </template></div></div>- <div class="field-control">- <input- type="text"- x-model="$store.selfUpdateStore.form.backup_path"- :disabled="$store.selfUpdateStore.isBusy"- />- </div></div>+ </template>- <div class="field">- <div class="field-label">- <div class="field-title">Manual backup</div>- <div class="field-description">- Open the existing backup and restore modal if you want to create a backup before scheduling the update.+ <template x-if="$store.selfUpdateStore.isSupported">+ <div>+ <div class="field">+ <div class="field-label">+ <div class="field-title">Target branch</div>+ <div class="field-description">+ Choose which official branch context should be used when resolving the requested tag.+ </div>+ </div>+ <div class="field-control">+ <select+ x-model="$store.selfUpdateStore.form.branch"+ x-effect="$nextTick(() => { $el.value = $store.selfUpdateStore.form.branch || 'main'; })"+ @change="$store.selfUpdateStore.onBranchChanged()"+ :disabled="$store.selfUpdateStore.isBusy"+ >+ <template x-for="branch in ($store.selfUpdateStore.info?.branches || [])" :key="branch.value">+ <option :value="branch.value" x-text="branch.label"></option>+ </template>+ </select></div></div>- <div class="field-control">- <button- type="button"- class="btn btn-field"- @click="$store.selfUpdateStore.openManualBackupModal()"- :disabled="$store.selfUpdateStore.isBusy"- >- Manual backup- </button>- </div>- </div>- <div class="field">- <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. Leave it as-is for the default <code>usr-timestamp.zip</code> format.+ <div class="field">+ <div class="field-label">+ <div class="field-title">Version</div>+ <div class="field-description">+ Choose a preloaded version target from the+ <a href="https://github.com/agent0ai/agent-zero" target="_blank" rel="noreferrer">Agent Zero repository</a>.+ Only versions from the current major release line are listed here. Newer major lines require a Docker image update first.+ </div>+ <div class="field-description">+ <code>latest</code> resolves to the newest tag on <code>main</code>, and to the current branch head on <code>testing</code> and <code>development</code>.+ </div>+ <template x-if="$store.selfUpdateStore.tagsError">+ <div class="field-description">+ Version lookup failed:+ <span x-text="$store.selfUpdateStore.tagsError"></span>+ </div>+ </template>+ </div>+ <template x-if="$store.selfUpdateStore.higherMajorVersionMessage">+ <div class="self-update-warning-banner">+ <div x-text="$store.selfUpdateStore.higherMajorVersionMessage"></div>+ <a+ href="https://www.agent-zero.ai/p/docs/get-started/"+ target="_blank"+ rel="noreferrer"+ >+ Docker update guide+ </a>+ </div>+ </template>+ <div class="field-control">+ <select+ x-model="$store.selfUpdateStore.form.tag"+ :disabled="$store.selfUpdateStore.isBusy || $store.selfUpdateStore.tagsLoading || !$store.selfUpdateStore.hasAvailableTags"+ >+ <option value="" x-text="$store.selfUpdateStore.versionSelectPlaceholder"></option>+ <template x-for="tagOption in $store.selfUpdateStore.availableTagOptions" :key="tagOption.value">+ <option :value="tagOption.value" x-text="tagOption.label"></option>+ </template>+ </select></div></div>- <div class="field-control">- <input- type="text"- x-model="$store.selfUpdateStore.form.backup_name"- :disabled="$store.selfUpdateStore.isBusy"- />++ <div class="field">+ <div class="field-label">+ <div class="field-title">Back up <code>/a0/usr</code> first</div>+ <div class="field-description">+ Creates a zip backup before the release files are replaced.+ </div>+ </div>+ <div class="field-control">+ <label class="toggle">+ <input+ type="checkbox"+ x-model="$store.selfUpdateStore.form.backup_usr"+ :disabled="$store.selfUpdateStore.isBusy"+ />+ <span class="toggler"></span>+ </label>+ </div></div>- </div>- <div class="field">- <div class="field-label">- <div class="field-title">If the filename already exists</div>- <div class="field-description">- Choose whether to rename the backup, replace it, or stop the update.+ <div x-show="$store.selfUpdateStore.form.backup_usr">+ <div class="field">+ <div class="field-label">+ <div class="field-title">Backup directory</div>+ <div class="field-description">+ Absolute or repo-relative path where the <code>usr</code> zip should be written.+ </div>+ </div>+ <div class="field-control">+ <input+ type="text"+ x-model="$store.selfUpdateStore.form.backup_path"+ :disabled="$store.selfUpdateStore.isBusy"+ />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Manual backup</div>+ <div class="field-description">+ Open the existing backup and restore modal if you want to create a backup before scheduling the update.+ </div>+ </div>+ <div class="field-control">+ <button+ type="button"+ class="btn btn-field"+ @click="$store.selfUpdateStore.openManualBackupModal()"+ :disabled="$store.selfUpdateStore.isBusy"+ >+ Manual backup+ </button>+ </div>+ </div>++ <div class="field">+ <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. Leave it as-is for the default <code>usr-timestamp.zip</code> format.+ </div>+ </div>+ <div class="field-control">+ <input+ type="text"+ x-model="$store.selfUpdateStore.form.backup_name"+ :disabled="$store.selfUpdateStore.isBusy"+ />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">If the filename already exists</div>+ <div class="field-description">+ Choose whether to rename the backup, replace it, or stop the update.+ </div>+ </div>+ <div class="field-control">+ <select+ x-model="$store.selfUpdateStore.form.backup_conflict_policy"+ :disabled="$store.selfUpdateStore.isBusy"+ >+ <option value="rename">Rename with suffix</option>+ <option value="overwrite">Overwrite existing zip</option>+ <option value="fail">Fail before restart</option>+ </select>+ </div></div></div>- <div class="field-control">- <select- x-model="$store.selfUpdateStore.form.backup_conflict_policy"- :disabled="$store.selfUpdateStore.isBusy"- >- <option value="rename">Rename with suffix</option>- <option value="overwrite">Overwrite existing zip</option>- <option value="fail">Fail before restart</option>- </select>++ <div class="self-update-file-hint">+ The durable trigger, status, and log files live outside <code>/a0</code>:+ <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>,+ <code x-text="$store.selfUpdateStore.info?.paths?.status_file || '/exe/a0-self-update-status.yaml'"></code>,+ <code x-text="$store.selfUpdateStore.info?.paths?.log_file || '/exe/a0-self-update.log'"></code>.</div></div>- </div>-- <div class="self-update-file-hint">- The durable trigger, status, and log files live outside <code>/a0</code>:- <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>,- <code x-text="$store.selfUpdateStore.info?.paths?.status_file || '/exe/a0-self-update-status.yaml'"></code>,- <code x-text="$store.selfUpdateStore.info?.paths?.log_file || '/exe/a0-self-update.log'"></code>.- </div>+ </template></div></template>@@ -329,9 +462,6 @@<span x-text="$store.selfUpdateStore.error"></span></div>- <div class="self-update-loading" x-show="$store.selfUpdateStore.loading">- Loading update status...- </div><div class="self-update-progress-state" x-show="$store.selfUpdateStore.restarting"><div class="self-update-progress-spinner"></div><div>@@ -341,21 +471,33 @@</div><div class="modal-footer" data-modal-footer>- <button- type="button"- class="btn btn-ok"- @click="$store.selfUpdateStore.scheduleUpdate()"- :disabled="!$store.selfUpdateStore.canScheduleUpdate"- >- Restart and Update- </button>+ <template x-if="$store.selfUpdateStore.activeTab === 'quick'">+ <button+ type="button"+ class="btn btn-ok"+ @click="$store.selfUpdateStore.scheduleQuickUpdate()"+ :disabled="!$store.selfUpdateStore.quickUpdateAvailable"+ >+ Restart and Update+ </button>+ </template>+ <template x-if="$store.selfUpdateStore.activeTab === 'advanced'">+ <button+ type="button"+ class="btn btn-ok"+ @click="$store.selfUpdateStore.scheduleUpdate()"+ :disabled="!$store.selfUpdateStore.canScheduleUpdate"+ >+ Restart and Update+ </button>+ </template><buttontype="button"class="btn btn-field"@click="$store.selfUpdateStore.refresh()":disabled="$store.selfUpdateStore.isBusy">- Refresh Status+ Refresh</button><buttontype="button"@@ -377,6 +519,146 @@gap: 1rem;}+ .self-update-tabs .nav {+ display: flex;+ padding-left: 0;+ margin: 0;+ list-style: none;+ border-bottom: 1px solid var(--color-border);+ gap: 0.25rem;+ }++ .self-update-major-version-banner {+ margin-bottom: -0.1rem;+ }++ .self-update-major-version-banner-copy {+ display: flex;+ flex-direction: column;+ gap: 0.2rem;+ max-width: 58rem;+ }++ .self-update-major-version-banner-title {+ font-weight: 700;+ }++ .self-update-tabs .nav-link {+ font-family: "Rubik", Arial, Helvetica, sans-serif;+ border: 1px solid transparent;+ border-top-left-radius: 4px;+ border-top-right-radius: 4px;+ padding: 0.4rem 0.7rem;+ background: transparent;+ color: var(--color-text-secondary);+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ }++ .self-update-tabs .nav-link.active {+ color: var(--color-text-primary);+ border-color: var(--color-border);+ border-bottom-color: transparent;+ background: var(--color-background);+ }++ .self-update-quick-card {+ padding: 0.25rem 0 0;+ }++ .self-update-quick-header {+ display: flex;+ align-items: center;+ justify-content: flex-start;+ gap: 0.75rem;+ margin-bottom: 0.65rem;+ }++ .status-pill.self-update-quick-status {+ margin-top: 0;+ padding: 0.34rem 0.82rem;+ font-size: 0.98rem;+ font-weight: 700;+ letter-spacing: 0.05em;+ }++ .self-update-quick-copy {+ color: var(--color-text-muted);+ line-height: 1.55;+ }++ .self-update-quick-copy-prominent {+ font-size: 1.18rem;+ color: var(--color-text);+ max-width: 58rem;+ }++ .self-update-quick-grid {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);+ gap: 0.9rem;+ align-items: stretch;+ margin-top: 1rem;+ }++ .self-update-quick-version-card {+ border: 1px solid var(--color-border);+ border-radius: 1rem;+ padding: 1rem;+ background: var(--color-panel);+ }++ .self-update-quick-version-card-accent {+ border-color: color-mix(in srgb, var(--color-border) 85%, transparent);+ }++ .self-update-quick-arrow {+ display: flex;+ align-items: center;+ justify-content: center;+ min-width: 3.25rem;+ }++ .self-update-quick-arrow .material-symbols-outlined {+ font-size: 2rem;+ }++ .self-update-quick-icon-success {+ color: var(--color-success, #16a34a);+ }++ .self-update-quick-icon-info {+ color: var(--color-primary, #2563eb);+ }++ .self-update-quick-icon-warning {+ color: var(--color-warning, #d97706);+ }++ .self-update-quick-icon-neutral {+ color: var(--color-text-muted);+ }++ .self-update-quick-version-card .summary-value {+ font-size: clamp(2rem, 3vw, 2.5rem);+ line-height: 1.05;+ }++ .self-update-quick-version-card .summary-meta {+ margin-top: 0.65rem;+ font-size: 1rem;+ }++ .self-update-quick-note {+ margin-top: 1rem;+ padding-top: 1rem;+ border-top: 1px solid color-mix(in srgb, var(--color-border) 78%, transparent);+ color: var(--color-text-muted);+ line-height: 1.5;+ }+.self-update-copy {color: var(--color-text-muted);line-height: 1.5;@@ -386,6 +668,12 @@margin: 0 0 0.75rem;}+ .self-update-advanced-layout {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ }+.self-update-panel {border: 1px solid var(--color-border);border-radius: 0.9rem;@@ -517,8 +805,7 @@}.self-update-warning,- .self-update-error,- .self-update-loading {+ .self-update-error {padding: 0.8rem 0.9rem;border-radius: 8px;}@@ -533,11 +820,6 @@color: var(--color-error);}- .self-update-loading {- background: var(--color-panel);- color: var(--color-text-muted);- }-.self-update-file-hint {color: var(--color-text-muted);line-height: 1.5;@@ -566,6 +848,12 @@color: var(--color-success, #16a34a);}+ .status-pill-info {+ border-color: color-mix(in srgb, var(--color-primary, #2563eb) 55%, var(--color-border));+ background: color-mix(in srgb, var(--color-primary, #2563eb) 16%, transparent);+ color: var(--color-primary, #2563eb);+ }+.status-pill-error {border-color: color-mix(in srgb, var(--color-error, #dc2626) 55%, var(--color-border));background: color-mix(in srgb, var(--color-error, #dc2626) 18%, transparent);@@ -590,6 +878,14 @@}@media (max-width: 720px) {+ .self-update-quick-grid {+ grid-template-columns: minmax(0, 1fr);+ }++ .self-update-quick-arrow {+ transform: rotate(90deg);+ }+.self-update-version-grid {grid-template-columns: minmax(0, 1fr);}diff --git a/webui/components/settings/external/self-update-store.js b/webui/components/settings/external/self-update-store.jsindex 87cf02b14..8c25bc1c7 100644--- a/webui/components/settings/external/self-update-store.js+++ b/webui/components/settings/external/self-update-store.js@@ -15,11 +15,13 @@ const model = {saving: false,restarting: false,tagsLoading: false,+ activeTab: "quick",error: "",tagsError: "",info: null,availableTagOptions: [],higherMajorVersions: [],+ majorUpgradeVersions: [],restartStatusText: "",restartDetailText: "",form: {@@ -37,18 +39,62 @@ const model = {return this.loading || this.saving || this.restarting;},+ get hasPendingInitialLoad() {+ return !this.info && !this.error;+ },++ get isCheckingStatus() {+ return this.loading || this.hasPendingInitialLoad;+ },+get isSupported() {return Boolean(this.info?.supported);},get currentVersion() {- return this.info?.current?.display_version || this.info?.current?.short_tag || "unknown";+ return (+ this.info?.current?.display_version ||+ this.info?.current?.short_tag ||+ (this.hasPendingInitialLoad ? "Loading" : "unknown")+ );},get currentBranch() {return this.info?.current?.branch || "";},+ get currentComparableVersion() {+ return this.info?.current?.short_tag || "";+ },++ get mainBranchLatestTag() {+ return this.info?.main_branch_latest?.short_tag || "";+ },++ get mainBranchLatestVersion() {+ return (+ this.info?.main_branch_latest?.display_version ||+ this.info?.main_branch_latest?.short_tag ||+ (this.hasPendingInitialLoad ? "Loading" : "Unavailable")+ );+ },++ get mainBranchLatestCommit() {+ return this.info?.main_branch_latest?.short_commit || "";+ },++ get mainBranchLatestSupported() {+ return Boolean(this.info?.main_branch_latest?.supported);+ },++ get currentReleasedAt() {+ return this.info?.current?.released_at || "";+ },++ get mainBranchLatestReleasedAt() {+ return this.info?.main_branch_latest?.released_at || "";+ },+get trimmedTag() {return (this.form.tag || "").trim();},@@ -78,6 +124,20 @@ const model = {return `A newer major release line is available on this branch (${versionText}). Major upgrades require downloading a newer Docker image before using self-update.`;},+ get hasMajorUpgrade() {+ return this.majorUpgradeVersions.length > 0;+ },++ get majorUpgradeBannerMessage() {+ if (!this.majorUpgradeVersions.length) return "";+ const versionLabels = this.majorUpgradeVersions.map((major) => `v${major}.x`);+ const versionText =+ versionLabels.length === 1+ ? versionLabels[0]+ : `${versionLabels.slice(0, -1).join(", ")} and ${versionLabels[versionLabels.length - 1]}`;+ return `A newer major release line is available (${versionText}). This self-updater keeps showing only updates from the current major version. Major upgrades require a new Docker image and data migration.`;+ },+get versionSelectPlaceholder() {if (this.tagsLoading) return "Loading versions...";if (!this.hasAvailableTags) return "No versions available";@@ -95,10 +155,157 @@ const model = {);},+ get quickUpdateComparison() {+ return this.compareSelectorVersions(+ this.mainBranchLatestTag,+ this.currentComparableVersion,+ );+ },++ get quickUpdateAvailable() {+ return (+ this.isSupported &&+ !this.isBusy &&+ this.mainBranchLatestSupported &&+ this.quickUpdateComparison !== null &&+ this.quickUpdateComparison > 0+ );+ },++ get quickStatusLabel() {+ if (this.isCheckingStatus) return "CHECKING";+ if (!this.isSupported) return "UNAVAILABLE";+ if (!this.mainBranchLatestSupported) return "MAIN UNAVAILABLE";+ if (!this.mainBranchLatestTag) return "UNAVAILABLE";+ if (this.quickUpdateComparison === null) return "REVIEW";+ if (this.quickUpdateComparison > 0) return "UPDATE AVAILABLE";+ if (this.quickUpdateComparison === 0) return "UP TO DATE";+ return "AHEAD OF MAIN";+ },++ get quickBehindMinorCount() {+ const latest = this.parseSelectorTag(this.mainBranchLatestTag);+ const current = this.parseSelectorTag(this.currentComparableVersion);+ if (!latest || !current || this.quickUpdateComparison === null || this.quickUpdateComparison <= 0) {+ return null;+ }+ if (latest[0] !== current[0]) {+ return 4;+ }+ return latest[1] - current[1];+ },++ get quickStatusMessage() {+ if (this.isCheckingStatus) {+ return "Checking update status...";+ }+ if (!this.isSupported) {+ return "Self-update is currently available only in dockerized Agent Zero deployments that boot through /exe/run_A0.sh.";+ }+ if (!this.mainBranchLatestSupported) {+ return "The main branch is not currently available from the configured remote.";+ }+ if (!this.mainBranchLatestTag) {+ return "No supported main-branch version could be resolved right now.";+ }+ if (this.quickUpdateComparison === null) {+ return "The current checkout does not expose a comparable tagged version. Use Advanced if you still want to choose a target manually.";+ }+ if (this.quickUpdateComparison > 0) {+ if (this.quickBehindMinorCount !== null && this.quickBehindMinorCount <= 3) {+ return `This instance is ${this.quickBehindMinorCount} minor version${this.quickBehindMinorCount === 1 ? "" : "s"} behind the latest release currently available on main.`;+ }+ return `This instance is significantly behind the latest release currently available on main. Restart Agent Zero to move to ${this.mainBranchLatestVersion}.`;+ }+ if (this.quickUpdateComparison === 0) {+ return "This instance already matches the latest version currently available on main.";+ }+ return "This checkout already reports a newer tagged version than main.";+ },++ get quickStatusBadgeClass() {+ if (this.isCheckingStatus) {+ return "status-pill-neutral";+ }+ if (!this.isSupported || !this.mainBranchLatestSupported || !this.mainBranchLatestTag) {+ return "status-pill-neutral";+ }+ if (this.quickUpdateComparison === null) {+ return "status-pill-neutral";+ }+ if (this.quickUpdateComparison === 0) {+ return "status-pill-success";+ }+ if (this.quickUpdateComparison > 0) {+ return this.quickBehindMinorCount !== null && this.quickBehindMinorCount <= 3+ ? "status-pill-info"+ : "status-pill-warning";+ }+ return "status-pill-neutral";+ },++ get quickComparisonIcon() {+ if (this.isCheckingStatus) return "progress_activity";+ if (!this.isSupported || !this.mainBranchLatestSupported || !this.mainBranchLatestTag) {+ return "help";+ }+ if (this.quickUpdateComparison === null) {+ return "help";+ }+ if (this.quickUpdateComparison === 0) {+ return "task_alt";+ }+ if (this.quickUpdateComparison > 0) {+ return this.quickBehindMinorCount !== null && this.quickBehindMinorCount <= 3+ ? "update"+ : "warning";+ }+ return "north_east";+ },++ get quickComparisonIconClass() {+ if (this.isCheckingStatus) {+ return "self-update-quick-icon-neutral";+ }+ if (!this.isSupported || !this.mainBranchLatestSupported || !this.mainBranchLatestTag) {+ return "self-update-quick-icon-neutral";+ }+ if (this.quickUpdateComparison === null) {+ return "self-update-quick-icon-neutral";+ }+ if (this.quickUpdateComparison === 0) {+ return "self-update-quick-icon-success";+ }+ if (this.quickUpdateComparison > 0) {+ return this.quickBehindMinorCount !== null && this.quickBehindMinorCount <= 3+ ? "self-update-quick-icon-info"+ : "self-update-quick-icon-warning";+ }+ return "self-update-quick-icon-neutral";+ },++ get quickMajorUpgradeNotice() {+ const latest = this.parseSelectorTag(this.mainBranchLatestTag);+ const current = this.parseSelectorTag(this.currentComparableVersion);+ if (!latest || !current || latest[0] === current[0]) {+ return "";+ }+ return (+ "This update crosses into a newer major release line. If your Docker image is older, " ++ "you may still need to update the image itself after applying the repo update."+ );+ },+async init() {await this.refresh();},+ setTab(tab) {+ if (tab === "quick" || tab === "advanced") {+ this.activeTab = tab;+ }+ },+cleanup() {this.clearReconnectTimer();this.error = "";@@ -109,6 +316,7 @@ const model = {this.tagsLoading = false;this.availableTagOptions = [];this.higherMajorVersions = [];+ this.majorUpgradeVersions = [];this.restartStatusText = "";this.restartDetailText = "";this.removeProgressOverlay();@@ -130,6 +338,19 @@ const model = {}},+ formatReleaseTimestamp(value) {+ if (!value) {+ if (this.hasPendingInitialLoad) {+ return "Loading";+ }+ return "Release date unavailable";+ }+ if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value)) {+ return value;+ }+ return this.formatTimestamp(value);+ },+formatBranchTag(branch, tag) {return `${branch || "main"} / ${tag || "None"}`;},@@ -283,6 +504,9 @@ const model = {throw new Error(response?.error || "Failed to load self-update info.");}this.info = response;+ this.majorUpgradeVersions = Array.isArray(response.major_upgrade_versions)+ ? response.major_upgrade_versions+ : [];this.applyFormState(response.pending || {...(response.defaults || {}),@@ -413,35 +637,22 @@ const model = {return this.isLatestSelectorTag(value) || this.isSupportedSelectorTag(value);},- async scheduleUpdate() {- if (!this.form.branch?.trim()) {- this.error = "Choose a branch.";- return;- }-- if (!this.form.tag?.trim()) {- this.error = "Choose a version from the list.";- return;- }-- if (!this.isLatestSelectorTag(this.form.tag) && !this.parseSelectorTag(this.form.tag)) {- this.error = "Release tag must use the format vX.Y.";- return;+ compareSelectorVersions(left, right) {+ const leftVersion = this.parseSelectorTag(left);+ const rightVersion = this.parseSelectorTag(right);+ if (!leftVersion || !rightVersion) {+ return null;}-- if (!this.isLatestSelectorTag(this.form.tag) && !this.isSupportedSelectorTag(this.form.tag)) {- this.error = "Release tag must be v1.0 or newer.";- return;+ if (leftVersion[0] !== rightVersion[0]) {+ return leftVersion[0] - rightVersion[0];}-- if (!this.selectedTagExistsOnBranch) {- await this.fetchTags();- if (!this.selectedTagExistsOnBranch) {- this.error = `Version ${this.trimmedTag} does not exist on branch ${this.form.branch || "main"}.`;- return;- }+ if (leftVersion[1] !== rightVersion[1]) {+ return leftVersion[1] - rightVersion[1];}+ return 0;+ },+ async scheduleUpdateRequest(payload, notificationMessage) {this.saving = true;this.error = "";this.setRestartState(@@ -450,14 +661,7 @@ const model = {);this.ensureProgressOverlay();try {- const response = await API.callJsonApi("self_update_schedule", {- branch: this.form.branch,- tag: this.form.tag,- backup_usr: this.form.backup_usr,- backup_path: this.form.backup_path,- backup_name: this.form.backup_name,- backup_conflict_policy: this.form.backup_conflict_policy,- });+ const response = await API.callJsonApi("self_update_schedule", payload);if (!response?.success) {throw new Error(response?.error || "Failed to schedule the self-update.");}@@ -466,7 +670,7 @@ const model = {this.info.pending = response.pending;}notificationStore.frontendWarning(- "Agent Zero is restarting to apply the requested branch and version target.",+ notificationMessage,"Self Update",10,"self-update-restart",@@ -487,6 +691,78 @@ const model = {}},+ async scheduleUpdate() {+ if (!this.form.branch?.trim()) {+ this.error = "Choose a branch.";+ return;+ }++ if (!this.form.tag?.trim()) {+ this.error = "Choose a version from the list.";+ return;+ }++ if (!this.isLatestSelectorTag(this.form.tag) && !this.parseSelectorTag(this.form.tag)) {+ this.error = "Release tag must use the format vX.Y.";+ return;+ }++ if (!this.isLatestSelectorTag(this.form.tag) && !this.isSupportedSelectorTag(this.form.tag)) {+ this.error = "Release tag must be v1.0 or newer.";+ return;+ }++ if (!this.selectedTagExistsOnBranch) {+ await this.fetchTags();+ if (!this.selectedTagExistsOnBranch) {+ this.error = `Version ${this.trimmedTag} does not exist on branch ${this.form.branch || "main"}.`;+ return;+ }+ }++ await this.scheduleUpdateRequest(+ {+ branch: this.form.branch,+ tag: this.form.tag,+ backup_usr: this.form.backup_usr,+ backup_path: this.form.backup_path,+ backup_name: this.form.backup_name,+ backup_conflict_policy: this.form.backup_conflict_policy,+ },+ "Agent Zero is restarting to apply the requested branch and version target.",+ );+ },++ async scheduleQuickUpdate() {+ if (!this.mainBranchLatestSupported || !this.mainBranchLatestTag) {+ this.error = "Latest main-branch version is not available right now.";+ return;+ }++ if (this.quickUpdateComparison === null) {+ this.error =+ "The current checkout cannot be compared to the latest main version. Use Advanced to choose a version manually.";+ return;+ }++ if (this.quickUpdateComparison <= 0) {+ return;+ }++ await this.scheduleUpdateRequest(+ {+ branch: "main",+ tag: this.mainBranchLatestTag,+ backup_usr: this.info?.defaults?.backup_usr ?? true,+ backup_path: this.info?.defaults?.backup_path || "",+ backup_name: this.info?.defaults?.backup_name || "",+ backup_conflict_policy:+ this.info?.defaults?.backup_conflict_policy || "rename",+ },+ "Agent Zero is restarting to apply the latest version from main.",+ );+ },+async restartAndReload() {this.restarting = true;this.clearReconnectTimer();