1668 lines
73 KiB
JavaScript
1668 lines
73 KiB
JavaScript
|
|
const _DBG = false; // set true to enable streaming/editor debug logs
|
|
const API = window.location.origin || 'http://127.0.0.1:18789';
|
|
let ws = null;
|
|
let wsWakeLock = null;
|
|
let selectedJobId = null;
|
|
let allJobs = [];
|
|
let pollInterval = null;
|
|
let currentMode = 'chat';
|
|
let sidebarTab = 'jobs';
|
|
let useAgentMode = false;
|
|
const CHAT_SESSIONS_KEY_BASE = 'homeclaw_chat_sessions_v1';
|
|
const AGENT_SESSION_KEY_BASE = 'homeclaw_agent_session_id';
|
|
const THEME_KEY = 'homeclaw_theme';
|
|
const TOKEN_KEY = 'smallclaw_token';
|
|
function toggleModeDropdown(e, id) {
|
|
if (e) e.stopPropagation();
|
|
var menu = document.getElementById(id.replace('mode-dropdown-', 'mode-dropdown-menu-'));
|
|
if (!menu) return;
|
|
var opening = !menu.classList.contains('open');
|
|
document.querySelectorAll('.mode-dropdown-menu.open').forEach(closeMenu);
|
|
if (opening) {
|
|
menu.classList.add('open');
|
|
positionModeDropdown(menu);
|
|
setTimeout(function() {
|
|
document.addEventListener('click', function closeModeDropdown() {
|
|
closeMenu(menu);
|
|
document.removeEventListener('click', closeModeDropdown);
|
|
});
|
|
}, 0);
|
|
}
|
|
}
|
|
|
|
function closeMenu(m) {
|
|
m.classList.remove('open');
|
|
m.classList.remove('dd-floating');
|
|
m.style.left = '';
|
|
m.style.top = '';
|
|
// Put it back next to its button, so previousElementSibling still finds the button next time.
|
|
if (m._ddHome) { m._ddHome.appendChild(m); m._ddHome = null; }
|
|
}
|
|
|
|
/**
|
|
* Place an open dropdown on mobile by moving it out to <body>.
|
|
*
|
|
* On mobile the app strip becomes a horizontally scrolling container with a right-edge fade
|
|
* (mask-image). Both of those clip descendants, so a menu hanging below the strip was clipped out
|
|
* of existence — the dropdown opened and simply could not be seen, and z-index cannot climb out of
|
|
* an ancestor's clip.
|
|
*
|
|
* position:fixed alone does NOT fix it: fixed escapes overflow clipping but not a mask. Measured
|
|
* 2026-08-14 with the menu fixed and still inside the strip — invisible, with <body> painted at
|
|
* its centre. Leaving the strip entirely is what works, so the menu is reparented to <body> while
|
|
* open and returned to its dropdown afterwards. Desktop is untouched: there the strip has no
|
|
* scroller and no mask, and plain CSS-absolute placement already works.
|
|
*/
|
|
function positionModeDropdown(menu) {
|
|
if (window.innerWidth > 1024) return;
|
|
var btn = menu.previousElementSibling;
|
|
if (!btn) return;
|
|
var r = btn.getBoundingClientRect();
|
|
menu._ddHome = menu.parentElement;
|
|
document.body.appendChild(menu);
|
|
menu.classList.add('dd-floating');
|
|
var width = menu.offsetWidth || 130; // measured after the move, once it is laid out unclipped
|
|
// Buttons near the right edge would otherwise push the menu off-screen.
|
|
menu.style.left = Math.round(Math.max(4, Math.min(r.left, window.innerWidth - width - 4))) + 'px';
|
|
menu.style.top = Math.round(r.bottom + 4) + 'px';
|
|
}
|
|
|
|
function getAuthToken() { try { return sessionStorage.getItem(TOKEN_KEY) || ''; } catch { return ''; } }
|
|
function setAuthToken(t) { try { t ? sessionStorage.setItem(TOKEN_KEY, t) : sessionStorage.removeItem(TOKEN_KEY); t ? localStorage.setItem(TOKEN_KEY, t) : localStorage.removeItem(TOKEN_KEY); } catch {} }
|
|
function authHeaders(extra) { const t = getAuthToken(); const h = { ...(extra||{}) }; if (t) h['Authorization'] = 'Bearer ' + t; return h; }
|
|
function chatSessionsKey() { const u = (currentUser && currentUser.username) || '__anon__'; return `${CHAT_SESSIONS_KEY_BASE}__${u}`; }
|
|
function agentSessionKey() { const u = (currentUser && currentUser.username) || '__anon__'; return `${AGENT_SESSION_KEY_BASE}__${u}`; }
|
|
function generateSessionId() {
|
|
return (crypto?.randomUUID?.() || ('sess_' + Math.random().toString(36).slice(2)));
|
|
}
|
|
function getCookie(name) {
|
|
const value = `; ${document.cookie}`;
|
|
const parts = value.split(`; ${name}=`);
|
|
if (parts.length === 2) return parts.pop().split(';').shift();
|
|
return '';
|
|
}
|
|
function setAgentSessionId(id) {
|
|
const next = String(id || '').trim() || generateSessionId();
|
|
agentSessionId = next;
|
|
localStorage.setItem(agentSessionKey(), next);
|
|
return next;
|
|
}
|
|
let agentSessionId = '';
|
|
let currentUser = null;
|
|
let userLogoUrl = '/homeclaw_logo.png';
|
|
let brandName = 'HomeClaw';
|
|
setAgentSessionId(generateSessionId()); // always fresh session on page load
|
|
checkAuth(); // Check authentication on page load
|
|
initTTSToggle();
|
|
initMicAutosendToggle();
|
|
|
|
// ── Server log panel ──────────────────────────────────────────────────────────
|
|
let logScrollLocked = true;
|
|
let logLastTotalCount = 0; // tracks server's monotonic counter, not ring size
|
|
// 빈 Set = 전체 표시 / 값 있으면 해당 레벨만 표시
|
|
const logLevelFilter = new Set();
|
|
const logLevelCounts = { log: 0, warn: 0, error: 0 };
|
|
|
|
function toggleLogFilter(level) {
|
|
if (logLevelFilter.has(level)) {
|
|
logLevelFilter.delete(level);
|
|
} else {
|
|
logLevelFilter.add(level);
|
|
}
|
|
applyLogFilters();
|
|
}
|
|
|
|
function setAllLogFilters(on) {
|
|
logLevelFilter.clear();
|
|
if (!on) logLevelFilter.add('__none__');
|
|
applyLogFilters();
|
|
}
|
|
|
|
function applyLogFilters() {
|
|
const body = document.getElementById('sidebar-log-body');
|
|
if (body) {
|
|
const none = logLevelFilter.has('__none__');
|
|
const filtered = !none && logLevelFilter.size > 0;
|
|
body.classList.toggle('filter-active', filtered || none);
|
|
['log', 'warn', 'error'].forEach(lv => {
|
|
body.classList.toggle('hide-' + lv, none || (filtered && !logLevelFilter.has(lv)));
|
|
});
|
|
|
|
// 필터 결과 빈 경우 안내 메시지
|
|
let emptyEl = body.querySelector('.log-empty-hint');
|
|
const none2 = logLevelFilter.has('__none__');
|
|
const filtered2 = !none2 && logLevelFilter.size > 0;
|
|
const visibleCount = none2 ? 0 : filtered2
|
|
? [...logLevelFilter].reduce((s, lv) => s + (logLevelCounts[lv] || 0), 0)
|
|
: logLevelCounts.log + logLevelCounts.warn + logLevelCounts.error;
|
|
if (visibleCount === 0 && (none2 || filtered2)) {
|
|
if (!emptyEl) {
|
|
emptyEl = document.createElement('div');
|
|
emptyEl.className = 'log-empty-hint';
|
|
emptyEl.style.cssText = 'padding:12px;text-align:center;color:var(--muted);font-size:11px;';
|
|
body.appendChild(emptyEl);
|
|
}
|
|
emptyEl.textContent = none2 ? '필터: 없음' : `해당 레벨 메시지 없음 (${[...logLevelFilter].map(l=>l.toUpperCase()).join(', ')})`;
|
|
} else if (emptyEl) {
|
|
emptyEl.remove();
|
|
}
|
|
}
|
|
|
|
// 버튼: 활성 상태 + 카운트
|
|
document.querySelectorAll('.log-filter-btn[data-level]').forEach(btn => {
|
|
const lv = btn.dataset.level;
|
|
const none = logLevelFilter.has('__none__');
|
|
const filtered = !none && logLevelFilter.size > 0;
|
|
btn.classList.toggle('active', !none && (!filtered || logLevelFilter.has(lv)));
|
|
const cnt = logLevelCounts[lv] || 0;
|
|
btn.title = `${lv.toUpperCase()}: ${cnt}건`;
|
|
});
|
|
const allBtn = document.querySelector('.log-filter-all');
|
|
const noneBtn = document.querySelector('.log-filter-none');
|
|
if (allBtn) allBtn.classList.toggle('active', logLevelFilter.size === 0);
|
|
if (noneBtn) noneBtn.classList.toggle('active', logLevelFilter.has('__none__'));
|
|
}
|
|
|
|
let logSearchQuery = '';
|
|
|
|
function onLogSearch(q) {
|
|
logSearchQuery = q.trim().toLowerCase();
|
|
const clearBtn = document.getElementById('log-search-clear');
|
|
const countEl = document.getElementById('log-search-count');
|
|
if (clearBtn) clearBtn.style.display = logSearchQuery ? '' : 'none';
|
|
|
|
const body = document.getElementById('sidebar-log-body');
|
|
if (!body) return;
|
|
|
|
const lines = body.querySelectorAll('.log-line');
|
|
let matchCount = 0;
|
|
|
|
lines.forEach(line => {
|
|
const msgEl = line.querySelector('.log-msg');
|
|
const tsEl = line.querySelector('.log-ts');
|
|
if (!msgEl) return;
|
|
|
|
if (!logSearchQuery) {
|
|
// 검색 없음: 원래 텍스트 복원, no-match 제거
|
|
line.classList.remove('no-match');
|
|
if (msgEl._origText !== undefined) {
|
|
msgEl.textContent = msgEl._origText;
|
|
delete msgEl._origText;
|
|
}
|
|
return;
|
|
}
|
|
|
|
const orig = msgEl._origText !== undefined ? msgEl._origText : msgEl.textContent;
|
|
msgEl._origText = orig;
|
|
const tsText = tsEl ? tsEl.textContent : '';
|
|
const haystack = (orig + ' ' + tsText).toLowerCase();
|
|
const matches = haystack.includes(logSearchQuery);
|
|
|
|
line.classList.toggle('no-match', !matches);
|
|
if (matches) {
|
|
matchCount++;
|
|
// 하이라이트: 대소문자 무시 치환
|
|
const re = new RegExp(logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
|
|
msgEl.innerHTML = orig.replace(re, m => `<span class="log-hl">${m}</span>`);
|
|
} else {
|
|
msgEl.textContent = orig;
|
|
}
|
|
});
|
|
|
|
if (countEl) {
|
|
if (logSearchQuery) {
|
|
countEl.textContent = `${matchCount}건`;
|
|
countEl.style.display = '';
|
|
countEl.style.color = matchCount === 0 ? '#ef4444' : 'var(--muted)';
|
|
} else {
|
|
countEl.style.display = 'none';
|
|
}
|
|
}
|
|
}
|
|
|
|
function toggleLogPanel() {
|
|
const panel = document.getElementById('sidebar-log-panel');
|
|
if (!panel) return;
|
|
panel.classList.toggle('collapsed');
|
|
localStorage.setItem('logPanelCollapsed', panel.classList.contains('collapsed') ? '1' : '0');
|
|
}
|
|
|
|
function toggleLogScrollLock() {
|
|
logScrollLocked = !logScrollLocked;
|
|
const btn = document.getElementById('log-scroll-lock-btn');
|
|
if (btn) btn.style.opacity = logScrollLocked ? '1' : '0.4';
|
|
}
|
|
|
|
function clearLogPanel() {
|
|
const body = document.getElementById('sidebar-log-body');
|
|
if (body) body.innerHTML = '';
|
|
logLastTotalCount = 0;
|
|
logLevelCounts.log = 0; logLevelCounts.warn = 0; logLevelCounts.error = 0;
|
|
const inp = document.getElementById('log-search-input');
|
|
if (inp) inp.value = '';
|
|
logSearchQuery = '';
|
|
applyLogFilters();
|
|
onLogSearch('');
|
|
}
|
|
|
|
function renderLogEntries(entries) {
|
|
const body = document.getElementById('sidebar-log-body');
|
|
if (!body) return;
|
|
const frag = document.createDocumentFragment();
|
|
for (const e of entries) {
|
|
const lv = e.level === 'error' ? 'error' : e.level === 'warn' ? 'warn' : 'log';
|
|
logLevelCounts[lv] = (logLevelCounts[lv] || 0) + 1;
|
|
const lvCls = lv === 'error' ? 'error lv-error' : lv === 'warn' ? 'warn lv-warn' : 'lv-log';
|
|
const line = document.createElement('div');
|
|
line.className = 'log-line ' + lvCls;
|
|
const ts = document.createElement('span');
|
|
ts.className = 'log-ts';
|
|
ts.textContent = e.ts;
|
|
const msg = document.createElement('span');
|
|
msg.className = 'log-msg';
|
|
msg.textContent = e.msg;
|
|
line.appendChild(ts);
|
|
line.appendChild(msg);
|
|
frag.appendChild(line);
|
|
}
|
|
body.appendChild(frag);
|
|
if (logScrollLocked) body.scrollTop = body.scrollHeight;
|
|
applyLogFilters();
|
|
if (logSearchQuery) onLogSearch(logSearchQuery);
|
|
}
|
|
|
|
async function pollServerLogs() {
|
|
try {
|
|
const data = await api('/api/logs');
|
|
const entries = data?.entries || [];
|
|
const totalCount = data?.totalCount ?? entries.length;
|
|
if (totalCount <= logLastTotalCount) return;
|
|
|
|
const newCount = totalCount - logLastTotalCount;
|
|
// Slice new entries from the end of the ring (handles wrap-around correctly)
|
|
const newEntries = entries.slice(Math.max(0, entries.length - newCount));
|
|
renderLogEntries(newEntries);
|
|
logLastTotalCount = totalCount;
|
|
} catch {}
|
|
}
|
|
|
|
setInterval(pollServerLogs, 2000);
|
|
pollServerLogs();
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
// Chat state
|
|
let chatHistory = [];
|
|
let chatSessions = [];
|
|
let activeChatSessionId = null;
|
|
let _appCtxMax = 0;
|
|
|
|
// force=true re-queries even when a value is cached — the window belongs to the
|
|
// active model, so a cache-once made the gauge keep showing the previous model's
|
|
// max after switching provider/model.
|
|
async function _fetchAppCtxMax(force) {
|
|
if (_appCtxMax > 0 && !force) return;
|
|
try {
|
|
const r = await fetch('/api/model-context', { headers: authHeaders() });
|
|
if (!r.ok) return;
|
|
const d = await r.json();
|
|
// provisional = the server could not actually resolve the window (지서버 asleep, etc) and
|
|
// handed us its 8192 last resort. Show it, but leave _appCtxMax unset so the next call
|
|
// re-asks — caching a guess is what pinned the panel at 8K until a page reload.
|
|
if (d.provisional) { renderSessionsList(); return; }
|
|
if (d.contextWindow && d.contextWindow !== _appCtxMax) {
|
|
_appCtxMax = d.contextWindow;
|
|
renderSessionsList();
|
|
}
|
|
} catch (_) {}
|
|
}
|
|
let sessionsEditMode = false;
|
|
let isThinking = false;
|
|
let thinkingStartedAt = 0;
|
|
let thinkingTicker = null;
|
|
let streamingSessionId = null; // which session owns the active stream
|
|
let processLogEntries = [];
|
|
let currentTurnStartIndex = -1;
|
|
let lastAgentMode = '-';
|
|
let lastTurnKind = '-';
|
|
let settingsTab = 'system';
|
|
let liveTaskSteps = [];
|
|
let quickSearchRigor = 'verified';
|
|
let _searchSettingsLoaded = false; // true after openSettings() successfully loads search config
|
|
let _modelSettingsLoaded = false; // true after loadModelSettings() successfully populates model/provider DOM
|
|
let quickThinkingEffort = localStorage.getItem('homeclaw_quick_thinking_effort') || 'standard';
|
|
let queuedPrompts = [];
|
|
const MAX_QUEUED_PROMPTS = 8;
|
|
let currentPreflightStatus = '';
|
|
let currentProgressLines = [];
|
|
let processLogAutoFollow = true;
|
|
let rightColumnAutoFollow = true;
|
|
|
|
// Agent Execution Tracking
|
|
let agentExecutionMap = new Map(); // Map<agentId, { name, status, task, logs: [] }>
|
|
let agentIdCounter = 0;
|
|
const AGENT_STATUS = { ACTIVE: 'active', COMPLETED: 'completed', PAUSED: 'paused' };
|
|
let agentsConfigList = [];
|
|
let selectedAgentId = '';
|
|
let agentMdEditor = null;
|
|
// (skills cache moved to skillsCache in v2 skills management section)
|
|
let lastHeartbeat = {
|
|
state: 'idle',
|
|
level: '',
|
|
current_step: '-',
|
|
retry_count: 0,
|
|
format_violation_count: 0,
|
|
message: '',
|
|
};
|
|
let lastHeartbeatLogSignature = '';
|
|
|
|
|
|
|
|
// --- Heartbeat / Tasks System -----------------------------------------------
|
|
|
|
// ---- Sidebar tabs ----
|
|
function setSidebarTab(tab) {
|
|
sidebarTab = tab;
|
|
const toggle = (id, active) => document.getElementById(id)?.classList.toggle('active', active);
|
|
toggle('tab-jobs', tab === 'jobs');
|
|
toggle('tab-bgtasks', tab === 'bgtasks');
|
|
toggle('tab-skills', tab === 'skills');
|
|
toggle('tab-pptx', tab === 'pptx');
|
|
toggle('tab-schedule', tab === 'schedule');
|
|
document.getElementById('sidebar-jobs').style.display = (tab === 'jobs' || tab === 'bgtasks') ? 'flex' : 'none';
|
|
document.getElementById('sidebar-skills').style.display = tab === 'skills' ? 'flex' : 'none';
|
|
document.getElementById('sidebar-pptx').style.display = tab === 'pptx' ? 'flex' : 'none';
|
|
const schedEl = document.getElementById('sidebar-schedule');
|
|
if (schedEl) schedEl.style.display = tab === 'schedule' ? 'flex' : 'none';
|
|
// 메인 뷰 전환
|
|
if (tab === 'bgtasks') { setMode('bgtasks'); }
|
|
else if (currentMode === 'bgtasks') { setMode('chat'); }
|
|
if (tab === 'skills') { initSkillsUserSelector(); loadInstalledSkills(); }
|
|
if (tab === 'schedule') refreshSchedules();
|
|
}
|
|
|
|
// ---- Agent mode toggle ----
|
|
function updateAgentMode() {
|
|
useAgentMode = document.getElementById('agent-mode-toggle').checked;
|
|
document.getElementById('agent-mode-label').textContent = useAgentMode ? '에이전트' : '채팅';
|
|
document.getElementById('agent-mode-badge').classList.toggle('visible', useAgentMode);
|
|
document.getElementById('chat-input').placeholder = useAgentMode
|
|
? 'Ask agent to do something... (has access to tools)'
|
|
: 'Type a message... (Enter to send, Shift+Enter for newline)';
|
|
}
|
|
|
|
// ---- Chat ----
|
|
|
|
// ---- WebSocket ----
|
|
// Screen Wake Lock keeps this main WS connection alive on mobile. Without it, the OS
|
|
// screen-timeout (idle reading a reply, thinking before typing) turns the screen off, the
|
|
// tab gets backgrounded, and the browser throttles/suspends it — the socket misses the
|
|
// server's 30s pings, gets terminated after ~60s, and the client sees a "connection keeps
|
|
// dropping" pattern that never shows up on a desktop/always-on connection. Same root cause
|
|
// as the voice-call page's drop bug (fixed 2026-07-09 with the same pattern, see
|
|
// voice-call.js) — added here 2026-08-10 after the same symptom showed up on the main chat
|
|
// while used away from home wifi. A Wake Lock is auto-released whenever the tab loses
|
|
// visibility, so it has to be re-requested once the tab is visible again.
|
|
async function acquireWsWakeLock() {
|
|
if (!('wakeLock' in navigator)) return;
|
|
try {
|
|
wsWakeLock = await navigator.wakeLock.request('screen');
|
|
wsWakeLock.addEventListener('release', () => { wsWakeLock = null; });
|
|
} catch (e) {
|
|
console.warn('[app] wsWakeLock request failed:', e.message);
|
|
}
|
|
}
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (ws && ws.readyState === WebSocket.OPEN && wsWakeLock === null && document.visibilityState === 'visible') {
|
|
acquireWsWakeLock();
|
|
}
|
|
});
|
|
|
|
function connectWS() {
|
|
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
|
const token = getAuthToken();
|
|
const qs = token ? `?token=${encodeURIComponent(token)}` : '';
|
|
ws = new WebSocket(`${proto}://${API.replace(/^https?:\/\//, '')}/ws${qs}`);
|
|
ws.onopen = () => { acquireWsWakeLock(); };
|
|
ws.onmessage = (e) => {
|
|
const msg = JSON.parse(e.data);
|
|
if (msg.type === 'jobs_update') {
|
|
allJobs = msg.jobs;
|
|
updateStats([]);
|
|
if (selectedJobId) refreshJobDetail(selectedJobId);
|
|
}
|
|
if (msg.type === 'job_created') {
|
|
log(`Job created: ${msg.jobId}`, 'info');
|
|
}
|
|
if (msg.type === 'boot_greeting') {
|
|
// Show boot greeting in current session regardless of existing history
|
|
const bootSess = chatSessions.find(s => s.id === activeChatSessionId);
|
|
if (bootSess) {
|
|
if (!bootSess.history) bootSess.history = [];
|
|
bootSess.history.push({ role: 'assistant', content: msg.text });
|
|
bootSess.updatedAt = Date.now();
|
|
saveChatSessions();
|
|
syncActiveChat();
|
|
renderChatMessages();
|
|
}
|
|
}
|
|
// -- Cron/Heartbeat task events --
|
|
if (msg.type === 'tasks_update') {
|
|
hbJobs = msg.jobs || [];
|
|
if (msg.config) hbConfig = msg.config;
|
|
if (currentMode === 'heartbeat') renderHeartbeatPage();
|
|
}
|
|
if (msg.type === 'task_running') {
|
|
const job = hbJobs.find(j => j.id === msg.jobId);
|
|
if (job) job.status = 'running';
|
|
if (currentMode === 'heartbeat') renderHeartbeatPage();
|
|
addProcessEntry('info', `Task running: ${msg.jobName}`);
|
|
}
|
|
if (msg.type === 'task_done') {
|
|
hbJobs = msg.jobs || hbJobs;
|
|
if (msg.config) hbConfig = msg.config;
|
|
if (currentMode === 'heartbeat') renderHeartbeatPage();
|
|
if (msg.automatedSession && !msg.isOk) {
|
|
// Add the automated session to chatSessions so it appears in the sidebar
|
|
const as = msg.automatedSession;
|
|
const existingIdx = chatSessions.findIndex(s => s.id === as.id);
|
|
const newSession = {
|
|
id: as.id, title: as.title,
|
|
history: as.history.map(m => ({ role: m.role === 'ai' ? 'assistant' : m.role, content: m.content })),
|
|
processLog: [], createdAt: as.createdAt, updatedAt: Date.now(),
|
|
automated: true, jobName: as.jobName, unread: true,
|
|
};
|
|
if (existingIdx === -1) chatSessions.push(newSession);
|
|
else chatSessions[existingIdx] = { ...chatSessions[existingIdx], ...newSession };
|
|
saveChatSessions();
|
|
renderSessionsList();
|
|
bgtToast('\uD83D\uDD50 Scheduled task done', `"${msg.jobName}" — results in sidebar`);
|
|
addProcessEntry('info', `Task "${msg.jobName}" completed — check sidebar for results`);
|
|
} else if (msg.isOk) {
|
|
addProcessEntry('info', `Task "${msg.jobName}" — OK (nothing to report)`);
|
|
}
|
|
}
|
|
// Cron job spawned a background task — switch to tasks view if currently watching
|
|
if (msg.type === 'cron_task_spawned') {
|
|
bgtToast('\uD83D\uDD50 Scheduled job running', `"${msg.jobName}" started as background task`);
|
|
if (currentMode === 'bgtasks') refreshBgTasks();
|
|
}
|
|
if (msg.type === 'task_sse') {
|
|
// Live progress from a running task — could update the NOW card
|
|
if (currentMode === 'heartbeat' && msg.event === 'tool_result') {
|
|
const card = document.querySelector(`[data-job-id="${msg.jobId}"] .hb-card-meta`);
|
|
if (card) card.innerHTML = `<span style="color:var(--brand)">Working: ${escHtml((msg.data?.action || '').slice(0,40))}...</span>`;
|
|
}
|
|
}
|
|
// -- Background Task (Kanban) events --
|
|
if (msg.type === 'task_running' || msg.type === 'task_complete' || msg.type === 'task_paused' ||
|
|
msg.type === 'task_failed' || msg.type === 'task_needs_assistance' || msg.type === 'task_step_done' || msg.type === 'task_tool_call' ||
|
|
msg.type === 'task_heartbeat_tick' || msg.type === 'task_heartbeat_resumed') {
|
|
// Live-refresh the kanban board if visible
|
|
if (currentMode === 'bgtasks') refreshBgTasks();
|
|
// If panel is open for this task, refresh it
|
|
if (bgtOpenTaskId && (msg.taskId === bgtOpenTaskId)) {
|
|
bgtRefreshOpenPanel();
|
|
}
|
|
// Toast notification for completions and errors
|
|
if (msg.type === 'task_complete') {
|
|
bgtToast(`\u2713 Task complete`, msg.summary ? msg.summary.slice(0,120) : '');
|
|
// If this task has a cron session ID (starts with cron_), create/update a sidebar session
|
|
// so the results are immediately visible without a page refresh.
|
|
if (msg.taskId) {
|
|
(async () => {
|
|
try {
|
|
const data = await fetch(`/api/bg-tasks/${msg.taskId}`, {
|
|
headers: authHeaders()
|
|
}).then(r => r.json());
|
|
const task = data?.task || data;
|
|
if (task && task.sessionId && task.sessionId.startsWith('cron_')) {
|
|
const journal = task.journal || [];
|
|
const summaryEntry = journal.filter(e => e.type === 'summary' || e.type === 'complete').pop();
|
|
const summaryText = msg.summary || (summaryEntry?.content) || '(Task complete — open Tasks panel for details)';
|
|
const titleText = `\uD83D\uDD50 ${task.title || 'Scheduled Task'} \u2014 ${new Date().toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}`;
|
|
const sessionId = `auto_${task.id}_${Date.now()}`;
|
|
const existingIdx = chatSessions.findIndex(s => s.id === task.sessionId || (s.jobName && s.automated && s.title === titleText));
|
|
const newSession = {
|
|
id: sessionId, title: titleText,
|
|
history: [
|
|
{ role: 'user', content: `[Scheduled Task: ${task.title}]\n\n${task.prompt || ''}` },
|
|
{ role: 'assistant', content: summaryText },
|
|
],
|
|
processLog: [], createdAt: Date.now(), updatedAt: Date.now(),
|
|
automated: true, jobName: task.title, unread: true,
|
|
};
|
|
if (existingIdx === -1) chatSessions.push(newSession);
|
|
saveChatSessions();
|
|
renderSessionsList();
|
|
}
|
|
} catch {}
|
|
})();
|
|
}
|
|
} else if (msg.type === 'task_failed') {
|
|
bgtToast(`\u2715 Task failed`, msg.error ? msg.error.slice(0,120) : '');
|
|
} else if (msg.type === 'task_needs_assistance') {
|
|
bgtToast(`Task paused`, msg.reason ? String(msg.reason).slice(0, 120) : 'Needs assistance');
|
|
}
|
|
}
|
|
// Panel-only refresh (frequent tool_call updates — only refresh open panel, not full kanban)
|
|
if (msg.type === 'task_panel_update') {
|
|
if (bgtOpenTaskId && msg.taskId === bgtOpenTaskId) {
|
|
bgtRefreshOpenPanel();
|
|
}
|
|
}
|
|
// Notification from task runner (status push to channel)
|
|
if (msg.type === 'task_notification' && msg.sessionId) {
|
|
// Try to add a status message to the originating chat session
|
|
const sess = chatSessions.find(s => s.id === msg.sessionId);
|
|
if (sess) {
|
|
sess.history = sess.history || [];
|
|
sess.history.push({ role: 'assistant', content: msg.message || '' });
|
|
saveChatSessions();
|
|
if (currentSessionId === msg.sessionId) renderMessages();
|
|
}
|
|
}
|
|
// ---- Agent Execution Events ----
|
|
if (msg.type === 'agent_spawned') {
|
|
const agentId = spawnAgentExecution(msg.name || 'Subagent', msg.task || '', msg.isSubagent);
|
|
// Store mapping for WebSocket message routing
|
|
if (msg.serverAgentId) {
|
|
if (!window.agentIdMap) window.agentIdMap = {};
|
|
window.agentIdMap[msg.serverAgentId] = agentId;
|
|
}
|
|
}
|
|
if (msg.type === 'agent_log') {
|
|
const agentId = window.agentIdMap?.[msg.serverAgentId] || msg.agentId;
|
|
if (agentId) addAgentLog(agentId, msg.logType || 'info', msg.content);
|
|
}
|
|
if (msg.type === 'agent_completed') {
|
|
const agentId = window.agentIdMap?.[msg.serverAgentId] || msg.agentId;
|
|
if (agentId) completeAgentExecution(agentId);
|
|
}
|
|
if (msg.type === 'agent_paused') {
|
|
const agentId = window.agentIdMap?.[msg.serverAgentId] || msg.agentId;
|
|
if (agentId) pauseAgentExecution(agentId, msg.reason);
|
|
}
|
|
};
|
|
ws.onclose = () => {
|
|
try { wsWakeLock && wsWakeLock.release(); } catch {}
|
|
wsWakeLock = null;
|
|
setTimeout(connectWS, 2000);
|
|
};
|
|
ws.onerror = () => ws.close();
|
|
}
|
|
|
|
// ---- API ----
|
|
async function api(path, opts = {}) {
|
|
const { headers: optsHeaders, credentials: _discard, ...restOpts } = opts;
|
|
const headers = authHeaders({ 'Content-Type': 'application/json', ...optsHeaders });
|
|
const r = await fetch(API + path, { headers, ...restOpts });
|
|
if (r.status === 401) { setAuthToken(''); window.location.href='/html/login.html'; throw new Error('Authentication required'); }
|
|
const ct = String(r.headers.get('content-type') || '').toLowerCase();
|
|
const bodyText = await r.text();
|
|
|
|
if (!ct.includes('application/json')) {
|
|
const preview = bodyText.slice(0, 120).replace(/\s+/g, ' ');
|
|
throw new Error(`Expected JSON from ${path}, got ${ct || 'unknown'} (HTTP ${r.status}) :: ${preview}`);
|
|
}
|
|
|
|
let data = null;
|
|
try {
|
|
data = bodyText ? JSON.parse(bodyText) : null;
|
|
} catch {
|
|
const preview = bodyText.slice(0, 120).replace(/\s+/g, ' ');
|
|
throw new Error(`Invalid JSON from ${path} (HTTP ${r.status}) :: ${preview}`);
|
|
}
|
|
|
|
if (!r.ok) {
|
|
const msg = (data && (data.error || data.message)) ? String(data.error || data.message) : `HTTP ${r.status}`;
|
|
throw new Error(msg);
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
|
|
// --- Per-User Telegram Bot ---------------------------------------------------
|
|
|
|
|
|
function escapeHtml(s) {
|
|
return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));
|
|
}
|
|
|
|
|
|
// --- Context Viewer Tab -------------------------------------------------------
|
|
|
|
let cvAutoRefreshTimer = null;
|
|
|
|
async function loadContextViewerTab() {
|
|
const listEl = document.getElementById('cv-sessions-list');
|
|
const warnEl = document.getElementById('cv-warn-banner');
|
|
if (!listEl) return;
|
|
listEl.innerHTML = '<div style="color:var(--muted);font-size:13px;text-align:center;padding:20px">로딩 중...</div>';
|
|
if (warnEl) warnEl.style.display = 'none';
|
|
|
|
try {
|
|
const data = await api('/api/admin/context-viewer');
|
|
if (!data || !data.sessions) {
|
|
listEl.innerHTML = '<div style="font-size:12px;color:var(--err)">권한이 없거나 데이터를 불러올 수 없습니다.</div>';
|
|
return;
|
|
}
|
|
const sessions = data.sessions;
|
|
if (sessions.length === 0) {
|
|
listEl.innerHTML = '<div style="color:var(--muted);font-size:13px;text-align:center;padding:20px">세션이 없습니다.</div>';
|
|
return;
|
|
}
|
|
|
|
// Token warning banner
|
|
const warnSessions = sessions.filter(s => s.usagePct >= 70);
|
|
if (warnEl && warnSessions.length > 0) {
|
|
warnEl.style.display = 'block';
|
|
warnEl.innerHTML = '⚠️ 토큰 경고: ' + warnSessions.map(s => {
|
|
const color = s.usagePct >= 80 ? '#dc2626' : '#d97706';
|
|
return `<strong style="color:${color}">${s.username}</strong> (${s.id.slice(0,8)}…) ${s.usagePct}%`;
|
|
}).join(' | ');
|
|
}
|
|
|
|
listEl.innerHTML = sessions.map(s => {
|
|
const pct = s.usagePct;
|
|
const barColor = pct >= 80 ? 'var(--err)' : pct >= 50 ? 'var(--warn)' : 'var(--ok)';
|
|
const lastActive = s.lastActiveAt ? new Date(s.lastActiveAt).toLocaleString() : '-';
|
|
const onlineDot = s.online
|
|
? '<span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--ok);margin-right:4px"></span>'
|
|
: '<span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--line-strong);margin-right:4px"></span>';
|
|
return `
|
|
<div id="cv-card-${escHtml(s.id)}" style="border:1px solid var(--line);border-radius:12px;padding:12px;background:var(--panel)">
|
|
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
|
|
<div style="display:flex;align-items:center;gap:8px">
|
|
${onlineDot}
|
|
<strong style="font-size:13px">${escHtml(s.username)}</strong>
|
|
<span style="font-family:'IBM Plex Mono',monospace;font-size:10px;color:var(--muted)">${s.id.slice(0,12)}…</span>
|
|
</div>
|
|
<div style="display:flex;align-items:center;gap:8px">
|
|
<span style="font-size:11px;color:var(--muted)">${lastActive}</span>
|
|
${pct >= 70 ? `<span style="font-size:11px;font-weight:700;color:${barColor};padding:2px 7px;border-radius:6px;background:${pct>=90?'#fee2e2':'#fff7ed'}">${pct}%</span>` : ''}
|
|
<button onclick="cvDeleteSession('${escHtml(s.username)}','${escHtml(s.id)}')" title="세션 삭제" style="background:none;border:1px solid var(--line);border-radius:6px;padding:2px 7px;font-size:11px;color:var(--muted);cursor:pointer" onmouseover="this.style.borderColor='var(--err)';this.style.color='var(--err)'" onmouseout="this.style.borderColor='var(--line)';this.style.color='var(--muted)'">✕</button>
|
|
</div>
|
|
</div>
|
|
<div style="display:flex;align-items:center;gap:6px;margin-bottom:8px">
|
|
<div style="flex:1;height:6px;border-radius:3px;background:var(--line);overflow:hidden">
|
|
<div style="height:100%;width:${Math.min(pct,100)}%;background:${barColor};border-radius:3px;transition:width .3s"></div>
|
|
</div>
|
|
<span style="font-size:11px;color:var(--muted);white-space:nowrap">${s.contextTokenEstimate.toLocaleString()} / ${s.numCtx.toLocaleString()} tok</span>
|
|
</div>
|
|
<div style="display:flex;gap:8px;font-size:11px;color:var(--muted);margin-bottom:6px">
|
|
<span>메시지 ${s.historyCount}개</span>
|
|
</div>
|
|
${s.lastUserMessage ? `<div style="font-size:11px;padding:6px 8px;background:var(--panel-2);border-radius:8px;margin-bottom:4px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%"><span style="color:var(--brand);font-weight:600">사용자: </span>${escHtml(s.lastUserMessage)}</div>` : ''}
|
|
${s.lastAssistantMessage ? `<div style="font-size:11px;padding:6px 8px;background:var(--panel-2);border-radius:8px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%"><span style="color:var(--ok);font-weight:600">AI: </span>${escHtml(s.lastAssistantMessage)}</div>` : ''}
|
|
</div>`;
|
|
}).join('');
|
|
} catch (e) {
|
|
listEl.innerHTML = `<div style="font-size:12px;color:var(--err)">오류: ${e.message || '알 수 없는 오류'}</div>`;
|
|
}
|
|
}
|
|
|
|
async function loadBannedIpsTab() {
|
|
const listEl = document.getElementById('cv-banned-ips-list');
|
|
const statEl = document.getElementById('cv-banned-ips-stat');
|
|
if (!listEl) return;
|
|
listEl.innerHTML = '<div style="color:var(--muted);font-size:13px;text-align:center;padding:20px">로딩 중...</div>';
|
|
if (statEl) statEl.textContent = '';
|
|
|
|
try {
|
|
const data = await api('/api/admin/banned-ips');
|
|
if (!data || !data.banned) {
|
|
listEl.innerHTML = '<div style="font-size:12px;color:var(--err)">권한이 없거나 데이터를 불러올 수 없습니다.</div>';
|
|
return;
|
|
}
|
|
const banned = data.banned;
|
|
if (statEl) statEl.textContent = `현재 차단 ${banned.length}건 · 누적 밴 ${data.totalBans.toLocaleString()}건`;
|
|
if (banned.length === 0) {
|
|
listEl.innerHTML = '<div style="color:var(--muted);font-size:13px;text-align:center;padding:20px">현재 차단된 IP가 없습니다.</div>';
|
|
return;
|
|
}
|
|
listEl.innerHTML = banned.map(b => `
|
|
<div style="display:flex;align-items:center;justify-content:space-between;border:1px solid var(--line);border-radius:8px;padding:6px 10px;background:var(--panel)">
|
|
<div style="display:flex;align-items:center;gap:8px">
|
|
<span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--err)"></span>
|
|
<span style="font-family:'IBM Plex Mono',monospace;font-size:12px">${escHtml(b.ip)}</span>
|
|
<span style="font-size:10px;color:var(--muted);border:1px solid var(--line);border-radius:5px;padding:1px 5px">${escHtml(b.jail)}</span>
|
|
</div>
|
|
<span style="font-size:11px;color:var(--muted)">${escHtml(b.bannedAt)}</span>
|
|
</div>`).join('');
|
|
} catch (e) {
|
|
listEl.innerHTML = `<div style="font-size:12px;color:var(--err)">오류: ${e.message || '알 수 없는 오류'}</div>`;
|
|
}
|
|
}
|
|
|
|
async function cvDeleteSession(username, sessionId) {
|
|
try {
|
|
const res = await fetch(`/api/admin/sessions/${encodeURIComponent(username)}/${encodeURIComponent(sessionId)}`, {
|
|
method: 'DELETE',
|
|
headers: authHeaders(),
|
|
});
|
|
if (!res.ok) throw new Error((await res.json()).error || res.statusText);
|
|
const card = document.getElementById('cv-card-' + sessionId);
|
|
if (card) card.remove();
|
|
} catch (e) {
|
|
alert('삭제 실패: ' + (e.message || e));
|
|
}
|
|
}
|
|
|
|
// --- PPT Template & Skin Tab ---------------------------------------------------
|
|
|
|
|
|
|
|
// --- Channels Settings Functions ---------------------------------------
|
|
|
|
// ─── Email Account Management (Channel Settings) ─────────────────────────
|
|
|
|
// ─── Heartbeat Notify Toggle ──────────────────────────────────────────────
|
|
|
|
async function saveSettings() {
|
|
const workspace_path = document.getElementById('settings-workspace-path').value.trim();
|
|
const allowed_paths = document.getElementById('settings-allowed-paths').value.split('\n').map(s => s.trim()).filter(Boolean);
|
|
const blocked_paths = document.getElementById('settings-blocked-paths').value.split('\n').map(s => s.trim()).filter(Boolean);
|
|
// If search settings were never loaded from the server (API failed or race with async load),
|
|
// fetch current values now so we don't overwrite searxng_url / preferred_provider with HTML defaults.
|
|
if (!_searchSettingsLoaded) {
|
|
try {
|
|
const s = await api('/api/settings/search');
|
|
// 서버 내부 이름 'ollama_cloud'는 화면 선택지 'ollama'와 같은 것이다 — 매핑 안 하면 select가 빈 값이 돼 저장 때 덮어쓴다.
|
|
document.getElementById('settings-provider').value = s.preferred_provider === 'ollama_cloud' ? 'ollama' : (s.preferred_provider || '');
|
|
document.getElementById('settings-search-rigor').value = s.search_rigor || 'verified';
|
|
if (document.getElementById('settings-search-searxng-url'))
|
|
document.getElementById('settings-search-searxng-url').value = s.searxng_url || '';
|
|
if (document.getElementById('settings-search-ollama-model'))
|
|
document.getElementById('settings-search-ollama-model').value = s.ollama_model || '';
|
|
_searchSettingsLoaded = true;
|
|
} catch {}
|
|
}
|
|
const payload = {
|
|
preferred_provider: document.getElementById('settings-provider').value,
|
|
search_rigor: document.getElementById('settings-search-rigor').value,
|
|
tavily_api_key: document.getElementById('cred-tavily-key')?.value.trim() || '',
|
|
google_api_key: document.getElementById('cred-google-key')?.value.trim() || '',
|
|
google_cx: document.getElementById('cred-google-cx')?.value.trim() || '',
|
|
brave_api_key: document.getElementById('cred-brave-key')?.value.trim() || '',
|
|
ollama_model: document.getElementById('settings-search-ollama-model')?.value.trim() || '',
|
|
searxng_url: document.getElementById('settings-search-searxng-url')?.value.trim() || '',
|
|
};
|
|
const policyPayload = {
|
|
force_web_for_fresh: document.getElementById('settings-force-web-fresh').checked,
|
|
memory_fallback_on_search_failure: document.getElementById('settings-memory-fallback').checked,
|
|
auto_store_web_facts: document.getElementById('settings-auto-store-web-facts').checked,
|
|
natural_language_tool_router: document.getElementById('settings-nl-tool-router').checked,
|
|
retrieval_mode: document.getElementById('settings-retrieval-mode').value,
|
|
};
|
|
// If model/provider settings were never loaded (models tab not opened), fetch and populate DOM now
|
|
// so buildProviderPayload() doesn't send HTML defaults (provider='ollama', empty model, etc.)
|
|
if (!_modelSettingsLoaded) {
|
|
try {
|
|
const data = await api('/api/settings/provider');
|
|
const llm = data?.llm || {};
|
|
const prov = llm.provider || '';
|
|
const pc = llm.providers || {};
|
|
const v = (id, val) => { const el = document.getElementById(id); if (el && val) el.value = val; };
|
|
if (prov) { const el = document.getElementById('settings-llm-provider'); if (el) el.value = prov; }
|
|
v('settings-ollama-endpoint', pc.ollama?.endpoint);
|
|
v('settings-ollamalocal-endpoint', pc.ollama_local?.endpoint);
|
|
// 지서버's model field is a <select> filled only on an explicit refresh (auto-refreshing it
|
|
// would fire a WOL packet just for picking an entry), so the saved model has to be seeded as
|
|
// a real option — plain .value on an unpopulated select silently does nothing, and saving
|
|
// from that state would blank the configured model.
|
|
//
|
|
// Guarded rather than called directly: seedModelSelect lives in settings-provider.js, and a
|
|
// browser holding a cached copy of that file alongside a fresh app.js would otherwise throw
|
|
// a ReferenceError here and take the whole settings load down with it.
|
|
if (typeof seedModelSelect === 'function') seedModelSelect('settings-ollamalocal-model', pc.ollama_local?.model);
|
|
else v('settings-ollamalocal-model', pc.ollama_local?.model);
|
|
v('settings-llamacpp-endpoint', pc.llama_cpp?.endpoint);
|
|
v('settings-llamacpp-model', pc.llama_cpp?.model);
|
|
v('settings-lmstudio-endpoint', pc.lm_studio?.endpoint);
|
|
v('settings-lmstudio-model', pc.lm_studio?.model);
|
|
{ const cb = document.getElementById('settings-lmstudio-disable-thinking'); if (cb) cb.checked = pc.lm_studio?.disable_thinking !== false; }
|
|
const savedPrimary = pc[prov]?.model || data?.models_primary || '';
|
|
if (savedPrimary) { const el = document.getElementById('settings-primary-model'); if (el) el.value = savedPrimary; }
|
|
_modelSettingsLoaded = true;
|
|
} catch {}
|
|
}
|
|
// Capture primaryModel AFTER _modelSettingsLoaded guard so the DOM value is correct
|
|
// even when the models tab was never opened in this settings session.
|
|
const primaryModel = (document.getElementById('settings-primary-model') || {}).value || '';
|
|
const modelPayload = {
|
|
ollama_endpoint: (document.getElementById('settings-ollama-endpoint') || {}).value || 'http://localhost:11434',
|
|
primary: primaryModel,
|
|
roles: {
|
|
manager: primaryModel,
|
|
executor: primaryModel,
|
|
verifier: primaryModel,
|
|
}
|
|
};
|
|
const providerPayload = buildProviderPayload();
|
|
// Keep llm.providers.ollama.model in sync with the primary model
|
|
// so getModelForRole() never falls back to the hardcoded 'qwen3:4b'.
|
|
if (providerPayload.providers && providerPayload.providers.ollama) {
|
|
providerPayload.providers.ollama.model = primaryModel || providerPayload.providers.ollama.model || '';
|
|
}
|
|
try {
|
|
await api('/api/settings/paths', { method: 'POST', body: JSON.stringify({ workspace_path, allowed_paths, blocked_paths }) });
|
|
await api('/api/settings/search', { method: 'POST', body: JSON.stringify(payload) });
|
|
await api('/api/settings/agent', { method: 'POST', body: JSON.stringify(policyPayload) });
|
|
await api('/api/settings/model', { method: 'POST', body: JSON.stringify(modelPayload) });
|
|
await api('/api/settings/provider', { method: 'POST', body: JSON.stringify({ llm: providerPayload }) });
|
|
const owKey = document.getElementById('cred-ow-key')?.value?.trim();
|
|
if (owKey && owKey !== '••••••••') {
|
|
await api('/api/settings/openweather', { method: 'POST', body: JSON.stringify({ api_key: owKey }) });
|
|
}
|
|
await loadSearchSettingsSummary();
|
|
// Model/provider may have just changed — the context gauge's max belongs to
|
|
// the active model, so re-resolve it instead of keeping the previous value.
|
|
_fetchAppCtxMax(true);
|
|
quickSearchRigor = payload.search_rigor || quickSearchRigor;
|
|
updateQuickModeUI();
|
|
addProcessEntry('final', '설정이 저장되었습니다.');
|
|
closeSettings();
|
|
} catch (err) {
|
|
addProcessEntry('error', `설정 저장 실패: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
// Approve a memory suggestion shown in the process log
|
|
async function confirmMemory(index) {
|
|
const entry = processLogEntries[index];
|
|
if (!entry || entry.type !== 'memory') return;
|
|
const suggestion = entry.extra || {};
|
|
try {
|
|
addProcessEntry('info', 'Saving memory...');
|
|
const res = await api('/api/memory/confirm', { method: 'POST', body: JSON.stringify(suggestion) });
|
|
if (res && res.ok === false) {
|
|
addProcessEntry('error', `Memory save failed: ${res.error || JSON.stringify(res)}`);
|
|
return;
|
|
}
|
|
processLogEntries[index].type = 'result';
|
|
processLogEntries[index].content = `Saved memory: ${String(entry.content).slice(0,200)}`;
|
|
renderProcessLog();
|
|
addProcessEntry('final', 'Memory persisted.');
|
|
} catch (err) {
|
|
addProcessEntry('error', `Failed to save memory: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
function rejectMemory(index) {
|
|
const entry = processLogEntries[index];
|
|
if (!entry || entry.type !== 'memory') return;
|
|
processLogEntries[index].type = 'warn';
|
|
processLogEntries[index].content = 'Memory suggestion rejected.';
|
|
renderProcessLog();
|
|
addProcessEntry('info', 'Memory suggestion rejected by user.');
|
|
}
|
|
|
|
// ---- Run mission ----
|
|
async function runMission() {
|
|
const input = document.getElementById('mission-input');
|
|
const btn = document.getElementById('run-btn');
|
|
const mission = input.value.trim();
|
|
if (!mission) return;
|
|
|
|
btn.disabled = true;
|
|
btn.innerHTML = '<span class="spinner"></span> Starting...';
|
|
|
|
try {
|
|
const res = await api('/api/jobs', { method: 'POST', body: JSON.stringify({ mission }) });
|
|
if (res.error) {
|
|
log(`Error: ${res.error}`, 'error');
|
|
} else {
|
|
log(`Mission started ? Job ${res.jobId.slice(0, 8)}...`, 'success');
|
|
input.value = '';
|
|
setTimeout(() => selectJob(res.jobId), 500);
|
|
}
|
|
} catch (err) {
|
|
log(`Failed: ${err.message}`, 'error');
|
|
}
|
|
|
|
btn.disabled = false;
|
|
btn.innerHTML = '? Run';
|
|
}
|
|
|
|
// ---- Sessions list ----
|
|
function renderSessionsList() {
|
|
const el = document.getElementById('jobs-list');
|
|
if (!chatSessions || chatSessions.length === 0) {
|
|
el.innerHTML = '<div class="empty-state">No chats yet.<br>Start a new conversation.</div>';
|
|
return;
|
|
}
|
|
const sorted = [...chatSessions].sort((a, b) => (b.updatedAt || b.createdAt) - (a.updatedAt || a.createdAt));
|
|
el.innerHTML = sorted.map(s => `
|
|
<div class="job-item ${s.id === activeChatSessionId ? 'active' : ''}${s.unread ? ' unread' : ''}" onclick="openSession('${s.id}')">
|
|
<div style="display:flex;align-items:center;justify-content:space-between;gap:8px">
|
|
<div class="job-item-title" style="flex:1">${s.unread ? '🔵 ' : ''}${escHtml(s.title || 'New chat')}</div>
|
|
${sessionsEditMode ? `<button class="sidebar-action" style="padding:3px 8px;font-size:10px" onclick="deleteChatSession('${s.id}', event)">삭제</button>` : ''}
|
|
</div>
|
|
<div style="display:flex;align-items:center;gap:6px;margin-top:4px">
|
|
${s.automated ? '<span class="session-auto-badge">Auto</span>' : ''}
|
|
<span class="badge badge-queued">${(s.history || []).length} msgs</span>
|
|
${(() => { const fmtTok = n => n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1000?`${Math.round(n/1000)}k`:`${n}`; const real = Number(s.contextTokens||0); const ct = real || (Number(s.toolOverheadTokens||0) + Math.round((s.history||[]).reduce((a,m)=>a+(m.content||'').length,0)/4)); const mx = _appCtxMax; if (!ct) return ''; if (mx > 0) { const pct = Math.min(100, Math.round(ct/mx*100)); const col = pct>=80?'var(--err)':pct>=50?'var(--warn)':'var(--ok)'; const lamp = pct>=80?'🔴':pct>=50?'🟡':'🟢'; return `<span style="font-size:10px;color:${col}" title="컨텍스트 ${pct}% (초록 50% 미만 · 노랑 50~80% · 빨강 80% 이상)">${lamp} ${real?'':'~'}${fmtTok(ct)}/${fmtTok(mx)}</span>`; } return `<span style="font-size:10px;color:var(--muted)">${real?'':'~'}${fmtTok(ct)} tok</span>`; })()}
|
|
<span style="color:var(--muted);font-size:10px">${timeAgo(s.updatedAt || s.createdAt)}</span>
|
|
</div>
|
|
</div>
|
|
`).join('');
|
|
}
|
|
|
|
// ---- Select job ----
|
|
async function selectJob(jobId) {
|
|
selectedJobId = jobId;
|
|
setMode('chat');
|
|
renderJobsList(allJobs);
|
|
await refreshJobDetail(jobId);
|
|
clearInterval(pollInterval);
|
|
pollInterval = setInterval(async () => {
|
|
const job = allJobs.find(j => j.id === jobId);
|
|
if (job && ['planning', 'executing', 'verifying'].includes(job.status)) {
|
|
await refreshJobDetail(jobId);
|
|
} else {
|
|
clearInterval(pollInterval);
|
|
}
|
|
}, 2000);
|
|
}
|
|
|
|
async function refreshJobDetail(jobId) {
|
|
try {
|
|
const data = await api(`/api/jobs/${jobId}`);
|
|
renderJobDetail(data);
|
|
} catch {}
|
|
}
|
|
|
|
function renderJobDetail(data) {
|
|
const { job, tasks, artifacts, state } = data;
|
|
const content = document.getElementById('main-content');
|
|
const isRunning = ['planning','executing','verifying'].includes(job.status);
|
|
|
|
content.innerHTML = `
|
|
<div class="job-detail-title">${escHtml(job.title)}</div>
|
|
<div class="job-detail-meta">
|
|
<span class="badge badge-${job.status}">${isRunning ? '<span class="spinner"></span>' : ''}${job.status}</span>
|
|
<span>ID: ${job.id.slice(0, 12)}...</span>
|
|
<span>${timeAgo(job.created_at)}</span>
|
|
</div>
|
|
|
|
${state ? `
|
|
<div class="section-title">Mission</div>
|
|
<div style="color:var(--muted);font-size:12px;line-height:1.7;background:var(--bg2);border:1px solid var(--border);border-radius:6px;padding:12px;margin-bottom:16px">
|
|
${escHtml(state.mission)}
|
|
</div>` : ''}
|
|
|
|
${tasks && tasks.length > 0 ? `
|
|
<div class="section-title">Tasks (${tasks.length})</div>
|
|
${tasks.map(t => `
|
|
<div class="task-card">
|
|
<div class="task-card-header">
|
|
<span class="task-card-title">${escHtml(t.title)}</span>
|
|
<span class="badge badge-${t.status}">${t.status}</span>
|
|
</div>
|
|
<div class="task-card-desc">${escHtml(t.description || '')}</div>
|
|
${t.acceptance_criteria && t.acceptance_criteria.length > 0 ? `
|
|
<div class="task-criteria">
|
|
${t.acceptance_criteria.map(c => `<div class="task-criteria-item">${escHtml(c)}</div>`).join('')}
|
|
</div>` : ''}
|
|
</div>
|
|
`).join('')}` : `
|
|
<div class="section-title">작업</div>
|
|
<div style="color:var(--muted);font-size:12px;padding:20px 0">
|
|
${isRunning ? '<span class="spinner pulsing"></span> Planning tasks...' : 'No tasks'}
|
|
</div>`}
|
|
|
|
${artifacts && artifacts.length > 0 ? `
|
|
<div class="section-title" style="margin-top:16px">Artifacts (${artifacts.length})</div>
|
|
${artifacts.map(a => `
|
|
<div class="task-card">
|
|
<div class="task-card-header">
|
|
<span class="task-card-title">${escHtml(a.path || a.type)}</span>
|
|
<span class="badge badge-completed">${a.type}</span>
|
|
</div>
|
|
${a.content ? `<div class="task-card-desc" style="margin-top:6px">${escHtml(a.content.slice(0, 200))}${a.content.length > 200 ? '...' : ''}</div>` : ''}
|
|
</div>
|
|
`).join('')}` : ''}
|
|
|
|
<div id="log-panel">${logLines.map(l => `<div class="log-line ${l.type}">${l.text}</div>`).join('')}</div>
|
|
`;
|
|
|
|
const lp = document.getElementById('log-panel');
|
|
if (lp) lp.scrollTop = lp.scrollHeight;
|
|
}
|
|
|
|
// ---- Stats ----
|
|
function updateStats(jobs) {
|
|
const totalEl = document.getElementById('r-total');
|
|
const runningEl = document.getElementById('r-running');
|
|
const modeEl = document.getElementById('r-completed');
|
|
if (totalEl) totalEl.textContent = String(chatSessions.length);
|
|
if (runningEl) runningEl.textContent = activeChatSessionId ? '1' : '0';
|
|
if (modeEl) modeEl.textContent = useAgentMode ? 'On' : 'Off';
|
|
}
|
|
|
|
// ---- Approvals ----
|
|
async function loadApprovals() {
|
|
try {
|
|
const approvals = await api('/api/approvals');
|
|
const el = document.getElementById('approvals-list');
|
|
if (!approvals || approvals.length === 0) {
|
|
el.innerHTML = '<div style="color:var(--muted);font-size:11px">대기 중인 승인 없음</div>';
|
|
return;
|
|
}
|
|
el.innerHTML = approvals.map(a => `
|
|
<div class="approval-card">
|
|
<div class="approval-action">${escHtml(a.action)}</div>
|
|
<div class="approval-reason">${escHtml(a.reason || 'Approval required')}</div>
|
|
<div class="approval-buttons">
|
|
<button class="btn btn-sm btn-green" onclick="resolveApproval('${a.id}','approved')">? Approve</button>
|
|
<button class="btn btn-sm btn-red" onclick="resolveApproval('${a.id}','rejected')">? Reject</button>
|
|
</div>
|
|
</div>
|
|
`).join('');
|
|
} catch {}
|
|
}
|
|
|
|
async function resolveApproval(id, decision) {
|
|
await api(`/api/approvals/${id}`, { method: 'POST', body: JSON.stringify({ decision }) });
|
|
loadApprovals();
|
|
}
|
|
|
|
async function refreshWolGateLog() {
|
|
const el = document.getElementById('wolgate-log');
|
|
if (!el) return;
|
|
try {
|
|
const data = await api('/api/wol-gate-log');
|
|
const lines = (data && data.lines) || [];
|
|
if (lines.length === 0) {
|
|
el.innerHTML = '<div style="color:var(--muted);text-align:center;padding:10px 0;opacity:0.5">로그 없음</div>';
|
|
return;
|
|
}
|
|
const colorFor = (t) => t === 'success' ? 'var(--brand)' : t === 'warn' ? '#e0a030' : 'var(--muted)';
|
|
el.innerHTML = lines.map(l => {
|
|
if (!l.event) {
|
|
// Startup/misc lines without structured fields — show raw text, muted, with time prefix.
|
|
const prefix = l.time ? `[${l.time}] ` : '';
|
|
return `<div style="color:var(--muted);opacity:0.6;white-space:pre-wrap;word-break:break-all;margin-bottom:6px">${escHtml(prefix + l.text)}</div>`;
|
|
}
|
|
const rows = [
|
|
['time', l.time],
|
|
['IP', l.ip],
|
|
['경로', l.method && l.host != null ? `${l.method} ${l.host}${l.path || ''}` : null],
|
|
['UA', l.ua],
|
|
].filter(([, v]) => v);
|
|
return `<div style="border-left:2px solid ${colorFor(l.type)};padding:2px 0 2px 6px;margin-bottom:6px">
|
|
<div style="color:${colorFor(l.type)};font-weight:600">${escHtml(l.event)}</div>
|
|
${rows.map(([k, v]) => `<div style="color:var(--muted);white-space:pre-wrap;word-break:break-all"><span style="opacity:0.7">${k}:</span> ${escHtml(v)}</div>`).join('')}
|
|
</div>`;
|
|
}).join('');
|
|
el.scrollTop = el.scrollHeight;
|
|
} catch (e) {
|
|
el.innerHTML = '<div style="color:var(--muted);text-align:center;padding:10px 0;opacity:0.5">불러오기 실패: ' + escHtml(String(e.message || e)) + '</div>';
|
|
}
|
|
}
|
|
|
|
function fmtPercent(v, digits = 0) {
|
|
const n = Number(v);
|
|
if (!Number.isFinite(n)) return '--%';
|
|
return `${n.toFixed(digits)}%`;
|
|
}
|
|
|
|
function fmtMemoryGb(usedGb, totalGb) {
|
|
const u = Number(usedGb);
|
|
const t = Number(totalGb);
|
|
if (!Number.isFinite(u) || !Number.isFinite(t) || t <= 0) return '-- / -- GB';
|
|
return `${u.toFixed(1)} / ${t.toFixed(1)} GB`;
|
|
}
|
|
|
|
function meterWidth(pct) {
|
|
const n = Number(pct);
|
|
if (!Number.isFinite(n)) return '0%';
|
|
const bounded = Math.max(0, Math.min(100, n));
|
|
return `${bounded}%`;
|
|
}
|
|
|
|
function setText(id, text) {
|
|
const el = document.getElementById(id);
|
|
if (el) el.textContent = String(text || '');
|
|
}
|
|
|
|
function setMeter(id, pct) {
|
|
const el = document.getElementById(id);
|
|
if (!el) return;
|
|
el.style.width = meterWidth(pct);
|
|
}
|
|
|
|
function fmtNetSpeed(bps) {
|
|
if (bps >= 1024 * 1024 * 1024) return (bps / (1024 ** 3)).toFixed(1) + ' GB/s';
|
|
if (bps >= 1024 * 1024) return (bps / (1024 ** 2)).toFixed(1) + ' MB/s';
|
|
if (bps >= 1024) return (bps / 1024).toFixed(0) + ' KB/s';
|
|
return bps.toFixed(0) + ' B/s';
|
|
}
|
|
|
|
// 네트워크 바: 최근 최댓값 기준으로 스케일
|
|
let _netPeak = 1024 * 1024; // 초기 1 MB/s 기준
|
|
function netBarPct(bps) {
|
|
if (bps > _netPeak) _netPeak = bps;
|
|
return Math.min(100, (bps / _netPeak) * 100);
|
|
}
|
|
|
|
// 사이드바 LAN 행: 링크 속도 + 최근 24시간 끊김 횟수, 점(초록/노랑/빨강), 마우스를 올리면 상세
|
|
function renderLanStatus(lan) {
|
|
const dot = document.getElementById('sb-lan-dot');
|
|
const txt = document.getElementById('sb-lan-text');
|
|
const row = document.getElementById('sb-lan-row');
|
|
if (!dot || !txt || !row) return;
|
|
if (!lan || lan.status === 'unknown') { txt.textContent = '확인 중'; dot.style.background = 'var(--muted)'; return; }
|
|
const color = { ok: 'var(--ok)', warn: '#e0a400', bad: '#d64545' }[lan.status] || 'var(--muted)';
|
|
dot.style.background = color;
|
|
const ms = lan.gateway && lan.gateway.avg_ms != null ? ` · ${lan.gateway.avg_ms.toFixed(1)}ms` : '';
|
|
txt.textContent = `${lan.label}${ms}`;
|
|
const nics = (lan.nics || []).map(n => `${n.name}: ${n.up ? (n.speed_mbps ? n.speed_mbps + 'Mbps ' + n.duplex : '링크 올라옴') : '끊김'} (오류 ${n.rx_errors + n.tx_errors}, CRC ${n.rx_crc_errors}, 링크전환 ${n.carrier_changes})`);
|
|
const gw = lan.gateway ? `공유기 ${lan.gateway.avg_ms ?? '-'}ms 손실 ${lan.gateway.loss_pct}%` : '공유기 없음';
|
|
const wan = lan.wan ? `인터넷 ${lan.wan.avg_ms ?? '-'}ms 손실 ${lan.wan.loss_pct}%` : '';
|
|
const sm = lan.summary ? `${new Date(lan.summary.since).toLocaleString()} 이후: 링크 끊김 ${lan.summary.flaps} · 절전/기상 ${lan.summary.resumes || 0} · 속도 하락 ${lan.summary.speed_drops} · 공유기 손실 ${lan.summary.lan_loss_samples}회 · 인터넷 끊김 ${lan.summary.wan_down_samples}회` : '';
|
|
const evs = (lan.events || []).slice(0, 5).map(e => `${new Date(e.ts).toLocaleTimeString()} ${e.detail}`);
|
|
row.title = [...nics, gw, wan, sm, ...(evs.length ? ['— 최근 이벤트 —', ...evs] : [])].filter(Boolean).join('\n');
|
|
}
|
|
|
|
async function resetLanStatus() {
|
|
if (!confirm('랜 오류 카운터와 이벤트 기록을 초기화할까요?\n(이전 기록은 파일로 백업돼요)')) return;
|
|
try {
|
|
await api('/api/lan-status/reset', { method: 'POST' });
|
|
loadSystemStats();
|
|
} catch (e) { alert('초기화 실패: ' + (e.message || e)); }
|
|
}
|
|
window.resetLanStatus = resetLanStatus;
|
|
|
|
let systemStatsFetchInFlight = false;
|
|
async function loadSystemStats() {
|
|
if (systemStatsFetchInFlight) return;
|
|
systemStatsFetchInFlight = true;
|
|
try {
|
|
const stats = await api('/api/system-stats');
|
|
const cpu = stats?.system?.cpu_percent;
|
|
const ram = stats?.system?.memory_percent;
|
|
const gpu = stats?.gpu?.gpu_util_percent;
|
|
const vram = stats?.gpu?.vram_used_percent;
|
|
const gpuAvailable = !!stats?.gpu?.available;
|
|
|
|
setText('quick-system-stats', `CPU ${fmtPercent(cpu)} • RAM ${fmtPercent(ram)} • GPU ${gpuAvailable ? fmtPercent(gpu) : '--%'}`);
|
|
|
|
setText('sys-cpu', fmtPercent(cpu));
|
|
setText('sys-ram', fmtPercent(ram));
|
|
setText('sys-gpu', gpuAvailable ? fmtPercent(gpu) : 'N/A');
|
|
setText('sys-vram', gpuAvailable ? fmtPercent(vram) : 'N/A');
|
|
setMeter('sys-cpu-meter', cpu);
|
|
setMeter('sys-ram-meter', ram);
|
|
setMeter('sys-gpu-meter', gpuAvailable ? gpu : 0);
|
|
setMeter('sys-vram-meter', gpuAvailable ? vram : 0);
|
|
|
|
// 사이드바 리소스 바
|
|
setText('sb-sys-cpu', fmtPercent(cpu));
|
|
setText('sb-sys-ram', fmtPercent(ram));
|
|
setMeter('sb-sys-cpu-meter', cpu);
|
|
setMeter('sb-sys-ram-meter', ram);
|
|
|
|
// GPU별 VRAM — 카드가 2개 이상이면 GPU0/GPU1 분리 표시, 1개면 GPU1 행 숨김
|
|
const gpuList = Array.isArray(stats?.gpu?.gpus) ? stats.gpu.gpus : [];
|
|
const gpu0 = gpuList[0];
|
|
const gpu1 = gpuList[1];
|
|
setText('sb-sys-vram0', gpu0 ? fmtPercent(gpu0.vram_used_percent) : (gpuAvailable ? fmtPercent(vram) : 'N/A'));
|
|
setMeter('sb-sys-vram0-meter', gpu0 ? gpu0.vram_used_percent : (gpuAvailable ? vram : 0));
|
|
const gpu1Row = document.getElementById('sb-gpu1-row');
|
|
if (gpu1Row) gpu1Row.style.display = gpu1 ? 'flex' : 'none';
|
|
if (gpu1) {
|
|
setText('sb-sys-vram1', fmtPercent(gpu1.vram_used_percent));
|
|
setMeter('sb-sys-vram1-meter', gpu1.vram_used_percent);
|
|
}
|
|
const rxBps = stats?.network?.rx_bps || 0;
|
|
const txBps = stats?.network?.tx_bps || 0;
|
|
setText('sb-sys-rx', fmtNetSpeed(rxBps));
|
|
setText('sb-sys-tx', fmtNetSpeed(txBps));
|
|
setMeter('sb-sys-rx-meter', netBarPct(rxBps));
|
|
setMeter('sb-sys-tx-meter', netBarPct(txBps));
|
|
|
|
renderLanStatus(stats?.lan);
|
|
|
|
const ollamaRunning = !!stats?.ollama_process?.running;
|
|
const ollamaCount = Number(stats?.ollama_process?.process_count || 0);
|
|
const ollamaMemMb = Number(stats?.ollama_process?.total_memory_mb || 0);
|
|
const gatewayRss = Number(stats?.gateway_process?.rss_mb || 0);
|
|
const gpuName = String(stats?.gpu?.name || '').trim();
|
|
const memUsage = fmtMemoryGb(stats?.system?.memory_used_gb, stats?.system?.memory_total_gb);
|
|
const updated = new Date(stats?.timestamp || Date.now()).toLocaleTimeString();
|
|
const activeProvider = stats?.active_provider || 'ollama';
|
|
const activeModel = stats?.active_model || document.getElementById('current-model')?.textContent || '-';
|
|
const isLocalProvider = activeProvider === 'ollama' || activeProvider === 'llama_cpp' || activeProvider === 'lm_studio';
|
|
|
|
// Show provider + model in the runtime card
|
|
const providerDisp = (PROVIDER_LABELS[activeProvider] || activeProvider);
|
|
let runtimeLabel;
|
|
if (activeProvider === 'ollama') {
|
|
runtimeLabel = ollamaRunning ? `Ollama • ${activeModel}` : `Ollama offline • ${activeModel}`;
|
|
} else {
|
|
runtimeLabel = `${providerDisp} • ${activeModel}`;
|
|
}
|
|
setText('sys-ollama', runtimeLabel);
|
|
const memPart = isLocalProvider && ollamaMemMb > 0 ? ` • LLM ${ollamaMemMb.toFixed(0)} MB` : '';
|
|
setText(
|
|
'sys-runtime-sub',
|
|
`${memUsage}${memPart} • Gateway ${gatewayRss.toFixed(0)} MB${gpuName ? ` • ${gpuName}` : ''} • ${updated}`
|
|
);
|
|
|
|
const onlineUsers = Array.isArray(stats?.online_users) ? stats.online_users : [];
|
|
const onlineEl = document.getElementById('sys-online-users');
|
|
if (onlineEl) {
|
|
if (onlineUsers.length === 0) {
|
|
onlineEl.textContent = '없음';
|
|
onlineEl.style.color = 'var(--muted)';
|
|
} else {
|
|
onlineEl.innerHTML = onlineUsers.map(u =>
|
|
`<span style="display:inline-flex;align-items:center;gap:4px;margin-right:8px"><span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--ok)"></span>${escHtml(String(u))}</span>`
|
|
).join('');
|
|
onlineEl.style.color = 'var(--text)';
|
|
}
|
|
}
|
|
} catch {
|
|
setText('quick-system-stats', 'CPU --% • RAM --% • GPU --%');
|
|
setText('sys-cpu', '--%');
|
|
setText('sys-ram', '--%');
|
|
setText('sys-gpu', 'N/A');
|
|
setText('sys-vram', 'N/A');
|
|
setText('sys-ollama', 'Stats unavailable');
|
|
setText('sys-runtime-sub', 'Could not fetch system stats right now');
|
|
setMeter('sys-cpu-meter', 0);
|
|
setMeter('sys-ram-meter', 0);
|
|
setMeter('sys-gpu-meter', 0);
|
|
setMeter('sys-vram-meter', 0);
|
|
setText('sb-sys-cpu', '--%');
|
|
setText('sb-sys-ram', '--%');
|
|
setText('sb-sys-vram0', 'N/A');
|
|
setText('sb-sys-vram1', 'N/A');
|
|
setMeter('sb-sys-cpu-meter', 0);
|
|
setMeter('sb-sys-ram-meter', 0);
|
|
setMeter('sb-sys-vram0-meter', 0);
|
|
setMeter('sb-sys-vram1-meter', 0);
|
|
setText('sb-sys-rx', '0 B/s');
|
|
setText('sb-sys-tx', '0 B/s');
|
|
setMeter('sb-sys-rx-meter', 0);
|
|
setMeter('sb-sys-tx-meter', 0);
|
|
} finally {
|
|
systemStatsFetchInFlight = false;
|
|
}
|
|
}
|
|
|
|
// ---- Status ----
|
|
|
|
// ---- Log ----
|
|
|
|
// ---- Stop Button ----
|
|
let currentAbortController = null;
|
|
|
|
function handleSendStop() {
|
|
if (isThinking) stopGeneration();
|
|
else sendChat();
|
|
}
|
|
|
|
function stopGeneration() {
|
|
if (currentAbortController) {
|
|
// 연결만 끊으면 서버가 중지를 놓쳐 못 본 답이 세션 기록에 남는다 — 서버에도 직접 알림
|
|
try {
|
|
fetch('/api/chat/stop', { method: 'POST', headers: authHeaders({ 'Content-Type': 'application/json' }),
|
|
body: JSON.stringify({ sessionId: agentSessionId }) }).catch(() => {});
|
|
} catch {}
|
|
currentAbortController.abort();
|
|
currentAbortController = null;
|
|
}
|
|
}
|
|
|
|
function setButtonState(thinking) {
|
|
const sendIcon = document.getElementById('send-icon');
|
|
const stopIcon = document.getElementById('stop-icon');
|
|
const btn = document.getElementById('send-btn');
|
|
if (!btn) return;
|
|
if (thinking) {
|
|
if (sendIcon) sendIcon.style.display = 'none';
|
|
if (stopIcon) stopIcon.style.display = '';
|
|
btn.style.background = 'var(--err)';
|
|
btn.title = 'Stop generation';
|
|
} else {
|
|
if (sendIcon) sendIcon.style.display = '';
|
|
if (stopIcon) stopIcon.style.display = 'none';
|
|
btn.style.background = '';
|
|
btn.title = 'Send';
|
|
}
|
|
}
|
|
|
|
|
|
// ---- Context Pinning ----
|
|
const MAX_PINS = 3;
|
|
let contextPinMode = false;
|
|
let pinnedMessageIndices = new Set();
|
|
let confirmedPins = []; // Array of { role, content } sent with each request
|
|
|
|
function toggleContextPinMode() {
|
|
const pop = document.getElementById('context-pin-popover');
|
|
if (!pop) return;
|
|
const isOpen = pop.classList.contains('open');
|
|
// Close other popovers
|
|
document.getElementById('quick-mode-popover')?.classList.remove('open');
|
|
if (isOpen) {
|
|
cancelContextPin();
|
|
} else {
|
|
contextPinMode = true;
|
|
pop.classList.add('open');
|
|
document.body.classList.add('context-pin-active');
|
|
// Reset selection to currently confirmed pins
|
|
pinnedMessageIndices = new Set();
|
|
for (const pin of confirmedPins) {
|
|
const idx = chatHistory.findIndex(m => m.content === pin.content && m.role === pin.role);
|
|
if (idx >= 0) pinnedMessageIndices.add(idx);
|
|
}
|
|
updatePinUI();
|
|
renderChatMessages();
|
|
}
|
|
}
|
|
|
|
function cancelContextPin() {
|
|
contextPinMode = false;
|
|
pinnedMessageIndices = new Set();
|
|
document.getElementById('context-pin-popover')?.classList.remove('open');
|
|
document.body.classList.remove('context-pin-active');
|
|
renderChatMessages();
|
|
}
|
|
|
|
function confirmContextPin() {
|
|
confirmedPins = [];
|
|
for (const idx of pinnedMessageIndices) {
|
|
const msg = chatHistory[idx];
|
|
if (msg) confirmedPins.push({ role: msg.role === 'user' ? 'user' : 'assistant', content: msg.content });
|
|
}
|
|
contextPinMode = false;
|
|
document.getElementById('context-pin-popover')?.classList.remove('open');
|
|
document.body.classList.remove('context-pin-active');
|
|
updatePinBadge();
|
|
renderChatMessages();
|
|
if (confirmedPins.length > 0) {
|
|
addProcessEntry('info', `${confirmedPins.length} message(s) pinned to context.`);
|
|
} else {
|
|
addProcessEntry('info', 'Context pins cleared.');
|
|
}
|
|
}
|
|
|
|
function togglePinMessage(index) {
|
|
if (!contextPinMode) return;
|
|
if (pinnedMessageIndices.has(index)) {
|
|
pinnedMessageIndices.delete(index);
|
|
} else if (pinnedMessageIndices.size < MAX_PINS) {
|
|
pinnedMessageIndices.add(index);
|
|
}
|
|
updatePinUI();
|
|
renderChatMessages();
|
|
}
|
|
|
|
function removePinFromList(index) {
|
|
pinnedMessageIndices.delete(index);
|
|
updatePinUI();
|
|
renderChatMessages();
|
|
}
|
|
|
|
function updatePinUI() {
|
|
const countEl = document.getElementById('context-pin-count');
|
|
const listEl = document.getElementById('context-pin-list');
|
|
if (countEl) countEl.textContent = `${pinnedMessageIndices.size}/${MAX_PINS} selected`;
|
|
if (listEl) {
|
|
if (pinnedMessageIndices.size === 0) {
|
|
listEl.innerHTML = '<div style="font-size:11px;color:var(--muted);text-align:center;padding:8px">Click messages in chat to select them</div>';
|
|
} else {
|
|
listEl.innerHTML = Array.from(pinnedMessageIndices).map(idx => {
|
|
const msg = chatHistory[idx];
|
|
if (!msg) return '';
|
|
const icon = msg.role === 'user' ? '??' : '??';
|
|
const text = msg.content.slice(0, 60) + (msg.content.length > 60 ? '...' : '');
|
|
return `<div class="pin-card">
|
|
<span>${icon}</span>
|
|
<div class="pin-card-text">${escHtml(text)}</div>
|
|
<button class="pin-card-remove" onclick="removePinFromList(${idx})">×</button>
|
|
</div>`;
|
|
}).join('');
|
|
}
|
|
}
|
|
}
|
|
|
|
function updatePinBadge() {
|
|
const label = document.getElementById('context-pin-label');
|
|
if (label) {
|
|
label.textContent = confirmedPins.length > 0 ? `컨텍스트 (${confirmedPins.length})` : '컨텍스트';
|
|
}
|
|
const btn = document.getElementById('context-pin-btn');
|
|
if (btn) {
|
|
btn.style.borderColor = confirmedPins.length > 0 ? '#86d4a8' : '';
|
|
btn.style.background = confirmedPins.length > 0 ? '#f0faf4' : '';
|
|
btn.style.color = confirmedPins.length > 0 ? '#0a6b3d' : '';
|
|
}
|
|
}
|
|
|
|
function getInitialTheme() {
|
|
try {
|
|
const saved = localStorage.getItem(THEME_KEY);
|
|
if (saved === 'light' || saved === 'dark') return saved;
|
|
} catch {}
|
|
return 'light';
|
|
}
|
|
|
|
function applyTheme(theme) {
|
|
const resolved = theme === 'dark' ? 'dark' : 'light';
|
|
document.documentElement.setAttribute('data-theme', resolved);
|
|
const toggle = document.getElementById('theme-toggle');
|
|
if (toggle) {
|
|
toggle.setAttribute('data-theme-state', resolved);
|
|
const title = resolved === 'dark' ? 'Switch to light mode' : 'Switch to dark mode';
|
|
toggle.title = title;
|
|
toggle.setAttribute('aria-label', title);
|
|
}
|
|
try { localStorage.setItem(THEME_KEY, resolved); } catch {}
|
|
}
|
|
|
|
function toggleTheme() {
|
|
const current = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
|
|
applyTheme(current === 'dark' ? 'light' : 'dark');
|
|
}
|
|
|
|
// ---- Boot ----
|
|
document.addEventListener('click', (e) => {
|
|
const pop = document.getElementById('quick-mode-popover');
|
|
const btn = document.getElementById('quick-mode-btn');
|
|
if (!pop || !btn) return;
|
|
if (!pop.contains(e.target) && !btn.contains(e.target)) pop.classList.remove('open');
|
|
// Also close context pin popover
|
|
const pinPop = document.getElementById('context-pin-popover');
|
|
const pinBtn = document.getElementById('context-pin-btn');
|
|
if (pinPop && pinBtn && !pinPop.contains(e.target) && !pinBtn.contains(e.target)) {
|
|
// Don't close if in pin mode and clicking on messages
|
|
if (contextPinMode && e.target.closest && e.target.closest('.msg')) return;
|
|
}
|
|
});
|
|
|
|
// --- SCHEDULER MANAGEMENT ---------------------------------------------------
|
|
|
|
|
|
loadChatSessions();
|
|
applyTheme(getInitialTheme());
|
|
setupProcessAndRightScrollTracking();
|
|
updateHeartbeatUI();
|
|
connectWS();
|
|
refreshAll();
|
|
updateQuickModeUI();
|
|
updateQueuedPromptUI();
|
|
setInterval(checkStatus, 10000);
|
|
setInterval(loadSystemStats, 3000);
|
|
setInterval(loadApprovals, 5000);
|
|
refreshWolGateLog();
|
|
setInterval(refreshWolGateLog, 60000);
|
|
setMode('chat'); // Start in chat mode
|
|
setSidebarTab('jobs');
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// BACKGROUND TASKS KANBAN SYSTEM
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// --- Integrations Tab ---------------------------------------------------------
|
|
|
|
|
|
// ───────────────────────────────────────────────────────────────────────────
|
|
// ERROR RESPONSE SYSTEM — Full JavaScript Implementation
|
|
// Handles: show/hide panel, option selection, input rendering,
|
|
// credential entry, form submission, WS event binding
|
|
// ───────────────────────────────────────────────────────────────────────────
|
|
|
|
// State
|
|
|
|
// ── Mobile tab navigation ───────────────────────────────────────────────────
|
|
function mobTab(tab) {
|
|
const body = document.body;
|
|
|
|
if (tab === 'menu') {
|
|
const isOpen = body.classList.contains('mob-menu');
|
|
if (isOpen) {
|
|
mobCloseMenu();
|
|
} else {
|
|
body.classList.add('mob-menu');
|
|
}
|
|
// Keep chat/ctx tab highlight unchanged; toggle menu highlight
|
|
document.getElementById('mob-tab-menu').classList.toggle('active', !isOpen);
|
|
return;
|
|
}
|
|
|
|
mobCloseMenu();
|
|
['chat', 'ctx', 'menu'].forEach(t =>
|
|
document.getElementById('mob-tab-' + t)?.classList.toggle('active', t === tab)
|
|
);
|
|
|
|
if (tab === 'ctx') {
|
|
body.classList.add('mob-ctx');
|
|
} else {
|
|
body.classList.remove('mob-ctx');
|
|
}
|
|
}
|
|
|
|
function mobCloseMenu() {
|
|
document.body.classList.remove('mob-menu');
|
|
document.getElementById('mob-backdrop').style.display = 'none';
|
|
document.getElementById('mob-tab-menu')?.classList.remove('active');
|
|
}
|
|
|
|
// ── Right-panel collapse ────────────────────────────────────────────────────
|
|
const RIGHT_COLLAPSE_KEY = 'rightPanelCollapsed';
|
|
function applyRightPanelCollapsed(collapsed) {
|
|
document.body.classList.toggle('right-collapsed', !!collapsed);
|
|
// Only override on the true 3-column desktop layout. At ≤1200px the tablet/mobile
|
|
// media queries own the grid (sidebar hidden), so inline 3-column styles here would
|
|
// fight them — e.g. restoring a wide saved width and letting the context panel eat
|
|
// most of the screen. Clear inline styles below that width so CSS takes over.
|
|
const isDesktop = window.matchMedia('(min-width: 1201px)').matches;
|
|
if (!isDesktop) { document.body.style.gridTemplateColumns = ''; return; }
|
|
if (collapsed) {
|
|
document.body.style.gridTemplateColumns = '280px 1fr 36px';
|
|
} else {
|
|
const saved = parseInt(localStorage.getItem('rightPanelWidth'), 10);
|
|
const max = Math.floor(window.innerWidth * 0.65);
|
|
const w = saved && saved >= 280 ? Math.min(saved, max) : '';
|
|
document.body.style.gridTemplateColumns = w ? `280px 1fr ${w}px` : '';
|
|
}
|
|
}
|
|
function toggleRightPanel() {
|
|
const next = !document.body.classList.contains('right-collapsed');
|
|
localStorage.setItem(RIGHT_COLLAPSE_KEY, next ? '1' : '0');
|
|
applyRightPanelCollapsed(next);
|
|
}
|
|
// Default to collapsed when no preference saved.
|
|
(function initRightPanelCollapse() {
|
|
const stored = localStorage.getItem(RIGHT_COLLAPSE_KEY);
|
|
const collapsed = stored === null ? true : stored === '1';
|
|
applyRightPanelCollapsed(collapsed);
|
|
})();
|
|
|
|
// Re-evaluate on viewport change (e.g. tablet rotation crossing the 1200px boundary)
|
|
// so inline desktop grid styles are cleared/applied to match the active CSS layout.
|
|
window.addEventListener('resize', () => {
|
|
const stored = localStorage.getItem(RIGHT_COLLAPSE_KEY);
|
|
applyRightPanelCollapsed(stored === null ? true : stored === '1');
|
|
});
|
|
|
|
// ── Right-panel resize ──────────────────────────────────────────────────────
|
|
(function initRightPanelResize() {
|
|
const MIN_W = 280;
|
|
const MAX_W_RATIO = 0.65;
|
|
const STORE_KEY = 'rightPanelWidth';
|
|
|
|
function applyWidth(px) {
|
|
document.body.style.gridTemplateColumns = `280px 1fr ${px}px`;
|
|
}
|
|
|
|
function clamp(px) {
|
|
return Math.max(MIN_W, Math.min(Math.floor(window.innerWidth * MAX_W_RATIO), px));
|
|
}
|
|
|
|
// Restore saved width — desktop only. Below 1201px the tablet/mobile CSS owns the
|
|
// grid, so applying a saved (often wide) width here would override it.
|
|
const isDesktop = () => window.matchMedia('(min-width: 1201px)').matches;
|
|
if (isDesktop() && !document.body.classList.contains('right-collapsed')) {
|
|
const saved = parseInt(localStorage.getItem(STORE_KEY), 10);
|
|
if (saved && saved >= MIN_W) applyWidth(clamp(saved));
|
|
}
|
|
|
|
function setup() {
|
|
const handle = document.getElementById('right-panel-resize-handle');
|
|
const panel = document.getElementById('right-panel');
|
|
if (!handle || !panel) return;
|
|
|
|
handle.addEventListener('mouseenter', () => { handle.style.background = 'var(--brand, #1668e3)'; handle.style.opacity = '0.35'; });
|
|
handle.addEventListener('mouseleave', () => { handle.style.background = 'transparent'; handle.style.opacity = '1'; });
|
|
|
|
handle.addEventListener('mousedown', (e) => {
|
|
e.preventDefault();
|
|
const startX = e.clientX;
|
|
const startW = panel.getBoundingClientRect().width;
|
|
|
|
// Prevent iframes from swallowing events during drag
|
|
document.querySelectorAll('iframe').forEach(f => f.style.pointerEvents = 'none');
|
|
document.body.style.userSelect = 'none';
|
|
handle.style.background = 'var(--brand, #1668e3)';
|
|
handle.style.opacity = '0.6';
|
|
|
|
function onMove(ev) {
|
|
const newW = clamp(startW + (startX - ev.clientX));
|
|
applyWidth(newW);
|
|
}
|
|
|
|
function onUp() {
|
|
document.removeEventListener('mousemove', onMove);
|
|
document.removeEventListener('mouseup', onUp);
|
|
document.querySelectorAll('iframe').forEach(f => f.style.pointerEvents = '');
|
|
document.body.style.userSelect = '';
|
|
handle.style.background = 'transparent';
|
|
handle.style.opacity = '1';
|
|
const finalW = panel.getBoundingClientRect().width;
|
|
localStorage.setItem(STORE_KEY, Math.round(finalW));
|
|
}
|
|
|
|
document.addEventListener('mousemove', onMove);
|
|
document.addEventListener('mouseup', onUp);
|
|
});
|
|
}
|
|
|
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', setup);
|
|
else setup();
|
|
})();
|
|
|
|
|
|
|
|
// ── Code editor stubs (editor moved to code.html) ────────────────────────
|
|
|
|
// ── PPTX Workflow Sidebar ─────────────────────────────────────────────────────
|
|
|
|
|