Agent Zero AI framework
refactor(git): Restructure git helpers with dataclasses and add remote update checking
frdel482fa42d9806
diff --git a/helpers/git.py b/helpers/git.pyindex 4e7049055..281317c4c 100644--- a/helpers/git.py+++ b/helpers/git.py@@ -1,6 +1,7 @@-from git import Repo+from git import Git, Repofrom giturlparse import parsefrom datetime import datetime+from dataclasses import dataclassimport osimport subprocessimport base64@@ -34,51 +35,332 @@ def extract_author_repo(url: str) -> tuple[str, str]:return author, repo-def get_git_info():- # Get the current working directory (assuming the repo is in the same folder as the script)- repo_path = files.get_base_dir()-- # Open the Git repository- repo = Repo(repo_path)+@dataclass+class GitHeadInfo:+ hash: str+ short_hash: str+ message: str+ author: str+ committed_at: str+ authored_at: str- # Ensure the repository is not bare- if repo.bare:- raise ValueError(f"Repository at {repo_path} is bare and cannot be used.")- # Get the current branch name- branch = repo.active_branch.name if repo.head.is_detached is False else ""+@dataclass+class GitReleaseInfo:+ tag: str+ short_tag: str+ version: str+ released_at: str+++@dataclass+class GitRemoteReleaseInfo:+ tag: str+ commit_hash: str+ short_commit_hash: str+ released_at: str+++@dataclass+class GitRemoteReleasesResult:+ is_git_repo: bool+ is_remote: bool+ author: str+ repo: str+ releases: list[GitRemoteReleaseInfo]+ error: str = ""+++@dataclass+class GitRemoteCommitsInfo:+ is_git_repo: bool+ is_remote: bool+ path: str+ branch: str+ remote_branch: str+ commits_since_local: int+ last_remote_commit_at: str+ error: str = ""+++@dataclass+class GitRepoReleaseInfo:+ is_git_repo: bool+ is_remote: bool+ path: str+ author: str+ repo: str+ branch: str+ head: GitHeadInfo | None+ release: GitReleaseInfo | None+ error: str = ""+++def _format_git_timestamp(timestamp: int) -> str:+ return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')+++def get_remote_releases(author: str, repo: str) -> GitRemoteReleasesResult:+ try:+ author = author.strip()+ repo = repo.strip()++ if not author or not repo:+ return GitRemoteReleasesResult(+ is_remote=False,+ is_git_repo=False,+ author=author,+ repo=repo,+ releases=[],+ error="Both author and repo are required.",+ )++ remote_url = f"https://github.com/{author}/{repo}.git"- # Get the latest commit hash- commit_hash = repo.head.commit.hexsha+ env = os.environ.copy()+ env['GIT_TERMINAL_PROMPT'] = '0'- # Get the commit date (ISO 8601 format)- commit_time = datetime.fromtimestamp(repo.head.commit.committed_date).strftime('%y-%m-%d %H:%M')+ try:+ output = Git().ls_remote('--tags', '--refs', '--', remote_url, with_extended_output=False, env=env)+ except Exception as e:+ return GitRemoteReleasesResult(+ is_remote=True,+ is_git_repo=False,+ author=author,+ repo=repo,+ releases=[],+ error=f"Git remote query failed: {str(e)}",+ )++ releases: list[GitRemoteReleaseInfo] = []++ for line in output.splitlines():+ line = line.strip()+ if not line:+ continue++ parts = line.split()+ if len(parts) != 2:+ continue++ commit_hash, ref_name = parts+ prefix = 'refs/tags/'+ if not ref_name.startswith(prefix):+ continue++ tag_name = ref_name[len(prefix):]+ releases.append(GitRemoteReleaseInfo(+ tag=tag_name,+ commit_hash=commit_hash,+ short_commit_hash=commit_hash[:7],+ released_at="",+ ))++ releases.sort(key=lambda release: release.tag, reverse=True)++ return GitRemoteReleasesResult(+ is_git_repo=True,+ is_remote=True,+ author=author,+ repo=repo,+ releases=releases,+ )+ except Exception as e:+ return GitRemoteReleasesResult(+ is_git_repo=False,+ is_remote=False,+ author=author,+ repo=repo,+ releases=[],+ error=str(e),+ )- # Get the latest tag description (if available)- short_tag = ""++def get_remote_commits_since_local(repo_path: str) -> GitRemoteCommitsInfo:try:- tag = repo.git.describe(tags=True)- tag_split = tag.split('-')- if len(tag_split) >= 3:- short_tag = "-".join(tag_split[:-1])- else:- short_tag = tag- except:+ repo = Repo(repo_path)+ if repo.bare:+ return GitRemoteCommitsInfo(+ is_git_repo=False,+ is_remote=False,+ path=repo_path,+ branch="",+ remote_branch="",+ commits_since_local=0,+ last_remote_commit_at="",+ error=f"Repository at {repo_path} is bare and cannot be used.",+ )++ if repo.head.is_detached:+ return GitRemoteCommitsInfo(+ is_git_repo=True,+ is_remote=False,+ path=repo_path,+ branch="",+ remote_branch="",+ commits_since_local=0,+ last_remote_commit_at="",+ error="Repository HEAD is detached.",+ )++ branch = repo.active_branch.name++ tracking_branch = repo.active_branch.tracking_branch()+ if tracking_branch is None:+ return GitRemoteCommitsInfo(+ is_git_repo=True,+ is_remote=False,+ path=repo_path,+ branch=branch,+ remote_branch="",+ commits_since_local=0,+ last_remote_commit_at="",+ error="Current branch has no tracking remote branch.",+ )++ remote_name = tracking_branch.remote_name+ remote = repo.remotes[remote_name]+ env = os.environ.copy()+ env['GIT_TERMINAL_PROMPT'] = '0'+ with repo.git.custom_environment(**env):+ remote.fetch(repo.active_branch.name)++ remote_commit = tracking_branch.commit+ commits = list(repo.iter_commits(f"{repo.head.commit.hexsha}..{tracking_branch.path}"))++ return GitRemoteCommitsInfo(+ is_git_repo=True,+ is_remote=True,+ path=repo_path,+ branch=branch,+ remote_branch=tracking_branch.path,+ commits_since_local=len(commits),+ last_remote_commit_at=_format_git_timestamp(remote_commit.committed_date) if commits else "",+ )+ except Exception as e:+ return GitRemoteCommitsInfo(+ is_git_repo=False,+ is_remote=False,+ path=repo_path,+ branch="",+ remote_branch="",+ commits_since_local=0,+ last_remote_commit_at="",+ error=str(e),+ )+++def get_repo_release_info(repo_path: str) -> GitRepoReleaseInfo:+ try:+ repo = Repo(repo_path)+ if repo.bare:+ return GitRepoReleaseInfo(+ is_git_repo=False,+ is_remote=False,+ path=repo_path,+ author="",+ repo="",+ branch="",+ head=None,+ release=None,+ error=f"Repository at {repo_path} is bare and cannot be used.",+ )++ commit = repo.head.commit+ author = ""+ repo_name = ""+ is_remote = False++ try:+ if repo.remotes:+ author, repo_name = extract_author_repo(repo.remotes.origin.url)+ is_remote = bool(author and repo_name)+ except Exception:+ author = ""+ repo_name = ""+ is_remote = False++ branch = ""+ try:+ branch = repo.active_branch.name if repo.head.is_detached is False else ""+ except Exception:+ branch = ""+tag = ""+ short_tag = ""+ release_time = ""+ try:+ tag = repo.git.describe(tags=True)+ tag_split = tag.split('-')+ if len(tag_split) >= 3:+ short_tag = "-".join(tag_split[:-1])+ else:+ short_tag = tag- version = branch[0].upper() + " " + ( short_tag or commit_hash[:7] )+ tag_ref = next((t for t in repo.tags if t.name == short_tag), None)+ if tag_ref:+ release_commit = tag_ref.commit+ release_time = _format_git_timestamp(release_commit.committed_date)+ except Exception:+ tag = ""+ short_tag = ""+ release_time = ""- # Create the dictionary with collected information- git_info = {- "branch": branch,- "commit_hash": commit_hash,- "commit_time": commit_time,- "tag": tag,- "short_tag": short_tag,- "version": version- }+ version_prefix = branch[0].upper() if branch else "D"+ version = version_prefix + " " + (short_tag or commit.hexsha[:7])- return git_info+ return GitRepoReleaseInfo(+ is_git_repo=True,+ is_remote=is_remote,+ path=repo_path,+ author=author,+ repo=repo_name,+ branch=branch,+ head=GitHeadInfo(+ hash=commit.hexsha,+ short_hash=commit.hexsha[:7],+ message=str(commit.message).split("\n")[0][:200],+ author=str(commit.author),+ committed_at=_format_git_timestamp(commit.committed_date),+ authored_at=_format_git_timestamp(commit.authored_date),+ ),+ release=GitReleaseInfo(+ tag=tag,+ short_tag=short_tag,+ version=version,+ released_at=release_time,+ ),+ )+ except Exception as e:+ return GitRepoReleaseInfo(+ is_git_repo=False,+ is_remote=False,+ path=repo_path,+ author="",+ repo="",+ branch="",+ head=None,+ release=None,+ error=str(e),+ )+++def get_git_info():+ # Get the current working directory (assuming the repo is in the same folder as the script)+ repo_path = files.get_base_dir()++ state = get_repo_release_info(repo_path)+ if not state.is_git_repo:+ raise ValueError(state.error or f"Repository at {repo_path} is not usable.")++ return {+ "branch": state.branch,+ "commit_hash": state.head.hash if state.head else "",+ "commit_time": state.head.committed_at if state.head else "",+ "tag": state.release.tag if state.release else "",+ "short_tag": state.release.short_tag if state.release else "",+ "version": state.release.version if state.release else "",+ }def get_version():try:@@ -137,6 +419,28 @@ def clone_repo(url: str, dest: str, token: str | None = None):return Repo(dest)+def update_repo(repo_path: str) -> Repo:+ repo = Repo(repo_path)+ if repo.bare:+ raise ValueError(f"Repository at {repo_path} is bare and cannot be updated.")++ if repo.head.is_detached:+ raise ValueError("Repository HEAD is detached.")++ branch = repo.active_branch.name+ tracking_branch = repo.active_branch.tracking_branch()+ if tracking_branch is None:+ raise ValueError("Current branch has no tracking remote branch.")++ env = os.environ.copy()+ env['GIT_TERMINAL_PROMPT'] = '0'++ with repo.git.custom_environment(**env):+ repo.remotes[tracking_branch.remote_name].pull(branch)++ return repo++# Files to ignore when checking dirty status (A0 project metadata)A0_IGNORE_PATTERNS = {".a0proj", ".a0proj/"}diff --git a/helpers/plugins.py b/helpers/plugins.pyindex 57141f730..0cbefe187 100644--- a/helpers/plugins.py+++ b/helpers/plugins.py@@ -17,6 +17,7 @@ from typing import (from helpers import (files,+ git,notification,print_style,yaml as yaml_helper,@@ -88,6 +89,21 @@ class PluginListItem(BaseModel):has_license: bool = Falsehas_init_script: bool = Falsetoggle_state: ToggleState = "disabled"+ current_commit: str = ""+ current_commit_timestamp: str = ""+++class PluginUpdateInfo(BaseModel):+ name: str+ path: str+ display_name: str = ""+ commits_since_local: int = 0+ last_remote_commit_at: str = ""+ branch: str = ""+ remote_branch: str = ""+ is_git_repo: bool = False+ is_remote: bool = False+ error: str = ""@extension.extensible@@ -125,16 +141,19 @@ def get_plugins_list():def get_enhanced_plugins_list(- custom: bool = True, builtin: bool = True+ custom: bool = True, builtin: bool = True, plugin_names: list[str] | None = None) -> List[PluginListItem]:"""Discover plugins by directory convention. First root wins on ID conflict."""results = []+ allowed_names = set(plugin_names) if plugin_names else Nonedef load_plugins(root_path: str, is_custom: bool):for d in sorted(Path(root_path).iterdir(), key=lambda p: p.name):try:if not d.is_dir() or d.name.startswith("."):continue+ if allowed_names is not None and d.name not in allowed_names:+ continuemeta_file = str(d / META_FILE_NAME)if not files.exists(meta_file):continue@@ -145,6 +164,13 @@ def get_enhanced_plugins_list(has_license = files.exists(str(d / "LICENSE"))has_init_script = files.exists(str(d / "initialize.py"))toggle_state = get_toggle_state(d.name)+ current_commit = ""+ current_commit_timestamp = ""+ if is_custom:+ repo_info = git.get_repo_release_info(str(d))+ if repo_info.is_git_repo and repo_info.head:+ current_commit = repo_info.head.hash+ current_commit_timestamp = repo_info.head.committed_atresults.append(PluginListItem(name=d.name,@@ -163,6 +189,8 @@ def get_enhanced_plugins_list(has_license=has_license,has_init_script=has_init_script,toggle_state=toggle_state,+ current_commit=current_commit,+ current_commit_timestamp=current_commit_timestamp,))except Exception as e:@@ -176,6 +204,30 @@ def get_enhanced_plugins_list(return results+def get_custom_plugins_updates(plugin_names: list[str] | None = None) -> List[PluginUpdateInfo]:+ plugins = get_enhanced_plugins_list(custom=True, builtin=False, plugin_names=plugin_names)+ results: list[PluginUpdateInfo] = []++ for plugin in plugins:+ update = git.get_remote_commits_since_local(plugin.path)+ results.append(+ PluginUpdateInfo(+ name=plugin.name,+ path=plugin.path,+ display_name=plugin.display_name,+ commits_since_local=update.commits_since_local,+ last_remote_commit_at=update.last_remote_commit_at,+ branch=update.branch,+ remote_branch=update.remote_branch,+ is_git_repo=update.is_git_repo,+ is_remote=update.is_remote,+ error=update.error,+ )+ )++ return results++def get_plugin_meta(plugin_name: str):plugin_dir = find_plugin_dir(plugin_name)if not plugin_dir:diff --git a/plugins/_plugin_installer/api/plugin_install.py b/plugins/_plugin_installer/api/plugin_install.pyindex 5e21a0802..d051f684c 100644--- a/plugins/_plugin_installer/api/plugin_install.py+++ b/plugins/_plugin_installer/api/plugin_install.py@@ -7,6 +7,7 @@ from plugins._plugin_installer.helpers.install import (get_marketplace_index,install_from_git,install_uploaded_zip,+ update_from_git,)class PluginInstall(ApiHandler):@@ -20,6 +21,8 @@ class PluginInstall(ApiHandler):return self._install_zip(request)elif action == "install_git":return self._install_git(input)+ elif action == "update_plugin":+ return self._update_git(input)elif action == "fetch_index":return self._fetch_index(input)else:@@ -48,5 +51,8 @@ class PluginInstall(ApiHandler):return install_from_git(url=git_url, token=git_token, plugin_name=plugin_name)+ def _update_git(self, input: dict) -> dict:+ return update_from_git(input.get("plugin_name", ""))+def _fetch_index(self, input: dict) -> dict:return {"success": True, **get_marketplace_index()}diff --git a/plugins/_plugin_installer/helpers/install.py b/plugins/_plugin_installer/helpers/install.pyindex 087f24be5..231c6e7aa 100644--- a/plugins/_plugin_installer/helpers/install.py+++ b/plugins/_plugin_installer/helpers/install.py@@ -1,5 +1,6 @@from __future__ import annotations+from datetime import datetime, timezoneimport jsonimport osimport time@@ -10,7 +11,7 @@ import zipfilefrom pathlib import Pathfrom typing import Any-from helpers import files, print_style, plugins+from helpers import files, print_style, plugins, gitfrom helpers import yaml as yaml_helperfrom helpers.plugins import (META_FILE_NAME,@@ -192,6 +193,52 @@ def install_from_git(url: str, token: str | None = None, plugin_name: str = "")}+def update_from_git(plugin_name: str) -> dict:+ plugin_name = (plugin_name or "").strip()+ if not plugin_name:+ raise ValueError("Missing plugin_name")++ plugin_dir = plugins.find_plugin_dir(plugin_name)+ if not plugin_dir:+ raise ValueError("Plugin not found")++ custom_plugins_dir = files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR)+ if not files.is_in_dir(plugin_dir, custom_plugins_dir):+ raise ValueError("Only custom plugins can be updated")++ try:+ repo = git.update_repo(plugin_dir)+ meta = plugins.get_plugin_meta(plugin_name)+ except Exception as e:+ print_style.PrintStyle.error(f"Failed to update plugin: {e}")+ raise++ try:+ run_install_hook(plugin_name)+ except Exception as e:+ print_style.PrintStyle.error(+ f"Failed to run installation hook for {plugin_name}: {e}"+ )+ raise++ after_plugin_change([plugin_name])+ head = repo.head.commit++ return {+ "ok": True,+ "success": True,+ "plugin_name": plugin_name,+ "title": meta.title if meta else plugin_name,+ "path": files.deabsolute_path(plugin_dir),+ "current_commit": head.hexsha,+ "current_commit_timestamp": datetime.fromtimestamp(head.committed_date, timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),+ "version": getattr(meta, "version", "") or "",+ "branch": repo.active_branch.name if not repo.head.is_detached else "",+ "remote_url": git.strip_auth_from_url(repo.remotes.origin.url) if repo.remotes else "",+ "directory_name": Path(plugin_dir).name,+ }++def run_install_hook(plugin_name: str):return plugins.call_plugin_hook(plugin_name, "install")diff --git a/plugins/_plugin_installer/webui/install-detail.html b/plugins/_plugin_installer/webui/install-detail.htmlindex 3db815e05..f6a311ced 100644--- a/plugins/_plugin_installer/webui/install-detail.html+++ b/plugins/_plugin_installer/webui/install-detail.html@@ -25,12 +25,14 @@<div class="pi-hero-title-row"><div class="pi-hero-main"><h2 class="pi-hero-title" x-text="$store.pluginInstallStore.selectedPlugin.title || $store.pluginInstallStore.selectedPlugin.key"></h2>- <template x-if="$store.pluginInstallStore.selectedPlugin.installed">- <div class="pi-installed-badge-simple">- <span class="material-symbols-outlined">check_circle</span>- <span>Installed</span>- </div>- </template>+ <div class="pi-status-badges">+ <template x-if="$store.pluginInstallStore.selectedPlugin.installed">+ <span class="pi-card-installed-pill">Installed</span>+ </template>+ <template x-if="$store.pluginInstallStore.selectedPlugin.has_update">+ <span class="pi-card-update-pill">New version</span>+ </template>+ </div><div class="pi-hero-meta"><template x-if="$store.pluginInstallStore.selectedPlugin.author"><span class="pi-hero-author">@@ -133,6 +135,24 @@</template></button></template>+ <template x-if="$store.pluginInstallStore.selectedPlugin.installed && $store.pluginInstallStore.installedPluginInfo?.is_custom && $store.pluginInstallStore.selectedPlugin.has_update">+ <button type="button" class="pi-btn-install"+ @click="$store.pluginInstallStore.handleUpdatePlugin()"+ :disabled="$store.pluginInstallStore.loading">+ <template x-if="$store.pluginInstallStore.loading">+ <span class="pi-btn-loading">+ <span class="spinner"></span>+ <span x-text="$store.pluginInstallStore.loadingMessage || 'Installing...'"></span>+ </span>+ </template>+ <template x-if="!$store.pluginInstallStore.loading">+ <span class="material-symbols-outlined">system_update</span>+ </template>+ <template x-if="!$store.pluginInstallStore.loading">+ <span>Update</span>+ </template>+ </button>+ </template><template x-if="$store.pluginInstallStore.selectedPlugin.installed && $store.pluginInstallStore.installedPluginInfo?.is_custom"><button type="button" class="pi-btn-uninstall"@click="$confirmClick($event, () => $store.pluginInstallStore.handleDeletePlugin())"@@ -152,7 +172,7 @@<template x-if="$store.pluginInstallStore.selectedPlugin.discussion"><a :href="$store.pluginInstallStore.selectedPlugin.discussion" target="_blank" class="pi-btn-discussion"><span class="material-symbols-outlined">forum</span>- <span>Join Discussion</span>+ <span>Discussion</span></a></template></div>@@ -166,6 +186,51 @@class="pi-readme-content" x-html="$store.pluginInstallStore.readmeContent"></div></div>+ <div class="pi-version-section"+ x-show="$store.pluginInstallStore.getCurrentInstalledVersion() || $store.pluginInstallStore.getCurrentInstalledCommit() || $store.pluginInstallStore.getLatestMarketplaceVersion() || $store.pluginInstallStore.getLatestMarketplaceCommit()">+ <div class="pi-version-header">Version</div>+ <div class="pi-version-grid">+ <div class="pi-version-card"+ x-show="$store.pluginInstallStore.selectedPlugin.installed && ($store.pluginInstallStore.getCurrentInstalledVersion() || $store.pluginInstallStore.getCurrentInstalledCommit())">+ <div class="pi-version-label">Current</div>+ <div class="pi-version-name"+ x-text="$store.pluginInstallStore.getCurrentInstalledVersion() || 'Unknown version'"></div>+ <template x-if="$store.pluginInstallStore.getCurrentInstalledCommit() && $store.pluginInstallStore.getRepoCommitUrl($store.pluginInstallStore.selectedPlugin, $store.pluginInstallStore.getCurrentInstalledCommit())">+ <a class="pi-version-commit"+ :href="$store.pluginInstallStore.getRepoCommitUrl($store.pluginInstallStore.selectedPlugin, $store.pluginInstallStore.getCurrentInstalledCommit())"+ target="_blank"+ rel="noopener noreferrer"+ x-text="$store.pluginInstallStore.getCommitShortHash($store.pluginInstallStore.getCurrentInstalledCommit())"></a>+ </template>+ <template x-if="!($store.pluginInstallStore.getCurrentInstalledCommit() && $store.pluginInstallStore.getRepoCommitUrl($store.pluginInstallStore.selectedPlugin, $store.pluginInstallStore.getCurrentInstalledCommit()))">+ <div class="pi-version-commit"+ x-text="$store.pluginInstallStore.getCommitShortHash($store.pluginInstallStore.getCurrentInstalledCommit()) || 'Unknown'"></div>+ </template>+ <div class="pi-version-time"+ x-text="$store.pluginInstallStore.formatUserLocaleDateTime($store.pluginInstallStore.getCurrentInstalledCommitTimestamp()) || 'Timestamp unavailable'"></div>+ </div>+ <div class="pi-version-card"+ x-show="$store.pluginInstallStore.getLatestMarketplaceVersion() || $store.pluginInstallStore.getLatestMarketplaceCommit()">+ <div class="pi-version-label">Latest</div>+ <div class="pi-version-name"+ x-text="$store.pluginInstallStore.getLatestMarketplaceVersion() || 'Unknown version'"></div>+ <template x-if="$store.pluginInstallStore.getLatestMarketplaceCommit() && $store.pluginInstallStore.getRepoCommitUrl($store.pluginInstallStore.selectedPlugin, $store.pluginInstallStore.getLatestMarketplaceCommit())">+ <a class="pi-version-commit"+ :href="$store.pluginInstallStore.getRepoCommitUrl($store.pluginInstallStore.selectedPlugin, $store.pluginInstallStore.getLatestMarketplaceCommit())"+ target="_blank"+ rel="noopener noreferrer"+ x-text="$store.pluginInstallStore.getCommitShortHash($store.pluginInstallStore.getLatestMarketplaceCommit())"></a>+ </template>+ <template x-if="!($store.pluginInstallStore.getLatestMarketplaceCommit() && $store.pluginInstallStore.getRepoCommitUrl($store.pluginInstallStore.selectedPlugin, $store.pluginInstallStore.getLatestMarketplaceCommit()))">+ <div class="pi-version-commit"+ x-text="$store.pluginInstallStore.getCommitShortHash($store.pluginInstallStore.getLatestMarketplaceCommit()) || 'Unknown'"></div>+ </template>+ <div class="pi-version-time"+ x-text="$store.pluginInstallStore.formatUserLocaleDateTime($store.pluginInstallStore.getLatestMarketplaceCommitTimestamp()) || 'Timestamp unavailable'"></div>+ </div>+ </div>+ </div>+<div class="pi-developer-section"><div class="pi-developer-header">Plugin Code</div><div class="pi-developer-links">@@ -256,6 +321,13 @@row-gap: var(--spacing-xxs);}+ .pi-status-badges {+ display: flex;+ flex-wrap: wrap;+ gap: 0.85rem;+ margin: var(--spacing-xs) 0;+ }+.pi-hero-title {margin: 0;font-size: 1.75rem;@@ -327,18 +399,16 @@gap: 0.4rem;}- .pi-installed-badge-simple {- display: inline-flex;- align-items: center;- gap: 0.35rem;- font-size: 0.9rem;- font-weight: 600;- color: #22c55e;- margin: var(--spacing-xs) 0;+ .pi-status-badges .pi-card-installed-pill {+ position: static;+ top: auto;+ right: auto;}- .pi-installed-badge-simple .material-symbols-outlined {- font-size: 1.1rem;+ .pi-status-badges .pi-card-update-pill {+ position: static;+ top: auto;+ right: auto;}.pi-tag {@@ -481,6 +551,66 @@border-top: 1px solid var(--color-border);}+ .pi-version-section {+ margin-bottom: 1.5rem;+ padding-top: 1.5rem;+ border-top: 1px solid var(--color-border);+ }++ .pi-version-header {+ font-size: 0.85rem;+ font-weight: 600;+ color: var(--color-text-muted);+ margin-bottom: 0.75rem;+ }++ .pi-version-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: 0.75rem;+ }++ .pi-version-card {+ display: flex;+ flex-direction: column;+ gap: 0.3rem;+ padding: 0.9rem 1rem;+ border: 1px solid var(--color-border);+ border-radius: 10px;+ }++ .pi-version-label {+ font-size: 0.78rem;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--color-text-muted);+ }++ .pi-version-name {+ font-size: 1rem;+ font-weight: 700;+ color: var(--color-text-primary);+ line-height: 1.35;+ }++ .pi-version-commit {+ font-size: 0.92rem;+ font-weight: 600;+ color: var(--color-text-secondary);+ text-decoration: none;+ }++ a.pi-version-commit:hover {+ color: var(--color-highlight);+ }++ .pi-version-time {+ font-size: 0.85rem;+ color: var(--color-text-secondary);+ line-height: 1.4;+ }+.pi-screenshots-header {font-size: 0.85rem;font-weight: 600;diff --git a/plugins/_plugin_installer/webui/install-index.html b/plugins/_plugin_installer/webui/install-index.htmlindex 3c92ffd8e..5bf153f36 100644--- a/plugins/_plugin_installer/webui/install-index.html+++ b/plugins/_plugin_installer/webui/install-index.html@@ -46,7 +46,10 @@<template x-for="filter in $store.pluginInstallStore.browseFilters" :key="filter.key"><button type="button"class="pi-filter-chip"- :class="{ active: $store.pluginInstallStore.browseFilter === filter.key }"+ :class="{+ active: $store.pluginInstallStore.browseFilter === filter.key,+ 'pi-filter-chip-update': filter.key === 'update' && filter.count > 0+ }"@click="$store.pluginInstallStore.setBrowseFilter(filter.key)"><span x-text="filter.label"></span><span class="pi-filter-count" x-text="filter.count"></span>@@ -77,6 +80,10 @@<template x-if="plugin.installed"><span class="pi-card-installed-pill">Installed</span></template>++ <template x-if="plugin.has_update">+ <span class="pi-card-update-pill" :class="{ 'pi-card-update-pill-offset': plugin.installed }">New version</span>+ </template></div><div class="pi-card-body">@@ -294,6 +301,41 @@color: var(--color-text-primary);}+ .pi-filter-chip-update {+ border-color: rgba(59, 130, 246, 0.22);+ color: #93c5fd;+ }++ .pi-filter-chip-update:hover,+ .pi-filter-chip-update.active {+ border-color: rgba(59, 130, 246, 0.38);+ background: rgba(59, 130, 246, 0.12);+ color: #bfdbfe;+ }++ .pi-filter-chip-update .pi-filter-count {+ background: rgba(59, 130, 246, 0.16);+ color: #bfdbfe;+ }++ body.light-mode .pi-filter-chip-update {+ border-color: rgba(37, 99, 235, 0.35);+ background: rgba(37, 99, 235, 0.08);+ color: #1d4ed8;+ }++ body.light-mode .pi-filter-chip-update:hover,+ body.light-mode .pi-filter-chip-update.active {+ border-color: rgba(37, 99, 235, 0.5);+ background: rgba(37, 99, 235, 0.14);+ color: #1e40af;+ }++ body.light-mode .pi-filter-chip-update .pi-filter-count {+ background: rgba(37, 99, 235, 0.18);+ color: #1e3a8a;+ }+.pi-filter-count {padding: 0.12rem 0.4rem;border-radius: 0.5rem;@@ -369,7 +411,7 @@height: 148px;padding: 0.5rem;background:- radial-gradient(circle at top, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0)),+ radial-gradient(circle at top, #6b728089, var(--color-panel)),var(--color-panel);border-bottom: 1px solid var(--color-border);}@@ -397,6 +439,32 @@font-weight: 700;}+ body.light-mode .pi-card-installed-pill {+ background: rgba(34, 197, 94, 0.22);+ color: #166534;+ }++ .pi-card-update-pill {+ position: absolute;+ top: 0.75rem;+ right: 0.75rem;+ padding: 0.24rem 0.5rem;+ border-radius: 0.5rem;+ background: rgba(59, 130, 246, 0.16);+ color: #60a5fa;+ font-size: 0.72rem;+ font-weight: 700;+ }++ body.light-mode .pi-card-update-pill {+ background: rgba(59, 130, 246, 0.2);+ color: #1d4ed8;+ }++ .pi-card-update-pill-offset {+ top: 2.35rem;+ }+.pi-card-body {flex: 1;display: flex;diff --git a/plugins/_plugin_installer/webui/pluginInstallStore.js b/plugins/_plugin_installer/webui/pluginInstallStore.jsindex 8c6b572e0..eab4dcf44 100644--- a/plugins/_plugin_installer/webui/pluginInstallStore.js+++ b/plugins/_plugin_installer/webui/pluginInstallStore.js@@ -39,6 +39,7 @@ const model = {// Index stateindex: { authors: {}, plugins: {} },installedPlugins: [],+ installedPluginDetails: {},search: "",page: 1,sortBy: "stars",@@ -97,6 +98,7 @@ const model = {_matchesBrowseFilter(plugin, filterKey) {if (!filterKey || filterKey === "all") return true;if (filterKey === "installed") return !!plugin?.installed;+ if (filterKey === "update") return !!plugin?.has_update;if (filterKey === "popular") return (plugin?.stars || 0) > 0;if (filterKey.startsWith("tag:")) {return this._pluginPrimaryTag(plugin) === filterKey.slice(4);@@ -104,6 +106,28 @@ const model = {return false;},+ _compareTimestamp(a, b) {+ const aTime = a ? Date.parse(a) : NaN;+ const bTime = b ? Date.parse(b) : NaN;+ if (Number.isNaN(aTime) || Number.isNaN(bTime)) return 0;+ if (aTime === bTime) return 0;+ return aTime > bTime ? 1 : -1;+ },++ _hasMarketplaceUpdate(indexPlugin, installedPlugin) {+ const latestCommit = (indexPlugin?.commit || "").trim();+ const currentCommit = (installedPlugin?.current_commit || "").trim();+ if (!latestCommit || !currentCommit) return false;+ if (latestCommit === currentCommit) return false;++ const latestTimestamp = indexPlugin?.updated || "";+ const currentTimestamp = installedPlugin?.current_commit_timestamp || "";+ const timestampComparison = this._compareTimestamp(latestTimestamp, currentTimestamp);+ if (timestampComparison !== 0) return timestampComparison > 0;++ return true;+ },+// ── ZIP Install ──────────────────────────────handleFileUpload(event) {@@ -219,6 +243,13 @@ const model = {this.index = data.index;this.installedPlugins = data.installed_plugins || [];+ const installedResponse = await api.callJsonApi("plugins_list", {+ filter: { custom: true, builtin: false, search: "" },+ });+ const installedList = Array.isArray(installedResponse.plugins) ? installedResponse.plugins : [];+ this.installedPluginDetails = Object.fromEntries(+ installedList.map((plugin) => [plugin.name, plugin])+ );this.page = 1;} catch (e) {const message = e instanceof Error ? e.message : String(e);@@ -231,24 +262,39 @@ const model = {get pluginsList() {if (!this.index?.plugins) return [];- return Object.entries(this.index.plugins).map(([key, val]) => ({- key,- ...val,- installed: this.installedPlugins.includes(key),- }));+ return Object.entries(this.index.plugins).map(([key, val]) => {+ const installedPlugin = this.installedPluginDetails[key] || null;+ const installed = this.installedPlugins.some((pluginKey) => pluginKey === key);+ const plugin = {+ key,+ ...val,+ commit: val?.commit || val?.latest_commit || "",+ updated: val?.updated || val?.latest_commit_timestamp || "",+ version: val?.version || "",+ installed,+ };++ return {+ ...plugin,+ current_commit: installedPlugin?.current_commit || "",+ current_commit_timestamp: installedPlugin?.current_commit_timestamp || "",+ has_update: this._hasMarketplaceUpdate(plugin, installedPlugin),+ };+ });},get browseFilters() {const plugins = this.pluginsList;const filters = [{ key: "all", label: "All", count: plugins.length }];- if (!plugins.length) return filters;-const installedCount = plugins.filter((plugin) => plugin.installed).length;if (installedCount) {filters.push({ key: "installed", label: "Installed", count: installedCount });}+ const updateCount = plugins.filter((plugin) => plugin.has_update).length;+ filters.push({ key: "update", label: "Update", count: updateCount });+const popularCount = plugins.filter((plugin) => (plugin.stars || 0) > 0).length;if (popularCount) {filters.push({ key: "popular", label: "Popular", count: popularCount });@@ -397,7 +443,7 @@ const model = {try {this.loading = true;- this.loadingMessage = `Installing ${plugin.title || plugin.key}...`;+ this.loadingMessage = "Installing";const data = await api.callJsonApi(PLUGIN_API, {action: "install_git",@@ -411,7 +457,7 @@ const model = {}const installedKey = plugin.key || data.plugin_name;- if (installedKey && !this.installedPlugins.includes(installedKey)) {+ if (installedKey && !this.installedPlugins.some((pluginKey) => pluginKey === installedKey)) {this.installedPlugins = [...this.installedPlugins, installedKey];}@@ -436,6 +482,25 @@ const model = {}},+ async _refreshSelectedPluginState(pluginKey) {+ await this.fetchInstalledPluginInfo(pluginKey);++ const latestInstalled = this.installedPluginInfo || null;+ const currentSelectedPlugin = this.selectedPlugin ? Object.assign({}, this.selectedPlugin) : null;+ const indexPlugin = this.pluginsList.find((plugin) => plugin.key === pluginKey) || currentSelectedPlugin;+ if (!indexPlugin) return;++ this.selectedPlugin = {+ ...indexPlugin,+ name: pluginKey || indexPlugin["name"] || "",+ installed: true,+ current_commit: latestInstalled?.["current_commit"] || indexPlugin["current_commit"] || "",+ current_commit_timestamp: latestInstalled?.["current_commit_timestamp"] || indexPlugin["current_commit_timestamp"] || "",+ has_update: this._hasMarketplaceUpdate(indexPlugin, latestInstalled),+ };+ this.detailThumbnailUrl = this.getThumbnailUrl(this.selectedPlugin);+ },+// ── Installed Plugin Info ─────────────────────async fetchInstalledPluginInfo(pluginName) {@@ -490,11 +555,11 @@ const model = {this.loadingMessage = "Uninstalling plugin...";await pluginListStore.deletePlugin(this.installedPluginInfo);- const currentPlugin = this.selectedPlugin;+ const currentPlugin = this.selectedPlugin ? Object.assign({}, this.selectedPlugin) : null;if (currentPlugin) {this.selectedPlugin = { ...currentPlugin, installed: false };this.installedPlugins = this.installedPlugins.filter(- (key) => key !== currentPlugin.key+ (key) => key !== currentPlugin["key"]);}this.installedPluginInfo = null;@@ -509,6 +574,118 @@ const model = {return `https://github.com/agent0ai/a0-plugins/tree/main/plugins/${pluginKey}`;},+ getCommitShortHash(commitHash) {+ if (!commitHash || typeof commitHash !== "string") return "";+ return commitHash.slice(0, 7);+ },++ formatUserLocaleDateTime(value) {+ if (!value || typeof value !== "string") return "";++ const normalizedValue = /t/i.test(value) ? value : value.replace(" ", "T");+ const date = new Date(normalizedValue);+ if (Number.isNaN(date.getTime())) return value;++ return new Intl.DateTimeFormat(undefined, {+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ }).format(date);+ },++ getRepoCommitUrl(plugin, commitHash) {+ const githubUrl = (plugin?.github || "").trim().replace(/\.git$/i, "");+ if (!githubUrl || !commitHash) return "";+ return `${githubUrl}/commit/${commitHash}`;+ },++ getCurrentInstalledCommit() {+ return this.installedPluginInfo?.["current_commit"] || this.selectedPlugin?.["current_commit"] || "";+ },++ getCurrentInstalledVersion() {+ return this.installedPluginInfo?.["version"] || "";+ },++ getCurrentInstalledCommitTimestamp() {+ return this.installedPluginInfo?.["current_commit_timestamp"] || this.selectedPlugin?.["current_commit_timestamp"] || "";+ },++ getLatestMarketplaceVersion() {+ return this.selectedPlugin?.["version"] || "";+ },++ getLatestMarketplaceCommit() {+ return this.selectedPlugin?.["commit"] || "";+ },++ getLatestMarketplaceCommitTimestamp() {+ return this.selectedPlugin?.["updated"] || "";+ },++ async handleUpdatePlugin() {+ const selectedPlugin = this["selectedPlugin"];+ const pluginRecord = selectedPlugin && typeof selectedPlugin === "object" ? selectedPlugin : {};+ const pluginKey = pluginRecord["key"] || pluginRecord["name"] || this.installedPluginInfo?.name || "";+ if (!pluginKey) {+ void toastFrontendError("Plugin name is missing", "Plugin Installer");+ return;+ }++ const confirmed = await showConfirmDialog({+ ...SECURITY_WARNING,+ extensionContext: {+ kind: "marketplace_plugin_install_warning",+ source: "plugin_installer",+ pluginKey,+ pluginTitle: pluginRecord["title"] || pluginKey,+ gitUrl: pluginRecord["github"] || "",+ },+ });+ if (!confirmed) return;++ try {+ this.loading = true;+ this.loadingMessage = "Updating";++ const data = await api.callJsonApi(PLUGIN_API, {+ action: "update_plugin",+ plugin_name: pluginKey,+ });++ if (!(data?.ok && data?.success)) {+ void toastFrontendError(data?.error || "Update failed", "Plugin Installer");+ return;+ }++ await this.fetchIndex();++ const installedPluginsSource = this["installedPlugins"];+ const installedPlugins = Array.isArray(installedPluginsSource) ? Array.from(installedPluginsSource) : [];+ if (!installedPlugins.some((installedKey) => installedKey === pluginKey)) {+ installedPlugins.push(String(pluginKey));+ Reflect.set(this, "installedPlugins", installedPlugins);+ }++ await this._refreshSelectedPluginState(pluginKey);+ this.refreshPluginList();++ toastFrontendSuccess(+ `Plugin "${data.title || data.plugin_name}" updated`,+ "Plugin Installer"+ );+ } catch (e) {+ const message = e instanceof Error ? e.message : String(e);+ void toastFrontendError(`Update error: ${message}`, "Plugin Installer");+ } finally {+ this.loading = false;+ this.loadingMessage = "";+ }+ },+getThumbnailUrl(plugin) {if (!plugin) return null;if (plugin.thumbnail && typeof plugin.thumbnail === "string") return plugin.thumbnail;@@ -522,8 +699,9 @@ const model = {openScreenshot(url) {if (!url) return;+ const selectedPlugin = this.selectedPlugin || null;imageViewerStore.open(url, {- name: this.selectedPlugin?.title || this.selectedPlugin?.key || "Plugin screenshot",+ name: selectedPlugin?.["title"] || selectedPlugin?.["key"] || "Plugin screenshot",});},