Agent Zero AI framework
refactor settings and scheduler
Alessandrob823fcfb5d74
diff --git a/python/api/settings_set.py b/python/api/settings_set.pyindex c24a3cc66..354392bf5 100644--- a/python/api/settings_set.py+++ b/python/api/settings_set.py@@ -7,6 +7,8 @@ from typing import Anyclass SetSettings(ApiHandler):async def process(self, input: dict[Any, Any], request: Request) -> dict[Any, Any] | Response:- set = settings.convert_in(input)- set = settings.set_settings(set)- return {"settings": set}+ # Convert SettingsOutput (sections/fields) into internal flat Settings,+ # persist it, then return the updated SettingsOutput back to the UI.+ internal = settings.convert_in(input)+ settings.set_settings(internal)+ return {"settings": settings.convert_out(settings.get_settings())}diff --git a/webui/components/settings/a2a/a2a-connection.html b/webui/components/settings/a2a/a2a-connection.htmlindex fc640a68d..060bbd906 100644--- a/webui/components/settings/a2a/a2a-connection.html+++ b/webui/components/settings/a2a/a2a-connection.html@@ -34,16 +34,25 @@<div id="a2a-connection-example"></div>- <script>+ <script type="module">+ import * as API from "/js/api.js";+setTimeout(async () => {const url = window.location.origin;- // Try to get a2a_token first, fallback to mcp_server_token- let tokenField = null;++ // Fetch token from settings API - try a2a_token first, fallback to mcp_server_token+ let token = "";try {- const allFields = settingsModalProxy.settings.sections.flatMap(s => s.fields);- tokenField = allFields.find(f => f.id === 'a2a_token') || allFields.find(f => f.id === 'mcp_server_token');- } catch (e) { }- const token = tokenField ? tokenField.value : '';+ const response = await API.callJsonApi("settings_get", null);+ if (response && response.settings && response.settings.sections) {+ const allFields = response.settings.sections.flatMap(s => s.fields || []);+ const tokenField = allFields.find(f => f.id === "a2a_token") ||+ allFields.find(f => f.id === "mcp_server_token");+ if (tokenField) token = tokenField.value || "";+ }+ } catch (e) {+ console.error("Failed to fetch token:", e);+ }// Fetch and populate projectsconst projectSelect = document.getElementById('a2a-project-select');diff --git a/webui/components/settings/agent/agent-settings.html b/webui/components/settings/agent/agent-settings.htmlnew file mode 100644index 000000000..4f0c610d5--- /dev/null+++ b/webui/components/settings/agent/agent-settings.html@@ -0,0 +1,62 @@+<html>+ <head>+ <title>Agent Settings</title>+ </head>++ <body>+ <div x-data>+ <template x-if="$store.settingsStore">+ <div>+ <nav>+ <ul>+ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <li>+ <a :href="'#section' + (index + 1)">+ <img+ :src="'/public/' + section.id + '.svg'"+ :alt="section.title"+ />+ <span x-text="section.title"></span>+ </a>+ </li>+ </template>+ </ul>+ </nav>++ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <div :id="'section' + (index + 1)" class="section">+ <template x-if="section.id === 'agent'">+ <x-component path="settings/agent/agent.html"></x-component>+ </template>+ <template x-if="section.id === 'chat_model'">+ <x-component path="settings/agent/chat_model.html"></x-component>+ </template>+ <template x-if="section.id === 'util_model'">+ <x-component path="settings/agent/util_model.html"></x-component>+ </template>+ <template x-if="section.id === 'browser_model'">+ <x-component path="settings/agent/browser_model.html"></x-component>+ </template>+ <template x-if="section.id === 'embed_model'">+ <x-component path="settings/agent/embed_model.html"></x-component>+ </template>+ <template x-if="section.id === 'memory'">+ <x-component path="settings/agent/memory.html"></x-component>+ </template>+ <template x-if="section.id === 'speech'">+ <x-component path="settings/agent/speech.html"></x-component>+ </template>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/agent/agent.html b/webui/components/settings/agent/agent.htmlnew file mode 100644index 000000000..5dbb9dc93--- /dev/null+++ b/webui/components/settings/agent/agent.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Agent Config</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('agent');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/agent/browser_model.html b/webui/components/settings/agent/browser_model.htmlnew file mode 100644index 000000000..4e5ff2809--- /dev/null+++ b/webui/components/settings/agent/browser_model.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Web Browser Model</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('browser_model');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/agent/chat_model.html b/webui/components/settings/agent/chat_model.htmlnew file mode 100644index 000000000..13c3097cd--- /dev/null+++ b/webui/components/settings/agent/chat_model.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Chat Model</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('chat_model');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/agent/embed_model.html b/webui/components/settings/agent/embed_model.htmlnew file mode 100644index 000000000..3d1bbf0ad--- /dev/null+++ b/webui/components/settings/agent/embed_model.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Embedding Model</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('embed_model');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/agent/memory.html b/webui/components/settings/agent/memory.htmlnew file mode 100644index 000000000..e53210a19--- /dev/null+++ b/webui/components/settings/agent/memory.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Memory</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('memory');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/agent/speech.html b/webui/components/settings/agent/speech.htmlnew file mode 100644index 000000000..18326f48f--- /dev/null+++ b/webui/components/settings/agent/speech.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Speech</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('speech');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/agent/util_model.html b/webui/components/settings/agent/util_model.htmlnew file mode 100644index 000000000..e8724c937--- /dev/null+++ b/webui/components/settings/agent/util_model.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Utility Model</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('util_model');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/backup/backup-settings.html b/webui/components/settings/backup/backup-settings.htmlnew file mode 100644index 000000000..b8440823e--- /dev/null+++ b/webui/components/settings/backup/backup-settings.html@@ -0,0 +1,44 @@+<html>+ <head>+ <title>Backup & Restore</title>+ </head>++ <body>+ <div x-data>+ <template x-if="$store.settingsStore">+ <div>+ <nav>+ <ul>+ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <li>+ <a :href="'#section' + (index + 1)">+ <img+ :src="'/public/' + section.id + '.svg'"+ :alt="section.title"+ />+ <span x-text="section.title"></span>+ </a>+ </li>+ </template>+ </ul>+ </nav>++ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <div :id="'section' + (index + 1)" class="section">+ <template x-if="section.id === 'backup_restore'">+ <x-component path="settings/backup/backup_restore.html"></x-component>+ </template>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/backup/backup_restore.html b/webui/components/settings/backup/backup_restore.htmlnew file mode 100644index 000000000..ca77cefe3--- /dev/null+++ b/webui/components/settings/backup/backup_restore.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Backup & Restore</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('backup_restore');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/developer/dev.html b/webui/components/settings/developer/dev.htmlnew file mode 100644index 000000000..bc4cff5c3--- /dev/null+++ b/webui/components/settings/developer/dev.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Development</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('dev');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/developer/developer-settings.html b/webui/components/settings/developer/developer-settings.htmlnew file mode 100644index 000000000..395ea84c6--- /dev/null+++ b/webui/components/settings/developer/developer-settings.html@@ -0,0 +1,44 @@+<html>+ <head>+ <title>Developer</title>+ </head>++ <body>+ <div x-data>+ <template x-if="$store.settingsStore">+ <div>+ <nav>+ <ul>+ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <li>+ <a :href="'#section' + (index + 1)">+ <img+ :src="'/public/' + section.id + '.svg'"+ :alt="section.title"+ />+ <span x-text="section.title"></span>+ </a>+ </li>+ </template>+ </ul>+ </nav>++ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <div :id="'section' + (index + 1)" class="section">+ <template x-if="section.id === 'dev'">+ <x-component path="settings/developer/dev.html"></x-component>+ </template>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/external/api-examples.html b/webui/components/settings/external/api-examples.htmlindex 615594682..490198f1b 100644--- a/webui/components/settings/external/api-examples.html+++ b/webui/components/settings/external/api-examples.html@@ -190,10 +190,26 @@</div>-->- <script>- setTimeout(() => {+ <script type="module">+ import * as API from "/js/api.js";++ setTimeout(async () => {const url = window.location.origin;- const token = settingsModalProxy.settings.sections.filter(x => x.id == "mcp_server")[0].fields.filter(x => x.id == "mcp_server_token")[0].value;++ // Fetch token from settings API+ let token = "";+ try {+ const response = await API.callJsonApi("settings_get", null);+ if (response && response.settings && response.settings.sections) {+ const mcpSection = response.settings.sections.find(s => s.id === "mcp_server");+ if (mcpSection) {+ const tokenField = (mcpSection.fields || []).find(f => f.id === "mcp_server_token");+ if (tokenField) token = tokenField.value || "";+ }+ }+ } catch (e) {+ console.error("Failed to fetch token:", e);+ }// Basic usage exampleconst basicExample = `// Basic message examplediff --git a/webui/components/settings/external/api_keys.html b/webui/components/settings/external/api_keys.htmlnew file mode 100644index 000000000..2f180c92b--- /dev/null+++ b/webui/components/settings/external/api_keys.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>API Keys</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('api_keys');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/external/auth.html b/webui/components/settings/external/auth.htmlnew file mode 100644index 000000000..3f90673c0--- /dev/null+++ b/webui/components/settings/external/auth.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Authentication</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('auth');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/external/external-settings.html b/webui/components/settings/external/external-settings.htmlnew file mode 100644index 000000000..5fcaca1fe--- /dev/null+++ b/webui/components/settings/external/external-settings.html@@ -0,0 +1,74 @@+<html>+ <head>+ <title>External Services</title>+ </head>++ <body>+ <div x-data>+ <template x-if="$store.settingsStore">+ <div>+ <nav>+ <ul>+ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <li>+ <a :href="'#section' + (index + 1)">+ <img+ :src="'/public/' + section.id + '.svg'"+ :alt="section.title"+ />+ <span x-text="section.title"></span>+ </a>+ </li>+ </template>++ <!-- Tunnel navigation entry -->+ <li>+ <a href="#section-tunnel">+ <img src="/public/tunnel.svg" alt="Tunnel" />+ <span>Flare Tunnel</span>+ </a>+ </li>+ </ul>+ </nav>++ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <div :id="'section' + (index + 1)" class="section">+ <template x-if="section.id === 'api_keys'">+ <x-component path="settings/external/api_keys.html"></x-component>+ </template>+ <template x-if="section.id === 'litellm'">+ <x-component path="settings/external/litellm.html"></x-component>+ </template>+ <template x-if="section.id === 'secrets'">+ <x-component path="settings/external/secrets.html"></x-component>+ </template>+ <template x-if="section.id === 'auth'">+ <x-component path="settings/external/auth.html"></x-component>+ </template>+ <template x-if="section.id === 'external_api'">+ <x-component path="settings/external/external_api.html"></x-component>+ </template>+ <template x-if="section.id === 'update_checker'">+ <x-component+ path="settings/external/update_checker.html"+ ></x-component>+ </template>+ </div>+ </template>++ <!-- Tunnel section content -->+ <div id="section-tunnel" class="section">+ <x-component path="settings/tunnel/tunnel-section.html"></x-component>+ </div>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/external/external_api.html b/webui/components/settings/external/external_api.htmlnew file mode 100644index 000000000..6c04cc4dd--- /dev/null+++ b/webui/components/settings/external/external_api.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>External API</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('external_api');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/external/litellm.html b/webui/components/settings/external/litellm.htmlnew file mode 100644index 000000000..8a3dd863f--- /dev/null+++ b/webui/components/settings/external/litellm.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>LiteLLM</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('litellm');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/external/secrets.html b/webui/components/settings/external/secrets.htmlnew file mode 100644index 000000000..3857c662a--- /dev/null+++ b/webui/components/settings/external/secrets.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Secrets</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('secrets');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/external/update_checker.html b/webui/components/settings/external/update_checker.htmlnew file mode 100644index 000000000..c1dbeaf8a--- /dev/null+++ b/webui/components/settings/external/update_checker.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>Update Checker</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('update_checker');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/mcp/a2a_server.html b/webui/components/settings/mcp/a2a_server.htmlnew file mode 100644index 000000000..a4b6897fd--- /dev/null+++ b/webui/components/settings/mcp/a2a_server.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>A0 A2A Server</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('a2a_server');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/mcp/client/mcp-servers-store.js b/webui/components/settings/mcp/client/mcp-servers-store.jsindex 1012ad21a..912b1eef7 100644--- a/webui/components/settings/mcp/client/mcp-servers-store.js+++ b/webui/components/settings/mcp/client/mcp-servers-store.js@@ -1,7 +1,7 @@import { createStore } from "/js/AlpineStore.js";-import { scrollModal } from "/js/modals.js";import sleep from "/js/sleep.js";import * as API from "/js/api.js";+import { store as settingsStore } from "/components/settings/settings-store.js";const model = {editor: null,@@ -24,7 +24,8 @@ const model = {}editor.session.setMode("ace/mode/json");- const json = this.getSettingsFieldConfigJson().value;+ const field = this.getSettingsFieldConfigJson();+ const json = field ? field.value : "{}";editor.setValue(json);editor.clearSelection();this.editor = editor;@@ -59,14 +60,14 @@ const model = {},getSettingsFieldConfigJson() {- return settingsModalProxy.settings.sections- .filter((x) => x.id == "mcp_client")[0]- .fields.filter((x) => x.id == "mcp_servers")[0];+ // Use the new settings modal store to access the field+ return settingsStore.getField("mcp_client", "mcp_servers");},onClose() {const val = this.getEditorValue();- this.getSettingsFieldConfigJson().value = val;+ // Update the field value in the settings modal store+ settingsStore.setFieldValue("mcp_client", "mcp_servers", val);this.stopStatusCheck();},diff --git a/webui/components/settings/mcp/mcp-settings.html b/webui/components/settings/mcp/mcp-settings.htmlnew file mode 100644index 000000000..bd689a01b--- /dev/null+++ b/webui/components/settings/mcp/mcp-settings.html@@ -0,0 +1,50 @@+<html>+ <head>+ <title>MCP/A2A</title>+ </head>++ <body>+ <div x-data>+ <template x-if="$store.settingsStore">+ <div>+ <nav>+ <ul>+ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <li>+ <a :href="'#section' + (index + 1)">+ <img+ :src="'/public/' + section.id + '.svg'"+ :alt="section.title"+ />+ <span x-text="section.title"></span>+ </a>+ </li>+ </template>+ </ul>+ </nav>++ <template+ x-for="(section, index) in $store.settingsStore.filteredSections"+ :key="section.id"+ >+ <div :id="'section' + (index + 1)" class="section">+ <template x-if="section.id === 'mcp_client'">+ <x-component path="settings/mcp/mcp_client.html"></x-component>+ </template>+ <template x-if="section.id === 'mcp_server'">+ <x-component path="settings/mcp/mcp_server.html"></x-component>+ </template>+ <template x-if="section.id === 'a2a_server'">+ <x-component path="settings/mcp/a2a_server.html"></x-component>+ </template>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/mcp/mcp_client.html b/webui/components/settings/mcp/mcp_client.htmlnew file mode 100644index 000000000..d3cbc74eb--- /dev/null+++ b/webui/components/settings/mcp/mcp_client.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>External MCP Servers</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('mcp_client');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/mcp/mcp_server.html b/webui/components/settings/mcp/mcp_server.htmlnew file mode 100644index 000000000..98ff212b6--- /dev/null+++ b/webui/components/settings/mcp/mcp_server.html@@ -0,0 +1,146 @@+<html>+ <head>+ <title>A0 MCP Server</title>+ </head>++ <body>+ <div+ x-data="{+ get section() {+ const store = $store.settingsStore;+ if (!store) return null;+ return store.getSectionById('mcp_server');+ },+ }"+ >+ <template x-if="section">+ <div>+ <div class="section-title" x-text="section.title"></div>+ <div class="section-description" x-html="section.description"></div>++ <template+ x-for="(field, fieldIndex) in (section.fields || []).filter((f) => !f.hidden)"+ :key="fieldIndex"+ >+ <div :class="{ field: true, 'field-full': field.type === 'textarea' }">+ <div class="field-label" x-show="field.title || field.description">+ <div class="field-title" x-text="field.title" x-show="field.title"></div>+ <div+ class="field-description"+ x-html="field.description || ''"+ x-show="field.description"+ ></div>+ </div>++ <div class="field-control">+ <template x-if="field.type === 'text'">+ <input+ type="text"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'number'">+ <input+ type="number"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ />+ </template>++ <template x-if="field.type === 'password'">+ <input+ type="password"+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ :id="field.id"+ autocomplete="off"+ @input="field.value = $event.target.value"+ />+ </template>++ <template x-if="field.type === 'textarea'">+ <textarea+ :class="field.classes"+ :value="field.value"+ :readonly="field.readonly === true"+ @input="field.value = $event.target.value"+ :style="field.style"+ ></textarea>+ </template>++ <template x-if="field.type === 'switch'">+ <label class="toggle">+ <input+ type="checkbox"+ :checked="field.value"+ :disabled="field.readonly === true"+ @change="field.value = $event.target.checked"+ />+ <span class="toggler"></span>+ </label>+ </template>++ <template x-if="field.type === 'range'">+ <div class="field-control">+ <input+ type="range"+ :min="field.min"+ :max="field.max"+ :step="field.step"+ :value="field.value"+ :disabled="field.readonly === true"+ @input="field.value = $event.target.value"+ :class="field.classes"+ />+ <span class="range-value" x-text="field.value"></span>+ </div>+ </template>++ <template x-if="field.type === 'button'">+ <button+ class="btn btn-field"+ :class="field.classes"+ :disabled="field.readonly === true"+ @click="$store.settingsStore.handleFieldButton(field)"+ x-text="field.value"+ ></button>+ </template>++ <template x-if="field.type === 'select'">+ <select+ :class="field.classes"+ x-model="field.value"+ :disabled="field.readonly === true"+ >+ <template x-for="option in field.options" :key="option.value">+ <option+ :value="option.value"+ x-text="option.label"+ :selected="option.value === field.value"+ ></option>+ </template>+ </select>+ </template>++ <template x-if="field.type === 'html'">+ <div :class="field.classes" x-html="field.value"></div>+ </template>+ </div>+ </div>+ </template>+ </div>+ </template>+ </div>+ </body>+</html>+diff --git a/webui/components/settings/mcp/server/example.html b/webui/components/settings/mcp/server/example.htmlindex db50343f4..34845e1fd 100644--- a/webui/components/settings/mcp/server/example.html+++ b/webui/components/settings/mcp/server/example.html@@ -33,10 +33,26 @@<div id="mcp-server-example"></div>- <script>+ <script type="module">+ import * as API from "/js/api.js";+setTimeout(async () => {const url = window.location.origin;- const token = settingsModalProxy.settings.sections.filter(x => x.id == "mcp_server")[0].fields.filter(x => x.id == "mcp_server_token")[0].value;++ // Fetch token from settings API+ let token = "";+ try {+ const response = await API.callJsonApi("settings_get", null);+ if (response && response.settings && response.settings.sections) {+ const mcpSection = response.settings.sections.find(s => s.id === "mcp_server");+ if (mcpSection) {+ const tokenField = (mcpSection.fields || []).find(f => f.id === "mcp_server_token");+ if (tokenField) token = tokenField.value || "";+ }+ }+ } catch (e) {+ console.error("Failed to fetch token:", e);+ }// Fetch and populate projectsconst projectSelect = document.getElementById('mcp-project-select');diff --git a/webui/components/settings/scheduler/scheduler-settings.html b/webui/components/settings/scheduler/scheduler-settings.htmlnew file mode 100644index 000000000..db6ce76f1--- /dev/null+++ b/webui/components/settings/scheduler/scheduler-settings.html@@ -0,0 +1,33 @@+<html>+<head>+ <script type="module">+ import { store } from "/components/settings/scheduler/scheduler-store.js";+ </script>+</head>+<body>+<div x-data>+ <template x-if="$store.schedulerStore">+ <div id="scheduler-settings-root">+ <nav>+ <ul>+ <li>+ <a href="#section-task-scheduler">+ <img src="/public/task_scheduler.svg" alt="Task Scheduler">+ <span>Task Scheduler</span>+ </a>+ </li>+ </ul>+ </nav>++ <div id="section-task-scheduler" class="section">+ <div class="section-title">Task Scheduler</div>+ <div class="section-description">Manage scheduled tasks and automated processes for Agent Zero.</div>++ <x-component path="settings/scheduler/scheduler-task-editor.html"></x-component>+ <x-component path="settings/scheduler/scheduler-task-list.html"></x-component>+ </div>+ </div>+ </template>+</div>+</body>+</html>diff --git a/webui/components/settings/scheduler/scheduler-store.js b/webui/components/settings/scheduler/scheduler-store.jsnew file mode 100644index 000000000..3bd3b0b7d--- /dev/null+++ b/webui/components/settings/scheduler/scheduler-store.js@@ -0,0 +1,1025 @@+import { createStore } from "/js/AlpineStore.js";+import { formatDateTime, getUserTimezone } from "/js/time-utils.js";+import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";+import { store as projectsStore } from "/components/projects/projects-store.js";+import { store as notificationsStore } from "/components/notifications/notification-store.js";++const API = globalThis.fetchApi || globalThis.fetch;+const VIEW_MODE_STORAGE_KEY = "scheduler_view_mode";+const NOTIFICATION_DURATION = {+ success: 3,+ info: 3,+ warning: 4,+ error: 5,+};+const DEFAULT_TASK_STATE = "idle";+const TASK_TYPES = ["scheduled", "adhoc", "planned"];++/**+ * @typedef {Object} SchedulerPlan+ * @property {string[]} todo+ * @property {string|null} in_progress+ * @property {string[]} done+ */++/**+ * @typedef {Object} SchedulerProject+ * @property {string|null} name+ * @property {string|null} title+ * @property {string} color+ */++/**+ * @typedef {Object} SchedulerTask+ * @property {string} uuid+ * @property {string} name+ * @property {string} type+ * @property {string} state+ * @property {SchedulerPlan} plan+ * @property {Object|string} schedule+ * @property {string} token+ * @property {SchedulerProject|null} project+ * @property {string|null} project_name+ * @property {string} [project_color]+ * @property {string[]} attachments+ * @property {string} [system_prompt]+ * @property {string} [prompt]+ * @property {string} [created_at]+ * @property {string} [updated_at]+ * @property {string} [last_run]+ * @property {string} [last_result]+ */++/**+ * @typedef {Object} EditingTask+ * @property {string} [uuid]+ * @property {string} name+ * @property {string} type+ * @property {string} state+ * @property {SchedulerPlan} plan+ * @property {ReturnType<typeof defaultSchedule>} schedule+ * @property {string} token+ * @property {SchedulerProject|null} project+ * @property {boolean} dedicated_context+ * @property {string[]} attachments+ * @property {string} system_prompt+ * @property {string} prompt+ */++/**+ * @template T+ * @typedef {Object} SchedulerApiResult+ * @property {boolean} ok+ * @property {string} [error]+ * @property {T} [data]+ */++// -----------------------------------------------------------------------------+// Pure helpers+// -----------------------------------------------------------------------------++const defaultSchedule = () => ({+ minute: "*",+ hour: "*",+ day: "*",+ month: "*",+ weekday: "*",+ timezone: getUserTimezone(),+});++const emptyPlan = () => ({+ todo: [],+ in_progress: null,+ done: [],+});++const defaultEditingTask = (overrides = {}) => ({+ name: "",+ type: "scheduled",+ state: DEFAULT_TASK_STATE,+ schedule: defaultSchedule(),+ token: "",+ plan: emptyPlan(),+ system_prompt: "",+ prompt: "",+ attachments: [],+ project: null,+ dedicated_context: true,+ ...overrides,+});++const readPersistedViewMode = () => {+ if (typeof window === "undefined") return "list";+ return window.localStorage?.getItem(VIEW_MODE_STORAGE_KEY) || "list";+};++const sleep = (ms = 0) =>+ new Promise((resolve) => {+ setTimeout(resolve, ms);+ });++function safeJsonClone(value) {+ try {+ return JSON.parse(JSON.stringify(value));+ } catch {+ return value;+ }+}++function normalizeAttachments(value) {+ if (!value) return [];+ if (Array.isArray(value)) {+ return value.filter((item) => typeof item === "string" && item.trim().length > 0);+ }+ if (typeof value === "string") {+ return value+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+ }+ return [];+}++function normalizeSchedule(schedule) {+ if (!schedule) return defaultSchedule();+ if (typeof schedule === "string") {+ const [minute = "*", hour = "*", day = "*", month = "*", weekday = "*"] = schedule+ .split(" ")+ .map((segment) => segment || "*");+ return {+ minute,+ hour,+ day,+ month,+ weekday,+ timezone: getUserTimezone(),+ };+ }+ return {+ minute: schedule.minute || "*",+ hour: schedule.hour || "*",+ day: schedule.day || "*",+ month: schedule.month || "*",+ weekday: schedule.weekday || "*",+ timezone: schedule.timezone || getUserTimezone(),+ };+}++function normalizePlanStruct(plan) {+ if (!plan) return emptyPlan();+ const clone = {+ todo: Array.isArray(plan.todo) ? [...plan.todo] : [],+ in_progress: plan.in_progress || null,+ done: Array.isArray(plan.done) ? [...plan.done] : [],+ };+ const sanitized = clone.todo+ .map((value) => new Date(value))+ .filter((date) => !Number.isNaN(date.getTime()))+ .map((date) => date.toISOString())+ .sort();+ clone.todo = sanitized;+ clone.done = clone.done+ .map((value) => new Date(value))+ .filter((date) => !Number.isNaN(date.getTime()))+ .map((date) => date.toISOString());+ if (clone.in_progress) {+ const inProgress = new Date(clone.in_progress);+ clone.in_progress = Number.isNaN(inProgress.getTime())+ ? null+ : inProgress.toISOString();+ }+ return clone;+}++function ensureTaskValidity(task) {+ return Boolean(task && task.uuid && task.name && task.type);+}++function extractProjectInfo(task) {+ if (!task) return null;+ const slug = task.project_name || task.project?.name || null;+ const title = task.project?.title || task.project?.name || slug;+ const color = task.project_color || task.project?.color || "";+ if (!slug && !title) return null;+ return {+ name: slug,+ title: title || slug,+ color: color || "",+ };+}++function composeEditingTask(task = {}) {+ const base = task && task.uuid ? { ...task } : { ...defaultEditingTask(), ...task };+ return {+ ...base,+ schedule: normalizeSchedule(base.schedule),+ plan: normalizePlanStruct(base.plan),+ attachments: normalizeAttachments(base.attachments),+ token: base.token || "",+ project: base.project || extractProjectInfo(base) || null,+ dedicated_context:+ typeof base.dedicated_context === "boolean" ? base.dedicated_context : true,+ state: base.state || DEFAULT_TASK_STATE,+ };+}++function normalizeTaskFromBackend(task) {+ if (!ensureTaskValidity(task)) return null;+ return composeEditingTask(task);+}++function buildPayloadFromEditingTask(editingTask, { isCreating = false } = {}) {+ const payload = {+ name: editingTask.name.trim(),+ system_prompt: editingTask.system_prompt || "",+ prompt: editingTask.prompt || "",+ state: editingTask.state || DEFAULT_TASK_STATE,+ timezone: getUserTimezone(),+ attachments: normalizeAttachments(editingTask.attachments),+ dedicated_context: editingTask.dedicated_context,+ };++ if (editingTask.type === "scheduled") {+ payload.schedule = normalizeSchedule(editingTask.schedule);+ }++ if (editingTask.type === "planned") {+ payload.plan = normalizePlanStruct(editingTask.plan);+ }++ if (editingTask.type === "adhoc") {+ payload.token = editingTask.token;+ }++ if (editingTask.project && editingTask.project.name) {+ payload.project_name = editingTask.project.name;+ if (editingTask.project.color) {+ payload.project_color = editingTask.project.color;+ }+ }++ if (!isCreating && editingTask.uuid) {+ payload.task_id = editingTask.uuid;+ }++ return payload;+}++async function callSchedulerEndpoint(endpoint, payload = {}, defaultError) {+ try {+ const response = await API(endpoint, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(payload),+ });+ const data = await response.json().catch(() => ({}));+ if (!response.ok) {+ return { ok: false, error: data?.error || defaultError || "Scheduler request failed" };+ }+ return { ok: true, data };+ } catch (error) {+ return { ok: false, error: error?.message || defaultError || "Scheduler request failed" };+ }+}++const schedulerApi = {+ async listTasks() {+ const result = await callSchedulerEndpoint(+ "/scheduler_tasks_list",+ { timezone: getUserTimezone() },+ "Failed to fetch tasks"+ );+ if (!result.ok) return { ok: false, error: result.error };+ const rawTasks = Array.isArray(result.data?.tasks) ? result.data.tasks : [];+ const normalized = rawTasks+ .filter(ensureTaskValidity)+ .map((task) => normalizeTaskFromBackend(task))+ .filter(Boolean);+ return { ok: true, tasks: normalized };+ },++ async createTask(payload) {+ const result = await callSchedulerEndpoint(+ "/scheduler_task_create",+ payload,+ "Failed to create task"+ );+ if (!result.ok) return { ok: false, error: result.error };+ const task = result.data?.task ? normalizeTaskFromBackend(result.data.task) : null;+ return { ok: true, task };+ },++ async updateTask(payload) {+ const result = await callSchedulerEndpoint(+ "/scheduler_task_update",+ payload,+ "Failed to update task"+ );+ if (!result.ok) return { ok: false, error: result.error };+ const task = result.data?.task ? normalizeTaskFromBackend(result.data.task) : null;+ return { ok: true, task };+ },++ async runTask(taskId) {+ return callSchedulerEndpoint(+ "/scheduler_task_run",+ { task_id: taskId, timezone: getUserTimezone() },+ "Failed to run task"+ );+ },++ async deleteTask(taskId) {+ return callSchedulerEndpoint(+ "/scheduler_task_delete",+ { task_id: taskId, timezone: getUserTimezone() },+ "Failed to delete task"+ );+ },+};++const notificationChannels = {+ success: "frontendSuccess",+ info: "frontendInfo",+ warning: "frontendWarning",+ error: "frontendError",+};++function pushNotification(type, message, title = "Scheduler", duration) {+ const channel = notificationChannels[type];+ if (!channel || typeof notificationsStore[channel] !== "function") return;+ const ttl = duration ?? NOTIFICATION_DURATION[type] ?? 4;+ notificationsStore[channel](message, title, ttl);+}++function destroyPlannerInput(inputId) {+ const input = typeof document !== "undefined" ? document.getElementById(inputId) : null;+ if (!input || !input._flatpickr) return;+ input._flatpickr.destroy();+ const wrapper = input.closest(".scheduler-flatpickr-wrapper");+ if (wrapper && wrapper.parentNode) {+ wrapper.parentNode.insertBefore(input, wrapper);+ wrapper.parentNode.removeChild(wrapper);+ }+ input.classList.remove("scheduler-flatpickr-input");+}++function setupPlannerInput(inputId) {+ if (typeof flatpickr === "undefined") {+ return null;+ }+ const input = document.getElementById(inputId);+ if (!input) return null;++ destroyPlannerInput(inputId);++ const wrapper = document.createElement("div");+ wrapper.className = "scheduler-flatpickr-wrapper";+ wrapper.style.overflow = "visible";+ input.parentNode.insertBefore(wrapper, input);+ wrapper.appendChild(input);+ input.classList.add("scheduler-flatpickr-input");++ const options = {+ dateFormat: "Y-m-d H:i",+ enableTime: true,+ time_24hr: true,+ static: false,+ appendTo: document.body,+ allowInput: true,+ positionElement: wrapper,+ theme: "scheduler-theme",+ minuteIncrement: 5,+ defaultHour: new Date().getHours(),+ defaultMinute: Math.ceil(new Date().getMinutes() / 5) * 5,+ onOpen(selectedDates, dateStr, instance) {+ instance.calendarContainer.style.zIndex = "9999";+ instance.calendarContainer.style.position = "absolute";+ instance.calendarContainer.style.visibility = "visible";+ instance.calendarContainer.style.opacity = "1";+ instance.calendarContainer.classList.add("scheduler-theme");+ },+ onReady(selectedDates, dateStr, instance) {+ if (!dateStr) {+ const now = new Date();+ now.setMinutes(now.getMinutes() + 30);+ instance.setDate(now, true);+ }+ },+ };++ const picker = flatpickr(input, options);+ const clearButton = document.createElement("button");+ clearButton.className = "scheduler-flatpickr-clear";+ clearButton.innerHTML = "×";+ clearButton.type = "button";+ clearButton.addEventListener("click", (event) => {+ event.preventDefault();+ event.stopPropagation();+ if (picker) picker.clear();+ });+ wrapper.appendChild(clearButton);++ return picker;+}++function readDateFromPlannerInput(input) {+ if (!input) return null;+ if (input._flatpickr && input._flatpickr.selectedDates.length > 0) {+ return input._flatpickr.selectedDates[0];+ }+ if (input.value) {+ const date = new Date(input.value);+ if (!Number.isNaN(date.getTime())) {+ return date;+ }+ }+ return null;+}++function sortByDate(value) {+ const date = new Date(value);+ return Number.isNaN(date.getTime()) ? 0 : date.getTime();+}++// -----------------------------------------------------------------------------+// Store definition+// -----------------------------------------------------------------------------++const schedulerStoreModel = {+ // Core collection state -----------------------------------------------------+ tasks: [],+ isLoading: false,+ showLoadingState: false,+ hasNoTasks: true,++ // Filtering & view ---------------------------------------------------------+ filterType: "all",+ filterState: "all",+ sortField: "name",+ sortDirection: "asc",+ viewMode: readPersistedViewMode(),+ selectedTaskForDetail: null,++ // Editor state -------------------------------------------------------------+ isCreating: false,+ isEditing: false,+ editingTask: defaultEditingTask(),+ selectedProjectSlug: "",+ projectOptions: [],++ // Polling ------------------------------------------------------------------+ pollingInterval: null,+ pollingActive: false,++ // Computed -----------------------------------------------------------------+ get filteredTasks() {+ if (!Array.isArray(this.tasks)) return [];+ let filtered = [...this.tasks];++ if (this.filterType && this.filterType !== "all") {+ filtered = filtered.filter((task) =>+ task.type ? task.type.toLowerCase() === this.filterType.toLowerCase() : false+ );+ }++ if (this.filterState && this.filterState !== "all") {+ filtered = filtered.filter((task) =>+ task.state ? task.state.toLowerCase() === this.filterState.toLowerCase() : false+ );+ }++ return this.sortTasks(filtered);+ },++ get attachmentsText() {+ const attachments = Array.isArray(this.editingTask.attachments)+ ? this.editingTask.attachments+ : [];+ return attachments.join("\n");+ },++ set attachmentsText(value) {+ if (typeof value === "string") {+ this.editingTask.attachments = value.split("\n");+ } else {+ this.editingTask.attachments = [];+ }+ },++ // Lifecycle ----------------------------------------------------------------+ init() {+ this.resetEditingTask();+ this.refreshProjectOptions();+ },++ persistViewMode(mode) {+ this.viewMode = mode;+ try {+ window.localStorage?.setItem(VIEW_MODE_STORAGE_KEY, mode);+ } catch {+ /* ignore storage failures */+ }+ },++ setViewMode(mode) {+ this.persistViewMode(mode);+ },++ onTabActivated() {+ this.pollingActive = true;+ this.startPolling();+ },++ onTabDeactivated() {+ this.stopPolling();+ },++ async onModalClosed() {+ this.stopPolling();+ this.destroyFlatpickr("all");+ this.isCreating = false;+ this.isEditing = false;+ this.resetEditingTask();+ this.selectedTaskForDetail = null;+ this.persistViewMode("list");+ },++ startPolling() {+ if (this.pollingInterval) return;+ this.fetchTasks();+ this.pollingInterval = setInterval(() => {+ if (this.pollingActive) {+ this.fetchTasks();+ }+ }, 2000);+ },++ stopPolling() {+ this.pollingActive = false;+ if (this.pollingInterval) {+ clearInterval(this.pollingInterval);+ this.pollingInterval = null;+ }+ },++ // Data fetching -------------------------------------------------------------+ async fetchTasks({ manual = false } = {}) {+ if (this.isCreating || this.isEditing) return;+ this.isLoading = true;+ try {+ const { ok, error, tasks } = await schedulerApi.listTasks();+ if (!ok) {+ if (manual) this.notifyError(`Failed to fetch tasks: ${error}`);+ this.tasks = [];+ this.hasNoTasks = true;+ return;+ }+ this.tasks = tasks;+ this.hasNoTasks = tasks.length === 0;+ } catch (error) {+ if (manual) this.notifyError(`Failed to fetch tasks: ${error.message}`);+ this.tasks = [];+ this.hasNoTasks = true;+ } finally {+ this.isLoading = false;+ }+ },++ async saveTask() {+ if (!this.editingTask.name?.trim() || !this.editingTask.prompt?.trim()) {+ window.alert("Task name and prompt are required");+ return;+ }++ if (!TASK_TYPES.includes(this.editingTask.type)) {+ window.alert("Invalid task type");+ return;+ }++ if (this.editingTask.type === "adhoc" && !this.editingTask.token) {+ this.editingTask.token = this.generateRandomToken();+ }++ const payload = buildPayloadFromEditingTask(this.editingTask, {+ isCreating: this.isCreating,+ });++ try {+ const result = this.isCreating+ ? await schedulerApi.createTask(payload)+ : await schedulerApi.updateTask(payload);++ if (!result.ok) {+ throw new Error(result.error);+ }++ const message = this.isCreating+ ? "Task created successfully"+ : "Task updated successfully";+ this.notifySuccess(message);++ if (result.task) {+ if (this.isCreating) {+ this.tasks = [...this.tasks, result.task];+ } else {+ this.tasks = this.tasks.map((task) =>+ task.uuid === result.task.uuid ? result.task : task+ );+ }+ } else {+ await this.fetchTasks({ manual: true });+ }+ } catch (error) {+ this.notifyError(`Failed to save task: ${error.message}`);+ return;+ } finally {+ this.destroyFlatpickr("all");+ this.resetEditingTask();+ this.isCreating = false;+ this.isEditing = false;+ }+ },++ async runTask(taskId) {+ try {+ const result = await schedulerApi.runTask(taskId);+ if (!result.ok) throw new Error(result.error);+ const warning = result.data?.warning;+ const message = result.data?.message || "Task started successfully";+ if (warning) {+ this.notifyWarning(warning);+ } else {+ this.notifySuccess(message);+ }+ this.fetchTasks({ manual: true });+ } catch (error) {+ this.notifyError(`Failed to run task: ${error.message}`);+ }+ },++ async resetTaskState(taskId) {+ const task = this.tasks.find((t) => t.uuid === taskId);+ if (!task) {+ this.notifyError("Task not found");+ return;+ }+ if (task.state === "idle") {+ this.notifyInfo("Task is already in idle state");+ return;+ }++ this.showLoadingState = true;+ try {+ const result = await schedulerApi.updateTask({ task_id: taskId, state: "idle" });+ if (!result.ok) throw new Error(result.error);+ this.notifySuccess("Task state reset to idle");+ await this.fetchTasks({ manual: true });+ } catch (error) {+ this.notifyError(`Failed to reset task state: ${error.message}`);+ } finally {+ this.showLoadingState = false;+ }+ },++ async deleteTask(taskId) {+ if (+ !window.confirm(+ "Are you sure you want to delete this task? This action cannot be undone."+ )+ ) {+ return;+ }++ try {+ if (typeof chatsStore.switchFromContext === "function") {+ await chatsStore.switchFromContext(taskId);+ }+ } catch (error) {+ console.warn("[scheduler] Failed to switch from context before delete", error);+ }++ try {+ const result = await schedulerApi.deleteTask(taskId);+ if (!result.ok) throw new Error(result.error);+ this.notifySuccess("Task deleted successfully");+ this.tasks = this.tasks.filter((task) => task.uuid !== taskId);+ this.hasNoTasks = this.tasks.length === 0;+ if (this.selectedTaskForDetail?.uuid === taskId) {+ this.closeTaskDetail();+ }+ } catch (error) {+ this.notifyError(`Failed to delete task: ${error.message}`);+ }+ },++ async deleteTaskFromSidebar(taskId) {+ await this.deleteTask(taskId);+ },++ // Domain helpers -----------------------------------------------------------+ resetEditingTask() {+ this.editingTask = defaultEditingTask();+ this.selectedProjectSlug = "";+ },++ setEditingTask(task) {+ const normalized = composeEditingTask(task);+ this.editingTask = normalized;+ this.selectedProjectSlug = normalized.project?.name || "";+ },++ async refreshProjectOptions() {+ try {+ if (+ !Array.isArray(projectsStore.projectList) ||+ projectsStore.projectList.length === 0+ ) {+ if (typeof projectsStore.loadProjectsList === "function") {+ await projectsStore.loadProjectsList();+ }+ }+ } catch (error) {+ console.warn("[scheduler] Failed to load project list", error);+ }++ const list = Array.isArray(projectsStore.projectList)+ ? projectsStore.projectList+ : [];++ this.projectOptions = list.map((proj) => ({+ name: proj.name,+ title: proj.title || proj.name,+ color: proj.color || "",+ }));+ },++ deriveActiveProject() {+ const selected = chatsStore?.selectedContext || null;+ if (!selected || !selected.project) return null;+ const project = selected.project;+ return {+ name: project.name || null,+ title: project.title || project.name || null,+ color: project.color || "",+ };+ },++ onProjectSelect(slug) {+ this.selectedProjectSlug = slug || "";+ if (!slug) {+ this.editingTask.project = null;+ return;+ }++ const option = this.projectOptions.find((item) => item.name === slug);+ if (option) {+ this.editingTask.project = { ...option };+ } else {+ this.editingTask.project = { name: slug, title: slug, color: "" };+ }+ },++ changeSort(field) {+ if (this.sortField === field) {+ this.sortDirection = this.sortDirection === "asc" ? "desc" : "asc";+ } else {+ this.sortField = field;+ this.sortDirection = "asc";+ }+ },++ sortTasks(tasks) {+ if (!Array.isArray(tasks) || tasks.length === 0) return tasks;+ const direction = this.sortDirection === "asc" ? 1 : -1;+ const field = this.sortField;+ return [...tasks].sort((a, b) => {+ const fieldA = a[field];+ const fieldB = b[field];+ if (fieldA === undefined && fieldB === undefined) return 0;+ if (fieldA === undefined) return 1;+ if (fieldB === undefined) return -1;+ if (["createdAt", "updatedAt", "last_run"].includes(field)) {+ return (sortByDate(fieldA) - sortByDate(fieldB)) * direction;+ }+ if (typeof fieldA === "string" && typeof fieldB === "string") {+ return fieldA.localeCompare(fieldB) * direction;+ }+ return (fieldA - fieldB) * direction;+ });+ },++ formatDate(dateString) {+ if (!dateString) return "Never";+ return formatDateTime(dateString, "full");+ },++ formatPlan(task) {+ if (!task || !task.plan) return "No plan";+ const todoCount = Array.isArray(task.plan.todo) ? task.plan.todo.length : 0;+ const inProgress = task.plan.in_progress ? "Yes" : "No";+ const doneCount = Array.isArray(task.plan.done) ? task.plan.done.length : 0;+ let nextRun = "";+ if (Array.isArray(task.plan.todo) && task.plan.todo.length > 0) {+ const nextTime = new Date(task.plan.todo[0]);+ nextRun = Number.isNaN(nextTime.getTime())+ ? "Invalid date"+ : formatDateTime(nextTime, "short");+ } else {+ nextRun = "None";+ }+ return `Next: ${nextRun}\nTodo: ${todoCount}\nIn Progress: ${inProgress}\nDone: ${doneCount}`;+ },++ formatSchedule(task) {+ if (!task.schedule) return "None";+ if (typeof task.schedule === "string") return task.schedule;+ return `${task.schedule.minute || "*"} ${task.schedule.hour || "*"} ${+ task.schedule.day || "*"+ } ${task.schedule.month || "*"} ${task.schedule.weekday || "*"}`;+ },++ getStateBadgeClass(state) {+ switch (state) {+ case "idle":+ return "scheduler-status-idle";+ case "running":+ return "scheduler-status-running";+ case "disabled":+ return "scheduler-status-disabled";+ case "error":+ return "scheduler-status-error";+ default:+ return "";+ }+ },++ extractTaskProject(task) {+ return extractProjectInfo(task);+ },++ formatProjectName(project) {+ if (!project) return "No Project";+ return project.title || project.name || "No Project";+ },++ formatProjectLabel(project) {+ return `Project: ${this.formatProjectName(project)}`;+ },++ formatTaskProject(task) {+ return this.formatProjectName(this.extractTaskProject(task));+ },++ showTaskDetail(taskId) {+ const task = this.tasks.find((t) => t.uuid === taskId);+ if (!task) {+ this.notifyError("Task not found");+ return;+ }++ const snapshot = safeJsonClone(task);+ if (!snapshot.attachments) {+ snapshot.attachments = [];+ }++ this.selectedTaskForDetail = snapshot;+ const closePromise = window.openModal("settings/scheduler/scheduler-task-detail.html");+ if (closePromise && typeof closePromise.then === "function") {+ closePromise.then(() => {+ if (this.selectedTaskForDetail?.uuid === snapshot.uuid) {+ this.selectedTaskForDetail = null;+ }+ });+ }+ },++ closeTaskDetail() {+ this.selectedTaskForDetail = null;+ window.closeModal();+ },++ async startCreateTask() {+ this.isCreating = true;+ this.isEditing = false;+ await this.refreshProjectOptions();++ let initialProject = this.deriveActiveProject();+ if (!initialProject && this.projectOptions.length > 0) {+ initialProject = { ...this.projectOptions[0] };+ }++ this.editingTask = defaultEditingTask({+ token: this.generateRandomToken(),+ project: initialProject,+ });+ this.selectedProjectSlug = initialProject?.name || "";+ setTimeout(() => this.initFlatpickr("create"), 100);+ },++ async startEditTask(taskId) {+ const task = this.tasks.find((t) => t.uuid === taskId);+ if (!task) {+ this.notifyError("Task not found");+ return;+ }++ this.isCreating = false;+ this.isEditing = true;+ this.setEditingTask(safeJsonClone(task));+ setTimeout(() => this.initFlatpickr("edit"), 100);+ },++ cancelEdit() {+ this.destroyFlatpickr("all");+ this.resetEditingTask();+ this.selectedProjectSlug = "";+ this.isCreating = false;+ this.isEditing = false;+ },++ normalizePlan() {+ this.editingTask.plan = normalizePlanStruct(this.editingTask.plan);+ },++ addPlannedTime(mode = "create") {+ if (!this.editingTask.plan) {+ this.editingTask.plan = emptyPlan();+ }+ if (!Array.isArray(this.editingTask.plan.todo)) {+ this.editingTask.plan.todo = [];+ }++ const inputId = mode === "edit" ? "newPlannedTime-edit" : "newPlannedTime-create";+ const input = document.getElementById(inputId);+ if (!input) {+ console.warn("[scheduler] Input element not found for planned time", inputId);+ return;+ }++ const selectedDate = readDateFromPlannerInput(input);+ if (!selectedDate) {+ window.alert("Please select a valid date and time");+ return;+ }++ this.editingTask.plan.todo.push(selectedDate.toISOString());+ this.editingTask.plan.todo.sort();++ if (input._flatpickr) {+ input._flatpickr.clear();+ } else {+ input.value = "";+ }+ },++ generateRandomToken() {+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+ let token = "";+ for (let i = 0; i < 16; i++) {+ token += characters.charAt(Math.floor(Math.random() * characters.length));+ }+ return token;+ },++ // UI bridge helpers --------------------------------------------------------+ initFlatpickr(mode = "all") {+ if (mode === "all" || mode === "create") {+ setupPlannerInput("newPlannedTime-create");+ }+ if (mode === "all" || mode === "edit") {+ setupPlannerInput("newPlannedTime-edit");+ }+ },++ destroyFlatpickr(mode = "all") {+ if (mode === "all" || mode === "create") {+ destroyPlannerInput("newPlannedTime-create");+ }+ if (mode === "all" || mode === "edit") {+ destroyPlannerInput("newPlannedTime-edit");+ }+ },++ // Notifications ------------------------------------------------------------+ notifySuccess(message, options = {}) {+ pushNotification("success", message, options.title, options.duration);+ },++ notifyInfo(message, options = {}) {+ pushNotification("info", message, options.title, options.duration);+ },++ notifyWarning(message, options = {}) {+ pushNotification("warning", message, options.title, options.duration);+ },++ notifyError(message, options = {}) {+ pushNotification("error", message, options.title, options.duration);+ },+};++const store = createStore("schedulerStore", schedulerStoreModel);++export { store };diff --git a/webui/components/settings/scheduler/scheduler-task-detail.html b/webui/components/settings/scheduler/scheduler-task-detail.htmlnew file mode 100644index 000000000..85dae0187--- /dev/null+++ b/webui/components/settings/scheduler/scheduler-task-detail.html@@ -0,0 +1,129 @@+<html>+<head>+ <title>Task Details</title>+ <script type="module">+ import { store } from "/components/settings/scheduler/scheduler-store.js";+ </script>+</head>+<body>+<div x-data>+ <template x-if="$store.schedulerStore">+ <div class="scheduler-detail-view"+ x-show="$store.schedulerStore.selectedTaskForDetail">+ <div class="scheduler-detail-header">+ <h2 class="scheduler-detail-title"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.selectedTaskForDetail.name : ''"></h2>+ <div class="scheduler-status-badge"+ :class="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.getStateBadgeClass($store.schedulerStore.selectedTaskForDetail.state) : ''"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.selectedTaskForDetail.state : ''"></div>+ <button class="btn btn-cancel" @click="$store.schedulerStore.closeTaskDetail()">Close</button>+ </div>++ <div class="scheduler-detail-content">+ <div class="scheduler-details-grid">+ <div class="scheduler-details-label">Type:</div>+ <div class="scheduler-details-value"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.selectedTaskForDetail.type : ''"></div>++ <div class="scheduler-details-label">Project:</div>+ <div class="scheduler-details-value">+ <span class="project-color-ball"+ :style="$store.schedulerStore.extractTaskProject($store.schedulerStore.selectedTaskForDetail)?.color ? { backgroundColor: $store.schedulerStore.extractTaskProject($store.schedulerStore.selectedTaskForDetail).color } : { border: '1px solid var(--color-border)' }"></span>+ <span x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.formatTaskProject($store.schedulerStore.selectedTaskForDetail) : 'No Project'"></span>+ </div>++ <div class="scheduler-details-label">Created:</div>+ <div class="scheduler-details-value"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.formatDate($store.schedulerStore.selectedTaskForDetail.created_at) : ''"></div>++ <div class="scheduler-details-label">Last Updated:</div>+ <div class="scheduler-details-value"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.formatDate($store.schedulerStore.selectedTaskForDetail.updated_at) : ''"></div>++ <div class="scheduler-details-label">Last Run:</div>+ <div class="scheduler-details-value"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.formatDate($store.schedulerStore.selectedTaskForDetail.last_run) : ''"></div>++ <div class="scheduler-details-label"+ x-show="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.type === 'scheduled'">+ Schedule:</div>+ <div class="scheduler-details-value"+ x-show="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.type === 'scheduled'"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.formatSchedule($store.schedulerStore.selectedTaskForDetail) : ''">+ </div>++ <div class="scheduler-details-label"+ x-show="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.type === 'adhoc'">+ Token:</div>+ <div class="scheduler-details-value"+ x-show="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.type === 'adhoc'"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.selectedTaskForDetail.token : ''"></div>++ <div class="scheduler-details-label"+ x-show="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.type === 'planned'">+ Plan:</div>+ <div class="scheduler-details-value"+ x-show="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.type === 'planned'">+ <div x-show="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.plan">+ <div><strong>Upcoming:</strong></div>+ <template x-if="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.plan && $store.schedulerStore.selectedTaskForDetail.plan.todo && $store.schedulerStore.selectedTaskForDetail.plan.todo.length > 0">+ <div>+ <template x-for="(time, index) in $store.schedulerStore.selectedTaskForDetail.plan.todo" :key="index">+ <div x-text="$store.schedulerStore.formatDate(time)"></div>+ </template>+ </div>+ </template>+ <template x-if="!$store.schedulerStore.selectedTaskForDetail || !$store.schedulerStore.selectedTaskForDetail.plan || !$store.schedulerStore.selectedTaskForDetail.plan.todo || $store.schedulerStore.selectedTaskForDetail.plan.todo.length === 0">+ <div>No upcoming executions</div>+ </template>++ <div><strong>In Progress:</strong></div>+ <div+ x-text="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.plan && $store.schedulerStore.selectedTaskForDetail.plan.in_progress ? $store.schedulerStore.formatDate($store.schedulerStore.selectedTaskForDetail.plan.in_progress) : 'None'"></div>++ <div><strong>Completed:</strong></div>+ <template x-if="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.plan && $store.schedulerStore.selectedTaskForDetail.plan.done && $store.schedulerStore.selectedTaskForDetail.plan.done.length > 0">+ <div>+ <template x-for="(time, index) in $store.schedulerStore.selectedTaskForDetail.plan.done" :key="index">+ <div x-text="$store.schedulerStore.formatDate(time)"></div>+ </template>+ </div>+ </template>+ <template x-if="!$store.schedulerStore.selectedTaskForDetail || !$store.schedulerStore.selectedTaskForDetail.plan || !$store.schedulerStore.selectedTaskForDetail.plan.done || $store.schedulerStore.selectedTaskForDetail.plan.done.length === 0">+ <div>No completed executions</div>+ </template>+ </div>+ </div>++ <div class="scheduler-details-label">Last Result:</div>+ <div class="scheduler-details-value"+ x-text="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.last_result ? $store.schedulerStore.selectedTaskForDetail.last_result : 'No results yet'"></div>++ <div class="scheduler-details-label">System Prompt:</div>+ <div class="scheduler-details-value"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.selectedTaskForDetail.system_prompt : ''"></div>++ <div class="scheduler-details-label">User Prompt:</div>+ <div class="scheduler-details-value"+ x-text="$store.schedulerStore.selectedTaskForDetail ? $store.schedulerStore.selectedTaskForDetail.prompt : ''"></div>++ <div class="scheduler-details-label">Attachments:</div>+ <div class="scheduler-details-value">+ <template x-if="$store.schedulerStore.selectedTaskForDetail && $store.schedulerStore.selectedTaskForDetail.attachments && $store.schedulerStore.selectedTaskForDetail.attachments.length > 0">+ <div>+ <template x-for="(attachment, index) in $store.schedulerStore.selectedTaskForDetail.attachments" :key="index">+ <div x-text="attachment"></div>+ </template>+ </div>+ </template>+ <template x-if="!$store.schedulerStore.selectedTaskForDetail || !$store.schedulerStore.selectedTaskForDetail.attachments || $store.schedulerStore.selectedTaskForDetail.attachments.length === 0">+ <div>No attachments</div>+ </template>+ </div>+ </div>+ </div>+ </div>+ </template>+</div>+</body>+</html>diff --git a/webui/components/settings/scheduler/scheduler-task-editor.html b/webui/components/settings/scheduler/scheduler-task-editor.htmlnew file mode 100644index 000000000..cc9b2e5f1--- /dev/null+++ b/webui/components/settings/scheduler/scheduler-task-editor.html@@ -0,0 +1,439 @@+<html>+<head>+ <script type="module">+ import { store } from "/components/settings/scheduler/scheduler-store.js";+ </script>+</head>+<body>+<div x-data>+ <template x-if="$store.schedulerStore">+ <div>+ <!-- Create Task Form -->+ <div class="scheduler-form" x-show="$store.schedulerStore.isCreating">+ <div class="scheduler-form-header">+ <div class="scheduler-form-title">Create New Task</div>+ <div class="scheduler-form-actions">+ <button class="btn btn-ok btn-field" @click="$store.schedulerStore.saveTask()">+ Save+ </button>+ <button class="btn btn-cancel" @click="$store.schedulerStore.cancelEdit()">+ Cancel+ </button>+ </div>+ </div>++ <div class="scheduler-form-grid">+ <div class="scheduler-form-field">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Task Name</label>+ <div class="scheduler-form-help">A unique name to identify this task</div>+ </div>+ <input type="text" x-model="$store.schedulerStore.editingTask.name" placeholder="Enter task name">+ </div>++ <div class="scheduler-form-field">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Type</label>+ <div class="scheduler-form-help">Task execution method</div>+ </div>+ <select x-model="$store.schedulerStore.editingTask.type">+ <option value="scheduled">Scheduled (Cron)</option>+ <option value="adhoc">Ad-hoc (Manual)</option>+ <option value="planned">Planned (Specific Times)</option>+ </select>+ </div>++ <div class="scheduler-form-field">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Project</label>+ <div class="scheduler-form-help"+ x-text="$store.schedulerStore.editingTask.dedicated_context ? 'Inherited from the active chat project.' : 'Mirrors the shared context project.'"></div>+ </div>+ <div class="project-selector">+ <select class="scheduler-project-select"+ x-model="$store.schedulerStore.selectedProjectSlug"+ @change="$store.schedulerStore.onProjectSelect($event.target.value)">+ <option value="">No project</option>+ <template x-for="proj in $store.schedulerStore.projectOptions" :key="proj.name">+ <option :value="proj.name" x-text="proj.title"></option>+ </template>+ </select>+ </div>+ </div>++ <div class="scheduler-form-field" x-show="$store.schedulerStore.isCreating">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">State</label>+ <div class="scheduler-form-help">Select the initial state of the task</div>+ </div>+ <div>+ <div class="scheduler-state-selector">+ <span class="scheduler-status-badge scheduler-status-idle"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'idle'}"+ @click="$store.schedulerStore.editingTask.state = 'idle'">idle</span>+ <span class="scheduler-status-badge scheduler-status-running"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'running'}"+ @click="$store.schedulerStore.editingTask.state = 'running'">running</span>+ <span class="scheduler-status-badge scheduler-status-disabled"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'disabled'}"+ @click="$store.schedulerStore.editingTask.state = 'disabled'">disabled</span>+ <span class="scheduler-status-badge scheduler-status-error"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'error'}"+ @click="$store.schedulerStore.editingTask.state = 'error'">error</span>+ </div>+ <div class="scheduler-state-explanation">+ <span x-show="$store.schedulerStore.editingTask.state === 'idle'"><strong>idle</strong>: ready to run</span>+ <span x-show="$store.schedulerStore.editingTask.state === 'running'"><strong>running</strong>: currently executing</span>+ <span x-show="$store.schedulerStore.editingTask.state === 'disabled'"><strong>disabled</strong>: won't execute automatically</span>+ <span x-show="$store.schedulerStore.editingTask.state === 'error'"><strong>error</strong>: task encountered an error</span>+ </div>+ </div>+ </div>++ <div class="scheduler-form-field full-width"+ x-show="$store.schedulerStore.editingTask.type === 'scheduled'">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Schedule</label>+ <div class="scheduler-form-help">Cron schedule for automated execution (minute hour day month weekday)</div>+ </div>+ <div class="scheduler-schedule-builder">+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Minute</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.minute"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Hour</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.hour"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Day</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.day"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Month</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.month"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Weekday</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.weekday"+ placeholder="*" maxlength="9">+ </div>+ </div>+ </div>++ <div class="scheduler-form-field full-width"+ x-show="$store.schedulerStore.editingTask.type === 'planned'"+ x-effect="if ($store.schedulerStore.isCreating && $store.schedulerStore.editingTask.type === 'planned') { $store.schedulerStore.initFlatpickr('create') }">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Plan</label>+ <div class="scheduler-form-help">Specific execution times for this task</div>+ </div>+ <div class="scheduler-plan-builder">+ <div class="scheduler-plan-todo">+ <span class="scheduler-plan-label">Upcoming Executions</span>+ <div class="scheduler-todo-list">+ <template x-if="$store.schedulerStore.editingTask.plan && Array.isArray($store.schedulerStore.editingTask.plan.todo) && $store.schedulerStore.editingTask.plan.todo.length > 0">+ <template x-for="(time, index) in $store.schedulerStore.editingTask.plan.todo" :key="index">+ <div class="scheduler-todo-item">+ <span x-text="$store.schedulerStore.formatDate(time)"></span>+ <button @click.prevent="$store.schedulerStore.editingTask.plan.todo.splice(index, 1)"+ class="scheduler-todo-remove">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"+ fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"+ stroke-linejoin="round">+ <line x1="18" y1="6" x2="6" y2="18"></line>+ <line x1="6" y1="6" x2="18" y2="18"></line>+ </svg>+ </button>+ </div>+ </template>+ </template>+ <template x-if="!$store.schedulerStore.editingTask.plan || !$store.schedulerStore.editingTask.plan.todo || $store.schedulerStore.editingTask.plan.todo.length === 0">+ <div class="scheduler-empty-plan">+ No scheduled execution times yet. Add one below.+ </div>+ </template>+ <div class="scheduler-add-todo">+ <input type="text" id="newPlannedTime-create"+ class="scheduler-flatpickr-input"+ placeholder="Select date and time">+ <button @click.prevent="$store.schedulerStore.addPlannedTime('create')"+ class="scheduler-add-todo-button">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"+ fill="none" stroke="currentColor" stroke-width="2"+ stroke-linecap="round" stroke-linejoin="round"+ style="margin-right: 4px;">+ <line x1="12" y1="5" x2="12" y2="19"></line>+ <line x1="5" y1="12" x2="19" y2="12"></line>+ </svg>+ Add Time+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>++ <div class="scheduler-form-field full-width"+ x-show="$store.schedulerStore.editingTask.type === 'adhoc'">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Token</label>+ <div class="scheduler-form-help">Token used to trigger this task externally</div>+ </div>+ <div class="input-group">+ <input type="text" x-model="$store.schedulerStore.editingTask.token"+ placeholder="Token for ad-hoc task">+ <button class="scheduler-task-action"+ @click="$store.schedulerStore.editingTask.token = $store.schedulerStore.generateRandomToken()">+ Generate+ </button>+ </div>+ </div>++ <div class="scheduler-form-field full-width">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">System Prompt</label>+ <div class="scheduler-form-help">System-level instructions for the assistant</div>+ </div>+ <textarea x-model="$store.schedulerStore.editingTask.system_prompt"+ placeholder="System instructions for the AI"></textarea>+ </div>++ <div class="scheduler-form-field full-width">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">User Prompt</label>+ <div class="scheduler-form-help">The main task prompt that will be executed</div>+ </div>+ <textarea x-model="$store.schedulerStore.editingTask.prompt"+ placeholder="User message for the AI"></textarea>+ </div>++ <div class="scheduler-form-field full-width">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Attachments</label>+ <div class="scheduler-form-help">Container file paths or URLs, one per line</div>+ </div>+ <textarea x-model="$store.schedulerStore.attachmentsText"+ placeholder="Enter file paths or URLs, one per line"></textarea>+ </div>+ </div>+ </div>++ <!-- Edit Task Form -->+ <div class="scheduler-form" x-show="$store.schedulerStore.isEditing">+ <div class="scheduler-form-header">+ <div class="scheduler-form-title">Edit Task</div>+ <div class="scheduler-form-actions">+ <button class="btn btn-ok btn-field" @click="$store.schedulerStore.saveTask()">+ Save+ </button>+ <button class="btn btn-cancel" @click="$store.schedulerStore.cancelEdit()">+ Cancel+ </button>+ </div>+ </div>++ <div class="scheduler-form-grid">+ <div class="scheduler-form-field">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Task Name</label>+ <div class="scheduler-form-help">A unique name to identify this task</div>+ </div>+ <input type="text" x-model="$store.schedulerStore.editingTask.name" placeholder="Enter task name">+ </div>++ <div class="scheduler-form-field">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Task Type</label>+ <div class="scheduler-form-help">Task type cannot be changed after creation</div>+ </div>+ <select x-model="$store.schedulerStore.editingTask.type" disabled>+ <option value="scheduled">Scheduled Task</option>+ <option value="adhoc">Ad-hoc Task</option>+ <option value="planned">Planned Task</option>+ </select>+ </div>++ <div class="scheduler-form-field">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Project</label>+ <div class="scheduler-form-help"+ x-text="$store.schedulerStore.editingTask.dedicated_context ? 'Dedicated tasks inherit the active chat project.' : 'Shared tasks mirror the project assigned to their context.'"></div>+ </div>+ <div class="project-display">+ <span class="project-color-ball"+ :style="$store.schedulerStore.editingTask.project?.color ? { backgroundColor: $store.schedulerStore.editingTask.project.color } : { border: '1px solid var(--color-border)' }"></span>+ <span x-text="$store.schedulerStore.formatProjectLabel($store.schedulerStore.editingTask.project)"></span>+ </div>+ </div>++ <div class="scheduler-form-field" x-show="$store.schedulerStore.isEditing">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">State</label>+ <div class="scheduler-form-help">Change the task's state</div>+ </div>+ <div>+ <div class="scheduler-state-selector">+ <span class="scheduler-status-badge scheduler-status-idle"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'idle'}"+ @click="$store.schedulerStore.editingTask.state = 'idle'">idle</span>+ <span class="scheduler-status-badge scheduler-status-running"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'running'}"+ @click="$store.schedulerStore.editingTask.state = 'running'">running</span>+ <span class="scheduler-status-badge scheduler-status-disabled"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'disabled'}"+ @click="$store.schedulerStore.editingTask.state = 'disabled'">disabled</span>+ <span class="scheduler-status-badge scheduler-status-error"+ :class="{'scheduler-status-selected': $store.schedulerStore.editingTask.state === 'error'}"+ @click="$store.schedulerStore.editingTask.state = 'error'">error</span>+ </div>+ <div class="scheduler-state-explanation">+ <span x-show="$store.schedulerStore.editingTask.state === 'idle'"><strong>idle</strong>: ready to run</span>+ <span x-show="$store.schedulerStore.editingTask.state === 'running'"><strong>running</strong>: currently executing</span>+ <span x-show="$store.schedulerStore.editingTask.state === 'disabled'"><strong>disabled</strong>: won't execute automatically</span>+ <span x-show="$store.schedulerStore.editingTask.state === 'error'"><strong>error</strong>: task encountered an error</span>+ </div>+ </div>+ </div>++ <div class="scheduler-form-field full-width"+ x-show="$store.schedulerStore.editingTask && $store.schedulerStore.editingTask.type === 'scheduled'">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Schedule (Cron Expression)</label>+ <div class="scheduler-form-help">Format: minute hour day month weekday (e.g., "* * * * *" for every minute)</div>+ </div>+ <div class="scheduler-schedule-builder">+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Minute</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.minute"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Hour</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.hour"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Day</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.day"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Month</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.month"+ placeholder="*" maxlength="9">+ </div>+ <div class="scheduler-schedule-field">+ <span class="scheduler-schedule-label">Weekday</span>+ <input type="text" x-model="$store.schedulerStore.editingTask.schedule.weekday"+ placeholder="*" maxlength="9">+ </div>+ </div>+ </div>++ <div class="scheduler-form-field full-width"+ x-show="$store.schedulerStore.editingTask.type === 'planned'"+ x-effect="if ($store.schedulerStore.isEditing && $store.schedulerStore.editingTask.type === 'planned') { $store.schedulerStore.initFlatpickr('edit') }">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Plan</label>+ <div class="scheduler-form-help">Specific execution times for this task</div>+ </div>+ <div class="scheduler-plan-builder">+ <div class="scheduler-plan-todo">+ <span class="scheduler-plan-label">Upcoming Executions</span>+ <div class="scheduler-todo-list">+ <template x-if="$store.schedulerStore.editingTask.plan && Array.isArray($store.schedulerStore.editingTask.plan.todo) && $store.schedulerStore.editingTask.plan.todo.length > 0">+ <template x-for="(time, index) in $store.schedulerStore.editingTask.plan.todo" :key="index">+ <div class="scheduler-todo-item">+ <span x-text="$store.schedulerStore.formatDate(time)"></span>+ <button @click.prevent="$store.schedulerStore.editingTask.plan.todo.splice(index, 1)"+ class="scheduler-todo-remove">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"+ fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"+ stroke-linejoin="round">+ <line x1="18" y1="6" x2="6" y2="18"></line>+ <line x1="6" y1="6" x2="18" y2="18"></line>+ </svg>+ </button>+ </div>+ </template>+ </template>+ <template x-if="!$store.schedulerStore.editingTask.plan || !$store.schedulerStore.editingTask.plan.todo || $store.schedulerStore.editingTask.plan.todo.length === 0">+ <div class="scheduler-empty-plan">+ No scheduled execution times yet. Add one below.+ </div>+ </template>+ <div class="scheduler-add-todo">+ <input type="text" id="newPlannedTime-edit"+ class="scheduler-flatpickr-input"+ placeholder="Select date and time">+ <button @click.prevent="$store.schedulerStore.addPlannedTime('edit')"+ class="scheduler-add-todo-button">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"+ fill="none" stroke="currentColor" stroke-width="2"+ stroke-linecap="round" stroke-linejoin="round"+ style="margin-right: 4px;">+ <line x1="12" y1="5" x2="12" y2="19"></line>+ <line x1="5" y1="12" x2="19" y2="12"></line>+ </svg>+ Add Time+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>++ <div class="scheduler-form-field full-width"+ x-show="$store.schedulerStore.editingTask.type === 'adhoc'">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Token</label>+ <div class="scheduler-form-help">Token used to trigger this task externally</div>+ </div>+ <div class="input-group">+ <input type="text" x-model="$store.schedulerStore.editingTask.token"+ placeholder="Token for ad-hoc task">+ <button class="scheduler-task-action"+ @click="$store.schedulerStore.editingTask.token = $store.schedulerStore.generateRandomToken()">+ Generate+ </button>+ </div>+ </div>++ <div class="scheduler-form-field full-width">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">System Prompt</label>+ <div class="scheduler-form-help">System-level instructions for the assistant</div>+ </div>+ <textarea x-model="$store.schedulerStore.editingTask.system_prompt"+ placeholder="System instructions for the AI"></textarea>+ </div>++ <div class="scheduler-form-field full-width">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">User Prompt</label>+ <div class="scheduler-form-help">The main task prompt that will be executed</div>+ </div>+ <textarea x-model="$store.schedulerStore.editingTask.prompt"+ placeholder="User message for the AI"></textarea>+ </div>++ <div class="scheduler-form-field full-width">+ <div class="label-help-wrapper">+ <label class="scheduler-form-label">Attachments</label>+ <div class="scheduler-form-help">Container file paths or URLs, one per line</div>+ </div>+ <textarea x-model="$store.schedulerStore.attachmentsText"+ placeholder="Enter file paths or URLs, one per line"></textarea>+ </div>+ </div>+ </div>+ </div>+ </template>+</div>+</body>+</html>diff --git a/webui/components/settings/scheduler/scheduler-task-list.html b/webui/components/settings/scheduler/scheduler-task-list.htmlnew file mode 100644index 000000000..0d60e45a9--- /dev/null+++ b/webui/components/settings/scheduler/scheduler-task-list.html@@ -0,0 +1,146 @@+<html>+<head>+ <script type="module">+ import { store } from "/components/settings/scheduler/scheduler-store.js";+ </script>+</head>+<body>+<div x-data>+ <template x-if="$store.schedulerStore">+ <div class="scheduler-container"+ x-show="!$store.schedulerStore.isCreating && !$store.schedulerStore.isEditing">+ <div class="scheduler-header">+ <h2>Task Management</h2>+ <div class="scheduler-actions">+ <button class="btn btn-ok" @click="$store.schedulerStore.startCreateTask()">+ New Task+ </button>+ </div>+ </div>++ <div class="scheduler-filters">+ <div class="scheduler-filter-group">+ <span class="scheduler-filter-label">Type:</span>+ <select class="scheduler-filter-select" x-model="$store.schedulerStore.filterType">+ <option value="all">All Types</option>+ <option value="scheduled">Scheduled</option>+ <option value="adhoc">Ad-hoc</option>+ <option value="planned">Planned</option>+ </select>+ </div>++ <div class="scheduler-filter-group">+ <span class="scheduler-filter-label">State:</span>+ <select class="scheduler-filter-select" x-model="$store.schedulerStore.filterState">+ <option value="all">All States</option>+ <option value="idle">Idle</option>+ <option value="running">Running</option>+ <option value="disabled">Disabled</option>+ <option value="error">Error</option>+ </select>+ </div>+ </div>++ <div class="scheduler-empty"+ x-show="!$store.schedulerStore.isLoading && $store.schedulerStore.filteredTasks.length === 0"+ x-effect="$el.style.display = (!$store.schedulerStore.isLoading && $store.schedulerStore.filteredTasks.length === 0) ? '' : 'none'">+ <div class="scheduler-empty-text">No tasks found</div>+ <button class="btn btn-ok" @click="$store.schedulerStore.startCreateTask()">Create your first task</button>+ </div>++ <table class="scheduler-task-list"+ x-show="!$store.schedulerStore.isLoading && $store.schedulerStore.filteredTasks.length > 0"+ x-effect="$el.style.display = (!$store.schedulerStore.isLoading && $store.schedulerStore.filteredTasks.length > 0) ? '' : 'none'">+ <thead>+ <tr>+ <th @click="$store.schedulerStore.changeSort('name')">+ Name+ <span class="scheduler-sort-indicator"+ x-show="$store.schedulerStore.sortField === 'name'"+ :class="{'scheduler-sort-desc': $store.schedulerStore.sortDirection === 'desc'}">↑</span>+ </th>+ <th @click="$store.schedulerStore.changeSort('state')">+ State+ <span class="scheduler-sort-indicator"+ x-show="$store.schedulerStore.sortField === 'state'"+ :class="{'scheduler-sort-desc': $store.schedulerStore.sortDirection === 'desc'}">↑</span>+ </th>+ <th>Type</th>+ <th>Project</th>+ <th>Schedule</th>+ <th @click="$store.schedulerStore.changeSort('last_run')">+ Last Run+ <span class="scheduler-sort-indicator"+ x-show="$store.schedulerStore.sortField === 'last_run'"+ :class="{'scheduler-sort-desc': $store.schedulerStore.sortDirection === 'desc'}">↑</span>+ </th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ <template x-for="task in $store.schedulerStore.filteredTasks" :key="task.uuid">+ <tr @click="$store.schedulerStore.showTaskDetail(task.uuid)">+ <td>+ <span x-text="task.name"></span>+ </td>+ <td>+ <span class="scheduler-status-badge"+ :class="$store.schedulerStore.getStateBadgeClass(task.state)"+ x-text="task.state"></span>+ </td>+ <td x-text="task.type"></td>+ <td>+ <span class="project-color-ball"+ :style="$store.schedulerStore.extractTaskProject(task)?.color ? { backgroundColor: $store.schedulerStore.extractTaskProject(task).color } : { border: '1px solid var(--color-border)' }"></span>+ <span x-text="$store.schedulerStore.formatTaskProject(task)"></span>+ </td>+ <td>+ <span x-show="task.type === 'scheduled'"+ x-text="$store.schedulerStore.formatSchedule(task)"></span>+ <span x-show="task.type === 'adhoc'"+ class="scheduler-no-schedule">—</span>+ <span x-show="task.type === 'planned'"+ x-html="$store.schedulerStore.formatPlan(task).replace(/\n/g, '<br>')"></span>+ </td>+ <td x-text="$store.schedulerStore.formatDate(task.last_run)"></td>+ <td @click.stop>+ <div class="scheduler-task-actions">+ <button class="scheduler-task-action"+ @click="$store.schedulerStore.runTask(task.uuid)" title="Run Task">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="16"+ height="16">+ <path d="M8 5v14l11-7z"/>+ </svg>+ </button>+ <button class="scheduler-task-action"+ @click="$store.schedulerStore.resetTaskState(task.uuid)" title="Reset State">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="16"+ height="16">+ <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>+ </svg>+ </button>+ <button class="scheduler-task-action"+ @click="$store.schedulerStore.startEditTask(task.uuid)" title="Edit Task">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="16"+ height="16">+ <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>+ </svg>+ </button>+ <button class="scheduler-task-action"+ @click="$store.schedulerStore.deleteTask(task.uuid)" title="Delete Task">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="16"+ height="16">+ <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>+ </svg>+ </button>+ </div>+ </td>+ </tr>+ </template>+ </tbody>+ </table>+ </div>+ </template>+</div>+</body>+</html>diff --git a/webui/components/settings/settings-store.js b/webui/components/settings/settings-store.jsnew file mode 100644index 000000000..98d13f41e--- /dev/null+++ b/webui/components/settings/settings-store.js@@ -0,0 +1,255 @@+import { createStore } from "/js/AlpineStore.js";+import * as API from "/js/api.js";+import { store as notificationStore } from "/components/notifications/notification-store.js";+import { store as schedulerStore } from "/components/settings/scheduler/scheduler-store.js";++// Constants+const VIEW_MODE_STORAGE_KEY = "settingsActiveTab";+const DEFAULT_TAB = "agent";++// Helper for toasts+function toast(text, type = "info", timeout = 5000) {+ notificationStore.addFrontendToastOnly(type, text, "", timeout / 1000);+}++// Settings Store+const model = {+ // State+ isLoading: false,+ error: null,+ settings: null,+ sectionsById: {},++ // Tab state+ _activeTab: DEFAULT_TAB,+ get activeTab() {+ return this._activeTab;+ },+ set activeTab(value) {+ const previous = this._activeTab;+ this._activeTab = value;+ this.applyActiveTab(previous, value);+ },++ // Lifecycle+ init() {+ // Restore persisted tab+ try {+ const saved = localStorage.getItem(VIEW_MODE_STORAGE_KEY);+ if (saved) this._activeTab = saved;+ } catch {}+ },++ async onOpen() {+ this.error = null;+ this.isLoading = true;++ try {+ const response = await API.callJsonApi("settings_get", null);+ if (response && response.settings) {+ this.settings = response.settings;+ this.rebuildSectionsIndex();+ } else {+ throw new Error("Invalid settings response");+ }+ } catch (e) {+ console.error("Failed to load settings:", e);+ this.error = e.message || "Failed to load settings";+ toast("Failed to load settings", "error");+ } finally {+ this.isLoading = false;+ }++ // Trigger tab activation for current tab+ this.applyActiveTab(null, this._activeTab);+ },++ cleanup() {+ // Notify scheduler if it was active+ if (this._activeTab === "scheduler") {+ schedulerStore.onTabDeactivated?.();+ }+ schedulerStore.onModalClosed?.();++ this.settings = null;+ this.sectionsById = {};+ this.error = null;+ this.isLoading = false;+ },++ // Tab management+ applyActiveTab(previous, current) {+ // Persist+ try {+ localStorage.setItem(VIEW_MODE_STORAGE_KEY, current);+ } catch {}++ // Scheduler lifecycle+ if (previous === "scheduler" && current !== "scheduler") {+ schedulerStore.onTabDeactivated?.();+ }+ if (current === "scheduler" && previous !== "scheduler") {+ schedulerStore.onTabActivated?.();+ }+ },++ switchTab(tabName) {+ this.activeTab = tabName;+ },++ // Computed: sections for current tab+ get filteredSections() {+ if (!this.settings || !this.settings.sections) return [];+ const sections = this.settings.sections.filter(+ (section) => section.tab === this._activeTab+ );+ return sections;+ },++ rebuildSectionsIndex() {+ const map = {};+ if (this.settings && Array.isArray(this.settings.sections)) {+ for (const section of this.settings.sections) {+ if (section && section.id) {+ map[section.id] = section;+ }+ }+ }+ this.sectionsById = map;+ },++ getSectionById(sectionId) {+ if (!sectionId) return null;+ return this.sectionsById[sectionId] || null;+ },++ // Save settings+ async saveSettings() {+ if (!this.settings) {+ toast("No settings to save", "warning");+ return false;+ }++ this.isLoading = true;+ try {+ const response = await API.callJsonApi("settings_set", this.settings);+ if (response && response.settings) {+ this.settings = response.settings;+ this.rebuildSectionsIndex();+ toast("Settings saved successfully", "success");+ document.dispatchEvent(+ new CustomEvent("settings-updated", { detail: response.settings })+ );+ return true;+ } else {+ throw new Error("Failed to save settings");+ }+ } catch (e) {+ console.error("Failed to save settings:", e);+ toast("Failed to save settings: " + e.message, "error");+ return false;+ } finally {+ this.isLoading = false;+ }+ },++ // Close the modal+ closeSettings() {+ window.closeModal("settings/settings.html");+ },++ // Save and close+ async saveAndClose() {+ const success = await this.saveSettings();+ if (success) {+ this.closeSettings();+ }+ },++ // Field helpers for external components+ getField(sectionId, fieldId) {+ if (!this.settings || !this.settings.sections) return null;+ for (const section of this.settings.sections) {+ if (section.id === sectionId) {+ for (const field of section.fields) {+ if (field.id === fieldId) {+ return field;+ }+ }+ }+ }+ return null;+ },++ setFieldValue(sectionId, fieldId, value) {+ const field = this.getField(sectionId, fieldId);+ if (field) {+ field.value = value;+ return true;+ }+ return false;+ },++ findFieldValue(fieldId) {+ if (!this.settings || !this.settings.sections) return null;+ for (const section of this.settings.sections) {+ for (const field of section.fields) {+ if (field.id === fieldId) {+ return field.value;+ }+ }+ }+ return null;+ },++ // Handle button field clicks (opens sub-modals)+ async handleFieldButton(field) {+ if (field.id === "mcp_servers_config") {+ window.openModal("settings/mcp/client/mcp-servers.html");+ } else if (field.id === "backup_create") {+ window.openModal("settings/backup/backup.html");+ } else if (field.id === "backup_restore") {+ window.openModal("settings/backup/restore.html");+ } else if (field.id === "show_a2a_connection") {+ window.openModal("settings/a2a/a2a-connection.html");+ } else if (field.id === "external_api_examples") {+ window.openModal("settings/external/api-examples.html");+ } else if (field.id === "memory_dashboard") {+ window.openModal("settings/memory/memory-dashboard.html");+ }+ },++ // Open settings modal from external callers+ async open(initialTab = null) {+ if (initialTab) {+ this._activeTab = initialTab;+ }+ await window.openModal("settings/settings.html");+ },++ // Scheduler integration: open Settings modal, switch to scheduler tab, show task detail+ async openSchedulerTaskDetail(taskId) {+ // Set tab to scheduler before opening+ this._activeTab = "scheduler";++ // Open the modal (do NOT await - openModal resolves on close)+ window.openModal("settings/settings.html");++ // Ensure scheduler tasks are loaded, then show the detail modal+ setTimeout(async () => {+ try {+ if (typeof schedulerStore.fetchTasks === "function") {+ await schedulerStore.fetchTasks({ manual: true });+ }+ schedulerStore.showTaskDetail?.(taskId);+ } catch (error) {+ console.warn("[settings-store] openSchedulerTaskDetail failed", error);+ }+ }, 200);+ },+};++const store = createStore("settingsStore", model);++export { store };+diff --git a/webui/components/settings/settings.html b/webui/components/settings/settings.htmlnew file mode 100644index 000000000..8e5ac124d--- /dev/null+++ b/webui/components/settings/settings.html@@ -0,0 +1,146 @@+<html>+<head>+ <title>Settings</title>+</head>++<body>+<script type="module">+ import { store as settingsStore } from "/components/settings/settings-store.js";+</script>++<div x-data>+ <template x-if="$store.settingsStore">+ <div x-init="$store.settingsStore.onOpen()" x-destroy="$store.settingsStore.cleanup()">++ <!-- Loading state -->+ <div x-show="$store.settingsStore.isLoading && !$store.settingsStore.settings" class="settings-loading">+ <span class="material-symbols-outlined spinning">progress_activity</span>+ <span>Loading settings...</span>+ </div>++ <!-- Error state -->+ <div x-show="$store.settingsStore.error && !$store.settingsStore.settings" class="settings-error">+ <span class="material-symbols-outlined">error</span>+ <span x-text="$store.settingsStore.error"></span>+ <button class="btn btn-retry" @click="$store.settingsStore.onOpen()">Retry</button>+ </div>++ <!-- Settings content -->+ <div x-show="$store.settingsStore.settings" class="settings-content">+ <!-- Tab Navigation -->+ <div class="settings-tabs-container">+ <div class="settings-tabs">+ <div class="settings-tab"+ :class="{'active': $store.settingsStore.activeTab === 'agent'}"+ @click="$store.settingsStore.switchTab('agent')"+ title="Agent Settings">Agent Settings</div>+ <div class="settings-tab"+ :class="{'active': $store.settingsStore.activeTab === 'external'}"+ @click="$store.settingsStore.switchTab('external')"+ title="External Services">External Services</div>+ <div class="settings-tab"+ :class="{'active': $store.settingsStore.activeTab === 'mcp'}"+ @click="$store.settingsStore.switchTab('mcp')"+ title="MCP">MCP/A2A</div>+ <div class="settings-tab"+ :class="{'active': $store.settingsStore.activeTab === 'developer'}"+ @click="$store.settingsStore.switchTab('developer')"+ title="Developer">Developer</div>+ <div class="settings-tab"+ :class="{'active': $store.settingsStore.activeTab === 'scheduler'}"+ @click="$store.settingsStore.switchTab('scheduler')"+ title="Task Scheduler">Task Scheduler</div>+ <div class="settings-tab"+ :class="{'active': $store.settingsStore.activeTab === 'backup'}"+ @click="$store.settingsStore.switchTab('backup')"+ title="Backup & Restore">Backup & Restore</div>+ </div>+ </div>++ <!-- Settings sections for agent, external, developer, mcp, backup tabs -->+ <div id="settings-sections" x-show="$store.settingsStore.activeTab !== 'scheduler'">+ <template x-if="$store.settingsStore.activeTab === 'agent'">+ <x-component path="settings/agent/agent-settings.html"></x-component>+ </template>+ <template x-if="$store.settingsStore.activeTab === 'external'">+ <x-component path="settings/external/external-settings.html"></x-component>+ </template>+ <template x-if="$store.settingsStore.activeTab === 'mcp'">+ <x-component path="settings/mcp/mcp-settings.html"></x-component>+ </template>+ <template x-if="$store.settingsStore.activeTab === 'developer'">+ <x-component path="settings/developer/developer-settings.html"></x-component>+ </template>+ <template x-if="$store.settingsStore.activeTab === 'backup'">+ <x-component path="settings/backup/backup-settings.html"></x-component>+ </template>+ </div>++ <!-- Task Scheduler Tab Content -->+ <template x-if="$store.settingsStore.activeTab === 'scheduler'">+ <div id="scheduler-tab-content">+ <x-component path="settings/scheduler/scheduler-settings.html"></x-component>+ </div>+ </template>+ </div>++ </div>+ </template>+</div>++<!-- Modal footer via data-modal-footer -->+<div data-modal-footer>+ <button class="btn btn-ok"+ @click="$store.settingsStore.saveSettings()"+ :disabled="$store.settingsStore?.isLoading">+ Save+ </button>+ <button class="btn btn-cancel"+ @click="$store.settingsStore.closeSettings()">+ Cancel+ </button>+</div>+</body>+</html>++<style>+.settings-loading,+.settings-error {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 0.75rem;+ padding: 2rem;+ color: var(--color-text-secondary, #999);+ font-size: 1rem;+}++.settings-error {+ flex-direction: column;+ color: var(--color-error, #e74c3c);+}++.settings-error .material-symbols-outlined {+ font-size: 2rem;+}++.settings-error .btn-retry {+ margin-top: 1rem;+}++.settings-content {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.spinning {+ animation: spin 1s linear infinite;+}++@keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+}+</style>+diff --git a/webui/components/sidebar/tasks/tasks-store.js b/webui/components/sidebar/tasks/tasks-store.jsindex f014207f0..bedacd27f 100644--- a/webui/components/sidebar/tasks/tasks-store.js+++ b/webui/components/sidebar/tasks/tasks-store.js@@ -1,5 +1,7 @@import { createStore } from "/js/AlpineStore.js";import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";+import { store as schedulerStore } from "/components/settings/scheduler/scheduler-store.js";+import { store as settingsStore } from "/components/settings/settings-store.js";// Tasks sidebar store: tasks list and selected task idconst model = {@@ -50,8 +52,9 @@ const model = {},openDetail(taskId) {- if (globalThis.openTaskDetail) {- globalThis.openTaskDetail(taskId);+ // Use the new settings modal store to open scheduler task detail+ if (settingsStore?.openSchedulerTaskDetail) {+ settingsStore.openSchedulerTaskDetail(taskId);}},@@ -60,8 +63,8 @@ const model = {},deleteTask(taskId) {- if (globalThis.deleteTaskGlobal) {- globalThis.deleteTaskGlobal(taskId);+ if (schedulerStore?.deleteTaskFromSidebar) {+ schedulerStore.deleteTaskFromSidebar(taskId);}},};diff --git a/webui/components/sidebar/top-section/quick-actions.html b/webui/components/sidebar/top-section/quick-actions.htmlindex a4d76e147..8b807e9ec 100644--- a/webui/components/sidebar/top-section/quick-actions.html+++ b/webui/components/sidebar/top-section/quick-actions.html@@ -3,6 +3,9 @@<head><script type="module">import { store } from "/components/sidebar/chats/chats-store.js";+ import { store as settingsStore } from "/components/settings/settings-store.js";+ // Expose for Alpine template access+ globalThis.openSettingsModal = () => settingsStore.open();</script></head>@@ -13,7 +16,7 @@<button class="config-button" id="loadChats" @click="$store.chats.loadChats()">Load Chat</button><button class="config-button" id="loadChat" @click="$store.chats.saveChat()">Save Chat</button><button class="config-button" id="restart" @click="$store.chats.restart()">Restart</button>- <button class="config-button" id="settings" @click="settingsModalProxy.openModal()"><svg+ <button class="config-button" id="settings" @click="openSettingsModal()"><svgxmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="-5.0 -17.0 110.0 135.0" fill="currentColor" width="24"height="24"><pathdiff --git a/webui/index.html b/webui/index.htmlindex 82abf4b59..0fb7ef0a2 100644--- a/webui/index.html+++ b/webui/index.html@@ -27,76 +27,6 @@}</script>- <!-- Pre-initialize schedulerSettings to ensure Alpine doesn't miss it -->- <script>- // Pre-define schedulerSettings skeleton to ensure it's available to Alpine- globalThis.schedulerSettings = function () {- return {- tasks: [],- isLoading: true,- selectedTask: null,- expandedTaskId: null,- sortField: 'name',- sortDirection: 'asc',- filterType: 'all',- filterState: 'all',- pollingInterval: null,- pollingActive: false,- editingTask: {- name: '',- type: 'scheduled',- state: 'idle',- schedule: {- minute: '*',- hour: '*',- day: '*',- month: '*',- weekday: '*',- timezone: ''- },- token: '',- plan: {- todo: [],- in_progress: null,- done: []- },- system_prompt: '',- prompt: '',- attachments: []- },- isCreating: false,- isEditing: false,- showLoadingState: false,- viewMode: 'list',- selectedTaskForDetail: null,- attachmentsText: '',- filteredTasks: [],- // Minimal init to avoid errors- init() {- console.log('Basic schedulerSettings initialized');- // Watch for task type changes- this.$watch('editingTask.type', (newType) => {- if (newType === 'planned') {- // When switching to planned task type, initialize the datetime picker- this.$nextTick(() => {- if (this.initFlatpickr) {- if (this.isCreating) {- this.initFlatpickr('create');- } else if (this.isEditing) {- this.initFlatpickr('edit');- }- }- });- }- });- }- };- };- </script>-- <!-- Load module scripts first -->- <script type="module" src="js/scheduler.js"></script>-<script type="module" src="index.js"></script><!-- Bootstrap JS (only for logic, importing bundled CSS => UI conflicts) -->@@ -126,8 +56,6 @@<!-- Link the PWA manifest file --><link rel="manifest" href="js/manifest.json">- <!-- Non-module scripts after Alpine.js -->- <script type="text/javascript" src="js/settings.js"></script><script>// Expose git info for sidebar componentglobalThis.gitinfo = { version: "{{version_no}}", commit_time: "{{version_time}}" };@@ -142,7 +70,6 @@<div class="sidebar-overlay" :class="{'visible': $store.sidebar.isOpen && $store.sidebar.isMobile()}" @click="$store.sidebar.close()"></div></template></div>- </template><!-- Left Sidebar (Header Icons, Quick Actions, Tabs, Chats, Tasks) --><x-component path="sidebar/left-sidebar.html"></x-component>@@ -181,1057 +108,7 @@<x-component path="chat/input/chat-bar.html"></x-component></div></div>- </div>- <div id="settingsModal" x-data="settingsModalProxy">- <template x-teleport="body">- <div x-show="isOpen" class="modal-overlay" @click.self="handleCancel()"- @keydown.escape.window="isOpen && handleCancel()" x-transition>- <div class="modal-container">- <div class="modal-header">- <h2 x-text="settings.title"></h2>- <button class="modal-close" @click="handleCancel()">×</button>- </div>-- <div class="modal-content">- <!-- Tab Navigation -->- <div class="settings-tabs-container">- <div class="settings-tabs">- <div class="settings-tab" :class="{'active': activeTab === 'agent'}"- @click="switchTab('agent')" title="Agent Settings">Agent Settings</div>- <div class="settings-tab" :class="{'active': activeTab === 'external'}"- @click="switchTab('external')" title="External Services">External Services</div>- <div class="settings-tab" :class="{'active': activeTab === 'mcp'}"- @click="switchTab('mcp')" title="MCP">MCP/A2A</div>- <div class="settings-tab" :class="{'active': activeTab === 'developer'}"- @click="switchTab('developer')" title="Developer">Developer</div>- <div class="settings-tab" :class="{'active': activeTab === 'scheduler'}"- @click="switchTab('scheduler')" title="Task Scheduler">Task Scheduler</div>- <div class="settings-tab" :class="{'active': activeTab === 'backup'}"- @click="switchTab('backup')" title="Backup & Restore">Backup & Restore</div>- </div>- </div>-- <!-- Display settings sections for agent, external, developer, mcp, backup tabs -->- <div id="settings-sections" x-show="activeTab !== 'scheduler'">- <nav>- <ul>- <template x-for="(section, index) in filteredSections" :key="section.title">- <li>- <a :href="'#section' + (index + 1)">- <img :src="'/public/' + section.id +'.svg'" :alt="section.title">- <span x-text="section.title"></span>- </a>- </li>- </template>- <!-- Tunnel navigation entry - only visible in the External Services tab -->- <li x-show="activeTab === 'external'">- <a href="#section-tunnel">- <img src="/public/tunnel.svg" alt="Tunnel">- <span>Flare Tunnel</span>- </a>- </li>- </ul>- </nav>-- <template x-for="(section, sectionIndex) in filteredSections" :key="sectionIndex">- <div :id="'section' + (sectionIndex + 1)" class="section">- <div class="section-title" x-text="section.title"></div>- <div class="section-description" x-html="section.description"></div>-- <template x-for="(field, fieldIndex) in section.fields.filter(f => !f.hidden)"- :key="fieldIndex">- <div :class="{'field': true, 'field-full': field.type === 'textarea'}">- <div class="field-label" x-show="field.title || field.description">- <div class="field-title" x-text="field.title" x-show="field.title">- </div>- <div class="field-description" x-html="field.description || ''"- x-show="field.description"></div>- </div>-- <div class="field-control">- <!-- Input field -->- <template x-if="field.type === 'text'">- <input type="text" :class="field.classes" :value="field.value"- :readonly="field.readonly === true"- @input="field.value = $event.target.value">- </template>-- <!-- Number field -->- <template x-if="field.type === 'number'">- <input type="number" :class="field.classes" :value="field.value"- :readonly="field.readonly === true"- @input="field.value = $event.target.value" :min="field.min"- :max="field.max" :step="field.step">- </template>--- <!-- Password field -->- <template x-if="field.type === 'password'">- <input type="password" :class="field.classes" :value="field.value"- :readonly="field.readonly === true" :id="field.id"- autocomplete="off" @input="field.value = $event.target.value">- </template>-- <!-- Textarea field -->- <template x-if="field.type === 'textarea'">- <textarea :class="field.classes" :value="field.value"- :readonly="field.readonly === true"- @input="field.value = $event.target.value"- :style="field.style"></textarea>- </template>-- <!-- Switch field -->- <template x-if="field.type === 'switch'">- <label class="toggle">- <input type="checkbox" :checked="field.value"- :disabled="field.readonly === true"- @change="field.value = $event.target.checked">- <span class="toggler"></span>- </label>- </template>-- <!-- Range field -->- <template x-if="field.type === 'range'">- <div class="field-control">- <input type="range" :min="field.min" :max="field.max"- :step="field.step" :value="field.value"- :disabled="field.readonly === true"- @input="field.value = $event.target.value"- :class="field.classes">- <span class="range-value" x-text="field.value"></span>- </div>- </template>-- <!-- Button field -->- <template x-if="field.type === 'button'">- <button class="btn btn-field" :class="field.classes"- :disabled="field.readonly === true"- @click="handleFieldButton(field)" x-text="field.value"></button>- </template>-- <!-- Select field -->- <template x-if="field.type === 'select'">- <select :class="field.classes" x-model="field.value"- :disabled="field.readonly === true">- <template x-for="option in field.options" :key="option.value">- <option :value="option.value" x-text="option.label"- :selected="option.value === field.value"></option>- </template>- </select>- </template>-- <!-- HTML field -->- <template x-if="field.type === 'html'">- <div :class="field.classes" x-html="field.value"></div>- </template>- </div>- </div>- </template>- </div>- </template>-- <!-- Tunnel section content - only visible in External Services tab -->- <div id="section-tunnel" class="section" x-show="activeTab === 'external'">- <x-component path="settings/tunnel/tunnel-section.html" />- </div>- </div>-- <!-- Task Scheduler Tab Content -->- <div id="scheduler-tab-content" x-show="activeTab === 'scheduler'" x-cloak>- <!-- Settings section structure for task scheduler -->- <nav>- <ul>- <li>- <a href="#section-task-scheduler">- <img src="/public/task_scheduler.svg" alt="Task Scheduler">- <span>Task Scheduler</span>- </a>- </li>- </ul>- </nav>-- <div id="section-task-scheduler" class="section" x-data="schedulerSettings">- <div class="section-title">Task Scheduler</div>- <div class="section-description">Manage scheduled tasks and automated processes for- Agent Zero.</div>-- <!-- Create Task Form -->- <div class="scheduler-form" x-show="isCreating">- <div class="scheduler-form-header">- <div class="scheduler-form-title">Create New Task</div>- <div class="scheduler-form-actions">- <button class="btn btn-ok btn-field" @click="saveTask()">- Save- </button>- <button class="btn btn-cancel" @click="cancelEdit()">- Cancel- </button>- </div>- </div>-- <div class="scheduler-form-grid">- <!-- Task Name -->- <div class="scheduler-form-field">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Task Name</label>- <div class="scheduler-form-help">A unique name to identify this task- </div>- </div>- <input type="text" x-model="editingTask.name" placeholder="Enter task name">- </div>-- <!-- Task Type Selection -->- <div class="scheduler-form-field">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Type</label>- <div class="scheduler-form-help">Task execution method</div>- </div>- <select x-model="editingTask.type">- <option value="scheduled">Scheduled (Cron)</option>- <option value="adhoc">Ad-hoc (Manual)</option>- <option value="planned">Planned (Specific Times)</option>- </select>- </div>-- <div class="scheduler-form-field">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Project</label>- <div class="scheduler-form-help" x-text="editingTask.dedicated_context ? 'Inherited from the active chat project.' : 'Mirrors the shared context project.'"></div>- </div>- <template x-if="isCreating">- <div class="project-selector">- <!-- <span class="project-color-ball"- :style="editingTask.project?.color ? { backgroundColor: editingTask.project.color } : { border: '1px solid var(--color-border)' }"></span> -->- <select class="scheduler-project-select"- x-model="selectedProjectSlug"- @change="onProjectSelect($event.target.value)">- <option value="">No project</option>- <template x-for="proj in projectOptions" :key="proj.name">- <option :value="proj.name" x-text="proj.title"></option>- </template>- </select>- </div>- </template>- <template x-if="!isCreating">- <div class="project-display">- <span class="project-color-ball"- :style="editingTask.project?.color ? { backgroundColor: editingTask.project.color } : { border: '1px solid var(--color-border)' }"></span>- <span x-text="formatProjectLabel(editingTask.project)"></span>- </div>- </template>- </div>-- <!-- Task State in Create Form - Add after Task Type -->- <div class="scheduler-form-field" x-show="isCreating">- <div class="label-help-wrapper">- <label class="scheduler-form-label">State</label>- <div class="scheduler-form-help">Select the initial state of the task- </div>- </div>- <div>- <div class="scheduler-state-selector">- <span class="scheduler-status-badge scheduler-status-idle"- :class="{'scheduler-status-selected': editingTask.state === 'idle'}"- @click="editingTask.state = 'idle'">idle</span>- <span class="scheduler-status-badge scheduler-status-running"- :class="{'scheduler-status-selected': editingTask.state === 'running'}"- @click="editingTask.state = 'running'">running</span>- <span class="scheduler-status-badge scheduler-status-disabled"- :class="{'scheduler-status-selected': editingTask.state === 'disabled'}"- @click="editingTask.state = 'disabled'">disabled</span>- <span class="scheduler-status-badge scheduler-status-error"- :class="{'scheduler-status-selected': editingTask.state === 'error'}"- @click="editingTask.state = 'error'">error</span>- </div>- <div class="scheduler-state-explanation">- <span x-show="editingTask.state === 'idle'"><strong>idle</strong>:- ready to run</span>- <span- x-show="editingTask.state === 'running'"><strong>running</strong>:- currently executing</span>- <span- x-show="editingTask.state === 'disabled'"><strong>disabled</strong>:- won't execute automatically</span>- <span x-show="editingTask.state === 'error'"><strong>error</strong>:- task encountered an error</span>- </div>- </div>- </div>-- <!-- Schedule (only for scheduled tasks) -->- <div class="scheduler-form-field full-width"- x-show="editingTask.type === 'scheduled'">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Schedule</label>- <div class="scheduler-form-help">Cron schedule for automated execution- (minute hour day month weekday)</div>- </div>- <div class="scheduler-schedule-builder">- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Minute</span>- <input type="text" x-model="editingTask.schedule.minute"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Hour</span>- <input type="text" x-model="editingTask.schedule.hour"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Day</span>- <input type="text" x-model="editingTask.schedule.day"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Month</span>- <input type="text" x-model="editingTask.schedule.month"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Weekday</span>- <input type="text" x-model="editingTask.schedule.weekday"- placeholder="*" maxlength="9">- </div>- </div>- </div>-- <!-- Plan (for planned tasks) -->- <div class="scheduler-form-field full-width"- x-show="editingTask.type === 'planned'">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Plan</label>- <div class="scheduler-form-help">Specific execution times for this task- </div>- </div>- <div class="scheduler-plan-builder">- <div class="scheduler-plan-todo">- <span class="scheduler-plan-label">Upcoming Executions</span>- <div class="scheduler-todo-list">- <template- x-if="editingTask.plan && Array.isArray(editingTask.plan.todo) && editingTask.plan.todo.length > 0">- <template x-for="(time, index) in editingTask.plan.todo"- :key="index">- <div class="scheduler-todo-item">- <span x-text="formatDate(time)"></span>- <button- @click.prevent="editingTask.plan.todo.splice(index, 1)"- class="scheduler-todo-remove">- <svg xmlns="http://www.w3.org/2000/svg"- width="16" height="16" viewBox="0 0 24 24"- fill="none" stroke="currentColor"- stroke-width="2" stroke-linecap="round"- stroke-linejoin="round">- <line x1="18" y1="6" x2="6" y2="18"></line>- <line x1="6" y1="6" x2="18" y2="18"></line>- </svg>- </button>- </div>- </template>- </template>- <template- x-if="!editingTask.plan || !Array.isArray(editingTask.plan.todo) || editingTask.plan.todo.length === 0">- <div class="scheduler-empty-plan">- No scheduled execution times yet. Add one below.- </div>- </template>- <div class="scheduler-add-todo">- <!-- Create form planned task input -->- <input type="text" id="newPlannedTime-create"- x-ref="plannedTimeCreate"- class="scheduler-flatpickr-input"- placeholder="Select date and time">- <!-- Create Task Form Add Time Button -->- <button @click.prevent="- const input = $refs.plannedTimeCreate;- if (!input) {- console.error('Input reference not found for plannedTimeCreate');- return;- }-- // Ensure plan structure exists- if (!editingTask.plan) {- editingTask.plan = { todo: [], in_progress: null, done: [] };- }- if (!Array.isArray(editingTask.plan.todo)) {- editingTask.plan.todo = [];- }-- // Get date from Flatpickr if available- let selectedDate;- if (input._flatpickr && input._flatpickr.selectedDates.length > 0) {- selectedDate = input._flatpickr.selectedDates[0];- } else if (input.value) {- selectedDate = new Date(input.value);- }-- if (!selectedDate || isNaN(selectedDate.getTime())) {- alert('Please select a valid date and time');- return;- }-- // Convert to ISO string and add to plan- editingTask.plan.todo.push(selectedDate.toISOString());-- // Sort by date (earliest first)- editingTask.plan.todo.sort();-- // Clear the input- if (input._flatpickr) {- input._flatpickr.clear();- } else {- input.value = '';- }- " class="scheduler-add-todo-button">- <svg xmlns="http://www.w3.org/2000/svg" width="16"- height="16" viewBox="0 0 24 24" fill="none"- stroke="currentColor" stroke-width="2"- stroke-linecap="round" stroke-linejoin="round"- style="margin-right: 4px;">- <line x1="12" y1="5" x2="12" y2="19"></line>- <line x1="5" y1="12" x2="19" y2="12"></line>- </svg>- Add Time- </button>- </div>- </div>- </div>- </div>- </div>-- <!-- Token (for ad-hoc tasks) -->- <div class="scheduler-form-field full-width"- x-show="editingTask.type === 'adhoc'">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Token</label>- <div class="scheduler-form-help">Token used to trigger this task- externally</div>- </div>- <div class="input-group">- <input type="text" x-model="editingTask.token"- placeholder="Token for ad-hoc task">- <button class="scheduler-task-action"- @click="editingTask.token = generateRandomToken()">- Generate- </button>- </div>- </div>-- <!-- System Prompt -->- <div class="scheduler-form-field full-width">- <div class="label-help-wrapper">- <label class="scheduler-form-label">System Prompt</label>- <div class="scheduler-form-help">System-level instructions for the- assistant</div>- </div>- <textarea x-model="editingTask.system_prompt"- placeholder="System instructions for the AI"></textarea>- </div>-- <!-- User Prompt -->- <div class="scheduler-form-field full-width">- <div class="label-help-wrapper">- <label class="scheduler-form-label">User Prompt</label>- <div class="scheduler-form-help">The main task prompt that will be- executed</div>- </div>- <textarea x-model="editingTask.prompt"- placeholder="User message for the AI"></textarea>- </div>-- <!-- Attachments Field -->- <div class="scheduler-form-field full-width">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Attachments</label>- <div class="scheduler-form-help">Container file paths or URLs, one per- line</div>- </div>- <textarea x-model="attachmentsText"- placeholder="Enter file paths or URLs, one per line"></textarea>- </div>- </div>- </div>-- <!-- Edit Task Form -->- <div class="scheduler-form" x-show="isEditing">- <div class="scheduler-form-header">- <div class="scheduler-form-title">Edit Task</div>- <div class="scheduler-form-actions">- <button class="btn btn-ok btn-field" @click="saveTask()">- Save- </button>- <button class="btn btn-cancel" @click="cancelEdit()">- Cancel- </button>- </div>- </div>-- <div class="scheduler-form-grid">- <!-- Task Name -->- <div class="scheduler-form-field">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Task Name</label>- <div class="scheduler-form-help">A unique name to identify this task- </div>- </div>- <input type="text" x-model="editingTask.name" placeholder="Enter task name">- </div>-- <!-- Task Type (disabled when editing) -->- <div class="scheduler-form-field">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Task Type</label>- <div class="scheduler-form-help">Task type cannot be changed after- creation</div>- </div>- <select x-model="editingTask.type" disabled>- <option value="scheduled">Scheduled Task</option>- <option value="adhoc">Ad-hoc Task</option>- <option value="planned">Planned Task</option>- </select>- </div>-- <div class="scheduler-form-field">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Project</label>- <div class="scheduler-form-help" x-text="editingTask.dedicated_context ? 'Dedicated tasks inherit the active chat project.' : 'Shared tasks mirror the project assigned to their context.'"></div>- </div>- <div class="project-display">- <span class="project-color-ball" :style="editingTask.project?.color ? { backgroundColor: editingTask.project.color } : { border: '1px solid var(--color-border)' }"></span>- <span x-text="formatProjectLabel(editingTask.project)"></span>- </div>- </div>-- <!-- Task State in Edit Form - Add after Task Type -->- <div class="scheduler-form-field" x-show="isEditing">- <div class="label-help-wrapper">- <label class="scheduler-form-label">State</label>- <div class="scheduler-form-help">Change the task's state</div>- </div>- <div>- <div class="scheduler-state-selector">- <span class="scheduler-status-badge scheduler-status-idle"- :class="{'scheduler-status-selected': editingTask.state === 'idle'}"- @click="editingTask.state = 'idle'">idle</span>- <span class="scheduler-status-badge scheduler-status-running"- :class="{'scheduler-status-selected': editingTask.state === 'running'}"- @click="editingTask.state = 'running'">running</span>- <span class="scheduler-status-badge scheduler-status-disabled"- :class="{'scheduler-status-selected': editingTask.state === 'disabled'}"- @click="editingTask.state = 'disabled'">disabled</span>- <span class="scheduler-status-badge scheduler-status-error"- :class="{'scheduler-status-selected': editingTask.state === 'error'}"- @click="editingTask.state = 'error'">error</span>- </div>- <div class="scheduler-state-explanation">- <span x-show="editingTask.state === 'idle'"><strong>idle</strong>:- ready to run</span>- <span- x-show="editingTask.state === 'running'"><strong>running</strong>:- currently executing</span>- <span- x-show="editingTask.state === 'disabled'"><strong>disabled</strong>:- won't execute automatically</span>- <span x-show="editingTask.state === 'error'"><strong>error</strong>:- task encountered an error</span>- </div>- </div>- </div>-- <!-- Schedule (for scheduled tasks) -->- <div class="scheduler-form-field full-width"- x-show="editingTask && editingTask.type === 'scheduled'">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Schedule (Cron Expression)</label>- <div class="scheduler-form-help">Format: minute hour day month weekday- (e.g., "* * * * *" for every minute)</div>- </div>- <div class="scheduler-schedule-builder">- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Minute</span>- <input type="text" x-model="editingTask.schedule.minute"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Hour</span>- <input type="text" x-model="editingTask.schedule.hour"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Day</span>- <input type="text" x-model="editingTask.schedule.day"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Month</span>- <input type="text" x-model="editingTask.schedule.month"- placeholder="*" maxlength="9">- </div>- <div class="scheduler-schedule-field">- <span class="scheduler-schedule-label">Weekday</span>- <input type="text" x-model="editingTask.schedule.weekday"- placeholder="*" maxlength="9">- </div>- </div>- </div>-- <!-- Plan (for planned tasks) -->- <div class="scheduler-form-field full-width"- x-show="editingTask.type === 'planned'">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Plan</label>- <div class="scheduler-form-help">Specific execution times for this task- </div>- </div>- <div class="scheduler-plan-builder">- <div class="scheduler-plan-todo">- <span class="scheduler-plan-label">Upcoming Executions</span>- <div class="scheduler-todo-list">- <template- x-if="editingTask.plan && Array.isArray(editingTask.plan.todo) && editingTask.plan.todo.length > 0">- <template x-for="(time, index) in editingTask.plan.todo"- :key="index">- <div class="scheduler-todo-item">- <span x-text="formatDate(time)"></span>- <button- @click.prevent="editingTask.plan.todo.splice(index, 1)"- class="scheduler-todo-remove">- <svg xmlns="http://www.w3.org/2000/svg"- width="16" height="16" viewBox="0 0 24 24"- fill="none" stroke="currentColor"- stroke-width="2" stroke-linecap="round"- stroke-linejoin="round">- <line x1="18" y1="6" x2="6" y2="18"></line>- <line x1="6" y1="6" x2="18" y2="18"></line>- </svg>- </button>- </div>- </template>- </template>- <template- x-if="!editingTask.plan || !Array.isArray(editingTask.plan.todo) || editingTask.plan.todo.length === 0">- <div class="scheduler-empty-plan">- No scheduled execution times yet. Add one below.- </div>- </template>- <div class="scheduler-add-todo">- <!-- Edit form planned task input -->- <input type="text" id="newPlannedTime-edit"- x-ref="plannedTimeEdit"- class="scheduler-flatpickr-input"- placeholder="Select date and time">- <!-- Edit Task Form Add Time Button -->- <button @click.prevent="- const input = $refs.plannedTimeEdit;- if (!input) {- console.error('Input reference not found for plannedTimeEdit');- return;- }-- // Ensure plan structure exists- if (!editingTask.plan) {- editingTask.plan = { todo: [], in_progress: null, done: [] };- }- if (!Array.isArray(editingTask.plan.todo)) {- editingTask.plan.todo = [];- }-- // Get date from Flatpickr if available- let selectedDate;- if (input._flatpickr && input._flatpickr.selectedDates.length > 0) {- selectedDate = input._flatpickr.selectedDates[0];- } else if (input.value) {- selectedDate = new Date(input.value);- }-- if (!selectedDate || isNaN(selectedDate.getTime())) {- alert('Please select a valid date and time');- return;- }-- // Convert to ISO string and add to plan- editingTask.plan.todo.push(selectedDate.toISOString());-- // Sort by date (earliest first)- editingTask.plan.todo.sort();-- // Clear the input- if (input._flatpickr) {- input._flatpickr.clear();- } else {- input.value = '';- }- " class="scheduler-add-todo-button">- <svg xmlns="http://www.w3.org/2000/svg" width="16"- height="16" viewBox="0 0 24 24" fill="none"- stroke="currentColor" stroke-width="2"- stroke-linecap="round" stroke-linejoin="round"- style="margin-right: 4px;">- <line x1="12" y1="5" x2="12" y2="19"></line>- <line x1="5" y1="12" x2="19" y2="12"></line>- </svg>- Add Time- </button>- </div>- </div>- </div>- </div>- </div>-- <!-- Token (for ad-hoc tasks) -->- <div class="scheduler-form-field full-width"- x-show="editingTask.type === 'adhoc'">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Token</label>- <div class="scheduler-form-help">Token used to trigger this task- externally</div>- </div>- <div class="input-group">- <input type="text" x-model="editingTask.token"- placeholder="Token for ad-hoc task">- <button class="scheduler-task-action"- @click="editingTask.token = generateRandomToken()">- Generate- </button>- </div>- </div>-- <!-- System Prompt -->- <div class="scheduler-form-field full-width">- <div class="label-help-wrapper">- <label class="scheduler-form-label">System Prompt</label>- <div class="scheduler-form-help">System-level instructions for the- assistant</div>- </div>- <textarea x-model="editingTask.system_prompt"- placeholder="System instructions for the AI"></textarea>- </div>-- <!-- User Prompt -->- <div class="scheduler-form-field full-width">- <div class="label-help-wrapper">- <label class="scheduler-form-label">User Prompt</label>- <div class="scheduler-form-help">The main task prompt that will be- executed</div>- </div>- <textarea x-model="editingTask.prompt"- placeholder="User message for the AI"></textarea>- </div>-- <!-- Attachments Field -->- <div class="scheduler-form-field full-width">- <div class="label-help-wrapper">- <label class="scheduler-form-label">Attachments</label>- <div class="scheduler-form-help">Container file paths or URLs, one per- line</div>- </div>- <textarea x-model="attachmentsText"- placeholder="Enter file paths or URLs, one per line"></textarea>- </div>- </div>- </div>-- <!-- Task List View -->- <div class="scheduler-container"- x-show="!isCreating && !isEditing && viewMode === 'list'">- <!-- Header with Actions -->- <div class="scheduler-header">- <h2>Task Management</h2>- <div class="scheduler-actions">- <button class="btn btn-ok" @click="startCreateTask()">- New Task- </button>- </div>- </div>-- <!-- Filters -->- <div class="scheduler-filters">- <div class="scheduler-filter-group">- <span class="scheduler-filter-label">Type:</span>- <select class="scheduler-filter-select" x-model="filterType">- <option value="all">All Types</option>- <option value="scheduled">Scheduled</option>- <option value="adhoc">Ad-hoc</option>- <option value="planned">Planned</option>- </select>- </div>-- <div class="scheduler-filter-group">- <span class="scheduler-filter-label">State:</span>- <select class="scheduler-filter-select" x-model="filterState">- <option value="all">All States</option>- <option value="idle">Idle</option>- <option value="running">Running</option>- <option value="disabled">Disabled</option>- <option value="error">Error</option>- </select>- </div>- </div>-- <!-- Loading State -->- <!-- <div class="scheduler-loading" x-show="isLoading">- Loading tasks...- </div> -->-- <!-- Empty State -->- <div class="scheduler-empty" x-show="!isLoading && filteredTasks.length === 0"- x-effect="$el.style.display = (!isLoading && filteredTasks.length === 0) ? '' : 'none'">- <!-- <div class="scheduler-empty-icon">📋</div> -->- <div class="scheduler-empty-text">No tasks found</div>- <button class="btn btn-ok" @click="startCreateTask()">Create your first- task</button>- </div>-- <!-- Task List Table -->- <table class="scheduler-task-list" x-show="!isLoading && filteredTasks.length > 0"- x-effect="$el.style.display = (!isLoading && filteredTasks.length > 0) ? '' : 'none'">- <thead>- <tr>- <th @click="changeSort('name')">- Name- <span class="scheduler-sort-indicator" x-show="sortField === 'name'"- :class="{'scheduler-sort-desc': sortDirection === 'desc'}">↑</span>- </th>- <th @click="changeSort('state')">- State- <span class="scheduler-sort-indicator"- x-show="sortField === 'state'"- :class="{'scheduler-sort-desc': sortDirection === 'desc'}">↑</span>- </th>- <th>Type</th>- <th>Project</th>- <th>Schedule</th>- <th @click="changeSort('last_run')">- Last Run- <span class="scheduler-sort-indicator"- x-show="sortField === 'last_run'"- :class="{'scheduler-sort-desc': sortDirection === 'desc'}">↑</span>- </th>- <th>Actions</th>- </tr>- </thead>- <tbody>- <template x-for="task in filteredTasks" :key="task.uuid">- <tr @click="showTaskDetail(task.uuid)">- <td>- <span x-text="task.name"></span>- </td>- <td>- <span class="scheduler-status-badge"- :class="getStateBadgeClass(task.state)"- x-text="task.state"></span>- </td>- <td x-text="task.type"></td>- <td>- <span class="project-color-ball"- :style="extractTaskProject(task)?.color ? { backgroundColor: extractTaskProject(task).color } : { border: '1px solid var(--color-border)' }"></span>- <span x-text="formatTaskProject(task)"></span>- </td>- <td>- <span x-show="task.type === 'scheduled'"- x-text="formatSchedule(task)"></span>- <span x-show="task.type === 'adhoc'"- class="scheduler-no-schedule">—</span>- <span x-show="task.type === 'planned'"- x-html="formatPlan(task).replace(/\n/g, '<br>')"></span>- </td>- <td x-text="formatDate(task.last_run)"></td>- <td @click.stop>- <div class="scheduler-task-actions">- <button class="scheduler-task-action"- @click="runTask(task.uuid)" title="Run Task">- <svg xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 24 24" fill="currentColor" width="16"- height="16">- <path d="M8 5v14l11-7z" />- </svg>- </button>- <button class="scheduler-task-action"- @click="resetTaskState(task.uuid)" title="Reset State">- <svg xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 24 24" fill="currentColor" width="16"- height="16">- <path- d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />- </svg>- </button>- <button class="scheduler-task-action"- @click="startEditTask(task.uuid)" title="Edit Task">- <svg xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 24 24" fill="currentColor" width="16"- height="16">- <path- d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" />- </svg>- </button>- <button class="scheduler-task-action"- @click="deleteTask(task.uuid)" title="Delete Task">- <svg xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 24 24" fill="currentColor" width="16"- height="16">- <path- d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />- </svg>- </button>- </div>- </td>- </tr>- </template>- </tbody>- </table>- </div>-- <!-- Task Detail View -->- <div class="scheduler-detail-view"- x-show="!isCreating && !isEditing && viewMode === 'detail' && selectedTaskForDetail">- <div class="scheduler-detail-header">- <h2 class="scheduler-detail-title"- x-text="selectedTaskForDetail ? selectedTaskForDetail.name : ''"></h2>- <div class="scheduler-status-badge"- :class="selectedTaskForDetail ? getStateBadgeClass(selectedTaskForDetail.state) : ''"- x-text="selectedTaskForDetail ? selectedTaskForDetail.state : ''">- </div>- <button class="btn btn-cancel" @click="closeTaskDetail()">Close</button>- </div>-- <div class="scheduler-detail-content">- <div class="scheduler-details-grid">- <div class="scheduler-details-label">Type:</div>- <div class="scheduler-details-value"- x-text="selectedTaskForDetail ? selectedTaskForDetail.type : ''"></div>-- <div class="scheduler-details-label">Project:</div>- <div class="scheduler-details-value">- <span class="project-color-ball"- :style="extractTaskProject(selectedTaskForDetail)?.color ? { backgroundColor: extractTaskProject(selectedTaskForDetail).color } : { border: '1px solid var(--color-border)' }"></span>- <span x-text="selectedTaskForDetail ? formatTaskProject(selectedTaskForDetail) : 'No Project'"></span>- </div>-- <div class="scheduler-details-label">Created:</div>- <div class="scheduler-details-value"- x-text="selectedTaskForDetail ? formatDate(selectedTaskForDetail.created_at) : ''">- </div>-- <div class="scheduler-details-label">Last Updated:</div>- <div class="scheduler-details-value"- x-text="selectedTaskForDetail ? formatDate(selectedTaskForDetail.updated_at) : ''">- </div>-- <div class="scheduler-details-label">Last Run:</div>- <div class="scheduler-details-value"- x-text="selectedTaskForDetail ? formatDate(selectedTaskForDetail.last_run) : ''">- </div>-- <div class="scheduler-details-label"- x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'scheduled'">- Schedule:</div>- <div class="scheduler-details-value"- x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'scheduled'"- x-text="selectedTaskForDetail ? formatSchedule(selectedTaskForDetail) : ''">- </div>-- <div class="scheduler-details-label"- x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'adhoc'">- Token:</div>- <div class="scheduler-details-value"- x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'adhoc'"- x-text="selectedTaskForDetail ? selectedTaskForDetail.token : ''"></div>-- <div class="scheduler-details-label"- x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'planned'">- Plan:</div>- <div class="scheduler-details-value"- x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'planned'">- <div x-show="selectedTaskForDetail && selectedTaskForDetail.plan">- <div><strong>Upcoming:</strong></div>- <template- x-if="selectedTaskForDetail && selectedTaskForDetail.plan && selectedTaskForDetail.plan.todo && selectedTaskForDetail.plan.todo.length > 0">- <div>- <template- x-for="(time, index) in selectedTaskForDetail.plan.todo"- :key="index">- <div x-text="formatDate(time)"></div>- </template>- </div>- </template>- <template- x-if="!selectedTaskForDetail || !selectedTaskForDetail.plan || !selectedTaskForDetail.plan.todo || selectedTaskForDetail.plan.todo.length === 0">- <div>No upcoming executions</div>- </template>-- <div><strong>In Progress:</strong></div>- <div- x-text="selectedTaskForDetail && selectedTaskForDetail.plan && selectedTaskForDetail.plan.in_progress ? formatDate(selectedTaskForDetail.plan.in_progress) : 'None'">- </div>-- <div><strong>Completed:</strong></div>- <template- x-if="selectedTaskForDetail && selectedTaskForDetail.plan && selectedTaskForDetail.plan.done && selectedTaskForDetail.plan.done.length > 0">- <div>- <template- x-for="(time, index) in selectedTaskForDetail.plan.done"- :key="index">- <div x-text="formatDate(time)"></div>- </template>- </div>- </template>- <template- x-if="!selectedTaskForDetail || !selectedTaskForDetail.plan || !selectedTaskForDetail.plan.done || selectedTaskForDetail.plan.done.length === 0">- <div>No completed executions</div>- </template>- </div>- </div>-- <div class="scheduler-details-label">Last Result:</div>- <div class="scheduler-details-value"- x-text="selectedTaskForDetail && selectedTaskForDetail.last_result ? selectedTaskForDetail.last_result : 'No results yet'">- </div>-- <div class="scheduler-details-label">System Prompt:</div>- <div class="scheduler-details-value"- x-text="selectedTaskForDetail ? selectedTaskForDetail.system_prompt : ''">- </div>-- <div class="scheduler-details-label">User Prompt:</div>- <div class="scheduler-details-value"- x-text="selectedTaskForDetail ? selectedTaskForDetail.prompt : ''">- </div>-- <div class="scheduler-details-label">Attachments:</div>- <div class="scheduler-details-value">- <template- x-if="selectedTaskForDetail && selectedTaskForDetail.attachments && selectedTaskForDetail.attachments.length > 0">- <div>- <template- x-for="(attachment, index) in selectedTaskForDetail.attachments"- :key="index">- <div x-text="attachment"></div>- </template>- </div>- </template>- <template- x-if="!selectedTaskForDetail || !selectedTaskForDetail.attachments || selectedTaskForDetail.attachments.length === 0">- <div>No attachments</div>- </template>- </div>- </div>- </div>- </div>- </div>- </div>- </div>-- <div class="modal-footer">- <div id="buttons-container">- <template x-for="button in settings.buttons" :key="button.id">- <button :class="button.classes" @click="handleButton(button.id)"- x-text="button.title"></button>- </template></div>- </div>- </div>- </div>- </template>- </div><!-- Drag and Drop Overlay Component --><x-component path="chat/attachments/dragDropOverlay.html"></x-component>diff --git a/webui/index.js b/webui/index.jsindex d7db5fc6a..2f09029b6 100644--- a/webui/index.js+++ b/webui/index.js@@ -631,61 +631,3 @@ document.addEventListener("DOMContentLoaded", function () {* - Both lists are sorted by creation time (newest first)* - Tasks use the same context system as chats for communication with the backend*/--// Open the scheduler detail view for a specific task-function openTaskDetail(taskId) {- // Wait for Alpine.js to be fully loaded- if (globalThis.Alpine) {- // Get the settings modal button and click it to ensure all init logic happens- const settingsButton = document.getElementById("settings");- if (settingsButton) {- // Programmatically click the settings button- settingsButton.click();-- // Now get a reference to the modal element- const modalEl = document.getElementById("settingsModal");- if (!modalEl) {- console.error("Settings modal element not found after clicking button");- return;- }-- // Get the Alpine.js data for the modal- const modalData = globalThis.Alpine ? Alpine.$data(modalEl) : null;-- // Use a timeout to ensure the modal is fully rendered- setTimeout(() => {- // Switch to the scheduler tab first- modalData.switchTab("scheduler");-- // Use another timeout to ensure the scheduler component is initialized- setTimeout(() => {- // Get the scheduler component- const schedulerComponent = document.querySelector(- '[x-data="schedulerSettings"]'- );- if (!schedulerComponent) {- console.error("Scheduler component not found");- return;- }-- // Get the Alpine.js data for the scheduler component- const schedulerData = globalThis.Alpine- ? Alpine.$data(schedulerComponent)- : null;-- // Show the task detail view for the specific task- schedulerData.showTaskDetail(taskId);-- console.log("Task detail view opened for task:", taskId);- }, 50); // Give time for the scheduler tab to initialize- }, 25); // Give time for the modal to render- } else {- console.error("Settings button not found");- }- } else {- console.error("Alpine.js not loaded");- }-}--// Make the function available globally-globalThis.openTaskDetail = openTaskDetail;diff --git a/webui/js/scheduler.js b/webui/js/scheduler.jsdeleted file mode 100644index 96cb548dd..000000000--- a/webui/js/scheduler.js+++ /dev/null@@ -1,1835 +0,0 @@-/**- * Task Scheduler Component for Settings Modal- * Manages scheduled and ad-hoc tasks through a dedicated settings tab- */--import { formatDateTime, getUserTimezone } from './time-utils.js';-import { store as chatsStore } from "/components/sidebar/chats/chats-store.js"-import { store as notificationsStore } from "/components/notifications/notification-store.js"-import { store as projectsStore } from "/components/projects/projects-store.js"--// Ensure the showToast function is available-// if (typeof window.showToast !== 'function') {-// window.showToast = function(message, type = 'info') {-// console.log(`[Toast ${type}]: ${message}`);-// // Create toast element if not already present-// let toastContainer = document.getElementById('toast-container');-// if (!toastContainer) {-// toastContainer = document.createElement('div');-// toastContainer.id = 'toast-container';-// toastContainer.style.position = 'fixed';-// toastContainer.style.bottom = '20px';-// toastContainer.style.right = '20px';-// toastContainer.style.zIndex = '9999';-// document.body.appendChild(toastContainer);-// }--// // Create the toast-// const toast = document.createElement('div');-// toast.className = `toast toast-${type}`;-// toast.style.padding = '10px 15px';-// toast.style.margin = '5px 0';-// toast.style.backgroundColor = type === 'error' ? '#f44336' :-// type === 'success' ? '#4CAF50' :-// type === 'warning' ? '#ff9800' : '#2196F3';-// toast.style.color = 'white';-// toast.style.borderRadius = '4px';-// toast.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';-// toast.style.width = 'auto';-// toast.style.maxWidth = '300px';-// toast.style.wordWrap = 'break-word';--// toast.innerHTML = message;--// // Add to container-// toastContainer.appendChild(toast);--// // Auto remove after 3 seconds-// setTimeout(() => {-// if (toast.parentNode) {-// toast.style.opacity = '0';-// toast.style.transition = 'opacity 0.5s ease';-// setTimeout(() => {-// if (toast.parentNode) {-// toast.parentNode.removeChild(toast);-// }-// }, 500);-// }-// }, 3000);-// };-// }--// Add this near the top of the scheduler.js file, outside of any function-const showToast = function(message, type = 'info') {- // Use new frontend notification system- switch (type.toLowerCase()) {- case 'error':- return notificationsStore.frontendError(message, "Scheduler", 5);- case 'success':- return notificationsStore.frontendInfo(message, "Scheduler", 3);- case 'warning':- return notificationsStore.frontendWarning(message, "Scheduler", 4);- case 'info':- default:- return notificationsStore.frontendInfo(message, "Scheduler", 3);- }-};--// Define the full component implementation-const fullComponentImplementation = function() {- return {- tasks: [],- isLoading: true,- selectedTask: null,- expandedTaskId: null,- sortField: 'name',- sortDirection: 'asc',- filterType: 'all', // all, scheduled, adhoc, planned- filterState: 'all', // all, idle, running, disabled, error- pollingInterval: null,- pollingActive: false, // Track if polling is currently active- editingTask: {- name: '',- type: 'scheduled',- state: 'idle',- schedule: {- minute: '*',- hour: '*',- day: '*',- month: '*',- weekday: '*',- timezone: getUserTimezone()- },- token: '',- plan: {- todo: [],- in_progress: null,- done: []- },- system_prompt: '',- prompt: '',- attachments: [],- project: null,- dedicated_context: true,- },- projectOptions: [],- selectedProjectSlug: '',- isCreating: false,- isEditing: false,- showLoadingState: false,- viewMode: 'list', // Controls whether to show list or detail view- selectedTaskForDetail: null, // Task object for detail view- attachmentsText: '',- filteredTasks: [],- hasNoTasks: true, // Add explicit reactive property-- // Initialize the component- init() {- // Initialize component data- this.tasks = [];- this.isLoading = true;- this.hasNoTasks = true; // Add explicit reactive property- this.filterType = 'all';- this.filterState = 'all';- this.sortField = 'name';- this.sortDirection = 'asc';- this.pollingInterval = null;- this.pollingActive = false;-- // Start polling for tasks- this.startPolling();-- // Refresh initial data- this.fetchTasks();-- // Set up event handler for tab selection to ensure view is refreshed when tab becomes visible- document.addEventListener('click', (event) => {- // Check if a tab was clicked- const clickedTab = event.target.closest('.settings-tab');- if (clickedTab && clickedTab.getAttribute('data-tab') === 'scheduler') {- setTimeout(() => {- this.fetchTasks();- }, 100);- }- });-- // Watch for changes to the tasks array to update UI- this.$watch('tasks', (newTasks) => {- this.updateTasksUI();- });-- this.$watch('filterType', () => {- this.updateTasksUI();- });-- this.$watch('filterState', () => {- this.updateTasksUI();- });-- // Set up default configuration- this.viewMode = localStorage.getItem('scheduler_view_mode') || 'list';- this.selectedTask = null;- this.expandedTaskId = null;- this.editingTask = {- name: '',- type: 'scheduled',- state: 'idle',- schedule: {- minute: '*',- hour: '*',- day: '*',- month: '*',- weekday: '*',- timezone: getUserTimezone()- },- token: this.generateRandomToken ? this.generateRandomToken() : '',- plan: {- todo: [],- in_progress: null,- done: []- },- system_prompt: '',- prompt: '',- attachments: [],- project: null,- dedicated_context: true,- };- this.refreshProjectOptions();-- // Initialize Flatpickr for date/time pickers after Alpine is fully initialized- this.$nextTick(() => {- // Wait until DOM is updated- setTimeout(() => {- if (this.isCreating) {- this.initFlatpickr('create');- } else if (this.isEditing) {- this.initFlatpickr('edit');- }- }, 100);- });-- // Cleanup on component destruction- this.$cleanup = () => {- console.log('Cleaning up schedulerSettings component');- this.stopPolling();-- // Clean up any Flatpickr instances- const createInput = document.getElementById('newPlannedTime-create');- if (createInput && createInput._flatpickr) {- createInput._flatpickr.destroy();- }-- const editInput = document.getElementById('newPlannedTime-edit');- if (editInput && editInput._flatpickr) {- editInput._flatpickr.destroy();- }- };- },-- // Start polling for task updates- startPolling() {- // Don't start if already polling- if (this.pollingInterval) {- console.log('Polling already active, not starting again');- return;- }-- console.log('Starting task polling');- this.pollingActive = true;-- // Fetch immediately, then set up interval for every 2 seconds- this.fetchTasks();- this.pollingInterval = setInterval(() => {- if (this.pollingActive) {- this.fetchTasks();- }- }, 2000); // Poll every 2 seconds as requested- },-- // Stop polling when tab is inactive- stopPolling() {- console.log('Stopping task polling');- this.pollingActive = false;-- if (this.pollingInterval) {- clearInterval(this.pollingInterval);- this.pollingInterval = null;- }- },-- // Fetch tasks from API- async fetchTasks() {- // Don't fetch if polling is inactive (prevents race conditions)- if (!this.pollingActive && this.pollingInterval) {- return;- }-- // Don't fetch while creating/editing a task- if (this.isCreating || this.isEditing) {- return;- }-- this.isLoading = true;- try {- const response = await fetchApi('/scheduler_tasks_list', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({- timezone: getUserTimezone()- })- });-- if (!response.ok) {- throw new Error('Failed to fetch tasks');- }-- const data = await response.json();-- // Check if data.tasks exists and is an array- if (!data || !data.tasks) {- console.error('Invalid response: data.tasks is missing', data);- this.tasks = [];- } else if (!Array.isArray(data.tasks)) {- console.error('Invalid response: data.tasks is not an array', data.tasks);- this.tasks = [];- } else {- // Verify each task has necessary properties- const validTasks = data.tasks.filter(task => {- if (!task || typeof task !== 'object') {- console.error('Invalid task (not an object):', task);- return false;- }- if (!task.uuid) {- console.error('Task missing uuid:', task);- return false;- }- if (!task.name) {- console.error('Task missing name:', task);- return false;- }- if (!task.type) {- console.error('Task missing type:', task);- return false;- }- return true;- });-- if (validTasks.length !== data.tasks.length) {- console.warn(`Filtered out ${data.tasks.length - validTasks.length} invalid tasks`);- }-- this.tasks = validTasks;-- // Update UI using the shared function- this.updateTasksUI();- }- } catch (error) {- console.error('Error fetching tasks:', error);- // Only show toast for errors on manual refresh, not during polling- if (!this.pollingInterval) {- showToast('Failed to fetch tasks: ' + error.message, 'error');- }- // Reset tasks to empty array on error- this.tasks = [];- } finally {- this.isLoading = false;- }- },-- // Change sort field/direction- changeSort(field) {- if (this.sortField === field) {- // Toggle direction if already sorting by this field- this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';- } else {- // Set new sort field and default to ascending- this.sortField = field;- this.sortDirection = 'asc';- }- },-- // Toggle expanded task row- toggleTaskExpand(taskId) {- if (this.expandedTaskId === taskId) {- this.expandedTaskId = null;- } else {- this.expandedTaskId = taskId;- }- },-- // Show task detail view- showTaskDetail(taskId) {- const task = this.tasks.find(t => t.uuid === taskId);- if (!task) {- showToast('Task not found', 'error');- return;- }-- // Create a copy of the task to avoid modifying the original- this.selectedTaskForDetail = JSON.parse(JSON.stringify(task));-- // Ensure attachments is always an array- if (!this.selectedTaskForDetail.attachments) {- this.selectedTaskForDetail.attachments = [];- }-- this.viewMode = 'detail';- },-- // Close detail view and return to list- closeTaskDetail() {- this.selectedTaskForDetail = null;- this.viewMode = 'list';- },-- // Format date for display- formatDate(dateString) {- if (!dateString) return 'Never';- return formatDateTime(dateString, 'full');- },-- // Format plan for display- formatPlan(task) {- if (!task || !task.plan) return 'No plan';-- const todoCount = Array.isArray(task.plan.todo) ? task.plan.todo.length : 0;- const inProgress = task.plan.in_progress ? 'Yes' : 'No';- const doneCount = Array.isArray(task.plan.done) ? task.plan.done.length : 0;-- let nextRun = '';- if (Array.isArray(task.plan.todo) && task.plan.todo.length > 0) {- try {- const nextTime = new Date(task.plan.todo[0]);-- // Verify it's a valid date before formatting- if (!isNaN(nextTime.getTime())) {- nextRun = formatDateTime(nextTime, 'short');- } else {- nextRun = 'Invalid date';- console.warn(`Invalid date format in plan.todo[0]: ${task.plan.todo[0]}`);- }- } catch (error) {- console.error(`Error formatting next run time: ${error.message}`);- nextRun = 'Error';- }- } else {- nextRun = 'None';- }-- return `Next: ${nextRun}\nTodo: ${todoCount}\nIn Progress: ${inProgress}\nDone: ${doneCount}`;- },-- // Format schedule for display- formatSchedule(task) {- if (!task.schedule) return 'None';-- let schedule = '';- if (typeof task.schedule === 'string') {- schedule = task.schedule;- } else if (typeof task.schedule === 'object') {- // Display only the cron parts, not the timezone- schedule = `${task.schedule.minute || '*'} ${task.schedule.hour || '*'} ${task.schedule.day || '*'} ${task.schedule.month || '*'} ${task.schedule.weekday || '*'}`;- }-- return schedule;- },-- // Get CSS class for state badge- getStateBadgeClass(state) {- switch (state) {- case 'idle': return 'scheduler-status-idle';- case 'running': return 'scheduler-status-running';- case 'disabled': return 'scheduler-status-disabled';- case 'error': return 'scheduler-status-error';- default: return '';- }- },-- deriveActiveProject() {- const selected = chatsStore?.selectedContext || null;- if (!selected || !selected.project) {- return null;- }-- const project = selected.project;- return {- name: project.name || null,- title: project.title || project.name || null,- color: project.color || '',- };- },-- formatProjectName(project) {- if (!project) {- return 'No Project';- }- const title = project.title || project.name;- return title || 'No Project';- },-- formatProjectLabel(project) {- return `Project: ${this.formatProjectName(project)}`;- },-- async refreshProjectOptions() {- try {- if (!Array.isArray(projectsStore.projectList) || !projectsStore.projectList.length) {- if (typeof projectsStore.loadProjectsList === 'function') {- await projectsStore.loadProjectsList();- }- }- } catch (error) {- console.warn('schedulerSettings: failed to load project list', error);- }-- const list = Array.isArray(projectsStore.projectList) ? projectsStore.projectList : [];- this.projectOptions = list.map((proj) => ({- name: proj.name,- title: proj.title || proj.name,- color: proj.color || '',- }));- },-- onProjectSelect(slug) {- this.selectedProjectSlug = slug || '';- if (!slug) {- this.editingTask.project = null;- return;- }-- const option = this.projectOptions.find((item) => item.name === slug);- if (option) {- this.editingTask.project = { ...option };- } else {- this.editingTask.project = {- name: slug,- title: slug,- color: '',- };- }- },-- extractTaskProject(task) {- if (!task) {- return null;- }-- const slug = task.project_name || null;- const project = task.project || {};- const title = project.name || slug;- const color = task.project_color || project.color || '';-- if (!slug && !title) {- return null;- }-- return {- name: slug,- title: title || slug,- color: color,- };- },-- formatTaskProject(task) {- return this.formatProjectName(this.extractTaskProject(task));- },-- // Create a new task- async startCreateTask() {- this.isCreating = true;- this.isEditing = false;- document.querySelector('[x-data="schedulerSettings"]')?.setAttribute('data-editing-state', 'creating');- await this.refreshProjectOptions();- const activeProject = this.deriveActiveProject();- let initialProject = activeProject ? { ...activeProject } : null;- if (!initialProject && this.projectOptions.length > 0) {- initialProject = { ...this.projectOptions[0] };- }-- this.editingTask = {- name: '',- type: 'scheduled', // Default to scheduled- state: 'idle', // Initialize with idle state- schedule: {- minute: '*',- hour: '*',- day: '*',- month: '*',- weekday: '*',- timezone: getUserTimezone()- },- token: this.generateRandomToken(), // Generate token even for scheduled tasks to prevent undefined errors- plan: { // Initialize plan for all task types to prevent undefined errors- todo: [],- in_progress: null,- done: []- },- system_prompt: '',- prompt: '',- attachments: [], // Always initialize as an empty array- project: initialProject,- dedicated_context: true,- };- this.selectedProjectSlug = initialProject && initialProject.name ? initialProject.name : '';-- // Set up Flatpickr after the component is visible- this.$nextTick(() => {- this.initFlatpickr('create');- });- },-- // Edit an existing task- async startEditTask(taskId) {- const task = this.tasks.find(t => t.uuid === taskId);- if (!task) {- showToast('Task not found', 'error');- return;- }-- this.isCreating = false;- this.isEditing = true;- document.querySelector('[x-data="schedulerSettings"]')?.setAttribute('data-editing-state', 'editing');-- // Create a deep copy to avoid modifying the original- this.editingTask = JSON.parse(JSON.stringify(task));- const projectSlug = task.project_name || null;- const projectDisplay = (task.project && task.project.name) || projectSlug;- const projectColor = task.project_color || (task.project ? task.project.color : '') || '';- this.editingTask.project = projectSlug || projectDisplay ? {- name: projectSlug,- title: projectDisplay,- color: projectColor,- } : null;- this.editingTask.dedicated_context = !!task.dedicated_context;- this.selectedProjectSlug = this.editingTask.project && this.editingTask.project.name ? this.editingTask.project.name : '';-- // Debug log- console.log('Task data for editing:', task);- console.log('Attachments from task:', task.attachments);-- // Ensure state is set with a default if missing- if (!this.editingTask.state) this.editingTask.state = 'idle';-- // Always initialize schedule to prevent UI errors- // All task types need this structure for the form to work properly- if (!this.editingTask.schedule || typeof this.editingTask.schedule === 'string') {- let scheduleObj = {- minute: '*',- hour: '*',- day: '*',- month: '*',- weekday: '*',- timezone: getUserTimezone()- };-- // If it's a string, parse it- if (typeof this.editingTask.schedule === 'string') {- const parts = this.editingTask.schedule.split(' ');- if (parts.length >= 5) {- scheduleObj.minute = parts[0] || '*';- scheduleObj.hour = parts[1] || '*';- scheduleObj.day = parts[2] || '*';- scheduleObj.month = parts[3] || '*';- scheduleObj.weekday = parts[4] || '*';- }- }-- this.editingTask.schedule = scheduleObj;- } else {- // Ensure timezone exists in the schedule- if (!this.editingTask.schedule.timezone) {- this.editingTask.schedule.timezone = getUserTimezone();- }- }-- // Ensure attachments is always an array- if (!this.editingTask.attachments) {- this.editingTask.attachments = [];- } else if (typeof this.editingTask.attachments === 'string') {- // Handle case where attachments might be stored as a string- this.editingTask.attachments = this.editingTask.attachments- .split('\n')- .map(line => line.trim())- .filter(line => line.length > 0);- } else if (!Array.isArray(this.editingTask.attachments)) {- // If not an array or string, set to empty array- this.editingTask.attachments = [];- }-- // Ensure appropriate properties are initialized based on task type- if (this.editingTask.type === 'scheduled') {- // Initialize token for scheduled tasks to prevent undefined errors if UI accesses it- if (!this.editingTask.token) {- this.editingTask.token = '';- }-- // Initialize plan stub for scheduled tasks to prevent undefined errors- if (!this.editingTask.plan) {- this.editingTask.plan = {- todo: [],- in_progress: null,- done: []- };- }- } else if (this.editingTask.type === 'adhoc') {- // Initialize token if it doesn't exist- if (!this.editingTask.token) {- this.editingTask.token = this.generateRandomToken();- console.log('Generated new token for adhoc task:', this.editingTask.token);- }-- console.log('Setting token for adhoc task:', this.editingTask.token);-- // Initialize plan stub for adhoc tasks to prevent undefined errors- if (!this.editingTask.plan) {- this.editingTask.plan = {- todo: [],- in_progress: null,- done: []- };- }- } else if (this.editingTask.type === 'planned') {- // Initialize plan if it doesn't exist- if (!this.editingTask.plan) {- this.editingTask.plan = {- todo: [],- in_progress: null,- done: []- };- }-- // Ensure todo is an array- if (!Array.isArray(this.editingTask.plan.todo)) {- this.editingTask.plan.todo = [];- }-- // Initialize token to prevent undefined errors- if (!this.editingTask.token) {- this.editingTask.token = '';- }- }-- // Set up Flatpickr after the component is visible and task data is loaded- this.$nextTick(() => {- this.initFlatpickr('edit');- });- },-- // Cancel editing- cancelEdit() {- // Clean up Flatpickr instances- const destroyFlatpickr = (inputId) => {- const input = document.getElementById(inputId);- if (input && input._flatpickr) {- console.log(`Destroying Flatpickr instance for ${inputId}`);- input._flatpickr.destroy();-- // Also remove any wrapper elements that might have been created- const wrapper = input.closest('.scheduler-flatpickr-wrapper');- if (wrapper && wrapper.parentNode) {- // Move the input back to its original position- wrapper.parentNode.insertBefore(input, wrapper);- // Remove the wrapper- wrapper.parentNode.removeChild(wrapper);- }-- // Remove any added classes- input.classList.remove('scheduler-flatpickr-input');- }- };-- if (this.isCreating) {- destroyFlatpickr('newPlannedTime-create');- } else if (this.isEditing) {- destroyFlatpickr('newPlannedTime-edit');- }-- // Reset to initial state but keep default values to prevent errors- this.editingTask = {- name: '',- type: 'scheduled',- state: 'idle', // Initialize with idle state- schedule: {- minute: '*',- hour: '*',- day: '*',- month: '*',- weekday: '*',- timezone: getUserTimezone()- },- token: '',- plan: { // Initialize plan for planned tasks- todo: [],- in_progress: null,- done: []- },- system_prompt: '',- prompt: '',- attachments: [], // Always initialize as an empty array- project: null,- dedicated_context: true,- };- this.selectedProjectSlug = '';- this.isCreating = false;- this.isEditing = false;- document.querySelector('[x-data="schedulerSettings"]')?.removeAttribute('data-editing-state');- },-- // Save task (create new or update existing)- async saveTask() {- // Validate task data- if (!this.editingTask.name.trim() || !this.editingTask.prompt.trim()) {- // showToast('Task name and prompt are required', 'error');- alert('Task name and prompt are required');- return;- }-- try {- let apiEndpoint, taskData;-- // Prepare task data- taskData = {- name: this.editingTask.name,- system_prompt: this.editingTask.system_prompt || '',- prompt: this.editingTask.prompt || '',- state: this.editingTask.state || 'idle', // Include state in task data- timezone: getUserTimezone()- };-- if (this.isCreating && this.editingTask.project) {- if (this.editingTask.project.name) {- taskData.project_name = this.editingTask.project.name;- }- if (this.editingTask.project.color) {- taskData.project_color = this.editingTask.project.color;- }- }-- // Process attachments - now always stored as array- taskData.attachments = Array.isArray(this.editingTask.attachments)- ? this.editingTask.attachments- .map(line => typeof line === 'string' ? line.trim() : line)- .filter(line => line && line.trim().length > 0)- : [];-- // Handle task type specific data- if (this.editingTask.type === 'scheduled') {- // Ensure schedule is properly formatted as an object- if (typeof this.editingTask.schedule === 'string') {- // Parse string schedule into object- const parts = this.editingTask.schedule.split(' ');- taskData.schedule = {- minute: parts[0] || '*',- hour: parts[1] || '*',- day: parts[2] || '*',- month: parts[3] || '*',- weekday: parts[4] || '*',- timezone: getUserTimezone() // Add timezone to schedule object- };- } else {- // Use object schedule directly but ensure timezone is included- taskData.schedule = {- ...this.editingTask.schedule,- timezone: this.editingTask.schedule.timezone || getUserTimezone()- };- }- // Don't send token or plan for scheduled tasks- delete taskData.token;- delete taskData.plan;- } else if (this.editingTask.type === 'adhoc') {- // Ad-hoc task with token- // Ensure token is a non-empty string, generate a new one if needed- if (!this.editingTask.token) {- this.editingTask.token = this.generateRandomToken();- console.log('Generated new token for adhoc task:', this.editingTask.token);- }-- console.log('Setting token in taskData:', this.editingTask.token);- taskData.token = this.editingTask.token;-- // Don't send schedule or plan for adhoc tasks- delete taskData.schedule;- delete taskData.plan;- } else if (this.editingTask.type === 'planned') {- // Planned task with plan- // Make sure plan exists and has required properties- if (!this.editingTask.plan) {- this.editingTask.plan = {- todo: [],- in_progress: null,- done: []- };- }-- // Ensure todo and done are arrays- if (!Array.isArray(this.editingTask.plan.todo)) {- this.editingTask.plan.todo = [];- }-- if (!Array.isArray(this.editingTask.plan.done)) {- this.editingTask.plan.done = [];- }-- // Validate each date in the todo list to ensure it's a valid ISO string- const validatedTodo = [];- for (const dateStr of this.editingTask.plan.todo) {- try {- const date = new Date(dateStr);- if (!isNaN(date.getTime())) {- validatedTodo.push(date.toISOString());- } else {- console.warn(`Skipping invalid date in todo list: ${dateStr}`);- }- } catch (error) {- console.warn(`Error processing date: ${error.message}`);- }- }-- // Replace with validated list- this.editingTask.plan.todo = validatedTodo;-- // Sort the todo items by date (earliest first)- this.editingTask.plan.todo.sort();-- // Set the plan in taskData- taskData.plan = {- todo: this.editingTask.plan.todo,- in_progress: this.editingTask.plan.in_progress,- done: this.editingTask.plan.done || []- };-- // Log the plan data for debugging- console.log('Planned task plan data:', JSON.stringify(taskData.plan, null, 2));-- // Don't send schedule or token for planned tasks- delete taskData.schedule;- delete taskData.token;- }-- // Determine if creating or updating- if (this.isCreating) {- apiEndpoint = '/scheduler_task_create';- } else {- apiEndpoint = '/scheduler_task_update';- taskData.task_id = this.editingTask.uuid;- }-- // Debug: Log the final task data being sent- console.log('Final task data being sent to API:', JSON.stringify(taskData, null, 2));-- // Make API request- const response = await fetchApi(apiEndpoint, {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify(taskData)- });-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || 'Failed to save task');- }-- // Parse response data to get the created/updated task- const responseData = await response.json();-- // Show success message- showToast(this.isCreating ? 'Task created successfully' : 'Task updated successfully', 'success');-- // Immediately update the UI if the response includes the task- if (responseData && responseData.task) {- console.log('Task received in response:', responseData.task);-- // Update the tasks array- if (this.isCreating) {- // For new tasks, add to the array- this.tasks = [...this.tasks, responseData.task];- } else {- // For updated tasks, replace the existing one- this.tasks = this.tasks.map(t =>- t.uuid === responseData.task.uuid ? responseData.task : t- );- }-- // Update UI using the shared function- this.updateTasksUI();- } else {- // Fallback to fetching tasks if no task in response- await this.fetchTasks();- }-- // Clean up Flatpickr instances- const destroyFlatpickr = (inputId) => {- const input = document.getElementById(inputId);- if (input && input._flatpickr) {- input._flatpickr.destroy();- }- };-- if (this.isCreating) {- destroyFlatpickr('newPlannedTime-create');- } else if (this.isEditing) {- destroyFlatpickr('newPlannedTime-edit');- }-- // Reset task data and form state- this.editingTask = {- name: '',- type: 'scheduled',- state: 'idle',- schedule: {- minute: '*',- hour: '*',- day: '*',- month: '*',- weekday: '*',- timezone: getUserTimezone()- },- token: '',- plan: {- todo: [],- in_progress: null,- done: []- },- system_prompt: '',- prompt: '',- attachments: [],- project: null,- dedicated_context: true,- };- this.isCreating = false;- this.isEditing = false;- document.querySelector('[x-data="schedulerSettings"]')?.removeAttribute('data-editing-state');- } catch (error) {- console.error('Error saving task:', error);- showToast('Failed to save task: ' + error.message, 'error');- }- },-- // Run a task- async runTask(taskId) {- try {- const response = await fetchApi('/scheduler_task_run', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({- task_id: taskId,- timezone: getUserTimezone()- })- });-- const data = await response.json();-- if (!response.ok) {- throw new Error(data?.error || 'Failed to run task');- }-- const toastMessage = data.warning || data.message || 'Task started successfully';- const toastType = data.warning ? 'warning' : 'success';- showToast(toastMessage, toastType);-- // Refresh task list- this.fetchTasks();- } catch (error) {- console.error('Error running task:', error);- showToast('Failed to run task: ' + error.message, 'error');- }- },-- // Reset a task's state- async resetTaskState(taskId) {- try {- const task = this.tasks.find(t => t.uuid === taskId);- if (!task) {- showToast('Task not found', 'error');- return;- }-- // Check if task is already in idle state- if (task.state === 'idle') {- showToast('Task is already in idle state', 'info');- return;- }-- this.showLoadingState = true;-- // Call API to update the task state- const response = await fetchApi('/scheduler_task_update', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({- task_id: taskId,- state: 'idle', // Always reset to idle state- timezone: getUserTimezone()- })- });-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || 'Failed to reset task state');- }-- showToast('Task state reset to idle', 'success');-- // Refresh task list- await this.fetchTasks();- this.showLoadingState = false;- } catch (error) {- console.error('Error resetting task state:', error);- showToast('Failed to reset task state: ' + error.message, 'error');- this.showLoadingState = false;- }- },-- // Delete a task- async deleteTask(taskId) {- // Confirm deletion- if (!confirm('Are you sure you want to delete this task? This action cannot be undone.')) {- return;- }-- try {-- // if we delete selected context, switch to another first- await chatsStore.switchFromContext(taskId);-- const response = await fetchApi('/scheduler_task_delete', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({- task_id: taskId,- timezone: getUserTimezone()- })- });-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || 'Failed to delete task');- }-- showToast('Task deleted successfully', 'success');-- // If we were viewing the detail of the deleted task, close the detail view- if (this.selectedTaskForDetail && this.selectedTaskForDetail.uuid === taskId) {- this.closeTaskDetail();- }-- // Immediately update UI without waiting for polling- this.tasks = this.tasks.filter(t => t.uuid !== taskId);-- // Update UI using the shared function- this.updateTasksUI();- } catch (error) {- console.error('Error deleting task:', error);- showToast('Failed to delete task: ' + error.message, 'error');- }- },-- // Initialize datetime input with default value (30 minutes from now)- initDateTimeInput(event) {- if (!event.target.value) {- const now = new Date();- now.setMinutes(now.getMinutes() + 30);-- // Format as YYYY-MM-DDThh:mm- const year = now.getFullYear();- const month = String(now.getMonth() + 1).padStart(2, '0');- const day = String(now.getDate()).padStart(2, '0');- const hours = String(now.getHours()).padStart(2, '0');- const minutes = String(now.getMinutes()).padStart(2, '0');-- event.target.value = `${year}-${month}-${day}T${hours}:${minutes}`;-- // If using Flatpickr, update it as well- if (event.target._flatpickr) {- event.target._flatpickr.setDate(event.target.value);- }- }- },-- // Generate a random token for ad-hoc tasks- generateRandomToken() {- const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';- let token = '';- for (let i = 0; i < 16; i++) {- token += characters.charAt(Math.floor(Math.random() * characters.length));- }- return token;- },-- // Getter for filtered tasks- get filteredTasks() {- // Make sure we have tasks to filter- if (!Array.isArray(this.tasks)) {- console.warn('Tasks is not an array:', this.tasks);- return [];- }-- let filtered = [...this.tasks];-- // Apply type filter with case-insensitive comparison- if (this.filterType && this.filterType !== 'all') {- filtered = filtered.filter(task => {- if (!task.type) return false;- return String(task.type).toLowerCase() === this.filterType.toLowerCase();- });- }-- // Apply state filter with case-insensitive comparison- if (this.filterState && this.filterState !== 'all') {- filtered = filtered.filter(task => {- if (!task.state) return false;- return String(task.state).toLowerCase() === this.filterState.toLowerCase();- });- }-- // Sort the filtered tasks- return this.sortTasks(filtered);- },-- // Sort the tasks based on sort field and direction- sortTasks(tasks) {- if (!Array.isArray(tasks) || tasks.length === 0) {- return tasks;- }-- return [...tasks].sort((a, b) => {- if (!this.sortField) return 0;-- const fieldA = a[this.sortField];- const fieldB = b[this.sortField];-- // Handle cases where fields might be undefined- if (fieldA === undefined && fieldB === undefined) return 0;- if (fieldA === undefined) return 1;- if (fieldB === undefined) return -1;-- // For dates, convert to timestamps- if (this.sortField === 'createdAt' || this.sortField === 'updatedAt') {- const dateA = new Date(fieldA).getTime();- const dateB = new Date(fieldB).getTime();- return this.sortDirection === 'asc' ? dateA - dateB : dateB - dateA;- }-- // For string comparisons- if (typeof fieldA === 'string' && typeof fieldB === 'string') {- return this.sortDirection === 'asc'- ? fieldA.localeCompare(fieldB)- : fieldB.localeCompare(fieldA);- }-- // For numerical comparisons- return this.sortDirection === 'asc' ? fieldA - fieldB : fieldB - fieldA;- });- },-- // Computed property for attachments text representation- get attachmentsText() {- // Ensure we always have an array to work with- const attachments = Array.isArray(this.editingTask.attachments)- ? this.editingTask.attachments- : [];-- // Join array items with newlines- return attachments.join('\n');- },-- // Setter for attachments text - preserves empty lines during editing- set attachmentsText(value) {- if (typeof value === 'string') {- // Just split by newlines without filtering to preserve editing experience- this.editingTask.attachments = value.split('\n');- } else {- // Fallback to empty array if not a string- this.editingTask.attachments = [];- }- },-- // Debug method to test filtering logic- testFiltering() {- console.group('SchedulerSettings Debug: Filter Test');- console.log('Current Filter Settings:');- console.log('- Filter Type:', this.filterType);- console.log('- Filter State:', this.filterState);- console.log('- Sort Field:', this.sortField);- console.log('- Sort Direction:', this.sortDirection);-- // Check if tasks is an array- if (!Array.isArray(this.tasks)) {- console.error('ERROR: this.tasks is not an array!', this.tasks);- console.groupEnd();- return;- }-- console.log(`Raw Tasks (${this.tasks.length}):`, this.tasks);-- // Test filtering by type- console.group('Filter by Type Test');- ['all', 'adhoc', 'scheduled', 'recurring'].forEach(type => {- const filtered = this.tasks.filter(task =>- type === 'all' ||- (task.type && String(task.type).toLowerCase() === type)- );- console.log(`Type "${type}": ${filtered.length} tasks`, filtered);- });- console.groupEnd();-- // Test filtering by state- console.group('Filter by State Test');- ['all', 'idle', 'running', 'completed', 'failed'].forEach(state => {- const filtered = this.tasks.filter(task =>- state === 'all' ||- (task.state && String(task.state).toLowerCase() === state)- );- console.log(`State "${state}": ${filtered.length} tasks`, filtered);- });- console.groupEnd();-- // Show current filtered tasks- console.log('Current Filtered Tasks:', this.filteredTasks);-- console.groupEnd();- },-- // New comprehensive debug method- debugTasks() {- console.group('SchedulerSettings Comprehensive Debug');-- // Component state- console.log('Component State:');- console.log({- filterType: this.filterType,- filterState: this.filterState,- sortField: this.sortField,- sortDirection: this.sortDirection,- isLoading: this.isLoading,- isEditing: this.isEditing,- isCreating: this.isCreating,- viewMode: this.viewMode- });-- // Tasks validation- if (!this.tasks) {- console.error('ERROR: this.tasks is undefined or null!');- console.groupEnd();- return;- }-- if (!Array.isArray(this.tasks)) {- console.error('ERROR: this.tasks is not an array!', typeof this.tasks, this.tasks);- console.groupEnd();- return;- }-- // Raw tasks- console.group('Raw Tasks');- console.log(`Count: ${this.tasks.length}`);- if (this.tasks.length > 0) {- console.table(this.tasks.map(t => ({- uuid: t.uuid,- name: t.name,- type: t.type,- state: t.state- })));-- // Inspect first task in detail- console.log('First Task Structure:', JSON.stringify(this.tasks[0], null, 2));- } else {- console.log('No tasks available');- }- console.groupEnd();-- // Filtered tasks- console.group('Filtered Tasks');- const filteredTasks = this.filteredTasks;- console.log(`Count: ${filteredTasks.length}`);- if (filteredTasks.length > 0) {- console.table(filteredTasks.map(t => ({- uuid: t.uuid,- name: t.name,- type: t.type,- state: t.state- })));- } else {- console.log('No filtered tasks');- }- console.groupEnd();-- // Check for potential issues- console.group('Potential Issues');-- // Check for case mismatches- if (this.tasks.length > 0 && filteredTasks.length === 0) {- console.warn('Filter seems to exclude all tasks. Checking why:');-- // Check type values- const uniqueTypes = [...new Set(this.tasks.map(t => t.type))];- console.log('Unique task types in data:', uniqueTypes);-- // Check state values- const uniqueStates = [...new Set(this.tasks.map(t => t.state))];- console.log('Unique task states in data:', uniqueStates);-- // Check for exact mismatches- if (this.filterType !== 'all') {- const typeMatch = this.tasks.some(t =>- t.type && String(t.type).toLowerCase() === this.filterType.toLowerCase()- );- console.log(`Type "${this.filterType}" matches found:`, typeMatch);- }-- if (this.filterState !== 'all') {- const stateMatch = this.tasks.some(t =>- t.state && String(t.state).toLowerCase() === this.filterState.toLowerCase()- );- console.log(`State "${this.filterState}" matches found:`, stateMatch);- }- }-- // Check for undefined or null values- const hasUndefinedType = this.tasks.some(t => t.type === undefined || t.type === null);- const hasUndefinedState = this.tasks.some(t => t.state === undefined || t.state === null);-- if (hasUndefinedType) {- console.warn('Some tasks have undefined or null type values!');- }-- if (hasUndefinedState) {- console.warn('Some tasks have undefined or null state values!');- }-- console.groupEnd();-- console.groupEnd();- },-- // Initialize Flatpickr datetime pickers for both create and edit forms- /**- * Initialize Flatpickr date/time pickers for scheduler forms- *- * @param {string} mode - Which pickers to initialize: 'all', 'create', or 'edit'- * @returns {void}- */- initFlatpickr(mode = 'all') {- const initPicker = (inputId, refName, wrapperClass, options = {}) => {- // Try to get input using Alpine.js x-ref first (more reliable)- let input = this.$refs[refName];-- // Fall back to getElementById if x-ref is not available- if (!input) {- input = document.getElementById(inputId);- console.log(`Using getElementById fallback for ${inputId}`);- }-- if (!input) {- console.warn(`Input element ${inputId} not found by ID or ref`);- return null;- }-- // Create a wrapper around the input- const wrapper = document.createElement('div');- wrapper.className = wrapperClass || 'scheduler-flatpickr-wrapper';- wrapper.style.overflow = 'visible'; // Ensure dropdown can escape container-- // Replace the input with our wrapped version- input.parentNode.insertBefore(wrapper, input);- wrapper.appendChild(input);- input.classList.add('scheduler-flatpickr-input');-- // Default options- const defaultOptions = {- dateFormat: "Y-m-d H:i",- enableTime: true,- time_24hr: true,- static: false, // Not static so it will float- appendTo: document.body, // Append to body to avoid overflow issues- theme: "scheduler-theme",- allowInput: true,- positionElement: wrapper, // Position relative to wrapper- onOpen: function(selectedDates, dateStr, instance) {- // Ensure calendar is properly positioned and visible- instance.calendarContainer.style.zIndex = '9999';- instance.calendarContainer.style.position = 'absolute';- instance.calendarContainer.style.visibility = 'visible';- instance.calendarContainer.style.opacity = '1';-- // Add class to calendar container for our custom styling- instance.calendarContainer.classList.add('scheduler-theme');- },- // Set default date to 30 minutes from now if no date selected- onReady: function(selectedDates, dateStr, instance) {- if (!dateStr) {- const now = new Date();- now.setMinutes(now.getMinutes() + 30);- instance.setDate(now, true);- }- }- };-- // Merge options- const mergedOptions = {...defaultOptions, ...options};-- // Initialize flatpickr- const fp = flatpickr(input, mergedOptions);-- // Add a clear button- const clearButton = document.createElement('button');- clearButton.className = 'scheduler-flatpickr-clear';- clearButton.innerHTML = '×';- clearButton.type = 'button';- clearButton.addEventListener('click', (e) => {- e.preventDefault();- e.stopPropagation();- if (fp) {- fp.clear();- }- });- wrapper.appendChild(clearButton);-- return fp;- };-- // Clear any existing Flatpickr instances to prevent duplication- if (mode === 'all' || mode === 'create') {- const createInput = document.getElementById('newPlannedTime-create');- if (createInput && createInput._flatpickr) {- createInput._flatpickr.destroy();- }- }-- if (mode === 'all' || mode === 'edit') {- const editInput = document.getElementById('newPlannedTime-edit');- if (editInput && editInput._flatpickr) {- editInput._flatpickr.destroy();- }- }-- // Initialize new instances- if (mode === 'all' || mode === 'create') {- initPicker('newPlannedTime-create', 'plannedTimeCreate', 'scheduler-flatpickr-wrapper', {- minuteIncrement: 5,- defaultHour: new Date().getHours(),- defaultMinute: Math.ceil(new Date().getMinutes() / 5) * 5- });- }-- if (mode === 'all' || mode === 'edit') {- initPicker('newPlannedTime-edit', 'plannedTimeEdit', 'scheduler-flatpickr-wrapper', {- minuteIncrement: 5,- defaultHour: new Date().getHours(),- defaultMinute: Math.ceil(new Date().getMinutes() / 5) * 5- });- }- },-- // Update tasks UI- updateTasksUI() {- // First update filteredTasks if that method exists- if (typeof this.updateFilteredTasks === 'function') {- this.updateFilteredTasks();- }-- // Wait for UI to update- this.$nextTick(() => {- // Get empty state and task list elements- const emptyElement = document.querySelector('.scheduler-empty');- const tableElement = document.querySelector('.scheduler-task-list');-- // Calculate visibility state based on filtered tasks- const hasFilteredTasks = Array.isArray(this.filteredTasks) && this.filteredTasks.length > 0;-- // Update visibility directly- if (emptyElement) {- emptyElement.style.display = !hasFilteredTasks ? '' : 'none';- }-- if (tableElement) {- tableElement.style.display = hasFilteredTasks ? '' : 'none';- }- });- }- };-};---// Only define the component if it doesn't already exist or extend the existing one-if (!window.schedulerSettings) {- console.log('Defining schedulerSettings component from scratch');- window.schedulerSettings = fullComponentImplementation;-} else {- console.log('Extending existing schedulerSettings component');- // Store the original function- const originalSchedulerSettings = window.schedulerSettings;-- // Replace with enhanced version that merges the pre-initialized stub with the full implementation- window.schedulerSettings = function() {- // Get the base pre-initialized component- const baseComponent = originalSchedulerSettings();-- // Create a backup of the original init function- const originalInit = baseComponent.init || function() {};-- // Create our enhanced init function that adds the missing functionality- baseComponent.init = function() {- // Call the original init if it exists- originalInit.call(this);-- console.log('Enhanced init running: adding missing methods to component');-- // Get the full implementation- const fullImpl = fullComponentImplementation();-- // Register all implementation methods (except init) directly- Object.keys(fullImpl).forEach((key) => {- if (key === 'init') {- return;- }- if (typeof fullImpl[key] === 'function') {- console.log(`Registering method: ${key}`);- this[key] = fullImpl[key];- }- });-- if (typeof this.refreshProjectOptions === 'function') {- this.refreshProjectOptions();- }-- // hack to expose deleteTask- window.deleteTaskGlobal = this.deleteTask.bind(this);-- // Make sure we have a filteredTasks array initialized- this.filteredTasks = [];-- // Initialize essential properties if missing- if (!Array.isArray(this.tasks)) {- this.tasks = [];- }-- if (!Array.isArray(this.projectOptions)) {- this.projectOptions = [];- }-- if (typeof this.selectedProjectSlug !== 'string') {- this.selectedProjectSlug = '';- }-- // Make sure attachmentsText getter/setter are defined- if (!Object.getOwnPropertyDescriptor(this, 'attachmentsText')?.get) {- Object.defineProperty(this, 'attachmentsText', {- get: function() {- // Ensure we always have an array to work with- const attachments = Array.isArray(this.editingTask?.attachments)- ? this.editingTask.attachments- : [];-- // Join array items with newlines- return attachments.join('\n');- },- set: function(value) {- if (!this.editingTask) {- this.editingTask = {- attachments: [],- project: null,- dedicated_context: true,- };- }-- if (typeof value === 'string') {- // Just split by newlines without filtering to preserve editing experience- this.editingTask.attachments = value.split('\n');- } else {- // Fallback to empty array if not a string- this.editingTask.attachments = [];- }- }- });- }-- // Add methods for updating filteredTasks directly- if (typeof this.updateFilteredTasks !== 'function') {- this.updateFilteredTasks = function() {- // Make sure we have tasks to filter- if (!Array.isArray(this.tasks)) {- this.filteredTasks = [];- return;- }-- let filtered = [...this.tasks];-- // Apply type filter with case-insensitive comparison- if (this.filterType && this.filterType !== 'all') {- filtered = filtered.filter(task => {- if (!task.type) return false;- return String(task.type).toLowerCase() === this.filterType.toLowerCase();- });- }-- // Apply state filter with case-insensitive comparison- if (this.filterState && this.filterState !== 'all') {- filtered = filtered.filter(task => {- if (!task.state) return false;- return String(task.state).toLowerCase() === this.filterState.toLowerCase();- });- }-- // Sort the filtered tasks- if (typeof this.sortTasks === 'function') {- filtered = this.sortTasks(filtered);- }-- // Directly update the filteredTasks property- this.filteredTasks = filtered;- };- }-- // Set up watchers to update filtered tasks when dependencies change- this.$nextTick(() => {- // Update filtered tasks when raw tasks change- this.$watch('tasks', () => {- this.updateFilteredTasks();- });-- // Update filtered tasks when filter type changes- this.$watch('filterType', () => {- this.updateFilteredTasks();- });-- // Update filtered tasks when filter state changes- this.$watch('filterState', () => {- this.updateFilteredTasks();- });-- // Update filtered tasks when sort field or direction changes- this.$watch('sortField', () => {- this.updateFilteredTasks();- });-- this.$watch('sortDirection', () => {- this.updateFilteredTasks();- });-- // Initial update- this.updateFilteredTasks();-- // Set up watcher for task type changes to initialize Flatpickr for planned tasks- this.$watch('editingTask.type', (newType) => {- if (newType === 'planned') {- this.$nextTick(() => {- // Reinitialize Flatpickr when switching to planned task type- if (this.isCreating) {- this.initFlatpickr('create');- } else if (this.isEditing) {- this.initFlatpickr('edit');- }- });- }- });-- // Initialize Flatpickr- this.$nextTick(() => {- if (typeof this.initFlatpickr === 'function') {- this.initFlatpickr();- } else {- console.error('initFlatpickr is not available');- }- });- });-- // Try fetching tasks after a short delay- setTimeout(() => {- if (typeof this.fetchTasks === 'function') {- this.fetchTasks();- } else {- console.error('fetchTasks still not available after enhancement');- }- }, 100);-- console.log('Enhanced init complete');- };-- return baseComponent;- };-}--// Force Alpine.js to register the component immediately-if (window.Alpine) {- // Alpine is already loaded, register now- console.log('Alpine already loaded, registering schedulerSettings component now');- window.Alpine.data('schedulerSettings', window.schedulerSettings);-} else {- // Wait for Alpine to load- document.addEventListener('alpine:init', () => {- console.log('Alpine:init - immediately registering schedulerSettings component');- Alpine.data('schedulerSettings', window.schedulerSettings);- });-}--// Add a document ready event handler to ensure the scheduler tab can be clicked on first load-document.addEventListener('DOMContentLoaded', function() {- console.log('DOMContentLoaded - setting up scheduler tab click handler');- // Setup scheduler tab click handling- const setupSchedulerTab = () => {- const settingsModal = document.getElementById('settingsModal');- if (!settingsModal) {- setTimeout(setupSchedulerTab, 100);- return;- }-- // Create a global event listener for clicks on the scheduler tab- document.addEventListener('click', function(e) {- // Find if the click was on the scheduler tab or its children- const schedulerTab = e.target.closest('.settings-tab[title="Task Scheduler"]');- if (!schedulerTab) return;-- e.preventDefault();- e.stopPropagation();-- // Get the settings modal data- try {- const modalData = Alpine.$data(settingsModal);- if (modalData.activeTab !== 'scheduler') {- // Directly call the modal's switchTab method- modalData.switchTab('scheduler');- }-- // Force start polling and fetch tasks immediately when tab is selected- setTimeout(() => {- // Get the scheduler component data- const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');- if (schedulerElement) {- const schedulerData = Alpine.$data(schedulerElement);-- // Force fetch tasks and start polling- if (typeof schedulerData.fetchTasks === 'function') {- schedulerData.fetchTasks();- } else {- console.error('fetchTasks is not a function on scheduler component');- }-- if (typeof schedulerData.startPolling === 'function') {- schedulerData.startPolling();- } else {- console.error('startPolling is not a function on scheduler component');- }- } else {- console.error('Could not find scheduler component element');- }- }, 100);- } catch (err) {- console.error('Error handling scheduler tab click:', err);- }- }, true); // Use capture phase to intercept before Alpine.js handlers- };-- // Initialize the tab handling- setupSchedulerTab();-});diff --git a/webui/js/settings.js b/webui/js/settings.jsdeleted file mode 100644index 059d64541..000000000--- a/webui/js/settings.js+++ /dev/null@@ -1,591 +0,0 @@-const settingsModalProxy = {- isOpen: false,- settings: {},- resolvePromise: null,- activeTab: 'agent', // Default tab- provider: 'cloudflared',-- // Computed property for filtered sections- get filteredSections() {- if (!this.settings || !this.settings.sections) return [];- const filteredSections = this.settings.sections.filter(section => section.tab === this.activeTab);-- // If no sections match the current tab (or all tabs are missing), show all sections- if (filteredSections.length === 0) {- return this.settings.sections;- }-- return filteredSections;- },-- // Switch tab method- switchTab(tabName) {- // Update our component state- this.activeTab = tabName;-- // Update the store safely- const store = Alpine.store('root');- if (store) {- store.activeTab = tabName;- }-- localStorage.setItem('settingsActiveTab', tabName);-- // Auto-scroll active tab into view after a short delay to ensure DOM updates- setTimeout(() => {- const activeTab = document.querySelector('.settings-tab.active');- if (activeTab) {- activeTab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });- }-- // When switching to the scheduler tab, initialize Flatpickr components- if (tabName === 'scheduler') {- console.log('Switching to scheduler tab, initializing Flatpickr');- const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');- if (schedulerElement) {- const schedulerData = Alpine.$data(schedulerElement);- if (schedulerData) {- // Start polling- if (typeof schedulerData.startPolling === 'function') {- schedulerData.startPolling();- }-- // Initialize Flatpickr if editing or creating- if (typeof schedulerData.initFlatpickr === 'function') {- // Check if we're creating or editing and initialize accordingly- if (schedulerData.isCreating) {- schedulerData.initFlatpickr('create');- } else if (schedulerData.isEditing) {- schedulerData.initFlatpickr('edit');- }- }-- // Force an immediate fetch- if (typeof schedulerData.fetchTasks === 'function') {- schedulerData.fetchTasks();- }- }- }- }- }, 10);- },-- async openModal() {- console.log('Settings modal opening');- const modalEl = document.getElementById('settingsModal');- const modalAD = Alpine.$data(modalEl);-- // First, ensure the store is updated properly- const store = Alpine.store('root');- if (store) {- // Set isOpen first to ensure proper state- store.isOpen = true;- }-- //get settings from backend- try {- const set = await sendJsonData("/settings_get", null);-- // First load the settings data without setting the active tab- const settings = {- "title": "Settings",- "buttons": [- {- "id": "save",- "title": "Save",- "classes": "btn btn-ok"- },- {- "id": "cancel",- "title": "Cancel",- "type": "secondary",- "classes": "btn btn-cancel"- }- ],- "sections": set.settings.sections- }-- // Update modal data- modalAD.isOpen = true;- modalAD.settings = settings;-- // Now set the active tab after the modal is open- // This ensures Alpine reactivity works as expected- setTimeout(() => {- // Get stored tab or default to 'agent'- const savedTab = localStorage.getItem('settingsActiveTab') || 'agent';- console.log(`Setting initial tab to: ${savedTab}`);-- // Directly set the active tab- modalAD.activeTab = savedTab;-- // Also update the store- if (store) {- store.activeTab = savedTab;- }-- localStorage.setItem('settingsActiveTab', savedTab);-- // Add a small delay *after* setting the tab to ensure scrolling works- setTimeout(() => {- const activeTabElement = document.querySelector('.settings-tab.active');- if (activeTabElement) {- activeTabElement.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });- }- // Debug log- const schedulerTab = document.querySelector('.settings-tab[title="Task Scheduler"]');- console.log(`Current active tab after direct set: ${modalAD.activeTab}`);- console.log('Scheduler tab active after direct initialization?',- schedulerTab && schedulerTab.classList.contains('active'));-- // Explicitly start polling if we're on the scheduler tab- if (modalAD.activeTab === 'scheduler') {- console.log('Settings opened directly to scheduler tab, initializing polling');- const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');- if (schedulerElement) {- const schedulerData = Alpine.$data(schedulerElement);- if (schedulerData && typeof schedulerData.startPolling === 'function') {- schedulerData.startPolling();- // Also force an immediate fetch- if (typeof schedulerData.fetchTasks === 'function') {- schedulerData.fetchTasks();- }- }- }- }- }, 10); // Small delay just for scrolling-- }, 5); // Keep a minimal delay for modal opening reactivity-- // Add a watcher to disable the Save button when a task is being created or edited- const schedulerComponent = document.querySelector('[x-data="schedulerSettings"]');- if (schedulerComponent) {- // Watch for changes to the scheduler's editing state- const checkSchedulerEditingState = () => {- const schedulerData = Alpine.$data(schedulerComponent);- if (schedulerData) {- // If we're on the scheduler tab and creating/editing a task, disable the Save button- const saveButton = document.querySelector('.modal-footer button.btn-ok');- if (saveButton && modalAD.activeTab === 'scheduler' &&- (schedulerData.isCreating || schedulerData.isEditing)) {- saveButton.disabled = true;- saveButton.classList.add('btn-disabled');- } else if (saveButton) {- saveButton.disabled = false;- saveButton.classList.remove('btn-disabled');- }- }- };-- // Add a mutation observer to detect changes in the scheduler component's state- const observer = new MutationObserver(checkSchedulerEditingState);- observer.observe(schedulerComponent, { attributes: true, subtree: true, childList: true });-- // Also watch for tab changes to update button state- modalAD.$watch('activeTab', checkSchedulerEditingState);-- // Initial check- setTimeout(checkSchedulerEditingState, 100);- }-- return new Promise(resolve => {- this.resolvePromise = resolve;- });-- } catch (e) {- window.toastFetchError("Error getting settings", e)- }- },-- async handleButton(buttonId) {- if (buttonId === 'save') {-- const modalEl = document.getElementById('settingsModal');- const modalAD = Alpine.$data(modalEl);- try {- resp = await window.sendJsonData("/settings_set", modalAD.settings);- } catch (e) {- window.toastFetchError("Error saving settings", e)- return- }- document.dispatchEvent(new CustomEvent('settings-updated', { detail: resp.settings }));- this.resolvePromise({- status: 'saved',- data: resp.settings- });- } else if (buttonId === 'cancel') {- this.handleCancel();- }-- // Stop scheduler polling if it's running- this.stopSchedulerPolling();-- // First update our component state- this.isOpen = false;-- // Then safely update the store- const store = Alpine.store('root');- if (store) {- // Use a slight delay to avoid reactivity issues- setTimeout(() => {- store.isOpen = false;- }, 10);- }- },-- async handleCancel() {- this.resolvePromise({- status: 'cancelled',- data: null- });-- // Stop scheduler polling if it's running- this.stopSchedulerPolling();-- // First update our component state- this.isOpen = false;-- // Then safely update the store- const store = Alpine.store('root');- if (store) {- // Use a slight delay to avoid reactivity issues- setTimeout(() => {- store.isOpen = false;- }, 10);- }- },-- // Add a helper method to stop scheduler polling- stopSchedulerPolling() {- // Find the scheduler component and stop polling if it exists- const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');- if (schedulerElement) {- const schedulerData = Alpine.$data(schedulerElement);- if (schedulerData && typeof schedulerData.stopPolling === 'function') {- console.log('Stopping scheduler polling on modal close');- schedulerData.stopPolling();- }- }- },-- async handleFieldButton(field) {- console.log(`Button clicked: ${field.id}`);-- if (field.id === "mcp_servers_config") {- openModal("settings/mcp/client/mcp-servers.html");- } else if (field.id === "backup_create") {- openModal("settings/backup/backup.html");- } else if (field.id === "backup_restore") {- openModal("settings/backup/restore.html");- } else if (field.id === "show_a2a_connection") {- openModal("settings/external/a2a-connection.html");- } else if (field.id === "external_api_examples") {- openModal("settings/external/api-examples.html");- } else if (field.id === "memory_dashboard") {- openModal("settings/memory/memory-dashboard.html");- }- }-};---// function initSettingsModal() {--// window.openSettings = function () {-// proxy.openModal().then(result => {-// console.log(result); // This will log the result when the modal is closed-// });-// }--// return proxy-// }---// document.addEventListener('alpine:init', () => {-// Alpine.store('settingsModal', initSettingsModal());-// });--document.addEventListener('alpine:init', function () {- // Initialize the root store first to ensure it exists before components try to access it- Alpine.store('root', {- activeTab: localStorage.getItem('settingsActiveTab') || 'agent',- isOpen: false,-- toggleSettings() {- this.isOpen = !this.isOpen;- }- });-- // Then initialize other Alpine components- Alpine.data('settingsModal', function () {- return {- settingsData: {},- filteredSections: [],- activeTab: 'agent',- isLoading: true,-- async init() {- // Initialize with the store value- this.activeTab = Alpine.store('root').activeTab || 'agent';-- // Watch store tab changes- this.$watch('$store.root.activeTab', (newTab) => {- if (typeof newTab !== 'undefined') {- this.activeTab = newTab;- localStorage.setItem('settingsActiveTab', newTab);- this.updateFilteredSections();- }- });-- // Load settings- await this.fetchSettings();- this.updateFilteredSections();- },-- switchTab(tab) {- // Update our component state- this.activeTab = tab;-- // Update the store safely- const store = Alpine.store('root');- if (store) {- store.activeTab = tab;- }- },-- async fetchSettings() {- try {- this.isLoading = true;- const response = await fetchApi('/api/settings_get', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- }- });-- if (response.ok) {- const data = await response.json();- if (data && data.settings) {- this.settingsData = data.settings;- } else {- console.error('Invalid settings data format');- }- } else {- console.error('Failed to fetch settings:', response.statusText);- }- } catch (error) {- console.error('Error fetching settings:', error);- } finally {- this.isLoading = false;- }- },-- updateFilteredSections() {- // Filter sections based on active tab- if (this.activeTab === 'agent') {- this.filteredSections = this.settingsData.sections?.filter(section =>- section.tab === 'agent'- ) || [];- } else if (this.activeTab === 'external') {- this.filteredSections = this.settingsData.sections?.filter(section =>- section.tab === 'external'- ) || [];- } else if (this.activeTab === 'developer') {- this.filteredSections = this.settingsData.sections?.filter(section =>- section.tab === 'developer'- ) || [];- } else if (this.activeTab === 'mcp') {- this.filteredSections = this.settingsData.sections?.filter(section =>- section.tab === 'mcp'- ) || [];- } else if (this.activeTab === 'backup') {- this.filteredSections = this.settingsData.sections?.filter(section =>- section.tab === 'backup'- ) || [];- } else {- // For any other tab, show nothing since those tabs have custom UI- this.filteredSections = [];- }- },-- async saveSettings() {- try {- // First validate- for (const section of this.settingsData.sections) {- for (const field of section.fields) {- if (field.required && (!field.value || field.value.trim() === '')) {- showToast(`${field.title} in ${section.title} is required`, 'error');- return;- }- }- }-- // Prepare data- const formData = {};- for (const section of this.settingsData.sections) {- for (const field of section.fields) {- formData[field.id] = field.value;- }- }-- // Send request- const response = await fetchApi('/api/settings_save', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify(formData)- });-- if (response.ok) {- showToast('Settings saved successfully', 'success');- // Refresh settings- await this.fetchSettings();- } else {- const errorData = await response.json();- throw new Error(errorData.error || 'Failed to save settings');- }- } catch (error) {- console.error('Error saving settings:', error);- showToast('Failed to save settings: ' + error.message, 'error');- }- },-- // Handle special button field actions- handleFieldButton(field) {- if (field.action === 'test_connection') {- this.testConnection(field);- } else if (field.action === 'reveal_token') {- this.revealToken(field);- } else if (field.action === 'generate_token') {- this.generateToken(field);- } else {- console.warn('Unknown button action:', field.action);- }- },-- // Test API connection- async testConnection(field) {- try {- field.testResult = 'Testing...';- field.testStatus = 'loading';-- // Find the API key field- let apiKey = '';- for (const section of this.settingsData.sections) {- for (const f of section.fields) {- if (f.id === field.target) {- apiKey = f.value;- break;- }- }- }-- if (!apiKey) {- throw new Error('API key is required');- }-- // Send test request- const response = await fetchApi('/api/test_connection', {- method: 'POST',- headers: {- 'Content-Type': 'application/json'- },- body: JSON.stringify({- service: field.service,- api_key: apiKey- })- });-- const data = await response.json();-- if (response.ok && data.success) {- field.testResult = 'Connection successful!';- field.testStatus = 'success';- } else {- throw new Error(data.error || 'Connection failed');- }- } catch (error) {- console.error('Connection test failed:', error);- field.testResult = `Failed: ${error.message}`;- field.testStatus = 'error';- }- },-- // Reveal token temporarily- revealToken(field) {- // Find target field- for (const section of this.settingsData.sections) {- for (const f of section.fields) {- if (f.id === field.target) {- // Toggle field type- f.type = f.type === 'password' ? 'text' : 'password';-- // Update button text- field.value = f.type === 'password' ? 'Show' : 'Hide';-- break;- }- }- }- },-- // Generate random token- generateToken(field) {- // Find target field- for (const section of this.settingsData.sections) {- for (const f of section.fields) {- if (f.id === field.target) {- // Generate random token- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';- let token = '';- for (let i = 0; i < 32; i++) {- token += chars.charAt(Math.floor(Math.random() * chars.length));- }-- // Set field value- f.value = token;- break;- }- }- }- },-- closeModal() {- // Stop scheduler polling before closing the modal- const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');- if (schedulerElement) {- const schedulerData = Alpine.$data(schedulerElement);- if (schedulerData && typeof schedulerData.stopPolling === 'function') {- console.log('Stopping scheduler polling on modal close');- schedulerData.stopPolling();- }- }-- this.$store.root.isOpen = false;- }- };- });-});--// Show toast notification - now uses new notification system-function showToast(message, type = 'info') {- // Use new frontend notification system based on type- if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {- const store = window.Alpine.store('notificationStore');- switch (type.toLowerCase()) {- case 'error':- return store.frontendError(message, "Settings", 5);- case 'success':- return store.frontendInfo(message, "Settings", 3);- case 'warning':- return store.frontendWarning(message, "Settings", 4);- case 'info':- default:- return store.frontendInfo(message, "Settings", 3);- }- } else {- // Fallback if Alpine/store not ready- console.log(`SETTINGS ${type.toUpperCase()}: ${message}`);- return null;- }-}