templates/index.html aktualisiert

This commit is contained in:
2026-03-05 19:16:48 +00:00
parent 1613f8f775
commit f852e15d6c

View File

@@ -110,7 +110,7 @@
} }
/* Der Container für die URL */ /* Der Container für die URL */
.ollama-url-container { #ollama-url-container {
display: none; /* Standardmäßig versteckt */ display: none; /* Standardmäßig versteckt */
align-items: center; align-items: center;
gap: 10px; gap: 10px;
@@ -235,190 +235,17 @@
</div> </div>
<script> <script>
let termDataDisposable = null; // 1. GLOBALE VARIABLEN (Ganz oben, für alle sichtbar)
// Diese Liste definiert, welche Modelle in der Auswahl erscheinen
const modelOptions = { const modelOptions = {
google: [ google: ["gemini-2.0-flash", "gemini-1.5-flash", "gemini-1.5-pro"],
"gemini-2.0-flash", openai: ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo"],
"gemini-1.5-flash", ollama: ["llama3.2", "llama3.1", "mistral", "phi3"]
"gemini-1.5-pro"
],
openai: [
"gpt-4o",
"gpt-4o-mini",
"gpt-4-turbo"
],
ollama: [
"llama3.2",
"llama3.1",
"mistral",
"phi3",
"qwen2.5"
]
}; };
let currentSettings = {}; let currentSettings = {};
let termDataDisposable = null;
document.addEventListener('DOMContentLoaded', function() { // 2. GLOBALE FUNKTIONEN (Damit das HTML onchange/onclick sie findet)
// 1. GridStack Initialisierung
var grid = GridStack.init({
cellHeight: 80,
margin: 10,
float: true,
handle: '.widget-header',
resizable: {
handles: 'all'
}
});
// Layout speichern/laden
function saveLayout() {
const data = grid.save(false);
localStorage.setItem('pi-orch-layout-v2', JSON.stringify(data));
}
const savedData = localStorage.getItem('pi-orch-layout-v2');
if (savedData) {
try { grid.load(JSON.parse(savedData)); } catch(e) { console.error(e); }
}
grid.on('resizestop dragstop', function() {
saveLayout();
if (window.fitAddon) setTimeout(() => window.fitAddon.fit(), 100);
});
// 2. Xterm.js Setup
const term = new Terminal({ theme: { background: '#000' }, fontSize: 13, cursorBlink: true, convertEol: true });
window.fitAddon = new FitAddon.FitAddon();
term.loadAddon(window.fitAddon);
term.open(document.getElementById('terminal'));
setTimeout(() => window.fitAddon.fit(), 500);
// 3. WebSockets
const logWs = new WebSocket(`ws://${location.host}/ws/install_logs`);
const logContainer = document.getElementById('install-log');
logWs.onmessage = (ev) => {
// 1. Neues Element erstellen statt innerHTML +=
const div = document.createElement('div');
div.textContent = `> ${ev.data}`;
logContainer.appendChild(div);
// 2. Zeilen begrenzen (z.B. max 500 Zeilen behalten)
if (logContainer.childNodes.length > 500) {
logContainer.removeChild(logContainer.firstChild);
}
// 3. Auto-Scroll nur wenn wir am Ende sind (optional, aber CPU-schonend)
logContainer.scrollTop = logContainer.scrollHeight;
};
const chatWs = new WebSocket(`ws://${location.host}/ws/chat`);
chatWs.onmessage = (ev) => appendChat("KI", ev.data, "text-blue-400 font-bold");
// 4. Chat Funktionen
const userInput = document.getElementById('user-input');
userInput.focus();
userInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); window.sendMessage(); }
});
window.sendMessage = function() {
const val = userInput.value.trim();
if(!val) return;
chatWs.send(val);
appendChat("Du", val, "text-slate-300 font-bold");
userInput.value = '';
userInput.focus();
};
function appendChat(user, msg, classes) {
const win = document.getElementById('chat-window');
let formattedMsg = msg;
if (user === "KI" && typeof marked !== 'undefined') {
formattedMsg = marked.parse(msg);
}
win.innerHTML += `<div class="mb-4"><span class="${classes} block mb-1">${user}:</span><div class="markdown-content text-slate-300 text-sm leading-relaxed">${formattedMsg}</div></div>`;
win.scrollTop = win.scrollHeight;
}
// 5. Node Funktionen
window.openTerminal = function(ip) {
// alte websocket schließen
if (window.termWs) {
window.termWs.close();
window.termWs = null;
}
// alten onData listener entfernen ✅
if (termDataDisposable) {
termDataDisposable.dispose();
termDataDisposable = null;
}
term.clear();
term.write(`\r\n\x1b[34m>>> Verbinde mit ${ip}...\x1b[0m\r\n`);
window.termWs = new WebSocket(`ws://${location.host}/ws/terminal/${ip}`);
window.termWs.onmessage = (ev) => {
term.write(ev.data);
};
window.termWs.onclose = () => {
term.write("\r\n\x1b[31m[Session beendet]\x1b[0m\r\n");
};
// NEUEN listener registrieren
termDataDisposable = term.onData(data => {
if (window.termWs &&
window.termWs.readyState === WebSocket.OPEN) {
window.termWs.send(data);
}
});
setTimeout(() => window.fitAddon.fit(), 100);
};
window.addNode = async function() {
const name = prompt("Node Name:");
const ip = prompt("IP Adresse:");
const user = prompt("Benutzername:", "pi");
const pass = prompt("SSH Passwort:");
if (name && ip && pass) {
const fd = new FormData();
fd.append('name', name); fd.append('ip', ip);
fd.append('user', user); fd.append('password', pass);
const response = await fetch('/add_node', { method: 'POST', body: fd });
if (response.ok) location.reload();
}
};
window.refreshNodeStatus = async function(nodeId) {
const badge = document.getElementById(`badge-${nodeId}`);
const led = document.getElementById(`led-${nodeId}`);
badge.innerText = "Prüfe...";
try {
const r = await fetch(`/refresh_status/${nodeId}`);
const d = await r.json();
badge.innerText = d.status;
if (d.status === "Docker Aktiv") {
led.className = "h-2 w-2 rounded-full bg-blue-500 shadow-[0_0_8px_#3b82f6]";
} else {
led.className = "h-2 w-2 rounded-full bg-yellow-500";
}
} catch (e) { badge.innerText = "Fehler"; }
};
// Bekannte Standard-Modelle für das Dropdown
const modelOptions = {
google: ["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"],
openai: ["gpt-4o", "gpt-4-turbo", "gpt-3.5-turbo"],
ollama: ["llama3", "mistral", "qwen"]
};
async function loadSettings() { async function loadSettings() {
try { try {
@@ -430,7 +257,7 @@
updateModelDropdown(true); updateModelDropdown(true);
} catch (e) { } catch (e) {
console.error("Fehler beim Laden der Einstellungen:", e); console.error("Fehler beim Laden:", e);
} }
} }
@@ -439,26 +266,21 @@
const modelSelect = document.getElementById('ai-model'); const modelSelect = document.getElementById('ai-model');
const urlContainer = document.getElementById('ollama-url-container'); const urlContainer = document.getElementById('ollama-url-container');
if (!providerSelect || !urlContainer) { if (!providerSelect || !urlContainer) return;
console.error("Fehler: HTML Elemente nicht gefunden!");
return;
}
const provider = providerSelect.value; const provider = providerSelect.value;
console.log("Gewählter Provider:", provider); // Debug-Ausgabe für die Konsole console.log("Wechsel zu Provider:", provider);
// 1. Sichtbarkeit umschalten mit !important-Logik über JS // Sichtbarkeit umschalten
if (provider === "ollama") { if (provider === "ollama") {
urlContainer.setAttribute("style", "display: flex !important"); urlContainer.style.display = "flex";
} else { } else {
urlContainer.setAttribute("style", "display: none !important"); urlContainer.style.display = "none";
} }
// 2. Dropdown befüllen // Modelle füllen
if (modelSelect) {
modelSelect.innerHTML = ''; modelSelect.innerHTML = '';
const options = modelOptions[provider] || []; const options = modelOptions[provider] || [];
options.forEach(m => { options.forEach(m => {
const opt = document.createElement('option'); const opt = document.createElement('option');
opt.value = m; opt.value = m;
@@ -466,59 +288,98 @@
modelSelect.appendChild(opt); modelSelect.appendChild(opt);
}); });
// 3. Wert beim Laden setzen // Gespeicherten Wert setzen
if (isInitialLoad && currentSettings) { if (isInitialLoad && currentSettings) {
const savedModel = currentSettings[`${provider}_model`]; const savedModel = currentSettings[`${provider}_model`];
if (savedModel) { if (savedModel) modelSelect.value = savedModel;
// Falls das Modell nicht in der Liste ist, hinzufügen
if (!options.includes(savedModel)) {
const opt = document.createElement('option');
opt.value = savedModel;
opt.textContent = savedModel;
modelSelect.appendChild(opt);
}
modelSelect.value = savedModel;
}
}
} }
} }
async function saveSettings() { async function saveSettings() {
const provider = document.getElementById('ai-provider').value; const provider = document.getElementById('ai-provider').value;
const model = document.getElementById('ai-model').value; const model = document.getElementById('ai-model').value;
const ollamaUrl = document.getElementById('ollama-url').value; // NEU const ollamaUrl = document.getElementById('ollama-url').value;
const statusEl = document.getElementById('settings-status'); const statusEl = document.getElementById('settings-status');
statusEl.textContent = "Speichere..."; statusEl.textContent = "Speichere...";
statusEl.style.color = "#f1c40f";
try { try {
await fetch('/api/settings', { await fetch('/api/settings', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({ provider, model, ollama_base_url: ollamaUrl })
provider: provider,
model: model,
ollama_base_url: ollamaUrl // NEU
})
}); });
statusEl.textContent = "✅ Gespeichert!"; statusEl.textContent = "✅ Gespeichert!";
statusEl.style.color = "#2ecc71"; statusEl.style.color = "#2ecc71";
currentSettings.provider = provider;
currentSettings[`${provider}_model`] = model;
currentSettings.ollama_base_url = ollamaUrl;
} catch (e) { } catch (e) {
statusEl.textContent = "❌ Fehler"; statusEl.textContent = "❌ Fehler";
statusEl.style.color = "#e74c3c"; statusEl.style.color = "#e74c3c";
} }
setTimeout(() => statusEl.textContent = "", 3000); setTimeout(() => statusEl.textContent = "", 3000);
} }
// Einstellungen beim Laden der Seite abrufen
window.addEventListener('DOMContentLoaded', loadSettings); // 3. INITIALISIERUNG (Wenn die Seite geladen ist)
document.addEventListener('DOMContentLoaded', function() {
// Hier nur die Gridstack/Terminal/WebSocket Initialisierung rein
// GridStack
var grid = GridStack.init({
cellHeight: 80, margin: 10, float: true, handle: '.widget-header'
});
const savedData = localStorage.getItem('pi-orch-layout-v2');
if (savedData) { try { grid.load(JSON.parse(savedData)); } catch(e) {} }
grid.on('resizestop dragstop', () => {
localStorage.setItem('pi-orch-layout-v2', JSON.stringify(grid.save(false)));
});
// Terminal
const term = new Terminal({ theme: { background: '#000' }, fontSize: 13, convertEol: true });
window.fitAddon = new FitAddon.FitAddon();
term.loadAddon(window.fitAddon);
term.open(document.getElementById('terminal'));
// WebSockets
const logWs = new WebSocket(`ws://${location.host}/ws/install_logs`);
logWs.onmessage = (ev) => {
const div = document.createElement('div');
div.textContent = `> ${ev.data}`;
document.getElementById('install-log').appendChild(div);
document.getElementById('install-log').scrollTop = document.getElementById('install-log').scrollHeight;
};
const chatWs = new WebSocket(`ws://${location.host}/ws/chat`);
chatWs.onmessage = (ev) => appendChat("KI", ev.data, "text-blue-400 font-bold");
// Chat Senden Funktion global machen
window.sendMessage = function() {
const input = document.getElementById('user-input');
if(!input.value.trim()) return;
chatWs.send(input.value);
appendChat("Du", input.value, "text-slate-300 font-bold");
input.value = '';
};
function appendChat(user, msg, classes) {
const win = document.getElementById('chat-window');
let formattedMsg = (user === "KI") ? marked.parse(msg) : msg;
win.innerHTML += `<div class="mb-4"><span class="${classes} block mb-1">${user}:</span><div class="markdown-content text-slate-300 text-sm">${formattedMsg}</div></div>`;
win.scrollTop = win.scrollHeight;
}
// Node Funktionen global machen
window.openTerminal = function(ip) {
if (window.termWs) window.termWs.close();
if (termDataDisposable) termDataDisposable.dispose();
term.clear();
window.termWs = new WebSocket(`ws://${location.host}/ws/terminal/${ip}`);
window.termWs.onmessage = (ev) => term.write(ev.data);
termDataDisposable = term.onData(data => {
if (window.termWs?.readyState === WebSocket.OPEN) window.termWs.send(data);
});
};
// Jetzt die Einstellungen laden
loadSettings();
}); });
</script> </script>
</body> </body>