// ===== State =====
let state = {
connections: [], currentConn: null,
status: {}, kernel: null,
settings: {}, meta: {}, pluginMeta: {}, settingsPlugins: ['core'],
selectedSection: 'core',
messages: [], chatLoading: false, chatStage: '',
installedPlugins: [], pluginInfo: null,
startedAt: null, uptimeTick: null, sidebarRefreshTick: null, eventSource: null,
_chatHistoryLoaded: false, _starmapData: null,
};
// ===== Markdown Renderer (lightweight, no dependencies) =====
function renderMarkdown(t) {
if (!t) return '';
let s = String(t)
.replace(/&/g,'&').replace(//g,'>');
// code blocks (fenced)
s = s.replace(/```(\w*)\n([\s\S]*?)```/g, '
$2 ');
// inline code
s = s.replace(/`([^`]+)`/g, '$1');
// headers
s = s.replace(/^### (.+)$/gm, '$1 ');
s = s.replace(/^## (.+)$/gm, '$1 ');
s = s.replace(/^# (.+)$/gm, '$1 ');
// bold & italic
s = s.replace(/\*\*\*(.+?)\*\*\*/g, '$1 ');
s = s.replace(/\*\*(.+?)\*\*/g, '$1 ');
s = s.replace(/\*(.+?)\*/g, '$1 ');
// links
s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ');
// images
s = s.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, ' ');
// blockquote
s = s.replace(/^> (.+)$/gm, '$1 ');
// horizontal rule
s = s.replace(/^---$/gm, ' ');
// unordered list
s = s.replace(/^[\s]*[-*] (.+)$/gm, '$1 ');
s = s.replace(/(.*<\/li>\n?)+/g, '');
// ordered list
s = s.replace(/^[\s]*\d+\. (.+)$/gm, ' $1 ');
// paragraphs: double newlines
s = s.replace(/\n\n/g, '');
s = '
' + s + '
';
// clean nested ps from lists
s = s.replace(/<\/p>\n?/g, '').replace(/<\/ul>\n?/g, '
');
s = s.replace(/<\/p>\n?/g, ' ').replace(/<\/li>\n?/g, '
');
s = s.replace(/<\/p>/g, '');
return s;
}
// ===== Connection Management =====
async function initApp() {
const data = await window.homeagent.connections.list();
state.connections = data.connections || [];
if (data.currentId) state.currentConn = state.connections.find(c => c.id === data.currentId) || null;
if (state.currentConn) {
document.getElementById('app').style.display = 'block';
document.getElementById('conn-overlay').style.display = 'none';
updateConnIndicator();
await renderAll();
startUptimeTicker(); startSidebarRefresh(); connectSSE();
} else {
document.getElementById('conn-overlay').style.display = 'flex';
}
renderConnList();
}
function updateConnIndicator() {
const el = document.getElementById('conn-name-display');
const dot = document.getElementById('conn-dot');
if (state.currentConn) {
el.textContent = state.currentConn.name;
dot.className = 'status-dot ' + (state.status.status === 'running' ? 'dot-green' : 'dot-yellow');
} else { el.textContent = '未连接'; dot.className = 'status-dot dot-gray'; }
}
function openConnManager() { renderConnList(); document.getElementById('conn-overlay').style.display = 'flex'; }
async function selectConnection(id) {
disconnectSSE();
const data = await window.homeagent.connections.setCurrent(id);
state.currentConn = data.connections.find(c => c.id === id) || null;
state.connections = data.connections;
state.messages = []; state._chatHistoryLoaded = false;
document.getElementById('app').style.display = 'block';
document.getElementById('conn-overlay').style.display = 'none';
updateConnIndicator();
await renderAll();
startUptimeTicker(); startSidebarRefresh(); connectSSE();
}
async function deleteConnection(id, e) {
e.stopPropagation();
if (!confirm('确定删除此连接?')) return;
const wasCurrent = state.currentConn && state.currentConn.id === id;
const data = await window.homeagent.connections.delete(id);
state.connections = data.connections;
state.currentConn = data.currentId ? state.connections.find(c => c.id === data.currentId) : null;
if (wasCurrent) { disconnectSSE(); if (state.sidebarRefreshTick) { clearInterval(state.sidebarRefreshTick); state.sidebarRefreshTick = null; } }
if (state.currentConn) {
updateConnIndicator(); await renderAll(); startSidebarRefresh(); connectSSE();
} else {
document.getElementById('app').style.display = 'none'; document.getElementById('conn-overlay').style.display = 'flex';
}
renderConnList();
}
function renderConnList() {
document.getElementById('conn-list').innerHTML = state.connections.map(c =>
'
'
+ '
'
+ '
' + escHtml(c.name) + '
' + escHtml(c.url) + '
'
+ '
'
+ '编辑 '
+ '删除
'
).join('');
}
let editingConnId = null;
function showConnForm() {
editingConnId = null;
document.getElementById('conn-form-title').textContent = '添加连接 / Add Connection';
document.getElementById('conn-name').value = 'My HomeAgent';
document.getElementById('conn-url').value = 'http://localhost:8080';
document.getElementById('conn-key').value = '';
document.getElementById('conn-form').style.display = 'block';
document.getElementById('conn-add-btn').style.display = 'none';
}
function editConnection(id, e) {
e.stopPropagation();
const c = state.connections.find(x => x.id === id);
if (!c) return;
editingConnId = id;
document.getElementById('conn-form-title').textContent = '编辑连接 / Edit Connection';
document.getElementById('conn-name').value = c.name;
document.getElementById('conn-url').value = c.url;
document.getElementById('conn-key').value = c.apiKey;
document.getElementById('conn-form').style.display = 'block';
document.getElementById('conn-add-btn').style.display = 'none';
document.querySelectorAll('.conn-item').forEach(el => el.style.opacity = '0.4');
}
function cancelConnForm() {
document.getElementById('conn-form').style.display = 'none';
document.getElementById('conn-add-btn').style.display = 'block';
document.querySelectorAll('.conn-item').forEach(el => el.style.opacity = '1');
}
async function saveConnForm() {
const name = document.getElementById('conn-name').value.trim();
const url = document.getElementById('conn-url').value.trim().replace(/\/+$/, '');
const apiKey = document.getElementById('conn-key').value.trim();
if (!name || !url) { toast('名称和地址不能为空', true); return; }
// test connection before saving
const testBtn = document.querySelector('#conn-form .btn-primary');
testBtn.textContent = '测试中...'; testBtn.disabled = true;
try {
const testR = await fetch(url + '/api/v1/status', {
headers: apiKey ? { 'X-API-Key': apiKey } : {}
});
if (!testR.ok) { toast('连接测试失败: HTTP ' + testR.status, true); testBtn.textContent = '保存 / Save'; testBtn.disabled = false; return; }
} catch(e) {
toast('无法连接到 ' + url + ': ' + e.message, true);
testBtn.textContent = '保存 / Save'; testBtn.disabled = false; return;
}
testBtn.textContent = '保存 / Save'; testBtn.disabled = false;
let data;
if (editingConnId) {
data = await window.homeagent.connections.update(editingConnId, { name, url, apiKey });
} else {
data = await window.homeagent.connections.add({ name, url, apiKey });
}
state.connections = data.connections;
const curId = data.currentId;
const cur = data.connections.find(c => c.id === curId);
if (cur) {
state.currentConn = cur;
if (!document.getElementById('app').style.display || document.getElementById('app').style.display === 'none') {
document.getElementById('app').style.display = 'block';
document.getElementById('conn-overlay').style.display = 'none';
updateConnIndicator(); await renderAll(); startUptimeTicker(); startSidebarRefresh(); connectSSE();
} else { updateConnIndicator(); if (editingConnId) await renderAll(); }
}
cancelConnForm(); renderConnList();
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && document.getElementById('conn-form').style.display === 'block') cancelConnForm();
});
// ===== API Client =====
async function api(path, opts = {}) {
if (!state.currentConn) throw new Error('No connection selected');
const headers = { 'Content-Type': 'application/json', ...opts.headers };
if (state.currentConn.apiKey) headers['X-API-Key'] = state.currentConn.apiKey;
const url = state.currentConn.url + '/api/v1' + path;
const res = await fetch(url, { ...opts, headers });
if (res.status === 401) throw new Error('unauthorized');
if (opts.raw) return res;
const ct = res.headers.get('content-type') || '';
if (ct.includes('json')) return res.json();
return res.text();
}
// ===== Toast =====
function toast(msg, isError) {
const t = document.getElementById('toast');
t.textContent = msg; t.className = 'toast' + (isError ? ' error' : ''); t.style.display = 'block';
setTimeout(function() { t.style.display = 'none' }, 3000);
}
// ===== Utility =====
function escHtml(s) { return String(s).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); }
function fmtUptime(ms) {
const s = Math.floor(ms / 1000);
if (s < 60) return s + 's'; const m = Math.floor(s / 60); s = s % 60;
if (m < 60) return m + 'm ' + s + 's'; const h = Math.floor(m / 60); m = m % 60;
return h + 'h ' + m + 'm ' + s + 's';
}
// ===== Theme =====
function setTheme(name) {
document.documentElement.setAttribute('data-theme', name);
localStorage.setItem('ha-theme', name);
document.getElementById('theme-btn').textContent = name === 'light' ? '☀️' : '🌙';
}
function toggleTheme() { setTheme(document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light'); }
(function() { setTheme(localStorage.getItem('ha-theme') || 'dark') })();
// ===== Navigation =====
function switchTab(n) {
document.querySelectorAll('.tab-content').forEach(function(e) { e.classList.remove('active') });
const el = document.getElementById('tab-' + n); if (el) el.classList.add('active');
document.querySelectorAll('nav a').forEach(function(e) { e.classList.remove('active') });
const m = document.querySelector('nav a[onclick*="' + n + '"]'); if (m) m.classList.add('active');
renderAll();
}
// ===== Tab Render Dispatch =====
async function renderAll() {
if (!state.currentConn) return;
try { const s = await api('/status'); state.status = s; state.startedAt = s.startedAt ? new Date(s.startedAt).getTime() : null; updateConnIndicator() } catch(e) {}
try { state.kernel = await api('/kernel') } catch(e) {}
try {
const s = await api('/settings'); state.settings = s.settings || {}; state.meta = s.meta || {};
state.settingsPlugins = s.plugins || ['core']; state.pluginMeta = s.plugin_meta || {};
} catch(e) {}
try { state.installedPlugins = await api('/plugins') } catch(e) {}
try { renderOverview() } catch(e) {} try { renderChat() } catch(e) {} try { renderPlugins() } catch(e) {}
try { renderKernel() } catch(e) {} try { renderOneSettings() } catch(e) {} try { renderAdapters() } catch(e) {}
}
function startUptimeTicker() {
if (state.uptimeTick) clearInterval(state.uptimeTick);
state.uptimeTick = setInterval(function() {
const el = document.querySelector('#uptime-val');
if (el && state.startedAt) el.textContent = fmtUptime(Date.now() - state.startedAt);
}, 1000);
}
// ===== SSE =====
function disconnectSSE() { if (state.eventSource) { state.eventSource.close(); state.eventSource = null; } }
function connectSSE() {
disconnectSSE(); if (!state.currentConn) return;
connectFetchSSE(state.currentConn.url + '/api/v1/chat/events');
}
async function connectFetchSSE(url) {
try {
const headers = {};
if (state.currentConn && state.currentConn.apiKey) headers['X-API-Key'] = state.currentConn.apiKey;
const resp = await fetch(url, { headers, cache: 'no-store' });
if (!resp.ok || !resp.body) { setTimeout(function() { connectSSE() }, 5000); return; }
const reader = resp.body.getReader(); const decoder = new TextDecoder();
let buffer = ''; let reconnectTimer = null;
state.eventSource = { close: function() { reader.cancel(); if (reconnectTimer) clearTimeout(reconnectTimer) } };
function processLines() {
const lines = buffer.split('\n'); buffer = lines.pop() || '';
let eventType = '', data = '';
for (const line of lines) {
if (line.startsWith('event: ')) eventType = line.slice(7).trim();
else if (line.startsWith('data: ')) data = line.slice(6).trim();
else if (line === '' && eventType && data) { handleSSEEvent(eventType, data); eventType = ''; data = ''; }
}
}
function handleSSEEvent(type, raw) {
try {
const p = JSON.parse(raw);
if (type === 'agent_output') {
const last = state.messages[state.messages.length - 1];
if (last && last.role === 'assistant' && last._streaming) {
last.content = (last.content || '') + (p.content || '');
rerenderChatIfActive();
}
} else if (type === 'stage') {
const phase = p.payload?.phase;
if (phase === 'thinking') state.chatStage = 'Thinking...';
else if (phase === 'before_toolcall') state.chatStage = 'Tool: ' + (p.payload?.tool || '');
else if (phase === 'before_output') state.chatStage = 'Output...';
updateChatStageBadge();
} else if (type === 'reasoning') {
const last = state.messages[state.messages.length - 1];
if (last && last.role === 'assistant' && last._streaming) {
last.reasoning_content = (last.reasoning_content || '') + (p.payload?.content || '');
}
}
} catch(err) {}
}
async function pump() {
while (true) {
try { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); processLines(); } catch(e) { break; }
}
reconnectTimer = setTimeout(function() { connectSSE() }, 3000);
}
pump();
} catch(e) { setTimeout(function() { connectSSE() }, 5000); }
}
function startSidebarRefresh() {
if (state.sidebarRefreshTick) clearInterval(state.sidebarRefreshTick);
state.sidebarRefreshTick = setInterval(async function() {
try { await loadSidebarData() } catch(e) {}
}, 5000);
}
// ===== Overview =====
function statCard(l, v) { return ''; }
function renderOverview() {
const s = state.status || {}; const k = state.kernel;
let html = '' + statCard('Status', s.status || 'unknown')
+ statCard('Uptime', '' + (state.startedAt ? fmtUptime(Date.now() - state.startedAt) : '-') + ' ')
+ statCard('Plugins', (k?.plugins || []).length || 0)
+ statCard('Version', s.version || '-') + '
';
if (k) {
html += ''
+ '
LLM Status '
+ '
Provider ' + (k.llm?.provider || 'Not configured') + '
'
+ '
Sources ' + (k.llm?.sources || 0) + '
'
+ '
Status ' + (k.llm?.available ? 'Running' : 'Unavailable') + '
'
+ '
Memory Status '
+ '
Graph Memory ' + (k.memory?.available ? k.memory.entity_count + ' entities, ' + k.memory.relation_count + ' relations' : 'Uninitialized') + '
'
+ '
Document Memory ' + (k.documents?.available ? k.documents.doc_count + ' docs' : 'Uninitialized') + '
'
+ '
Text Memory ' + (k.text_memory?.available ? k.text_memory.file_count + ' files' : 'Uninitialized') + '
'
+ '
Knowledge ' + (k.knowledge?.available ? k.knowledge.item_count + ' items' : 'Uninitialized') + '
';
}
html += 'Runtime ' + statCard('Goroutines', k?.runtime?.goroutines || '-') + statCard('Memory', k?.runtime?.memory_mb ? k.runtime.memory_mb + ' MB' : '-') + statCard('Go Version', k?.runtime?.go_version || '-') + '
'
+ 'Memory Graph '
+ 'Loading memory graph...
';
document.getElementById('tab-overview').innerHTML = html;
loadStarmapData();
}
async function loadStarmapData() {
try {
const resp = await api('/memory/graph');
if (resp && resp.success && resp.data && resp.data.nodes && resp.data.nodes.length > 0) {
state._starmapData = resp.data;
document.getElementById('starmap-placeholder').textContent = resp.data.nodes.length + ' nodes, ' + (resp.data.edges?.length || 0) + ' edges';
} else {
document.getElementById('starmap-placeholder').textContent = 'No memory data yet';
}
} catch(e) {
document.getElementById('starmap-placeholder').textContent = 'Failed to load: ' + e.message;
}
}
// ===== Chat =====
let _chatLayoutBuilt = false;
let _terminals = [], _cmdHistory = [];
function buildChatLayout() {
const k = state.kernel || {};
document.getElementById('tab-chat').innerHTML =
'';
_chatLayoutBuilt = true;
}
function renderChat() {
if (!_chatLayoutBuilt) { buildChatLayout(); renderTerminalsList(); renderCmdHistoryList(); }
const msgsEl = document.getElementById('chat-msgs');
if (!msgsEl) return;
if (state.messages.length === 0) {
msgsEl.innerHTML = ''; return;
}
let html = '';
state.messages.forEach(function(m) {
const role = m.role || 'user'; let c = m.content || '';
if (role === 'assistant') { c = renderMarkdown(c) } else { c = ' ' + escHtml(c) + ' ' }
const rc = m.reasoning_content ? 'Collapse
' + renderMarkdown(m.reasoning_content) + '
' : '';
html += '' + (role === 'user' ? 'U' : 'A') + '
'
+ '
';
});
msgsEl.innerHTML = html; msgsEl.scrollTop = msgsEl.scrollHeight;
updateChatStageBadge();
}
function switchChatSub(name, el) {
document.querySelectorAll('.sidebar-subnav span').forEach(function(e) { e.classList.remove('active') });
if (el) el.classList.add('active');
['memory','context','knowledge'].forEach(function(s) { document.getElementById('chat-sub-' + s).style.display = s === name ? 'block' : 'none' });
}
async function sendChat() {
const inp = document.getElementById('chat-input'); const btn = document.getElementById('chat-send-btn');
const text = inp.value.trim(); if (!text || state.chatLoading) return;
state.messages.push({ role: 'user', content: text }); inp.value = '';
const streamingMsg = { role: 'assistant', content: '', reasoning_content: '', _streaming: true };
state.messages.push(streamingMsg); renderChat();
state.chatLoading = true; btn.disabled = true; btn.textContent = '...';
try {
const r = await api('/chat', { method: 'POST', body: JSON.stringify({ message: text }) });
if (streamingMsg._streaming) {
streamingMsg.content = r.response || '(no response)'; streamingMsg.reasoning_content = r.reasoning_content || '';
} else {
streamingMsg.content = (streamingMsg.content || '') + (r.response || ''); streamingMsg.reasoning_content = (streamingMsg.reasoning_content || '') + (r.reasoning_content || '');
}
delete streamingMsg._streaming; saveChatHistory(); renderChat();
} catch(e) {
if (streamingMsg._streaming) { streamingMsg.content = 'Error: ' + e.message; delete streamingMsg._streaming; }
renderChat(); toast('Request failed: ' + e.message, true);
} finally {
state.chatLoading = false; btn.disabled = false; btn.textContent = 'Send'; renderChat();
}
}
function updateChatStageBadge() {
const badge = document.getElementById('chat-stage');
if (!badge) return; badge.textContent = state.chatStage || ''; badge.style.display = state.chatStage ? 'inline' : 'none';
}
function rerenderChatIfActive() {
const tab = document.getElementById('tab-chat');
if (tab && tab.classList.contains('active')) renderChat();
}
async function loadSidebarData() {
try { const d = await api('/terminals'); _terminals = d?.terminals || []; renderTerminalsList() } catch(e) {}
try { const d = await api('/cmd/history'); _cmdHistory = d?.history || []; renderCmdHistoryList() } catch(e) {}
}
function renderTerminalsList() {
const el = document.getElementById('term-list'); const badge = document.getElementById('term-count-badge');
if (!el) return; if (badge) badge.textContent = _terminals.length;
if (_terminals.length === 0) { el.innerHTML = 'No active terminals
'; return; }
el.innerHTML = _terminals.map(function(t) {
const status = t.running ? ' ' : ' ';
return '' + status + ' ' + escHtml((t.command || t.id || '').substring(0, 40)) + ' ' + (t.uptime || '') + '
';
}).join('');
}
function renderCmdHistoryList() {
const el = document.getElementById('cmd-list'); const badge = document.getElementById('cmd-count-badge');
if (!el) return; if (badge) badge.textContent = _cmdHistory.length;
if (_cmdHistory.length === 0) { el.innerHTML = 'No command history
'; return; }
el.innerHTML = _cmdHistory.slice(-10).reverse().map(function(c) {
const status = c.status === 'completed' ? 'OK ' : '' + escHtml(c.status || 'FAIL') + ' ';
return '' + escHtml((c.command || '').substring(0, 40)) + ' ' + status + '
';
}).join('');
}
// ===== Chat History Persistence =====
async function saveChatHistory() {
try {
const msgs = state.messages.filter(function(m) { return !m._streaming }).map(function(m) {
return { role: m.role, content: m.content, reasoning_content: m.reasoning_content, time: new Date().toISOString() };
}).slice(-100);
await api('/settings', { method: 'PUT', body: JSON.stringify({ key: 'plugin.webui.chathistory', value: JSON.stringify(msgs) }) });
} catch(e) {}
}
async function loadChatHistory() {
if (state._chatHistoryLoaded || !state.currentConn) return;
try {
const s = await api('/settings?prefix=plugin.webui');
const raw = s?.settings?.['plugin.webui.chathistory'];
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed) && parsed.length > 0) {
state.messages = parsed.map(function(m) { return { role: m.role, content: m.content || '', reasoning_content: m.reasoning_content || '' } });
state._chatHistoryLoaded = true;
renderChat();
}
}
} catch(e) {}
state._chatHistoryLoaded = true;
}
// hook into renderChat init
const _origRenderChat = renderChat;
renderChat = function() {
loadChatHistory();
return _origRenderChat.apply(this, arguments);
};
async function queryMemoryChat() {
const q = document.getElementById('mem-query')?.value; const r = document.getElementById('mem-result-chat');
if (!r || !q) return; r.innerHTML = '
';
try { const d = await api('/memory?q=' + encodeURIComponent(q) + '&depth=2'); r.innerHTML = '' + escHtml(JSON.stringify(d, null, 2)) + ' '; }
catch(e) { r.innerHTML = 'Query failed: ' + escHtml(e.message) + '
'; }
}
async function queryMemoryContext() {
const q = document.getElementById('ctx-query')?.value; const r = document.getElementById('ctx-result');
if (!r) return; r.innerHTML = '
';
try {
const d = await api('/memory/context?q=' + encodeURIComponent(q || ''));
let html = '';
if (d?.summary) html += '
Summary ' + escHtml(d.summary) + '
';
html += '
Token Estimate ' + (d?.token_estimate || 0) + '
';
if (d?.entities?.length) html += '
Entities ' + d.entities.map(function(e) { return escHtml(e.name || e.id || '') }).join(', ') + '
';
html += '
Context ' + escHtml(d?.context || 'No context') + ' ';
r.innerHTML = html;
} catch(e) { r.innerHTML = 'Query failed: ' + escHtml(e.message) + '
'; }
}
async function searchKnowledgeChat() {
const q = document.getElementById('know-query')?.value; const r = document.getElementById('know-result-chat');
if (!r || !q) return; r.innerHTML = '
';
try { const d = await api('/knowledge?q=' + encodeURIComponent(q)); r.innerHTML = '' + escHtml(JSON.stringify(d, null, 2)) + ' '; }
catch(e) { r.innerHTML = 'Search failed: ' + escHtml(e.message) + '
'; }
}
async function createKnowledgeChat() {
const name = document.getElementById('know-name')?.value; const content = document.getElementById('know-content')?.value;
if (!name || !content) { toast('Name and content required', true); return; }
try { await api('/knowledge', { method: 'POST', body: JSON.stringify({ name, content }) }); toast('Knowledge created'); document.getElementById('know-name').value = ''; document.getElementById('know-content').value = ''; }
catch(e) { toast('Create failed: ' + e.message, true); }
}
// ===== Plugins =====
async function renderPlugins() {
const list = state.installedPlugins?.plugins || []; const info = state.pluginInfo;
let html = '';
if (list.length === 0) { html += '
No plugins installed
'; }
else {
html += '
Name Type Status ';
list.forEach(function(p) {
const status = p.loaded ? 'Loaded ' : 'Error ';
html += '' + escHtml(p.name || '') + ' ' + escHtml(p.type || '') + ' ' + status + ' '
+ 'Info ';
}); html += '
';
}
html += '
';
if (info) {
html += '' + escHtml(info.name || '') + ' Details ' + escHtml(JSON.stringify(info, null, 2)) + ' '
+ '
Close ';
}
document.getElementById('tab-plugins').innerHTML = html;
}
async function showPluginInfo(name) {
try { const d = await api('/plugins/' + encodeURIComponent(name)); state.pluginInfo = d; renderPlugins(); }
catch(e) { toast('Failed: ' + e.message, true); }
}
async function installPluginFile(file) {
if (!file) return;
try {
const form = new FormData(); form.append('plugin', file);
await fetch(state.currentConn.url + '/api/v1/plugins', { method: 'POST', body: form, headers: state.currentConn.apiKey ? { 'X-API-Key': state.currentConn.apiKey } : {} });
toast('Plugin uploaded'); state.installedPlugins = await api('/plugins'); renderPlugins();
} catch(e) { toast('Upload failed: ' + e.message, true); }
}
async function reloadPlugins() {
try { await api('/plugins/reload', { method: 'POST' }); state.kernel = await api('/kernel'); state.installedPlugins = await api('/plugins'); toast('Plugins reloaded'); renderPlugins(); renderOverview(); }
catch(e) { toast('Reload failed: ' + e.message, true); }
}
// ===== Knowledge Browser =====
async function renderKnowledgeBrowser() {
if (document.getElementById('tab-knowledge')) return;
const tab = document.getElementById('tab-kernel');
if (!tab || !tab.classList.contains('active')) return;
const cont = document.getElementById('knowledge-browser');
if (!cont) return;
try {
const d = await api('/knowledge');
let html = 'Knowledge Base ';
if (d?.categories) {
html += '
Name Size ';
(d.categories || []).forEach(function(c) {
html += '' + escHtml(c.name || c) + ' ' + (c.content_length || '-') + ' ';
});
html += '
';
}
if (d?.stats) {
html += '
' + statCard('Categories', d.stats.categories || 0) + statCard('Items', d.stats.items || 0) + statCard('Size', d.stats.size || 0) + '
';
}
html += '
';
cont.innerHTML = html;
} catch(e) { cont.innerHTML = '' + escHtml(e.message) + '
'; }
}
// ===== Settings =====
function renderOneSettings() {
const section = state.selectedSection || 'core';
const isPlugin = section.startsWith('plugin.'); const prefix = isPlugin ? section : (section === 'core' ? '' : section);
const values = {}; const meta = {};
if (isPlugin) { const pname = section.substring(7); Object.entries(state.settings).filter(function(e) { return e[0].startsWith('plugin.' + pname + '.') }).forEach(function(e) { values[e[0]] = e[1] }) }
else if (section === 'core') { Object.entries(state.settings).filter(function(e) { return !e[0].startsWith('plugin.') }).forEach(function(e) { values[e[0]] = e[1] }) }
else { Object.entries(state.settings).filter(function(e) { return e[0].startsWith(section + '.') || (!e[0].startsWith('plugin.') && e[0].startsWith(section)) }).forEach(function(e) { values[e[0]] = e[1] }) }
Object.assign(meta, state.meta);
let html = '' + (isPlugin ? 'Plugin: ' + section.substring(7) : 'Core Settings') + ' ';
const keys = Object.keys(values);
if (keys.length === 0) { html += '
No settings
' }
else {
keys.sort().forEach(function(k) {
const v = values[k]; const m = meta[k]; const display = m?.displayName || k.split('.').pop() || k; const desc = m?.description || '';
html += '
' + escHtml(k) + '
' + escHtml(display) + ' '
+ '
'
+ (desc ? '
' + escHtml(desc) + '
' : '') + '
';
});
}
html += '
';
document.getElementById('tab-settings').innerHTML = '';
}
async function saveSetting(key, value) {
try { await api('/settings', { method: 'PUT', body: JSON.stringify({ key, value }) }); toast('Saved'); const s = await api('/settings'); state.settings = s.settings || {}; state.meta = s.meta || {}; renderOneSettings(); }
catch(e) { toast('Save failed: ' + e.message, true); }
}
// ===== Adapters =====
async function renderAdapters() {
let html = '
LLM Adapters Upload ';
try {
const d = await api('/adapters'); const adapters = d?.adapters || [];
if (adapters.length === 0) { html += '
No adapters
' }
else {
html += '
Name Type ';
adapters.forEach(function(a) { html += '' + escHtml(a.name || a) + ' ' + escHtml(a.type || 'lua') + ' Delete ' });
html += '
';
}
} catch(e) { html += '
Failed to load: ' + escHtml(e.message) + '
' }
html += '
';
document.getElementById('tab-adapters').innerHTML = html;
}
function showUploadAdapter() { const name = prompt('Adapter name:'); if (!name) return; const code = prompt('Paste Lua adapter code:'); if (!code) return; uploadAdapter(name, code); }
async function uploadAdapter(name, code) { try { await api('/adapters', { method: 'POST', body: JSON.stringify({ name, code }) }); toast('Uploaded'); renderAdapters(); } catch(e) { toast('Failed: ' + e.message, true); } }
async function deleteAdapter(name) { if (!confirm('Delete: ' + name + '?')) return; try { await api('/adapters/' + encodeURIComponent(name), { method: 'DELETE' }); toast('Deleted'); renderAdapters(); } catch(e) { toast('Failed: ' + e.message, true); } }
// ===== Kernel =====
async function renderKernel() {
const k = state.kernel;
let html = 'Kernel Status ';
if (!k) { html += '
Unavailable
' }
else {
html += '
LLM Provider ' + escHtml(k.llm?.provider || '-') + '
Sources ' + (k.llm?.sources || 0) + '
Available ' + (k.llm?.available ? 'Yes' : 'No') + '
'
+ '
Memory Available ' + (k.memory?.available ? 'Yes' : 'No') + '
'
+ (k.memory?.available ? '
Entities ' + k.memory.entity_count + '
Relations ' + k.memory.relation_count + '
' : '') + '
';
html += '
Runtime Goroutines ' + (k.runtime?.goroutines || '-') + '
Memory ' + (k.runtime?.memory_mb || '-') + ' MB
Go Version ' + escHtml(k.runtime?.go_version || '-') + '
';
html += '
Plugins ';
if (k.plugins && k.plugins.length > 0) { html += '
' + k.plugins.map(function(p) { return '' + escHtml(p.name || p) + ' ' }).join('') + '
' }
}
html += '
Actions Run Healthcheck '
+ 'View Text Memory '
+ '
'
+ '
';
document.getElementById('tab-kernel').innerHTML = html;
renderKnowledgeBrowser();
}
async function runHealthcheck() {
const el = document.getElementById('health-result'); el.innerHTML = '
';
try { const r = await api('/chat', { method: 'POST', body: JSON.stringify({ message: 'Please run the healthcheck tool for a full system check and report the results' }) }); el.innerHTML = 'Healthcheck Result ' + escHtml(r.response || '') + ' '; }
catch(e) { el.innerHTML = '' + escHtml(e.message) + '
'; }
}
async function loadTextMemory() {
const el = document.getElementById('text-memory-result'); el.innerHTML = '
';
try { const d = await api('/memory/text'); el.innerHTML = 'Text Memory ' + escHtml(JSON.stringify(d, null, 2)) + ' '; }
catch(e) { el.innerHTML = '' + escHtml(e.message) + '
'; }
}
// ===== Init =====
document.addEventListener('DOMContentLoaded', initApp);