Agent Zero AI framework
fix(plugin-hub): preserve dirty edits during updates
spinnakergitd1e1c6494e1c
diff --git a/helpers/git.py b/helpers/git.pyindex a56f5f4b3..340d3fa1a 100644--- a/helpers/git.py+++ b/helpers/git.py@@ -6,6 +6,7 @@ import osimport subprocessimport base64import re+import timefrom urllib.parse import urlparse, urlunparsefrom helpers import filesfrom helpers.localization import Localization@@ -453,7 +454,36 @@ def clone_repo(url: str, dest: str, token: str | None = None):return Repo(dest)-def update_repo(repo_path: str) -> Repo:+class DirtyTreeConflictError(Exception):+ """Raised when a dirty plugin cannot be updated without overwriting local edits."""++ def __init__(self, conflicting_files: list[str]):+ super().__init__(+ "Local changes conflict with the update. "+ "Your plugin was restored without applying the update."+ )+ self.conflicting_files = conflicting_files+++def _list_dirty_tracked_files(repo: "Repo") -> list[str]:+ """Return tracked files with uncommitted modifications, excluding A0 metadata."""+ def _is_a0_file(path: str) -> bool:+ return path.startswith(".a0proj") or path == ".a0proj"++ changed = {d.a_path for d in repo.index.diff(None)}+ changed.update(d.a_path for d in repo.index.diff("HEAD"))+ return sorted(p for p in changed if p and not _is_a0_file(p))+++def update_repo(repo_path: str, auto_stash: bool = True) -> Repo:+ """Fast-forward the repo to its tracking branch.++ When `auto_stash` is True (default) and the working tree has uncommitted+ changes to tracked files, those changes are stashed before the pull and+ reapplied afterwards. If they conflict with the update, the repo and local+ edits are restored to their original state before `DirtyTreeConflictError`+ is raised.+ """repo = Repo(repo_path)if repo.bare:raise ValueError(f"Repository at {repo_path} is bare and cannot be updated.")@@ -469,8 +499,31 @@ def update_repo(repo_path: str) -> Repo:env = os.environ.copy()env['GIT_TERMINAL_PROMPT'] = '0'- with repo.git.custom_environment(**env):- repo.remotes[tracking_branch.remote_name].pull(branch)+ dirty_files = _list_dirty_tracked_files(repo) if auto_stash else []+ original_head = repo.head.commit.hexsha+ if dirty_files:+ stash_msg = f"a0-auto-stash-{int(time.time())}"+ repo.git.stash("push", "-m", stash_msg, "--", *dirty_files)++ def restore_original_state():+ repo.git.reset("--hard", original_head)+ if dirty_files:+ repo.git.stash("pop")++ try:+ with repo.git.custom_environment(**env):+ repo.remotes[tracking_branch.remote_name].pull(branch)+ except Exception:+ if dirty_files:+ restore_original_state()+ raise++ if dirty_files:+ try:+ repo.git.stash("pop")+ except Exception:+ restore_original_state()+ raise DirtyTreeConflictError(dirty_files)return repodiff --git a/helpers/git.py.dox.md b/helpers/git.py.dox.mdindex 2437ef854..9661a9d52 100644--- a/helpers/git.py.dox.md+++ b/helpers/git.py.dox.md@@ -30,7 +30,8 @@- `get_version()`- `is_official_agent_zero_repo() -> bool`: Return True when origin points to agent0ai/agent-zero.- `clone_repo(url: str, dest: str, token: str | None=...)`: Clone a git repository. Uses http.extraHeader for token auth (never stored in URL/config).-- `update_repo(repo_path: str) -> Repo`+- `DirtyTreeConflictError`: Reports a plugin update that was rolled back because its local edits conflict with upstream.+- `update_repo(repo_path: str, auto_stash: bool = True) -> Repo`: Temporarily stashes tracked plugin edits for an update, then restores them; on conflict it restores the original checkout and edits before raising `DirtyTreeConflictError`.- `get_repo_status(repo_path: str) -> dict`: Get Git repository status, ignoring A0 project metadata files.- Notable constants/configuration names: `A0_IGNORE_PATTERNS`.diff --git a/plugins/_plugin_installer/helpers/install.py b/plugins/_plugin_installer/helpers/install.pyindex d5ac1cc1f..9d6016688 100644--- a/plugins/_plugin_installer/helpers/install.py+++ b/plugins/_plugin_installer/helpers/install.py@@ -250,6 +250,16 @@ def update_from_git(plugin_name: str) -> dict:try:repo = git.update_repo(plugin_dir)meta = plugins.get_plugin_meta(plugin_name)+ except git.DirtyTreeConflictError as e:+ print_style.PrintStyle.error(f"Failed to update plugin: {e}")+ return {+ "ok": False,+ "success": False,+ "error": str(e),+ "error_kind": "dirty_tree_conflict",+ "plugin_name": plugin_name,+ "conflicting_files": e.conflicting_files,+ }except Exception as e:print_style.PrintStyle.error(f"Failed to update plugin: {e}")raisediff --git a/plugins/_plugin_installer/webui/install-detail.html b/plugins/_plugin_installer/webui/install-detail.htmlindex ef59dfce1..ce673e3b1 100644--- a/plugins/_plugin_installer/webui/install-detail.html+++ b/plugins/_plugin_installer/webui/install-detail.html@@ -193,6 +193,22 @@</template></div>+ <template x-if="$store.pluginInstallStore.detailError">+ <div class="pi-detail-error">+ <div class="pi-detail-error-header">+ <x-icon name="error"></x-icon>+ <span x-text="$store.pluginInstallStore.detailError.message"></span>+ </div>+ <template x-if="$store.pluginInstallStore.detailError.conflicting_files?.length">+ <ul class="pi-detail-error-files">+ <template x-for="f in $store.pluginInstallStore.detailError.conflicting_files" :key="f">+ <li x-text="f"></li>+ </template>+ </ul>+ </template>+ </div>+ </template>+<div class="pi-readme-section" x-show="$store.pluginInstallStore.readmeContent || $store.pluginInstallStore.readmeLoading"><div class="pi-readme-header">Readme</div><div x-show="$store.pluginInstallStore.readmeLoading" class="pi-loading-text">diff --git a/plugins/_plugin_installer/webui/install-shared.css b/plugins/_plugin_installer/webui/install-shared.cssindex c2837d576..02ce8f8a2 100644--- a/plugins/_plugin_installer/webui/install-shared.css+++ b/plugins/_plugin_installer/webui/install-shared.css@@ -40,3 +40,35 @@margin-top: 0.25rem;font-family: var(--font-family-code);}++.pi-detail-error {+ margin-top: 0.75rem;+ padding: 0.75rem;+ background: rgba(239, 68, 68, 0.1);+ border: 1px solid rgba(239, 68, 68, 0.35);+ border-radius: 4px;+ color: var(--color-text-primary);+}++.pi-detail-error-header {+ display: flex;+ align-items: flex-start;+ gap: 0.5rem;+ font-size: 0.9rem;+ line-height: 1.4;+}++.pi-detail-error-header x-icon {+ color: #ef4444;+ font-size: 1.25rem;+ flex-shrink: 0;+}++.pi-detail-error-files {+ margin: 0.5rem 0 0 1.75rem;+ padding: 0;+ list-style: disc;+ font-family: var(--font-family-code);+ font-size: 0.8rem;+ color: var(--color-text-secondary);+}diff --git a/plugins/_plugin_installer/webui/pluginInstallStore.js b/plugins/_plugin_installer/webui/pluginInstallStore.jsindex 7be752bde..c2bb3d632 100644--- a/plugins/_plugin_installer/webui/pluginInstallStore.js+++ b/plugins/_plugin_installer/webui/pluginInstallStore.js@@ -61,6 +61,11 @@ const model = {detailThumbnailUrl: null,+ // Inline error for the detail modal (e.g. update failure), structured so+ // the UI can render it next to the action button instead of relying on a+ // toast the user can miss.+ detailError: null,+// Tab stateactiveTab: "store",@@ -548,6 +553,7 @@ const model = {this.result = null;this.installedPluginInfo = null;this.readmeContent = null;+ this.detailError = null;this.detailThumbnailUrl = this.getThumbnailUrl(this.selectedPlugin);if (this.selectedPlugin.installed) {this.fetchInstalledPluginInfo(this.selectedPlugin.name);@@ -831,6 +837,8 @@ const model = {});if (!confirmed) return;+ this.detailError = null;+try {this.loading = true;this.loadingMessage = "Updating";@@ -841,7 +849,13 @@ const model = {});if (!(data?.ok && data?.success)) {- void toastFrontendError(data?.error || "Update failed", "Plugin Installer");+ const message = data?.error || "Update failed";+ this.detailError = {+ kind: data?.error_kind || "update_failed",+ message,+ conflicting_files: Array.isArray(data?.conflicting_files) ? data.conflicting_files : [],+ };+ void toastFrontendError(message, "Plugin Installer");return;}diff --git a/tests/test_plugin_git_update.py b/tests/test_plugin_git_update.pynew file mode 100644index 000000000..035cbe6a1--- /dev/null+++ b/tests/test_plugin_git_update.py@@ -0,0 +1,140 @@+import subprocess+import sys+from pathlib import Path++import pytest++PROJECT_ROOT = Path(__file__).resolve().parents[1]+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++from helpers import git as git_helpers+from plugins._plugin_installer.helpers import install+++def run_git(repo: Path, *args: str) -> str:+ return subprocess.run(+ ["git", "-C", str(repo), *args],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+++def git_status(repo: Path) -> str:+ return subprocess.run(+ ["git", "-C", str(repo), "status", "--porcelain"],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.rstrip()+++def make_plugin_repos(tmp_path: Path) -> tuple[Path, Path, Path]:+ remote = tmp_path / "remote.git"+ source = tmp_path / "source"+ installed = tmp_path / "installed"+ subprocess.run(["git", "init", "--bare", str(remote)], check=True, capture_output=True)+ subprocess.run(["git", "init", str(source)], check=True, capture_output=True)+ run_git(source, "config", "user.email", "[email protected]")+ run_git(source, "config", "user.name", "Tests")+ (source / "plugin.py").write_text("value = 'old'\n", encoding="utf-8")+ (source / "README.md").write_text("old\n", encoding="utf-8")+ run_git(source, "add", ".")+ run_git(source, "commit", "-m", "initial")+ run_git(source, "branch", "-M", "main")+ run_git(source, "remote", "add", "origin", str(remote))+ run_git(source, "push", "-u", "origin", "main")+ subprocess.run(+ ["git", "-C", str(remote), "symbolic-ref", "HEAD", "refs/heads/main"],+ check=True,+ capture_output=True,+ )+ subprocess.run(["git", "clone", str(remote), str(installed)], check=True, capture_output=True)+ run_git(installed, "config", "user.email", "[email protected]")+ run_git(installed, "config", "user.name", "Tests")+ return remote, source, installed+++def push_source_change(source: Path, path: str, content: str) -> None:+ (source / path).write_text(content, encoding="utf-8")+ run_git(source, "add", path)+ run_git(source, "commit", "-m", f"update {path}")+ run_git(source, "push")+++def test_update_repo_preserves_non_conflicting_tracked_and_untracked_files(tmp_path: Path):+ _, source, installed = make_plugin_repos(tmp_path)+ original_head = run_git(installed, "rev-parse", "HEAD")+ (installed / "README.md").write_text("local edit\n", encoding="utf-8")+ (installed / ".toggle-1").write_text("enabled\n", encoding="utf-8")+ push_source_change(source, "plugin.py", "value = 'upstream'\n")++ git_helpers.update_repo(str(installed))++ assert run_git(installed, "rev-parse", "HEAD") != original_head+ assert (installed / "plugin.py").read_text(encoding="utf-8") == "value = 'upstream'\n"+ assert (installed / "README.md").read_text(encoding="utf-8") == "local edit\n"+ assert (installed / ".toggle-1").read_text(encoding="utf-8") == "enabled\n"+ assert run_git(installed, "stash", "list") == ""+++def test_update_repo_drops_local_edit_that_matches_the_new_upstream_version(tmp_path: Path):+ _, source, installed = make_plugin_repos(tmp_path)+ (installed / "plugin.py").write_text("value = 'upstream'\n", encoding="utf-8")+ push_source_change(source, "plugin.py", "value = 'upstream'\n")++ git_helpers.update_repo(str(installed))++ assert (installed / "plugin.py").read_text(encoding="utf-8") == "value = 'upstream'\n"+ assert git_status(installed) == ""+ assert run_git(installed, "stash", "list") == ""+++def test_update_repo_restores_original_plugin_and_local_edit_after_conflict(tmp_path: Path):+ _, source, installed = make_plugin_repos(tmp_path)+ original_head = run_git(installed, "rev-parse", "HEAD")+ (installed / "plugin.py").write_text("value = 'local'\n", encoding="utf-8")+ push_source_change(source, "plugin.py", "value = 'upstream'\n")++ with pytest.raises(git_helpers.DirtyTreeConflictError) as exc_info:+ git_helpers.update_repo(str(installed))++ assert exc_info.value.conflicting_files == ["plugin.py"]+ assert run_git(installed, "rev-parse", "HEAD") == original_head+ assert (installed / "plugin.py").read_text(encoding="utf-8") == "value = 'local'\n"+ assert git_status(installed) == " M plugin.py"+ assert run_git(installed, "stash", "list") == ""+++def test_plugin_hub_renders_dirty_update_errors_inline():+ store = (PROJECT_ROOT / "plugins/_plugin_installer/webui/pluginInstallStore.js").read_text(encoding="utf-8")+ detail = (PROJECT_ROOT / "plugins/_plugin_installer/webui/install-detail.html").read_text(encoding="utf-8")++ assert "detailError" in store+ assert "error_kind" in store+ assert "pi-detail-error" in detail+ assert "conflicting_files" in detail+++def test_plugin_update_returns_structured_dirty_tree_error(monkeypatch, tmp_path: Path):+ plugin_dir = tmp_path / "plugin"+ plugin_dir.mkdir()+ monkeypatch.setattr(install.plugins, "find_plugin_dir", lambda _name: str(plugin_dir))+ monkeypatch.setattr(install.files, "get_abs_path", lambda *_parts: str(tmp_path))+ monkeypatch.setattr(install.files, "is_in_dir", lambda *_paths: True)+ monkeypatch.setattr(install, "run_pre_update_hook", lambda _name: None)++ def raise_conflict(_path: str):+ raise git_helpers.DirtyTreeConflictError(["plugin.py"])++ monkeypatch.setattr(install.git, "update_repo", raise_conflict)++ assert install.update_from_git("demo") == {+ "ok": False,+ "success": False,+ "error": "Local changes conflict with the update. Your plugin was restored without applying the update.",+ "error_kind": "dirty_tree_conflict",+ "plugin_name": "demo",+ "conflicting_files": ["plugin.py"],+ }