808 lines
31 KiB
JavaScript
808 lines
31 KiB
JavaScript
const refresh = document.getElementById("refresh");
|
|
const title = document.getElementById("printer-title");
|
|
const status = document.getElementById("printer-status");
|
|
const agentFacts = document.getElementById("agent-facts");
|
|
const connectivityFacts = document.getElementById("connectivity-facts");
|
|
const uiFacts = document.getElementById("ui-facts");
|
|
const syncFacts = document.getElementById("sync-facts");
|
|
const syncSummary = document.getElementById("sync-summary");
|
|
const installSummary = document.getElementById("install-summary");
|
|
const installVersionSummary = document.getElementById("install-version-summary");
|
|
const installMessage = document.getElementById("install-message");
|
|
const installFacts = document.getElementById("install-facts");
|
|
const rinkhalsSummary = document.getElementById("rinkhals-summary");
|
|
const rinkhalsFacts = document.getElementById("rinkhals-facts");
|
|
const rinkhalsLink = document.getElementById("rinkhals-link");
|
|
const installHistoryList = document.getElementById("install-history-list");
|
|
const printStatusFacts = document.getElementById("print-status-facts");
|
|
const moonrakerRawFacts = document.getElementById("moonraker-raw-facts");
|
|
const moonrakerRawSummary = document.getElementById("moonraker-raw-summary");
|
|
const moonrakerRawJson = document.getElementById("moonraker-raw-json");
|
|
const cameraList = document.getElementById("camera-list");
|
|
const healthLink = document.getElementById("health-link");
|
|
const printStatusLink = document.getElementById("print-status-link");
|
|
const moonrakerRawLink = document.getElementById("moonraker-raw-link");
|
|
const cameraLink = document.getElementById("camera-link");
|
|
const settingsLink = document.getElementById("settings-link");
|
|
const settingsEditLink = document.getElementById("settings-edit-link");
|
|
const installLink = document.getElementById("install-link");
|
|
const installAction = document.getElementById("install-action");
|
|
const upgradeNow = document.getElementById("upgrade-now");
|
|
const updateCheck = document.getElementById("update-check");
|
|
const installHistoryLink = document.getElementById("install-history-link");
|
|
const sshPasswordModal = document.getElementById("ssh-password-modal");
|
|
const sshPasswordInput = document.getElementById("ssh-password-input");
|
|
const sshPasswordCancel = document.getElementById("ssh-password-cancel");
|
|
const sshPasswordContinue = document.getElementById("ssh-password-continue");
|
|
const uiLink = document.getElementById("ui-link");
|
|
const backLink = document.getElementById("back-link");
|
|
const logoutCSRF = document.getElementById("logout-csrf");
|
|
const adminLink = document.getElementById("admin-link");
|
|
|
|
const printerID = decodeURIComponent(window.location.pathname.replace(/^\/printers\//, "").replace(/\/agent\/?$/, ""));
|
|
let lastData = null;
|
|
let pendingReinstallURL = "";
|
|
|
|
if (printerID) {
|
|
const encoded = encodeURIComponent(printerID);
|
|
if (backLink) {
|
|
backLink.href = `/printers/${encoded}`;
|
|
}
|
|
if (settingsLink) {
|
|
settingsLink.href = `/printers/${encoded}/settings`;
|
|
}
|
|
if (settingsEditLink) {
|
|
settingsEditLink.href = `/printers/${encoded}/settings`;
|
|
}
|
|
if (uiLink) {
|
|
uiLink.href = `/printers/${encoded}/ui/`;
|
|
}
|
|
if (healthLink) {
|
|
healthLink.href = `/api/printers/${encoded}`;
|
|
}
|
|
if (printStatusLink) {
|
|
printStatusLink.href = `/p/${encoded}/moonraker/printer/objects/query?print_stats&display_status&gcode_move&toolhead`;
|
|
}
|
|
if (moonrakerRawLink) {
|
|
moonrakerRawLink.href = `/p/${encoded}/moonraker/printer/objects/query?print_stats&display_status&gcode_move&toolhead`;
|
|
}
|
|
if (cameraLink) {
|
|
cameraLink.href = `/p/${encoded}/moonraker/server/webcams/list`;
|
|
}
|
|
if (adminLink) {
|
|
adminLink.href = `/admin?printer_id=${encoded}`;
|
|
}
|
|
if (installLink) {
|
|
installLink.href = `/install?printer_id=${encoded}`;
|
|
}
|
|
if (installAction) {
|
|
installAction.href = `/install?printer_id=${encoded}`;
|
|
}
|
|
if (installHistoryLink) {
|
|
installHistoryLink.href = `/api/printers/${encoded}`;
|
|
}
|
|
if (rinkhalsLink) {
|
|
rinkhalsLink.href = `/api/printers/${encoded}`;
|
|
}
|
|
}
|
|
|
|
async function loadSession() {
|
|
const response = await fetch("/api/session", { credentials: "same-origin" });
|
|
if (response.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
const session = await response.json();
|
|
if (!session.authenticated) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
window.__KA_SESSION__ = session;
|
|
logoutCSRF.value = session.csrf_token || "";
|
|
}
|
|
|
|
async function loadPrinter() {
|
|
if (!printerID) {
|
|
title.textContent = "Unknown printer";
|
|
return;
|
|
}
|
|
|
|
const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}`, { credentials: "same-origin" });
|
|
if (response.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
if (!response.ok) {
|
|
setStatus("Not reachable", false);
|
|
agentFacts.innerHTML = fact("Agent", `Unavailable (${response.status})`);
|
|
return;
|
|
}
|
|
|
|
const data = await response.json();
|
|
lastData = data;
|
|
const health = data.health || {};
|
|
const settings = data.settings || {};
|
|
const syncState = computeSettingsSync(settings, health);
|
|
const label = (settings.display_name && String(settings.display_name).trim()) || printerID;
|
|
title.textContent = label;
|
|
|
|
const reachable = Boolean(data.connected && health.moonraker_reachable);
|
|
setStatus(reachable ? (health.moonraker_state || "Reachable") : "Not reachable", reachable);
|
|
|
|
agentFacts.innerHTML = [
|
|
fact("Printer ID", printerID),
|
|
fact("Display name", settings.display_name || "Not set"),
|
|
fact("Agent hostname", health.hostname || "Unknown"),
|
|
fact("Agent version", health.agent_version || "Unknown"),
|
|
fact("Last heartbeat", health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat"),
|
|
fact("Access", data.access || "unknown"),
|
|
].join("");
|
|
|
|
connectivityFacts.innerHTML = [
|
|
fact("Connected", data.connected ? "Yes" : "No"),
|
|
fact("Moonraker", health.moonraker_reachable ? "Reachable" : "Not reachable"),
|
|
fact("Moonraker state", health.moonraker_state || "Unknown"),
|
|
fact("Moonraker message", health.moonraker_message || "No status message yet."),
|
|
fact("Moonraker URL", health.moonraker_url || "Unknown"),
|
|
fact("Camera count", String(Array.isArray(health.cameras) ? health.cameras.length : 0)),
|
|
].join("");
|
|
|
|
uiFacts.innerHTML = [
|
|
fact("Configured UI", settings.ui_url || "Auto"),
|
|
fact("Applied UI", health.ui_url || "Unavailable"),
|
|
fact("UI source", health.ui_source || "Unknown"),
|
|
fact("UI reachable", health.ui_reachable ? "Yes" : "No"),
|
|
fact("Auto-detect", settings.ui_auto_detect ? "On" : "Off"),
|
|
].join("");
|
|
|
|
syncSummary.textContent = syncState.detail;
|
|
syncFacts.innerHTML = [
|
|
fact("Control mode", settings.control_mode || "readonly"),
|
|
fact("Applied mode", health.control_mode || "Unknown"),
|
|
fact("Sync", syncState.state),
|
|
fact("Last sync", settings.last_synced_at ? new Date(settings.last_synced_at).toLocaleString() : "Unknown"),
|
|
fact("Updated", settings.updated_at ? new Date(settings.updated_at).toLocaleString() : "Unknown"),
|
|
].join("");
|
|
const versionState = computeVersionState(health);
|
|
renderInstallDetails(settings.install, versionState);
|
|
renderRinkhalsRuntime(settings.install, health);
|
|
renderInstallHistory(settings.install_history || [], versionState);
|
|
updateInstallAction(settings.install, versionState);
|
|
updateUpgradeButton(settings.install, versionState);
|
|
updateCheckButton(versionState);
|
|
|
|
renderPrintStatus(data.print_status || health.print_status || null, data.print_status_error || "");
|
|
renderRawMoonraker({
|
|
query: (data.print_status && data.print_status.moonraker_status) || (health.print_status && health.print_status.moonraker_status) || null,
|
|
layer_source: (data.print_status && data.print_status.layer_source) || (health.print_status && health.print_status.layer_source) || "",
|
|
}, data.print_status_error || "");
|
|
void loadRawMoonraker();
|
|
renderCameras(health.cameras || []);
|
|
|
|
if (uiLink) {
|
|
updateUILink(health);
|
|
}
|
|
if (installLink) {
|
|
installLink.href = installURL(settings.install);
|
|
}
|
|
}
|
|
|
|
function updateInstallAction(install, versionState) {
|
|
if (!installAction) {
|
|
return;
|
|
}
|
|
installAction.textContent = "Reinstall via SSH";
|
|
installAction.href = installURL(install);
|
|
}
|
|
|
|
function installURL(install) {
|
|
const params = new URLSearchParams({ printer_id: printerID });
|
|
const hostType = String(install && install.host_type ? install.host_type : "").trim().toLowerCase();
|
|
if (hostType) {
|
|
params.set("host_type", hostType);
|
|
}
|
|
return `/install?${params.toString()}`;
|
|
}
|
|
|
|
function updateUpgradeButton(install, versionState) {
|
|
if (!upgradeNow) {
|
|
return;
|
|
}
|
|
const canUpgrade = Boolean(install);
|
|
const label = !canUpgrade ? "Upgrade now" : (versionState && versionState.upToDate ? "Reinstall now" : "Upgrade now");
|
|
upgradeNow.textContent = label;
|
|
upgradeNow.disabled = !canUpgrade;
|
|
upgradeNow.title = canUpgrade ? versionState.detail : "No saved install details are available yet.";
|
|
}
|
|
|
|
function renderInstallDetails(install, versionState) {
|
|
if (!installFacts || !installSummary) {
|
|
return;
|
|
}
|
|
if (!install) {
|
|
installSummary.textContent = "No install details saved yet.";
|
|
if (installVersionSummary) {
|
|
installVersionSummary.textContent = versionState.detail;
|
|
}
|
|
installFacts.innerHTML = fact("Status", "None");
|
|
return;
|
|
}
|
|
const statusLabel = String(install.status || "unknown");
|
|
installSummary.textContent = install.error
|
|
? `Last install failed. ${install.error}`
|
|
: install.post_install_connected
|
|
? "Last install completed and the agent called back."
|
|
: `Last install saved for ${install.printer_id || printerID}.`;
|
|
if (installVersionSummary) {
|
|
installVersionSummary.textContent = versionState.detail;
|
|
}
|
|
installFacts.innerHTML = [
|
|
fact("Status", statusLabel),
|
|
fact("Host", `${install.host || "Unknown"}:${install.port || 22}`),
|
|
fact("Host type", install.host_type || "standard"),
|
|
fact("Username", install.username || "Unknown"),
|
|
fact("Server URL", install.server_url || "Unknown"),
|
|
fact("Moonraker URL", install.moonraker_url || "Unknown"),
|
|
fact("UI URL", install.ui_url || "Auto"),
|
|
fact("UI auto-detect", install.ui_auto_detect ? "On" : "Off"),
|
|
fact("Requested by", install.requested_by || "Unknown"),
|
|
fact("Remote host", install.remote_host || "Unknown"),
|
|
fact("Release URL", install.release_url || "Unknown"),
|
|
fact("Binary source", install.binary_source || "Unknown"),
|
|
fact("Message", install.message || "No install message."),
|
|
fact("Post-install", install.post_install_connected ? "Confirmed" : "Pending"),
|
|
fact("Rollback", install.rollback_performed ? "Available" : "Not needed"),
|
|
fact("Updated", install.updated_at ? new Date(install.updated_at).toLocaleString() : "Unknown"),
|
|
].join("");
|
|
}
|
|
|
|
function renderRinkhalsRuntime(install, health) {
|
|
if (!rinkhalsFacts || !rinkhalsSummary) {
|
|
return;
|
|
}
|
|
const isRinkhals = String(install && install.host_type ? install.host_type : "").trim().toLowerCase() === "rinkhals";
|
|
if (!isRinkhals) {
|
|
rinkhalsSummary.textContent = "Not using the Rinkhals app runtime.";
|
|
rinkhalsFacts.innerHTML = fact("Runtime", "Not applicable");
|
|
if (rinkhalsLink) {
|
|
rinkhalsLink.hidden = true;
|
|
}
|
|
return;
|
|
}
|
|
const enabled = Boolean(install && (install.status === "installed" || install.status === "upgraded") && install.post_install_connected);
|
|
const appRoot = String(install.binary_path || "").replace(/\/[^/]+$/, "") || "Unknown";
|
|
rinkhalsSummary.textContent = enabled
|
|
? "The Rinkhals app bundle is installed and has called back."
|
|
: "The Rinkhals app bundle is installed but has not confirmed a callback yet.";
|
|
rinkhalsFacts.innerHTML = [
|
|
fact("Enabled", enabled ? "Yes" : "No"),
|
|
fact("App root", appRoot),
|
|
fact("Config path", install.config_path || "Unknown"),
|
|
fact("Launcher", "app.sh"),
|
|
fact("Status", install.status || "unknown"),
|
|
fact("Post-install", install.post_install_connected ? "Confirmed" : "Pending"),
|
|
fact("Rollback", install.rollback_performed ? "Available" : "Not needed"),
|
|
fact("Latest heartbeat", health && health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat"),
|
|
].join("");
|
|
if (rinkhalsLink) {
|
|
rinkhalsLink.hidden = false;
|
|
rinkhalsLink.href = `/api/printers/${encodeURIComponent(printerID)}`;
|
|
}
|
|
}
|
|
|
|
function renderInstallHistory(history, versionState) {
|
|
if (!installHistoryList) {
|
|
return;
|
|
}
|
|
if (!Array.isArray(history) || history.length === 0) {
|
|
installHistoryList.innerHTML = '<p class="empty-state">No install history saved yet.</p>';
|
|
return;
|
|
}
|
|
installHistoryList.innerHTML = history.slice(0, 8).map((entry) => {
|
|
const statusLabel = String(entry.status || "unknown");
|
|
const statusClass = statusLabel === "installed" || statusLabel === "upgraded" ? "ok" : "warn";
|
|
const summary = entry.error
|
|
? `Failed: ${entry.error}`
|
|
: entry.post_install_connected
|
|
? (statusLabel === "upgraded" ? "Agent self-update completed." : "Agent called back successfully.")
|
|
: entry.rollback_performed
|
|
? "Replacement rolled back after reconnect timeout."
|
|
: "Install run completed.";
|
|
const context = [];
|
|
if (entry.host_type) {
|
|
context.push(entry.host_type);
|
|
}
|
|
if (entry.requested_by) {
|
|
context.push(`by ${entry.requested_by}`);
|
|
}
|
|
if (entry.binary_source) {
|
|
context.push(entry.binary_source);
|
|
}
|
|
if (entry.remote_host) {
|
|
context.push(entry.remote_host);
|
|
}
|
|
return `
|
|
<section class="job-row">
|
|
<div class="job-row-top">
|
|
<strong>${escapeHTML(entry.updated_at ? new Date(entry.updated_at).toLocaleString() : "Unknown time")}</strong>
|
|
<span class="status-pill ${statusClass}">${escapeHTML(statusLabel)}</span>
|
|
</div>
|
|
<p class="panel-subtitle">${escapeHTML(summary)}</p>
|
|
<dl class="printer-facts job-facts">
|
|
<div><dt>Host</dt><dd>${escapeHTML(`${entry.host || "Unknown"}:${entry.port || 22}`)}</dd></div>
|
|
<div><dt>Username</dt><dd>${escapeHTML(entry.username || "Unknown")}</dd></div>
|
|
<div><dt>Version</dt><dd>${escapeHTML(entry.status === "installed" ? versionState.current : "Unknown")}</dd></div>
|
|
<div><dt>Context</dt><dd>${escapeHTML(context.join(" / ") || "No extra details")}</dd></div>
|
|
</dl>
|
|
</section>
|
|
`;
|
|
}).join("");
|
|
}
|
|
|
|
function updateCheckButton(versionState) {
|
|
if (!updateCheck) {
|
|
return;
|
|
}
|
|
updateCheck.textContent = versionState.upToDate ? "Up to date" : "Check for updates";
|
|
updateCheck.title = versionState.detail;
|
|
updateCheck.disabled = false;
|
|
}
|
|
|
|
function setInstallMessage(text, ok) {
|
|
if (!installMessage) {
|
|
return;
|
|
}
|
|
if (!text) {
|
|
installMessage.hidden = true;
|
|
installMessage.textContent = "";
|
|
installMessage.className = "form-message";
|
|
return;
|
|
}
|
|
installMessage.hidden = false;
|
|
installMessage.textContent = text;
|
|
installMessage.className = ok ? "form-message success" : "form-message error";
|
|
}
|
|
|
|
async function handleUpdateCheckClick() {
|
|
if (updateCheck) {
|
|
updateCheck.disabled = true;
|
|
updateCheck.textContent = "Checking...";
|
|
}
|
|
await loadSession();
|
|
await loadPrinter();
|
|
}
|
|
|
|
async function handleUpgradeNowClick() {
|
|
if (!upgradeNow || upgradeNow.disabled) {
|
|
return;
|
|
}
|
|
upgradeNow.disabled = true;
|
|
upgradeNow.textContent = "Upgrading...";
|
|
try {
|
|
const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/agent/update`, {
|
|
method: "POST",
|
|
credentials: "same-origin",
|
|
headers: {
|
|
"X-CSRF-Token": logoutCSRF.value || "",
|
|
},
|
|
});
|
|
if (!response.ok) {
|
|
const error = await response.text();
|
|
setInstallMessage(error || `Agent update failed (${response.status})`, false);
|
|
return;
|
|
}
|
|
const payload = await response.json().catch(() => ({}));
|
|
setInstallMessage(String(payload.reconnect_message || "Agent update requested."), true);
|
|
await loadSession();
|
|
await loadPrinter();
|
|
} finally {
|
|
upgradeNow.disabled = false;
|
|
}
|
|
}
|
|
|
|
function getSSHPasswordStorageKey() {
|
|
return `ka-ssh-password:${printerID}`;
|
|
}
|
|
|
|
function openSSHPasswordModal(targetURL) {
|
|
if (!sshPasswordModal || !sshPasswordInput || !sshPasswordContinue) {
|
|
window.location.href = targetURL;
|
|
return;
|
|
}
|
|
pendingReinstallURL = targetURL;
|
|
sshPasswordInput.value = "";
|
|
sshPasswordModal.hidden = false;
|
|
sshPasswordInput.focus();
|
|
}
|
|
|
|
function closeSSHPasswordModal() {
|
|
if (!sshPasswordModal || !sshPasswordInput) {
|
|
return;
|
|
}
|
|
sshPasswordModal.hidden = true;
|
|
sshPasswordInput.value = "";
|
|
pendingReinstallURL = "";
|
|
}
|
|
|
|
function confirmSSHPasswordModal() {
|
|
if (!sshPasswordInput || !pendingReinstallURL) {
|
|
return;
|
|
}
|
|
const password = String(sshPasswordInput.value || "").trim();
|
|
if (!password) {
|
|
setInstallMessage("SSH password is required to continue with reinstall.", false);
|
|
return;
|
|
}
|
|
try {
|
|
sessionStorage.setItem(getSSHPasswordStorageKey(), password);
|
|
} catch {
|
|
// Session storage can fail in private/locked-down modes; continue anyway.
|
|
}
|
|
const targetURL = pendingReinstallURL;
|
|
closeSSHPasswordModal();
|
|
window.location.href = targetURL;
|
|
}
|
|
|
|
function renderPrintStatus(statusData, error) {
|
|
if (!printStatusFacts) {
|
|
return;
|
|
}
|
|
if (!statusData) {
|
|
printStatusFacts.innerHTML = fact("State", error ? `Unavailable (${error})` : "Unknown");
|
|
return;
|
|
}
|
|
const printStats = statusData.print_stats || statusData;
|
|
const displayStatus = statusData.display_status || statusData;
|
|
printStatusFacts.innerHTML = [
|
|
fact("State", printStats.state || "Unknown"),
|
|
fact("File", printStats.filename || "No file loaded"),
|
|
fact("Progress", formatProgress(displayStatus.progress)),
|
|
fact("Print duration", formatDuration(printStats.print_duration)),
|
|
fact("Total duration", formatDuration(printStats.total_duration)),
|
|
fact("Remaining", formatDuration(printStats.estimated_time_remaining || printStats.estimated_duration)),
|
|
fact("Filament", formatFilament(printStats.filament_used)),
|
|
fact("Message", printStats.message || displayStatus.message || "No status message yet."),
|
|
].join("");
|
|
}
|
|
|
|
function renderRawMoonraker(payload, error) {
|
|
if (!moonrakerRawFacts || !moonrakerRawSummary || !moonrakerRawJson) {
|
|
return;
|
|
}
|
|
const rawQuery = payload && typeof payload === "object" && payload.query && typeof payload.query === "object" ? payload.query : null;
|
|
const layerSource = payload && typeof payload === "object" && typeof payload.layer_source === "string" ? payload.layer_source : "";
|
|
const rawStatus = rawQuery;
|
|
if (!rawStatus) {
|
|
moonrakerRawSummary.textContent = error ? `Raw Moonraker payload unavailable (${error}).` : "Raw Moonraker payload unavailable.";
|
|
moonrakerRawFacts.innerHTML = [
|
|
fact("Raw keys", "None"),
|
|
fact("MMU keys", "None"),
|
|
fact("print_stats.info.current_layer", "Unset"),
|
|
fact("print_stats.info.total_layer", "Unset"),
|
|
fact("Layer source", layerSource || "Unset"),
|
|
fact("display_status.progress", "0%"),
|
|
fact("gcode_move.position.z", "Unset"),
|
|
fact("toolhead.position.z", "Unset"),
|
|
fact("mmu.enabled", "Unset"),
|
|
fact("mmu.print_state", "Unset"),
|
|
fact("mmu.action", "Unset"),
|
|
fact("mmu_machine.unit_0.name", "Unset"),
|
|
fact("display_status.message", "No raw payload available."),
|
|
].join("");
|
|
moonrakerRawJson.textContent = "Waiting for raw Moonraker data...";
|
|
return;
|
|
}
|
|
|
|
const printStats = rawStatus.print_stats || {};
|
|
const displayStatus = rawStatus.display_status || {};
|
|
const gcodeMove = rawStatus.gcode_move || {};
|
|
const toolhead = rawStatus.toolhead || {};
|
|
const mmu = rawStatus.mmu && typeof rawStatus.mmu === "object" ? rawStatus.mmu : null;
|
|
const mmuMachine = rawStatus.mmu_machine && typeof rawStatus.mmu_machine === "object" ? rawStatus.mmu_machine : null;
|
|
const printInfo = printStats.info || {};
|
|
const currentLayer = printInfo.current_layer ?? printStats.current_layer ?? displayStatus.current_layer ?? null;
|
|
const totalLayer = printInfo.total_layer ?? printStats.total_layer ?? displayStatus.total_layer ?? null;
|
|
const rawKeys = Object.keys(rawStatus).sort().join(", ") || "None";
|
|
const mmuKeys = mmu && typeof mmu === "object" ? Object.keys(mmu).sort().join(", ") || "None" : "None";
|
|
const mmuMachineName = mmuMachine && mmuMachine.unit_0 && typeof mmuMachine.unit_0 === "object" && mmuMachine.unit_0.name ? String(mmuMachine.unit_0.name) : "Unset";
|
|
const mmuEnabled = mmu && Object.prototype.hasOwnProperty.call(mmu, "enabled")
|
|
? (mmu.enabled ? "Yes" : "No")
|
|
: "Unset";
|
|
const activeFilament = mmu && mmu.active_filament && typeof mmu.active_filament === "object"
|
|
? [
|
|
mmu.active_filament.vendor || "",
|
|
mmu.active_filament.manufacturer || "",
|
|
mmu.active_filament.material || "",
|
|
mmu.active_filament.color || "",
|
|
].filter((value) => String(value || "").trim()).join(" / ") || "Unset"
|
|
: "Unset";
|
|
|
|
moonrakerRawSummary.textContent = "Raw Moonraker query payload from the agent heartbeat.";
|
|
moonrakerRawFacts.innerHTML = [
|
|
fact("Raw keys", rawKeys),
|
|
fact("MMU keys", mmuKeys),
|
|
fact("print_stats.info.current_layer", currentLayer === null || currentLayer === undefined ? "Unset" : String(currentLayer)),
|
|
fact("print_stats.info.total_layer", totalLayer === null || totalLayer === undefined ? "Unset" : String(totalLayer)),
|
|
fact("Layer source", layerSource || "Unset"),
|
|
fact("display_status.progress", formatProgress(displayStatus.progress)),
|
|
fact("display_status.message", displayStatus.message || "No message"),
|
|
fact("gcode_move.position.z", formatDecimal(positionZ(gcodeMove))),
|
|
fact("toolhead.position.z", formatDecimal(positionZ(toolhead))),
|
|
fact("mmu.enabled", mmuEnabled),
|
|
fact("mmu.print_state", mmu && mmu.print_state ? String(mmu.print_state) : "Unset"),
|
|
fact("mmu.action", mmu && mmu.action ? String(mmu.action) : "Unset"),
|
|
fact("mmu_machine.unit_0.name", mmuMachineName),
|
|
fact("mmu.active_filament", activeFilament),
|
|
].join("");
|
|
moonrakerRawJson.textContent = JSON.stringify({ query: rawStatus }, null, 2);
|
|
}
|
|
|
|
async function loadRawMoonraker() {
|
|
if (!moonrakerRawFacts || !moonrakerRawSummary || !moonrakerRawJson) {
|
|
return;
|
|
}
|
|
if (!printerID) {
|
|
return;
|
|
}
|
|
try {
|
|
const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/objects/query?print_stats&display_status&gcode_move&toolhead`, {
|
|
credentials: "same-origin",
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP ${response.status}`);
|
|
}
|
|
const payload = await response.json();
|
|
const rawStatus = payload && payload.result && payload.result.status ? payload.result.status : null;
|
|
renderRawMoonraker({
|
|
query: rawStatus,
|
|
layer_source: (lastData && ((lastData.print_status && lastData.print_status.layer_source) || (lastData.health && lastData.health.print_status && lastData.health.print_status.layer_source))) || "",
|
|
}, "");
|
|
} catch (error) {
|
|
const fallbackQuery = lastData && ((lastData.print_status && lastData.print_status.moonraker_status) || (lastData.health && lastData.health.print_status && lastData.health.print_status.moonraker_status)) || null;
|
|
const fallbackLayerSource = lastData && ((lastData.print_status && lastData.print_status.layer_source) || (lastData.health && lastData.health.print_status && lastData.health.print_status.layer_source)) || "";
|
|
renderRawMoonraker({ query: fallbackQuery, layer_source: fallbackLayerSource }, error && error.message ? error.message : String(error || "unknown error"));
|
|
}
|
|
}
|
|
|
|
function positionZ(source) {
|
|
if (!source || typeof source !== "object") {
|
|
return null;
|
|
}
|
|
for (const key of ["position", "gcode_position"]) {
|
|
const value = source[key];
|
|
if (Array.isArray(value) && value.length > 2) {
|
|
const number = Number(value[2]);
|
|
if (Number.isFinite(number)) {
|
|
return number;
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function formatDecimal(value) {
|
|
if (value === null || value === undefined || value === "") {
|
|
return "Unset";
|
|
}
|
|
const number = Number(value);
|
|
if (!Number.isFinite(number)) {
|
|
return "Unset";
|
|
}
|
|
return number.toFixed(3).replace(/\.?0+$/, "");
|
|
}
|
|
|
|
function renderCameras(cameras) {
|
|
if (!cameraList) {
|
|
return;
|
|
}
|
|
if (!Array.isArray(cameras) || cameras.length === 0) {
|
|
cameraList.innerHTML = '<p class="empty-state">No cameras are configured for this agent.</p>';
|
|
return;
|
|
}
|
|
cameraList.innerHTML = cameras.map((camera) => {
|
|
const previewBits = [];
|
|
if (camera.location) {
|
|
previewBits.push(camera.location);
|
|
}
|
|
if (camera.service) {
|
|
previewBits.push(camera.service);
|
|
}
|
|
if (camera.source) {
|
|
previewBits.push(camera.source);
|
|
}
|
|
const snapshotURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/snapshot`;
|
|
const streamURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/stream`;
|
|
return `
|
|
<section class="job-row">
|
|
<div class="job-row-top">
|
|
<strong>${escapeHTML(camera.name || "Camera")}</strong>
|
|
<span class="status-pill ${camera.has_stream ? "ok" : "warn"}">${camera.has_stream ? "stream" : "snapshot"}</span>
|
|
</div>
|
|
<dl class="printer-facts job-facts">
|
|
<div><dt>Source</dt><dd>${escapeHTML(previewBits.join(" / ") || "Configured camera")}</dd></div>
|
|
<div><dt>Snapshot</dt><dd>${camera.has_snapshot ? `<a href="${snapshotURL}" target="_blank" rel="noreferrer">Open</a>` : "Unavailable"}</dd></div>
|
|
<div><dt>Stream</dt><dd>${camera.has_stream ? `<a href="${streamURL}" target="_blank" rel="noreferrer">Open</a>` : "Unavailable"}</dd></div>
|
|
<div><dt>Aspect</dt><dd>${escapeHTML(camera.aspect_ratio || "16:9")}</dd></div>
|
|
</dl>
|
|
</section>
|
|
`;
|
|
}).join("");
|
|
}
|
|
|
|
function updateUILink(health) {
|
|
if (!uiLink) {
|
|
return;
|
|
}
|
|
const uiRoute = `/printers/${encodeURIComponent(printerID)}/ui/`;
|
|
if (health.ui_reachable) {
|
|
uiLink.href = uiRoute;
|
|
uiLink.removeAttribute("aria-disabled");
|
|
uiLink.classList.remove("disabled");
|
|
uiLink.textContent = "Open Printer UI";
|
|
return;
|
|
}
|
|
uiLink.href = "#";
|
|
uiLink.setAttribute("aria-disabled", "true");
|
|
uiLink.classList.add("disabled");
|
|
uiLink.textContent = "UI unavailable";
|
|
}
|
|
|
|
function computeSettingsSync(settings, health) {
|
|
const updatedAt = parseTimestamp(settings.updated_at);
|
|
const lastSyncedAt = parseTimestamp(settings.last_synced_at);
|
|
const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly";
|
|
const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown";
|
|
const uiURL = String(settings.ui_url || "").trim();
|
|
const agentUIURL = String(health.ui_url || "").trim();
|
|
const autoDetect = Boolean(settings.ui_auto_detect);
|
|
const agentAutoDetect = Boolean(health.ui_auto_detect);
|
|
const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt);
|
|
if (synced) {
|
|
return {
|
|
synced: true,
|
|
state: "Synced",
|
|
detail: "Agent acknowledged the latest saved settings.",
|
|
};
|
|
}
|
|
const detailBits = [];
|
|
if (controlMode !== appliedMode && appliedMode !== "unknown") {
|
|
detailBits.push(`control mode ${controlMode} -> ${appliedMode}`);
|
|
}
|
|
if (uiURL && uiURL !== agentUIURL) {
|
|
detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`);
|
|
}
|
|
if (autoDetect !== agentAutoDetect) {
|
|
detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`);
|
|
}
|
|
return {
|
|
synced: false,
|
|
state: "Pending",
|
|
detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.",
|
|
};
|
|
}
|
|
|
|
function computeVersionState(health) {
|
|
const current = String(health && health.agent_version ? health.agent_version : "Unknown");
|
|
const available = String(window.__KA_SESSION__ && window.__KA_SESSION__.server_version ? window.__KA_SESSION__.server_version : "dev");
|
|
const upToDate = Boolean(current && available && current !== "Unknown" && available !== "Unknown" && current === available);
|
|
return {
|
|
current,
|
|
available,
|
|
upToDate,
|
|
detail: upToDate
|
|
? `Agent ${current} is up to date.`
|
|
: current === "Unknown"
|
|
? `Available agent version: ${available}.`
|
|
: `Installed agent ${current}; available ${available}.`,
|
|
};
|
|
}
|
|
|
|
function setStatus(label, ok) {
|
|
status.textContent = label;
|
|
status.classList.toggle("ok", ok);
|
|
status.classList.toggle("warn", !ok);
|
|
}
|
|
|
|
function fact(label, value) {
|
|
return `<div><dt>${escapeHTML(label)}</dt><dd>${escapeHTML(value)}</dd></div>`;
|
|
}
|
|
|
|
function parseTimestamp(value) {
|
|
if (!value) {
|
|
return 0;
|
|
}
|
|
const parsed = Date.parse(value);
|
|
return Number.isFinite(parsed) ? parsed : 0;
|
|
}
|
|
|
|
function relativeTime(unixSeconds) {
|
|
const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds);
|
|
if (seconds < 5) {
|
|
return "just now";
|
|
}
|
|
if (seconds < 60) {
|
|
return `${seconds}s ago`;
|
|
}
|
|
const minutes = Math.floor(seconds / 60);
|
|
if (minutes < 60) {
|
|
return `${minutes}m ago`;
|
|
}
|
|
const hours = Math.floor(minutes / 60);
|
|
return `${hours}h ago`;
|
|
}
|
|
|
|
function formatProgress(value) {
|
|
const progress = Number(value);
|
|
if (!Number.isFinite(progress) || progress <= 0) {
|
|
return "0%";
|
|
}
|
|
if (progress <= 1) {
|
|
return `${Math.round(progress * 100)}%`;
|
|
}
|
|
return `${Math.round(progress)}%`;
|
|
}
|
|
|
|
function formatDuration(value) {
|
|
const seconds = Number(value);
|
|
if (!Number.isFinite(seconds) || seconds < 0) {
|
|
return "Unknown";
|
|
}
|
|
const whole = Math.floor(seconds);
|
|
const hours = Math.floor(whole / 3600);
|
|
const minutes = Math.floor((whole % 3600) / 60);
|
|
const secs = whole % 60;
|
|
if (hours > 0) {
|
|
return `${hours}h ${minutes}m ${secs}s`;
|
|
}
|
|
if (minutes > 0) {
|
|
return `${minutes}m ${secs}s`;
|
|
}
|
|
return `${secs}s`;
|
|
}
|
|
|
|
function formatFilament(value) {
|
|
const number = Number(value);
|
|
if (!Number.isFinite(number) || number <= 0) {
|
|
return "Unknown";
|
|
}
|
|
return `${number.toFixed(1)} mm`;
|
|
}
|
|
|
|
function escapeHTML(value) {
|
|
return String(value)
|
|
.replaceAll("&", "&")
|
|
.replaceAll("<", "<")
|
|
.replaceAll(">", ">")
|
|
.replaceAll('"', """)
|
|
.replaceAll("'", "'");
|
|
}
|
|
|
|
refresh.addEventListener("click", loadPrinter);
|
|
if (updateCheck) {
|
|
updateCheck.addEventListener("click", handleUpdateCheckClick);
|
|
}
|
|
if (upgradeNow) {
|
|
upgradeNow.addEventListener("click", handleUpgradeNowClick);
|
|
}
|
|
if (installAction) {
|
|
installAction.addEventListener("click", (event) => {
|
|
event.preventDefault();
|
|
openSSHPasswordModal(installAction.href);
|
|
});
|
|
}
|
|
if (sshPasswordCancel) {
|
|
sshPasswordCancel.addEventListener("click", () => closeSSHPasswordModal());
|
|
}
|
|
if (sshPasswordContinue) {
|
|
sshPasswordContinue.addEventListener("click", () => confirmSSHPasswordModal());
|
|
}
|
|
if (sshPasswordModal) {
|
|
sshPasswordModal.addEventListener("click", (event) => {
|
|
if (event.target === sshPasswordModal) {
|
|
closeSSHPasswordModal();
|
|
}
|
|
});
|
|
}
|
|
loadSession().then(loadPrinter);
|
|
setInterval(loadPrinter, 15000);
|