Agent Zero AI framework
plugins - frontend PoC
frdel3918133cbf31
diff --git a/jsconfig.json b/jsconfig.jsonindex 7efa80e95..91123b807 100644--- a/jsconfig.json+++ b/jsconfig.json@@ -2,7 +2,9 @@"compilerOptions": {"baseUrl": ".","paths": {- "*": ["webui/*"]+ "*": ["webui/*"],+ "/plugins/*": ["plugins/*"],+ "/usr/plugins/*": ["usr/plugins/*"]}},"include": ["webui/**/*.js"]diff --git a/plugins/README.md b/plugins/README.mdindex cb697e84e..a664f6b40 100644--- a/plugins/README.md+++ b/plugins/README.md@@ -37,9 +37,11 @@ Components without the meta tag (e.g. modals, dashboards) are standalone and notResolution flow:+TODO update:ú+1. The backend parses `<meta name="plugin-target">` from each component HTML at scan time.2. `/plugins_resolve` returns component URLs with their target selectors.-3. `plugins.js` (loaded globally) creates `<x-component>` elements at the declared target selectors.+3. TODO REM: `plugins.js` (loaded globally) creates `<x-component>` elements at the declared target selectors.4. The standard `components.js` MutationObserver handles loading automatically.5. A MutationObserver in `plugins.js` retries for targets that appear after initial page render.diff --git a/plugins/memory/extensions/frontend/sidebar.quick_actions.dropdown/memory-entry.html b/plugins/memory/extensions/frontend/sidebar.quick_actions.dropdown/memory-entry.htmldeleted file mode 100644index ea3d38b33..000000000--- a/plugins/memory/extensions/frontend/sidebar.quick_actions.dropdown/memory-entry.html+++ /dev/null@@ -1,14 +0,0 @@-<html>--<head>- <meta name="plugin-target" content=".quick-actions-dropdown">-</head>--<body>- <button class="dropdown-item" @click="openModal('../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html'); dropdownOpen = false">- <span class="material-symbols-outlined">psychology</span>- <span>Memories</span>- </button>-</body>--</html>diff --git a/plugins/memory/extensions/webui/sidebar-quick-actions-main-2/memory-entry.html b/plugins/memory/extensions/webui/sidebar-quick-actions-main-2/memory-entry.htmlnew file mode 100644index 000000000..779cf10c6--- /dev/null+++ b/plugins/memory/extensions/webui/sidebar-quick-actions-main-2/memory-entry.html@@ -0,0 +1,19 @@+<!-- <html>++<head>+ <meta name="plugin-target" content=".quick-actions-dropdown">+</head>++<body>+ <button class="dropdown-item" @click="openModal('../plugins/memory/webui/memory-dashboard.html'); dropdownOpen = false">+ <span class="material-symbols-outlined">psychology</span>+ <span>Memories</span>+ </button>+</body>++</html> -->++ <!-- Memory -->+ <button class="config-button" id="memory-dash" @click="openModal('../plugins/memory/webui/memory-dashboard.html')" title="Memory">+ <span class="material-symbols-outlined">psychology</span>+ </button>diff --git a/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js b/plugins/memory/webui/memory-dashboard-store.jssimilarity index 99%rename from plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.jsrename to plugins/memory/webui/memory-dashboard-store.jsindex f1c6af5f8..d2b61cafa 100644--- a/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js+++ b/plugins/memory/webui/memory-dashboard-store.js@@ -54,7 +54,7 @@ const memoryDashboardStore = {pollingEnabled: false,async openModal() {- await openModal("../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html");+ await openModal("../plugins/memory/webui/memory-dashboard.html");},init() {@@ -449,7 +449,7 @@ ${memory.content_full}this.editMode = false;this.editMemoryBackup = null;// Use global modal system- openModal("../plugins/memory/extensions/frontend/memory_dashboard/memory-detail-modal.html");+ openModal("../plugins/memory/webui/memory-detail-modal.html");},closeMemoryDetails() {diff --git a/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html b/plugins/memory/webui/memory-dashboard.htmlsimilarity index 99%rename from plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.htmlrename to plugins/memory/webui/memory-dashboard.htmlindex c58cfaca5..8cc6a7095 100644--- a/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html+++ b/plugins/memory/webui/memory-dashboard.html@@ -3,7 +3,7 @@<head><title>Memory Dashboard</title><script type="module">- import { store } from "/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js";+ import { store } from "/plugins/memory/webui/memory-dashboard-store.js";</script></head>diff --git a/plugins/memory/extensions/frontend/memory_dashboard/memory-detail-modal.html b/plugins/memory/webui/memory-detail-modal.htmlsimilarity index 100%rename from plugins/memory/extensions/frontend/memory_dashboard/memory-detail-modal.htmlrename to plugins/memory/webui/memory-detail-modal.htmldiff --git a/python/api/banners.py b/python/api/banners.pyindex 88b171b8e..f20e02ea1 100644--- a/python/api/banners.py+++ b/python/api/banners.py@@ -17,6 +17,3 @@ class GetBanners(ApiHandler):return {"banners": banners}- @classmethod- def get_methods(cls) -> list[str]:- return ["POST"]diff --git a/python/api/load_webui_extensions.py b/python/api/load_webui_extensions.pynew file mode 100644index 000000000..7c7c44fa5--- /dev/null+++ b/python/api/load_webui_extensions.py@@ -0,0 +1,19 @@+from python.helpers.api import ApiHandler, Request, Response+from python.helpers import plugins+++class LoadWebuiExtensions(ApiHandler):+ """+ API endpoint for Welcome Screen banners.+ Add checks as extension scripts in python/extensions/banners/ or usr/extensions/banners/+ """++ async def process(self, input: dict, request: Request) -> dict | Response:+ extension_point = input.get("extension_point", [])++ if not extension_point:+ return Response(status=400, response="Missing extension_point")++ exts = plugins.get_webui_extensions(extension_point)++ return {"extensions": exts or []}diff --git a/python/api/plugins_resolve.py b/python/api/plugins_resolve.pydeleted file mode 100644index dae93af62..000000000--- a/python/api/plugins_resolve.py+++ /dev/null@@ -1,18 +0,0 @@-from python.helpers.api import ApiHandler, Request, Response-from python.helpers import plugins---class PluginsResolve(ApiHandler):- """- Return all injectable plugin frontend components.- Each plugin's extensions/frontend/**/*.html files are returned.- The components themselves declare their injection target via <meta> tags.- """-- @classmethod- def get_methods(cls):- return ["POST"]-- async def process(self, input: dict, request: Request) -> dict | Response:- data = plugins.get_frontend_components()- return {"ok": True, "data": data}diff --git a/python/helpers/plugins.py b/python/helpers/plugins.pyindex 3cff77e0a..bb33f8998 100644--- a/python/helpers/plugins.py+++ b/python/helpers/plugins.py@@ -5,7 +5,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Dict, List, Optional-from python.helpers import files+from python.helpers import files, print_style# Extracts target selector from <meta name="plugin-target" content="...">_META_TARGET_RE = re.compile(@@ -62,8 +62,8 @@ def get_plugin_paths(*subpaths: str) -> List[str]:Resolve existing directories under each plugin matching subpaths.Example:- get_plugin_paths("extensions", "backend", "monologue_end")- -> ["/abs/plugins/memory/extensions/backend/monologue_end", ...]+ get_plugin_paths("extensions", "python", "monologue_end")+ -> ["/abs/plugins/memory/extensions/python/monologue_end", ...]"""sub = "/".join(subpaths) if subpaths else ""paths: List[str] = []@@ -74,32 +74,21 @@ def get_plugin_paths(*subpaths: str) -> List[str]:return paths-def get_frontend_components() -> List[Dict[str, Any]]:- """- Return all injectable plugin frontend components.- Convention: plugins/*/extensions/frontend/**/*.html- The backend reads each file to extract the optional- <meta name="plugin-target" content=".css-selector"> tag so the- frontend never needs to fetch component HTML just to discover targets.- """+def get_webui_extensions(extension_point:str) -> List[Dict[str, Any]]:entries: List[Dict[str, Any]] = []for plugin in list_plugins():- frontend_dir = plugin.path / "extensions" / "frontend"+ frontend_dir = plugin.path / "extensions" / "webui" / extension_pointif not frontend_dir.is_dir():continuefor html_file in sorted(frontend_dir.rglob("*.html"), key=lambda p: p.name):- rel_path = html_file.relative_to(plugin.path).as_posix()- entry: Dict[str, Any] = {- "plugin_id": plugin.id,- "component_url": f"/plugins/{plugin.id}/{rel_path}",- }- # Extract injection target from meta tag (if present)try:- content = html_file.read_text(encoding="utf-8")- m = _META_TARGET_RE.search(content)- if m:- entry["target"] = m.group(1)+ rel_path = html_file.relative_to(plugin.path).as_posix()+ entry: Dict[str, Any] = {+ "plugin_id": plugin.id,+ "component_url": f"{plugin.path}/{rel_path}",+ "html": html_file.read_text(encoding="utf-8"),+ }+ entries.append(entry)except Exception:- pass- entries.append(entry)+ print_style.PrintStyle.error(f"Failed to load frontend extension file {html_file}")return entriesdiff --git a/python/helpers/skills.py b/python/helpers/skills.pyindex 9f8f25458..e9f6aca14 100644--- a/python/helpers/skills.py+++ b/python/helpers/skills.py@@ -54,13 +54,21 @@ def get_skill_roots(projects = files.find_existing_paths_by_pattern("usr/projects/*/.a0proj/skills") # projectsusr_agents = files.find_existing_paths_by_pattern("usr/agents/*/skills") # agentsagents = files.find_existing_paths_by_pattern("agents/*/skills") # agents+ plugins = files.find_existing_paths_by_pattern("plugins/*/skills") # plugins+ usr_plugins = files.find_existing_paths_by_pattern("usr/plugins/*/skills") # plugins+ plugins_agents = files.find_existing_paths_by_pattern("plugins/*/agents/*/skills") # agents in plugins+ usr_plugins_agents = files.find_existing_paths_by_pattern("usr/plugins/*/agents/*/skills") # agents in pluginspaths = [files.get_abs_path("skills"),files.get_abs_path("usr/skills"),*project_agents,*projects,*usr_agents,- *agents+ *agents,+ *plugins,+ *usr_plugins,+ *plugins_agents,+ *usr_plugins_agents,]return pathsdiff --git a/run_ui.py b/run_ui.pyindex bf8d63d94..a9bf51111 100644--- a/run_ui.py+++ b/run_ui.py@@ -260,7 +260,7 @@ async def serve_plugin_asset(plugin_id, asset_path):plugin_root = plugin.path.resolve()# Security: ensure the resolved path is within the plugin directory- if not str(asset_file).startswith(str(plugin_root) + os.sep) and str(asset_file) != str(plugin_root):+ if not files.is_in_dir(str(asset_file), str(plugin_root)):return Response("Access denied", 403)if not asset_file.is_file():@@ -494,7 +494,7 @@ def run():handlers = load_classes_from_folder("python/api", "*.py", ApiHandler)for handler in handlers:- register_api_handler(webapp, handler)+ register_api_handler(webapp, handler, url_prefix="/api")# Load API handlers from plugins (prefixed with /plugins/{plugin_id}/)from python.helpers import plugins@@ -507,9 +507,7 @@ def run():plugin_handlers = load_classes_from_folder(str(api_path), "*.py", ApiHandler)for handler in plugin_handlers:# prefixed route for explicit namespacing- register_api_handler(webapp, handler, url_prefix=f"/plugins/{plugin.id}")- # bare route so callers don't need to know the plugin prefix- register_api_handler(webapp, handler)+ register_api_handler(webapp, handler, url_prefix=f"/api/plugins/{plugin.id}")handlers_by_namespace = _build_websocket_handlers_by_namespace(socketio_server, lock)configure_websocket_namespaces(diff --git a/webui/components/settings/a2a/a2a-connection.html b/webui/components/settings/a2a/a2a-connection.htmlindex 9436f0c85..9a3b24aaf 100644--- a/webui/components/settings/a2a/a2a-connection.html+++ b/webui/components/settings/a2a/a2a-connection.html@@ -58,7 +58,7 @@// Fetch and populate projectsconst projectSelect = document.getElementById('a2a-project-select');try {- const response = await fetch('/projects', {+ const response = await fetchApi('/projects', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ action: 'list' })diff --git a/webui/components/settings/agent/memory.html b/webui/components/settings/agent/memory.htmlindex 8b30b42ca..9efa1f068 100644--- a/webui/components/settings/agent/memory.html+++ b/webui/components/settings/agent/memory.html@@ -34,7 +34,7 @@<div class="field-control"><buttonclass="btn btn-field"- @click="openModal('../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html');"+ @click="openModal('../plugins/memory/webui/memory-dashboard.html');">Open Dashboard</button>diff --git a/webui/components/settings/external/api-examples.html b/webui/components/settings/external/api-examples.htmlindex e2eeed79e..c403a6297 100644--- a/webui/components/settings/external/api-examples.html+++ b/webui/components/settings/external/api-examples.html@@ -209,7 +209,7 @@const basicExample = `// Basic message exampleasync function sendMessage() {try {- const response = await fetch('${url}/api_message', {+ const response = await fetch('${url}/api/api_message', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -249,7 +249,7 @@ sendMessage().then(result => {const continuationExample = `// Continue conversation exampleasync function continueConversation(contextId) {try {- const response = await fetch('${url}/api_message', {+ const response = await fetch('${url}/api/api_message', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -296,7 +296,7 @@ async function sendWithAttachment() {const textContent = "Hello World from attachment!";const base64Content = btoa(textContent);- const response = await fetch('${url}/api_message', {+ const response = await fetch('${url}/api/api_message', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -342,7 +342,7 @@ async function getLogsGET(contextId, length = 50) {length: length.toString()});- const response = await fetch('${url}/api_log_get?' + params, {+ const response = await fetch('${url}/api/api_log_get?' + params, {method: 'GET',headers: {'X-API-KEY': '${token}'@@ -374,7 +374,7 @@ getLogsGET('ctx_abc123', 20);`;const logPostExample = `// Get logs using POST requestasync function getLogsPOST(contextId, length = 50) {try {- const response = await fetch('${url}/api_log_get', {+ const response = await fetch('${url}/api/api_log_get', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -415,7 +415,7 @@ getLogsPOST('ctx_abc123', 10);`;const terminateExample = `// Basic terminate chat functionasync function terminateChat(contextId) {try {- const response = await fetch('${url}/api_terminate_chat', {+ const response = await fetch('${url}/api/api_terminate_chat', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -469,7 +469,7 @@ simpleWorkflow();`;const resetExample = `// Basic reset chat functionasync function resetChat(contextId) {try {- const response = await fetch('${url}/api_reset_chat', {+ const response = await fetch('${url}/api/api_reset_chat', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -511,7 +511,7 @@ async function resetAndContinue() {console.log('Chat reset, starting fresh conversation...');// Continue with same context_id but fresh history- const response = await fetch('${url}/api_message', {+ const response = await fetch('${url}/api/api_message', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -536,7 +536,7 @@ resetAndContinue();`;const filesGetExample = `// Basic file retrievalasync function getFiles(filePaths) {try {- const response = await fetch('${url}/api_files_get', {+ const response = await fetch('${url}/api/api_files_get', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -584,7 +584,7 @@ getFiles(filePaths);// Example 2: Complete attachment workflowasync function attachmentWorkflow() {// Step 1: Send message with attachments- const messageResponse = await fetch('${url}/api_message', {+ const messageResponse = await fetch('${url}/api/api_message', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -621,7 +621,7 @@ attachmentWorkflow();`;async function sendMessageWithProject() {try {// First message - activate project- const response = await fetch('${url}/api_message', {+ const response = await fetch('${url}/api/api_message', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -641,7 +641,7 @@ async function sendMessageWithProject() {console.log('Response:', data.response);// Continue conversation - project already set- const followUp = await fetch('${url}/api_message', {+ const followUp = await fetch('${url}/api/api_message', {method: 'POST',headers: {'Content-Type': 'application/json',diff --git a/webui/components/settings/mcp/server/example.html b/webui/components/settings/mcp/server/example.htmlindex 2f608b3d0..52f54f6e3 100644--- a/webui/components/settings/mcp/server/example.html+++ b/webui/components/settings/mcp/server/example.html@@ -58,7 +58,7 @@// Fetch and populate projectsconst projectSelect = document.getElementById('mcp-project-select');try {- const response = await fetch('/projects', {+ const response = await fetchApi('/projects', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ action: 'list' })diff --git a/webui/components/sidebar/top-section/quick-actions.html b/webui/components/sidebar/top-section/quick-actions.htmlindex 1d7a26b81..8da1cd21c 100644--- a/webui/components/sidebar/top-section/quick-actions.html+++ b/webui/components/sidebar/top-section/quick-actions.html@@ -11,26 +11,38 @@<body><div class="wrapper" x-data="{ dropdownOpen: false }" @click.outside="dropdownOpen = false" @keydown.escape.window="dropdownOpen = false" x-init="$watch('dropdownOpen', v => v && $store.sidebar.updateDropdownPosition($el))"><div id="quick-actions">++ <x-extension id="sidebar-quick-actions-main-start"></x-extension>+<!-- Dashboard --><button class="config-button" id="dashboard" @click="deselectChat()" title="Dashboard"><span class="material-symbols-outlined">home</span></button>+ <x-extension id="sidebar-quick-actions-main-2"></x-extension>++<!-- Memory -->- <button class="config-button" id="memory-dash" @click="openModal('../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html')" title="Memory">+ <!-- <button class="config-button" id="memory-dash" @click="openModal('../plugins/memory/webui/memory-dashboard.html')" title="Memory"><span class="material-symbols-outlined">psychology</span>- </button>+ </button> -->++ <x-extension id="sidebar-quick-actions-main-3"></x-extension><!-- Scheduler --><button class="config-button" id="scheduler" @click="openModal('modals/scheduler/scheduler-modal.html')" title="Scheduler"><span class="material-symbols-outlined">schedule</span></button>+ <x-extension id="sidebar-quick-actions-main-4"></x-extension>+<!-- Settings --><button class="config-button" id="settings" @click="openModal('settings/settings.html')" title="Settings"><span class="material-symbols-outlined">settings</span></button>+ <x-extension id="sidebar-quick-actions-main-end"></x-extension>+<!-- Dropdown Toggle --><button class="config-button dropdown-toggle" @click="dropdownOpen = !dropdownOpen" title="More options"><span class="material-symbols-outlined" :class="dropdownOpen ? 'rotated' : ''">expand_more</span>@@ -42,8 +54,12 @@x-show="dropdownOpen":style="$store.sidebar.dropdownStyle">+ <x-extension id="sidebar-quick-actions-dropdown-start"></x-extension>+<div class="dropdown-header">Navigation</div>+ <x-extension id="sidebar-quick-actions-dropdown-navigation-start"></x-extension>+<button class="dropdown-item" @click="deselectChat(); dropdownOpen = false"><span class="material-symbols-outlined">home</span><span>Dashboard</span>@@ -63,10 +79,15 @@<span class="material-symbols-outlined">settings</span><span>Settings</span></button>++ <x-extension id="sidebar-quick-actions-dropdown-navigation-end"></x-extension>+<div class="dropdown-separator"></div><div class="dropdown-header">Chat Actions</div>+ <x-extension id="sidebar-quick-actions-dropdown-chat-start"></x-extension>+<button class="dropdown-item" @click="$store.chats.newChat(); dropdownOpen = false"><span class="material-symbols-outlined">edit_square</span><span>New Chat</span>@@ -87,8 +108,12 @@<span>Clear Chat</span></button>+ <x-extension id="sidebar-quick-actions-dropdown-chat-end"></x-extension>+<div class="dropdown-separator"></div>+ <x-extension id="sidebar-quick-actions-dropdown-rest-start"></x-extension>+<button class="dropdown-item" @click="$confirmClick($event, () => { $store.chats.logout(); dropdownOpen = false })" :disabled="!$store.chats.loggedIn"><span class="material-symbols-outlined">logout</span><span>Logout</span>@@ -99,6 +124,7 @@<span>Restart A0</span></button>+ <x-extension id="sidebar-quick-actions-dropdown-rest-end"></x-extension></div></div></body>diff --git a/webui/components/welcome/welcome-store.js b/webui/components/welcome/welcome-store.jsindex 50bc30c3d..791226d45 100644--- a/webui/components/welcome/welcome-store.js+++ b/webui/components/welcome/welcome-store.js@@ -1,7 +1,7 @@import { createStore } from "/js/AlpineStore.js";import { getContext } from "/index.js";import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";-import { store as memoryStore } from "/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js";+import { store as memoryStore } from "/plugins/memory/webui/memory-dashboard-store.js";import { store as projectsStore } from "/components/projects/projects-store.js";import { store as chatInputStore } from "/components/chat/input/input-store.js";import * as API from "/js/api.js";diff --git a/webui/js/api.js b/webui/js/api.jsindex aa10b73b8..84ebea754 100644--- a/webui/js/api.js+++ b/webui/js/api.js@@ -45,7 +45,8 @@ export async function fetchApi(url, request) {finalRequest.headers["X-CSRF-Token"] = token;// perform the fetch with the updated request- const response = await fetch(url, finalRequest);+ const apiUrl = url.startsWith('/api/') || url.startsWith('api/') ? `/${url.replace(/^\/+/, '')}` : `/api/${url.replace(/^\/+/, '')}`;+ const response = await fetch(apiUrl, finalRequest);// check if there was an CSRF errorif (response.status === 403 && retry) {@@ -125,7 +126,7 @@ export async function getCsrfToken() {fetchOptions.signal = controller.signal;}- const fetchPromise = fetch("/csrf_token", fetchOptions);+ const fetchPromise = fetch("/api/csrf_token", fetchOptions);response = timeoutPromise? await Promise.race([fetchPromise, timeoutPromise]): await fetchPromise;diff --git a/webui/js/components.js b/webui/js/components.jsindex 16612662f..328ee55d0 100644--- a/webui/js/components.js+++ b/webui/js/components.js@@ -114,7 +114,7 @@ export async function importComponent(path, targetElement) {const modulePromise = import(blobUrl).catch((err) => {- console.error("Failed to load inline module", err);+ console.error(`Failed to load inline module ${virtualUrl}:`, err);throw err;}).finally(() => URL.revokeObjectURL(blobUrl));@@ -261,4 +261,4 @@ const observer = new MutationObserver((mutations) => {}}});-observer.observe(document.body, { childList: true, subtree: true });+observer.observe(document.body, { childList: true, subtree: true });\ No newline at end of filediff --git a/webui/js/extensions.js b/webui/js/extensions.jsnew file mode 100644index 000000000..37a83f399--- /dev/null+++ b/webui/js/extensions.js@@ -0,0 +1,63 @@+import * as api from "./api.js";++// Load all x-component tags starting from root elements+export async function loadExtensions(roots = [document.documentElement]) {+ try {+ // Convert single root to array if needed+ const rootElements = Array.isArray(roots) ? roots : [roots];++ // Find all top-level components and load them in parallel+ const extensions = rootElements.flatMap((root) =>+ Array.from(root.querySelectorAll("x-extension")),+ );++ if (extensions.length === 0) return;++ await Promise.all(+ extensions.map(async (extension) => {+ const path = extension.getAttribute("id");+ if (!path) {+ console.error("x-extension missing id attribute:", extension);+ return;+ }+ await importExtensions(path, extension);+ }),+ );+ } catch (error) {+ console.error("Error loading extensions:", error);+ }+}++// import all extensions for extension point via backend api+export async function importExtensions(extensionPointId, targetElement) {+ try {+ const response = await api.callJsonApi(`/api/load_webui_extensions`, {+ extension_point: extensionPointId,+ });+ let combinedHTML = "";+ for (const extension of response.extensions) {+ combinedHTML += extension.html.trim();+ }+ targetElement.innerHTML = combinedHTML;+ } catch (error) {+ console.error("Error importing extensions:", error);+ }+}++// Watch for DOM changes to dynamically load x-extensions+const extensionObserver = new MutationObserver((mutations) => {+ for (const mutation of mutations) {+ for (const node of mutation.addedNodes) {+ if (node.nodeType === 1) {+ // ELEMENT_NODE+ // Check if this node or its descendants contain x-extension(s)+ if (node.matches?.("x-extension")) {+ importExtensions(node.getAttribute("id"), node);+ } else if (node.querySelectorAll) {+ loadExtensions([node]);+ }+ }+ }+ }+});+extensionObserver.observe(document.body, { childList: true, subtree: true });diff --git a/webui/js/initFw.js b/webui/js/initFw.jsindex 73fa3815c..8f7d1c00b 100644--- a/webui/js/initFw.js+++ b/webui/js/initFw.js@@ -1,7 +1,7 @@import * as initializer from "./initializer.js";import * as _modals from "./modals.js";import * as _components from "./components.js";-import "./plugins.js";+import * as _extensions from "./extensions.js";import { registerAlpineMagic } from "./confirmClick.js";// initialize required elements